diff --git a/.gitattributes b/.gitattributes index 1452b4c4965493f0b4d65c4fb64091fa74dfef54..1897e55a2867ed073920b030850d557b42999eb0 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3993,3 +3993,8 @@ OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/night.exr filter=lfs diff=lfs mer OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/sunrise.exr filter=lfs diff=lfs merge=lfs -text OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/sunset.exr filter=lfs diff=lfs merge=lfs -text OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/_C.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/common.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/gridencoder.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/Utils.cpp.o filter=lfs diff=lfs merge=lfs -text +OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o filter=lfs diff=lfs merge=lfs -text +OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/mycpp.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001006.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001006.txt new file mode 100644 index 0000000000000000000000000000000000000000..7cd51b1abd45102bd199d29a8875c7317eddac29 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001006.txt @@ -0,0 +1,4 @@ +-8.923123707025195639e-01 4.510926292247209313e-01 1.227867374076993231e-03 -6.155160539311817919e-02 +2.985809657721401611e-01 5.926822602936366868e-01 -7.484129846199867320e-01 9.856492630090384066e-02 +-3.371444370928001755e-01 -6.676410657539734173e-01 -6.624605073687090950e-01 6.295474742696518522e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001007.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001007.txt new file mode 100644 index 0000000000000000000000000000000000000000..d5ee3acaed597393b1f2a3596f46237c79a97ce0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001007.txt @@ -0,0 +1,4 @@ +-8.917366735056371230e-01 4.531094158031606645e-01 4.082987563360148189e-03 -6.207863542958092645e-02 +2.983003516035732661e-01 5.926929302671132271e-01 -7.487336156228707740e-01 9.695185884387209907e-02 +-3.403584414906242750e-01 -6.664746834874542003e-01 -6.627229006875893225e-01 6.285394944815940743e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001008.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001008.txt new file mode 100644 index 0000000000000000000000000000000000000000..9e4f377b806453fb86e2b25e01e7f1617f8d5eec --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001008.txt @@ -0,0 +1,4 @@ +-8.883703178618959084e-01 4.592609833918432360e-01 -1.863361302989016482e-03 -6.190490979509545577e-02 +3.050141921261115829e-01 5.875921770112093601e-01 -7.493073941678736194e-01 9.717491368583243416e-02 +-3.422722020352569894e-01 -6.659813146944320028e-01 -6.615532961457291083e-01 6.286319302995978520e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001009.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001009.txt new file mode 100644 index 0000000000000000000000000000000000000000..92c9c3f0de3737c283f5c639c1acbb61850e5d64 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001009.txt @@ -0,0 +1,4 @@ +-8.839717599559632211e-01 4.657474840013812178e-01 -1.638317680078102759e-02 -6.151390255112332978e-02 +3.216306275391936920e-01 5.845207579059047420e-01 -7.448241081913634654e-01 9.730516519512379114e-02 +-3.365662996719857580e-01 -6.649560689244259359e-01 -6.653647324227196513e-01 6.288766671813712517e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001010.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001010.txt new file mode 100644 index 0000000000000000000000000000000000000000..fcecb38abfce9608df279214501b703fd8ffea41 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001010.txt @@ -0,0 +1,4 @@ +-8.847700698673398589e-01 4.644003409982863650e-01 -3.985882687801033109e-02 -6.103036636931963993e-02 +3.411623759060357086e-01 5.855164214053387717e-01 -7.362798533095270548e-01 9.744542698555409832e-02 +-3.172380401170961650e-01 -6.651163258754037022e-01 -6.749211777857194727e-01 6.284326255132134387e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001011.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001011.txt new file mode 100644 index 0000000000000000000000000000000000000000..c9ca8b014b0a9359a873660322405419cd12fe55 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001011.txt @@ -0,0 +1,4 @@ +-8.838601973426271075e-01 4.645117102024985956e-01 -4.504300030972883950e-02 -6.207105257570615098e-02 +3.462491339812638347e-01 5.880525207911383445e-01 -7.314606383881641083e-01 9.751967322217681977e-02 +-3.131041482836162682e-01 -6.628766017457756732e-01 -6.788152260929749549e-01 6.285759482494950312e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001012.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001012.txt new file mode 100644 index 0000000000000000000000000000000000000000..418742125d7eba5f32fc4290fee9a497ce202c4b --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001012.txt @@ -0,0 +1,4 @@ +-8.877799961973554810e-01 4.577527395078743733e-01 -3.403276819375589124e-02 -6.117376176500385898e-02 +3.327396883865018640e-01 5.901572968326284085e-01 -7.360147673485807340e-01 9.761566206378517740e-02 +-3.159962280890038500e-01 -6.645100916603005059e-01 -6.752683657730325084e-01 6.288949987214723647e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001013.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001013.txt new file mode 100644 index 0000000000000000000000000000000000000000..5ac2cc3c378109b91b81246f68ea07fe0b11b747 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001013.txt @@ -0,0 +1,4 @@ +-8.879544496726152758e-01 4.580013328582476229e-01 -3.331917862492234095e-02 -6.150124590679888897e-02 +3.317317588194628741e-01 5.887959770426510753e-01 -7.369097789513839869e-01 9.710289822661047343e-02 +-3.171425611441247017e-01 -6.660722652620579831e-01 -6.742965058931054134e-01 6.289478813482056729e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001014.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001014.txt new file mode 100644 index 0000000000000000000000000000000000000000..e2c1b510a077322b5988fefd68eb0e9b714df87c --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001014.txt @@ -0,0 +1,4 @@ +-8.874755351299099537e-01 4.585338491436060093e-01 -3.140251887848553858e-02 -6.147829634710191837e-02 +3.302903369996872396e-01 5.890420125369791871e-01 -7.381444728166902669e-01 9.773410356184067393e-02 +-3.181858517503468042e-01 -6.661133869633497628e-01 -6.734644706529130387e-01 6.293863998357334122e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001015.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001015.txt new file mode 100644 index 0000000000000000000000000000000000000000..7445d8f5f0ea44b5e54816e715f1c6a78fa7efb4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001015.txt @@ -0,0 +1,4 @@ +-8.829535820308521687e-01 4.664412561319069006e-01 -4.428404462005298969e-02 -6.207338889063101356e-02 +3.473554998852920184e-01 5.867181208740042120e-01 -7.319986950891985700e-01 9.749640375063807485e-02 +-3.144242356898917512e-01 -6.622449868716038246e-01 -6.795794208717953477e-01 6.289671363961714112e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001016.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001016.txt new file mode 100644 index 0000000000000000000000000000000000000000..9a2892f8e9d4ba1c3f5638dae037a7376387f67c --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001016.txt @@ -0,0 +1,4 @@ +-8.846730420674165929e-01 4.631956830989829577e-01 -4.207910079726694813e-02 -6.189189399727451635e-02 +3.404484750893976841e-01 5.824393594585107747e-01 -7.375422978195340651e-01 9.691498330300901687e-02 +-3.164858210790734150e-01 -6.680829112639898870e-01 -6.722216118731760837e-01 6.287683197786592126e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001017.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001017.txt new file mode 100644 index 0000000000000000000000000000000000000000..2a6c61b2a0e475d2ce045b31fb1a4cf2d4863ed4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001017.txt @@ -0,0 +1,4 @@ +-8.865163844973020790e-01 4.621414717318200749e-01 -1.158326655128994256e-02 -6.157192434117660096e-02 +3.155409289094662229e-01 5.860170866514242682e-01 -7.463002809814719418e-01 9.704865090008407691e-02 +-3.362116423926939657e-01 -6.660413377944481850e-01 -6.639701176140963002e-01 6.293063607976635554e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001018.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001018.txt new file mode 100644 index 0000000000000000000000000000000000000000..24a67702211622198ac624656398130f8edd99fc --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001018.txt @@ -0,0 +1,4 @@ +-8.815918696875502114e-01 4.682447717477410398e-01 -4.574928035201395599e-02 -6.171157517803727705e-02 +3.471075000597936833e-01 5.815836033585365383e-01 -7.354334218842368820e-01 9.767069273742616520e-02 +-3.168608083725660829e-01 -6.659759931536411992e-01 -6.743216955448535499e-01 6.285797802703920745e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001020.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001020.txt new file mode 100644 index 0000000000000000000000000000000000000000..19b769340f78c8514f551bae99330eb6508c893f --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001020.txt @@ -0,0 +1,4 @@ +-8.859277923895610973e-01 4.574061871891269004e-01 -6.757018789400034975e-02 -6.149720460670455441e-02 +3.568513973756212154e-01 5.835645369619280043e-01 -7.301602998663732080e-01 9.762046101253255004e-02 +-2.933919905661683813e-01 -6.714035264644571122e-01 -6.798548241101025624e-01 6.292997333763288292e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001021.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001021.txt new file mode 100644 index 0000000000000000000000000000000000000000..da6fd556a2503bc4a967d4c78a5cdd0294dc31a4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001021.txt @@ -0,0 +1,4 @@ +-8.875199585165327587e-01 4.566534746037164694e-01 -5.625534597364367090e-02 -6.199906274064420630e-02 +3.499411755196571439e-01 5.905443084146123622e-01 -7.272680508267816979e-01 9.772652350866573023e-02 +-2.981369610880096332e-01 -6.668628706507796489e-01 -6.827815286689580265e-01 6.289610674154075820e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001022.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001022.txt new file mode 100644 index 0000000000000000000000000000000000000000..c6d6824bca6278a1fccb0fa70116b2eee925efe5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001022.txt @@ -0,0 +1,4 @@ +-8.833581497655030867e-01 4.659630054928605158e-01 -4.832170851249844440e-02 -6.126298011356464540e-02 +3.483813234232837619e-01 5.843552806094517438e-01 -7.333183329234554959e-01 9.766254773100671582e-02 +-3.123275736029422767e-01 -6.652323960368958788e-01 -6.775067942430017531e-01 6.286129808465045210e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001023.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001023.txt new file mode 100644 index 0000000000000000000000000000000000000000..0a4b1c30f127b449eccedced6508986c15602610 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001023.txt @@ -0,0 +1,4 @@ +-8.959065522980101948e-01 4.392120453676767178e-01 -6.035507543008098580e-02 -6.189452281149288027e-02 +3.328444884805926707e-01 5.747366581403334784e-01 -7.479136239513247686e-01 9.799581006885972612e-02 +-2.927284754314216642e-01 -6.911654438735589379e-01 -6.603733583969436660e-01 6.293576255135406861e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001024.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001024.txt new file mode 100644 index 0000000000000000000000000000000000000000..fb12bc8323e521cb928db1487a41d70670fdc6cb --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001024.txt @@ -0,0 +1,4 @@ +-8.961503006462676613e-01 4.387895949290557263e-01 -6.087699809744555324e-02 -6.146377723380929553e-02 +3.323694680013847824e-01 5.749782080397085604e-01 -7.475313641574852230e-01 9.749009911863863731e-02 +-2.933729108986279921e-01 -6.907749342106738188e-01 -6.599404408046813941e-01 6.284855887328222313e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001025.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001025.txt new file mode 100644 index 0000000000000000000000000000000000000000..85c1b12c0bcf3ba2281fa451edfe3aa6cd695ded --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001025.txt @@ -0,0 +1,4 @@ +-8.959029944922343169e-01 4.395273546730950609e-01 -5.994404670727927070e-02 -6.134371484889721005e-02 +3.326916258378307956e-01 5.745634043466762986e-01 -7.482096263748336806e-01 9.800679829809323673e-02 +-2.924699696720240438e-01 -6.911524999010389969e-01 -6.594822424454811483e-01 6.287924434459168932e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001026.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001026.txt new file mode 100644 index 0000000000000000000000000000000000000000..999e03afd6fc9adbe284efb25b1363a6a1cbf9a9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001026.txt @@ -0,0 +1,4 @@ +-8.958917525180777330e-01 4.390409474804167211e-01 -6.045972000317925005e-02 -6.113689048893784089e-02 +3.327465253820030000e-01 5.746449156572898120e-01 -7.475407511841234420e-01 9.717153803550036828e-02 +-2.929675350490388297e-01 -6.909599724774984075e-01 -6.601388495703520709e-01 6.292864562379336668e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001027.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001027.txt new file mode 100644 index 0000000000000000000000000000000000000000..549043b59d31399125d1b5c22d4e9da307950f31 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001027.txt @@ -0,0 +1,4 @@ +-8.960277622910028938e-01 4.389126107203444316e-01 -6.087385082709417111e-02 -6.162146496165153697e-02 +3.322692335828492660e-01 5.747348188956883375e-01 -7.477875808398614099e-01 9.777844318124885581e-02 +-2.925261624282853856e-01 -6.906039589287257252e-01 -6.595470329631119011e-01 6.293740369784616151e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001028.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001028.txt new file mode 100644 index 0000000000000000000000000000000000000000..b3edb1e9ee4929b5904c196d7a5f858757798e93 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001028.txt @@ -0,0 +1,4 @@ +-8.962194234473245258e-01 4.391359930336873885e-01 -6.047686010018514524e-02 -6.193265304790343539e-02 +3.327465052683450941e-01 5.745197271321463850e-01 -7.477640275786510138e-01 9.718347741684084384e-02 +-2.933340218023857138e-01 -6.906042137830720185e-01 -6.601264298593498836e-01 6.287834604944029238e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001032.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001032.txt new file mode 100644 index 0000000000000000000000000000000000000000..33e5f8a3110671e77b4faa1f0b32a469ed90f2df --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001032.txt @@ -0,0 +1,4 @@ +-8.956796578260786124e-01 4.388984551908935994e-01 -6.091781993046677113e-02 -6.122002137996780669e-02 +3.325937120991937501e-01 5.751310053270268785e-01 -7.481927633755597329e-01 9.746037625956398276e-02 +-2.929991344560294309e-01 -6.907246345465519743e-01 -6.603028711336336176e-01 6.287019044852348859e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001033.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001033.txt new file mode 100644 index 0000000000000000000000000000000000000000..8fccfa25e6e59354d50d35d709fe1a5d3e2ddb4c --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001033.txt @@ -0,0 +1,4 @@ +-8.959099475867038365e-01 4.393709695305971219e-01 -6.044891863343726524e-02 -6.114839075714396249e-02 +3.325370481900363218e-01 5.742023692917316291e-01 -7.475579615190700578e-01 9.758270724993130252e-02 +-2.931151687066536060e-01 -6.911880099434871694e-01 -6.603132310805792660e-01 6.289522640878102422e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001036.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001036.txt new file mode 100644 index 0000000000000000000000000000000000000000..522e3bcf58c391b11a82015379f511f660a15edd --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001036.txt @@ -0,0 +1,4 @@ +-8.962505402355103179e-01 4.395933833406368563e-01 -6.044301599371896400e-02 -6.187329366298549571e-02 +3.324690256204553274e-01 5.744450599978506711e-01 -7.475288445436216733e-01 9.776006205829879114e-02 +-2.927327475928193090e-01 -6.909761026569073428e-01 -6.598995840518192546e-01 6.287902869079083912e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001037.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001037.txt new file mode 100644 index 0000000000000000000000000000000000000000..439e54ce2f29c123d2bc6eb7e60ca9fe2bd77159 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001037.txt @@ -0,0 +1,4 @@ +-8.959228986495612057e-01 4.388821768862229411e-01 -6.015518251246888132e-02 -6.150309922812860486e-02 +3.324842412443321238e-01 5.748638938188331826e-01 -7.474808997296294999e-01 9.766695558244187225e-02 +-2.924385556116413931e-01 -6.908768257347415176e-01 -6.596728663499672463e-01 6.286345591934675570e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001040.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001040.txt new file mode 100644 index 0000000000000000000000000000000000000000..52f6d33fbe0a1c0e7e37194990671811bf8d3e43 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001040.txt @@ -0,0 +1,4 @@ +-8.963318229374427348e-01 4.392423583702607104e-01 -5.994801305038024303e-02 -6.174815331356367509e-02 +3.318790546219499982e-01 5.742248236555476115e-01 -7.477014021078939310e-01 9.716741723175492673e-02 +-2.926117440538980041e-01 -6.903615751147523794e-01 -6.594268317694648163e-01 6.286803254130428620e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001043.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001043.txt new file mode 100644 index 0000000000000000000000000000000000000000..07ef8f195bd9d2e2e8bd0aed05d912ecab9e9f91 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001043.txt @@ -0,0 +1,4 @@ +-8.958621908996651229e-01 4.387972078379927532e-01 -6.015525095882445772e-02 -6.165183866280334046e-02 +3.320129814176601135e-01 5.745426848902535077e-01 -7.481181430011638600e-01 9.770048542877933506e-02 +-2.926489147297087201e-01 -6.904645526345442041e-01 -6.600520966989987803e-01 6.291546921448560870e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001046.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001046.txt new file mode 100644 index 0000000000000000000000000000000000000000..be5120dc90c722eb412c39f77a1610264774db99 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001046.txt @@ -0,0 +1,4 @@ +-8.963728628907539075e-01 4.394766623393003835e-01 -6.088180449599255029e-02 -6.178294831328890596e-02 +3.325518313096239020e-01 5.746983157498454231e-01 -7.481704429290122471e-01 9.768347996270246303e-02 +-2.926170671249328503e-01 -6.908809406998073221e-01 -6.603223994981365363e-01 6.291206168126247666e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001049.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001049.txt new file mode 100644 index 0000000000000000000000000000000000000000..886e806f769f43a2a7f6abe895c005d781ee875d --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001049.txt @@ -0,0 +1,4 @@ +-8.964914745415286657e-01 4.387911851682486097e-01 -6.005255329966507905e-02 -6.125164878687983094e-02 +3.319175564191159666e-01 5.744693664330030591e-01 -7.477671998086174998e-01 9.769310520701623979e-02 +-2.925645772152827284e-01 -6.905598635309421196e-01 -6.598150048637984044e-01 6.293433621801993727e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001052.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001052.txt new file mode 100644 index 0000000000000000000000000000000000000000..2eb432d1a6dc250cf2a79112807c9dfdb40b843d --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001052.txt @@ -0,0 +1,4 @@ +-8.960213128147718198e-01 4.389157256441199584e-01 -6.000413891118917820e-02 -6.181069618592567594e-02 +3.326524730590745271e-01 5.742333462636021180e-01 -7.481069918984609712e-01 9.803559310307079222e-02 +-2.933154829756398629e-01 -6.904185261290334275e-01 -6.594269621601576148e-01 6.292673718305968888e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001055.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001055.txt new file mode 100644 index 0000000000000000000000000000000000000000..03519c7fcad67419a2a5e66e261615362ae9a2da --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001055.txt @@ -0,0 +1,4 @@ +-8.959590379329104293e-01 4.388576399695620633e-01 -6.022153195911113949e-02 -6.197355012535427088e-02 +3.322354992760052084e-01 5.751087043780054309e-01 -7.478247406221647520e-01 9.773481884990174728e-02 +-2.924155415871714792e-01 -6.903185444793428216e-01 -6.599955174637291977e-01 6.293457379066369484e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001058.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001058.txt new file mode 100644 index 0000000000000000000000000000000000000000..a72309bd0944eaf1932da44de26cf0e74ec5967f --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001058.txt @@ -0,0 +1,4 @@ +-8.964434117604467289e-01 4.397007441296601482e-01 -6.053229427677389585e-02 -6.138424183605142165e-02 +3.318985523691720396e-01 5.747794457370772880e-01 -7.477440715844453356e-01 9.786315793120013706e-02 +-2.932598078857755475e-01 -6.908800508887912306e-01 -6.596900434586681072e-01 6.287410801058068710e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001061.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001061.txt new file mode 100644 index 0000000000000000000000000000000000000000..e4775ac76b005a089bed482b18b3d1b38460b279 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001061.txt @@ -0,0 +1,4 @@ +-8.960421543936176736e-01 4.393013021032982635e-01 -6.078738399929838748e-02 -6.123734521940094044e-02 +3.319214898517184320e-01 5.749796317580075922e-01 -7.484446155265480627e-01 9.801664737829966778e-02 +-2.929513906775741416e-01 -6.903354789134091840e-01 -6.602175638934006940e-01 6.293405400420047924e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001064.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001064.txt new file mode 100644 index 0000000000000000000000000000000000000000..72128c7daa3adf602a2293bd3aca549808cd49a7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001064.txt @@ -0,0 +1,4 @@ +-8.960662452365858455e-01 4.394173079257093217e-01 -6.034599503418686117e-02 -6.145768427183943144e-02 +3.322527989882270716e-01 5.744000642402705692e-01 -7.477848590703897180e-01 9.753270452490818421e-02 +-2.924881629869476862e-01 -6.903563564551489229e-01 -6.594047899206225694e-01 6.289876573435017049e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001067.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001067.txt new file mode 100644 index 0000000000000000000000000000000000000000..5d929ccaf338d04c5deda8e7cf4248371c9da446 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001067.txt @@ -0,0 +1,4 @@ +-8.963540746233588097e-01 4.388987842989034438e-01 -5.996383701521586229e-02 -6.204682479171271664e-02 +3.322960250364717094e-01 5.747696046943874260e-01 -7.480094914582300358e-01 9.748600696156765888e-02 +-2.928650234410561937e-01 -6.907801808861057102e-01 -6.599858634657500556e-01 6.291437483853318247e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001070.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001070.txt new file mode 100644 index 0000000000000000000000000000000000000000..e2118a7195f139a8e889267ff1cd507dff953bb9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001070.txt @@ -0,0 +1,4 @@ +-8.963615025397488889e-01 4.388027398893037945e-01 -6.046760122937490378e-02 -6.163358762284013720e-02 +3.328263591180863346e-01 5.747597984411926264e-01 -7.477798061086528003e-01 9.764497469048723233e-02 +-2.926121272706758147e-01 -6.903436336842230236e-01 -6.598717266466933573e-01 6.285357586737458924e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001073.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001073.txt new file mode 100644 index 0000000000000000000000000000000000000000..432b7f18781db9d48e9eea05aa52eb64982455a5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001073.txt @@ -0,0 +1,4 @@ +-8.965072417518193948e-01 4.391100788967745028e-01 -6.063335919441444760e-02 -6.202980382355175598e-02 +3.325024815333909589e-01 5.744984658555030155e-01 -7.480255829584768756e-01 9.775108854807507131e-02 +-2.932325676807448489e-01 -6.906411494854790556e-01 -6.602830766720366729e-01 6.288528478084726148e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001076.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001076.txt new file mode 100644 index 0000000000000000000000000000000000000000..5e2592c8d94ce95069f406b9a6e3bf80c79d4530 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001076.txt @@ -0,0 +1,4 @@ +-8.959957536002423062e-01 4.396727872121045100e-01 -6.026653113578006593e-02 -6.183211661342780802e-02 +3.319985709361072956e-01 5.745646454287464122e-01 -7.481750909110419512e-01 9.711845843609606677e-02 +-2.933080258918917549e-01 -6.904033792027312044e-01 -6.597014882244122136e-01 6.287483764045692647e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001079.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001079.txt new file mode 100644 index 0000000000000000000000000000000000000000..5c935558761909bdb5e929526959fd35e4c9b39f --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001079.txt @@ -0,0 +1,4 @@ +-8.958369511420987141e-01 4.388321800817968077e-01 -6.033556498898622750e-02 -6.203158740555558825e-02 +3.320993799368388566e-01 5.748574358528895090e-01 -7.482450379368285054e-01 9.772099994639521503e-02 +-2.932166366033081006e-01 -6.904313985001675480e-01 -6.600464804256425122e-01 6.285899323087263957e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001082.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001082.txt new file mode 100644 index 0000000000000000000000000000000000000000..22b0963a05f341b2a23d35660d6f343df4029409 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001082.txt @@ -0,0 +1,4 @@ +-8.960301455427339690e-01 4.391054190449510397e-01 -6.058604302306564576e-02 -6.149542109635703496e-02 +3.322069051483677593e-01 5.745690257015660940e-01 -7.482920312030317822e-01 9.780063442356402847e-02 +-2.933844327394380946e-01 -6.909202254696313883e-01 -6.594620930228730638e-01 6.290862282822824447e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001085.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001085.txt new file mode 100644 index 0000000000000000000000000000000000000000..5d7c3c4c44e4f7a1bcd2cd0d531a07561bc68f9d --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001085.txt @@ -0,0 +1,4 @@ +-8.963947954283993935e-01 4.393236905047619434e-01 -6.002807819228345859e-02 -6.163939822974321553e-02 +3.325035608429371403e-01 5.745385937386109365e-01 -7.475416091247992778e-01 9.766149976041312020e-02 +-2.925938007590461742e-01 -6.910835746578496419e-01 -6.595632665435747777e-01 6.291198108326458982e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001088.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001088.txt new file mode 100644 index 0000000000000000000000000000000000000000..e1aab3e6c6809a73a7be2d5d4dc1807c588bb585 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001088.txt @@ -0,0 +1,4 @@ +-8.955738578359301316e-01 4.393830968003492599e-01 -6.037827392807367660e-02 -6.113885431665351533e-02 +3.322317456033597738e-01 5.750649215939035441e-01 -7.478387989940683545e-01 9.789127950141440770e-02 +-2.928302402089305034e-01 -6.909915946374434181e-01 -6.597444950245856532e-01 6.284492804991336223e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001091.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001091.txt new file mode 100644 index 0000000000000000000000000000000000000000..e7a625e1928fee8ad6f528411da444aa6e912220 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001091.txt @@ -0,0 +1,4 @@ +-8.958670365045690032e-01 4.397106691310568305e-01 -6.045870186224353016e-02 -6.201676271336251101e-02 +3.322840957731342248e-01 5.741854849942390482e-01 -7.476393028024449494e-01 9.746130578145995038e-02 +-2.930035788839583932e-01 -6.905920669737246609e-01 -6.603747228801865043e-01 6.285622390010185967e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001094.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001094.txt new file mode 100644 index 0000000000000000000000000000000000000000..fab23a014927d8d0058338dd82cbdc60f4758661 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001094.txt @@ -0,0 +1,4 @@ +-8.962918345934485220e-01 4.391811960281952754e-01 -6.026110215817778032e-02 -6.182142710594710350e-02 +3.321917560640237910e-01 5.745701037898480745e-01 -7.476507392148528108e-01 9.711725572608391477e-02 +-2.932572185640296425e-01 -6.906373824011788898e-01 -6.600567501179419594e-01 6.287605756873940743e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001097.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001097.txt new file mode 100644 index 0000000000000000000000000000000000000000..8885a639035de5a57b5d3d3a79c1cc4d5f18a74e --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001097.txt @@ -0,0 +1,4 @@ +-8.963972613840632819e-01 4.395743917113488775e-01 -5.996821639778702334e-02 -6.140365160889898338e-02 +3.327709279067257442e-01 5.746580993094605461e-01 -7.482800957455294499e-01 9.783947476197270288e-02 +-2.932189869127449500e-01 -6.905884138137601269e-01 -6.594082747887891616e-01 6.293142496565242716e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001100.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001100.txt new file mode 100644 index 0000000000000000000000000000000000000000..e7a7177bd47dd1de04fcc1f34f8359980fc20128 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001100.txt @@ -0,0 +1,4 @@ +-8.961664591004329106e-01 4.394186924411719875e-01 -6.007641225906226040e-02 -6.171876872357090482e-02 +3.328260787228937145e-01 5.749002291707246970e-01 -7.475488654080872930e-01 9.751759330383662217e-02 +-2.926552404776353589e-01 -6.912267580477303719e-01 -6.598131784199747774e-01 6.290896732428234994e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001103.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001103.txt new file mode 100644 index 0000000000000000000000000000000000000000..57b51a698023d674ba8ed2ea099629ca4a706049 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001103.txt @@ -0,0 +1,4 @@ +-8.957114790662945580e-01 4.389210729715964932e-01 -6.027784980198896969e-02 -6.142945471717720790e-02 +3.320733503270461018e-01 5.751079264630278853e-01 -7.476923546133529275e-01 9.769154343722555311e-02 +-2.933490461152230555e-01 -6.909135667622663401e-01 -6.600858414157245724e-01 6.292707094163589865e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001106.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001106.txt new file mode 100644 index 0000000000000000000000000000000000000000..36e5b7030db36cf6e76983a73e2e7fbf20dc4ca2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001106.txt @@ -0,0 +1,4 @@ +-8.964136160274039922e-01 4.391141726115260768e-01 -6.050500025058659637e-02 -6.121877215976703757e-02 +3.319989202458857314e-01 5.745693603181085685e-01 -7.475638891394121854e-01 9.808242576529199730e-02 +-2.930447574181625492e-01 -6.909170629788932150e-01 -6.598760963804810586e-01 6.293647636408800095e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001109.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001109.txt new file mode 100644 index 0000000000000000000000000000000000000000..76708f8bbc9cb98dc571952bb70d28b23ece6062 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001109.txt @@ -0,0 +1,4 @@ +-8.955707889217950912e-01 4.393356682673034141e-01 -6.092212440294152848e-02 -6.169663283204698812e-02 +3.328596575142175329e-01 5.749293749062646119e-01 -7.475599198965074965e-01 9.727100741233107861e-02 +-2.931146893908190276e-01 -6.911059780950763454e-01 -6.596204799221911941e-01 6.291467284125160653e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001112.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001112.txt new file mode 100644 index 0000000000000000000000000000000000000000..11336826238b135700be6e2d703d5883e97af3ca --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001112.txt @@ -0,0 +1,4 @@ +-8.957970213109416324e-01 4.393446322346855615e-01 -6.001015690069615854e-02 -6.142389950563276885e-02 +3.322522898635544286e-01 5.750438671468560692e-01 -7.478360954322746945e-01 9.741742082179856432e-02 +-2.929880762733413357e-01 -6.910058566425891780e-01 -6.594533249572391842e-01 6.290187360836607677e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001115.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001115.txt new file mode 100644 index 0000000000000000000000000000000000000000..40860abf9cd7ccb375127408698aa46704e59521 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001115.txt @@ -0,0 +1,4 @@ +-8.963508890970933729e-01 4.390587628214429605e-01 -6.043369376427545903e-02 -6.157683804986693876e-02 +3.319556940780594156e-01 5.749377844348140254e-01 -7.480012075097457469e-01 9.770300296086806280e-02 +-2.929607593938060583e-01 -6.903803909814092421e-01 -6.593981371280926984e-01 6.291953286053584282e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001118.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001118.txt new file mode 100644 index 0000000000000000000000000000000000000000..2bbaa3f6619422dff75eddcbec251cc69aaf077a --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001118.txt @@ -0,0 +1,4 @@ +-8.961397713337918569e-01 4.393601493960188065e-01 -6.059718920519701485e-02 -6.140695494998619358e-02 +3.326888009370091437e-01 5.746573894935274041e-01 -7.484088373086147383e-01 9.718912244764593700e-02 +-2.932671858127566811e-01 -6.907594992391593580e-01 -6.597723863626718810e-01 6.286407122671263670e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001121.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001121.txt new file mode 100644 index 0000000000000000000000000000000000000000..b316ba10a940fcfe6bf26c560d4ff83ca0d554ad --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001121.txt @@ -0,0 +1,4 @@ +-8.961375375245377306e-01 4.392286290263033854e-01 -6.003150620858680592e-02 -6.180050008131462991e-02 +3.321326603003097455e-01 5.751454497577532798e-01 -7.476457206740627637e-01 9.713131813057347685e-02 +-2.932805712613752447e-01 -6.906955477700545964e-01 -6.594227324329327011e-01 6.291078327052694874e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001124.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001124.txt new file mode 100644 index 0000000000000000000000000000000000000000..4a3e0a68e8d841b0e7ef4fa12077574543af850d --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001124.txt @@ -0,0 +1,4 @@ +-8.964631711182758922e-01 4.389178187327900105e-01 -6.085917007107678051e-02 -6.204623086880325933e-02 +3.319944060561620391e-01 5.747905266508622768e-01 -7.481186000318859053e-01 9.718337078854005773e-02 +-2.927929137086973665e-01 -6.908079017091240948e-01 -6.600263800178300944e-01 6.284568605753645398e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001127.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001127.txt new file mode 100644 index 0000000000000000000000000000000000000000..30bed5f7b68ec0c54f1a1f2a4fccf4efc422f7b9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001127.txt @@ -0,0 +1,4 @@ +-8.963239195499105305e-01 4.397029638138986174e-01 -6.049076486998451740e-02 -6.163873851973328960e-02 +3.325658973403057272e-01 5.743058179768086857e-01 -7.482191949500285322e-01 9.715509671241331913e-02 +-2.931863880944688416e-01 -6.905976430821922918e-01 -6.596437412080264906e-01 6.285086913859954105e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001152.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001152.txt new file mode 100644 index 0000000000000000000000000000000000000000..ba44cb2102243c1d07de0071db59a63a2b2ea9c2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/annotated_poses/0001152.txt @@ -0,0 +1,4 @@ +-8.965092599010235919e-01 4.392288242153957190e-01 -6.030666266747036069e-02 -6.142438111652291644e-02 +3.324223717014027635e-01 5.746087461226043747e-01 -7.476923881287245166e-01 9.754007254394472803e-02 +-2.926082301216597070e-01 -6.906594341932554837e-01 -6.602010445205885869e-01 6.292732840914074810e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/cam_K.txt b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/cam_K.txt new file mode 100644 index 0000000000000000000000000000000000000000..aa43631aaf0bc423a779d39229755a7f0a66fab6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/cam_K.txt @@ -0,0 +1,3 @@ +3.195820007324218750e+02 0.000000000000000000e+00 3.202149847676955687e+02 +0.000000000000000000e+00 4.171186828613281250e+02 2.443486680871046701e+02 +0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/mesh/textured_simple.obj.mtl b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/mesh/textured_simple.obj.mtl new file mode 100644 index 0000000000000000000000000000000000000000..8dfc1f64e19f8c6971e5dce7fb2acb31a4c9c239 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/demo_data/mustard/mesh/textured_simple.obj.mtl @@ -0,0 +1,14 @@ +# +# Wavefront material file +# Converted by Meshlab Group +# + +newmtl material_0 +Ka 0.200000 0.200000 0.200000 +Kd 0.639216 0.639216 0.639216 +Ks 1.000000 1.000000 1.000000 +Tr 1.000000 +illum 2 +Ns 0.000000 +map_Kd texture_map.png + diff --git a/OVOW/engine/oneposeviagen/fpose/docker/dockerfile b/OVOW/engine/oneposeviagen/fpose/docker/dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc235a80f6f8e9e31e38aa1a29877747a400dfdb --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/docker/dockerfile @@ -0,0 +1,60 @@ +FROM nvidia/cudagl:11.3.0-devel-ubuntu20.04 + +ENV TZ=US/Pacific +RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone + +RUN apt-get update --fix-missing && \ + apt-get install -y libgtk2.0-dev && \ + apt-get install -y wget bzip2 ca-certificates curl git vim tmux g++ gcc build-essential cmake checkinstall gfortran libjpeg8-dev libtiff5-dev pkg-config yasm libavcodec-dev libavformat-dev libswscale-dev libdc1394-22-dev libxine2-dev libv4l-dev qt5-default libgtk2.0-dev libtbb-dev libatlas-base-dev libfaac-dev libmp3lame-dev libtheora-dev libvorbis-dev libxvidcore-dev libopencore-amrnb-dev libopencore-amrwb-dev x264 v4l-utils libprotobuf-dev protobuf-compiler libgoogle-glog-dev libgflags-dev libgphoto2-dev libhdf5-dev doxygen libflann-dev libboost-all-dev proj-data libproj-dev libyaml-cpp-dev cmake-curses-gui libzmq3-dev freeglut3-dev + + +RUN cd / && git clone https://github.com/pybind/pybind11 &&\ + cd pybind11 && git checkout v2.10.0 &&\ + mkdir build && cd build && cmake .. -DCMAKE_BUILD_TYPE=Release -DPYBIND11_INSTALL=ON -DPYBIND11_TEST=OFF &&\ + make -j6 && make install + + +RUN cd / && wget https://gitlab.com/libeigen/eigen/-/archive/3.4.0/eigen-3.4.0.tar.gz &&\ + tar xvzf ./eigen-3.4.0.tar.gz &&\ + cd eigen-3.4.0 &&\ + mkdir build &&\ + cd build &&\ + cmake .. &&\ + make install + +SHELL ["/bin/bash", "--login", "-c"] + +RUN cd / && wget --quiet https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /miniconda.sh && \ + /bin/bash /miniconda.sh -b -p /opt/conda &&\ + ln -s /opt/conda/etc/profile.d/conda.sh /etc/profile.d/conda.sh &&\ + echo ". /opt/conda/etc/profile.d/conda.sh" >> ~/.bashrc &&\ + /bin/bash -c "source ~/.bashrc" && \ + /opt/conda/bin/conda update -n base -c defaults conda -y &&\ + /opt/conda/bin/conda create -n my python=3.8 + + +ENV PATH $PATH:/opt/conda/envs/my/bin + +RUN conda init bash &&\ + echo "conda activate my" >> ~/.bashrc &&\ + conda activate my &&\ + pip install torch==2.0.0+cu118 torchvision==0.15.1+cu118 torchaudio==2.0.1 --index-url https://download.pytorch.org/whl/cu118 &&\ + pip install "git+https://github.com/facebookresearch/pytorch3d.git@stable" &&\ + pip install scipy joblib scikit-learn ruamel.yaml trimesh pyyaml opencv-python imageio open3d transformations warp-lang einops kornia pyrender + +RUN cd / && git clone --recursive https://github.com/NVIDIAGameWorks/kaolin +RUN conda activate my && cd /kaolin &&\ + FORCE_CUDA=1 python setup.py develop + +RUN cd / && git clone https://github.com/NVlabs/nvdiffrast &&\ + conda activate my && cd /nvdiffrast && pip install . + +ENV OPENCV_IO_ENABLE_OPENEXR=1 + +RUN conda activate my &&\ + pip install scikit-image meshcat webdataset omegaconf pypng roma seaborn opencv-contrib-python openpyxl wandb imgaug Ninja xlsxwriter timm albumentations xatlas rtree nodejs jupyterlab objaverse g4f ultralytics==8.0.120 pycocotools videoio numba &&\ + conda install -y -c anaconda h5py + + +ENV SHELL=/bin/bash +RUN ln -sf /bin/bash /bin/sh diff --git a/OVOW/engine/oneposeviagen/fpose/docker/run_container.sh b/OVOW/engine/oneposeviagen/fpose/docker/run_container.sh new file mode 100644 index 0000000000000000000000000000000000000000..85035714e53650c4c09cf67c01d94d08e62d78e3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/docker/run_container.sh @@ -0,0 +1,3 @@ +docker rm -f foundationpose +DIR=$(pwd)/../ +xhost + && docker run --gpus all --env NVIDIA_DISABLE_REQUIRE=1 -it --network=host --name foundationpose --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -v $DIR:$DIR -v /home:/home -v /mnt:/mnt -v /tmp/.X11-unix:/tmp/.X11-unix -v /tmp:/tmp --ipc=host -e DISPLAY=${DISPLAY} -e GIT_INDEX_FILE foundationpose:latest bash -c "cd $DIR && bash" diff --git a/OVOW/engine/oneposeviagen/fpose/fpose.egg-info/PKG-INFO b/OVOW/engine/oneposeviagen/fpose/fpose.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..d28057c195f72eaeb2ff4b924f20e5f09d9cdba9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose.egg-info/PKG-INFO @@ -0,0 +1,3 @@ +Metadata-Version: 2.4 +Name: fpose +Version: 0.1 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose.egg-info/SOURCES.txt b/OVOW/engine/oneposeviagen/fpose/fpose.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..5792974955fa1b3087f855ddb6a809aee050b7d0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose.egg-info/SOURCES.txt @@ -0,0 +1,5 @@ +setup.py +fpose.egg-info/PKG-INFO +fpose.egg-info/SOURCES.txt +fpose.egg-info/dependency_links.txt +fpose.egg-info/top_level.txt \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/fpose/fpose.egg-info/dependency_links.txt b/OVOW/engine/oneposeviagen/fpose/fpose.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/OVOW/engine/oneposeviagen/fpose/fpose.egg-info/top_level.txt b/OVOW/engine/oneposeviagen/fpose/fpose.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose.egg-info/top_level.txt @@ -0,0 +1 @@ + diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/.gitignore b/OVOW/engine/oneposeviagen/fpose/fpose/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..cc59bdd934c1ca5e79be63449e4790c20fd31d36 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/.gitignore @@ -0,0 +1,158 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +.history +exp/ +*.py[cod] +*$py.class +# C extensions +*.so +BundleTrack/build +# Distribution / packaging +.Python +foundationpose/ +build/ +develop-eggs/ +*.zip +demo_data/* +dist/ +# *.png +# *.jpg +debug/ +weights/* +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +.vscode/ +wheels/ +wandb/ +*.blend1 +*.tar.* +*.zip +*.svg +sacred/ +artifacts/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +demo_data/ +debug/ +coverage.xml +*.cover +demo_data/ +debug/ +weights/ +*.py,cover +.hypothesis/ +.pytest_cache/ +*.pth +weights/ +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache +cosypose/experiments + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Datasets +data/ +logs/ +!BundleTrack/XMem/inference/data +run_used.yml \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/LICENSE b/OVOW/engine/oneposeviagen/fpose/fpose/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6704932cd8979da01a39360783279b9c4b506305 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/LICENSE @@ -0,0 +1,94 @@ +Copyright (c) 2022-Present, NVIDIA Corporation & affiliates. All rights reserved. + + +======================================================================= + +1. Definitions + +"Licensor" means any person or entity that distributes its Work. + +"Software" means the original work of authorship made available under +this License. + +"Work" means the Software and any additions to or derivative works of +the Software that are made available under this License. + +The terms "reproduce," "reproduction," "derivative works," and +"distribution" have the meaning as provided under U.S. copyright law; +provided, however, that for the purposes of this License, derivative +works shall not include works that remain separable from, or merely +link (or bind by name) to the interfaces of, the Work. + +Works, including the Software, are "made available" under this License +by including in or with the Work either (a) a copyright notice +referencing the applicability of this License to the Work, or (b) a +copy of this License. + +2. License Grants + + 2.1 Copyright Grant. Subject to the terms and conditions of this + License, each Licensor grants to you a perpetual, worldwide, + non-exclusive, royalty-free, copyright license to reproduce, + prepare derivative works of, publicly display, publicly perform, + sublicense and distribute its Work and any resulting derivative + works in any form. + +3. Limitations + + 3.1 Redistribution. You may reproduce or distribute the Work only + if (a) you do so under this License, (b) you include a complete + copy of this License with your distribution, and (c) you retain + without modification any copyright, patent, trademark, or + attribution notices that are present in the Work. + + 3.2 Derivative Works. You may specify that additional or different + terms apply to the use, reproduction, and distribution of your + derivative works of the Work ("Your Terms") only if (a) Your Terms + provide that the use limitation in Section 3.3 applies to your + derivative works, and (b) you identify the specific derivative + works that are subject to Your Terms. Notwithstanding Your Terms, + this License (including the redistribution requirements in Section + 3.1) will continue to apply to the Work itself. + + 3.3 Use Limitation. The Work and any derivative works thereof only + may be used or intended for use non-commercially. Notwithstanding + the foregoing, NVIDIA and its affiliates may use the Work and any + derivative works commercially. As used herein, "non-commercially" + means for research or evaluation purposes only. + + 3.4 Patent Claims. If you bring or threaten to bring a patent claim + against any Licensor (including any claim, cross-claim or + counterclaim in a lawsuit) to enforce any patents that you allege + are infringed by any Work, then your rights under this License from + such Licensor (including the grant in Section 2.1) will terminate + immediately. + + 3.5 Trademarks. This License does not grant any rights to use any + Licensor�s or its affiliates� names, logos, or trademarks, except + as necessary to reproduce the notices described in this License. + + 3.6 Termination. If you violate any term of this License, then your + rights under this License (including the grant in Section 2.1) will + terminate immediately. + +4. Disclaimer of Warranty. + +THE WORK IS PROVIDED "AS IS" WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WARRANTIES OR CONDITIONS OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR +NON-INFRINGEMENT. YOU BEAR THE RISK OF UNDERTAKING ANY ACTIVITIES UNDER +THIS LICENSE. + +5. Limitation of Liability. + +EXCEPT AS PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL +THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE +SHALL ANY LICENSOR BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT, +INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF +OR RELATED TO THIS LICENSE, THE USE OR INABILITY TO USE THE WORK +(INCLUDING BUT NOT LIMITED TO LOSS OF GOODWILL, BUSINESS INTERRUPTION, +LOST PROFITS OR DATA, COMPUTER FAILURE OR MALFUNCTION, OR ANY OTHER +COMMERCIAL DAMAGES OR LOSSES), EVEN IF THE LICENSOR HAS BEEN ADVISED OF +THE POSSIBILITY OF SUCH DAMAGES. + +======================================================================= diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/Utils.py b/OVOW/engine/oneposeviagen/fpose/fpose/Utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dbf4fcadab83f4f51f740548bc40f93057374d58 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/Utils.py @@ -0,0 +1,1177 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os, sys, time,torch,pickle,trimesh,itertools,pdb,zipfile,datetime,imageio,gzip,logging,joblib,importlib,uuid,signal,multiprocessing,psutil,subprocess,tarfile,scipy,argparse +from pytorch3d.transforms import so3_log_map,so3_exp_map,se3_exp_map,se3_log_map,matrix_to_axis_angle,matrix_to_euler_angles,euler_angles_to_matrix, rotation_6d_to_matrix +from pytorch3d.renderer import FoVPerspectiveCameras, PerspectiveCameras, look_at_view_transform, look_at_rotation, RasterizationSettings, MeshRenderer, MeshRasterizer, BlendParams, SoftSilhouetteShader, HardPhongShader, PointLights, TexturesVertex +from pytorch3d.renderer.mesh.rasterize_meshes import barycentric_coordinates +from pytorch3d.renderer.mesh.shader import SoftDepthShader, HardFlatShader +from pytorch3d.renderer.mesh.textures import Textures +from pytorch3d.structures import Meshes +from scipy.interpolate import griddata +import nvdiffrast.torch as dr +import torch.nn.functional as F +import torchvision +import torch.nn as nn +from functools import partial +import pandas as pd +import open3d as o3d +from uuid import uuid4 +import cv2 +from PIL import Image +import numpy as np +from collections import defaultdict +import multiprocessing as mp +import matplotlib.pyplot as plt +import math,glob,re,copy +from transformations import * +from scipy.spatial import cKDTree +from collections import OrderedDict +import ruamel.yaml +yaml = ruamel.yaml.YAML() +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(code_dir) +# sys.path.append(f"{code_dir}/mycpp/build") +try: + import kornia +except: + kornia = None +try: + import mycpp.build.mycpp as mycpp +except: + mycpp = None +try: + from bundlesdf.mycuda import common +except: + common = None +try: + import warp as wp + wp.init() +except: + wp = None +enable_timer = 0 + +def NestDict(): + return defaultdict(NestDict) + +to8b = lambda x : (255*np.clip(x,0,1)).astype(np.uint8) + +BAD_DEPTH = 99 +BAD_COLOR = 0 + +glcam_in_cvcam = np.array([[1,0,0,0], + [0,-1,0,0], + [0,0,-1,0], + [0,0,0,1]]).astype(float) + +COLOR_MAP=np.array([[0, 0, 0], #Ignore + [128,0,0], #Background + [0,128,0], #Wall + [128,128,0], #Floor + [0,0,128], #Ceiling + [128,0,128], #Table + [0,128,128], #Chair + [128,128,128], #Window + [64,0,0], #Door + [192,0,0], #Monitor + [64, 128, 0], # 11th + [192, 0, 128], + [64, 128, 128], + [192, 128, 128], + [0, 64, 0], + [128, 64, 0], + [0, 192, 0], + [128, 192, 0], + ]) + + +def set_logging_format(level=logging.INFO): + importlib.reload(logging) + FORMAT = '[%(funcName)s()] %(message)s' + logging.basicConfig(level=level, format=FORMAT) + +set_logging_format() + + + + +def make_mesh_tensors(mesh, device='cuda', max_tex_size=None): + mesh_tensors = {} + if isinstance(mesh.visual, trimesh.visual.texture.TextureVisuals): + img_obj = getattr(getattr(mesh.visual, "material", None), "image", None) + if img_obj is None: + logging.info("WARN: texture visual has no image; using dummy texture") + img = np.ones((1, 1, 3), dtype=np.uint8) * 128 + else: + img = np.array(img_obj.convert('RGB')) + img = img[...,:3] + if max_tex_size is not None: + max_size = max(img.shape[0], img.shape[1]) + if max_size>max_tex_size: + scale = 1/max_size * max_tex_size + img = cv2.resize(img, fx=scale, fy=scale, dsize=None) + mesh_tensors['tex'] = torch.as_tensor(img, device=device, dtype=torch.float)[None]/255.0 + mesh_tensors['uv_idx'] = torch.as_tensor(mesh.faces, device=device, dtype=torch.int) + if hasattr(mesh.visual, "uv") and mesh.visual.uv is not None: + uv = torch.as_tensor(mesh.visual.uv, device=device, dtype=torch.float) + else: + uv = torch.zeros((len(mesh.vertices), 2), device=device, dtype=torch.float) + uv[:,1] = 1 - uv[:,1] + mesh_tensors['uv'] = uv + else: + if mesh.visual.vertex_colors is None: + logging.info(f"WARN: mesh doesn't have vertex_colors, assigning a pure color") + mesh.visual.vertex_colors = np.tile(np.array([128,128,128]).reshape(1,3), (len(mesh.vertices), 1)) + mesh_tensors['vertex_color'] = torch.as_tensor(mesh.visual.vertex_colors[...,:3], device=device, dtype=torch.float)/255.0 + + mesh_tensors.update({ + 'pos': torch.tensor(mesh.vertices, device=device, dtype=torch.float), + 'faces': torch.tensor(mesh.faces, device=device, dtype=torch.int), + 'vnormals': torch.tensor(mesh.vertex_normals, device=device, dtype=torch.float), + }) + return mesh_tensors + + +def nvdiffrast_render(K=None, H=None, W=None, ob_in_cams=None, glctx=None, context='cuda', get_normal=False, mesh_tensors=None, mesh=None, projection_mat=None, bbox2d=None, output_size=None, use_light=False, light_color=None, light_dir=np.array([0,0,1]), light_pos=np.array([0,0,0]), w_ambient=0.8, w_diffuse=0.5, extra={}): + '''Just plain rendering, not support any gradient + @K: (3,3) np array + @ob_in_cams: (N,4,4) torch tensor, openCV camera + @projection_mat: np array (4,4) + @output_size: (height, width) + @bbox2d: (N,4) (umin,vmin,umax,vmax) if only roi need to render. + @light_dir: in cam space + @light_pos: in cam space + ''' + if glctx is None: + if context == 'gl': + glctx = dr.RasterizeGLContext() + elif context=='cuda': + glctx = dr.RasterizeCudaContext() + else: + raise NotImplementedError + logging.info("created context") + + if mesh_tensors is None: + mesh_tensors = make_mesh_tensors(mesh) + pos = mesh_tensors['pos'] + vnormals = mesh_tensors['vnormals'] + pos_idx = mesh_tensors['faces'] + has_tex = 'tex' in mesh_tensors + + ob_in_glcams = torch.tensor(glcam_in_cvcam, device='cuda', dtype=torch.float)[None]@ob_in_cams + if projection_mat is None: + projection_mat = projection_matrix_from_intrinsics(K, height=H, width=W, znear=0.001, zfar=100) + projection_mat = torch.as_tensor(projection_mat.reshape(-1,4,4), device='cuda', dtype=torch.float) + mtx = projection_mat@ob_in_glcams + + if output_size is None: + output_size = np.asarray([H,W]) + + pts_cam = transform_pts(pos, ob_in_cams) + pos_homo = to_homo_torch(pos) + pos_clip = (mtx[:,None]@pos_homo[None,...,None])[...,0] + if bbox2d is not None: + l = bbox2d[:,0] + t = H-bbox2d[:,1] + r = bbox2d[:,2] + b = H-bbox2d[:,3] + tf = torch.eye(4, dtype=torch.float, device='cuda').reshape(1,4,4).expand(len(ob_in_cams),4,4).contiguous() + tf[:,0,0] = W/(r-l) + tf[:,1,1] = H/(t-b) + tf[:,3,0] = (W-r-l)/(r-l) + tf[:,3,1] = (H-t-b)/(t-b) + pos_clip = pos_clip@tf + rast_out, _ = dr.rasterize(glctx, pos_clip, pos_idx, resolution=np.asarray(output_size)) + xyz_map, _ = dr.interpolate(pts_cam, rast_out, pos_idx) + depth = xyz_map[...,2] + if has_tex: + texc, _ = dr.interpolate(mesh_tensors['uv'], rast_out, mesh_tensors['uv_idx']) + color = dr.texture(mesh_tensors['tex'], texc, filter_mode='linear') + else: + color, _ = dr.interpolate(mesh_tensors['vertex_color'], rast_out, pos_idx) + + if use_light: + get_normal = True + if get_normal: + vnormals_cam = transform_dirs(vnormals, ob_in_cams) + normal_map, _ = dr.interpolate(vnormals_cam, rast_out, pos_idx) + normal_map = F.normalize(normal_map, dim=-1) + normal_map = torch.flip(normal_map, dims=[1]) + else: + normal_map = None + + if use_light: + if light_dir is not None: + light_dir_neg = -torch.as_tensor(light_dir, dtype=torch.float, device='cuda') + else: + light_dir_neg = torch.as_tensor(light_pos, dtype=torch.float, device='cuda').reshape(1,1,3) - pts_cam + diffuse_intensity = (F.normalize(vnormals_cam, dim=-1) * F.normalize(light_dir_neg, dim=-1)).sum(dim=-1).clip(0, 1)[...,None] + diffuse_intensity_map, _ = dr.interpolate(diffuse_intensity, rast_out, pos_idx) # (N_pose, H, W, 1) + if light_color is None: + light_color = color + else: + light_color = torch.as_tensor(light_color, device='cuda', dtype=torch.float) + color = color*w_ambient + diffuse_intensity_map*light_color*w_diffuse + + color = color.clip(0,1) + color = color * torch.clamp(rast_out[..., -1:], 0, 1) # Mask out background using alpha + color = torch.flip(color, dims=[1]) # Flip Y coordinates + depth = torch.flip(depth, dims=[1]) + extra['xyz_map'] = torch.flip(xyz_map, dims=[1]) + return color, depth, normal_map + + +def set_seed(random_seed): + import torch,random + np.random.seed(random_seed) + random.seed(random_seed) + torch.manual_seed(random_seed) + torch.cuda.manual_seed_all(random_seed) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + + +def add_err(pred,gt,model_pts,symetry_tfs=np.eye(4)[None]): + """ + Average Distance of Model Points for objects with no indistinguishable views + - by Hinterstoisser et al. (ACCV 2012). + """ + pred_pts = transform_pts(model_pts, pred) + gt_pts = transform_pts(model_pts, gt) + e = np.linalg.norm(pred_pts - gt_pts, axis=-1).mean() + return e + +def adds_err(pred,gt,model_pts): + """ + @pred: 4x4 mat + @gt: + @model: (N,3) + """ + pred_pts = transform_pts(model_pts, pred) + gt_pts = transform_pts(model_pts, gt) + nn_index = cKDTree(pred_pts) + nn_dists, _ = nn_index.query(gt_pts, k=1, workers=-1) + e = nn_dists.mean() + return e + +def compute_auc_sklearn(errs, max_val=0.1, step=0.001): + from sklearn import metrics + errs = np.sort(np.array(errs)) + X = np.arange(0, max_val+step, step) + Y = np.ones(len(X)) + for i,x in enumerate(X): + y = (errs<=x).sum()/len(errs) + Y[i] = y + if y>=1: + break + auc = metrics.auc(X, Y) / (max_val*1) + return auc + + + +def normalizeRotation(pose): + '''Assume no shear case + ''' + new_pose = pose.copy() + scales = np.linalg.norm(pose[:3,:3],axis=0) + new_pose[:3,:3] /= scales.reshape(1,3) + return new_pose + + + +def toOpen3dCloud(points,colors=None,normals=None): + cloud = o3d.geometry.PointCloud() + cloud.points = o3d.utility.Vector3dVector(points.astype(np.float64)) + if colors is not None: + if colors.max()>1: + colors = colors/255.0 + cloud.colors = o3d.utility.Vector3dVector(colors.astype(np.float64)) + if normals is not None: + cloud.normals = o3d.utility.Vector3dVector(normals.astype(np.float64)) + return cloud + + + +def make_grid_image(imgs, nrow, padding=5, pad_value=255): + ''' + @imgs: (B,H,W,C) np array + @nrow: num of images per row + ''' + grid = torchvision.utils.make_grid(torch.as_tensor(np.asarray(imgs)).permute(0,3,1,2), nrow=nrow, padding=padding, pad_value=pad_value) + grid = grid.permute(1,2,0).contiguous().data.cpu().numpy().astype(np.uint8) + return grid + + +if wp is not None: + @wp.kernel(enable_backward=False) + def bilateral_filter_depth_kernel(depth:wp.array(dtype=float, ndim=2), out:wp.array(dtype=float, ndim=2), radius:int, zfar:float, sigmaD:float, sigmaR:float): + h,w = wp.tid() + H = depth.shape[0] + W = depth.shape[1] + if w>=W or h>=H: + return + out[h,w] = 0.0 + mean_depth = float(0.0) + num_valid = int(0) + for u in range(w-radius, w+radius+1): + if u<0 or u>=W: + continue + for v in range(h-radius, h+radius+1): + if v<0 or v>=H: + continue + cur_depth = depth[v,u] + if cur_depth>=0.001 and cur_depth=W: + continue + for v in range(h-radius, h+radius+1): + if v<0 or v>=H: + continue + cur_depth = depth[v,u] + if cur_depth>=0.001 and cur_depth0 and num_valid>0: + out[h,w] = sum/sum_weight + + def bilateral_filter_depth(depth, radius=2, zfar=100, sigmaD=2, sigmaR=100000, device='cuda'): + if isinstance(depth, np.ndarray): + depth_wp = wp.array(depth, dtype=float, device=device) + else: + depth_wp = wp.from_torch(depth) + out_wp = wp.zeros(depth.shape, dtype=float, device=device) + wp.launch(kernel=bilateral_filter_depth_kernel, device=device, dim=[depth.shape[0], depth.shape[1]], inputs=[depth_wp, out_wp, radius, zfar, sigmaD, sigmaR]) + depth_out = wp.to_torch(out_wp) + + if isinstance(depth, np.ndarray): + depth_out = depth_out.data.cpu().numpy() + return depth_out + + + @wp.kernel(enable_backward=False) + def erode_depth_kernel(depth:wp.array(dtype=float, ndim=2), out:wp.array(dtype=float, ndim=2), radius:int, depth_diff_thres:float, ratio_thres:float, zfar:float): + h,w = wp.tid() + H = depth.shape[0] + W = depth.shape[1] + if w>=W or h>=H: + return + d_ori = depth[h,w] + if d_ori<0.001 or d_ori>=zfar: + out[h,w] = 0.0 + bad_cnt = float(0) + total = float(0) + for u in range(w-radius, w+radius+1): + if u<0 or u>=W: + continue + for v in range(h-radius, h+radius+1): + if v<0 or v>=H: + continue + cur_depth = depth[v,u] + total += 1.0 + if cur_depth<0.001 or cur_depth>=zfar or abs(cur_depth-d_ori)>depth_diff_thres: + bad_cnt += 1.0 + if bad_cnt/total>ratio_thres: + out[h,w] = 0.0 + else: + out[h,w] = d_ori + + + def erode_depth(depth, radius=2, depth_diff_thres=0.001, ratio_thres=0.8, zfar=100, device='cuda'): + depth_wp = wp.from_torch(torch.as_tensor(depth, dtype=torch.float, device=device)) + out_wp = wp.zeros(depth.shape, dtype=float, device=device) + wp.launch(kernel=erode_depth_kernel, device=device, dim=[depth.shape[0], depth.shape[1]], inputs=[depth_wp, out_wp, radius, depth_diff_thres, ratio_thres, zfar],) + depth_out = wp.to_torch(out_wp) + + if isinstance(depth, np.ndarray): + depth_out = depth_out.data.cpu().numpy() + return depth_out + + + +def depth2xyzmap(depth, K, uvs=None): + invalid_mask = (depth<0.001) + H,W = depth.shape[:2] + if uvs is None: + vs,us = np.meshgrid(np.arange(0,H),np.arange(0,W), sparse=False, indexing='ij') + vs = vs.reshape(-1) + us = us.reshape(-1) + else: + uvs = uvs.round().astype(int) + us = uvs[:,0] + vs = uvs[:,1] + zs = depth[vs,us] + xs = (us-K[0,2])*zs/K[0,0] + ys = (vs-K[1,2])*zs/K[1,1] + pts = np.stack((xs.reshape(-1),ys.reshape(-1),zs.reshape(-1)), 1) #(N,3) + xyz_map = np.zeros((H,W,3), dtype=np.float32) + xyz_map[vs,us] = pts + xyz_map[invalid_mask] = 0 + return xyz_map + + +def depth2xyzmap_batch(depths, Ks, zfar): + ''' + @depths: torch tensor (B,H,W) + @Ks: torch tensor (B,3,3) + ''' + bs = depths.shape[0] + invalid_mask = (depths<0.001) | (depths>zfar) + H,W = depths.shape[-2:] + vs,us = torch.meshgrid(torch.arange(0,H),torch.arange(0,W), indexing='ij') + vs = vs.reshape(-1).float().cuda()[None].expand(bs,-1) + us = us.reshape(-1).float().cuda()[None].expand(bs,-1) + zs = depths.reshape(bs,-1) + Ks = Ks[:,None].expand(bs,zs.shape[-1],3,3) + xs = (us-Ks[...,0,2])*zs/Ks[...,0,0] #(B,N) + ys = (vs-Ks[...,1,2])*zs/Ks[...,1,1] + pts = torch.stack([xs,ys,zs], dim=-1) #(B,N,3) + xyz_maps = pts.reshape(bs,H,W,3) + xyz_maps[invalid_mask] = 0 + return xyz_maps + + + +def rle_to_mask(rle: dict) -> np.ndarray: + """Compute a binary mask from an uncompressed RLE.""" + h, w = rle["size"] + mask = np.empty(h * w, dtype=bool) + idx = 0 + parity = False + for count in rle["counts"]: + mask[idx : idx + count] = parity + idx += count + parity ^= True + mask = mask.reshape(w, h) + return mask.transpose() # Put in C order + + +def depth_to_vis(depth, zmin=None, zmax=None, mode='rgb', inverse=True): + if zmin is None: + zmin = depth.min() + if zmax is None: + zmax = depth.max() + + if inverse: + invalid = depth<0.001 + vis = zmin/(depth+1e-8) + vis[invalid] = 0 + else: + depth = depth.clip(zmin, zmax) + invalid = (depth==zmin) | (depth==zmax) + vis = (depth-zmin)/(zmax-zmin) + vis[invalid] = 1 + + if mode=='gray': + vis = (vis*255).clip(0, 255).astype(np.uint8) + elif mode=='rgb': + vis = cv2.applyColorMap((vis*255).astype(np.uint8), cv2.COLORMAP_JET)[...,::-1] + else: + raise RuntimeError + + return vis + + + +def sample_views_icosphere(n_views, subdivisions=None, radius=1): + if subdivisions is not None: + mesh = trimesh.creation.icosphere(subdivisions=subdivisions, radius=radius) + else: + subdivision = 1 + while 1: + mesh = trimesh.creation.icosphere(subdivisions=subdivision, radius=radius) + if mesh.vertices.shape[0]>=n_views: + break + subdivision += 1 + cam_in_obs = np.tile(np.eye(4)[None], (len(mesh.vertices),1,1)) + cam_in_obs[:,:3,3] = mesh.vertices + up = np.array([0,0,1]) + z_axis = -cam_in_obs[:,:3,3] #(N,3) + z_axis /= np.linalg.norm(z_axis, axis=-1).reshape(-1,1) + x_axis = np.cross(up.reshape(1,3), z_axis) + invalid = (x_axis==0).all(axis=-1) + x_axis[invalid] = [1,0,0] + x_axis /= np.linalg.norm(x_axis, axis=-1).reshape(-1,1) + y_axis = np.cross(z_axis, x_axis) + y_axis /= np.linalg.norm(y_axis, axis=-1).reshape(-1,1) + cam_in_obs[:,:3,0] = x_axis + cam_in_obs[:,:3,1] = y_axis + cam_in_obs[:,:3,2] = z_axis + return cam_in_obs + + + +def to_homo(pts): + ''' + @pts: (N,3 or 2) will homogeneliaze the last dimension + ''' + assert len(pts.shape)==2, f'pts.shape: {pts.shape}' + homo = np.concatenate((pts, np.ones((pts.shape[0],1))),axis=-1) + return homo + + +def to_homo_torch(pts): + ''' + @pts: shape can be (...,N,3 or 2) or (N,3) will homogeneliaze the last dimension + ''' + ones = torch.ones((*pts.shape[:-1],1), dtype=torch.float, device=pts.device) + homo = torch.cat((pts, ones),dim=-1) + return homo + + +def transform_pts(pts,tf): + """Transform 2d or 3d points + @pts: (...,N_pts,3) + @tf: (...,4,4) + """ + if len(tf.shape)>=3 and tf.shape[-3]!=pts.shape[-2]: + tf = tf[...,None,:,:] + return (tf[...,:-1,:-1]@pts[...,None] + tf[...,:-1,-1:])[...,0] + + +def transform_dirs(dirs,tf): + """ + @dirs: (...,3) + @tf: (...,4,4) + """ + if len(tf.shape)>=3 and tf.shape[-3]!=dirs.shape[-2]: + tf = tf[...,None,:,:] + return (tf[...,:3,:3]@dirs[...,None])[...,0] + + + +def random_direction(): + '''https://stackoverflow.com/questions/33976911/generate-a-random-sample-of-points-distributed-on-the-surface-of-a-unit-sphere + ''' + vec = np.random.randn(3).reshape(3) + vec /= np.linalg.norm(vec) + return vec + + + +def compute_mesh_diameter(model_pts=None, mesh=None, n_sample=1000): + from sklearn.decomposition import TruncatedSVD + if mesh is not None: + u, s, vh = scipy.linalg.svd(mesh.vertices, full_matrices=False) + pts = u@s + diameter = np.linalg.norm(pts.max(axis=0)-pts.min(axis=0)) + return float(diameter) + + if n_sample is None: + pts = model_pts + else: + ids = np.random.choice(len(model_pts), size=min(n_sample, len(model_pts)), replace=False) + pts = model_pts[ids] + dists = np.linalg.norm(pts[None]-pts[:,None], axis=-1) + diameter = dists.max() + return diameter + + +def compute_crop_window_tf_batch(pts=None, H=None, W=None, poses=None, K=None, crop_ratio=1.2, out_size=None, rgb=None, uvs=None, method='min_box', mesh_diameter=None): + '''Project the points and find the cropping transform + @pts: (N,3) + @poses: (B,4,4) tensor + @min_box: min_box/min_circle + @scale: scale to apply to the tightly enclosing roi + ''' + if torch.is_tensor(poses): + device = poses.device + dtype = poses.dtype + else: + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + dtype = torch.float32 + poses = torch.as_tensor(poses, device=device, dtype=dtype) + + def compute_tf_batch(left, right, top, bottom): + B = len(left) + left = left.round() + right = right.round() + top = top.round() + bottom = bottom.round() + + tf = torch.eye(3, device=device, dtype=dtype)[None].expand(B,-1,-1).contiguous() + tf[:,0,2] = -left + tf[:,1,2] = -top + new_tf = torch.eye(3, device=device, dtype=dtype)[None].expand(B,-1,-1).contiguous() + new_tf[:,0,0] = out_size[0]/(right-left) + new_tf[:,1,1] = out_size[1]/(bottom-top) + tf = new_tf@tf + return tf + + B = len(poses) + if method=='box_3d': + radius = mesh_diameter*crop_ratio/2 + offsets = torch.tensor([0,0,0, + radius,0,0, + -radius,0,0, + 0,radius,0, + 0,-radius,0], device=device, dtype=dtype).reshape(-1,3) + pts = poses[:,:3,3].reshape(-1,1,3)+offsets.reshape(1,-1,3) + K = torch.as_tensor(K, device=device, dtype=dtype) + projected = (K@pts.reshape(-1,3).T).T + uvs = projected[:,:2]/projected[:,2:3] + uvs = uvs.reshape(B, -1, 2) + center = uvs[:,0] #(B,2) + radius = torch.abs(uvs-center.reshape(-1,1,2)).reshape(B,-1).max(axis=-1)[0].reshape(-1) #(B) + left = center[:,0]-radius + right = center[:,0]+radius + top = center[:,1]-radius + bottom = center[:,1]+radius + tfs = compute_tf_batch(left, right, top, bottom) + return tfs + + else: + raise RuntimeError + + return tf + + + +def cv_draw_text(img,text,uv_top_left,color=(255, 255, 255),fontScale=0.5,thickness=1,fontFace=cv2.FONT_HERSHEY_SIMPLEX,outline_color=None,line_spacing=1.5): + H,W = img.shape[:2] + uv_top_left = np.array(uv_top_left, dtype=float) + assert uv_top_left.shape == (2,) + + for line in text.splitlines(): + (w, h), _ = cv2.getTextSize(text=line,fontFace=fontFace,fontScale=fontScale,thickness=thickness,) + uv_bottom_left_i = uv_top_left + [0, h] + + ############# Ensure inside image + while uv_bottom_left_i[0]<0: + uv_bottom_left_i[0] += 1 + while uv_bottom_left_i[0]+w>=W: + uv_bottom_left_i[0] -= 1 + while uv_bottom_left_i[1]>=H: + uv_bottom_left_i[1] -= 1 + while uv_bottom_left_i[1]-h<0: + uv_bottom_left_i[1] += 1 + + org = tuple(uv_bottom_left_i.astype(int)) + + if outline_color is not None: + cv2.putText(img,text=line,org=org,fontFace=fontFace,fontScale=fontScale,color=outline_color,thickness=thickness,lineType=cv2.LINE_AA,) + cv2.putText(img,text=line,org=org,fontFace=fontFace,fontScale=fontScale,color=color,thickness=thickness,lineType=cv2.LINE_AA,) + uv_top_left[1] = uv_bottom_left_i[1]-h+h*line_spacing + return img + + +def trimesh_add_pure_colored_texture(mesh, color=np.array([255,255,255]), resolution=5): + tex_img = np.tile(color.reshape(1,1,3), (resolution, resolution, 1)).astype(np.uint8) + mesh = mesh.unwrap() + mesh.visual = trimesh.visual.texture.TextureVisuals(uv=mesh.visual.uv,image=Image.fromarray(tex_img)) + return mesh + + + + +def project_3d_to_2d(pt,K,ob_in_cam): + pt = pt.reshape(4,1) + projected = K @ ((ob_in_cam@pt)[:3,:]) + projected = projected.reshape(-1) + projected = projected/projected[2] + return projected.reshape(-1)[:2].round().astype(int) + + +def draw_xyz_axis(color, ob_in_cam, scale=0.1, K=np.eye(3), thickness=3, transparency=0, is_input_rgb=False): + ''' + @color: BGR + ''' + if is_input_rgb: + color = cv2.cvtColor(color,cv2.COLOR_RGB2BGR) + xx = np.array([1,0,0,1]).astype(float) + yy = np.array([0,1,0,1]).astype(float) + zz = np.array([0,0,1,1]).astype(float) + xx[:3] = xx[:3]*scale + yy[:3] = yy[:3]*scale + zz[:3] = zz[:3]*scale + origin = tuple(project_3d_to_2d(np.array([0,0,0,1]), K, ob_in_cam)) + xx = tuple(project_3d_to_2d(xx, K, ob_in_cam)) + yy = tuple(project_3d_to_2d(yy, K, ob_in_cam)) + zz = tuple(project_3d_to_2d(zz, K, ob_in_cam)) + line_type = cv2.LINE_AA + arrow_len = 0 + tmp = color.copy() + tmp1 = tmp.copy() + tmp1 = cv2.arrowedLine(tmp1, origin, xx, color=(0,0,255), thickness=thickness,line_type=line_type, tipLength=arrow_len) + mask = np.linalg.norm(tmp1-tmp, axis=-1)>0 + tmp[mask] = tmp[mask]*transparency + tmp1[mask]*(1-transparency) + tmp1 = tmp.copy() + tmp1 = cv2.arrowedLine(tmp1, origin, yy, color=(0,255,0), thickness=thickness,line_type=line_type, tipLength=arrow_len) + mask = np.linalg.norm(tmp1-tmp, axis=-1)>0 + tmp[mask] = tmp[mask]*transparency + tmp1[mask]*(1-transparency) + tmp1 = tmp.copy() + tmp1 = cv2.arrowedLine(tmp1, origin, zz, color=(255,0,0), thickness=thickness,line_type=line_type, tipLength=arrow_len) + mask = np.linalg.norm(tmp1-tmp, axis=-1)>0 + tmp[mask] = tmp[mask]*transparency + tmp1[mask]*(1-transparency) + tmp = tmp.astype(np.uint8) + if is_input_rgb: + tmp = cv2.cvtColor(tmp,cv2.COLOR_BGR2RGB) + + return tmp + +def draw_xyz_axis_with_depth(color, depth, ob_in_cam, scale=0.1, K=np.eye(3), thickness=3, transparency=0, is_input_rgb=False): + """ + 绘制XYZ坐标轴,并更新深度图上的相应位置。 + @color: 输入图像(BGR格式) + @depth: 深度图 + @ob_in_cam: 物体到相机的变换矩阵 + @scale: 坐标轴长度比例 + @K: 相机内参矩阵 + @thickness: 线宽 + @transparency: 透明度 + @is_input_rgb: 如果输入图像是RGB格式,则设置为True + """ + # if is_input_rgb: + # color = cv2.cvtColor(color, cv2.COLOR_RGB2BGR) + + # 定义X,Y,Z轴方向向量,并缩放 + x_end = np.array([1,0,0]).astype(float) * scale + y_end = np.array([0,1,0]).astype(float) * scale + z_end = np.array([0,0,1]).astype(float) * scale + + origin = np.array([0,0,0]).astype(float) + + # 计算投影点 + # origin = project_3d_to_2d(np.array([0,0,0,1]), K, ob_in_cam) + # x_end = project_3d_to_2d(xx, K, ob_in_cam) + # y_end = project_3d_to_2d(yy, K, ob_in_cam) + # z_end = project_3d_to_2d(zz, K, ob_in_cam) + + H, W = color.shape[:2] + linewidth = thickness + def draw_line3d_xyz(start, end, img, depth, line_color): + # 构造两个点并转换到相机坐标系 + pts = np.stack((start, end), axis=0) + pts_homo = to_homo(pts) @ ob_in_cam.T # (2, 4) -> (2, 3) + cam_pts = pts_homo[:, :3] + + # 投影到图像平面 + projected = K @ cam_pts.T # (3, 2) + uv = (projected[:2] / projected[2]).T + uv_int = np.round(uv).astype(int) + + # 使用 OpenCV 绘制线段 + for i in range(len(uv_int) - 1): + pt1 = tuple(uv_int[i]) + pt2 = tuple(uv_int[i + 1]) + + # 使用抗锯齿线段绘制 + img = cv2.line(img, pt1, pt2, color=line_color, thickness=linewidth, lineType=cv2.LINE_AA) + + # 插值所有像素点,并更新深度图 + line_pixels = np.array(list(cv2.line(np.zeros((H, W), dtype=np.uint8), pt1, pt2, 255, linewidth).nonzero())).T + for y, x in line_pixels: + if 0 <= x < W and 0 <= y < H: + # 计算当前像素在两个端点之间的插值深度 + t = np.linalg.norm(np.array([x, y]) - uv[0]) / np.linalg.norm(uv[1] - uv[0]) + depth_val = (1 - t) * cam_pts[0, 2] + t * cam_pts[1, 2] + depth[y, x] = depth_val + + return img, depth + + tmp = color.copy() + # X轴:红色 + tmp, depth = draw_line3d_xyz(origin, x_end, tmp, depth, (0, 0, 255)) + + # Y轴:绿色 + tmp, depth = draw_line3d_xyz(origin, y_end, tmp, depth, (0, 255, 0)) + + # Z轴:蓝色 + tmp, depth = draw_line3d_xyz(origin, z_end, tmp, depth, (255, 0, 0)) + + tmp = tmp.astype(np.uint8) + if is_input_rgb: + tmp = cv2.cvtColor(tmp, cv2.COLOR_BGR2RGB) + + return tmp, depth + +def draw_posed_3d_box(K, img, ob_in_cam, bbox, line_color=(0,255,0), linewidth=2): + '''Revised from 6pack dataset/inference_dataset_nocs.py::projection + @bbox: (2,3) min/max + @line_color: RGB + ''' + min_xyz = bbox.min(axis=0) + xmin, ymin, zmin = min_xyz + max_xyz = bbox.max(axis=0) + xmax, ymax, zmax = max_xyz + + def draw_line3d(start,end,img): + pts = np.stack((start,end),axis=0).reshape(-1,3) + pts = (ob_in_cam@to_homo(pts).T).T[:,:3] #(2,3) + projected = (K@pts.T).T + uv = np.round(projected[:,:2]/projected[:,2].reshape(-1,1)).astype(int) #(2,2) + img = cv2.line(img, uv[0].tolist(), uv[1].tolist(), color=line_color, thickness=linewidth, lineType=cv2.LINE_AA) + return img + + for y in [ymin,ymax]: + for z in [zmin,zmax]: + start = np.array([xmin,y,z]) + end = start+np.array([xmax-xmin,0,0]) + img = draw_line3d(start,end,img) + + for x in [xmin,xmax]: + for z in [zmin,zmax]: + start = np.array([x,ymin,z]) + end = start+np.array([0,ymax-ymin,0]) + img = draw_line3d(start,end,img) + + for x in [xmin,xmax]: + for y in [ymin,ymax]: + start = np.array([x,y,zmin]) + end = start+np.array([0,0,zmax-zmin]) + img = draw_line3d(start,end,img) + + return img + +def draw_posed_3d_box_with_depth(K, img, depth, ob_in_cam, bbox, line_color=(0,255,0), linewidth=2): + """ + @K: 相机内参矩阵 (3, 3) + @img: RGB 图像 (H, W, 3) + @depth: 深度图 (H, W), dtype=np.float32 或类似 + @ob_in_cam: 从物体坐标系到相机坐标系的变换矩阵 (4, 4) + @bbox: (2,3) min/max 点 + @line_color: RGB 颜色 + """ + min_xyz = bbox.min(axis=0) + xmin, ymin, zmin = min_xyz + max_xyz = bbox.max(axis=0) + xmax, ymax, zmax = max_xyz + + H, W = img.shape[:2] + + def draw_line3d(start, end, img, depth): + # 构造两个点并转换到相机坐标系 + pts = np.stack((start, end), axis=0) + pts_homo = to_homo(pts) @ ob_in_cam.T # (2, 4) -> (2, 3) + cam_pts = pts_homo[:, :3] + + # 投影到图像平面 + projected = K @ cam_pts.T # (3, 2) + uv = (projected[:2] / projected[2]).T + uv_int = np.round(uv).astype(int) + + # 使用 OpenCV 绘制线段 + for i in range(len(uv_int) - 1): + pt1 = tuple(uv_int[i]) + pt2 = tuple(uv_int[i + 1]) + + # 使用抗锯齿线段绘制 + img = cv2.line(img, pt1, pt2, color=line_color, thickness=linewidth, lineType=cv2.LINE_AA) + + # 插值所有像素点,并更新深度图 + line_pixels = np.array(list(cv2.line(np.zeros((H, W), dtype=np.uint8), pt1, pt2, 255, linewidth).nonzero())).T + for y, x in line_pixels: + if 0 <= x < W and 0 <= y < H: + # 计算当前像素在两个端点之间的插值深度 + t = np.linalg.norm(np.array([x, y]) - uv[0]) / np.linalg.norm(uv[1] - uv[0]) + depth_val = (1 - t) * cam_pts[0, 2] + t * cam_pts[1, 2] + depth[y, x] = depth_val + + return img, depth + + # 绘制立方体的 12 条边 + edges = [] + + # 底面和顶面 + for y in [ymin, ymax]: + for z in [zmin, zmax]: + edges.append((np.array([xmin, y, z]), np.array([xmax, y, z]))) + + for x in [xmin, xmax]: + for z in [zmin, zmax]: + edges.append((np.array([x, ymin, z]), np.array([x, ymax, z]))) + + for x in [xmin, xmax]: + for y in [ymin, ymax]: + edges.append((np.array([x, y, zmin]), np.array([x, y, zmax]))) + + # 逐条绘制每条边 + for start, end in edges: + img, depth = draw_line3d(start, end, img, depth) + + return img, depth + +def projection_matrix_from_intrinsics(K, height, width, znear, zfar, window_coords='y_down'): + """Conversion of Hartley-Zisserman intrinsic matrix to OpenGL proj. matrix. + + Ref: + 1) https://strawlab.org/2011/11/05/augmented-reality-with-OpenGL + 2) https://github.com/strawlab/opengl-hz/blob/master/src/calib_test_utils.py + + :param K: 3x3 ndarray with the intrinsic camera matrix. + :param x0 The X coordinate of the camera image origin (typically 0). + :param y0: The Y coordinate of the camera image origin (typically 0). + :param w: Image width. + :param h: Image height. + :param nc: Near clipping plane. + :param fc: Far clipping plane. + :param window_coords: 'y_up' or 'y_down'. + :return: 4x4 ndarray with the OpenGL projection matrix. + """ + x0 = 0 + y0 = 0 + w = width + h = height + nc = znear + fc = zfar + + depth = float(fc - nc) + q = -(fc + nc) / depth + qn = -2 * (fc * nc) / depth + + # Draw our images upside down, so that all the pixel-based coordinate + # systems are the same. + if window_coords == 'y_up': + proj = np.array([ + [2 * K[0, 0] / w, -2 * K[0, 1] / w, (-2 * K[0, 2] + w + 2 * x0) / w, 0], + [0, -2 * K[1, 1] / h, (-2 * K[1, 2] + h + 2 * y0) / h, 0], + [0, 0, q, qn], # Sets near and far planes (glPerspective). + [0, 0, -1, 0] + ]) + + # Draw the images upright and modify the projection matrix so that OpenGL + # will generate window coords that compensate for the flipped image coords. + elif window_coords == 'y_down': + proj = np.array([ + [2 * K[0, 0] / w, -2 * K[0, 1] / w, (-2 * K[0, 2] + w + 2 * x0) / w, 0], + [0, 2 * K[1, 1] / h, (2 * K[1, 2] - h + 2 * y0) / h, 0], + [0, 0, q, qn], # Sets near and far planes (glPerspective). + [0, 0, -1, 0] + ]) + else: + raise NotImplementedError + + return proj + + + +def symmetry_tfs_from_info(info, rot_angle_discrete=5): + symmetry_tfs = [np.eye(4)] + if 'symmetries_discrete' in info: + tfs = np.array(info['symmetries_discrete']).reshape(-1,4,4) + tfs[...,:3,3] *= 0.001 + symmetry_tfs = [np.eye(4)] + symmetry_tfs += list(tfs) + if 'symmetries_continuous' in info: + axis = np.array(info['symmetries_continuous'][0]['axis']).reshape(3) + offset = info['symmetries_continuous'][0]['offset'] + rxs = [0] + rys = [0] + rzs = [0] + if axis[0]>0: + rxs = np.arange(0,360,rot_angle_discrete)/180.0*np.pi + elif axis[1]>0: + rys = np.arange(0,360,rot_angle_discrete)/180.0*np.pi + elif axis[2]>0: + rzs = np.arange(0,360,rot_angle_discrete)/180.0*np.pi + for rx in rxs: + for ry in rys: + for rz in rzs: + tf = euler_matrix(rx, ry, rz) + tf[:3,3] = offset + symmetry_tfs.append(tf) + if len(symmetry_tfs)==0: + symmetry_tfs = [np.eye(4)] + symmetry_tfs = np.array(symmetry_tfs) + return symmetry_tfs + + + +def pose_to_egocentric_delta_pose(A_in_cam, B_in_cam): + '''Used for Pose Refinement. Given the object's two poses in camera, convert them to relative poses in camera's egocentric view + @A_in_cam: (B,4,4) torch tensor + ''' + trans_delta = B_in_cam[:,:3,3] - A_in_cam[:,:3,3] + rot_mat_delta = B_in_cam[:,:3,:3]@A_in_cam[:,:3,:3].permute(0,2,1) + return trans_delta, rot_mat_delta + + + +def egocentric_delta_pose_to_pose(A_in_cam, trans_delta, rot_mat_delta): + '''Used for Pose Refinement. Given the object's two poses in camera, convert them to relative poses in camera's egocentric view + @A_in_cam: (B,4,4) torch tensor + ''' + B_in_cam = torch.eye(4, dtype=torch.float, device=A_in_cam.device)[None].expand(len(A_in_cam),-1,-1).contiguous() + B_in_cam[:,:3,3] = A_in_cam[:,:3,3]+trans_delta + B_in_cam[:,:3,:3] = rot_mat_delta@A_in_cam[:,:3,:3] + return B_in_cam + + +def sdg_load_bounding_box(file_path: str): + """Load bounding boxes. + Args: + file_path: Path of the bounding box. + + Returns: + A dictionary of the bounding boxes. + """ + bbox_dict = {} + bbox_array = np.load(file_path) + for id, x_min, y_min, x_max, y_max, occlusion_ratio in zip( + bbox_array["semanticId"], + bbox_array["x_min"], + bbox_array["y_min"], + bbox_array["x_max"], + bbox_array["y_max"], + bbox_array["occlusionRatio"], + ): + bbox_dict[id] = { + "x_min": x_min, + "y_min": y_min, + "x_max": x_max, + "y_max": y_max, + "occlusion_ratio": occlusion_ratio, + } + return bbox_dict + + +def texture_map_interpolation(tex_image_numpy): + all_channels = [] + mask = np.all(tex_image_numpy == 0, axis=2) + x = np.arange(0, tex_image_numpy.shape[1]) + y = np.arange(0, tex_image_numpy.shape[0]) + xx, yy = np.meshgrid(x, y) + for each_channel in range(tex_image_numpy.shape[2]): + curr_channel = tex_image_numpy[:,:,each_channel] + x1 = xx[~mask] + y1 = yy[~mask] + newarr = curr_channel[~mask] + GD1 = griddata((x1, y1), newarr.ravel(), (xx, yy), method='nearest') + all_channels.append(GD1[:,:,np.newaxis].round().astype(np.uint8)) + final_image = np.concatenate(all_channels, axis =-1) + return final_image + + + +class OctreeManager: + def __init__(self,pts=None,max_level=None,octree=None): + import kaolin + if octree is None: + pts_quantized = kaolin.ops.spc.quantize_points(pts.contiguous(), level=max_level) + self.octree = kaolin.ops.spc.unbatched_points_to_octree(pts_quantized, max_level, sorted=False) + else: + self.octree = octree + lengths = torch.tensor([len(self.octree)], dtype=torch.int32).cpu() + self.max_level, self.pyramids, self.exsum = kaolin.ops.spc.scan_octrees(self.octree,lengths) + self.finest_vox_size = 2.0/(2**self.max_level) + self.n_level = self.max_level+1 + self.vox_point_all_levels = kaolin.ops.spc.generate_points(self.octree, self.pyramids, self.exsum) + self.point_hierarchy_dual, self.pyramid_dual = kaolin.ops.spc.unbatched_make_dual(self.vox_point_all_levels, self.pyramids[0]) + self.trinkets, self.pointers_to_parent = kaolin.ops.spc.unbatched_make_trinkets(self.vox_point_all_levels, self.pyramids[0], self.point_hierarchy_dual, self.pyramid_dual) + self.n_vox = len(self.vox_point_all_levels) + self.n_corners = len(self.point_hierarchy_dual) + + for level in range(self.n_level): + vox_pts = self.get_level_quantized_points(level) + corner_pts = self.get_level_corner_quantized_points(level) + logging.info(f'level:{level}, vox_pts:{vox_pts.shape}, corner_pts:{corner_pts.shape}') + + def get_level_corner_quantized_points(self,level): + start = self.pyramid_dual[...,1,level] + num = self.pyramid_dual[...,0,level] + return self.point_hierarchy_dual[start:start+num] + + def get_level_quantized_points(self,level): + start = self.pyramids[...,1,level] + num = self.pyramids[...,0,level] + return self.vox_point_all_levels[start:start+num] + + + def get_center_ids(self,x,level): + '''Get ids with 0 starting from current level's first point + ''' + import kaolin + pidx = kaolin.ops.spc.unbatched_query(self.octree, self.exsum, x.float(), level, with_parents=False) + return pidx + + + def get_vox_size_at_level(self, level): + return 2.0/(2**level) + + + def draw(self,level, method='point'): + import kaolin + logging.info(f"level:{level}") + vox_size = self.get_vox_size_at_level(level) + + if method=='point': + corner_coords = self.get_level_corner_quantized_points(level) + pts = corner_coords*vox_size - 1 + mesh = trimesh.points.PointCloud(pts.data.cpu().numpy().reshape(-1,3)) + return mesh + + + def ray_trace(self,rays_o,rays_d,level,debug=False): + """Octree is in normalized [-1,1] world coordinate frame + 'rays_o': ray origin in normalized world coordinate system + 'rays_d': (N,3) unit length ray direction in normalized world coordinate system + 'octree': spc + @voxel_size: in the scale of [-1,1] space + Return: + ray_depths_in_out: traveling times, NOT the Z value; invalid will be zeros + """ + from mycuda import common + import kaolin + + ray_index, rays_pid, depth_in_out = kaolin.render.spc.unbatched_raytrace(self.octree,self.vox_point_all_levels,self.pyramids[0],self.exsum,rays_o,rays_d,level=level,return_depth=True,with_exit=True) + if ray_index.size()[0] == 0: + pdb.set_trace() + print("[WARNING] batch has 0 intersections!!") + ray_depths_in_out = torch.zeros((rays_o.shape[0],1,2)) + rays_pid = -torch.ones_like(rays_o[:, :1]) + rays_near = torch.zeros_like(rays_o[:, :1]) + rays_far = torch.zeros_like(rays_o[:, :1]) + return rays_near, rays_far, rays_pid, ray_depths_in_out + + intersected_ray_ids,counts = torch.unique_consecutive(ray_index,return_counts=True) + max_intersections = counts.max().item() + start_poss = torch.cat([torch.tensor([0], device=counts.device),torch.cumsum(counts[:-1],dim=0)],dim=0) + + ray_depths_in_out = common.postprocessOctreeRayTracing(ray_index.long().contiguous(),depth_in_out.contiguous(),intersected_ray_ids.long().contiguous(),start_poss.long().contiguous(), max_intersections, rays_o.shape[0]) + + rays_far = ray_depths_in_out[:,:,1].max(dim=-1)[0].reshape(-1,1) + rays_near = ray_depths_in_out[:,0,0].reshape(-1,1) + + return rays_near, rays_far, rays_pid, ray_depths_in_out + + +def make_yaml_dumpable(D): + if isinstance(D, np.ndarray): + return D.tolist() + for d in D: + if isinstance(D[d], dict) or isinstance(D[d], OrderedDict) or isinstance(D[d], defaultdict): + D[d] = dict(D[d]) + D[d] = make_yaml_dumpable(D[d]) + continue + if isinstance(D[d], np.ndarray): + D[d] = D[d].tolist() + continue + if np.issubdtype(type(D[d]), int): + D[d] = int(D[d]) + continue + if np.issubdtype(type(D[d]), float): + D[d] = float(D[d]) + continue + if np.issubdtype(type(D[d]), str): + D[d] = str(D[d]) + continue + if isinstance(D[d], list): + for i in range(len(D[d])): + D[d][i] = make_yaml_dumpable(D[d][i]) + continue + return dict(D) diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/build_all.sh b/OVOW/engine/oneposeviagen/fpose/fpose/build_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..90937574a06a56189cae6adbdc4d45a1875fe498 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/build_all.sh @@ -0,0 +1,7 @@ +DIR=$(pwd) + +cd $DIR/mycpp/ && mkdir -p build && cd build && cmake .. -DPYTHON_EXECUTABLE=$(which python) && make -j11 +cd /kaolin && rm -rf build *egg* && pip install -e . +cd $DIR/bundlesdf/mycuda && rm -rf build *egg* && pip install -e . + +cd ${DIR} diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/build_all_conda.sh b/OVOW/engine/oneposeviagen/fpose/fpose/build_all_conda.sh new file mode 100644 index 0000000000000000000000000000000000000000..0f066c37d2402286b9a03cb6459f4cf75672c82e --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/build_all_conda.sh @@ -0,0 +1,14 @@ +PROJ_ROOT=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) + +# Install mycpp +cd ${PROJ_ROOT}/mycpp/ && \ +rm -rf build && mkdir -p build && cd build && \ +cmake .. && \ +make -j$(nproc) + +# Install mycuda +cd ${PROJ_ROOT}/bundlesdf/mycuda && \ +rm -rf build *egg* *.so && \ +python -m pip install -e . --no-build-isolation + +cd ${PROJ_ROOT} diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/config_linemod.yml b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/config_linemod.yml new file mode 100644 index 0000000000000000000000000000000000000000..477faa88f2830fae95b8edaa8e8cdf773bf23073 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/config_linemod.yml @@ -0,0 +1,105 @@ +notes: '' +n_step: 1000 +netdepth: 8 +netwidth: 256 +netdepth_fine: 8 +netwidth_fine: 256 +N_rand: 2048 # Batch number of rays +first_frame_ray_in_batch: 0 +lrate: 0.01 +lrate_pose: 0.01 +pose_optimize_start: 0 +decay_rate: 0.1 +chunk: 99999999999 +netchunk: 6553600 +no_batching: 0 +amp: true + +N_samples: 128 #number of coarse samples per ray +N_samples_around_depth: 128 +N_importance: 0 +N_importance_iter: 1 +perturb: 1 +use_viewdirs: 1 +i_embed: 1 #set 1 for hashed embedding, 0 for default positional encoding, 2 for spherical; 3 for octree grid +i_embed_views: 2 #set 1 for hashed embedding, 0 for default positional encoding, 2 for spherical +multires: 8 #log2 of max freq for positional encoding (3D location) +multires_views: 3 #log2 of max freq for positional encoding (2D direction) +feature_grid_dim: 2 +raw_noise_std: 0 +white_bkgd: 0 +gradient_max_norm: 0.1 +gradient_pose_max_norm: 0.1 + +# logging/saving options +i_print: 500 +i_img: 500 +i_weights: 500 +i_mesh: 500 +i_nerf_normals: 500 +i_save_ray: 500 +i_pose: 500 +save_octree_clouds: True + +finest_res: 256 +base_res: 32 +num_levels: 16 +log2_hashmap_size: 22 +datadir: /path/to/github/HashNeRF-pytorch/data/bundlesdf_bundlesdf_e03000196 +n_train_image: 300 +use_octree: 1 +first_frame_weight: 1 +denoise_depth_use_octree_cloud: true +octree_embed_base_voxel_size: 0.02 +octree_smallest_voxel_size: 0.02 # This determines the smallest feature vox size +octree_raytracing_voxel_size: 0.02 +octree_dilate_size: 0.02 # meters +down_scale_ratio: 1 +bounding_box: [[-1,-1,-1], [1,1,1]] +farthest_pose_sampling: 0 # Sampling train images. This replace uniform skip +use_mask: 1 +dilate_mask_size: 0 +rays_valid_depth_only: true +near: 0.1 +far: 2 +rgb_weight: 1 +depth_weight: 0 +trunc: 0.01 #length of the truncation region in meters +trunc_start: 0.01 +sdf_lambda: 5 +neg_trunc_ratio: 1 # -trunc distance ratio compared to +trunc +trunc_decay_type: '' +sdf_loss_type: l2 +fs_weight: 1000 +empty_weight: 1 +fs_rgb_weight: 0 +trunc_weight: 6000 +sparse_loss_weight: 0 +tv_loss_weight: 0 +frame_features: 2 #number of channels of the learnable per-frame features +optimize_poses: 1 #optimize a pose refinement for the initial poses +pose_reg_weight: 0 +point_cloud_loss_weight: 0 +point_cloud_loss_normal_weight: 0 +eikonal_weight: 0 +normal_loss_weight: 0 +feature_reg_weight: 0.1 +deformation_reg_weight: 0 +use_deformation_field: 0 #use a deformation field to account for inaccuracies in intrinsic parameters +max_pix_shift: 0.02 # Pixel shift ratio relative to image size +share_coarse_fine: 1 +mode: sdf +fs_sdf: 1 # Uncertain free space +crop: 0 +mesh_resolution: 0.003 +max_trans: 0.02 # meters +max_rot: 10 # deg + +continual: True + +######### dbscan +dbscan_eps: 0.01 +dbscan_eps_min_samples: 1 + +####### bundlenerf +sync_max_delay: 0 # 0 for strict sync \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/config_ycbv.yml b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/config_ycbv.yml new file mode 100644 index 0000000000000000000000000000000000000000..8044598ed778df4aee4ab3f9a21dcaf6214f0fa9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/config_ycbv.yml @@ -0,0 +1,105 @@ +notes: '' +n_step: 1000 +netdepth: 8 +netwidth: 256 +netdepth_fine: 8 +netwidth_fine: 256 +N_rand: 2048 # Batch number of rays +first_frame_ray_in_batch: 0 +lrate: 0.01 +lrate_pose: 0.01 +pose_optimize_start: 0 +decay_rate: 0.1 +chunk: 99999999999 +netchunk: 6553600 +no_batching: 0 +amp: true + +N_samples: 128 #number of coarse samples per ray +N_samples_around_depth: 128 +N_importance: 0 +N_importance_iter: 1 +perturb: 1 +use_viewdirs: 1 +i_embed: 1 #set 1 for hashed embedding, 0 for default positional encoding, 2 for spherical; 3 for octree grid +i_embed_views: 2 #set 1 for hashed embedding, 0 for default positional encoding, 2 for spherical +multires: 8 #log2 of max freq for positional encoding (3D location) +multires_views: 3 #log2 of max freq for positional encoding (2D direction) +feature_grid_dim: 2 +raw_noise_std: 0 +white_bkgd: 0 +gradient_max_norm: 0.1 +gradient_pose_max_norm: 0.1 + +# logging/saving options +i_print: 500 +i_img: 500 +i_weights: 500 +i_mesh: 500 +i_nerf_normals: 500 +i_save_ray: 500 +i_pose: 500 +save_octree_clouds: True + +finest_res: 512 +base_res: 32 +num_levels: 16 +log2_hashmap_size: 22 +datadir: /path/to/github/HashNeRF-pytorch/data/bundlesdf_bundlesdf_e03000196 +n_train_image: 300 +use_octree: 1 +first_frame_weight: 1 +denoise_depth_use_octree_cloud: true +octree_embed_base_voxel_size: 0.02 +octree_smallest_voxel_size: 0.02 # This determines the smallest feature vox size +octree_raytracing_voxel_size: 0.02 +octree_dilate_size: 0.02 # meters +down_scale_ratio: 1 +bounding_box: [[-1,-1,-1], [1,1,1]] +farthest_pose_sampling: 0 # Sampling train images. This replace uniform skip +use_mask: 1 +dilate_mask_size: 0 +rays_valid_depth_only: true +near: 0.1 +far: 2 +rgb_weight: 100 +depth_weight: 0 +trunc: 0.01 #length of the truncation region in meters +trunc_start: 0.01 +sdf_lambda: 5 +neg_trunc_ratio: 1 # -trunc distance ratio compared to +trunc +trunc_decay_type: '' +sdf_loss_type: l2 +fs_weight: 100 +empty_weight: 1 +fs_rgb_weight: 0 +trunc_weight: 6000 +sparse_loss_weight: 0 +tv_loss_weight: 0 +frame_features: 2 #number of channels of the learnable per-frame features +optimize_poses: 1 #optimize a pose refinement for the initial poses +pose_reg_weight: 0 +point_cloud_loss_weight: 0 +point_cloud_loss_normal_weight: 0 +eikonal_weight: 0 +normal_loss_weight: 0 +feature_reg_weight: 0.1 +deformation_reg_weight: 0 +use_deformation_field: 0 #use a deformation field to account for inaccuracies in intrinsic parameters +max_pix_shift: 0.02 # Pixel shift ratio relative to image size +share_coarse_fine: 1 +mode: sdf +fs_sdf: 1 # Uncertain free space +crop: 0 +mesh_resolution: 0.003 +max_trans: 0.02 # meters +max_rot: 10 # deg + +continual: True + +######### dbscan +dbscan_eps: 0.01 +dbscan_eps_min_samples: 1 + +####### bundlenerf +sync_max_delay: 0 # 0 for strict sync \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/__init__.py b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/bindings.cpp b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/bindings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..605ffb44af1ac7a26a1c5a58dfea7e56431b1125 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/bindings.cpp @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#include +#include "common.h" + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("sampleRaysUniformOccupiedVoxels", &sampleRaysUniformOccupiedVoxels); + m.def("postprocessOctreeRayTracing", &postprocessOctreeRayTracing); + m.def("rayColorToTextureImageCUDA", &rayColorToTextureImageCUDA); + +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/common.cpython-311-x86_64-linux-gnu.so b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/common.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..76f0bae4e96c1af3d085fd0b0ed516b613212519 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/common.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87c73413a759362437af7f71c29b91d89abf1650b7c2058140d3d62a13bada90 +size 311752 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/common.cu b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/common.cu new file mode 100644 index 0000000000000000000000000000000000000000..97974d2d1766bd01d059499fa3f71e3fb12794c4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/common.cu @@ -0,0 +1,313 @@ +/* + * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "common.h" +#include "Eigen/Dense" + + + + + +/** + * @brief + * + * @tparam scalar_t + * @param z_sampled + * @param z_in_out + * @param z_vals + * @return __global__ + */ +template +__global__ void sample_rays_uniform_occupied_voxels_kernel(const torch::PackedTensorAccessor32 z_sampled, const torch::PackedTensorAccessor32 z_in_out, torch::PackedTensorAccessor32 z_vals) +{ + const int i_ray = blockIdx.x * blockDim.x + threadIdx.x; + const int i_sample = blockIdx.y * blockDim.y + threadIdx.y; + if (i_ray>=z_sampled.size(0)) return; + if (i_sample>=z_sampled.size(1)) return; + + int i_box = 0; + float z_remain = z_sampled[i_ray][i_sample]; + auto z_in_out_cur_ray = z_in_out[i_ray]; + const float eps = 1e-4; + const int max_n_box = z_in_out.size(1); + + if (z_in_out_cur_ray[0][0]==0) return; + + while (1) + { + if (i_box>=max_n_box) + { + if (z_remain<=eps) + { + z_vals[i_ray][i_sample] = z_in_out_cur_ray[max_n_box-1][1]; + } + else + { + printf("ERROR sample_rays_uniform_occupied_voxels_kernel: z_remain=%f, i_ray=%d, i_sample=%d, i_box=%d, z_in_out_cur_ray=(%f,%f)\n",z_remain,i_ray,i_sample,i_box,z_in_out_cur_ray[i_box][0],z_in_out_cur_ray[i_box][1]); + for (int i=0;i=1) + { + z_vals[i_ray][i_sample] = z_in_out_cur_ray[i_box-1][1]; + return; + } + else + { + printf("ERROR sample_rays_uniform_occupied_voxels_kernel: z_remain=%f, i_ray=%d, i_sample=%d, i_box=%d, z_in_out_cur_ray=(%f,%f)\n",z_remain,i_ray,i_sample,i_box,z_in_out_cur_ray[i_box][0],z_in_out_cur_ray[i_box][1]); + for (int i=0;i<<<{divCeil(N_rays,threadx),divCeil(N_samples,thready)}, {threadx,thready}>>>(z_sampled.packed_accessor32(),z_in_out.packed_accessor32(),z_vals.packed_accessor32()); + })); + + return z_vals; +} + +template +__global__ void postprocessOctreeRayTracingKernel(const torch::PackedTensorAccessor32 ray_index, const torch::PackedTensorAccessor32 depth_in_out, const torch::PackedTensorAccessor32 unique_intersect_ray_ids, const torch::PackedTensorAccessor32 start_poss, torch::PackedTensorAccessor32 depths_in_out_padded) +{ + const int unique_id_pos = blockIdx.x * blockDim.x + threadIdx.x; + if (unique_id_pos>=unique_intersect_ray_ids.size(0)) return; + const int i_ray = unique_intersect_ray_ids[unique_id_pos]; + + int i_intersect = 0; + auto cur_depths_in_out_padded = depths_in_out_padded[i_ray]; + for (int i=start_poss[unique_id_pos];idepth_in_out[i][1]) continue; + if (abs(depth_in_out[i][1]-depth_in_out[i][0])<1e-4) continue; + + cur_depths_in_out_padded[i_intersect][0] = depth_in_out[i][0]; + cur_depths_in_out_padded[i_intersect][1] = depth_in_out[i][1]; + + i_intersect++; + + } +} + +at::Tensor postprocessOctreeRayTracing(const at::Tensor ray_index, const at::Tensor depth_in_out, const at::Tensor unique_intersect_ray_ids, const at::Tensor start_poss, const int max_intersections, const int N_rays) +{ + CHECK_INPUT(ray_index); + CHECK_INPUT(depth_in_out); + CHECK_INPUT(start_poss); + + const int n_unique_ids = unique_intersect_ray_ids.sizes()[0]; + at::Tensor depths_in_out_padded = at::zeros({N_rays,max_intersections,2}, torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCUDA, 0).requires_grad(false)); + dim3 threads = {256}; + dim3 blocks = {divCeil(n_unique_ids,threads.x)}; + AT_DISPATCH_FLOATING_TYPES(depth_in_out.type(), "postprocessOctreeRayTracingKernel", ([&] + { + postprocessOctreeRayTracingKernel<<>>(ray_index.packed_accessor32(), depth_in_out.packed_accessor32(), unique_intersect_ray_ids.packed_accessor32(), start_poss.packed_accessor32(), depths_in_out_padded.packed_accessor32()); + })); + + return depths_in_out_padded; +} + + +at::Tensor calculateBarycentricCoordinate3D(const at::Tensor &triangle, const at::Tensor &p) +{ + auto vector_A = triangle[1]-triangle[2]; + auto vector_B = triangle[1]-triangle[0]; + auto normal = vector_A.cross(vector_B); + auto areaABC = (normal * at::cross(triangle[1]-triangle[0], triangle[2]-triangle[0])).sum(); + auto areaPBC = (normal * at::cross(triangle[1]-p, triangle[2]-p)).sum(); + auto areaPCA = (normal * at::cross(triangle[2]-p, triangle[0]-p)).sum(); + at::Tensor ws = at::zeros({3}).to(torch::kFloat32); + ws[0] = areaPBC / areaABC; + ws[1] = areaPCA / areaABC; + ws[2] = 1-ws[0]-ws[1]; + return ws; +} + + +__device__ Eigen::Vector3f calculateBarycentricCoordinate3DKernel(const Eigen::Matrix &triangle, const Eigen::Vector3f &p) +{ + Eigen::Vector3f vector_A = triangle.row(1)-triangle.row(2); + Eigen::Vector3f vector_B = triangle.row(1)-triangle.row(0); + Eigen::Vector3f normal = vector_A.cross(vector_B); + float areaABC = (normal.array() * (triangle.row(1)-triangle.row(0)).cross(triangle.row(2)-triangle.row(0)).transpose().array()).sum(); + float areaPBC = (normal.array() * (triangle.row(1).transpose()-p).cross(triangle.row(2).transpose()-p).array()).sum(); + float areaPCA = (normal.array() * (triangle.row(2).transpose()-p).cross(triangle.row(0).transpose()-p).array()).sum(); + Eigen::Vector3f w; + w[0] = areaPBC / areaABC; + w[1] = areaPCA / areaABC; + w[2] = 1-w[0]-w[1]; + return w; + +} + + +__device__ void calculateBarycentricCoordinate2DKernel(const Eigen::Matrix &triangle, const Eigen::Vector2f &p, Eigen::Vector3f &w) +{ + Eigen::Vector2f CA = triangle.row(0)-triangle.row(2); + Eigen::Vector2f AC = -CA; + Eigen::Vector2f CP = p-triangle.row(2).transpose(); + Eigen::Vector2f AB = triangle.row(1)-triangle.row(0); + Eigen::Vector2f AP = p-triangle.row(0).transpose(); + Eigen::Matrix2f numerator, denominator; + numerator << CA, CP; + denominator< +__global__ void rayColorToTextureImageKernel(const torch::PackedTensorAccessor32 F, const torch::PackedTensorAccessor32 V, const torch::PackedTensorAccessor32 hit_locations, const torch::PackedTensorAccessor32 hit_face_ids, const torch::PackedTensorAccessor32 uvs_tex, torch::PackedTensorAccessor32 uvs) +{ + const int i_hit = blockIdx.x*blockDim.x + threadIdx.x; + if (i_hit>=hit_locations.size(0)) return; + + auto face = F[hit_face_ids[i_hit]]; + Eigen::Matrix3f tri_v = Eigen::Matrix3f::Zero(); + for (int r=0;r<3;r++) + { + for (int c=0;c<3;c++) + { + tri_v(r,c) = V[face[r]][c]; + } + } + auto location = hit_locations[i_hit]; + Eigen::Vector3f p(location[0], location[1], location[2]); + auto w = calculateBarycentricCoordinate3DKernel(tri_v, p); + + Eigen::Matrix tri_uvs; + for (int i=0;i<3;i++) + { + for (int j=0;j<2;j++) + { + tri_uvs(i,j) = uvs_tex[face[i]][j]; + } + } + + Eigen::Vector2f cur_uv = tri_uvs.transpose() * w; + uvs[i_hit][0] = cur_uv(0); + uvs[i_hit][1] = cur_uv(1); +} + + + +void rayColorToTextureImageCUDA(const at::Tensor &F, const at::Tensor &V, const at::Tensor &hit_locations, const at::Tensor &hit_face_ids, const at::Tensor &uvs_tex, at::Tensor &uvs) +{ + CHECK_CONTIGUOUS(F); + CHECK_CONTIGUOUS(V); + CHECK_CONTIGUOUS(hit_locations); + CHECK_CONTIGUOUS(hit_face_ids); + CHECK_CONTIGUOUS(uvs_tex); + + dim3 threads = {512}; + dim3 blocks = {divCeil(int(hit_locations.sizes()[0]),threads.x)}; + + AT_DISPATCH_FLOATING_TYPES(V.type(), "rayColorToTextureImageKernel", ([&] + { + rayColorToTextureImageKernel<<>>(F.packed_accessor32(), V.packed_accessor32(), hit_locations.packed_accessor32(), hit_face_ids.packed_accessor32(), uvs_tex.packed_accessor32(), uvs.packed_accessor32()); + })); +} + + + +__device__ bool isLineIntersectLine(Eigen::Vector2f l1p1, Eigen::Vector2f l1p2, Eigen::Vector2f l2p1, Eigen::Vector2f l2p2) +{ + float q = (l1p1(1) - l2p1(1)) * (l2p2(0) - l2p1(0)) - (l1p1(0) - l2p1(0)) * (l2p2(1) - l2p1(1)); + float d = (l1p2(0) - l1p1(0)) * (l2p2(1) - l2p1(1)) - (l1p2(1) - l1p1(1)) * (l2p2(0) - l2p1(0)); + + if ( d == 0 ) + { + return false; + } + + float r = q / d; + + q = (l1p1(1) - l2p1(1)) * (l1p2(0) - l1p1(0)) - (l1p1(0) - l2p1(0)) * (l1p2(1) - l1p1(1)); + float s = q / d; + + if( r < 0 || r > 1 || s < 0 || s > 1 ) + { + return false; + } + + return true; +} + +__device__ bool isLineIntersectSquare(const Eigen::Vector2f &la, const Eigen::Vector2f &lb, const Eigen::Vector2f &p0, const Eigen::Vector2f &p1, const Eigen::Vector2f &p2, const Eigen::Vector2f &p3) +{ + return isLineIntersectLine(la, lb, p0, p1) || isLineIntersectLine(la, lb, p1, p2) || isLineIntersectLine(la, lb, p2, p3) || isLineIntersectLine(la, lb, p3, p0); +} + + +__device__ bool isPixelInsideTriangle(const Eigen::Matrix &triangle, Eigen::Vector2f p, Eigen::Vector3f &w) +{ + calculateBarycentricCoordinate2DKernel(triangle, p, w); + for (int j=0;j<3;j++) + { + if (w(j)<0) return false; + } + return true; +} diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/common.h b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/common.h new file mode 100644 index 0000000000000000000000000000000000000000..77d98cb166588a80f8bdde52bb9de3588bf69f71 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/common.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. + * + * NVIDIA CORPORATION and its licensors retain all intellectual property + * and proprietary rights in and to this software, related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA CORPORATION is strictly prohibited. + */ + + +#pragma once + +#include +#include + +#define CHECK_CUDA(x) AT_ASSERTM(x.is_cuda(), #x " must be a CUDA tensor") +#define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") +#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) + + +inline int divCeil(int a, int b) +{ + return (a+b-1)/b; +}; + + +at::Tensor sampleRaysUniformOccupiedVoxels(const at::Tensor z_in_out, const at::Tensor z_sampled, at::Tensor z_vals); +at::Tensor postprocessOctreeRayTracing(const at::Tensor ray_index, const at::Tensor depth_in_out, const at::Tensor unique_intersect_ray_ids, const at::Tensor start_poss, const int max_intersections, const int N_rays); +void rayColorToTextureImageCUDA(const at::Tensor &F, const at::Tensor &V, const at::Tensor &hit_locations, const at::Tensor &hit_face_ids, const at::Tensor &uvs_tex, at::Tensor &uvs); \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/gridencoder.cpython-311-x86_64-linux-gnu.so b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/gridencoder.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ea6d8a553bc50c5477b0e9551192b83467df89e5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/gridencoder.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:369f130c8ed439f7ef2102185bd375620bded3b2661c85789dbf0edcfb03c01f +size 7560480 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/setup.py b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..84875f1dc51385978054f87b33649a46ccbc079e --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/setup.py @@ -0,0 +1,41 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from setuptools import setup +import os,sys +from torch.utils.cpp_extension import BuildExtension, CUDAExtension +from torch.utils.cpp_extension import load + +code_dir = os.path.dirname(os.path.realpath(__file__)) +conda_path = os.getenv('CONDA_PREFIX') + +nvcc_flags = ['-Xcompiler', '-O3', '-std=c++17', '-U__CUDA_NO_HALF_OPERATORS__', '-U__CUDA_NO_HALF_CONVERSIONS__', '-U__CUDA_NO_HALF2_OPERATORS__'] +c_flags = ['-O3', '-std=c++17'] + +setup( + name='common', + extra_cflags=c_flags, + extra_cuda_cflags=nvcc_flags, + ext_modules=[ + CUDAExtension('common', [ + 'bindings.cpp', + 'common.cu', + ],extra_compile_args={'gcc': c_flags, 'nvcc': nvcc_flags}), + CUDAExtension('gridencoder', [ + f"{code_dir}/torch_ngp_grid_encoder/gridencoder.cu", + f"{code_dir}/torch_ngp_grid_encoder/bindings.cpp", + ],extra_compile_args={'gcc': c_flags, 'nvcc': nvcc_flags}), + ], + include_dirs=[ + f"{conda_path}/include/eigen3", + "/usr/include/eigen3", + ], + cmdclass={ + 'build_ext': BuildExtension +}) diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/torch_ngp_grid_encoder/LICENSE b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/torch_ngp_grid_encoder/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..56f524a263863d139bce3bef0f9c71a2c37a36ad --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/torch_ngp_grid_encoder/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 hawkey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/torch_ngp_grid_encoder/bindings.cpp b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/torch_ngp_grid_encoder/bindings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..afa6f64fd7d7d1efc0380e279aad3ae3ca66c36f --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/torch_ngp_grid_encoder/bindings.cpp @@ -0,0 +1,8 @@ +#include + +#include "gridencoder.h" + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("grid_encode_forward", &grid_encode_forward, "grid_encode_forward (CUDA)"); + m.def("grid_encode_backward", &grid_encode_backward, "grid_encode_backward (CUDA)"); +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/torch_ngp_grid_encoder/grid.py b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/torch_ngp_grid_encoder/grid.py new file mode 100644 index 0000000000000000000000000000000000000000..6573ce498c282b9aacaf76254b22d2e1a96bb63d --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/torch_ngp_grid_encoder/grid.py @@ -0,0 +1,158 @@ +import numpy as np +import os,sys,pdb +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(code_dir) +import torch +import torch.nn as nn +from torch.autograd import Function +from torch.autograd.function import once_differentiable +from torch.cuda.amp import custom_bwd, custom_fwd +from setuptools import setup +from torch.utils.cpp_extension import BuildExtension, CUDAExtension +from torch.utils.cpp_extension import load +import os,sys +import gridencoder + + +_gridtype_to_id = { + 'hash': 0, + 'tiled': 1, +} + +class _grid_encode(Function): + @staticmethod + @custom_fwd + def forward(ctx, inputs, embeddings, offsets, per_level_scale, base_resolution, calc_grad_inputs=False, gridtype=0, align_corners=False): + # inputs: [B, D], float in [0, 1] + # embeddings: [sO, C], float + # offsets: [L + 1], int + # RETURN: [B, F], float + + inputs = inputs.contiguous() + + B, D = inputs.shape + L = offsets.shape[0] - 1 + C = embeddings.shape[1] + S = np.log2(per_level_scale) + H = base_resolution + + if torch.is_autocast_enabled() and C % 2 == 0: + embeddings = embeddings.to(torch.half) + + outputs = torch.empty(L, B, C, device=inputs.device, dtype=embeddings.dtype) + + if calc_grad_inputs: + dy_dx = torch.empty(B, L * D * C, device=inputs.device, dtype=embeddings.dtype) + else: + dy_dx = torch.empty(1, device=inputs.device, dtype=embeddings.dtype) # placeholder... TODO: a better way? + + gridencoder.grid_encode_forward(inputs, embeddings, offsets, outputs, B, D, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners) + + outputs = outputs.permute(1, 0, 2).reshape(B, L * C) + + ctx.save_for_backward(inputs, embeddings, offsets, dy_dx) + ctx.dims = [B, D, C, L, S, H, gridtype] + ctx.calc_grad_inputs = calc_grad_inputs + ctx.align_corners = align_corners + + return outputs + + @staticmethod + @custom_bwd + def backward(ctx, grad): + + inputs, embeddings, offsets, dy_dx = ctx.saved_tensors + B, D, C, L, S, H, gridtype = ctx.dims + calc_grad_inputs = ctx.calc_grad_inputs + align_corners = ctx.align_corners + + # grad: [B, L * C] --> [L, B, C] + grad = grad.view(B, L, C).permute(1, 0, 2).contiguous() + + grad_embeddings = torch.zeros_like(embeddings) + + if calc_grad_inputs: + grad_inputs = torch.zeros_like(inputs, dtype=embeddings.dtype) + else: + grad_inputs = torch.zeros(1, device=inputs.device, dtype=embeddings.dtype) + + gridencoder.grid_encode_backward(grad, inputs, embeddings, offsets, grad_embeddings, B, D, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners) + + if calc_grad_inputs: + grad_inputs = grad_inputs.to(inputs.dtype) + return grad_inputs, grad_embeddings, None, None, None, None, None, None + else: + return None, grad_embeddings, None, None, None, None, None, None + + +grid_encode = _grid_encode.apply + + +# https://github.com/ashawkey/torch-ngp/blob/main/gridencoder/grid.py +class GridEncoder(nn.Module): + def __init__(self, input_dim=3, n_levels=16, level_dim=2, base_resolution=16, log2_hashmap_size=19, desired_resolution=None, gridtype='hash', align_corners=False): + super().__init__() + + per_level_scale = np.exp2(np.log2(desired_resolution / base_resolution) / (n_levels - 1)) + + self.input_dim = input_dim # coord dims, 2 or 3 + self.n_levels = n_levels # num levels, each level multiply resolution by 2 + self.level_dim = level_dim # encode channels per level + self.per_level_scale = per_level_scale # multiply resolution by this scale at each level. + self.log2_hashmap_size = log2_hashmap_size + self.base_resolution = base_resolution + self.out_dim = n_levels * level_dim + self.gridtype = gridtype + self.gridtype_id = _gridtype_to_id[gridtype] # "tiled" or "hash" + self.align_corners = align_corners + + # allocate parameters + offsets = [] + offset = 0 + self.max_params = 2 ** log2_hashmap_size + for i in range(n_levels): + resolution = int(np.ceil(base_resolution * per_level_scale ** i)) + params_in_level = min(self.max_params, (resolution if align_corners else resolution + 1) ** input_dim) # limit max number + params_in_level = int(np.ceil(params_in_level / 8) * 8) # make divisible + print(f"level {i}, resolution: {resolution}") + offsets.append(offset) + offset += params_in_level + offsets.append(offset) + offsets = torch.from_numpy(np.array(offsets, dtype=np.int32)) + self.register_buffer('offsets', offsets) + + self.n_params = offsets[-1] * level_dim + + # parameters + self.embeddings = nn.Parameter(torch.empty(offset, level_dim)) + # self.embeddings = nn.Embedding(offset, level_dim, sparse=True) + + self.reset_parameters() + + def reset_parameters(self): + std = 1e-4 + self.embeddings.data.uniform_(-std, std) + # self.embeddings.weight.data.uniform_(-std, std) + + + def __repr__(self): + return f"GridEncoder: input_dim={self.input_dim} n_levels={self.n_levels} level_dim={self.level_dim} resolution={self.base_resolution} -> {int(round(self.base_resolution * self.per_level_scale ** (self.n_levels - 1)))} per_level_scale={self.per_level_scale:.4f} params={tuple(self.embeddings.shape)} gridtype={self.gridtype} align_corners={self.align_corners}" + + + def forward(self, inputs, bound=1): + # inputs: [..., input_dim], normalized real world positions in [-bound, bound] + # return: [..., num_levels * level_dim] + + inputs = (inputs + bound) / (2 * bound) # map to [0, 1] + + #print('inputs', inputs.shape, inputs.dtype, inputs.min().item(), inputs.max().item()) + + prefix_shape = list(inputs.shape[:-1]) + inputs = inputs.view(-1, self.input_dim) + + outputs = grid_encode(inputs, self.embeddings, self.offsets, self.per_level_scale, self.base_resolution, inputs.requires_grad, self.gridtype_id, self.align_corners) + outputs = outputs.view(prefix_shape + [self.out_dim]) + + #print('outputs', outputs.shape, outputs.dtype, outputs.min().item(), outputs.max().item()) + + return outputs \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.cu b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.cu new file mode 100644 index 0000000000000000000000000000000000000000..6bb45c7133f2d9a6d577c74137d5c28a6c27f868 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.cu @@ -0,0 +1,500 @@ +#include +#include +#include + +#include +#include + +#include +#include + +#include +#include + + +#define CHECK_CUDA(x) TORCH_CHECK(x.device().is_cuda(), #x " must be a CUDA tensor") +#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be a contiguous tensor") +#define CHECK_IS_INT(x) TORCH_CHECK(x.scalar_type() == at::ScalarType::Int, #x " must be an int tensor") +#define CHECK_IS_FLOATING(x) TORCH_CHECK(x.scalar_type() == at::ScalarType::Float || x.scalar_type() == at::ScalarType::Half || x.scalar_type() == at::ScalarType::Double, #x " must be a floating tensor") + + +// just for compatability of half precision in AT_DISPATCH_FLOATING_TYPES_AND_HALF... +static inline __device__ at::Half atomicAdd(at::Half *address, at::Half val) { + // requires CUDA >= 10 and ARCH >= 70 + // this is very slow compared to float or __half2, and never used. + //return atomicAdd(reinterpret_cast<__half*>(address), val); +} + + +template +static inline __host__ __device__ T div_round_up(T val, T divisor) { + return (val + divisor - 1) / divisor; +} + + +template +__device__ uint32_t fast_hash(const uint32_t pos_grid[D]) { + static_assert(D <= 7, "fast_hash can only hash up to 7 dimensions."); + + // While 1 is technically not a good prime for hashing (or a prime at all), it helps memory coherence + // and is sufficient for our use case of obtaining a uniformly colliding index from high-dimensional + // coordinates. + constexpr uint32_t primes[7] = { 1, 2654435761, 805459861, 3674653429, 2097192037, 1434869437, 2165219737 }; + + uint32_t result = 0; + #pragma unroll + for (uint32_t i = 0; i < D; ++i) { + result ^= pos_grid[i] * primes[i]; + } + + return result; +} + + +template +__device__ uint32_t get_grid_index(const uint32_t gridtype, const bool align_corners, const uint32_t ch, const uint32_t hashmap_size, const uint32_t resolution, const uint32_t pos_grid[D]) { + uint32_t stride = 1; + uint32_t index = 0; + + #pragma unroll + for (uint32_t d = 0; d < D && stride <= hashmap_size; d++) { + index += pos_grid[d] * stride; + stride *= align_corners ? resolution: (resolution + 1); + } + + // NOTE: for NeRF, the hash is in fact not necessary. Check https://github.com/NVlabs/instant-ngp/issues/97. + // gridtype: 0 == hash, 1 == tiled + if (gridtype == 0 && stride > hashmap_size) { + index = fast_hash(pos_grid); + } + + return (index % hashmap_size) * C + ch; +} + + +/** + * @brief + * + * @tparam scalar_t + * @tparam D : point dimension usually 3D + * @tparam C : embedding dim 1/2/4 + * @param inputs + * @param grid + * @param offsets + * @param outputs + * @param B + * @param L + * @param S + * @param H + * @param calc_grad_inputs + * @param dy_dx + * @param gridtype + * @param align_corners + * @return __global__ + */ +template +__global__ void kernel_grid( + const float * __restrict__ inputs, + const scalar_t * __restrict__ grid, + const int * __restrict__ offsets, + scalar_t * __restrict__ outputs, + const uint32_t B, const uint32_t L, const float S, const uint32_t H, + const bool calc_grad_inputs, + scalar_t * __restrict__ dy_dx, + const uint32_t gridtype, + const bool align_corners +) { + const uint32_t b = blockIdx.x * blockDim.x + threadIdx.x; // batch id + + if (b >= B) return; + + const uint32_t level = blockIdx.y; + + // locate + grid += (uint32_t)offsets[level] * C; + inputs += b * D; + outputs += level * B * C + b * C; + + // check input range (should be in [0, 1]) + bool flag_oob = false; + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + if (inputs[d] < 0 || inputs[d] > 1) { + flag_oob = true; + } + } + // if input out of bound, just set output to 0 + if (flag_oob) { + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + outputs[ch] = 0; + } + if (calc_grad_inputs) { + dy_dx += b * D * L * C + level * D * C; // B L D C + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + dy_dx[d * C + ch] = 0; + } + } + } + return; + } + + const uint32_t hashmap_size = offsets[level + 1] - offsets[level]; + const float scale = exp2f(level * S) * H - 1.0f; + const uint32_t resolution = (uint32_t)ceil(scale) + 1; + + // calculate coordinate + float pos[D]; + uint32_t pos_grid[D]; + + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + pos[d] = inputs[d] * scale + (align_corners ? 0.0f : 0.5f); + pos_grid[d] = floorf(pos[d]); + pos[d] -= (float)pos_grid[d]; + } + + //printf("[b=%d, l=%d] pos=(%f, %f)+(%d, %d)\n", b, level, pos[0], pos[1], pos_grid[0], pos_grid[1]); + + // interpolate + scalar_t results[C] = {0}; // temp results in register + + #pragma unroll + for (uint32_t idx = 0; idx < (1 << D); idx++) { + float w = 1; + uint32_t pos_grid_local[D]; + + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + if ((idx & (1 << d)) == 0) { + w *= 1 - pos[d]; + pos_grid_local[d] = pos_grid[d]; + } else { + w *= pos[d]; + pos_grid_local[d] = pos_grid[d] + 1; + } + } + + uint32_t index = get_grid_index(gridtype, align_corners, 0, hashmap_size, resolution, pos_grid_local); // Hashing + + // writing to register (fast) + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + results[ch] += w * grid[index + ch]; + } + + //printf("[b=%d, l=%d] int %d, idx %d, w %f, val %f\n", b, level, idx, index, w, grid[index]); + } + + // writing to global memory (slow) + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + outputs[ch] = results[ch]; + } + + // prepare dy_dx for calc_grad_inputs + // differentiable (soft) indexing: https://discuss.pytorch.org/t/differentiable-indexing/17647/9 + if (calc_grad_inputs) { + + dy_dx += b * D * L * C + level * D * C; // B L D C + + #pragma unroll + for (uint32_t gd = 0; gd < D; gd++) { + + scalar_t results_grad[C] = {0}; + + #pragma unroll + for (uint32_t idx = 0; idx < (1 << (D - 1)); idx++) { + float w = scale; + uint32_t pos_grid_local[D]; + + #pragma unroll + for (uint32_t nd = 0; nd < D - 1; nd++) { + const uint32_t d = (nd >= gd) ? (nd + 1) : nd; + + if ((idx & (1 << nd)) == 0) { + w *= 1 - pos[d]; + pos_grid_local[d] = pos_grid[d]; + } else { + w *= pos[d]; + pos_grid_local[d] = pos_grid[d] + 1; + } + } + + pos_grid_local[gd] = pos_grid[gd]; + uint32_t index_left = get_grid_index(gridtype, align_corners, 0, hashmap_size, resolution, pos_grid_local); + pos_grid_local[gd] = pos_grid[gd] + 1; + uint32_t index_right = get_grid_index(gridtype, align_corners, 0, hashmap_size, resolution, pos_grid_local); + + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + results_grad[ch] += w * (grid[index_right + ch] - grid[index_left + ch]); + } + } + + #pragma unroll + for (uint32_t ch = 0; ch < C; ch++) { + dy_dx[gd * C + ch] = results_grad[ch]; + } + } + } +} + + +template +__global__ void kernel_grid_backward( + const scalar_t * __restrict__ grad, + const float * __restrict__ inputs, + const scalar_t * __restrict__ grid, + const int * __restrict__ offsets, + scalar_t * __restrict__ grad_grid, + const uint32_t B, const uint32_t L, const float S, const uint32_t H, + const uint32_t gridtype, + const bool align_corners +) { + const uint32_t b = (blockIdx.x * blockDim.x + threadIdx.x) * N_C / C; + if (b >= B) return; + + const uint32_t level = blockIdx.y; + const uint32_t ch = (blockIdx.x * blockDim.x + threadIdx.x) * N_C - b * C; + + // locate + grad_grid += offsets[level] * C; + inputs += b * D; + grad += level * B * C + b * C + ch; // L, B, C + + const uint32_t hashmap_size = offsets[level + 1] - offsets[level]; + const float scale = exp2f(level * S) * H - 1.0f; + const uint32_t resolution = (uint32_t)ceil(scale) + 1; + + // check input range (should be in [0, 1]) + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + if (inputs[d] < 0 || inputs[d] > 1) { + return; // grad is init as 0, so we simply return. + } + } + + // calculate coordinate + float pos[D]; + uint32_t pos_grid[D]; + + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + pos[d] = inputs[d] * scale + (align_corners ? 0.0f : 0.5f); + pos_grid[d] = floorf(pos[d]); + pos[d] -= (float)pos_grid[d]; + } + + scalar_t grad_cur[N_C] = {0}; // fetch to register + #pragma unroll + for (uint32_t c = 0; c < N_C; c++) { + grad_cur[c] = grad[c]; + } + + // interpolate + #pragma unroll + for (uint32_t idx = 0; idx < (1 << D); idx++) { + float w = 1; + uint32_t pos_grid_local[D]; + + #pragma unroll + for (uint32_t d = 0; d < D; d++) { + if ((idx & (1 << d)) == 0) { + w *= 1 - pos[d]; + pos_grid_local[d] = pos_grid[d]; + } else { + w *= pos[d]; + pos_grid_local[d] = pos_grid[d] + 1; + } + } + + uint32_t index = get_grid_index(gridtype, align_corners, ch, hashmap_size, resolution, pos_grid_local); + + // atomicAdd for __half is slow (especially for large values), so we use __half2 if N_C % 2 == 0 + // TODO: use float which is better than __half, if N_C % 2 != 0 + if (std::is_same::value && N_C % 2 == 0) { + #pragma unroll + for (uint32_t c = 0; c < N_C; c += 2) { + // process two __half at once (by interpreting as a __half2) + __half2 v = {(__half)(w * grad_cur[c]), (__half)(w * grad_cur[c + 1])}; + atomicAdd((__half2*)&grad_grid[index + c], v); + } + // float, or __half when N_C % 2 != 0 (which means C == 1) + } else { + #pragma unroll + for (uint32_t c = 0; c < N_C; c++) { + atomicAdd(&grad_grid[index + c], w * grad_cur[c]); + } + } + } +} + + +template +__global__ void kernel_input_backward( + const scalar_t * __restrict__ grad, + const scalar_t * __restrict__ dy_dx, + scalar_t * __restrict__ grad_inputs, + uint32_t B, uint32_t L +) { + const uint32_t t = threadIdx.x + blockIdx.x * blockDim.x; + if (t >= B * D) return; + + const uint32_t b = t / D; + const uint32_t d = t - b * D; + + dy_dx += b * L * D * C; + + scalar_t result = 0; + + # pragma unroll + for (int l = 0; l < L; l++) { + # pragma unroll + for (int ch = 0; ch < C; ch++) { + result += grad[l * B * C + b * C + ch] * dy_dx[l * D * C + d * C + ch]; + } + } + + grad_inputs[t] = result; +} + + +template +void kernel_grid_wrapper(const float *inputs, const scalar_t *embeddings, const int *offsets, scalar_t *outputs, const uint32_t B, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, scalar_t *dy_dx, const uint32_t gridtype, const bool align_corners) { + static constexpr uint32_t N_THREAD = 512; + const dim3 blocks_hashgrid = { div_round_up(B, N_THREAD), L, 1 }; + switch (C) { + case 1: kernel_grid<<>>(inputs, embeddings, offsets, outputs, B, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 2: kernel_grid<<>>(inputs, embeddings, offsets, outputs, B, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 4: kernel_grid<<>>(inputs, embeddings, offsets, outputs, B, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 8: kernel_grid<<>>(inputs, embeddings, offsets, outputs, B, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + default: throw std::runtime_error{"GridEncoding: C must be 1, 2, 4, or 8."}; + } +} + +// inputs: [B, D], float, in [0, 1] +// embeddings: [sO, C], float +// offsets: [L + 1], uint32_t +// outputs: [L, B, C], float (L first, so only one level of hashmap needs to fit into cache at a time.) +// H: base resolution +// dy_dx: [B, L * D * C] +template +void grid_encode_forward_cuda(const float *inputs, const scalar_t *embeddings, const int *offsets, scalar_t *outputs, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, scalar_t *dy_dx, const uint32_t gridtype, const bool align_corners) { + switch (D) { + case 1: kernel_grid_wrapper(inputs, embeddings, offsets, outputs, B, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 2: kernel_grid_wrapper(inputs, embeddings, offsets, outputs, B, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 3: kernel_grid_wrapper(inputs, embeddings, offsets, outputs, B, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 4: kernel_grid_wrapper(inputs, embeddings, offsets, outputs, B, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + case 5: kernel_grid_wrapper(inputs, embeddings, offsets, outputs, B, C, L, S, H, calc_grad_inputs, dy_dx, gridtype, align_corners); break; + default: throw std::runtime_error{"GridEncoding: D must be 1, 2, 3, 4, or 5."}; + } + +} + +template +void kernel_grid_backward_wrapper(const scalar_t *grad, const float *inputs, const scalar_t *embeddings, const int *offsets, scalar_t *grad_embeddings, const uint32_t B, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, scalar_t *dy_dx, scalar_t *grad_inputs, const uint32_t gridtype, const bool align_corners) { + static constexpr uint32_t N_THREAD = 256; + const uint32_t N_C = std::min(2u, C); // n_features_per_thread + const dim3 blocks_hashgrid = { div_round_up(B * C / N_C, N_THREAD), L, 1 }; + switch (C) { + case 1: + kernel_grid_backward<<>>(grad, inputs, embeddings, offsets, grad_embeddings, B, L, S, H, gridtype, align_corners); + if (calc_grad_inputs) kernel_input_backward<<>>(grad, dy_dx, grad_inputs, B, L); + break; + case 2: + kernel_grid_backward<<>>(grad, inputs, embeddings, offsets, grad_embeddings, B, L, S, H, gridtype, align_corners); + if (calc_grad_inputs) kernel_input_backward<<>>(grad, dy_dx, grad_inputs, B, L); + break; + case 4: + kernel_grid_backward<<>>(grad, inputs, embeddings, offsets, grad_embeddings, B, L, S, H, gridtype, align_corners); + if (calc_grad_inputs) kernel_input_backward<<>>(grad, dy_dx, grad_inputs, B, L); + break; + case 8: + kernel_grid_backward<<>>(grad, inputs, embeddings, offsets, grad_embeddings, B, L, S, H, gridtype, align_corners); + if (calc_grad_inputs) kernel_input_backward<<>>(grad, dy_dx, grad_inputs, B, L); + break; + default: throw std::runtime_error{"GridEncoding: C must be 1, 2, 4, or 8."}; + } +} + + +// grad: [L, B, C], float +// inputs: [B, D], float, in [0, 1] +// embeddings: [sO, C], float +// offsets: [L + 1], uint32_t +// grad_embeddings: [sO, C] +// H: base resolution +template +void grid_encode_backward_cuda(const scalar_t *grad, const float *inputs, const scalar_t *embeddings, const int *offsets, scalar_t *grad_embeddings, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, scalar_t *dy_dx, scalar_t *grad_inputs, const uint32_t gridtype, const bool align_corners) { + switch (D) { + case 1: kernel_grid_backward_wrapper(grad, inputs, embeddings, offsets, grad_embeddings, B, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners); break; + case 2: kernel_grid_backward_wrapper(grad, inputs, embeddings, offsets, grad_embeddings, B, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners); break; + case 3: kernel_grid_backward_wrapper(grad, inputs, embeddings, offsets, grad_embeddings, B, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners); break; + case 4: kernel_grid_backward_wrapper(grad, inputs, embeddings, offsets, grad_embeddings, B, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners); break; + case 5: kernel_grid_backward_wrapper(grad, inputs, embeddings, offsets, grad_embeddings, B, C, L, S, H, calc_grad_inputs, dy_dx, grad_inputs, gridtype, align_corners); break; + default: throw std::runtime_error{"GridEncoding: D must be 1, 2, 3, 4, or 5."}; + } +} + + + +void grid_encode_forward(const at::Tensor inputs, const at::Tensor embeddings, const at::Tensor offsets, at::Tensor outputs, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, at::Tensor dy_dx, const uint32_t gridtype, const bool align_corners) { + CHECK_CUDA(inputs); + CHECK_CUDA(embeddings); + CHECK_CUDA(offsets); + CHECK_CUDA(outputs); + CHECK_CUDA(dy_dx); + + CHECK_CONTIGUOUS(inputs); + CHECK_CONTIGUOUS(embeddings); + CHECK_CONTIGUOUS(offsets); + CHECK_CONTIGUOUS(outputs); + CHECK_CONTIGUOUS(dy_dx); + + CHECK_IS_FLOATING(inputs); + CHECK_IS_FLOATING(embeddings); + CHECK_IS_INT(offsets); + CHECK_IS_FLOATING(outputs); + CHECK_IS_FLOATING(dy_dx); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF( + embeddings.scalar_type(), "grid_encode_forward", ([&] { + grid_encode_forward_cuda(inputs.data_ptr(), embeddings.data_ptr(), offsets.data_ptr(), outputs.data_ptr(), B, D, C, L, S, H, calc_grad_inputs, dy_dx.data_ptr(), gridtype, align_corners); + })); +} + +void grid_encode_backward(const at::Tensor grad, const at::Tensor inputs, const at::Tensor embeddings, const at::Tensor offsets, at::Tensor grad_embeddings, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, const at::Tensor dy_dx, at::Tensor grad_inputs, const uint32_t gridtype, const bool align_corners) { + CHECK_CUDA(grad); + CHECK_CUDA(inputs); + CHECK_CUDA(embeddings); + CHECK_CUDA(offsets); + CHECK_CUDA(grad_embeddings); + CHECK_CUDA(dy_dx); + CHECK_CUDA(grad_inputs); + + CHECK_CONTIGUOUS(grad); + CHECK_CONTIGUOUS(inputs); + CHECK_CONTIGUOUS(embeddings); + CHECK_CONTIGUOUS(offsets); + CHECK_CONTIGUOUS(grad_embeddings); + CHECK_CONTIGUOUS(dy_dx); + CHECK_CONTIGUOUS(grad_inputs); + + CHECK_IS_FLOATING(grad); + CHECK_IS_FLOATING(inputs); + CHECK_IS_FLOATING(embeddings); + CHECK_IS_INT(offsets); + CHECK_IS_FLOATING(grad_embeddings); + CHECK_IS_FLOATING(dy_dx); + CHECK_IS_FLOATING(grad_inputs); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF( + grad.scalar_type(), "grid_encode_backward", ([&] { + grid_encode_backward_cuda(grad.data_ptr(), inputs.data_ptr(), embeddings.data_ptr(), offsets.data_ptr(), grad_embeddings.data_ptr(), B, D, C, L, S, H, calc_grad_inputs, dy_dx.data_ptr(), grad_inputs.data_ptr(), gridtype, align_corners); + })); + +} diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.h b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.h new file mode 100644 index 0000000000000000000000000000000000000000..b093e78272ee55a309fadfa08db6a2943c247700 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/torch_ngp_grid_encoder/gridencoder.h @@ -0,0 +1,15 @@ +#ifndef _HASH_ENCODE_H +#define _HASH_ENCODE_H + +#include +#include + +// inputs: [B, D], float, in [0, 1] +// embeddings: [sO, C], float +// offsets: [L + 1], uint32_t +// outputs: [B, L * C], float +// H: base resolution +void grid_encode_forward(const at::Tensor inputs, const at::Tensor embeddings, const at::Tensor offsets, at::Tensor outputs, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, at::Tensor dy_dx, const uint32_t gridtype, const bool align_corners); +void grid_encode_backward(const at::Tensor grad, const at::Tensor inputs, const at::Tensor embeddings, const at::Tensor offsets, at::Tensor grad_embeddings, const uint32_t B, const uint32_t D, const uint32_t C, const uint32_t L, const float S, const uint32_t H, const bool calc_grad_inputs, const at::Tensor dy_dx, at::Tensor grad_inputs, const uint32_t gridtype, const bool align_corners); + +#endif \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/nerf_helpers.py b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/nerf_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..0b8e0f2f4a23c4fb5e1ba5a365502aedbb742cf8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/nerf_helpers.py @@ -0,0 +1,475 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import torch,pdb,os,sys +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../') +from Utils import * +from pytorch3d.transforms import so3_log_map,so3_exp_map,se3_exp_map + +img2mse = lambda x, y : torch.mean((x - y) ** 2) +img2mae = lambda x, y: (torch.abs(x - y)).mean() +mse2psnr = lambda x : -10. * torch.log(x) / torch.log(torch.Tensor([10.])) +to8b = lambda x : (255*np.clip(x,0,1)).astype(np.uint8) + + +class FeatureArray(nn.Module): + """ + Per-frame corrective latent code. + """ + + def __init__(self, num_frames, num_channels): + super().__init__() + + self.num_frames = num_frames + self.num_channels = num_channels + + self.data = nn.parameter.Parameter(torch.normal(0,1,size=[num_frames, num_channels]).float(), requires_grad=True) + self.register_parameter('data',self.data) + + + def __call__(self, ids): + return self.data[ids] + + +class PoseArray(nn.Module): + def __init__(self, num_frames,max_trans,max_rot): + super().__init__() + self.num_frames = num_frames + self.max_trans = max_trans + self.max_rot = max_rot + self.data = nn.parameter.Parameter(torch.zeros([num_frames, 6]).float(), requires_grad=True) + self.register_parameter('data',self.data) + + + def get_matrices(self,ids): + if not torch.is_tensor(ids): + ids = torch.tensor(ids).long() + theta = torch.tanh(self.data) + trans = theta[:,:3] * self.max_trans + rot = theta[:,3:6] * self.max_rot/180.0*np.pi + Ts_data = se3_exp_map(torch.cat((trans,rot),dim=-1)).permute(0,2,1) + Ts = torch.eye(4, device=self.data.device).reshape(1,4,4).repeat(len(ids),1,1) + mask = ids!=0 + Ts[mask] = Ts_data[ids[mask]] + return Ts + + + +class SHEncoder(nn.Module): + '''Spherical encoding + ''' + def __init__(self, input_dim=3, degree=4): + + super().__init__() + + self.input_dim = input_dim + self.degree = degree + + assert self.input_dim == 3 + assert self.degree >= 1 and self.degree <= 5 + + self.out_dim = degree ** 2 + + self.C0 = 0.28209479177387814 + self.C1 = 0.4886025119029199 + self.C2 = [ + 1.0925484305920792, + -1.0925484305920792, + 0.31539156525252005, + -1.0925484305920792, + 0.5462742152960396 + ] + self.C3 = [ + -0.5900435899266435, + 2.890611442640554, + -0.4570457994644658, + 0.3731763325901154, + -0.4570457994644658, + 1.445305721320277, + -0.5900435899266435 + ] + self.C4 = [ + 2.5033429417967046, + -1.7701307697799304, + 0.9461746957575601, + -0.6690465435572892, + 0.10578554691520431, + -0.6690465435572892, + 0.47308734787878004, + -1.7701307697799304, + 0.6258357354491761 + ] + + def forward(self, input, **kwargs): + + result = torch.empty((*input.shape[:-1], self.out_dim), dtype=input.dtype, device=input.device) + x, y, z = input.unbind(-1) + + result[..., 0] = self.C0 + if self.degree > 1: + result[..., 1] = -self.C1 * y + result[..., 2] = self.C1 * z + result[..., 3] = -self.C1 * x + if self.degree > 2: + xx, yy, zz = x * x, y * y, z * z + xy, yz, xz = x * y, y * z, x * z + result[..., 4] = self.C2[0] * xy + result[..., 5] = self.C2[1] * yz + result[..., 6] = self.C2[2] * (2.0 * zz - xx - yy) + #result[..., 6] = self.C2[2] * (3.0 * zz - 1) # xx + yy + zz == 1, but this will lead to different backward gradients, interesting... + result[..., 7] = self.C2[3] * xz + result[..., 8] = self.C2[4] * (xx - yy) + if self.degree > 3: + result[..., 9] = self.C3[0] * y * (3 * xx - yy) + result[..., 10] = self.C3[1] * xy * z + result[..., 11] = self.C3[2] * y * (4 * zz - xx - yy) + result[..., 12] = self.C3[3] * z * (2 * zz - 3 * xx - 3 * yy) + result[..., 13] = self.C3[4] * x * (4 * zz - xx - yy) + result[..., 14] = self.C3[5] * z * (xx - yy) + result[..., 15] = self.C3[6] * x * (xx - 3 * yy) + if self.degree > 4: + result[..., 16] = self.C4[0] * xy * (xx - yy) + result[..., 17] = self.C4[1] * yz * (3 * xx - yy) + result[..., 18] = self.C4[2] * xy * (7 * zz - 1) + result[..., 19] = self.C4[3] * yz * (7 * zz - 3) + result[..., 20] = self.C4[4] * (zz * (35 * zz - 30) + 3) + result[..., 21] = self.C4[5] * xz * (7 * zz - 3) + result[..., 22] = self.C4[6] * (xx - yy) * (7 * zz - 1) + result[..., 23] = self.C4[7] * xz * (xx - 3 * yy) + result[..., 24] = self.C4[8] * (xx * (xx - 3 * yy) - yy * (3 * xx - yy)) + + return result + + +class Embedder(nn.Module): + def __init__(self, **kwargs): + super().__init__() + self.kwargs = kwargs + self.create_embedding_fn() + + def create_embedding_fn(self): + embed_fns = [] + d = self.kwargs['input_dims'] + out_dim = 0 + if self.kwargs['include_input']: + embed_fns.append(lambda x : x) + out_dim += d + + max_freq = self.kwargs['max_freq_log2'] + N_freqs = self.kwargs['num_freqs'] + + if self.kwargs['log_sampling']: + freq_bands = 2.**torch.linspace(0., max_freq, steps=N_freqs) + else: + freq_bands = torch.linspace(2.**0., 2.**max_freq, steps=N_freqs) + + for freq in freq_bands: + for p_fn in self.kwargs['periodic_fns']: + embed_fns.append(lambda x, p_fn=p_fn, freq=freq : p_fn(x * freq)) + out_dim += d + + self.embed_fns = embed_fns + self.out_dim = out_dim + + def forward(self, inputs): + return torch.cat([fn(inputs) for fn in self.embed_fns], -1) + + +def get_embedder(multires, cfg, i=0, octree_m=None): + if i == -1: + return nn.Identity(), 3 + elif i==0: + embed_kwargs = { + 'include_input' : True, + 'input_dims' : 3, + 'max_freq_log2' : multires-1, + 'num_freqs' : multires, + 'log_sampling' : True, + 'periodic_fns' : [torch.sin, torch.cos], + } + + embed = Embedder(**embed_kwargs) + out_dim = embed.out_dim + elif i==1: + from mycuda.torch_ngp_grid_encoder.grid import GridEncoder + embed = GridEncoder(input_dim=3, n_levels=cfg['num_levels'], log2_hashmap_size=cfg['log2_hashmap_size'], desired_resolution=cfg['finest_res'], base_resolution=cfg['base_res'], level_dim=cfg['feature_grid_dim']) + print(embed) + out_dim = embed.out_dim + elif i==2: + embed = SHEncoder(degree=cfg['multires_views']) + out_dim = embed.out_dim + return embed, out_dim + + + +def mesh_to_real_world(mesh,pose_offset,translation,sc_factor): + ''' + @pose_offset: optimized delta pose of the first frame. Usually it's identity + ''' + mesh.vertices = mesh.vertices/sc_factor - np.array(translation).reshape(1,3) + mesh.apply_transform(pose_offset) + return mesh + + +def get_optimized_poses_in_real_world(poses_normalized, pose_array, sc_factor, translation): + ''' + @poses_normalized: np array, cam_in_ob (opengl convention), normalized to [-1,1] and centered + @pose_array: PoseArray, delta poses + Return: + cam_in_ob, real-world unit, opencv convention + ''' + original_poses = poses_normalized.copy() + original_poses[:, :3, 3] /= sc_factor # To true world scale + original_poses[:, :3, 3] -= translation + + # Apply pose transformation + tf = pose_array.get_matrices(np.arange(len(poses_normalized))).reshape(-1,4,4).data.cpu().numpy() + optimized_poses = tf@poses_normalized + + optimized_poses = np.array(optimized_poses).astype(np.float32) + optimized_poses[:, :3, 3] /= sc_factor + optimized_poses[:, :3, 3] -= translation + + original_init_ob_in_cam = optimized_poses[0].copy() + offset = np.linalg.inv(original_init_ob_in_cam)@original_poses[0] + for i in range(len(optimized_poses)): + new_ob_in_cam = optimized_poses[i]@offset + optimized_poses[i] = new_ob_in_cam + optimized_poses[i] = optimized_poses[i]@glcam_in_cvcam + + return optimized_poses,offset + +def preprocess_data(rgbs,depths,masks,normal_maps,poses,sc_factor,translation): + ''' + @rgbs: np array (N,H,W,3) + @depths: (N,H,W) + @masks: (N,H,W) + @normal_maps: (N,H,W,3) + @poses: (N,4,4) + ''' + depths[depths<0.001] = BAD_DEPTH + if masks is not None: + rgbs[masks==0] = BAD_COLOR + depths[masks==0] = BAD_DEPTH + if normal_maps is not None: + normal_maps[...,[1,2]] *= -1 # To OpenGL + normal_maps[masks==0] = 0 + masks = masks[...,None] + + rgbs = (rgbs / 255.0).astype(np.float32) + depths *= sc_factor + depths = depths[...,None] + poses[:, :3, 3] += translation + poses[:, :3, 3] *= sc_factor + return rgbs,depths,masks,normal_maps,poses + + +class NeRFSmall(nn.Module): + def __init__(self,num_layers=3,hidden_dim=64,geo_feat_dim=15,num_layers_color=4,hidden_dim_color=64,input_ch=3, input_ch_views=3): + super(NeRFSmall, self).__init__() + + self.input_ch = input_ch + self.input_ch_views = input_ch_views + + # sigma network + self.num_layers = num_layers + self.hidden_dim = hidden_dim + self.geo_feat_dim = geo_feat_dim + + sigma_net = [] + for l in range(num_layers): + if l == 0: + in_dim = self.input_ch + else: + in_dim = hidden_dim + + if l == num_layers - 1: + out_dim = 1 + self.geo_feat_dim # 1 sigma + 15 SH features for color + else: + out_dim = hidden_dim + + sigma_net.append(nn.Linear(in_dim, out_dim, bias=True)) + if l!=num_layers-1: + sigma_net.append(nn.ReLU(inplace=True)) + + self.sigma_net = nn.Sequential(*sigma_net) + torch.nn.init.constant_(self.sigma_net[-1].bias, 0.1) # Encourage last layer predict positive SDF + + # color network + self.num_layers_color = num_layers_color + self.hidden_dim_color = hidden_dim_color + + color_net = [] + for l in range(num_layers_color): + if l == 0: + in_dim = self.input_ch_views + self.geo_feat_dim + else: + in_dim = hidden_dim + + if l == num_layers_color - 1: + out_dim = 3 # 3 rgb + else: + out_dim = hidden_dim + + color_net.append(nn.Linear(in_dim, out_dim, bias=True)) + if l!=num_layers_color-1: + color_net.append(nn.ReLU(inplace=True)) + + self.color_net = nn.Sequential(*color_net) + + def forward_sdf(self,x): + ''' + @x: embedded positions + ''' + h = self.sigma_net(x) + sigma, geo_feat = h[..., 0], h[..., 1:] + return sigma + + + def forward(self, x): + x = x.float() + input_pts, input_views = torch.split(x, [self.input_ch, self.input_ch_views], dim=-1) + + # sigma + h = input_pts + h = self.sigma_net(h) + + sigma, geo_feat = h[..., 0], h[..., 1:] + + # color + h = torch.cat([input_views, geo_feat], dim=-1) + color = self.color_net(h) + + outputs = torch.cat([color, sigma.unsqueeze(dim=-1)], -1) + + return outputs + + +def sample_pdf(bins, weights, N_samples, det=False): + weights = weights + 1e-5 # prevent nans + pdf = weights / torch.sum(weights, -1, keepdim=True) + cdf = torch.cumsum(pdf, -1) + cdf = torch.cat([torch.zeros_like(cdf[...,:1]), cdf], -1) # (batch, len(bins)) + + if det: + u = torch.linspace(0., 1., steps=N_samples) + u = u.expand(list(cdf.shape[:-1]) + [N_samples]) + else: + u = torch.rand(list(cdf.shape[:-1]) + [N_samples]) + + u = u.contiguous() + inds = torch.searchsorted(cdf, u, right=True) + below = torch.max(torch.zeros_like(inds-1), inds-1) + above = torch.min((cdf.shape[-1]-1) * torch.ones_like(inds), inds) + inds_g = torch.stack([below, above], -1) # (batch, N_samples, 2) + + matched_shape = [inds_g.shape[0], inds_g.shape[1], cdf.shape[-1]] + cdf_g = torch.gather(cdf.unsqueeze(1).expand(matched_shape), 2, inds_g) + bins_g = torch.gather(bins.unsqueeze(1).expand(matched_shape), 2, inds_g) + + denom = (cdf_g[...,1]-cdf_g[...,0]) + denom = torch.where(denom<1e-5, torch.ones_like(denom), denom) + t = (u-cdf_g[...,0])/denom + samples = bins_g[...,0] + t * (bins_g[...,1]-bins_g[...,0]) + + return samples + + + +def get_camera_rays_np(H, W, K): + """Get ray origins, directions from a pinhole camera.""" + i, j = np.meshgrid(np.arange(W, dtype=np.float32), + np.arange(H, dtype=np.float32), indexing='xy') + dirs = np.stack([(i - K[0,2])/K[0,0], -(j - K[1,2])/K[1,1], -np.ones_like(i)], axis=-1) + return dirs + + + +def get_masks(z_vals, target_d, truncation, cfg, dir_norm=None): + valid_depth_mask = (target_d>=cfg['near']*cfg['sc_factor']) & (target_d<=cfg['far']*cfg['sc_factor']) + front_mask = (z_vals < target_d - truncation) + back_mask = (z_vals > target_d + truncation*cfg['neg_trunc_ratio']) + + sdf_mask = (1.0 - front_mask.float()) * (1.0 - back_mask.float()) * valid_depth_mask + + num_fs_samples = front_mask.sum() + num_sdf_samples = sdf_mask.sum() + num_samples = num_sdf_samples + num_fs_samples + fs_weight = 0.5 + sdf_weight = 1.0 - fs_weight + return front_mask.bool(), sdf_mask.bool(), fs_weight, sdf_weight + + +def get_sdf_loss(z_vals, target_d, predicted_sdf, truncation, cfg, return_mask=False, sample_weights=None, rays_d=None): + dir_norm = rays_d.norm(dim=-1,keepdim=True) + front_mask, sdf_mask, fs_weight, sdf_weight = get_masks(z_vals, target_d, truncation, cfg, dir_norm=dir_norm) + front_mask = front_mask.bool() + + mask = (target_d>cfg['far']*cfg['sc_factor']) & (predicted_sdf tymax) | (tymin > tmax)] = 0 + tmin[tymin>tmin] = tymin[tymin>tmin] + tmax[tymax tzmax) | (tzmin > tmax)] = 0 + tmin[tzmin>tmin] = tzmin[tzmin>tmin] #(N) + tmax[tzmax=0 + near = (dirs_unit*tmin.reshape(-1,1))[:,2] + far = (dirs_unit*tmax.reshape(-1,1))[:,2] + good_rays = rays[ishit] + near = near[ishit] + far = far[ishit] + near = np.abs(near) + far = np.abs(far) + good_rays = np.concatenate((good_rays,near.reshape(-1,1),far.reshape(-1,1)), axis=-1) #(N,8+2) + + return good_rays + +@torch.no_grad() +def sample_rays_uniform(N_samples,near,far,lindisp=False,perturb=True): + ''' + @near: (N_ray,1) + ''' + N_ray = near.shape[0] + t_vals = torch.linspace(0., 1., steps=N_samples, device=near.device).reshape(1,-1) + if not lindisp: + z_vals = near * (1.-t_vals) + far * (t_vals) + else: + z_vals = 1./(1./near * (1.-t_vals) + 1./far * (t_vals)) #(N_ray,N_sample) + + if perturb > 0.: + mids = .5 * (z_vals[...,1:] + z_vals[...,:-1]) + upper = torch.cat([mids, z_vals[...,-1:]], -1) + lower = torch.cat([z_vals[...,:1], mids], -1) + t_rand = torch.rand(z_vals.shape, device=far.device) + z_vals = lower + (upper - lower) * t_rand + z_vals = torch.clip(z_vals,near,far) + + return z_vals.reshape(N_ray,N_samples) + + +class DataLoader: + def __init__(self,rays,batch_size): + self.rays = rays + self.batch_size = batch_size + self.pos = 0 + self.ids = torch.randperm(len(self.rays)) + + def __next__(self): + if self.pos+self.batch_size0) & (rays[:,self.ray_depth_slice]<=self.cfg['far']*self.cfg['sc_factor']) + rays_dir = rays[mask][:,self.ray_dir_slice] + rays_depth = rays[mask][:,self.ray_depth_slice] + pts3d = rays_dir*rays_depth.reshape(-1,1) + frame_ids = rays[mask][:,self.ray_frame_id_slice].astype(int) + pts3d_w = (self.poses[frame_ids]@to_homo(pts3d)[...,None])[:,:3,0] + logging.info(f"Denoising rays based on octree cloud") + + kdtree = cKDTree(self.build_octree_pts) + dists,indices = kdtree.query(pts3d_w,k=1,workers=-1) + bad_mask = dists>0.02*self.cfg['sc_factor'] + bad_ids = np.arange(len(rays))[mask][bad_mask] + rays[bad_ids,self.ray_depth_slice] = BAD_DEPTH*self.cfg['sc_factor'] + rays[bad_ids, self.ray_type_slice] = 1 + rays = rays[rays[:,self.ray_type_slice]==0] + logging.info(f"bad_mask#={bad_mask.sum()}") + + rays = torch.tensor(rays, dtype=torch.float).cuda() + + self.rays = rays + print("rays",rays.shape) + self.data_loader = DataLoader(rays=self.rays, batch_size=self.cfg['N_rand']) + + + def create_nerf(self,device=torch.device("cuda")): + """Instantiate NeRF's MLP model. + """ + models = {} + embed_fn, input_ch = get_embedder(self.cfg['multires'], self.cfg, i=self.cfg['i_embed'], octree_m=self.octree_m) + embed_fn = embed_fn.to(device) + models['embed_fn'] = embed_fn + + input_ch_views = 0 + embeddirs_fn = None + if self.cfg['use_viewdirs']: + embeddirs_fn, input_ch_views = get_embedder(self.cfg['multires_views'], self.cfg, i=self.cfg['i_embed_views'], octree_m=self.octree_m) + models['embeddirs_fn'] = embeddirs_fn + + output_ch = 4 + skips = [4] + + model = NeRFSmall(num_layers=2,hidden_dim=64,geo_feat_dim=15,num_layers_color=3,hidden_dim_color=64,input_ch=input_ch, input_ch_views=input_ch_views+self.cfg['frame_features']).to(device) + model = model.to(device) + models['model'] = model + + model_fine = None + if self.cfg['N_importance'] > 0: + if not self.cfg['share_coarse_fine']: + model_fine = NeRFSmall(num_layers=2,hidden_dim=64,geo_feat_dim=15,num_layers_color=3,hidden_dim_color=64,input_ch=input_ch, input_ch_views=input_ch_views).to(device) + models['model_fine'] = model_fine + + # Create feature array + num_training_frames = len(self.images) + feature_array = None + if self.cfg['frame_features'] > 0: + feature_array = FeatureArray(num_training_frames, self.cfg['frame_features']).to(device) + models['feature_array'] = feature_array + # Create pose array + pose_array = None + if self.cfg['optimize_poses']: + pose_array = PoseArray(num_training_frames,max_trans=self.cfg['max_trans']*self.cfg['sc_factor'],max_rot=self.cfg['max_rot']).to(device) + models['pose_array'] = pose_array + self.models = models + + + + def make_frame_rays(self,frame_id): + mask = self.masks[frame_id,...,0].copy() + rays = get_camera_rays_np(self.H, self.W, self.K) # [self.H, self.W, 3] We create rays frame-by-frame to save memory + rays = np.concatenate([rays, self.images[frame_id]], -1) # [H, W, 6] + rays = np.concatenate([rays, self.depths[frame_id]], -1) # [H, W, 7] + rays = np.concatenate([rays, self.masks[frame_id]>0], -1) # [H, W, 8] + if self.normal_maps is not None: + rays = np.concatenate([rays, self.normal_maps[frame_id]], -1) # [H, W, 11] + rays = np.concatenate([rays, frame_id*np.ones(self.depths[frame_id].shape)], -1) # [H, W, 12] + ray_types = np.zeros((self.H,self.W,1)) # 0 is good; 1 is invalid depth (uncertain) + invalid_depth = ((self.depths[frame_id,...,0]self.cfg['far']*self.cfg['sc_factor'])) & (mask>0) + ray_types[invalid_depth] = 1 + rays = np.concatenate((rays,ray_types), axis=-1) + self.ray_dir_slice = [0,1,2] + self.ray_rgb_slice = [3,4,5] + self.ray_depth_slice = 6 + self.ray_mask_slice = 7 + if self.normal_maps is not None: + self.ray_normal_slice = [8,9,10] + self.ray_frame_id_slice = 11 + self.ray_type_slice = 12 + else: + self.ray_frame_id_slice = 8 + self.ray_type_slice = 9 + + n = rays.shape[-1] + + ########## Option2: dilate + down_scale_ratio = int(self.cfg['down_scale_ratio']) + if frame_id==0: #!NOTE first frame ob mask is assumed perfect + kernel = np.ones((100, 100), np.uint8) + mask = cv2.dilate(mask.astype(np.uint8), kernel, iterations=1) + if self.occ_masks is not None: + mask[self.occ_masks[frame_id]>0] = 0 + else: + dilate = 60//down_scale_ratio + kernel = np.ones((dilate, dilate), np.uint8) + mask = cv2.dilate(mask.astype(np.uint8), kernel, iterations=1) + if self.occ_masks is not None: + mask[self.occ_masks[frame_id]>0] = 0 + + + if self.cfg['rays_valid_depth_only']: + mask[invalid_depth] = 0 + + vs,us = np.where(mask>0) + cur_rays = rays[vs,us].reshape(-1,n) + cur_rays = cur_rays[cur_rays[:,self.ray_type_slice]==0] + cur_rays = compute_near_far_and_filter_rays(self.poses[frame_id],cur_rays,self.cfg) + if self.normal_maps is not None: + self.ray_near_slice = 13 + self.ray_far_slice = 14 + else: + self.ray_near_slice = 10 + self.ray_far_slice = 11 + + if self.cfg['use_octree']: + rays_o_world = (self.poses[frame_id]@to_homo(np.zeros((len(cur_rays),3))).T).T[:,:3] + rays_o_world = torch.from_numpy(rays_o_world).cuda().float() + rays_unit_d_cam = cur_rays[:,:3]/np.linalg.norm(cur_rays[:,:3],axis=-1).reshape(-1,1) + rays_d_world = (self.poses[frame_id][:3,:3]@rays_unit_d_cam.T).T + rays_d_world = torch.from_numpy(rays_d_world).cuda().float() + + vox_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor'] + level = int(np.floor(np.log2(2.0/vox_size))) + near,far,_,ray_depths_in_out = self.octree_m.ray_trace(rays_o_world,rays_d_world,level=level) + near = near.cpu().numpy() + valid = (near>0).reshape(-1) + cur_rays = cur_rays[valid] + + return cur_rays + + + def build_octree(self): + if self.cfg['save_octree_clouds']: + dir = f"{self.cfg['save_dir']}/build_octree_cloud.ply" + pcd = toOpen3dCloud(self.build_octree_pts) + o3d.io.write_point_cloud(dir,pcd) + if self._run is not None: + self._run.add_artifact(dir) + pts = torch.tensor(self.build_octree_pts).cuda().float() # Must be within [-1,1] + octree_smallest_voxel_size = self.cfg['octree_smallest_voxel_size']*self.cfg['sc_factor'] + finest_n_voxels = 2.0/octree_smallest_voxel_size + max_level = int(np.round(np.log2(finest_n_voxels))) + octree_smallest_voxel_size = 2.0/(2**max_level) + + #################### Dilate + dilate_radius = int(np.round(self.cfg['octree_dilate_size']/octree_smallest_voxel_size)) + dilate_radius = max(1, dilate_radius) + logging.info(f"Octree voxel dilate_radius:{dilate_radius}") + shifts = [] + for dx in [-1,0,1]: + for dy in [-1,0,1]: + for dz in [-1,0,1]: + shifts.append([dx,dy,dz]) + shifts = torch.tensor(shifts).cuda().long() # (27,3) + coords = torch.floor((pts+1)/octree_smallest_voxel_size).long() #(N,3) + dilated_coords = coords.detach().clone() + for iter in range(dilate_radius): + dilated_coords = (dilated_coords[None].expand(shifts.shape[0],-1,-1) + shifts[:,None]).reshape(-1,3) + dilated_coords = torch.unique(dilated_coords,dim=0) + pts = (dilated_coords+0.5) * octree_smallest_voxel_size - 1 + pts = torch.clip(pts,-1,1) + + if self.cfg['save_octree_clouds']: + pcd = toOpen3dCloud(pts.data.cpu().numpy()) + dir = f"{self.cfg['save_dir']}/build_octree_cloud_dilated.ply" + o3d.io.write_point_cloud(dir,pcd) + if self._run is not None: + self._run.add_artifact(dir) + #################### + + assert pts.min()>=-1 and pts.max()<=1 + self.octree_m = OctreeManager(pts, max_level) + + if self.cfg['save_octree_clouds']: + dir = f"{self.cfg['save_dir']}/octree_boxes_max_level.ply" + m = self.octree_m.draw(level=max_level,method='point') + m.export(dir) + if self._run is not None: + self._run.add_artifact(dir) + vox_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor'] + level = int(np.round(np.log2(2.0/vox_size))) + if self.cfg['save_octree_clouds']: + dir = f"{self.cfg['save_dir']}/octree_boxes_ray_tracing_level.ply" + m = self.octree_m.draw(level=level,method='point') + m.export(dir) + if self._run is not None: + self._run.add_artifact(dir) + + + def create_optimizer(self): + params = [] + for k in self.models: + if self.models[k] is not None and k!='pose_array': + params += list(self.models[k].parameters()) + + param_groups = [{'name':'basic', 'params':params, 'lr':self.cfg['lrate']}] + if self.models['pose_array'] is not None: + param_groups.append({'name':'pose_array', 'params':self.models['pose_array'].parameters(), 'lr':self.cfg['lrate_pose']}) + + self.optimizer = torch.optim.Adam(param_groups, betas=(0.9, 0.999),weight_decay=0,eps=1e-15) + + self.param_groups_init = copy.deepcopy(self.optimizer.param_groups) + + + def save_weights(self,out_file,models): + data = { + 'global_step': self.global_step, + 'model': models['model'].state_dict(), + 'optimizer': self.optimizer.state_dict(), + } + if 'model_fine' in models and models['model_fine'] is not None: + data['model_fine'] = models['model_fine'].state_dict() + if models['embed_fn'] is not None: + data['embed_fn'] = models['embed_fn'].state_dict() + if models['embeddirs_fn'] is not None: + data['embeddirs_fn'] = models['embeddirs_fn'].state_dict() + if self.cfg['optimize_poses']>0: + data['pose_array'] = models['pose_array'].state_dict() + if self.cfg['frame_features'] > 0: + data['feature_array'] = models['feature_array'].state_dict() + if self.octree_m is not None: + data['octree'] = self.octree_m.octree + dir = out_file + torch.save(data,dir) + print('Saved checkpoints at', dir) + if self._run is not None: + self._run.add_artifact(dir) + dir1 = copy.deepcopy(dir) + dir = f'{os.path.dirname(out_file)}/model_latest.pth' + if dir1!=dir: + os.system(f'cp {dir1} {dir}') + if self._run is not None: + self._run.add_artifact(dir) + + + def schedule_lr(self): + for i,param_group in enumerate(self.optimizer.param_groups): + init_lr = self.param_groups_init[i]['lr'] + new_lrate = init_lr * (self.cfg['decay_rate'] ** (float(self.global_step) / self.N_iters)) + param_group['lr'] = new_lrate + + + def render_images(self,img_i,cur_rays=None): + if cur_rays is None: + frame_ids = self.rays[:, self.ray_frame_id_slice].cuda() + cur_rays = self.rays[frame_ids==img_i].cuda() + gt_depth = cur_rays[:,self.ray_depth_slice] + gt_rgb = cur_rays[:,self.ray_rgb_slice].cpu() + ray_type = cur_rays[:,self.ray_type_slice].data.cpu().numpy() + + ori_chunk = self.cfg['chunk'] + self.cfg['chunk'] = copy.deepcopy(self.cfg['N_rand']) + with torch.no_grad(): + rgb, extras = self.render(rays=cur_rays, lindisp=False,perturb=False,raw_noise_std=0, depth=gt_depth) + self.cfg['chunk'] = ori_chunk + + sdf = extras['raw'][...,-1] + z_vals = extras['z_vals'] + signs = sdf[:, 1:] * sdf[:, :-1] + empty_rays = (signs>0).all(dim=-1) + mask = signs<0 + inds = torch.argmax(mask.float(), axis=1) + inds = inds[..., None] + depth = torch.gather(z_vals,dim=1,index=inds) + depth[empty_rays] = self.cfg['far']*self.cfg['sc_factor'] + depth = depth[..., None].data.cpu().numpy() + + rgb = rgb.data.cpu().numpy() + + rgb_full = np.zeros((self.H,self.W,3),dtype=float) + depth_full = np.zeros((self.H,self.W),dtype=float) + ray_mask_full = np.zeros((self.H,self.W,3),dtype=np.uint8) + X = cur_rays[:,self.ray_dir_slice].data.cpu().numpy() + X[:,[1,2]] = -X[:,[1,2]] + projected = (self.K@X.T).T + uvs = projected/projected[:,2].reshape(-1,1) + uvs = uvs.round().astype(int) + uvs_good = uvs[ray_type==0] + ray_mask_full[uvs_good[:,1],uvs_good[:,0]] = [255,0,0] + uvs_uncertain = uvs[ray_type==1] + ray_mask_full[uvs_uncertain[:,1],uvs_uncertain[:,0]] = [0,255,0] + rgb_full[uvs[:,1],uvs[:,0]] = rgb.reshape(-1,3) + depth_full[uvs[:,1],uvs[:,0]] = depth.reshape(-1) + gt_rgb_full = np.zeros((self.H,self.W,3),dtype=float) + gt_rgb_full[uvs[:,1],uvs[:,0]] = gt_rgb.reshape(-1,3).data.cpu().numpy() + gt_depth_full = np.zeros((self.H,self.W),dtype=float) + gt_depth_full[uvs[:,1],uvs[:,0]] = gt_depth.reshape(-1).data.cpu().numpy() + + return rgb_full, depth_full, ray_mask_full, gt_rgb_full, gt_depth_full, extras + + + def get_gradients(self): + if self.models['pose_array'] is not None: + max_pose_grad = torch.abs(self.models['pose_array'].data.grad).max() + max_embed_grad = 0 + for embed in self.models['embed_fn'].embeddings: + max_embed_grad = max(max_embed_grad,torch.abs(embed.weight.grad).max()) + if self.models['feature_array'] is not None: + max_feature_grad = torch.abs(self.models['feature_array'].data.grad).max() + return max_pose_grad, max_embed_grad, max_feature_grad + + + def get_truncation(self): + '''Annearl truncation over training + ''' + if self.cfg['trunc_decay_type']=='linear': + truncation = self.cfg['trunc_start'] - (self.cfg['trunc_start']-self.cfg['trunc']) * float(self.global_step)/self.cfg['n_step'] + elif self.cfg['trunc_decay_type']=='exp': + lamb = np.log(self.cfg['trunc']/self.cfg['trunc_start']) / (self.cfg['n_step']/4) + truncation = self.cfg['trunc_start']*np.exp(self.global_step*lamb) + truncation = max(truncation,self.cfg['trunc']) + else: + truncation = self.cfg['trunc'] + + truncation *= self.cfg['sc_factor'] + return truncation + + + def train_loop(self,batch): + target_s = batch[:, self.ray_rgb_slice] # Color (N,3) + target_d = batch[:, self.ray_depth_slice] # Normalized scale (N) + + target_mask = batch[:,self.ray_mask_slice].bool().reshape(-1) + frame_ids = batch[:,self.ray_frame_id_slice] + + rgb, extras = self.render(rays=batch, depth=target_d,lindisp=False,perturb=True,raw_noise_std=self.cfg['raw_noise_std'], get_normals=False) + + valid_samples = extras['valid_samples'] #(N_ray,N_samples) + z_vals = extras['z_vals'] # [N_rand, N_samples + N_importance] + sdf = extras['raw'][..., -1] + + N_rays,N_samples = sdf.shape[:2] + valid_rays = (valid_samples>0).any(dim=-1).bool().reshape(N_rays) & (batch[:,self.ray_type_slice]==0) + + ray_type = batch[:,self.ray_type_slice].reshape(-1) + ray_weights = torch.ones((N_rays), device=rgb.device, dtype=torch.float32) + ray_weights[(frame_ids==0).view(-1)] = self.cfg['first_frame_weight'] + ray_weights = ray_weights*valid_rays.view(-1) + sample_weights = ray_weights.view(N_rays,1).expand(-1,N_samples) * valid_samples + img_loss = (((rgb-target_s)**2 * ray_weights.view(-1,1))).mean() + rgb_loss = self.cfg['rgb_weight'] * img_loss + loss = rgb_loss + + rgb0_loss = torch.tensor(0) + if 'rgb0' in extras: + img_loss0 = (((extras['rgb0']-target_s)**2 * ray_weights.view(-1,1))).mean() + rgb0_loss = img_loss0*self.cfg['rgb_weight'] + loss += rgb0_loss + + depth_loss = torch.tensor(0) + depth_loss0 = torch.tensor(0) + if self.cfg['depth_weight']>0: + signs = sdf[:, 1:] * sdf[:, :-1] + mask = signs<0 + inds = torch.argmax(mask.float(), axis=1) + inds = inds[..., None] + z_min = torch.gather(z_vals,dim=1,index=inds) + weights = ray_weights * (depth<=self.cfg['far']*self.cfg['sc_factor']) * (mask.any(dim=-1)) + depth_loss = ((z_min*weights-depth.view(-1,1)*weights)**2).mean() * self.cfg['depth_weight'] + loss = loss+depth_loss + + truncation = self.get_truncation() + sample_weights[ray_type==1] = 0 + fs_loss, sdf_loss,empty_loss, front_mask,sdf_mask = get_sdf_loss(z_vals, target_d.reshape(-1,1).expand(-1,N_samples), sdf, truncation, self.cfg,return_mask=True, sample_weights=sample_weights, rays_d=batch[:,self.ray_dir_slice]) + fs_loss = fs_loss*self.cfg['fs_weight'] + empty_loss = empty_loss*self.cfg['empty_weight'] + sdf_loss = sdf_loss*self.cfg['trunc_weight'] + loss = loss + fs_loss + sdf_loss + empty_loss + + fs_rgb_loss = torch.tensor(0) + if self.cfg['fs_rgb_weight']>0: + fs_rgb_loss = ((((torch.sigmoid(extras['raw'][...,:3])-1)*front_mask[...,None])**2) * sample_weights[...,None]).mean() + loss += fs_rgb_loss*self.cfg['fs_rgb_weight'] + + eikonal_loss = torch.tensor(0) + if self.cfg['eikonal_weight']>0: + nerf_normals = extras['normals'] + eikonal_loss = ((torch.norm(nerf_normals[sdf<1], dim=-1)-1)**2).mean() * self.cfg['eikonal_weight'] + loss += eikonal_loss + + point_cloud_loss = torch.tensor(0) + point_cloud_normal_loss = torch.tensor(0) + + + reg_features = torch.tensor(0) + if self.models['feature_array'] is not None: + reg_features = self.cfg['feature_reg_weight'] * (self.models['feature_array'].data**2).mean() + loss += reg_features + + if self.models['pose_array'] is not None: + pose_array = self.models['pose_array'] + pose_reg = self.cfg['pose_reg_weight']*pose_array.data[1:].norm() + loss += pose_reg + + variation_loss = torch.tensor(0) + + self.optimizer.zero_grad() + self.amp_scaler.scale(loss).backward() + + self.amp_scaler.step(self.optimizer) + self.amp_scaler.update() + if self.global_step%10==0 and self.global_step>0: + self.schedule_lr() + + if self.global_step%self.cfg['i_weights']==0 and self.global_step>0: + self.save_weights(out_file=os.path.join(self.cfg['save_dir'], f'model_latest.pth'), models=self.models) + + if self.global_step % self.cfg['i_img'] == 0 and self.global_step>0: + ids = torch.unique(self.rays[:, self.ray_frame_id_slice]).data.cpu().numpy().astype(int).tolist() + ids.sort() + last = ids[-1] + ids = ids[::max(1,len(ids)//5)] + if last not in ids: + ids.append(last) + canvas = [] + for frame_idx in ids: + rgb, depth, ray_mask, gt_rgb, gt_depth, _ = self.render_images(frame_idx) + mask_vis = (rgb*255*0.2 + ray_mask*0.8).astype(np.uint8) + mask_vis = np.clip(mask_vis,0,255) + rgb = np.concatenate((rgb,gt_rgb),axis=1) + far = self.cfg['far']*self.cfg['sc_factor'] + gt_depth = np.clip(gt_depth, self.cfg['near']*self.cfg['sc_factor'], far) + depth_vis = np.concatenate((to8b(depth / far), to8b(gt_depth / far)), axis=1) + depth_vis = np.tile(depth_vis[...,None],(1,1,3)) + row = np.concatenate((to8b(rgb),depth_vis,mask_vis),axis=1) + canvas.append(row) + canvas = np.concatenate(canvas,axis=0).astype(np.uint8) + dir = f"{self.cfg['save_dir']}/image_step_{self.global_step:07d}.png" + imageio.imwrite(dir,canvas) + if self._run is not None: + self._run.add_artifact(dir) + + + if self.global_step%self.cfg['i_print']==0: + msg = f"Iter: {self.global_step}, valid_samples: {valid_samples.sum()}/{torch.numel(valid_samples)}, valid_rays: {valid_rays.sum()}/{torch.numel(valid_rays)}, " + metrics = { + 'loss':loss.item(), + 'rgb_loss':rgb_loss.item(), + 'rgb0_loss':rgb0_loss.item(), + 'fs_rgb_loss': fs_rgb_loss.item(), + 'depth_loss':depth_loss.item(), + 'depth_loss0':depth_loss0.item(), + 'fs_loss':fs_loss.item(), + 'point_cloud_loss': point_cloud_loss.item(), + 'point_cloud_normal_loss':point_cloud_normal_loss.item(), + 'sdf_loss':sdf_loss.item(), + 'eikonal_loss': eikonal_loss.item(), + "variation_loss": variation_loss.item(), + 'truncation(meter)': self.get_truncation()/self.cfg['sc_factor'], + } + if self.models['pose_array'] is not None: + metrics['pose_reg'] = pose_reg.item() + if 'feature_array' in self.models: + metrics['reg_features'] = reg_features.item() + for k in metrics.keys(): + msg += f"{k}: {metrics[k]:.7f}, " + msg += "\n" + logging.info(msg) + + if self._run is not None: + for k in metrics.keys(): + self._run.log_scalar(k,metrics[k],self.global_step) + + if self.global_step % self.cfg['i_mesh'] == 0 and self.global_step > 0: + with torch.no_grad(): + model = self.models['model_fine'] if self.models['model_fine'] is not None else self.models['model'] + mesh = self.extract_mesh(isolevel=0, voxel_size=self.cfg['mesh_resolution']) + self.mesh = copy.deepcopy(mesh) + if mesh is not None: + dir = os.path.join(self.cfg['save_dir'], f'step_{self.global_step:07d}_mesh_normalized_space.obj') + mesh.export(dir) + if self._run is not None: + self._run.add_artifact(dir) + dir = os.path.join(self.cfg['save_dir'], f'step_{self.global_step:07d}_mesh_real_world.obj') + if self.models['pose_array'] is not None: + _,offset = get_optimized_poses_in_real_world(self.poses,self.models['pose_array'],translation=self.cfg['translation'],sc_factor=self.cfg['sc_factor']) + else: + offset = np.eye(4) + mesh = mesh_to_real_world(mesh,offset,translation=self.cfg['translation'],sc_factor=self.cfg['sc_factor']) + mesh.export(dir) + if self._run is not None: + self._run.add_artifact(dir) + + if self.global_step % self.cfg['i_pose'] == 0 and self.global_step > 0: + if self.models['pose_array'] is not None: + optimized_poses,offset = get_optimized_poses_in_real_world(self.poses,self.models['pose_array'],translation=self.cfg['translation'],sc_factor=self.cfg['sc_factor']) + else: + optimized_poses = self.poses + dir = os.path.join(self.cfg['save_dir'], f'step_{self.global_step:07d}_optimized_poses.txt') + np.savetxt(dir,optimized_poses.reshape(-1,4)) + if self._run is not None: + self._run.add_artifact(dir) + + + def train(self): + set_seed(0) + + for iter in range(self.N_iters): + if iter%(self.N_iters//10)==0: + logging.info(f'train progress {iter}/{self.N_iters}') + batch = next(self.data_loader) + self.train_loop(batch.cuda()) + self.global_step += 1 + + + + @torch.no_grad() + def sample_rays_uniform_occupied_voxels(self,rays_d,depths_in_out,lindisp=False,perturb=False, depths=None, N_samples=None): + '''We first connect the discontinuous boxes for each ray and treat it as uniform sample, then we disconnect into correct boxes + @rays_d: (N_ray,3) + @depths_in_out: Padded tensor each has (N_ray,N_intersect,2) tensor, the time travel of each ray + ''' + N_rays = rays_d.shape[0] + N_intersect = depths_in_out.shape[1] + dirs = rays_d/rays_d.norm(dim=-1,keepdim=True) + + ########### Convert the time to Z + z_in_out = depths_in_out.cuda()*torch.abs(dirs[...,2]).reshape(N_rays,1,1).cuda() + + if depths is not None: + depths = depths.reshape(-1,1) + trunc = self.get_truncation() + valid = (depths>=self.cfg['near']*self.cfg['sc_factor']) & (depths<=self.cfg['far']*self.cfg['sc_factor']).expand(-1,N_intersect) + valid = valid & (z_in_out>0).all(dim=-1) #(N_ray, N_intersect) + z_in_out[valid] = torch.clip(z_in_out[valid], + min=torch.zeros_like(z_in_out[valid]), + max=torch.ones_like(z_in_out[valid])*(depths.reshape(-1,1,1).expand(-1,N_intersect,2)[valid]+trunc)) + + + depths_lens = z_in_out[:,:,1]-z_in_out[:,:,0] #(N_ray,N_intersect) + z_vals_continous = sample_rays_uniform(N_samples,torch.zeros((N_rays,1),device=z_in_out.device).reshape(-1,1),depths_lens.sum(dim=-1).reshape(-1,1),lindisp=lindisp,perturb=perturb) #(N_ray,N_sample) + + ############# Option2 mycuda extension + N_samples = z_vals_continous.shape[1] + z_vals = torch.zeros((N_rays,N_samples), dtype=torch.float, device=rays_d.device) + z_vals = common.sampleRaysUniformOccupiedVoxels(z_in_out.contiguous(),z_vals_continous.contiguous(), z_vals) + z_vals = z_vals.float().to(rays_d.device) #(N_ray,N_sample) + + return z_vals,z_vals_continous + + + def render_rays(self,ray_batch,retraw=True,lindisp=False,perturb=False,raw_noise_std=0.,depth=None, get_normals=False, tf=None): + """Volumetric rendering. + Args: + ray_batch: array of shape [batch_size, ...]. All information necessary + for sampling along a ray, including: ray origin, ray direction, min + dist, max dist, and unit-magnitude viewing direction, frame_ids. + model: function. Model for predicting RGB and density at each point + in space. + N_samples: int. Number of different times to sample along each ray. + retraw: bool. If True, include model's raw, unprocessed predictions. + lindisp: bool. If True, sample linearly in inverse depth rather than in depth. + perturb: float, 0 or 1. If non-zero, each ray is sampled at stratified + random points in time. + N_importance: int. Number of additional times to sample along each ray. + These samples are only passed to model_fine. + model_fine: "fine" network with same spec as model. + raw_noise_std: ... + verbose: bool. If True, print more debugging info. + @depth: depth (from depth image) values of the ray (N_ray,1) + @tf: (N_ray,4,4) glcam in ob, normalized space + Returns: + rgb_map: [num_rays, 3]. Estimated RGB color of a ray. Comes from fine model. + disp_map: [num_rays]. Disparity map. 1 / depth. + acc_map: [num_rays]. Accumulated opacity along each ray. Comes from fine model. + raw: [num_rays, num_samples, 4]. Raw predictions from model. + rgb0: See rgb_map. Output for coarse model. + disp0: See disp_map. Output for coarse model. + acc0: See acc_map. Output for coarse model. + z_std: [num_rays]. Standard deviation of distances along ray for each + sample. + """ + N_rays = ray_batch.shape[0] + rays_d = ray_batch[:,self.ray_dir_slice] + rays_o = torch.zeros_like(rays_d) + viewdirs = rays_d/rays_d.norm(dim=-1,keepdim=True) + + frame_ids = ray_batch[:,self.ray_frame_id_slice].long() + + tf = self.c2w_array[frame_ids] + if self.models['pose_array'] is not None: + tf = self.models['pose_array'].get_matrices(frame_ids)@tf + + rays_o_w = transform_pts(rays_o,tf) + viewdirs_w = (tf[:,:3,:3]@viewdirs[:,None].permute(0,2,1))[:,:3,0] + voxel_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor'] + level = int(np.floor(np.log2(2.0/voxel_size))) + near,far,_,depths_in_out = self.octree_m.ray_trace(rays_o_w,viewdirs_w,level=level,debug=0) + z_vals,_ = self.sample_rays_uniform_occupied_voxels(rays_d=viewdirs,depths_in_out=depths_in_out,lindisp=lindisp,perturb=perturb, depths=depth, N_samples=self.cfg['N_samples']) + + if self.cfg['N_samples_around_depth']>0 and depth is not None: #!NOTE only fine when depths are all valid + valid_depth_mask = (depth>=self.cfg['near']*self.cfg['sc_factor']) & (depth<=self.cfg['far']*self.cfg['sc_factor']) + valid_depth_mask = valid_depth_mask.reshape(-1) + trunc = self.get_truncation() + near_depth = depth[valid_depth_mask]-trunc + far_depth = depth[valid_depth_mask]+trunc*self.cfg['neg_trunc_ratio'] + z_vals_around_depth = torch.zeros((N_rays,self.cfg['N_samples_around_depth']), device=ray_batch.device).float() + # if torch.sum(inside_mask)>0: + z_vals_around_depth[valid_depth_mask] = sample_rays_uniform(self.cfg['N_samples_around_depth'],near_depth.reshape(-1,1),far_depth.reshape(-1,1),lindisp=lindisp,perturb=perturb) + invalid_depth_mask = valid_depth_mask==0 + + if invalid_depth_mask.any() and self.cfg['use_octree']: + z_vals_invalid,_ = self.sample_rays_uniform_occupied_voxels(rays_d=viewdirs[invalid_depth_mask],depths_in_out=depths_in_out[invalid_depth_mask],lindisp=lindisp,perturb=perturb, depths=None, N_samples=self.cfg['N_samples_around_depth']) + z_vals_around_depth[invalid_depth_mask] = z_vals_invalid + else: + z_vals_around_depth[invalid_depth_mask] = sample_rays_uniform(self.cfg['N_samples_around_depth'],near[invalid_depth_mask].reshape(-1,1),far[invalid_depth_mask].reshape(-1,1),lindisp=lindisp,perturb=perturb) + + z_vals = torch.cat((z_vals,z_vals_around_depth), dim=-1) + valid_samples = torch.ones(z_vals.shape, dtype=torch.bool, device=ray_batch.device) # During pose update if ray out of box, it becomes invalid + + pts = rays_o[...,None,:] + rays_d[...,None,:] * z_vals[...,:,None] # [N_rays, N_samples, 3] + + deformation = None + raw,normals,valid_samples = self.run_network(pts, viewdirs, frame_ids, tf=tf, valid_samples=valid_samples, get_normals=get_normals) # [N_rays, N_samples, 4] + + rgb_map, weights = self.raw2outputs(raw, z_vals, rays_d, raw_noise_std=raw_noise_std, valid_samples=valid_samples, depth=depth) + + if self.cfg['N_importance'] > 0: + rgb_map_0 = rgb_map + + for iter in range(self.cfg['N_importance_iter']): + z_vals_mid = .5 * (z_vals[...,1:] + z_vals[...,:-1]) + z_samples = sample_pdf(z_vals_mid, weights[...,1:-1], self.cfg['N_importance'], det=(perturb==0.)) + z_samples = z_samples.detach() + valid_samples_importance = torch.ones(z_samples.shape, dtype=torch.bool).to(z_vals.device) + valid_samples_importance[torch.all(valid_samples==0, dim=-1).reshape(-1)] = 0 + + if self.models['model_fine'] is not None and self.models['model_fine']!=self.models['model']: + z_vals, _ = torch.sort(torch.cat([z_vals, z_samples], -1), -1) + pts = rays_o[...,None,:] + rays_d[...,None,:] * z_vals[...,:,None] # [N_rays, N_samples + self.cfg['N_importance'], 3] + raw, normals,valid_samples = self.run_network(pts, viewdirs, frame_ids, tf=tf, valid_samples=valid_samples, get_normals=False) + else: + pts = rays_o[..., None, :] + rays_d[..., None, :] * z_samples[..., :, None] # [N_rays, N_samples + self.cfg['N_importance'], 3] + raw_fine,valid_samples_importance = self.run_network(pts, viewdirs, frame_ids, tf=tf, valid_samples=valid_samples_importance, get_normals=False) + z_vals = torch.cat([z_vals, z_samples], -1) #(N_ray, N_sample) + indices = torch.argsort(z_vals, dim=-1) + z_vals = torch.gather(z_vals,dim=1,index=indices) + raw = torch.gather(torch.cat([raw, raw_fine], dim=1), dim=1, index=indices[...,None].expand(-1,-1,raw.shape[-1])) + valid_samples = torch.cat((valid_samples,valid_samples_importance), dim=-1) + + rgb_map, weights = self.raw2outputs(raw, z_vals, rays_d, raw_noise_std=raw_noise_std,valid_samples=valid_samples) + + ret = {'rgb_map' : rgb_map, 'valid_samples':valid_samples, 'weights':weights, 'z_vals':z_vals} + + if retraw: + ret['raw'] = raw + + if normals is not None: + ret['normals'] = normals + + if deformation is not None: + ret['deformation'] = deformation + + if self.cfg['N_importance'] > 0: + ret['rgb0'] = rgb_map_0 + + return ret + + + def raw2outputs(self, raw, z_vals, rays_d, raw_noise_std=0, valid_samples=None, depth=None): + """Transforms model's predictions to semantically meaningful values. + Args: + raw: [num_rays, num_samples along ray, 4]. Prediction from model. + z_vals: [num_rays, num_samples along ray]. Integration time. + rays_d: [num_rays, 3]. Direction of each ray. + Returns: + rgb_map: [num_rays, 3]. Estimated RGB color of a ray. + disp_map: [num_rays]. Disparity map. Inverse of depth map. + acc_map: [num_rays]. Sum of weights along each ray. + weights: [num_rays, num_samples]. Weights assigned to each sampled color. + depth_map: [num_rays]. Estimated distance to object. + """ + truncation = self.get_truncation() + if depth is not None: + depth = depth.view(-1,1) + + if valid_samples is None: + valid_samples = torch.ones(z_vals.shape, dtype=torch.bool).to(z_vals.device) + + def sdf2weights(sdf): + sdf_from_depth = (depth.view(-1,1)-z_vals)/truncation + weights = torch.sigmoid(sdf_from_depth*self.cfg['sdf_lambda']) * torch.sigmoid(-sdf_from_depth*self.cfg['sdf_lambda']) # This not work well + + invalid = (depth>self.cfg['far']*self.cfg['sc_factor']).reshape(-1) + mask = (z_vals-depth<=truncation*self.cfg['neg_trunc_ratio']) & (z_vals-depth>=-truncation) + weights[~invalid] = weights[~invalid] * mask[~invalid] + weights[invalid] = 0 + + return weights / (weights.sum(dim=-1,keepdim=True) + 1e-10) + + rgb = torch.sigmoid(raw[...,:3]) # [N_rays, N_samples, 3] + weights = sdf2weights(raw[..., 3]) + + weights[valid_samples==0] = 0 + rgb_map = torch.sum(weights[...,None] * rgb, -2) # [N_rays, 3] + + return rgb_map, weights + + + def render(self, rays, depth=None,lindisp=False,perturb=False,raw_noise_std=0.0, get_normals=False): + """Render rays + Args: + H: int. Height of image in pixels. + W: int. Width of image in pixels. + K: float. Focal length of pinhole camera. + chunk: int. Maximum number of rays to process simultaneously. Used to + control maximum memory usage. Does not affect final results. + rays: array of shape [batch_size, 6]. Ray origin and direction for + each example in batch. + ndc: bool. If True, represent ray origin, direction in NDC coordinates. Only true for llff data + near: float or array of shape [batch_size]. Nearest distance for a ray. + far: float or array of shape [batch_size]. Farthest distance for a ray. + @depth: depth values (N_ray,1) + Returns: + rgb_map: [batch_size, 3]. Predicted RGB values for rays. + disp_map: [batch_size]. Disparity map. Inverse of depth. + acc_map: [batch_size]. Accumulated opacity (alpha) along a ray. + extras: dict with everything. + """ + all_ret = self.batchify_rays(rays,depth=depth,lindisp=lindisp,perturb=perturb,raw_noise_std=raw_noise_std, get_normals=get_normals) + + k_extract = ['rgb_map'] + ret_list = [all_ret[k] for k in k_extract] + ret_dict = {k : all_ret[k] for k in all_ret if k not in k_extract} + return ret_list + [ret_dict] + + + + def batchify_rays(self,rays_flat, depth=None,lindisp=False,perturb=False,raw_noise_std=0.0, get_normals=False): + """Render rays in smaller minibatches to avoid OOM. + """ + all_ret = {} + chunk = self.cfg['chunk'] + for i in range(0, rays_flat.shape[0], chunk): + if depth is not None: + cur_depth = depth[i:i+chunk] + else: + cur_depth = None + ret = self.render_rays(rays_flat[i:i+chunk],depth=cur_depth,lindisp=lindisp,perturb=perturb,raw_noise_std=raw_noise_std, get_normals=get_normals) + for k in ret: + if ret[k] is None: + continue + if k not in all_ret: + all_ret[k] = [] + all_ret[k].append(ret[k]) + + all_ret = {k : torch.cat(all_ret[k], 0) for k in all_ret} + return all_ret + + + def run_network(self, inputs, viewdirs, frame_ids=None, tf=None, latent_code=None, valid_samples=None, get_normals=False): + """Prepares inputs and applies network 'fn'. + @inputs: (N_ray,N_sample,3) sampled points on rays in GL camera's frame + @viewdirs: (N_ray,3) unit length vector in camera frame, z-axis backward + @frame_ids: (N_ray) + @tf: (N_ray,4,4) + @latent_code: (N_ray, D) + """ + N_ray,N_sample = inputs.shape[:2] + + if valid_samples is None: + valid_samples = torch.ones((N_ray,N_sample), dtype=torch.bool, device=inputs.device) + + inputs_flat = torch.reshape(inputs, [-1, inputs.shape[-1]]) + + tf_flat = tf[:,None].expand(-1,N_sample,-1,-1).reshape(-1,4,4) + inputs_flat = transform_pts(inputs_flat, tf_flat) + + valid_samples = valid_samples.bool() & (torch.abs(inputs_flat)<=1).all(dim=-1).view(N_ray,N_sample).bool() + + embedded = torch.zeros((inputs_flat.shape[0],self.models['embed_fn'].out_dim), device=inputs_flat.device) + if valid_samples is None: + valid_samples = torch.ones((N_ray,N_sample), dtype=torch.bool, device=inputs_flat.device) + + if get_normals: + if inputs_flat.requires_grad==False: + inputs_flat.requires_grad = True + + with torch.cuda.amp.autocast(enabled=self.cfg['amp']): + if self.cfg['i_embed'] in [3]: + embedded[valid_samples.reshape(-1)], valid_samples_embed = self.models['embed_fn'](inputs_flat[valid_samples.reshape(-1)]) + valid_samples = valid_samples.reshape(-1) + prev_valid_ids = valid_samples.nonzero().reshape(-1) + bad_ids = prev_valid_ids[valid_samples_embed==0] + new_valid_ids = torch.ones((N_ray*N_sample),device=inputs.device).bool() + new_valid_ids[bad_ids] = 0 + valid_samples = valid_samples & new_valid_ids + valid_samples = valid_samples.reshape(N_ray,N_sample).bool() + else: + embedded[valid_samples.reshape(-1)] = self.models['embed_fn'](inputs_flat[valid_samples.reshape(-1)]).to(embedded.dtype) + embedded = embedded.float() + + # Add latent code + if self.models['feature_array'] is not None: + if latent_code is None: + frame_features = self.models['feature_array'](frame_ids) + D = frame_features.shape[-1] + frame_features = frame_features[:,None].expand(-1,N_sample,-1).reshape(-1,D) + else: + D = latent_code.shape[-1] + frame_features = latent_code[:,None].expand(N_ray,N_sample,latent_code.shape[-1]).reshape(-1,D) + embedded = torch.cat([embedded, frame_features], -1) + + # Add view directions + if self.models['embeddirs_fn'] is not None: + input_dirs = (tf[..., :3, :3]@viewdirs[...,None])[...,0] #(N_ray,3) + embedded_dirs = self.models['embeddirs_fn'](input_dirs) + tmp = embedded_dirs.shape[1:] + embedded_dirs_flat = embedded_dirs[:,None].expand(-1,N_sample,*tmp).reshape(-1,*tmp) + embedded = torch.cat([embedded, embedded_dirs_flat], -1) + + outputs_flat = [] + with torch.cuda.amp.autocast(enabled=self.cfg['amp']): + chunk = self.cfg['netchunk'] + for i in range(0,embedded.shape[0],chunk): + out = self.models['model'](embedded[i:i+chunk]) + outputs_flat.append(out) + outputs_flat = torch.cat(outputs_flat, dim=0).float() + outputs = torch.reshape(outputs_flat, list(inputs.shape[:-1]) + [outputs_flat.shape[-1]]).float() + + normals = None + if get_normals: + sdf = outputs[...,-1] + d_output = torch.zeros(sdf.shape, device=sdf.device) + normals = torch.autograd.grad(outputs=sdf,inputs=inputs_flat,grad_outputs=d_output,create_graph=False,retain_graph=True,only_inputs=True,allow_unused=True)[0] + normals = normals.reshape(N_ray,N_sample,3) + + return outputs,normals,valid_samples + + + def run_network_density(self, inputs, get_normals=False): + """Directly query the network w/o pose transformations or deformations (inputs are already in normalized [-1,1]); Particularly used for mesh extraction + @inputs: (N,3) sampled points on rays in GL camera's frame + """ + inputs_flat = torch.reshape(inputs, [-1, inputs.shape[-1]]) + + inputs_flat = torch.clip(inputs_flat,-1,1) + valid_samples = torch.ones((len(inputs_flat)),device=inputs.device).bool() + + if not inputs_flat.requires_grad: + inputs_flat.requires_grad = True + + with torch.cuda.amp.autocast(enabled=self.cfg['amp']): + if self.cfg['i_embed'] in [3]: + embedded, valid_samples_embed = self.models['embed_fn'](inputs_flat) + valid_samples = valid_samples.reshape(-1) + prev_valid_ids = valid_samples.nonzero().reshape(-1) + bad_ids = prev_valid_ids[valid_samples_embed==0] + new_valid_ids = torch.ones((len(inputs_flat)),device=inputs.device).bool() + new_valid_ids[bad_ids] = 0 + valid_samples = valid_samples & new_valid_ids + else: + embedded = self.models['embed_fn'](inputs_flat) + embedded = embedded.float() + input_ch = embedded.shape[-1] + + outputs_flat = [] + with torch.cuda.amp.autocast(enabled=self.cfg['amp']): + chunk = self.cfg['netchunk'] + for i in range(0,embedded.shape[0],chunk): + alpha = self.models['model'].forward_sdf(embedded[i:i+chunk]) #(N,1) + outputs_flat.append(alpha.reshape(-1,1)) + outputs_flat = torch.cat(outputs_flat,dim=0).float() + outputs = torch.reshape(outputs_flat, list(inputs.shape[:-1]) + [outputs_flat.shape[-1]]) + + if get_normals: + d_output = torch.ones_like(outputs, requires_grad=False, device=outputs.device) + normal = torch.autograd.grad(outputs=outputs,inputs=inputs_flat,grad_outputs=d_output,create_graph=False,retain_graph=True,only_inputs=True,allow_unused=True)[0] + outputs = torch.cat((outputs, normal), dim=-1) + + return outputs,valid_samples + + + @torch.no_grad() + def extract_mesh(self, level=None, voxel_size=0.003, isolevel=0.0, return_sigma=False): + voxel_size *= self.cfg['sc_factor'] # in "network space" + + bounds = np.array(self.cfg['bounding_box']).reshape(2,3) + x_min, x_max = bounds[0,0], bounds[1,0] + y_min, y_max = bounds[0,1], bounds[1,1] + z_min, z_max = bounds[0,2], bounds[1,2] + tx = np.arange(x_min+0.5*voxel_size, x_max, voxel_size) + ty = np.arange(y_min+0.5*voxel_size, y_max, voxel_size) + tz = np.arange(z_min+0.5*voxel_size, z_max, voxel_size) + N = len(tx) + query_pts = torch.tensor(np.stack(np.meshgrid(tx, ty, tz, indexing='ij'), -1).astype(np.float32).reshape(-1,3)).float().cuda() + + if self.octree_m is not None: + vox_size = self.cfg['octree_raytracing_voxel_size']*self.cfg['sc_factor'] + level = int(np.floor(np.log2(2.0/vox_size))) + center_ids = self.octree_m.get_center_ids(query_pts, level) + valid = center_ids>=0 + else: + valid = torch.ones(len(query_pts), dtype=bool).cuda() + + logging.info(f'query_pts:{query_pts.shape}, valid:{valid.sum()}') + flat = query_pts[valid] + + sigma = [] + chunk = self.cfg['netchunk'] + for i in range(0,flat.shape[0],chunk): + inputs = flat[i:i+chunk] + with torch.no_grad(): + outputs,valid_samples = self.run_network_density(inputs=inputs) + sigma.append(outputs) + sigma = torch.cat(sigma, dim=0) + sigma_ = torch.ones((N**3)).float().cuda() + sigma_[valid] = sigma.reshape(-1) + sigma = sigma_.reshape(N,N,N).data.cpu().numpy() + + logging.info('Running Marching Cubes') + from skimage import measure + try: + vertices, triangles, normals, values = measure.marching_cubes(sigma, isolevel) + except Exception as e: + logging.info(f"ERROR Marching Cubes {e}") + return None + + logging.info(f'done V:{vertices.shape}, F:{triangles.shape}') + + voxel_size_ndc = np.array([tx[-1] - tx[0], ty[-1] - ty[0], tz[-1] - tz[0]]) / np.array([[tx.shape[0] - 1, ty.shape[0] - 1, tz.shape[0] - 1]]) + offset = np.array([tx[0], ty[0], tz[0]]) + vertices[:, :3] = voxel_size_ndc.reshape(1,3) * vertices[:, :3] + offset.reshape(1,3) + + mesh = trimesh.Trimesh(vertices, triangles, process=False) + + if return_sigma: + return mesh,sigma,query_pts + + return mesh + + + def mesh_texture_from_train_images(self, mesh, rgbs_raw, tex_res=1024): + ''' + @rgbs_raw: raw complete image that was trained on, no black holes + @mesh: in normalized space + ''' + assert len(self.images)==len(rgbs_raw) + + frame_ids = torch.arange(len(self.images)).long().cuda() + tf = self.c2w_array[frame_ids] + if self.models['pose_array'] is not None: + tf = self.models['pose_array'].get_matrices(frame_ids)@tf + tf = tf.data.cpu().numpy() + from offscreen_renderer import ModelRendererOffscreen + + tex_image = torch.zeros((tex_res,tex_res,3)).cuda().float() + weight_tex_image = torch.zeros(tex_image.shape[:-1]).cuda().float() + mesh.merge_vertices() + mesh.remove_duplicate_faces() + mesh = mesh.unwrap() + H,W = tex_image.shape[:2] + uvs_tex = (mesh.visual.uv*np.array([W-1,H-1]).reshape(1,2)) #(n_V,2) + + renderer = ModelRendererOffscreen(cam_K=self.K, H=self.H, W=self.W, zfar=self.cfg['far']*self.cfg['sc_factor']) + + vertices_cuda = torch.from_numpy(mesh.vertices).float().cuda() + faces_cuda = torch.from_numpy(mesh.faces).long().cuda() + face_vertices = torch.zeros((len(faces_cuda),3,3)) + for i in range(3): + face_vertices[:,i] = vertices_cuda[faces_cuda[:,i]] + + all_tri_list= {key: [] for key in range(mesh.triangles.shape[0])} + for i in range(len(rgbs_raw)): + cvcam_in_ob = tf[i]@np.linalg.inv(glcam_in_cvcam) + _, render_depth = renderer.render(mesh=mesh, ob_in_cvcam=np.linalg.inv(cvcam_in_ob)) + xyz_map = depth2xyzmap(render_depth, self.K) + mask = self.masks[i].reshape(self.H,self.W).astype(bool) + valid = (render_depth.reshape(self.H,self.W)>=0.1*self.cfg['sc_factor']) & (mask) + pts = xyz_map[valid].reshape(-1,3) + pts = transform_pts(pts, cvcam_in_ob) + ray_colors = rgbs_raw[i][valid].reshape(-1,3) + locations, distance, index_tri = trimesh.proximity.closest_point(mesh, pts) + normals = mesh.face_normals[index_tri] + for ind_tri, each_tri in enumerate(index_tri): + rays_o = np.zeros(3) + pts = transform_pts(rays_o, cvcam_in_ob) #transform to world space + rays_d = locations[ind_tri]-pts + rays_d /= np.linalg.norm(rays_d) + dot_product = np.dot(-rays_d, normals[ind_tri]) + angle_radians = np.arccos(dot_product) + angle_degrees = np.degrees(angle_radians) + all_tri_list[each_tri].extend([[i,angle_degrees]]) + + _CHOOSE_TOP_N = 4 + all_triangles_dict={} + for k,v in all_tri_list.items(): + if(v): + v.sort(key=lambda x: x[1]) + tep = [i[0] for i in v[:_CHOOSE_TOP_N]] + all_triangles_dict[k]=set(list(tep)) + + + all_tri_visited= {key: 0 for key in range(mesh.triangles.shape[0])} + + logging.info(f"Texture: Texture map computation") + for i in range(len(rgbs_raw)): + print(f'project train_images {i}/{len(rgbs_raw)}') + + cvcam_in_ob = tf[i]@np.linalg.inv(glcam_in_cvcam) + _, render_depth = renderer.render(mesh=mesh, ob_in_cvcam=np.linalg.inv(cvcam_in_ob)) + xyz_map = depth2xyzmap(render_depth, self.K) + mask = self.masks[i].reshape(self.H,self.W).astype(bool) + valid = (render_depth.reshape(self.H,self.W)>=0.1*self.cfg['sc_factor']) & (mask) + pts = xyz_map[valid].reshape(-1,3) + pts = transform_pts(pts, cvcam_in_ob) + ray_colors = rgbs_raw[i][valid].reshape(-1,3) + locations, distance, index_tri = trimesh.proximity.closest_point(mesh, pts) + normals = mesh.face_normals[index_tri] + rays_o = np.zeros((len(normals),3)) + rays_o = transform_pts(rays_o,cvcam_in_ob) + rays_d = locations-rays_o + rays_d /= np.linalg.norm(rays_d,axis=-1).reshape(-1,1) + dots = (normals*(-rays_d)).sum(axis=-1) + ray_weights = np.ones((len(rays_o))) + bool_weights=torch.zeros(len(locations), dtype=torch.bool, device='cuda') + count = 0 + for jj, trtind__ in enumerate(index_tri): + if(i in all_triangles_dict[trtind__] ): + bool_weights[jj]=1 + all_tri_visited[trtind__]=1 + count +=1 + + uvs = torch.zeros((len(locations),2)).cuda().float() + common.rayColorToTextureImageCUDA(torch.from_numpy(mesh.faces).cuda().long(), torch.from_numpy(mesh.vertices).cuda().float(), torch.from_numpy(locations).cuda().float(), torch.from_numpy(index_tri).cuda().long(), torch.from_numpy(uvs_tex).cuda().float(), uvs) + uvs = torch.round(uvs).long() + uvs_flat = uvs[:,1]*(W-1) + uvs[:,0] + uvs_flat_unique, inverse_ids, cnts = torch.unique(uvs_flat, return_counts=True, return_inverse=True) + perm = torch.arange(inverse_ids.size(0)).cuda() + inverse_ids, perm = inverse_ids.flip([0]), perm.flip([0]) + unique_ids = inverse_ids.new_empty(uvs_flat_unique.size(0)).scatter_(0, inverse_ids, perm) + uvs_unique = torch.stack((uvs_flat_unique%(W-1), uvs_flat_unique//(W-1)), dim=-1).reshape(-1,2) + cur_weights= bool_weights[unique_ids].cuda().float() + tex_image[uvs_unique[:,1],uvs_unique[:,0]] += torch.from_numpy(ray_colors).cuda().float()[unique_ids]*cur_weights.reshape(-1,1) + weight_tex_image[uvs_unique[:,1], uvs_unique[:,0]] += cur_weights + + tex_image = tex_image/weight_tex_image[...,None] + tex_image = tex_image.data.cpu().numpy() + tex_image = np.clip(tex_image,0,255).astype(np.uint8) + tex_image = tex_image[::-1].copy() + new_texture = texture_map_interpolation(tex_image) + + mesh.visual = trimesh.visual.texture.TextureVisuals(uv=mesh.visual.uv,image=Image.fromarray(new_texture)) + return mesh diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/run_nerf.py b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/run_nerf.py new file mode 100644 index 0000000000000000000000000000000000000000..8c6a1310d5c7e2e22744b13b33aeccec8c12deb3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/run_nerf.py @@ -0,0 +1,115 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from nerf_runner import * +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../') +from datareader import * +from bundlesdf.tool import * +import yaml,argparse + + +def run_neural_object_field(cfg, K, rgbs, depths, masks, cam_in_obs, debug=0, save_dir='/path/to/debug/foundationpose_bundlesdf'): + rgbs = np.asarray(rgbs) + depths = np.asarray(depths) + masks = np.asarray(masks) + cam_in_obs = np.asarray(cam_in_obs) + glcam_in_obs = cam_in_obs@glcam_in_cvcam + + cfg['save_dir'] = save_dir + os.makedirs(save_dir, exist_ok=True) + + for i,rgb in enumerate(rgbs): + imageio.imwrite(f'{save_dir}/rgb_{i:07d}.png', rgb) + + sc_factor,translation,pcd_real_scale, pcd_normalized = compute_scene_bounds(None,glcam_in_obs, K, use_mask=True,base_dir=save_dir,rgbs=rgbs,depths=depths,masks=masks, eps=cfg['dbscan_eps'], min_samples=cfg['dbscan_eps_min_samples']) + cfg['sc_factor'] = sc_factor + cfg['translation'] = translation + + o3d.io.write_point_cloud(f'{save_dir}/pcd_normalized.ply', pcd_normalized) + + rgbs_, depths_, masks_, normal_maps,poses = preprocess_data(rgbs, depths, masks,normal_maps=None,poses=glcam_in_obs,sc_factor=cfg['sc_factor'],translation=cfg['translation']) + + nerf = NerfRunner(cfg, rgbs_, depths_, masks_, normal_maps=None, poses=poses, K=K, occ_masks=None, build_octree_pcd=pcd_normalized) + nerf.train() + + mesh = nerf.extract_mesh(isolevel=0,voxel_size=cfg['mesh_resolution']) + mesh = nerf.mesh_texture_from_train_images(mesh, rgbs_raw=rgbs, tex_res=1028) + optimized_cvcam_in_obs,offset = get_optimized_poses_in_real_world(poses,nerf.models['pose_array'],cfg['sc_factor'],cfg['translation']) + mesh = mesh_to_real_world(mesh, pose_offset=offset, translation=nerf.cfg['translation'], sc_factor=nerf.cfg['sc_factor']) + return mesh + + +def run_one_ob(base_dir, cfg, use_refined_mask=False): + save_dir = f'{base_dir}/nerf' + os.system(f'rm -rf {save_dir} && mkdir -p {save_dir}') + with open(f'{base_dir}/select_frames.yml','r') as ff: + info = yaml.safe_load(ff) + rgbs = [] + depths = [] + masks = [] + cam_in_obs = [] + color_files = sorted(glob.glob(f'{base_dir}/rgb/*.png')) + K = np.loadtxt(f'{base_dir}/K.txt') + for i,color_file in enumerate(color_files): + rgb = imageio.imread(color_file) + depth = cv2.imread(color_file.replace('rgb','depth_enhanced'), -1)/1e3 + if use_refined_mask: + mask = cv2.imread(color_file.replace('rgb','mask_refined'), -1) + else: + mask = cv2.imread(color_file.replace('rgb','mask'), -1) + cam_in_ob = np.loadtxt(color_file.replace('rgb','cam_in_ob').replace('.png','.txt')).reshape(4,4) + rgbs.append(rgb) + depths.append(depth) + masks.append(mask) + cam_in_obs.append(cam_in_ob) + + mesh = run_neural_object_field(cfg, K, rgbs, depths, masks, cam_in_obs, save_dir=save_dir, debug=0) + return mesh + + +def run_ycbv(): + ob_ids = np.arange(1,22) + code_dir = os.path.dirname(os.path.realpath(__file__)) + with open(f'{code_dir}/config_ycbv.yml','r') as ff: + cfg = yaml.safe_load(ff) + + for ob_id in ob_ids: + base_dir = f'{args.ref_view_dir}/ob_{ob_id:07d}' + mesh = run_one_ob(base_dir=base_dir, cfg=cfg) + out_file = f'{base_dir}/model/model.obj' + os.makedirs(os.path.dirname(out_file), exist_ok=True) + mesh.export(out_file) + + +def run_linemod(): + ob_ids = np.setdiff1d(np.arange(1,16), np.array([7,3])).tolist() + code_dir = os.path.dirname(os.path.realpath(__file__)) + with open(f'{code_dir}/config_linemod.yml','r') as ff: + cfg = yaml.safe_load(ff) + for ob_id in ob_ids: + base_dir = f'{args.ref_view_dir}/ob_{ob_id:07d}' + mesh = run_one_ob(base_dir=base_dir, cfg=cfg, use_refined_mask=True) + out_file = f'{base_dir}/model/model.obj' + os.makedirs(os.path.dirname(out_file), exist_ok=True) + mesh.export(out_file) + logging.info(f"saved to {out_file}") + + +if __name__=="__main__": + parser = argparse.ArgumentParser() + code_dir = os.path.dirname(os.path.realpath(__file__)) + parser.add_argument('--ref_view_dir', type=str, default=f'/path/to/DATASET/YCB_Video/bowen_addon/ref_views_16') + parser.add_argument('--dataset', type=str, default=f'ycbv', help='one of [ycbv/linemod]') + args = parser.parse_args() + + if args.dataset=='ycbv': + run_ycbv() + else: + run_linemod() diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/tool.py b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/tool.py new file mode 100644 index 0000000000000000000000000000000000000000..d52bb9d57a175edf54ed46647d37921107fb2953 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/tool.py @@ -0,0 +1,132 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import joblib,json,gzip,pickle +from sklearn.cluster import DBSCAN +import shutil,re,imageio,pdb,os,sys +from Utils import * +import pandas as pd + + +def find_biggest_cluster(pts, eps=0.06, min_samples=1): + dbscan = DBSCAN(eps=eps,min_samples=min_samples,n_jobs=-1) + dbscan.fit(pts) + ids, cnts = np.unique(dbscan.labels_, return_counts=True) + best_id = ids[cnts.argsort()[-1]] + keep_mask = dbscan.labels_==best_id + pts_cluster = pts[keep_mask] + return pts_cluster, keep_mask + + +def compute_translation_scales(pts,max_dim=2,cluster=True, eps=0.06, min_samples=1): + if cluster: + pts, keep_mask = find_biggest_cluster(pts, eps, min_samples) + else: + keep_mask = np.ones((len(pts)), dtype=bool) + max_xyz = pts.max(axis=0) + min_xyz = pts.min(axis=0) + center = (max_xyz+min_xyz)/2 + sc_factor = max_dim/(max_xyz-min_xyz).max() #Normalize to [-1,1] + sc_factor *= 0.9 + translation_cvcam = -center + return translation_cvcam, sc_factor, keep_mask + + +def compute_scene_bounds_worker(color_file,K,glcam_in_world,use_mask,rgb=None,depth=None,mask=None): + if rgb is None: + depth_file = color_file.replace('images','depth_filtered') + mask_file = color_file.replace('images','masks') + rgb = np.array(Image.open(color_file))[...,:3] + depth = cv2.imread(depth_file,-1)/1e3 + xyz_map = depth2xyzmap(depth,K) + valid = depth>=0.1 + if use_mask: + if mask is None: + mask = cv2.imread(mask_file,-1) + valid = valid & (mask>0) + pts = xyz_map[valid].reshape(-1,3) + if len(pts)==0: + return None + colors = rgb[valid].reshape(-1,3) + pcd = toOpen3dCloud(pts,colors) + pcd = pcd.voxel_down_sample(0.01) + pcd, ind = pcd.remove_statistical_outlier(nb_neighbors=30,std_ratio=2.0) + cam_in_world = glcam_in_world@glcam_in_cvcam + pcd.transform(cam_in_world) + return np.asarray(pcd.points).copy(), np.asarray(pcd.colors).copy() + + +def compute_scene_bounds(color_files,glcam_in_worlds,K,use_mask=True,base_dir=None,rgbs=None,depths=None,masks=None,cluster=True, translation_cvcam=None, sc_factor=None, eps=0.06, min_samples=1): + assert color_files is None or rgbs is None + + if base_dir is None: + base_dir = os.path.dirname(color_files[0])+'/../' + + args = [] + if rgbs is not None: + for i in range(len(rgbs)): + args.append((None,K,glcam_in_worlds[i],use_mask,rgbs[i],depths[i],masks[i])) + else: + for i in range(len(color_files)): + args.append((color_files[i],K,glcam_in_worlds[i],use_mask)) + + logging.info(f"compute_scene_bounds_worker start") + ret = joblib.Parallel(n_jobs=10, prefer="threads")(joblib.delayed(compute_scene_bounds_worker)(*arg) for arg in args) + logging.info(f"compute_scene_bounds_worker done") + + pcd_all = None + for r in ret: + if r is None: + continue + if pcd_all is None: + pcd_all = toOpen3dCloud(r[0],r[1]) + else: + pcd_all += toOpen3dCloud(r[0],r[1]) + pcd = pcd_all.voxel_down_sample(eps/5) + + logging.info(f"merge pcd") + + o3d.io.write_point_cloud(f'{base_dir}/naive_fusion.ply',pcd) + pts = np.asarray(pcd.points).copy() + + def make_tf(translation_cvcam, sc_factor): + tf = np.eye(4) + tf[:3,3] = translation_cvcam + tf1 = np.eye(4) + tf1[:3,:3] *= sc_factor + tf = tf1@tf + return tf + + if translation_cvcam is None: + translation_cvcam, sc_factor, keep_mask = compute_translation_scales(pts, cluster=cluster, eps=eps, min_samples=min_samples) + tf = make_tf(translation_cvcam, sc_factor) + else: + tf = make_tf(translation_cvcam, sc_factor) + tmp = copy.deepcopy(pcd) + tmp.transform(tf) + tmp_pts = np.asarray(tmp.points) + keep_mask = (np.abs(tmp_pts)<1).all(axis=-1) + + logging.info(f"compute_translation_scales done") + + pcd = toOpen3dCloud(pts[keep_mask],np.asarray(pcd.colors)[keep_mask]) + o3d.io.write_point_cloud(f"{base_dir}/naive_fusion_biggest_cluster.ply",pcd) + pcd_real_scale = copy.deepcopy(pcd) + print(f'translation_cvcam={translation_cvcam}, sc_factor={sc_factor}') + with open(f'{base_dir}/normalization.yml','w') as ff: + tmp = { + 'translation_cvcam':translation_cvcam.tolist(), + 'sc_factor':float(sc_factor), + } + yaml.dump(tmp,ff) + + pcd.transform(tf) + return sc_factor, translation_cvcam, pcd_real_scale, pcd + + diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/datareader.py b/OVOW/engine/oneposeviagen/fpose/fpose/datareader.py new file mode 100644 index 0000000000000000000000000000000000000000..4a0a1dcc0b2daec87beb885f5252370ce0fac917 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/datareader.py @@ -0,0 +1,613 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from fpose.Utils import * +import json,os,sys + + +BOP_LIST = ['lmo','tless','ycbv','hb','tudl','icbin','itodd'] +BOP_DIR = os.getenv('BOP_DIR') + +def get_bop_reader(video_dir, zfar=np.inf): + if 'ycbv' in video_dir or 'YCB' in video_dir: + return YcbVideoReader(video_dir, zfar=zfar) + if 'lmo' in video_dir or 'LINEMOD-O' in video_dir: + return LinemodOcclusionReader(video_dir, zfar=zfar) + if 'tless' in video_dir or 'TLESS' in video_dir: + return TlessReader(video_dir, zfar=zfar) + if 'hb' in video_dir: + return HomebrewedReader(video_dir, zfar=zfar) + if 'tudl' in video_dir: + return TudlReader(video_dir, zfar=zfar) + if 'icbin' in video_dir: + return IcbinReader(video_dir, zfar=zfar) + if 'itodd' in video_dir: + return ItoddReader(video_dir, zfar=zfar) + else: + raise RuntimeError + + +def get_bop_video_dirs(dataset): + if dataset=='ycbv': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/ycbv/test/*')) + elif dataset=='lmo': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/lmo/lmo_test_bop19/test/*')) + elif dataset=='tless': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/tless/tless_test_primesense_bop19/test_primesense/*')) + elif dataset=='hb': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/hb/hb_test_primesense_bop19/test_primesense/*')) + elif dataset=='tudl': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/tudl/tudl_test_bop19/test/*')) + elif dataset=='icbin': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/icbin/icbin_test_bop19/test/*')) + elif dataset=='itodd': + video_dirs = sorted(glob.glob(f'{BOP_DIR}/itodd/itodd_test_bop19/test/*')) + else: + raise RuntimeError + return video_dirs + + + +class YcbineoatReader: + def __init__(self,video_dir, downscale=1, shorter_side=None, zfar=np.inf): + self.video_dir = video_dir + self.downscale = downscale + self.zfar = zfar + self.color_files = sorted(glob.glob(f"{self.video_dir}/rgb/*.png")) + self.K = np.loadtxt(f'{video_dir}/cam_K.txt').reshape(3,3) + self.id_strs = [] + for color_file in self.color_files: + id_str = os.path.basename(color_file).replace('.png','') + self.id_strs.append(id_str) + self.H,self.W = cv2.imread(self.color_files[0]).shape[:2] + + if shorter_side is not None: + self.downscale = shorter_side/min(self.H, self.W) + + self.H = int(self.H*self.downscale) + self.W = int(self.W*self.downscale) + self.K[:2] *= self.downscale + + self.gt_pose_files = sorted(glob.glob(f'{self.video_dir}/annotated_poses/*')) + + self.videoname_to_object = { + 'bleach0': "021_bleach_cleanser", + 'bleach_hard_00_03_chaitanya': "021_bleach_cleanser", + 'cracker_box_reorient': '003_cracker_box', + 'cracker_box_yalehand0': '003_cracker_box', + 'mustard0': '006_mustard_bottle', + 'mustard_easy_00_02': '006_mustard_bottle', + 'sugar_box1': '004_sugar_box', + 'sugar_box_yalehand0': '004_sugar_box', + 'tomato_soup_can_yalehand0': '005_tomato_soup_can', + } + + + def get_video_name(self): + return self.video_dir.split('/')[-1] + + def __len__(self): + return len(self.color_files) + + def get_gt_pose(self,i): + try: + pose = np.loadtxt(self.gt_pose_files[i]).reshape(4,4) + return pose + except: + logging.info("GT pose not found, return None") + return None + + + def get_color(self,i): + color = imageio.imread(self.color_files[i])[...,:3] + color = cv2.resize(color, (self.W,self.H), interpolation=cv2.INTER_NEAREST) + return color + + def get_mask(self,i): + mask = cv2.imread(self.color_files[i].replace('rgb','masks'),-1) + if len(mask.shape)==3: + for c in range(3): + if mask[...,c].sum()>0: + mask = mask[...,c] + break + mask = cv2.resize(mask, (self.W,self.H), interpolation=cv2.INTER_NEAREST).astype(bool).astype(np.uint8) + return mask + + def get_depth(self,i): + depth = cv2.imread(self.color_files[i].replace('rgb','depth'),-1)/1e3 + depth = cv2.resize(depth, (self.W,self.H), interpolation=cv2.INTER_NEAREST) + depth[(depth<0.001) | (depth>=self.zfar)] = 0 + return depth + + + def get_xyz_map(self,i): + depth = self.get_depth(i) + xyz_map = depth2xyzmap(depth, self.K) + return xyz_map + + def get_occ_mask(self,i): + hand_mask_file = self.color_files[i].replace('rgb','masks_hand') + occ_mask = np.zeros((self.H,self.W), dtype=bool) + if os.path.exists(hand_mask_file): + occ_mask = occ_mask | (cv2.imread(hand_mask_file,-1)>0) + + right_hand_mask_file = self.color_files[i].replace('rgb','masks_hand_right') + if os.path.exists(right_hand_mask_file): + occ_mask = occ_mask | (cv2.imread(right_hand_mask_file,-1)>0) + + occ_mask = cv2.resize(occ_mask, (self.W,self.H), interpolation=cv2.INTER_NEAREST) + + return occ_mask.astype(np.uint8) + + def get_gt_mesh(self): + ob_name = self.videoname_to_object[self.get_video_name()] + YCB_VIDEO_DIR = os.getenv('YCB_VIDEO_DIR') + mesh = trimesh.load(f'{YCB_VIDEO_DIR}/models/{ob_name}/textured_simple.obj') + return mesh + + +class BopBaseReader: + def __init__(self, base_dir, zfar=np.inf, resize=1): + self.base_dir = base_dir + self.resize = resize + self.dataset_name = None + self.color_files = sorted(glob.glob(f"{self.base_dir}/rgb/*")) + if len(self.color_files)==0: + self.color_files = sorted(glob.glob(f"{self.base_dir}/gray/*")) + self.zfar = zfar + + self.K_table = {} + with open(f'{self.base_dir}/scene_camera.json','r') as ff: + info = json.load(ff) + for k in info: + self.K_table[f'{int(k):06d}'] = np.array(info[k]['cam_K']).reshape(3,3) + self.bop_depth_scale = info[k]['depth_scale'] + + if os.path.exists(f'{self.base_dir}/scene_gt.json'): + with open(f'{self.base_dir}/scene_gt.json','r') as ff: + self.scene_gt = json.load(ff) + self.scene_gt = copy.deepcopy(self.scene_gt) # Release file handle to be pickle-able by joblib + assert len(self.scene_gt)==len(self.color_files) + else: + self.scene_gt = None + + self.make_id_strs() + + + def make_scene_ob_ids_dict(self): + with open(f'{BOP_DIR}/{self.dataset_name}/test_targets_bop19.json','r') as ff: + self.scene_ob_ids_dict = {} + data = json.load(ff) + for d in data: + if d['scene_id']==self.get_video_id(): + id_str = f"{d['im_id']:06d}" + if id_str not in self.scene_ob_ids_dict: + self.scene_ob_ids_dict[id_str] = [] + self.scene_ob_ids_dict[id_str] += [d['obj_id']]*d['inst_count'] + + + def get_K(self, i_frame): + K = self.K_table[self.id_strs[i_frame]] + if self.resize!=1: + K[:2,:2] *= self.resize + return K + + + def get_video_dir(self): + video_id = int(self.base_dir.rstrip('/').split('/')[-1]) + return video_id + + def make_id_strs(self): + self.id_strs = [] + for i in range(len(self.color_files)): + name = os.path.basename(self.color_files[i]).split('.')[0] + self.id_strs.append(name) + + + def get_instance_ids_in_image(self, i_frame:int): + ob_ids = [] + if self.scene_gt is not None: + name = int(os.path.basename(self.color_files[i_frame]).split('.')[0]) + for k in self.scene_gt[str(name)]: + ob_ids.append(k['obj_id']) + elif self.scene_ob_ids_dict is not None: + return np.array(self.scene_ob_ids_dict[self.id_strs[i_frame]]) + else: + mask_dir = os.path.dirname(self.color_files[0]).replace('rgb','mask_visib') + id_str = self.id_strs[i_frame] + mask_files = sorted(glob.glob(f'{mask_dir}/{id_str}_*.png')) + ob_ids = [] + for mask_file in mask_files: + ob_id = int(os.path.basename(mask_file).split('.')[0].split('_')[1]) + ob_ids.append(ob_id) + ob_ids = np.asarray(ob_ids) + return ob_ids + + + def get_gt_mesh_file(self, ob_id): + raise RuntimeError("You should override this") + + + def get_color(self,i): + color = imageio.imread(self.color_files[i]) + if len(color.shape)==2: + color = np.tile(color[...,None], (1,1,3)) # Gray to RGB + if self.resize!=1: + color = cv2.resize(color, fx=self.resize, fy=self.resize, dsize=None) + return color + + + def get_depth(self,i, filled=False): + if filled: + depth_file = self.color_files[i].replace('rgb','depth_filled') + depth_file = f'{os.path.dirname(depth_file)}/0{os.path.basename(depth_file)}' + depth = cv2.imread(depth_file,-1)/1e3 + else: + depth_file = self.color_files[i].replace('rgb','depth').replace('gray','depth') + depth = cv2.imread(depth_file,-1)*1e-3*self.bop_depth_scale + if self.resize!=1: + depth = cv2.resize(depth, fx=self.resize, fy=self.resize, dsize=None, interpolation=cv2.INTER_NEAREST) + depth[depth<0.001] = 0 + depth[depth>self.zfar] = 0 + return depth + + def get_xyz_map(self,i): + depth = self.get_depth(i) + xyz_map = depth2xyzmap(depth, self.get_K(i)) + return xyz_map + + + def get_mask(self, i_frame:int, ob_id:int, type='mask_visib'): + ''' + @type: mask_visib (only visible part) / mask (projected mask from whole model) + ''' + pos = 0 + name = int(os.path.basename(self.color_files[i_frame]).split('.')[0]) + if self.scene_gt is not None: + for k in self.scene_gt[str(name)]: + if k['obj_id']==ob_id: + break + pos += 1 + mask_file = f'{self.base_dir}/{type}/{name:06d}_{pos:06d}.png' + if not os.path.exists(mask_file): + logging.info(f'{mask_file} not found') + return None + else: + # mask_dir = os.path.dirname(self.color_files[0]).replace('rgb',type) + # mask_file = f'{mask_dir}/{self.id_strs[i_frame]}_{ob_id:06d}.png' + raise RuntimeError + mask = cv2.imread(mask_file, -1) + if self.resize!=1: + mask = cv2.resize(mask, fx=self.resize, fy=self.resize, dsize=None, interpolation=cv2.INTER_NEAREST) + return mask>0 + + + def get_gt_mesh(self, ob_id:int): + mesh_file = self.get_gt_mesh_file(ob_id) + mesh = trimesh.load(mesh_file) + mesh.vertices *= 1e-3 + return mesh + + + def get_model_diameter(self, ob_id): + dir = os.path.dirname(self.get_gt_mesh_file(self.ob_ids[0])) + info_file = f'{dir}/models_info.json' + with open(info_file,'r') as ff: + info = json.load(ff) + return info[str(ob_id)]['diameter']/1e3 + + + + def get_gt_poses(self, i_frame, ob_id): + gt_poses = [] + name = int(self.id_strs[i_frame]) + for i_k, k in enumerate(self.scene_gt[str(name)]): + if k['obj_id']==ob_id: + cur = np.eye(4) + cur[:3,:3] = np.array(k['cam_R_m2c']).reshape(3,3) + cur[:3,3] = np.array(k['cam_t_m2c'])/1e3 + gt_poses.append(cur) + return np.asarray(gt_poses).reshape(-1,4,4) + + + def get_gt_pose(self, i_frame:int, ob_id, mask=None, use_my_correction=False): + ob_in_cam = np.eye(4) + best_iou = -np.inf + best_gt_mask = None + name = int(self.id_strs[i_frame]) + for i_k, k in enumerate(self.scene_gt[str(name)]): + if k['obj_id']==ob_id: + cur = np.eye(4) + cur[:3,:3] = np.array(k['cam_R_m2c']).reshape(3,3) + cur[:3,3] = np.array(k['cam_t_m2c'])/1e3 + if mask is not None: # When multi-instance exists, use mask to determine which one + gt_mask = cv2.imread(f'{self.base_dir}/mask_visib/{self.id_strs[i_frame]}_{i_k:06d}.png', -1).astype(bool) + intersect = (gt_mask*mask).astype(bool) + union = (gt_mask+mask).astype(bool) + iou = float(intersect.sum())/union.sum() + if iou>best_iou: + best_iou = iou + best_gt_mask = gt_mask + ob_in_cam = cur + else: + ob_in_cam = cur + break + + + if use_my_correction: + if 'ycb' in self.base_dir.lower() and 'train_real' in self.color_files[i_frame]: + video_id = self.get_video_id() + if ob_id==1: + if video_id in [12,13,14,17,24]: + ob_in_cam = ob_in_cam@self.symmetry_tfs[ob_id][1] + return ob_in_cam + + + def load_symmetry_tfs(self): + dir = os.path.dirname(self.get_gt_mesh_file(self.ob_ids[0])) + info_file = f'{dir}/models_info.json' + with open(info_file,'r') as ff: + info = json.load(ff) + self.symmetry_tfs = {} + self.symmetry_info_table = {} + for ob_id in self.ob_ids: + self.symmetry_info_table[ob_id] = info[str(ob_id)] + self.symmetry_tfs[ob_id] = symmetry_tfs_from_info(info[str(ob_id)], rot_angle_discrete=5) + self.geometry_symmetry_info_table = copy.deepcopy(self.symmetry_info_table) + + + def get_video_id(self): + return int(self.base_dir.split('/')[-1]) + + +class LinemodOcclusionReader(BopBaseReader): + def __init__(self,base_dir='/path/to/DATASET/LINEMOD-O/lmo_test_all/test/000002', zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'lmo' + self.K = list(self.K_table.values())[0] + self.ob_ids = [1,5,6,8,9,10,11,12] + self.ob_id_to_names = { + 1: 'ape', + 2: 'benchvise', + 3: 'bowl', + 4: 'camera', + 5: 'water_pour', + 6: 'cat', + 7: 'cup', + 8: 'driller', + 9: 'duck', + 10: 'eggbox', + 11: 'glue', + 12: 'holepuncher', + 13: 'iron', + 14: 'lamp', + 15: 'phone', + } + self.load_symmetry_tfs() + + def get_gt_mesh_file(self, ob_id): + mesh_dir = f'{BOP_DIR}/{self.dataset_name}/models/obj_{ob_id:06d}.ply' + return mesh_dir + + + +class LinemodReader(LinemodOcclusionReader): + def __init__(self, base_dir='/path/to/DATASET/LINEMOD/lm_test_all/test/000001', zfar=np.inf, split=None): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'lm' + if split is not None: # train/test + with open(f'/path/to/DATASET/LINEMOD/Linemod_preprocessed/data/{self.get_video_id():02d}/{split}.txt','r') as ff: + lines = ff.read().splitlines() + self.color_files = [] + for line in lines: + id = int(line) + self.color_files.append(f'{self.base_dir}/rgb/{id:06d}.png') + self.make_id_strs() + + self.ob_ids = np.setdiff1d(np.arange(1,16), np.array([7,3])).tolist() # Exclude bowl and mug + self.load_symmetry_tfs() + + + def get_gt_mesh_file(self, ob_id): + root = self.base_dir + while 1: + if os.path.exists(f'{root}/lm_models'): + mesh_dir = f'{root}/lm_models/models/obj_{ob_id:06d}.ply' + break + else: + root = os.path.abspath(f'{root}/../') + return mesh_dir + + + def get_reconstructed_mesh(self, ob_id, ref_view_dir): + mesh = trimesh.load(os.path.abspath(f'{ref_view_dir}/ob_{ob_id:07d}/model/model.obj')) + return mesh + + +class YcbVideoReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'ycbv' + self.K = list(self.K_table.values())[0] + + self.make_id_strs() + + self.ob_ids = np.arange(1,22).astype(int).tolist() + YCB_VIDEO_DIR = os.getenv('YCB_VIDEO_DIR') + names = sorted(os.listdir(f'{YCB_VIDEO_DIR}/models/')) + self.ob_id_to_names = {} + self.name_to_ob_id = {} + for i,ob_id in enumerate(self.ob_ids): + self.ob_id_to_names[ob_id] = names[i] + self.name_to_ob_id[names[i]] = ob_id + + if 'BOP' not in self.base_dir: + with open(f'{self.base_dir}/../../keyframe.txt','r') as ff: + self.keyframe_lines = ff.read().splitlines() + + self.load_symmetry_tfs() + for ob_id in self.ob_ids: + if ob_id in [1,4,6,18]: # Cylinder + self.geometry_symmetry_info_table[ob_id] = { + 'symmetries_continuous': [ + {'axis':[0,0,1], 'offset':[0,0,0]}, + ], + 'symmetries_discrete': euler_matrix(0, np.pi, 0).reshape(1,4,4).tolist(), + } + elif ob_id in [13]: + self.geometry_symmetry_info_table[ob_id] = { + 'symmetries_continuous': [ + {'axis':[0,0,1], 'offset':[0,0,0]}, + ], + } + elif ob_id in [2,3,9,21]: # Rectangle box + tfs = [] + for rz in [0, np.pi]: + for rx in [0,np.pi]: + for ry in [0,np.pi]: + tfs.append(euler_matrix(rx, ry, rz)) + self.geometry_symmetry_info_table[ob_id] = { + 'symmetries_discrete': np.asarray(tfs).reshape(-1,4,4).tolist(), + } + else: + pass + + def get_gt_mesh_file(self, ob_id): + if 'BOP' in self.base_dir: + mesh_file = os.path.abspath(f'{self.base_dir}/../../ycbv_models/models/obj_{ob_id:06d}.ply') + else: + mesh_file = f'{self.base_dir}/../../ycbv_models/models/obj_{ob_id:06d}.ply' + return mesh_file + + + def get_gt_mesh(self, ob_id:int, get_posecnn_version=False): + if get_posecnn_version: + YCB_VIDEO_DIR = os.getenv('YCB_VIDEO_DIR') + mesh = trimesh.load(f'{YCB_VIDEO_DIR}/models/{self.ob_id_to_names[ob_id]}/textured_simple.obj') + return mesh + mesh_file = self.get_gt_mesh_file(ob_id) + mesh = trimesh.load(mesh_file, process=False) + mesh.vertices *= 1e-3 + tex_file = mesh_file.replace('.ply','.png') + if os.path.exists(tex_file): + from PIL import Image + im = Image.open(tex_file) + uv = mesh.visual.uv + material = trimesh.visual.texture.SimpleMaterial(image=im) + color_visuals = trimesh.visual.TextureVisuals(uv=uv, image=im, material=material) + mesh.visual = color_visuals + return mesh + + + def get_reconstructed_mesh(self, ob_id, ref_view_dir): + mesh = trimesh.load(os.path.abspath(f'{ref_view_dir}/ob_{ob_id:07d}/model/model.obj')) + return mesh + + + def get_transform_reconstructed_to_gt_model(self, ob_id): + out = np.eye(4) + return out + + + def get_visible_cloud(self, ob_id): + file = os.path.abspath(f'{self.base_dir}/../../models/{self.ob_id_to_names[ob_id]}/visible_cloud.ply') + pcd = o3d.io.read_point_cloud(file) + return pcd + + + def is_keyframe(self, i): + color_file = self.color_files[i] + video_id = self.get_video_id() + frame_id = int(os.path.basename(color_file).split('.')[0]) + key = f'{video_id:04d}/{frame_id:06d}' + return (key in self.keyframe_lines) + + + +class TlessReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'tless' + + self.ob_ids = np.arange(1,31).astype(int).tolist() + self.load_symmetry_tfs() + + + def get_gt_mesh_file(self, ob_id): + mesh_file = f'{self.base_dir}/../../../models_cad/obj_{ob_id:06d}.ply' + return mesh_file + + + def get_gt_mesh(self, ob_id): + mesh = trimesh.load(self.get_gt_mesh_file(ob_id)) + mesh.vertices *= 1e-3 + mesh = trimesh_add_pure_colored_texture(mesh, color=np.ones((3))*200) + return mesh + + +class HomebrewedReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'hb' + self.ob_ids = np.arange(1,34).astype(int).tolist() + self.load_symmetry_tfs() + self.make_scene_ob_ids_dict() + + + def get_gt_mesh_file(self, ob_id): + mesh_file = f'{self.base_dir}/../../../hb_models/models/obj_{ob_id:06d}.ply' + return mesh_file + + + def get_gt_pose(self, i_frame:int, ob_id, use_my_correction=False): + logging.info("WARN HomeBrewed doesn't have GT pose") + return np.eye(4) + + + +class ItoddReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'itodd' + self.make_id_strs() + + self.ob_ids = np.arange(1,29).astype(int).tolist() + self.load_symmetry_tfs() + self.make_scene_ob_ids_dict() + + + def get_gt_mesh_file(self, ob_id): + mesh_file = f'{self.base_dir}/../../../itodd_models/models/obj_{ob_id:06d}.ply' + return mesh_file + + +class IcbinReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'icbin' + self.ob_ids = np.arange(1,3).astype(int).tolist() + self.load_symmetry_tfs() + + def get_gt_mesh_file(self, ob_id): + mesh_file = f'{self.base_dir}/../../../icbin_models/models/obj_{ob_id:06d}.ply' + return mesh_file + + +class TudlReader(BopBaseReader): + def __init__(self, base_dir, zfar=np.inf): + super().__init__(base_dir, zfar=zfar) + self.dataset_name = 'tudl' + self.ob_ids = np.arange(1,4).astype(int).tolist() + self.load_symmetry_tfs() + + def get_gt_mesh_file(self, ob_id): + mesh_file = f'{self.base_dir}/../../../tudl_models/models/obj_{ob_id:06d}.ply' + return mesh_file + + diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/estimater.py b/OVOW/engine/oneposeviagen/fpose/fpose/estimater.py new file mode 100644 index 0000000000000000000000000000000000000000..ff571ef1edd86ef66c19b75aa38462601b5d94b8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/estimater.py @@ -0,0 +1,306 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from fpose.Utils import * +from fpose.datareader import * +import itertools +from fpose.learning.training.predict_score import * +from fpose.learning.training.predict_pose_refine import * +import yaml +import tempfile + +# ----------------- FoundationPose 进程内常驻(OPG_FP_RESIDENT=1 开启)----------------- +# ScorePredictor/PoseRefinePredictor 是物体无关的重网络,原来每物体/每次调用都重建 +# (实测 ~19 次/视频)。这里缓存为模块级单例,跨物体/跨调用复用;glctx(RasterizeCuda +# Context)同理。默认关 -> 每次新建,行为不变。 +import os as _fp_os +_FP_RESIDENT_CACHE = {} + + +def _fp_resident_on(): + return _fp_os.environ.get("OPG_FP_RESIDENT", "0") == "1" + + +def get_cached_scorer(): + if not _fp_resident_on(): + return ScorePredictor() + if "scorer" not in _FP_RESIDENT_CACHE: + _FP_RESIDENT_CACHE["scorer"] = ScorePredictor() + return _FP_RESIDENT_CACHE["scorer"] + + +def get_cached_refiner(): + if not _fp_resident_on(): + return PoseRefinePredictor() + if "refiner" not in _FP_RESIDENT_CACHE: + _FP_RESIDENT_CACHE["refiner"] = PoseRefinePredictor() + return _FP_RESIDENT_CACHE["refiner"] + + +def get_cached_glctx(): + if not _fp_resident_on(): + return dr.RasterizeCudaContext() + if "glctx" not in _FP_RESIDENT_CACHE: + _FP_RESIDENT_CACHE["glctx"] = dr.RasterizeCudaContext() + return _FP_RESIDENT_CACHE["glctx"] + + +class FoundationPose: + def __init__(self, model_pts, model_normals, symmetry_tfs=None, mesh=None, scorer:ScorePredictor=None, refiner:PoseRefinePredictor=None, glctx=None, debug=0, debug_dir='/path/to/debug/novel_pose_debug/', export_mesh_path: bool = True): + self.gt_pose = None + self.ignore_normal_flip = True + self.debug = debug + self.debug_dir = debug_dir + self.export_mesh_path = export_mesh_path + os.makedirs(debug_dir, exist_ok=True) + + self.reset_object(model_pts, model_normals, symmetry_tfs=symmetry_tfs, mesh=mesh) + self.make_rotation_grid(min_n_views=40, inplane_step=60) + + self.glctx = glctx + + if scorer is not None: + self.scorer = scorer + else: + self.scorer = ScorePredictor() + + if refiner is not None: + self.refiner = refiner + else: + self.refiner = PoseRefinePredictor() + + self.pose_last = None # Used for tracking; per the centered mesh + + + def reset_object(self, model_pts, model_normals, symmetry_tfs=None, mesh=None): + max_xyz = mesh.vertices.max(axis=0) + min_xyz = mesh.vertices.min(axis=0) + self.model_center = (min_xyz+max_xyz)/2 + if mesh is not None: + self.mesh_ori = mesh.copy() + mesh = mesh.copy() + mesh.vertices = mesh.vertices - self.model_center.reshape(1,3) + + model_pts = mesh.vertices + self.diameter = compute_mesh_diameter(model_pts=mesh.vertices, n_sample=10000) + self.vox_size = max(self.diameter/20.0, 0.003) + logging.info(f'self.diameter:{self.diameter}, vox_size:{self.vox_size}') + self.dist_bin = self.vox_size/2 + self.angle_bin = 20 # Deg + pcd = toOpen3dCloud(model_pts, normals=model_normals) + pcd = pcd.voxel_down_sample(self.vox_size) + self.max_xyz = np.asarray(pcd.points).max(axis=0) + self.min_xyz = np.asarray(pcd.points).min(axis=0) + self.pts = torch.tensor(np.asarray(pcd.points), dtype=torch.float32, device='cuda') + self.normals = F.normalize(torch.tensor(np.asarray(pcd.normals), dtype=torch.float32, device='cuda'), dim=-1) + logging.info(f'self.pts:{self.pts.shape}') + self.mesh_path = None + self.mesh = mesh + if self.mesh is not None and self.export_mesh_path: + mesh_tmp_dir = tempfile.mkdtemp(prefix='foundationpose_mesh_') + self.mesh_path = os.path.join(mesh_tmp_dir, f'{uuid.uuid4()}.obj') + self.mesh.export(self.mesh_path) + self.mesh_tensors = make_mesh_tensors(self.mesh) + + if symmetry_tfs is None: + self.symmetry_tfs = torch.eye(4).float().cuda()[None] + else: + self.symmetry_tfs = torch.as_tensor(symmetry_tfs, device='cuda', dtype=torch.float) + + logging.info("reset done") + + + + def get_tf_to_centered_mesh(self): + tf_to_center = torch.eye(4, dtype=torch.float, device='cuda') + tf_to_center[:3,3] = -torch.as_tensor(self.model_center, device='cuda', dtype=torch.float) + return tf_to_center + + + def to_device(self, s='cuda:0'): + for k in self.__dict__: + self.__dict__[k] = self.__dict__[k] + if torch.is_tensor(self.__dict__[k]) or isinstance(self.__dict__[k], nn.Module): + logging.info(f"Moving {k} to device {s}") + self.__dict__[k] = self.__dict__[k].to(s) + for k in self.mesh_tensors: + logging.info(f"Moving {k} to device {s}") + self.mesh_tensors[k] = self.mesh_tensors[k].to(s) + if self.refiner is not None: + self.refiner.model.to(s) + if self.scorer is not None: + self.scorer.model.to(s) + if self.glctx is not None: + self.glctx = dr.RasterizeCudaContext(s) + + + + def make_rotation_grid(self, min_n_views=40, inplane_step=60): + cam_in_obs = sample_views_icosphere(n_views=min_n_views) + logging.info(f'cam_in_obs:{cam_in_obs.shape}') + rot_grid = [] + for i in range(len(cam_in_obs)): + for inplane_rot in np.deg2rad(np.arange(0, 360, inplane_step)): + cam_in_ob = cam_in_obs[i] + R_inplane = np.asarray(euler_matrix(0, 0, inplane_rot), dtype=np.float64) + cam_in_ob = cam_in_ob @ R_inplane + ob_in_cam = np.linalg.inv(cam_in_ob) + rot_grid.append(ob_in_cam) + + rot_grid = np.asarray(rot_grid) + logging.info(f"rot_grid:{rot_grid.shape}") + rot_grid = mycpp.cluster_poses(30, 99999, rot_grid, self.symmetry_tfs.data.cpu().numpy()) + rot_grid = np.asarray(rot_grid) + logging.info(f"after cluster, rot_grid:{rot_grid.shape}") + self.rot_grid = torch.as_tensor(rot_grid, device='cuda', dtype=torch.float) + logging.info(f"self.rot_grid: {self.rot_grid.shape}") + + + def generate_random_pose_hypo(self, K, rgb, depth, mask, scene_pts=None): + ''' + @scene_pts: torch tensor (N,3) + ''' + ob_in_cams = self.rot_grid.clone() + center = self.guess_translation(depth=depth, mask=mask, K=K) + ob_in_cams[:,:3,3] = torch.tensor(center, device='cuda', dtype=torch.float).reshape(1,3) + return ob_in_cams + + + def guess_translation(self, depth, mask, K): + vs,us = np.where(mask>0) + if len(us)==0: + logging.info(f'mask is all zero') + return np.zeros((3)) + uc = (us.min()+us.max())/2.0 + vc = (vs.min()+vs.max())/2.0 + valid = mask.astype(bool) & (depth>=0.001) + if not valid.any(): + logging.info(f"valid is empty") + return np.zeros((3)) + + zc = np.median(depth[valid]) + center = (np.linalg.inv(K)@np.asarray([uc,vc,1]).reshape(3,1))*zc + + if self.debug>=2: + pcd = toOpen3dCloud(center.reshape(1,3)) + o3d.io.write_point_cloud(f'{self.debug_dir}/init_center.ply', pcd) + + return center.reshape(3) + + + def register(self, K, rgb, depth, ob_mask, ob_id=None, glctx=None, iteration=5): + '''Copmute pose from given pts to self.pcd + @pts: (N,3) np array, downsampled scene points + ''' + set_seed(0) + logging.info('Welcome') + + if self.glctx is None: + if glctx is None: + self.glctx = get_cached_glctx() + # self.glctx = dr.RasterizeGLContext() + else: + self.glctx = glctx + + depth = erode_depth(depth, radius=2, device='cuda') + depth = bilateral_filter_depth(depth, radius=2, device='cuda') + + if self.debug>=2: + xyz_map = depth2xyzmap(depth, K) + valid = xyz_map[...,2]>=0.001 + pcd = toOpen3dCloud(xyz_map[valid], rgb[valid]) + o3d.io.write_point_cloud(f'{self.debug_dir}/scene_raw.ply',pcd) + cv2.imwrite(f'{self.debug_dir}/ob_mask.png', (ob_mask*255.0).clip(0,255)) + + normal_map = None + valid = (depth>=0.001) & (ob_mask>0) + if valid.sum()<4: + logging.info(f'valid too small, return') + pose = np.eye(4) + pose[:3,3] = self.guess_translation(depth=depth, mask=ob_mask, K=K) + return pose + + if self.debug>=2: + imageio.imwrite(f'{self.debug_dir}/color.png', rgb) + cv2.imwrite(f'{self.debug_dir}/depth.png', (depth*1000).astype(np.uint16)) + valid = xyz_map[...,2]>=0.001 + pcd = toOpen3dCloud(xyz_map[valid], rgb[valid]) + o3d.io.write_point_cloud(f'{self.debug_dir}/scene_complete.ply',pcd) + + self.H, self.W = depth.shape[:2] + self.K = K + self.ob_id = ob_id + self.ob_mask = ob_mask + + poses = self.generate_random_pose_hypo(K=K, rgb=rgb, depth=depth, mask=ob_mask, scene_pts=None) + poses = poses.data.cpu().numpy() + logging.info(f'poses:{poses.shape}') + center = self.guess_translation(depth=depth, mask=ob_mask, K=K) + + poses = torch.as_tensor(poses, device='cuda', dtype=torch.float) + poses[:,:3,3] = torch.as_tensor(center.reshape(1,3), device='cuda') + + add_errs = self.compute_add_err_to_gt_pose(poses) + logging.info(f"after viewpoint, add_errs min:{add_errs.min()}") + + xyz_map = depth2xyzmap(depth, K) + poses, vis = self.refiner.predict(mesh=self.mesh, mesh_tensors=self.mesh_tensors, rgb=rgb, depth=depth, K=K, ob_in_cams=poses.data.cpu().numpy(), normal_map=normal_map, xyz_map=xyz_map, glctx=self.glctx, mesh_diameter=self.diameter, iteration=iteration, get_vis=self.debug>=2) + if vis is not None: + imageio.imwrite(f'{self.debug_dir}/vis_refiner.png', vis) + + scores, vis = self.scorer.predict(mesh=self.mesh, rgb=rgb, depth=depth, K=K, ob_in_cams=poses.data.cpu().numpy(), normal_map=normal_map, mesh_tensors=self.mesh_tensors, glctx=self.glctx, mesh_diameter=self.diameter, get_vis=self.debug>=2) + if vis is not None: + imageio.imwrite(f'{self.debug_dir}/vis_score.png', vis) + + add_errs = self.compute_add_err_to_gt_pose(poses) + logging.info(f"final, add_errs min:{add_errs.min()}") + + ids = torch.as_tensor(scores).argsort(descending=True) + # logging.info(f'sort ids:{ids}') + scores = scores[ids] + poses = poses[ids] + + # logging.info(f'sorted scores:{scores}') + + best_pose = poses[0]@self.get_tf_to_centered_mesh() + self.pose_last = poses[0] + self.best_id = ids[0] + + self.poses = poses + self.scores = scores + + return best_pose.data.cpu().numpy() + + + def compute_add_err_to_gt_pose(self, poses): + ''' + @poses: wrt. the centered mesh + ''' + return -torch.ones(len(poses), device='cuda', dtype=torch.float) + + + def track_one(self, rgb, depth, K, iteration, extra={}): + if self.pose_last is None: + logging.info("Please init pose by register first") + raise RuntimeError + logging.info("Welcome") + + depth = torch.as_tensor(depth, device='cuda', dtype=torch.float) + depth = erode_depth(depth, radius=2, device='cuda') + depth = bilateral_filter_depth(depth, radius=2, device='cuda') + logging.info("depth processing done") + + xyz_map = depth2xyzmap_batch(depth[None], torch.as_tensor(K, dtype=torch.float, device='cuda')[None], zfar=np.inf)[0] + + pose, vis = self.refiner.predict(mesh=self.mesh, mesh_tensors=self.mesh_tensors, rgb=rgb, depth=depth, K=K, ob_in_cams=self.pose_last.reshape(1,4,4).data.cpu().numpy(), normal_map=None, xyz_map=xyz_map, mesh_diameter=self.diameter, glctx=self.glctx, iteration=iteration, get_vis=self.debug>=2) + logging.info("pose done") + if self.debug>=2: + extra['vis'] = vis + self.pose_last = pose + return (pose@self.get_tf_to_centered_mesh()).data.cpu().numpy().reshape(4,4) diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/learning/datasets/h5_dataset.py b/OVOW/engine/oneposeviagen/fpose/fpose/learning/datasets/h5_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..3bb51a5919e199bcc205564f1d075c535e1d5566 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/learning/datasets/h5_dataset.py @@ -0,0 +1,220 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + + +import os,sys,h5py,bisect,io,json +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../../../../') +from Utils import * +from learning.datasets.pose_dataset import * + + + + +class PairH5Dataset(torch.utils.data.Dataset): + def __init__(self, cfg, h5_file, mode='train', max_num_key=None, cache_data=None): + self.cfg = cfg + self.h5_file = h5_file + self.mode = mode + + logging.info(f"self.h5_file:{self.h5_file}") + self.n_perturb = None + self.H_ori = None + self.W_ori = None + self.cache_data = cache_data + + if self.mode=='test': + pass + else: + self.object_keys = [] + key_file = h5_file.replace('.h5','_keys.pkl') + if os.path.exists(key_file): + with open(key_file, 'rb') as ff: + self.object_keys = pickle.load(ff) + logging.info(f'object_keys loaded#:{len(self.object_keys)} from {key_file}') + if max_num_key is not None: + self.object_keys = self.object_keys[:max_num_key] + else: + with h5py.File(h5_file, 'r', libver='latest') as hf: + for k in hf: + self.object_keys.append(k) + if max_num_key is not None and len(self.object_keys)>=max_num_key: + logging.info("break due to max_num_key") + break + + logging.info(f'self.object_keys#:{len(self.object_keys)}, max_num_key:{max_num_key}') + + with h5py.File(h5_file, 'r', libver='latest') as hf: + group = hf[self.object_keys[0]] + cnt = 0 + for k_perturb in group: + if 'i_perturb' in k_perturb: + cnt += 1 + if 'crop_ratio' in group[k_perturb]: + self.cfg['crop_ratio'] = float(group[k_perturb]['crop_ratio'][()]) + if self.H_ori is None: + if 'H_ori' in group[k_perturb]: + self.H_ori = int(group[k_perturb]['H_ori'][()]) + self.W_ori = int(group[k_perturb]['W_ori'][()]) + else: + self.H_ori = 540 + self.W_ori = 720 + self.n_perturb = cnt + logging.info(f'self.n_perturb:{self.n_perturb}') + + + def __len__(self): + if self.mode=='test': + return 1 + return len(self.object_keys) + + + + def transform_depth_to_xyzmap(self, batch:BatchPoseData, H_ori, W_ori, bound=1): + bs = len(batch.rgbAs) + H,W = batch.rgbAs.shape[-2:] + mesh_radius = batch.mesh_diameters.cuda()/2 + tf_to_crops = batch.tf_to_crops.cuda() + crop_to_oris = batch.tf_to_crops.inverse().cuda() #(B,3,3) + batch.poseA = batch.poseA.cuda() + batch.Ks = batch.Ks.cuda() + + if batch.xyz_mapAs is None: + depthAs_ori = kornia.geometry.transform.warp_perspective(batch.depthAs.cuda().expand(bs,-1,-1,-1), crop_to_oris, dsize=(H_ori, W_ori), mode='nearest', align_corners=False) + batch.xyz_mapAs = depth2xyzmap_batch(depthAs_ori[:,0], batch.Ks, zfar=np.inf).permute(0,3,1,2) #(B,3,H,W) + batch.xyz_mapAs = kornia.geometry.transform.warp_perspective(batch.xyz_mapAs, tf_to_crops, dsize=(H,W), mode='nearest', align_corners=False) + batch.xyz_mapAs = batch.xyz_mapAs.cuda() + if self.cfg['normalize_xyz']: + invalid = batch.xyz_mapAs[:,2:3]<0.001 + batch.xyz_mapAs = batch.xyz_mapAs-batch.poseA[:,:3,3].reshape(bs,3,1,1) + if self.cfg['normalize_xyz']: + batch.xyz_mapAs *= 1/mesh_radius.reshape(bs,1,1,1) + invalid = invalid.expand(bs,3,-1,-1) | (torch.abs(batch.xyz_mapAs)>=2) + batch.xyz_mapAs[invalid.expand(bs,3,-1,-1)] = 0 + + if batch.xyz_mapBs is None: + depthBs_ori = kornia.geometry.transform.warp_perspective(batch.depthBs.cuda().expand(bs,-1,-1,-1), crop_to_oris, dsize=(H_ori, W_ori), mode='nearest', align_corners=False) + batch.xyz_mapBs = depth2xyzmap_batch(depthBs_ori[:,0], batch.Ks, zfar=np.inf).permute(0,3,1,2) #(B,3,H,W) + batch.xyz_mapBs = kornia.geometry.transform.warp_perspective(batch.xyz_mapBs, tf_to_crops, dsize=(H,W), mode='nearest', align_corners=False) + batch.xyz_mapBs = batch.xyz_mapBs.cuda() + if self.cfg['normalize_xyz']: + invalid = batch.xyz_mapBs[:,2:3]<0.001 + batch.xyz_mapBs = batch.xyz_mapBs-batch.poseA[:,:3,3].reshape(bs,3,1,1) + if self.cfg['normalize_xyz']: + batch.xyz_mapBs *= 1/mesh_radius.reshape(bs,1,1,1) + invalid = invalid.expand(bs,3,-1,-1) | (torch.abs(batch.xyz_mapBs)>=2) + batch.xyz_mapBs[invalid.expand(bs,3,-1,-1)] = 0 + + return batch + + + + def transform_batch(self, batch:BatchPoseData, H_ori, W_ori, bound=1): + '''Transform the batch before feeding to the network + !NOTE the H_ori, W_ori could be different at test time from the training data, and needs to be set + ''' + bs = len(batch.rgbAs) + batch.rgbAs = batch.rgbAs.cuda().float()/255.0 + batch.rgbBs = batch.rgbBs.cuda().float()/255.0 + + batch = self.transform_depth_to_xyzmap(batch, H_ori, W_ori, bound=bound) + return batch + + + + +class TripletH5Dataset(PairH5Dataset): + def __init__(self, cfg, h5_file, mode, max_num_key=None, cache_data=None): + super().__init__(cfg, h5_file, mode, max_num_key, cache_data=cache_data) + + + def transform_depth_to_xyzmap(self, batch:BatchPoseData, H_ori, W_ori, bound=1): + bs = len(batch.rgbAs) + H,W = batch.rgbAs.shape[-2:] + mesh_radius = batch.mesh_diameters.cuda()/2 + tf_to_crops = batch.tf_to_crops.cuda() + crop_to_oris = batch.tf_to_crops.inverse().cuda() #(B,3,3) + batch.poseA = batch.poseA.cuda() + batch.Ks = batch.Ks.cuda() + + if batch.xyz_mapAs is None: + depthAs_ori = kornia.geometry.transform.warp_perspective(batch.depthAs.cuda().expand(bs,-1,-1,-1), crop_to_oris, dsize=(H_ori, W_ori), mode='nearest', align_corners=False) + batch.xyz_mapAs = depth2xyzmap_batch(depthAs_ori[:,0], batch.Ks, zfar=np.inf).permute(0,3,1,2) #(B,3,H,W) + batch.xyz_mapAs = kornia.geometry.transform.warp_perspective(batch.xyz_mapAs, tf_to_crops, dsize=(H,W), mode='nearest', align_corners=False) + batch.xyz_mapAs = batch.xyz_mapAs.cuda() + invalid = batch.xyz_mapAs[:,2:3]<0.1 + batch.xyz_mapAs = (batch.xyz_mapAs-batch.poseA[:,:3,3].reshape(bs,3,1,1)) + if self.cfg['normalize_xyz']: + batch.xyz_mapAs *= 1/mesh_radius.reshape(bs,1,1,1) + invalid = invalid.expand(bs,3,-1,-1) | (torch.abs(batch.xyz_mapAs)>=2) + batch.xyz_mapAs[invalid.expand(bs,3,-1,-1)] = 0 + + if batch.xyz_mapBs is None: + depthBs_ori = kornia.geometry.transform.warp_perspective(batch.depthBs.cuda().expand(bs,-1,-1,-1), crop_to_oris, dsize=(H_ori, W_ori), mode='nearest', align_corners=False) + batch.xyz_mapBs = depth2xyzmap_batch(depthBs_ori[:,0], batch.Ks, zfar=np.inf).permute(0,3,1,2) #(B,3,H,W) + batch.xyz_mapBs = kornia.geometry.transform.warp_perspective(batch.xyz_mapBs, tf_to_crops, dsize=(H,W), mode='nearest', align_corners=False) + batch.xyz_mapBs = batch.xyz_mapBs.cuda() + invalid = batch.xyz_mapBs[:,2:3]<0.1 + batch.xyz_mapBs = (batch.xyz_mapBs-batch.poseA[:,:3,3].reshape(bs,3,1,1)) + if self.cfg['normalize_xyz']: + batch.xyz_mapBs *= 1/mesh_radius.reshape(bs,1,1,1) + invalid = invalid.expand(bs,3,-1,-1) | (torch.abs(batch.xyz_mapBs)>=2) + batch.xyz_mapBs[invalid.expand(bs,3,-1,-1)] = 0 + + return batch + + + def transform_batch(self, batch:BatchPoseData, H_ori, W_ori, bound=1): + bs = len(batch.rgbAs) + batch.rgbAs = batch.rgbAs.cuda().float()/255.0 + batch.rgbBs = batch.rgbBs.cuda().float()/255.0 + + batch = self.transform_depth_to_xyzmap(batch, H_ori, W_ori, bound=bound) + return batch + + + +class ScoreMultiPairH5Dataset(TripletH5Dataset): + def __init__(self, cfg, h5_file, mode, max_num_key=None, cache_data=None): + super().__init__(cfg, h5_file, mode, max_num_key, cache_data=cache_data) + if mode in ['train', 'val']: + self.cfg['train_num_pair'] = self.n_perturb + + +class PoseRefinePairH5Dataset(PairH5Dataset): + def __init__(self, cfg, h5_file, mode='train', max_num_key=None, cache_data=None): + super().__init__(cfg=cfg, h5_file=h5_file, mode=mode, max_num_key=max_num_key, cache_data=cache_data) + + if mode!='test': + with h5py.File(h5_file, 'r', libver='latest') as hf: + group = hf[self.object_keys[0]] + for key_perturb in group: + depthA = imageio.imread(group[key_perturb]['depthA'][()]) + depthB = imageio.imread(group[key_perturb]['depthB'][()]) + self.cfg['n_view'] = min(self.cfg['n_view'], depthA.shape[1]//depthB.shape[1]) + logging.info(f'n_view:{self.cfg["n_view"]}') + self.trans_normalizer = group[key_perturb]['trans_normalizer'][()] + if isinstance(self.trans_normalizer, np.ndarray): + self.trans_normalizer = self.trans_normalizer.tolist() + self.rot_normalizer = group[key_perturb]['rot_normalizer'][()]/180.0*np.pi + logging.info(f'self.trans_normalizer:{self.trans_normalizer}, self.rot_normalizer:{self.rot_normalizer}') + break + + + def transform_batch(self, batch:BatchPoseData, H_ori, W_ori, bound=1): + '''Transform the batch before feeding to the network + !NOTE the H_ori, W_ori could be different at test time from the training data, and needs to be set + ''' + bs = len(batch.rgbAs) + batch.rgbAs = batch.rgbAs.cuda().float()/255.0 + batch.rgbBs = batch.rgbBs.cuda().float()/255.0 + + batch = self.transform_depth_to_xyzmap(batch, H_ori, W_ori, bound=bound) + return batch + diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/learning/datasets/pose_dataset.py b/OVOW/engine/oneposeviagen/fpose/fpose/learning/datasets/pose_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..8e76ee4645731128daad385879b738ff58eee9fc --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/learning/datasets/pose_dataset.py @@ -0,0 +1,135 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys +from dataclasses import dataclass +from typing import Iterator, List, Optional, Set, Union +import numpy as np +import torch +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../../../../') +from Utils import * + + +@dataclass +class PoseData: + """ + rgb: (h, w, 3) uint8 + depth: (bsz, h, w) float32 + bbox: (4, ) int + K: (3, 3) float32 + """ + rgb: np.ndarray = None + bbox: np.ndarray = None + K: np.ndarray = None + depth: Optional[np.ndarray] = None + object_data = None + mesh_diameter: float = None + rgbA: np.ndarray = None + rgbB: np.ndarray = None + depthA: np.ndarray = None + depthB: np.ndarray = None + maskA = None + maskB = None + poseA: np.ndarray = None #(4,4) + target: float = None + + def __init__(self, rgbA=None, rgbB=None, depthA=None, depthB=None, maskA=None, maskB=None, normalA=None, normalB=None, xyz_mapA=None, xyz_mapB=None, poseA=None, poseB=None, K=None, target=None, mesh_diameter=None, tf_to_crop=None, crop_mask=None, model_pts=None, label=None, model_scale=None): + self.rgbA = rgbA #(H,W,3) or (H,W*n_view,3) when multiview + self.rgbB = rgbB + self.depthA = depthA + self.depthB = depthB + self.poseA = poseA + self.poseB = poseB + self.maskA = maskA + self.maskB = maskB + self.crop_mask = crop_mask + self.normalA = normalA + self.normalB = normalB + self.xyz_mapA = xyz_mapA + self.xyz_mapB = xyz_mapB + self.target = target + self.K = K + self.mesh_diameter = mesh_diameter + self.tf_to_crop = tf_to_crop + self.model_pts = model_pts + self.label = label + self.model_scale = model_scale + + +@dataclass +class BatchPoseData: + """ + rgbs: (bsz, 3, h, w) torch tensor uint8 + depths: (bsz, h, w) float32 + bboxes: (bsz, 4) int + K: (bsz, 3, 3) float32 + """ + + rgbs: torch.Tensor = None + object_datas = None + bboxes: torch.Tensor = None + K: torch.Tensor = None + depths: Optional[torch.Tensor] = None + rgbAs = None + rgbBs = None + depthAs = None + depthBs = None + normalAs = None + normalBs = None + poseA = None #(B,4,4) + poseB = None + targets = None # Score targets, torch tensor (B) + + def __init__(self, rgbAs=None, rgbBs=None, depthAs=None, depthBs=None, normalAs=None, normalBs=None, maskAs=None, maskBs=None, poseA=None, poseB=None, xyz_mapAs=None, xyz_mapBs=None, tf_to_crops=None, Ks=None, crop_masks=None, model_pts=None, mesh_diameters=None, labels=None): + self.rgbAs = rgbAs + self.rgbBs = rgbBs + self.depthAs = depthAs + self.depthBs = depthBs + self.normalAs = normalAs + self.normalBs = normalBs + self.poseA = poseA + self.poseB = poseB + self.maskAs = maskAs + self.maskBs = maskBs + self.xyz_mapAs = xyz_mapAs + self.xyz_mapBs = xyz_mapBs + self.tf_to_crops = tf_to_crops + self.crop_masks = crop_masks + self.Ks = Ks + self.model_pts = model_pts + self.mesh_diameters = mesh_diameters + self.labels = labels + + + def pin_memory(self) -> "BatchPoseData": + for k in self.__dict__: + if self.__dict__[k] is not None: + try: + self.__dict__[k] = self.__dict__[k].pin_memory() + except Exception as e: + pass + return self + + def cuda(self): + for k in self.__dict__: + if self.__dict__[k] is not None: + try: + self.__dict__[k] = self.__dict__[k].cuda() + except: + pass + return self + + def select_by_indices(self, ids): + out = BatchPoseData() + for k in self.__dict__: + if self.__dict__[k] is not None: + out.__dict__[k] = self.__dict__[k][ids.to(self.__dict__[k].device)] + return out + diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/learning/models/network_modules.py b/OVOW/engine/oneposeviagen/fpose/fpose/learning/models/network_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..a0e4246628fcf60ab7b1cc44bca789892ac59bc6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/learning/models/network_modules.py @@ -0,0 +1,138 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys,copy,math,tqdm +import numpy as np +dir_path = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(dir_path) +import torch.nn.functional as F +import torch +import torch.nn as nn +import time +import cv2 +sys.path.append(f'{dir_path}/../../../../') +from Utils import * + + + +class ConvBN(nn.Module): + def __init__(self, C_in, C_out, kernel_size=3, stride=1, groups=1, bias=True,dilation=1,): + super().__init__() + padding = (kernel_size - 1) // 2 + self.net = nn.Sequential( + nn.Conv2d(C_in, C_out, kernel_size, stride, padding, groups=groups, bias=bias,dilation=dilation), + nn.BatchNorm2d(C_out), + ) + + def forward(self, x): + return self.net(x) + + +class ConvBNReLU(nn.Module): + def __init__(self, C_in, C_out, kernel_size=3, stride=1, groups=1, bias=True,dilation=1, norm_layer=nn.BatchNorm2d): + super().__init__() + padding = (kernel_size - 1) // 2 + layers = [ + nn.Conv2d(C_in, C_out, kernel_size, stride, padding, groups=groups, bias=bias,dilation=dilation), + ] + if norm_layer is not None: + layers.append(norm_layer(C_out)) + layers.append(nn.ReLU(inplace=True)) + self.net = nn.Sequential(*layers) + + def forward(self, x): + return self.net(x) + + +class ConvPadding(nn.Module): + def __init__(self,C_in, C_out, kernel_size=3, stride=1, groups=1, bias=True,dilation=1): + super(ConvPadding, self).__init__() + padding = (kernel_size - 1) // 2 + self.conv = nn.Conv2d(C_in, C_out, kernel_size, stride, padding, groups=groups, bias=bias,dilation=dilation) + + def forward(self,x): + return self.conv(x) + + +def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1, bias=False): + """3x3 convolution with padding""" + return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, + padding=dilation, groups=groups, bias=bias, dilation=dilation) + + +def conv1x1(in_planes, out_planes, stride=1, bias=False): + """1x1 convolution""" + return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=bias) + +class ResnetBasicBlock(nn.Module): + __constants__ = ['downsample'] + + def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=nn.BatchNorm2d, bias=False): + super().__init__() + self.norm_layer = norm_layer + if groups != 1 or base_width != 64: + raise ValueError('BasicBlock only supports groups=1 and base_width=64') + if dilation > 1: + raise NotImplementedError("Dilation > 1 not supported in BasicBlock") + # Both self.conv1 and self.downsample layers downsample the input when stride != 1 + self.conv1 = conv3x3(inplanes, planes, stride,bias=bias) + if self.norm_layer is not None: + self.bn1 = norm_layer(planes) + self.relu = nn.ReLU(inplace=True) + self.conv2 = conv3x3(planes, planes,bias=bias) + if self.norm_layer is not None: + self.bn2 = norm_layer(planes) + self.downsample = downsample + self.stride = stride + + def forward(self, x): + identity = x + + out = self.conv1(x) + if self.norm_layer is not None: + out = self.bn1(out) + out = self.relu(out) + + out = self.conv2(out) + if self.norm_layer is not None: + out = self.bn2(out) + + if self.downsample is not None: + identity = self.downsample(x) + out += identity + out = self.relu(out) + + return out + + + +class PositionalEmbedding(nn.Module): + def __init__(self, d_model, max_len=512): + super().__init__() + + # Compute the positional encodings once in log space. + pe = torch.zeros(max_len, d_model).float() + pe.require_grad = False + + position = torch.arange(0, max_len).float().unsqueeze(1) #(N,1) + div_term = (torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)).exp()[None] + + pe[:, 0::2] = torch.sin(position * div_term) #(N, d_model/2) + pe[:, 1::2] = torch.cos(position * div_term) + + pe = pe.unsqueeze(0) + self.register_buffer('pe', pe) #(1, max_len, D) + + + def forward(self, x): + ''' + @x: (B,N,D) + ''' + return x + self.pe[:, :x.size(1)] + diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/learning/models/refine_network.py b/OVOW/engine/oneposeviagen/fpose/fpose/learning/models/refine_network.py new file mode 100644 index 0000000000000000000000000000000000000000..c2e399efc309f36129ad0365c940de71df443f60 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/learning/models/refine_network.py @@ -0,0 +1,93 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys +import numpy as np +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(code_dir) +sys.path.append(f'{code_dir}/../../../../') +from Utils import * +import torch.nn.functional as F +import torch +import torch.nn as nn +import cv2 +from functools import partial +from network_modules import * +from Utils import * + + + +class RefineNet(nn.Module): + def __init__(self, cfg=None, c_in=4, n_view=1): + super().__init__() + self.cfg = cfg + if self.cfg.use_BN: + norm_layer = nn.BatchNorm2d + norm_layer1d = nn.BatchNorm1d + else: + norm_layer = None + norm_layer1d = None + + self.encodeA = nn.Sequential( + ConvBNReLU(C_in=c_in,C_out=64,kernel_size=7,stride=2, norm_layer=norm_layer), + ConvBNReLU(C_in=64,C_out=128,kernel_size=3,stride=2, norm_layer=norm_layer), + ResnetBasicBlock(128,128,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(128,128,bias=True, norm_layer=norm_layer), + ) + + self.encodeAB = nn.Sequential( + ResnetBasicBlock(256,256,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(256,256,bias=True, norm_layer=norm_layer), + ConvBNReLU(256,512,kernel_size=3,stride=2, norm_layer=norm_layer), + ResnetBasicBlock(512,512,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(512,512,bias=True, norm_layer=norm_layer), + ) + + embed_dim = 512 + num_heads = 4 + self.pos_embed = PositionalEmbedding(d_model=embed_dim, max_len=400) + + self.trans_head = nn.Sequential( + nn.TransformerEncoderLayer(d_model=embed_dim, nhead=num_heads, dim_feedforward=512, batch_first=True), + nn.Linear(512, 3), + ) + + if self.cfg['rot_rep']=='axis_angle': + rot_out_dim = 3 + elif self.cfg['rot_rep']=='6d': + rot_out_dim = 6 + else: + raise RuntimeError + self.rot_head = nn.Sequential( + nn.TransformerEncoderLayer(d_model=embed_dim, nhead=num_heads, dim_feedforward=512, batch_first=True), + nn.Linear(512, rot_out_dim), + ) + + + def forward(self, A, B): + """ + @A: (B,C,H,W) + """ + bs = len(A) + output = {} + + x = torch.cat([A,B], dim=0) + x = self.encodeA(x) + a = x[:bs] + b = x[bs:] + + ab = torch.cat((a,b),1).contiguous() + ab = self.encodeAB(ab) #(B,C,H,W) + + ab = self.pos_embed(ab.reshape(bs, ab.shape[1], -1).permute(0,2,1)) + + output['trans'] = self.trans_head(ab).mean(dim=1) + output['rot'] = self.rot_head(ab).mean(dim=1) + + return output diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/learning/models/score_network.py b/OVOW/engine/oneposeviagen/fpose/fpose/learning/models/score_network.py new file mode 100644 index 0000000000000000000000000000000000000000..fbf362ec0f9d95d4ecbd00ef0d64c6d5d903f9e7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/learning/models/score_network.py @@ -0,0 +1,90 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys +import numpy as np +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(code_dir) +sys.path.append(f'{code_dir}/../../../../') +from Utils import * +from functools import partial +import torch.nn.functional as F +import torch +import torch.nn as nn +import cv2 +from network_modules import * +from Utils import * + + + + +class ScoreNetMultiPair(nn.Module): + def __init__(self, cfg=None, c_in=4): + super().__init__() + self.cfg = cfg + if self.cfg.use_BN: + norm_layer = nn.BatchNorm2d + else: + norm_layer = None + + self.encoderA = nn.Sequential( + ConvBNReLU(C_in=c_in,C_out=64,kernel_size=7,stride=2, norm_layer=norm_layer), + ConvBNReLU(C_in=64,C_out=128,kernel_size=3,stride=2, norm_layer=norm_layer), + ResnetBasicBlock(128,128,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(128,128,bias=True, norm_layer=norm_layer), + ) + + self.encoderAB = nn.Sequential( + ResnetBasicBlock(256,256,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(256,256,bias=True, norm_layer=norm_layer), + ConvBNReLU(256,512,kernel_size=3,stride=2, norm_layer=norm_layer), + ResnetBasicBlock(512,512,bias=True, norm_layer=norm_layer), + ResnetBasicBlock(512,512,bias=True, norm_layer=norm_layer), + ) + + embed_dim = 512 + num_heads = 4 + self.att = nn.MultiheadAttention(embed_dim=embed_dim, num_heads=num_heads, bias=True, batch_first=True) + self.att_cross = nn.MultiheadAttention(embed_dim=embed_dim, num_heads=num_heads, bias=True, batch_first=True) + + self.pos_embed = PositionalEmbedding(d_model=embed_dim, max_len=400) + self.linear = nn.Linear(embed_dim, 1) + + + def extract_feat(self, A, B): + """ + @A: (B*L,C,H,W) L is num of pairs + """ + bs = A.shape[0] # B*L + + x = torch.cat([A,B], dim=0) + x = self.encoderA(x) + a = x[:bs] + b = x[bs:] + ab = torch.cat((a,b), dim=1) + ab = self.encoderAB(ab) + ab = self.pos_embed(ab.reshape(bs, ab.shape[1], -1).permute(0,2,1)) + ab, _ = self.att(ab, ab, ab) + return ab.mean(dim=1).reshape(bs,-1) + + + def forward(self, A, B, L): + """ + @A: (B*L,C,H,W) L is num of pairs + @L: num of pairs + """ + output = {} + bs = A.shape[0]//L + feats = self.extract_feat(A, B) #(B*L, C) + x = feats.reshape(bs,L,-1) + x, _ = self.att_cross(x, x, x) + + output['score_logit'] = self.linear(x).reshape(bs,L) # (B,L) + + return output diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/learning/training/predict_pose_refine.py b/OVOW/engine/oneposeviagen/fpose/fpose/learning/training/predict_pose_refine.py new file mode 100644 index 0000000000000000000000000000000000000000..af0c55cacfabe80087b4a1d47f189ef65a55ae04 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/learning/training/predict_pose_refine.py @@ -0,0 +1,347 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import functools +import os,sys,kornia +import time +from pathlib import Path +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/../../') +import numpy as np +import torch +from omegaconf import OmegaConf +from learning.models.refine_network import RefineNet +from learning.datasets.h5_dataset import * +from Utils import * +from datareader import * + + +def _find_onepose_repo_root() -> Path | None: + p = Path(__file__).resolve() + for parent in p.parents: + if parent.name == 'OnePoseviaGen': + return parent + return None + + +def _resolve_checkpoint_path(rel_path: str) -> Path: + rel = Path(rel_path) + candidates: list[Path] = [] + + ckpt_root = os.environ.get('ONEPOSEVIA_CHECKPOINT_ROOT') + if ckpt_root: + candidates.append(Path(ckpt_root) / rel) + + onepose_root = _find_onepose_repo_root() + if onepose_root is not None: + candidates.append(onepose_root / rel) + + candidates.append(rel) + + for candidate in candidates: + if candidate.exists(): + return candidate + + searched = '\n'.join(f' - {c}' for c in candidates) + raise FileNotFoundError(f'Checkpoint not found for: {rel_path}\nSearched:\n{searched}') + + +def _tensor_type_from_name(type_name: str): + module_name, _, class_name = type_name.rpartition('.') + module = torch + if module_name == 'torch.cuda': + module = torch.cuda + return getattr(module, class_name) + + + +@torch.inference_mode() +def make_crop_data_batch(render_size, ob_in_cams, mesh, rgb, depth, K, crop_ratio, xyz_map, normal_map=None, mesh_diameter=None, cfg=None, glctx=None, mesh_tensors=None, dataset:PoseRefinePairH5Dataset=None): + logging.info("Welcome make_crop_data_batch") + H,W = depth.shape[:2] + args = [] + method = 'box_3d' + tf_to_crops = compute_crop_window_tf_batch(pts=mesh.vertices, H=H, W=W, poses=ob_in_cams, K=K, crop_ratio=crop_ratio, out_size=(render_size[1], render_size[0]), method=method, mesh_diameter=mesh_diameter) + + logging.info("make tf_to_crops done") + + B = len(ob_in_cams) + poseA = torch.as_tensor(ob_in_cams, dtype=torch.float, device='cuda') + + bs = 512 + rgb_rs = [] + depth_rs = [] + normal_rs = [] + xyz_map_rs = [] + + bbox2d_crop = torch.as_tensor(np.array([0, 0, cfg['input_resize'][0]-1, cfg['input_resize'][1]-1]).reshape(2,2), device='cuda', dtype=torch.float) + bbox2d_ori = transform_pts(bbox2d_crop, tf_to_crops.inverse()).reshape(-1,4) + + for b in range(0,len(poseA),bs): + extra = {} + rgb_r, depth_r, normal_r = nvdiffrast_render(K=K, H=H, W=W, ob_in_cams=poseA[b:b+bs], context='cuda', get_normal=cfg['use_normal'], glctx=glctx, mesh_tensors=mesh_tensors, output_size=cfg['input_resize'], bbox2d=bbox2d_ori[b:b+bs], use_light=True, extra=extra) + rgb_rs.append(rgb_r) + depth_rs.append(depth_r[...,None]) + normal_rs.append(normal_r) + xyz_map_rs.append(extra['xyz_map']) + rgb_rs = torch.cat(rgb_rs, dim=0).permute(0,3,1,2) * 255 + depth_rs = torch.cat(depth_rs, dim=0).permute(0,3,1,2) #(B,1,H,W) + xyz_map_rs = torch.cat(xyz_map_rs, dim=0).permute(0,3,1,2) #(B,3,H,W) + Ks = torch.as_tensor(K, device='cuda', dtype=torch.float).reshape(1,3,3) + if cfg['use_normal']: + normal_rs = torch.cat(normal_rs, dim=0).permute(0,3,1,2) #(B,3,H,W) + + logging.info("render done") + + rgbBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(rgb, dtype=torch.float, device='cuda').permute(2,0,1)[None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='bilinear', align_corners=False) + if rgb_rs.shape[-2:]!=cfg['input_resize']: + rgbAs = kornia.geometry.transform.warp_perspective(rgb_rs, tf_to_crops, dsize=render_size, mode='bilinear', align_corners=False) + else: + rgbAs = rgb_rs + if xyz_map_rs.shape[-2:]!=cfg['input_resize']: + xyz_mapAs = kornia.geometry.transform.warp_perspective(xyz_map_rs, tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + else: + xyz_mapAs = xyz_map_rs + xyz_mapBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(xyz_map, device='cuda', dtype=torch.float).permute(2,0,1)[None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) #(B,3,H,W) + + if cfg['use_normal']: + normalAs = kornia.geometry.transform.warp_perspective(normal_rs, tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + normalBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(normal_map, dtype=torch.float, device='cuda').permute(2,0,1)[None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + else: + normalAs = None + normalBs = None + + logging.info("warp done") + + mesh_diameters = torch.ones((len(rgbAs)), dtype=torch.float, device='cuda')*mesh_diameter + pose_data = BatchPoseData(rgbAs=rgbAs, rgbBs=rgbBs, depthAs=None, depthBs=None, normalAs=normalAs, normalBs=normalBs, poseA=poseA, poseB=None, xyz_mapAs=xyz_mapAs, xyz_mapBs=xyz_mapBs, tf_to_crops=tf_to_crops, Ks=Ks, mesh_diameters=mesh_diameters) + pose_data = dataset.transform_batch(batch=pose_data, H_ori=H, W_ori=W, bound=1) + + logging.info("pose batch data done") + + return pose_data + + + +class PoseRefinePredictor: + def __init__(self,): + logging.info("welcome") + self.amp = True + self.run_name = "2023-10-28-18-33-37" + model_name = 'model_best.pth' + ckpt_path = _resolve_checkpoint_path( + f'checkpoints/OnePoseViaGen/FoundationPose/{self.run_name}/{model_name}' + ) + config_path = _resolve_checkpoint_path( + f'checkpoints/OnePoseViaGen/FoundationPose/{self.run_name}/config.yml' + ) + ckpt_dir = str(ckpt_path) + + self.cfg = OmegaConf.load(str(config_path)) + + self.cfg['ckpt_dir'] = ckpt_dir + self.cfg['enable_amp'] = True + + ########## Defaults, to be backward compatible + if 'use_normal' not in self.cfg: + self.cfg['use_normal'] = False + if 'use_mask' not in self.cfg: + self.cfg['use_mask'] = False + if 'use_BN' not in self.cfg: + self.cfg['use_BN'] = False + if 'c_in' not in self.cfg: + self.cfg['c_in'] = 4 + if 'crop_ratio' not in self.cfg or self.cfg['crop_ratio'] is None: + self.cfg['crop_ratio'] = 1.2 + if 'n_view' not in self.cfg: + self.cfg['n_view'] = 1 + if 'trans_rep' not in self.cfg: + self.cfg['trans_rep'] = 'tracknet' + if 'rot_rep' not in self.cfg: + self.cfg['rot_rep'] = 'axis_angle' + if 'zfar' not in self.cfg: + self.cfg['zfar'] = 3 + if 'normalize_xyz' not in self.cfg: + self.cfg['normalize_xyz'] = False + if isinstance(self.cfg['zfar'], str) and 'inf' in self.cfg['zfar'].lower(): + self.cfg['zfar'] = np.inf + if 'normal_uint8' not in self.cfg: + self.cfg['normal_uint8'] = False + logging.info(f"self.cfg: \n {OmegaConf.to_yaml(self.cfg)}") + + self.dataset = PoseRefinePairH5Dataset(cfg=self.cfg, h5_file='', mode='test') + self.model = RefineNet(cfg=self.cfg, c_in=self.cfg['c_in']).cuda() + + logging.info(f"Using pretrained model from {ckpt_dir}") + ckpt = torch.load(ckpt_dir) + if 'model' in ckpt: + ckpt = ckpt['model'] + self.model.load_state_dict(ckpt) + + self.model.cuda().eval() + logging.info("init done") + self.last_trans_update = None + self.last_rot_update = None + + + @torch.inference_mode() + def predict(self, rgb, depth, K, ob_in_cams, xyz_map, normal_map=None, get_vis=False, mesh=None, mesh_tensors=None, glctx=None, mesh_diameter=None, iteration=5): + prev_type_name = torch.tensor(0.0).type() + new_default = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor + torch.set_default_tensor_type(new_default) + try: + return self._predict_impl(rgb, depth, K, ob_in_cams, xyz_map, normal_map, get_vis, mesh, mesh_tensors, glctx, mesh_diameter, iteration) + finally: + torch.set_default_tensor_type(_tensor_type_from_name(prev_type_name)) + + def _predict_impl(self, rgb, depth, K, ob_in_cams, xyz_map, normal_map=None, get_vis=False, mesh=None, mesh_tensors=None, glctx=None, mesh_diameter=None, iteration=5): + ''' + @rgb: np array (H,W,3) + @ob_in_cams: np array (N,4,4) + ''' + logging.info(f'ob_in_cams:{ob_in_cams.shape}') + tf_to_center = np.eye(4) + ob_centered_in_cams = ob_in_cams + mesh_centered = mesh + + logging.info(f'self.cfg.use_normal:{self.cfg.use_normal}') + if not self.cfg.use_normal: + normal_map = None + + crop_ratio = self.cfg['crop_ratio'] + logging.info(f"trans_normalizer:{self.cfg['trans_normalizer']}, rot_normalizer:{self.cfg['rot_normalizer']}") + bs = 1024 + + B_in_cams = torch.as_tensor(ob_centered_in_cams, device='cuda', dtype=torch.float) + + + if mesh_tensors is None: + mesh_tensors = make_mesh_tensors(mesh_centered) + + rgb_tensor = torch.as_tensor(rgb, device='cuda', dtype=torch.float) + depth_tensor = torch.as_tensor(depth, device='cuda', dtype=torch.float) + xyz_map_tensor = torch.as_tensor(xyz_map, device='cuda', dtype=torch.float) + trans_normalizer = self.cfg['trans_normalizer'] + if not isinstance(trans_normalizer, float): + trans_normalizer = torch.as_tensor(list(trans_normalizer), device='cuda', dtype=torch.float).reshape(1,3) + + for _ in range(iteration): + logging.info("making cropped data") + pose_data = make_crop_data_batch(self.cfg.input_resize, B_in_cams, mesh_centered, rgb_tensor, depth_tensor, K, crop_ratio=crop_ratio, normal_map=normal_map, xyz_map=xyz_map_tensor, cfg=self.cfg, glctx=glctx, mesh_tensors=mesh_tensors, dataset=self.dataset, mesh_diameter=mesh_diameter) + B_in_cams = [] + for b in range(0, pose_data.rgbAs.shape[0], bs): + A = torch.cat([pose_data.rgbAs[b:b+bs].cuda(), pose_data.xyz_mapAs[b:b+bs].cuda()], dim=1).float() + B = torch.cat([pose_data.rgbBs[b:b+bs].cuda(), pose_data.xyz_mapBs[b:b+bs].cuda()], dim=1).float() + logging.info("forward start") + with torch.cuda.amp.autocast(enabled=self.amp): + output = self.model(A,B) + for k in output: + output[k] = output[k].float() + logging.info("forward done") + if self.cfg['trans_rep']=='tracknet': + if not self.cfg['normalize_xyz']: + trans_delta = torch.tanh(output["trans"])*trans_normalizer + else: + trans_delta = output["trans"] + + elif self.cfg['trans_rep']=='deepim': + def project_and_transform_to_crop(centers): + uvs = (pose_data.Ks[b:b+bs]@centers.reshape(-1,3,1)).reshape(-1,3) + uvs = uvs/uvs[:,2:3] + uvs = (pose_data.tf_to_crops[b:b+bs]@uvs.reshape(-1,3,1)).reshape(-1,3) + return uvs[:,:2] + + rot_delta = output["rot"] + z_pred = output['trans'][:,2]*pose_data.poseA[b:b+bs][...,2,3] + uvA_crop = project_and_transform_to_crop(pose_data.poseA[b:b+bs][...,:3,3]) + uv_pred_crop = uvA_crop + output['trans'][:,:2]*self.cfg['input_resize'][0] + uv_pred = transform_pts(uv_pred_crop, pose_data.tf_to_crops[b:b+bs].inverse().cuda()) + center_pred = torch.cat([uv_pred, torch.ones((len(rot_delta),1), dtype=torch.float, device='cuda')], dim=-1) + center_pred = (pose_data.Ks[b:b+bs].inverse().cuda()@center_pred.reshape(len(rot_delta),3,1)).reshape(len(rot_delta),3) * z_pred.reshape(len(rot_delta),1) + trans_delta = center_pred-pose_data.poseA[b:b+bs][...,:3,3] + + else: + trans_delta = output["trans"] + + if self.cfg['rot_rep']=='axis_angle': + rot_mat_delta = torch.tanh(output["rot"])*self.cfg['rot_normalizer'] + rot_mat_delta = so3_exp_map(rot_mat_delta).permute(0,2,1) + elif self.cfg['rot_rep']=='6d': + rot_mat_delta = rotation_6d_to_matrix(output['rot']).permute(0,2,1) + else: + raise RuntimeError + + if self.cfg['normalize_xyz']: + trans_delta *= (mesh_diameter/2) + + B_in_cam = egocentric_delta_pose_to_pose(pose_data.poseA[b:b+bs], trans_delta=trans_delta, rot_mat_delta=rot_mat_delta) + B_in_cams.append(B_in_cam) + + B_in_cams = torch.cat(B_in_cams, dim=0).reshape(len(ob_in_cams),4,4) + + B_in_cams_out = B_in_cams@torch.tensor(tf_to_center[None], device='cuda', dtype=torch.float) + torch.cuda.empty_cache() + self.last_trans_update = trans_delta + self.last_rot_update = rot_mat_delta + + if get_vis: + logging.info("get_vis...") + canvas = [] + padding = 2 + pose_data = make_crop_data_batch(self.cfg.input_resize, torch.as_tensor(ob_centered_in_cams), mesh_centered, rgb, depth, K, crop_ratio=crop_ratio, normal_map=normal_map, xyz_map=xyz_map_tensor, cfg=self.cfg, glctx=glctx, mesh_tensors=mesh_tensors, dataset=self.dataset, mesh_diameter=mesh_diameter) + for id in range(0, len(B_in_cams)): + rgbA_vis = (pose_data.rgbAs[id]*255).permute(1,2,0).data.cpu().numpy() + rgbB_vis = (pose_data.rgbBs[id]*255).permute(1,2,0).data.cpu().numpy() + row = [rgbA_vis, rgbB_vis] + H,W = rgbA_vis.shape[:2] + if pose_data.depthAs is not None: + depthA = pose_data.depthAs[id].data.cpu().numpy().reshape(H,W) + depthB = pose_data.depthBs[id].data.cpu().numpy().reshape(H,W) + elif pose_data.xyz_mapAs is not None: + depthA = pose_data.xyz_mapAs[id][2].data.cpu().numpy().reshape(H,W) + depthB = pose_data.xyz_mapBs[id][2].data.cpu().numpy().reshape(H,W) + zmin = min(depthA.min(), depthB.min()) + zmax = max(depthA.max(), depthB.max()) + depthA_vis = depth_to_vis(depthA, zmin=zmin, zmax=zmax, inverse=False) + depthB_vis = depth_to_vis(depthB, zmin=zmin, zmax=zmax, inverse=False) + row += [depthA_vis, depthB_vis] + if pose_data.normalAs is not None: + pass + row = make_grid_image(row, nrow=len(row), padding=padding, pad_value=255) + row = cv_draw_text(row, text=f'id:{id}', uv_top_left=(10,10), color=(0,255,0), fontScale=0.5) + canvas.append(row) + canvas = make_grid_image(canvas, nrow=1, padding=padding, pad_value=255) + + pose_data = make_crop_data_batch(self.cfg.input_resize, B_in_cams, mesh_centered, rgb, depth, K, crop_ratio=crop_ratio, normal_map=normal_map, xyz_map=xyz_map_tensor, cfg=self.cfg, glctx=glctx, mesh_tensors=mesh_tensors, dataset=self.dataset, mesh_diameter=mesh_diameter) + canvas_refined = [] + for id in range(0, len(B_in_cams)): + rgbA_vis = (pose_data.rgbAs[id]*255).permute(1,2,0).data.cpu().numpy() + rgbB_vis = (pose_data.rgbBs[id]*255).permute(1,2,0).data.cpu().numpy() + row = [rgbA_vis, rgbB_vis] + H,W = rgbA_vis.shape[:2] + if pose_data.depthAs is not None: + depthA = pose_data.depthAs[id].data.cpu().numpy().reshape(H,W) + depthB = pose_data.depthBs[id].data.cpu().numpy().reshape(H,W) + elif pose_data.xyz_mapAs is not None: + depthA = pose_data.xyz_mapAs[id][2].data.cpu().numpy().reshape(H,W) + depthB = pose_data.xyz_mapBs[id][2].data.cpu().numpy().reshape(H,W) + zmin = min(depthA.min(), depthB.min()) + zmax = max(depthA.max(), depthB.max()) + depthA_vis = depth_to_vis(depthA, zmin=zmin, zmax=zmax, inverse=False) + depthB_vis = depth_to_vis(depthB, zmin=zmin, zmax=zmax, inverse=False) + row += [depthA_vis, depthB_vis] + row = make_grid_image(row, nrow=len(row), padding=padding, pad_value=255) + canvas_refined.append(row) + + canvas_refined = make_grid_image(canvas_refined, nrow=1, padding=padding, pad_value=255) + canvas = make_grid_image([canvas, canvas_refined], nrow=2, padding=padding, pad_value=255) + torch.cuda.empty_cache() + return B_in_cams_out, canvas + + return B_in_cams_out, None diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/learning/training/predict_score.py b/OVOW/engine/oneposeviagen/fpose/fpose/learning/training/predict_score.py new file mode 100644 index 0000000000000000000000000000000000000000..ebfb8ec2066f8d62a07ada296730b5276fb7156f --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/learning/training/predict_score.py @@ -0,0 +1,265 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import functools +import os,sys,kornia +import time +from pathlib import Path +import numpy as np +import torch +import torch.distributed as dist +from omegaconf import OmegaConf +from tqdm import tqdm +code_dir = Path(__file__).resolve().parent +# Make `learning.*` imports resolvable regardless of caller CWD/PYTHONPATH. +fpose_pkg_dir = code_dir.parent.parent # .../fpose/fpose +if str(fpose_pkg_dir) not in sys.path: + sys.path.append(str(fpose_pkg_dir)) +from learning.datasets.h5_dataset import * +from learning.models.score_network import * +from learning.datasets.pose_dataset import * +from Utils import * +from datareader import * + + +def _find_onepose_repo_root() -> Path | None: + p = Path(__file__).resolve() + for parent in p.parents: + if parent.name == 'OnePoseviaGen': + return parent + return None + + +def _resolve_checkpoint_path(rel_path: str) -> Path: + rel = Path(rel_path) + candidates: list[Path] = [] + + ckpt_root = os.environ.get('ONEPOSEVIA_CHECKPOINT_ROOT') + if ckpt_root: + candidates.append(Path(ckpt_root) / rel) + + onepose_root = _find_onepose_repo_root() + if onepose_root is not None: + candidates.append(onepose_root / rel) + + candidates.append(rel) + + for candidate in candidates: + if candidate.exists(): + return candidate + + searched = '\n'.join(f' - {c}' for c in candidates) + raise FileNotFoundError(f'Checkpoint not found for: {rel_path}\nSearched:\n{searched}') + + +def vis_batch_data_scores(pose_data, ids, scores, pad_margin=5): + assert len(scores)==len(ids) + canvas = [] + for id in ids: + rgbA_vis = (pose_data.rgbAs[id]*255).permute(1,2,0).data.cpu().numpy() + rgbB_vis = (pose_data.rgbBs[id]*255).permute(1,2,0).data.cpu().numpy() + H,W = rgbA_vis.shape[:2] + zmin = pose_data.depthAs[id].data.cpu().numpy().reshape(H,W).min() + zmax = pose_data.depthAs[id].data.cpu().numpy().reshape(H,W).max() + depthA_vis = depth_to_vis(pose_data.depthAs[id].data.cpu().numpy().reshape(H,W), zmin=zmin, zmax=zmax, inverse=False) + depthB_vis = depth_to_vis(pose_data.depthBs[id].data.cpu().numpy().reshape(H,W), zmin=zmin, zmax=zmax, inverse=False) + if pose_data.normalAs is not None: + pass + pad = np.ones((rgbA_vis.shape[0],pad_margin,3))*255 + if pose_data.normalAs is not None: + pass + else: + row = np.concatenate([rgbA_vis, pad, depthA_vis, pad, rgbB_vis, pad, depthB_vis], axis=1) + s = 100/row.shape[0] + row = cv2.resize(row, fx=s, fy=s, dsize=None) + row = cv_draw_text(row, text=f'id:{id}, score:{scores[id]:.3f}', uv_top_left=(10,10), color=(0,255,0), fontScale=0.5) + canvas.append(row) + pad = np.ones((pad_margin, row.shape[1], 3))*255 + canvas.append(pad) + canvas = np.concatenate(canvas, axis=0).astype(np.uint8) + return canvas + + + +@torch.no_grad() +def make_crop_data_batch(render_size, ob_in_cams, mesh, rgb, depth, K, crop_ratio, normal_map=None, mesh_diameter=None, glctx=None, mesh_tensors=None, dataset:TripletH5Dataset=None, cfg=None): + logging.info("Welcome make_crop_data_batch") + H,W = depth.shape[:2] + + args = [] + method = 'box_3d' + tf_to_crops = compute_crop_window_tf_batch(pts=mesh.vertices, H=H, W=W, poses=ob_in_cams, K=K, crop_ratio=crop_ratio, out_size=(render_size[1], render_size[0]), method=method, mesh_diameter=mesh_diameter) + logging.info("make tf_to_crops done") + + B = len(ob_in_cams) + poseAs = torch.as_tensor(ob_in_cams, dtype=torch.float, device='cuda') + + bs = 512 + rgb_rs = [] + depth_rs = [] + xyz_map_rs = [] + + bbox2d_crop = torch.as_tensor(np.array([0, 0, cfg['input_resize'][0]-1, cfg['input_resize'][1]-1]).reshape(2,2), device='cuda', dtype=torch.float) + bbox2d_ori = transform_pts(bbox2d_crop, tf_to_crops.inverse()[:,None]).reshape(-1,4) + + for b in range(0,len(ob_in_cams),bs): + extra = {} + rgb_r, depth_r, normal_r = nvdiffrast_render(K=K, H=H, W=W, ob_in_cams=poseAs[b:b+bs], context='cuda', get_normal=cfg['use_normal'], glctx=glctx, mesh_tensors=mesh_tensors, output_size=cfg['input_resize'], bbox2d=bbox2d_ori[b:b+bs], use_light=True, extra=extra) + rgb_rs.append(rgb_r) + depth_rs.append(depth_r[...,None]) + xyz_map_rs.append(extra['xyz_map']) + + rgb_rs = torch.cat(rgb_rs, dim=0).permute(0,3,1,2) * 255 + depth_rs = torch.cat(depth_rs, dim=0).permute(0,3,1,2) + xyz_map_rs = torch.cat(xyz_map_rs, dim=0).permute(0,3,1,2) #(B,3,H,W) + logging.info("render done") + + rgbBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(rgb, dtype=torch.float, device='cuda').permute(2,0,1)[None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='bilinear', align_corners=False) + depthBs = kornia.geometry.transform.warp_perspective(torch.as_tensor(depth, dtype=torch.float, device='cuda')[None,None].expand(B,-1,-1,-1), tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + if rgb_rs.shape[-2:]!=cfg['input_resize']: + rgbAs = kornia.geometry.transform.warp_perspective(rgb_rs, tf_to_crops, dsize=render_size, mode='bilinear', align_corners=False) + depthAs = kornia.geometry.transform.warp_perspective(depth_rs, tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + else: + rgbAs = rgb_rs + depthAs = depth_rs + + if xyz_map_rs.shape[-2:]!=cfg['input_resize']: + xyz_mapAs = kornia.geometry.transform.warp_perspective(xyz_map_rs, tf_to_crops, dsize=render_size, mode='nearest', align_corners=False) + else: + xyz_mapAs = xyz_map_rs + + normalAs = None + normalBs = None + + Ks = torch.as_tensor(K, dtype=torch.float).reshape(1,3,3).expand(len(rgbAs),3,3) + mesh_diameters = torch.ones((len(rgbAs)), dtype=torch.float, device='cuda')*mesh_diameter + + pose_data = BatchPoseData(rgbAs=rgbAs, rgbBs=rgbBs, depthAs=depthAs, depthBs=depthBs, normalAs=normalAs, normalBs=normalBs, poseA=poseAs, xyz_mapAs=xyz_mapAs, tf_to_crops=tf_to_crops, Ks=Ks, mesh_diameters=mesh_diameters) + pose_data = dataset.transform_batch(pose_data, H_ori=H, W_ori=W, bound=1) + + logging.info("pose batch data done") + + return pose_data + + +class ScorePredictor: + def __init__(self, amp=True): + self.amp = amp + self.run_name = "2024-01-11-20-02-45" + + model_name = 'model_best.pth' + ckpt_path = _resolve_checkpoint_path( + f'checkpoints/OnePoseViaGen/FoundationPose/{self.run_name}/{model_name}' + ) + config_path = _resolve_checkpoint_path( + f'checkpoints/OnePoseViaGen/FoundationPose/{self.run_name}/config.yml' + ) + ckpt_dir = str(ckpt_path) + + self.cfg = OmegaConf.load(str(config_path)) + + self.cfg['ckpt_dir'] = ckpt_dir + self.cfg['enable_amp'] = True + + ########## Defaults, to be backward compatible + if 'use_normal' not in self.cfg: + self.cfg['use_normal'] = False + if 'use_BN' not in self.cfg: + self.cfg['use_BN'] = False + if 'zfar' not in self.cfg: + self.cfg['zfar'] = np.inf + if 'c_in' not in self.cfg: + self.cfg['c_in'] = 4 + if 'normalize_xyz' not in self.cfg: + self.cfg['normalize_xyz'] = False + if 'crop_ratio' not in self.cfg or self.cfg['crop_ratio'] is None: + self.cfg['crop_ratio'] = 1.2 + + logging.info(f"self.cfg: \n {OmegaConf.to_yaml(self.cfg)}") + + self.dataset = ScoreMultiPairH5Dataset(cfg=self.cfg, mode='test', h5_file=None, max_num_key=1) + self.model = ScoreNetMultiPair(cfg=self.cfg, c_in=self.cfg['c_in']).cuda() + + logging.info(f"Using pretrained model from {ckpt_dir}") + ckpt = torch.load(ckpt_dir) + if 'model' in ckpt: + ckpt = ckpt['model'] + self.model.load_state_dict(ckpt) + + self.model.cuda().eval() + logging.info("init done") + + + @torch.inference_mode() + def predict(self, rgb, depth, K, ob_in_cams, normal_map=None, get_vis=False, mesh=None, mesh_tensors=None, glctx=None, mesh_diameter=None): + ''' + @rgb: np array (H,W,3) + ''' + logging.info(f"ob_in_cams:{ob_in_cams.shape}") + ob_in_cams = torch.as_tensor(ob_in_cams, dtype=torch.float, device='cuda') + + logging.info(f'self.cfg.use_normal:{self.cfg.use_normal}') + if not self.cfg.use_normal: + normal_map = None + + logging.info("making cropped data") + + if mesh_tensors is None: + mesh_tensors = make_mesh_tensors(mesh) + + rgb = torch.as_tensor(rgb, device='cuda', dtype=torch.float) + depth = torch.as_tensor(depth, device='cuda', dtype=torch.float) + + pose_data = make_crop_data_batch(self.cfg.input_resize, ob_in_cams, mesh, rgb, depth, K, crop_ratio=self.cfg['crop_ratio'], glctx=glctx, mesh_tensors=mesh_tensors, dataset=self.dataset, cfg=self.cfg, mesh_diameter=mesh_diameter) + + def find_best_among_pairs(pose_data:BatchPoseData): + logging.info(f'pose_data.rgbAs.shape[0]: {pose_data.rgbAs.shape[0]}') + ids = [] + scores = [] + bs = pose_data.rgbAs.shape[0] + for b in range(0, pose_data.rgbAs.shape[0], bs): + A = torch.cat([pose_data.rgbAs[b:b+bs].cuda(), pose_data.xyz_mapAs[b:b+bs].cuda()], dim=1).float() + B = torch.cat([pose_data.rgbBs[b:b+bs].cuda(), pose_data.xyz_mapBs[b:b+bs].cuda()], dim=1).float() + if pose_data.normalAs is not None: + A = torch.cat([A, pose_data.normalAs.cuda().float()], dim=1) + B = torch.cat([B, pose_data.normalBs.cuda().float()], dim=1) + with torch.cuda.amp.autocast(enabled=self.amp): + output = self.model(A, B, L=len(A)) + scores_cur = output["score_logit"].float().reshape(-1) + ids.append(scores_cur.argmax()+b) + scores.append(scores_cur) + ids = torch.stack(ids, dim=0).reshape(-1) + scores = torch.cat(scores, dim=0).reshape(-1) + return ids, scores + + pose_data_iter = pose_data + global_ids = torch.arange(len(ob_in_cams), device='cuda', dtype=torch.long) + scores_global = torch.zeros((len(ob_in_cams)), dtype=torch.float, device='cuda') + + while 1: + ids, scores = find_best_among_pairs(pose_data_iter) + if len(ids)==1: + scores_global[global_ids] = scores + 100 + break + global_ids = global_ids[ids] + pose_data_iter = pose_data.select_by_indices(global_ids) + + scores = scores_global + + logging.info(f'forward done') + torch.cuda.empty_cache() + + if get_vis: + logging.info("get_vis...") + canvas = [] + ids = scores.argsort(descending=True) + canvas = vis_batch_data_scores(pose_data, ids=ids, scores=scores) + return scores, canvas + + return scores, None diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/learning/training/training_config.py b/OVOW/engine/oneposeviagen/fpose/fpose/learning/training/training_config.py new file mode 100644 index 0000000000000000000000000000000000000000..9d689c65da3fd03e9a32b5df332fcdd70af9c67d --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/learning/training/training_config.py @@ -0,0 +1,102 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys +from dataclasses import dataclass, field +from typing import List, Optional, Tuple,Union +import numpy as np +import omegaconf +import torch + + +@dataclass +class TrainingConfig(omegaconf.dictconfig.DictConfig): + input_resize: tuple = (160, 160) + normalize_xyz:Optional[bool] = True + use_mask:Optional[bool] = False + crop_ratio:Optional[float] = None + split_objects_across_gpus: bool = True + max_num_key: Optional[int] = None + use_normal:bool = False + n_view:int = 1 + zfar:float = np.inf + c_in:int = 6 + train_num_pair:Optional[int] = None + make_pair_online:Optional[bool] = False + render_backend:Optional[str] = 'nvdiffrast' + + # Run management + run_id: Optional[str] = None + exp_name:Optional[str] = None + resume_run_id: Optional[str] = None + save_dir: Optional[str] = None + batch_size: int = 64 + epoch_size: int = 115200 + val_size: int = 1280 + n_epochs: int = 25 + save_epoch_interval: int = 100 + n_dataloader_workers: int = 20 + n_rendering_workers: int = 1 + gradient_max_norm:float = np.inf + max_step_per_epoch: Optional[int] = 25000 + + # Network + use_BN:bool = True + loss_type:Optional[str] = 'pairwise_valid' + + # Optimizer + optimizer: str = "adam" + weight_decay: float = 0.0 + clip_grad_norm: float = np.inf + lr: float = 0.0001 + warmup_step: int = -1 # -1 means disable + n_epochs_warmup: int = 1 + + # Visualization + vis_interval: Optional[int] = 1000 + + debug: Optional[bool] = None + + + +@dataclass +class TrainRefinerConfig: + # Datasets + input_resize: tuple = (160, 160) #(W,H) + crop_ratio:Optional[float] = None + max_num_key: Optional[int] = None + use_normal:bool = False + use_mask:Optional[bool] = False + normal_uint8:bool = False + normalize_xyz:Optional[bool] = True + trans_normalizer:Optional[list] = None + rot_normalizer:Optional[float] = None + c_in:int = 6 + n_view:int = 1 + zfar:float = np.inf + trans_rep:str = 'tracknet' # tracknet/deepim + rot_rep:Optional[str] = 'axis_angle' # 6d/axis_angle + save_dir: Optional[str] = None + + # Run management + run_id: Optional[str] = None + exp_name:Optional[str] = None + batch_size: int = 64 + use_BN:bool = True + optimizer: str = "adam" + weight_decay: float = 0.0 + clip_grad_norm: float = np.inf + lr: float = 0.0001 + warmup_step: int = -1 + loss_type:str = 'l2' # l1/l2/add + + vis_interval: Optional[int] = 1000 + debug: Optional[bool] = None + + diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/CMakeLists.txt b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..7c8a9a5cca867d327b7495d98c5cf13bd15fcbe7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/CMakeLists.txt @@ -0,0 +1,25 @@ +cmake_minimum_required(VERSION 3.15) +project(mycpp) + + +set(CMAKE_BUILD_TYPE Release) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -fopenmp -g3 -O3") + + +find_package(Boost REQUIRED COMPONENTS system program_options) +find_package(OpenMP REQUIRED) +find_package(Eigen3 REQUIRED) +find_package(pybind11 REQUIRED) + +include_directories( + include + ${BLAS_INCLUDE_DIR} +) + +file(GLOB MY_SRC ${PROJECT_SOURCE_DIR}/src/*.cpp) + +set(PYBIND11_CPP_STANDARD -std=c++14) + +pybind11_add_module(mycpp src/app/pybind_api.cpp ${MY_SRC}) +target_link_libraries(mycpp PRIVATE ${Boost_LIBRARIES} ${OpenMP_CXX_FLAGS} Eigen3::Eigen) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeCache.txt b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeCache.txt new file mode 100644 index 0000000000000000000000000000000000000000..0cc9c62b56b826ecbabc261652eac09254333d8b --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeCache.txt @@ -0,0 +1,489 @@ +# This is the CMakeCache file. +# For build in directory: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build +# It was generated by CMake: /usr/bin/cmake +# You can edit this file to change values found and used by cmake. +# If you do not want to change any of the values, simply exit the editor. +# If you do want to change a value, simply edit, save, and exit the editor. +# The syntax for the file is as follows: +# KEY:TYPE=VALUE +# KEY is the name of a variable in the cache. +# TYPE is a hint to GUIs for the type of VALUE, DO NOT EDIT TYPE!. +# VALUE is the current value for the KEY. + +######################## +# EXTERNAL cache entries +######################## + +//The directory containing a CMake configuration file for Boost. +Boost_DIR:PATH=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/Boost-1.82.0 + +//Path to a file. +Boost_INCLUDE_DIR:PATH=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include + +Boost_PROGRAM_OPTIONS_LIBRARY_RELEASE:STRING=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/libboost_program_options.so.1.82.0 + +Boost_SYSTEM_LIBRARY_RELEASE:STRING=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/libboost_system.so.1.82.0 + +//Path to a program. +CMAKE_ADDR2LINE:FILEPATH=/usr/bin/addr2line + +//Path to a program. +CMAKE_AR:FILEPATH=/usr/bin/ar + +//Choose the type of build, options are: None Debug Release RelWithDebInfo +// MinSizeRel ... +CMAKE_BUILD_TYPE:STRING= + +//Enable/Disable color output during build. +CMAKE_COLOR_MAKEFILE:BOOL=ON + +//CXX compiler +CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/c++ + +//A wrapper around 'ar' adding the appropriate '--plugin' option +// for the GCC compiler +CMAKE_CXX_COMPILER_AR:FILEPATH=/usr/bin/gcc-ar-11 + +//A wrapper around 'ranlib' adding the appropriate '--plugin' option +// for the GCC compiler +CMAKE_CXX_COMPILER_RANLIB:FILEPATH=/usr/bin/gcc-ranlib-11 + +//Flags used by the CXX compiler during all build types. +CMAKE_CXX_FLAGS:STRING= + +//Flags used by the CXX compiler during DEBUG builds. +CMAKE_CXX_FLAGS_DEBUG:STRING=-g + +//Flags used by the CXX compiler during MINSIZEREL builds. +CMAKE_CXX_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG + +//Flags used by the CXX compiler during RELEASE builds. +CMAKE_CXX_FLAGS_RELEASE:STRING=-O3 -DNDEBUG + +//Flags used by the CXX compiler during RELWITHDEBINFO builds. +CMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG + +//C compiler +CMAKE_C_COMPILER:FILEPATH=/usr/bin/cc + +//A wrapper around 'ar' adding the appropriate '--plugin' option +// for the GCC compiler +CMAKE_C_COMPILER_AR:FILEPATH=/usr/bin/gcc-ar-11 + +//A wrapper around 'ranlib' adding the appropriate '--plugin' option +// for the GCC compiler +CMAKE_C_COMPILER_RANLIB:FILEPATH=/usr/bin/gcc-ranlib-11 + +//Flags used by the C compiler during all build types. +CMAKE_C_FLAGS:STRING= + +//Flags used by the C compiler during DEBUG builds. +CMAKE_C_FLAGS_DEBUG:STRING=-g + +//Flags used by the C compiler during MINSIZEREL builds. +CMAKE_C_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG + +//Flags used by the C compiler during RELEASE builds. +CMAKE_C_FLAGS_RELEASE:STRING=-O3 -DNDEBUG + +//Flags used by the C compiler during RELWITHDEBINFO builds. +CMAKE_C_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG + +//Path to a program. +CMAKE_DLLTOOL:FILEPATH=CMAKE_DLLTOOL-NOTFOUND + +//Flags used by the linker during all build types. +CMAKE_EXE_LINKER_FLAGS:STRING= + +//Flags used by the linker during DEBUG builds. +CMAKE_EXE_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during MINSIZEREL builds. +CMAKE_EXE_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during RELEASE builds. +CMAKE_EXE_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during RELWITHDEBINFO builds. +CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//Enable/Disable output of compile commands during generation. +CMAKE_EXPORT_COMPILE_COMMANDS:BOOL= + +//Install path prefix, prepended onto install directories. +CMAKE_INSTALL_PREFIX:PATH=/usr/local + +//Path to a program. +CMAKE_LINKER:FILEPATH=/usr/bin/ld + +//Path to a program. +CMAKE_MAKE_PROGRAM:FILEPATH=/usr/bin/gmake + +//Flags used by the linker during the creation of modules during +// all build types. +CMAKE_MODULE_LINKER_FLAGS:STRING= + +//Flags used by the linker during the creation of modules during +// DEBUG builds. +CMAKE_MODULE_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during the creation of modules during +// MINSIZEREL builds. +CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during the creation of modules during +// RELEASE builds. +CMAKE_MODULE_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during the creation of modules during +// RELWITHDEBINFO builds. +CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//Path to a program. +CMAKE_NM:FILEPATH=/usr/bin/nm + +//Path to a program. +CMAKE_OBJCOPY:FILEPATH=/usr/bin/objcopy + +//Path to a program. +CMAKE_OBJDUMP:FILEPATH=/usr/bin/objdump + +//Value Computed by CMake +CMAKE_PROJECT_DESCRIPTION:STATIC= + +//Value Computed by CMake +CMAKE_PROJECT_HOMEPAGE_URL:STATIC= + +//Value Computed by CMake +CMAKE_PROJECT_NAME:STATIC=mycpp + +//Path to a program. +CMAKE_RANLIB:FILEPATH=/usr/bin/ranlib + +//Path to a program. +CMAKE_READELF:FILEPATH=/usr/bin/readelf + +//Flags used by the linker during the creation of shared libraries +// during all build types. +CMAKE_SHARED_LINKER_FLAGS:STRING= + +//Flags used by the linker during the creation of shared libraries +// during DEBUG builds. +CMAKE_SHARED_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during the creation of shared libraries +// during MINSIZEREL builds. +CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during the creation of shared libraries +// during RELEASE builds. +CMAKE_SHARED_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during the creation of shared libraries +// during RELWITHDEBINFO builds. +CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//If set, runtime paths are not added when installing shared libraries, +// but are added when building. +CMAKE_SKIP_INSTALL_RPATH:BOOL=NO + +//If set, runtime paths are not added when using shared libraries. +CMAKE_SKIP_RPATH:BOOL=NO + +//Flags used by the linker during the creation of static libraries +// during all build types. +CMAKE_STATIC_LINKER_FLAGS:STRING= + +//Flags used by the linker during the creation of static libraries +// during DEBUG builds. +CMAKE_STATIC_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during the creation of static libraries +// during MINSIZEREL builds. +CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during the creation of static libraries +// during RELEASE builds. +CMAKE_STATIC_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during the creation of static libraries +// during RELWITHDEBINFO builds. +CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//Path to a program. +CMAKE_STRIP:FILEPATH=/usr/bin/strip + +//If this value is on, makefiles will be generated without the +// .SILENT directive, and all commands will be echoed to the console +// during the make. This is useful for debugging only. With Visual +// Studio IDE projects all commands are done without /nologo. +CMAKE_VERBOSE_MAKEFILE:BOOL=FALSE + +//The directory containing a CMake configuration file for Eigen3. +Eigen3_DIR:PATH=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/share/eigen3/cmake + +//CXX compiler flags for OpenMP parallelization +OpenMP_CXX_FLAGS:STRING=-fopenmp + +//CXX compiler libraries for OpenMP parallelization +OpenMP_CXX_LIB_NAMES:STRING=gomp;pthread + +//C compiler flags for OpenMP parallelization +OpenMP_C_FLAGS:STRING=-fopenmp + +//C compiler libraries for OpenMP parallelization +OpenMP_C_LIB_NAMES:STRING=gomp;pthread + +//Path to the gomp library for OpenMP +OpenMP_gomp_LIBRARY:FILEPATH=/usr/lib/gcc/x86_64-linux-gnu/11/libgomp.so + +//Path to the pthread library for OpenMP +OpenMP_pthread_LIBRARY:FILEPATH=/usr/lib/x86_64-linux-gnu/libpthread.a + +//Overwrite cached values read from Python library (classic search). +// Turn off if cross-compiling and manually setting these values. +PYBIND11_PYTHONLIBS_OVERWRITE:BOOL=ON + +//Python version to use for compiling modules +PYBIND11_PYTHON_VERSION:STRING= + +//Path to a program. +PYTHON_EXECUTABLE:FILEPATH=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python + +//Path to a library. +PYTHON_LIBRARY:FILEPATH=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/libpython3.11.so + +//The directory containing a CMake configuration file for boost_headers. +boost_headers_DIR:PATH=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/boost_headers-1.82.0 + +//The directory containing a CMake configuration file for boost_program_options. +boost_program_options_DIR:PATH=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/boost_program_options-1.82.0 + +//The directory containing a CMake configuration file for boost_system. +boost_system_DIR:PATH=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/boost_system-1.82.0 + +//Value Computed by CMake +mycpp_BINARY_DIR:STATIC=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build + +//Value Computed by CMake +mycpp_IS_TOP_LEVEL:STATIC=ON + +//Value Computed by CMake +mycpp_SOURCE_DIR:STATIC=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp + +//The directory containing a CMake configuration file for pybind11. +pybind11_DIR:PATH=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/share/cmake/pybind11 + + +######################## +# INTERNAL cache entries +######################## + +//ADVANCED property for variable: Boost_DIR +Boost_DIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_ADDR2LINE +CMAKE_ADDR2LINE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_AR +CMAKE_AR-ADVANCED:INTERNAL=1 +//This is the directory where this CMakeCache.txt was created +CMAKE_CACHEFILE_DIR:INTERNAL=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build +//Major version of cmake used to create the current loaded cache +CMAKE_CACHE_MAJOR_VERSION:INTERNAL=3 +//Minor version of cmake used to create the current loaded cache +CMAKE_CACHE_MINOR_VERSION:INTERNAL=22 +//Patch version of cmake used to create the current loaded cache +CMAKE_CACHE_PATCH_VERSION:INTERNAL=1 +//ADVANCED property for variable: CMAKE_COLOR_MAKEFILE +CMAKE_COLOR_MAKEFILE-ADVANCED:INTERNAL=1 +//Path to CMake executable. +CMAKE_COMMAND:INTERNAL=/usr/bin/cmake +//Path to cpack program executable. +CMAKE_CPACK_COMMAND:INTERNAL=/usr/bin/cpack +//Path to ctest program executable. +CMAKE_CTEST_COMMAND:INTERNAL=/usr/bin/ctest +//ADVANCED property for variable: CMAKE_CXX_COMPILER +CMAKE_CXX_COMPILER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_COMPILER_AR +CMAKE_CXX_COMPILER_AR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_COMPILER_RANLIB +CMAKE_CXX_COMPILER_RANLIB-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS +CMAKE_CXX_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_DEBUG +CMAKE_CXX_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_MINSIZEREL +CMAKE_CXX_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELEASE +CMAKE_CXX_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELWITHDEBINFO +CMAKE_CXX_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_COMPILER +CMAKE_C_COMPILER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_COMPILER_AR +CMAKE_C_COMPILER_AR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_COMPILER_RANLIB +CMAKE_C_COMPILER_RANLIB-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS +CMAKE_C_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_DEBUG +CMAKE_C_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_MINSIZEREL +CMAKE_C_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_RELEASE +CMAKE_C_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_RELWITHDEBINFO +CMAKE_C_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_DLLTOOL +CMAKE_DLLTOOL-ADVANCED:INTERNAL=1 +//Executable file format +CMAKE_EXECUTABLE_FORMAT:INTERNAL=ELF +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS +CMAKE_EXE_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_DEBUG +CMAKE_EXE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_MINSIZEREL +CMAKE_EXE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELEASE +CMAKE_EXE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXPORT_COMPILE_COMMANDS +CMAKE_EXPORT_COMPILE_COMMANDS-ADVANCED:INTERNAL=1 +//Name of external makefile project generator. +CMAKE_EXTRA_GENERATOR:INTERNAL= +//Name of generator. +CMAKE_GENERATOR:INTERNAL=Unix Makefiles +//Generator instance identifier. +CMAKE_GENERATOR_INSTANCE:INTERNAL= +//Name of generator platform. +CMAKE_GENERATOR_PLATFORM:INTERNAL= +//Name of generator toolset. +CMAKE_GENERATOR_TOOLSET:INTERNAL= +//Source directory with the top level CMakeLists.txt file for this +// project +CMAKE_HOME_DIRECTORY:INTERNAL=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp +//Install .so files without execute permission. +CMAKE_INSTALL_SO_NO_EXE:INTERNAL=1 +//ADVANCED property for variable: CMAKE_LINKER +CMAKE_LINKER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MAKE_PROGRAM +CMAKE_MAKE_PROGRAM-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS +CMAKE_MODULE_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_DEBUG +CMAKE_MODULE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL +CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELEASE +CMAKE_MODULE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_NM +CMAKE_NM-ADVANCED:INTERNAL=1 +//number of local generators +CMAKE_NUMBER_OF_MAKEFILES:INTERNAL=1 +//ADVANCED property for variable: CMAKE_OBJCOPY +CMAKE_OBJCOPY-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_OBJDUMP +CMAKE_OBJDUMP-ADVANCED:INTERNAL=1 +//Platform information initialized +CMAKE_PLATFORM_INFO_INITIALIZED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_RANLIB +CMAKE_RANLIB-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_READELF +CMAKE_READELF-ADVANCED:INTERNAL=1 +//Path to CMake installation. +CMAKE_ROOT:INTERNAL=/usr/share/cmake-3.22 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS +CMAKE_SHARED_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_DEBUG +CMAKE_SHARED_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL +CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELEASE +CMAKE_SHARED_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SKIP_INSTALL_RPATH +CMAKE_SKIP_INSTALL_RPATH-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SKIP_RPATH +CMAKE_SKIP_RPATH-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS +CMAKE_STATIC_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_DEBUG +CMAKE_STATIC_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL +CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELEASE +CMAKE_STATIC_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STRIP +CMAKE_STRIP-ADVANCED:INTERNAL=1 +//uname command +CMAKE_UNAME:INTERNAL=/usr/bin/uname +//ADVANCED property for variable: CMAKE_VERBOSE_MAKEFILE +CMAKE_VERBOSE_MAKEFILE-ADVANCED:INTERNAL=1 +//Details about finding Boost +FIND_PACKAGE_MESSAGE_DETAILS_Boost:INTERNAL=[/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/Boost-1.82.0/BoostConfig.cmake][cfound components: system program_options ][v1.82.0()] +//Details about finding OpenMP +FIND_PACKAGE_MESSAGE_DETAILS_OpenMP:INTERNAL=[TRUE][TRUE][c ][v4.5()] +//Details about finding OpenMP_C +FIND_PACKAGE_MESSAGE_DETAILS_OpenMP_C:INTERNAL=[-fopenmp][/usr/lib/gcc/x86_64-linux-gnu/11/libgomp.so][/usr/lib/x86_64-linux-gnu/libpthread.a][v4.5()] +//Details about finding OpenMP_CXX +FIND_PACKAGE_MESSAGE_DETAILS_OpenMP_CXX:INTERNAL=[-fopenmp][/usr/lib/gcc/x86_64-linux-gnu/11/libgomp.so][/usr/lib/x86_64-linux-gnu/libpthread.a][v4.5()] +//Details about finding PYTHON +FIND_PACKAGE_MESSAGE_DETAILS_PYTHON:INTERNAL=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python3.11.16 +//Details about finding PythonInterp +FIND_PACKAGE_MESSAGE_DETAILS_PythonInterp:INTERNAL=[/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python][v3.11.16(3.9)] +//Test HAS_FLTO_AUTO +HAS_FLTO_AUTO:INTERNAL=1 +//Result of TRY_COMPILE +OpenMP_COMPILE_RESULT_CXX_fopenmp:INTERNAL=TRUE +//Result of TRY_COMPILE +OpenMP_COMPILE_RESULT_C_fopenmp:INTERNAL=TRUE +//ADVANCED property for variable: OpenMP_CXX_FLAGS +OpenMP_CXX_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: OpenMP_CXX_LIB_NAMES +OpenMP_CXX_LIB_NAMES-ADVANCED:INTERNAL=1 +//CXX compiler's OpenMP specification date +OpenMP_CXX_SPEC_DATE:INTERNAL=201511 +//ADVANCED property for variable: OpenMP_C_FLAGS +OpenMP_C_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: OpenMP_C_LIB_NAMES +OpenMP_C_LIB_NAMES-ADVANCED:INTERNAL=1 +//C compiler's OpenMP specification date +OpenMP_C_SPEC_DATE:INTERNAL=201511 +//Result of TRY_COMPILE +OpenMP_SPECTEST_CXX_:INTERNAL=TRUE +//Result of TRY_COMPILE +OpenMP_SPECTEST_C_:INTERNAL=TRUE +//ADVANCED property for variable: OpenMP_gomp_LIBRARY +OpenMP_gomp_LIBRARY-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: OpenMP_pthread_LIBRARY +OpenMP_pthread_LIBRARY-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: PYTHON_EXECUTABLE +PYTHON_EXECUTABLE-ADVANCED:INTERNAL=1 +PYTHON_INCLUDE_DIRS:INTERNAL=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11 +PYTHON_IS_DEBUG:INTERNAL=0 +PYTHON_LIBRARIES:INTERNAL=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/libpython3.11.so +//ADVANCED property for variable: PYTHON_LIBRARY +PYTHON_LIBRARY-ADVANCED:INTERNAL=1 +PYTHON_MODULE_DEBUG_POSTFIX:INTERNAL= +PYTHON_MODULE_EXTENSION:INTERNAL=.cpython-311-x86_64-linux-gnu.so +PYTHON_MODULE_PREFIX:INTERNAL= +PYTHON_VERSION:INTERNAL=3.11.16 +PYTHON_VERSION_MAJOR:INTERNAL=3 +PYTHON_VERSION_MINOR:INTERNAL=11 +Python_ADDITIONAL_VERSIONS:INTERNAL=3.15;3.14;3.13;3.12;3.11;3.10;3.9 +_PYBIND11_CROSSCOMPILING:INTERNAL=OFF +_Python:INTERNAL=PYTHON +//ADVANCED property for variable: boost_headers_DIR +boost_headers_DIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: boost_program_options_DIR +boost_program_options_DIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: boost_system_DIR +boost_system_DIR-ADVANCED:INTERNAL=1 +//Directories where pybind11 and possibly Python headers are located +pybind11_INCLUDE_DIRS:INTERNAL=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include;/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11 + diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CMakeCCompiler.cmake b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CMakeCCompiler.cmake new file mode 100644 index 0000000000000000000000000000000000000000..488ad37510279ee3a1dc535c7ccd5a2cf9a69d5b --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CMakeCCompiler.cmake @@ -0,0 +1,72 @@ +set(CMAKE_C_COMPILER "/usr/bin/cc") +set(CMAKE_C_COMPILER_ARG1 "") +set(CMAKE_C_COMPILER_ID "GNU") +set(CMAKE_C_COMPILER_VERSION "11.4.0") +set(CMAKE_C_COMPILER_VERSION_INTERNAL "") +set(CMAKE_C_COMPILER_WRAPPER "") +set(CMAKE_C_STANDARD_COMPUTED_DEFAULT "17") +set(CMAKE_C_EXTENSIONS_COMPUTED_DEFAULT "ON") +set(CMAKE_C_COMPILE_FEATURES "c_std_90;c_function_prototypes;c_std_99;c_restrict;c_variadic_macros;c_std_11;c_static_assert;c_std_17;c_std_23") +set(CMAKE_C90_COMPILE_FEATURES "c_std_90;c_function_prototypes") +set(CMAKE_C99_COMPILE_FEATURES "c_std_99;c_restrict;c_variadic_macros") +set(CMAKE_C11_COMPILE_FEATURES "c_std_11;c_static_assert") +set(CMAKE_C17_COMPILE_FEATURES "c_std_17") +set(CMAKE_C23_COMPILE_FEATURES "c_std_23") + +set(CMAKE_C_PLATFORM_ID "Linux") +set(CMAKE_C_SIMULATE_ID "") +set(CMAKE_C_COMPILER_FRONTEND_VARIANT "") +set(CMAKE_C_SIMULATE_VERSION "") + + + + +set(CMAKE_AR "/usr/bin/ar") +set(CMAKE_C_COMPILER_AR "/usr/bin/gcc-ar-11") +set(CMAKE_RANLIB "/usr/bin/ranlib") +set(CMAKE_C_COMPILER_RANLIB "/usr/bin/gcc-ranlib-11") +set(CMAKE_LINKER "/usr/bin/ld") +set(CMAKE_MT "") +set(CMAKE_COMPILER_IS_GNUCC 1) +set(CMAKE_C_COMPILER_LOADED 1) +set(CMAKE_C_COMPILER_WORKS TRUE) +set(CMAKE_C_ABI_COMPILED TRUE) + +set(CMAKE_C_COMPILER_ENV_VAR "CC") + +set(CMAKE_C_COMPILER_ID_RUN 1) +set(CMAKE_C_SOURCE_FILE_EXTENSIONS c;m) +set(CMAKE_C_IGNORE_EXTENSIONS h;H;o;O;obj;OBJ;def;DEF;rc;RC) +set(CMAKE_C_LINKER_PREFERENCE 10) + +# Save compiler ABI information. +set(CMAKE_C_SIZEOF_DATA_PTR "8") +set(CMAKE_C_COMPILER_ABI "ELF") +set(CMAKE_C_BYTE_ORDER "LITTLE_ENDIAN") +set(CMAKE_C_LIBRARY_ARCHITECTURE "x86_64-linux-gnu") + +if(CMAKE_C_SIZEOF_DATA_PTR) + set(CMAKE_SIZEOF_VOID_P "${CMAKE_C_SIZEOF_DATA_PTR}") +endif() + +if(CMAKE_C_COMPILER_ABI) + set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_C_COMPILER_ABI}") +endif() + +if(CMAKE_C_LIBRARY_ARCHITECTURE) + set(CMAKE_LIBRARY_ARCHITECTURE "x86_64-linux-gnu") +endif() + +set(CMAKE_C_CL_SHOWINCLUDES_PREFIX "") +if(CMAKE_C_CL_SHOWINCLUDES_PREFIX) + set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_C_CL_SHOWINCLUDES_PREFIX}") +endif() + + + + + +set(CMAKE_C_IMPLICIT_INCLUDE_DIRECTORIES "/usr/lib/gcc/x86_64-linux-gnu/11/include;/usr/local/include;/usr/include/x86_64-linux-gnu;/usr/include") +set(CMAKE_C_IMPLICIT_LINK_LIBRARIES "gcc;gcc_s;c;gcc;gcc_s") +set(CMAKE_C_IMPLICIT_LINK_DIRECTORIES "/usr/lib/gcc/x86_64-linux-gnu/11;/usr/lib/x86_64-linux-gnu;/usr/lib;/lib/x86_64-linux-gnu;/lib") +set(CMAKE_C_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "") diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CMakeCXXCompiler.cmake b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CMakeCXXCompiler.cmake new file mode 100644 index 0000000000000000000000000000000000000000..345e9307d98d4da7a2cb8a1cad976671f62ac568 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CMakeCXXCompiler.cmake @@ -0,0 +1,83 @@ +set(CMAKE_CXX_COMPILER "/usr/bin/c++") +set(CMAKE_CXX_COMPILER_ARG1 "") +set(CMAKE_CXX_COMPILER_ID "GNU") +set(CMAKE_CXX_COMPILER_VERSION "11.4.0") +set(CMAKE_CXX_COMPILER_VERSION_INTERNAL "") +set(CMAKE_CXX_COMPILER_WRAPPER "") +set(CMAKE_CXX_STANDARD_COMPUTED_DEFAULT "17") +set(CMAKE_CXX_EXTENSIONS_COMPUTED_DEFAULT "ON") +set(CMAKE_CXX_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters;cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates;cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates;cxx_std_17;cxx_std_20;cxx_std_23") +set(CMAKE_CXX98_COMPILE_FEATURES "cxx_std_98;cxx_template_template_parameters") +set(CMAKE_CXX11_COMPILE_FEATURES "cxx_std_11;cxx_alias_templates;cxx_alignas;cxx_alignof;cxx_attributes;cxx_auto_type;cxx_constexpr;cxx_decltype;cxx_decltype_incomplete_return_types;cxx_default_function_template_args;cxx_defaulted_functions;cxx_defaulted_move_initializers;cxx_delegating_constructors;cxx_deleted_functions;cxx_enum_forward_declarations;cxx_explicit_conversions;cxx_extended_friend_declarations;cxx_extern_templates;cxx_final;cxx_func_identifier;cxx_generalized_initializers;cxx_inheriting_constructors;cxx_inline_namespaces;cxx_lambdas;cxx_local_type_template_args;cxx_long_long_type;cxx_noexcept;cxx_nonstatic_member_init;cxx_nullptr;cxx_override;cxx_range_for;cxx_raw_string_literals;cxx_reference_qualified_functions;cxx_right_angle_brackets;cxx_rvalue_references;cxx_sizeof_member;cxx_static_assert;cxx_strong_enums;cxx_thread_local;cxx_trailing_return_types;cxx_unicode_literals;cxx_uniform_initialization;cxx_unrestricted_unions;cxx_user_literals;cxx_variadic_macros;cxx_variadic_templates") +set(CMAKE_CXX14_COMPILE_FEATURES "cxx_std_14;cxx_aggregate_default_initializers;cxx_attribute_deprecated;cxx_binary_literals;cxx_contextual_conversions;cxx_decltype_auto;cxx_digit_separators;cxx_generic_lambdas;cxx_lambda_init_captures;cxx_relaxed_constexpr;cxx_return_type_deduction;cxx_variable_templates") +set(CMAKE_CXX17_COMPILE_FEATURES "cxx_std_17") +set(CMAKE_CXX20_COMPILE_FEATURES "cxx_std_20") +set(CMAKE_CXX23_COMPILE_FEATURES "cxx_std_23") + +set(CMAKE_CXX_PLATFORM_ID "Linux") +set(CMAKE_CXX_SIMULATE_ID "") +set(CMAKE_CXX_COMPILER_FRONTEND_VARIANT "") +set(CMAKE_CXX_SIMULATE_VERSION "") + + + + +set(CMAKE_AR "/usr/bin/ar") +set(CMAKE_CXX_COMPILER_AR "/usr/bin/gcc-ar-11") +set(CMAKE_RANLIB "/usr/bin/ranlib") +set(CMAKE_CXX_COMPILER_RANLIB "/usr/bin/gcc-ranlib-11") +set(CMAKE_LINKER "/usr/bin/ld") +set(CMAKE_MT "") +set(CMAKE_COMPILER_IS_GNUCXX 1) +set(CMAKE_CXX_COMPILER_LOADED 1) +set(CMAKE_CXX_COMPILER_WORKS TRUE) +set(CMAKE_CXX_ABI_COMPILED TRUE) + +set(CMAKE_CXX_COMPILER_ENV_VAR "CXX") + +set(CMAKE_CXX_COMPILER_ID_RUN 1) +set(CMAKE_CXX_SOURCE_FILE_EXTENSIONS C;M;c++;cc;cpp;cxx;m;mm;mpp;CPP;ixx;cppm) +set(CMAKE_CXX_IGNORE_EXTENSIONS inl;h;hpp;HPP;H;o;O;obj;OBJ;def;DEF;rc;RC) + +foreach (lang C OBJC OBJCXX) + if (CMAKE_${lang}_COMPILER_ID_RUN) + foreach(extension IN LISTS CMAKE_${lang}_SOURCE_FILE_EXTENSIONS) + list(REMOVE_ITEM CMAKE_CXX_SOURCE_FILE_EXTENSIONS ${extension}) + endforeach() + endif() +endforeach() + +set(CMAKE_CXX_LINKER_PREFERENCE 30) +set(CMAKE_CXX_LINKER_PREFERENCE_PROPAGATES 1) + +# Save compiler ABI information. +set(CMAKE_CXX_SIZEOF_DATA_PTR "8") +set(CMAKE_CXX_COMPILER_ABI "ELF") +set(CMAKE_CXX_BYTE_ORDER "LITTLE_ENDIAN") +set(CMAKE_CXX_LIBRARY_ARCHITECTURE "x86_64-linux-gnu") + +if(CMAKE_CXX_SIZEOF_DATA_PTR) + set(CMAKE_SIZEOF_VOID_P "${CMAKE_CXX_SIZEOF_DATA_PTR}") +endif() + +if(CMAKE_CXX_COMPILER_ABI) + set(CMAKE_INTERNAL_PLATFORM_ABI "${CMAKE_CXX_COMPILER_ABI}") +endif() + +if(CMAKE_CXX_LIBRARY_ARCHITECTURE) + set(CMAKE_LIBRARY_ARCHITECTURE "x86_64-linux-gnu") +endif() + +set(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX "") +if(CMAKE_CXX_CL_SHOWINCLUDES_PREFIX) + set(CMAKE_CL_SHOWINCLUDES_PREFIX "${CMAKE_CXX_CL_SHOWINCLUDES_PREFIX}") +endif() + + + + + +set(CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES "/usr/include/c++/11;/usr/include/x86_64-linux-gnu/c++/11;/usr/include/c++/11/backward;/usr/lib/gcc/x86_64-linux-gnu/11/include;/usr/local/include;/usr/include/x86_64-linux-gnu;/usr/include") +set(CMAKE_CXX_IMPLICIT_LINK_LIBRARIES "stdc++;m;gcc_s;gcc;c;gcc_s;gcc") +set(CMAKE_CXX_IMPLICIT_LINK_DIRECTORIES "/usr/lib/gcc/x86_64-linux-gnu/11;/usr/lib/x86_64-linux-gnu;/usr/lib;/lib/x86_64-linux-gnu;/lib") +set(CMAKE_CXX_IMPLICIT_LINK_FRAMEWORK_DIRECTORIES "") diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CMakeDetermineCompilerABI_C.bin b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CMakeDetermineCompilerABI_C.bin new file mode 100644 index 0000000000000000000000000000000000000000..ba1f8f8aa2b69e4af76ce2d48ba9438aad5dd336 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CMakeDetermineCompilerABI_C.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:000517d39b33bfa2d18f7be65e111759f2752b449855c32370eb4264fb29e244 +size 15968 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CMakeDetermineCompilerABI_CXX.bin b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CMakeDetermineCompilerABI_CXX.bin new file mode 100644 index 0000000000000000000000000000000000000000..43a6a0a83b79e8dfbdae842c8a324d2738529e93 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CMakeDetermineCompilerABI_CXX.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e2e968bb6ffef2f6cdb281d8fbf6964dac7ad65ca39384d46fcaa1f6107870b7 +size 15992 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CMakeSystem.cmake b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CMakeSystem.cmake new file mode 100644 index 0000000000000000000000000000000000000000..149809818d6840d981758545c8b64f585aacbf82 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CMakeSystem.cmake @@ -0,0 +1,15 @@ +set(CMAKE_HOST_SYSTEM "Linux-6.8.0-1057-aws") +set(CMAKE_HOST_SYSTEM_NAME "Linux") +set(CMAKE_HOST_SYSTEM_VERSION "6.8.0-1057-aws") +set(CMAKE_HOST_SYSTEM_PROCESSOR "x86_64") + + + +set(CMAKE_SYSTEM "Linux-6.8.0-1057-aws") +set(CMAKE_SYSTEM_NAME "Linux") +set(CMAKE_SYSTEM_VERSION "6.8.0-1057-aws") +set(CMAKE_SYSTEM_PROCESSOR "x86_64") + +set(CMAKE_CROSSCOMPILING "FALSE") + +set(CMAKE_SYSTEM_LOADED 1) diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CompilerIdC/CMakeCCompilerId.c b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CompilerIdC/CMakeCCompilerId.c new file mode 100644 index 0000000000000000000000000000000000000000..41b99d7783c1e447962d3183b641863e61a8edd0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CompilerIdC/CMakeCCompilerId.c @@ -0,0 +1,803 @@ +#ifdef __cplusplus +# error "A C++ compiler has been selected for C." +#endif + +#if defined(__18CXX) +# define ID_VOID_MAIN +#endif +#if defined(__CLASSIC_C__) +/* cv-qualifiers did not exist in K&R C */ +# define const +# define volatile +#endif + +#if !defined(__has_include) +/* If the compiler does not have __has_include, pretend the answer is + always no. */ +# define __has_include(x) 0 +#endif + + +/* Version number components: V=Version, R=Revision, P=Patch + Version date components: YYYY=Year, MM=Month, DD=Day */ + +#if defined(__INTEL_COMPILER) || defined(__ICC) +# define COMPILER_ID "Intel" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# if defined(__GNUC__) +# define SIMULATE_ID "GNU" +# endif + /* __INTEL_COMPILER = VRP prior to 2021, and then VVVV for 2021 and later, + except that a few beta releases use the old format with V=2021. */ +# if __INTEL_COMPILER < 2021 || __INTEL_COMPILER == 202110 || __INTEL_COMPILER == 202111 +# define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER/100) +# define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER/10 % 10) +# if defined(__INTEL_COMPILER_UPDATE) +# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER_UPDATE) +# else +# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER % 10) +# endif +# else +# define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER) +# define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER_UPDATE) + /* The third version component from --version is an update index, + but no macro is provided for it. */ +# define COMPILER_VERSION_PATCH DEC(0) +# endif +# if defined(__INTEL_COMPILER_BUILD_DATE) + /* __INTEL_COMPILER_BUILD_DATE = YYYYMMDD */ +# define COMPILER_VERSION_TWEAK DEC(__INTEL_COMPILER_BUILD_DATE) +# endif +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif +# if defined(__GNUC__) +# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) +# elif defined(__GNUG__) +# define SIMULATE_VERSION_MAJOR DEC(__GNUG__) +# endif +# if defined(__GNUC_MINOR__) +# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) +# endif +# if defined(__GNUC_PATCHLEVEL__) +# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif + +#elif (defined(__clang__) && defined(__INTEL_CLANG_COMPILER)) || defined(__INTEL_LLVM_COMPILER) +# define COMPILER_ID "IntelLLVM" +#if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +#endif +#if defined(__GNUC__) +# define SIMULATE_ID "GNU" +#endif +/* __INTEL_LLVM_COMPILER = VVVVRP prior to 2021.2.0, VVVVRRPP for 2021.2.0 and + * later. Look for 6 digit vs. 8 digit version number to decide encoding. + * VVVV is no smaller than the current year when a version is released. + */ +#if __INTEL_LLVM_COMPILER < 1000000L +# define COMPILER_VERSION_MAJOR DEC(__INTEL_LLVM_COMPILER/100) +# define COMPILER_VERSION_MINOR DEC(__INTEL_LLVM_COMPILER/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__INTEL_LLVM_COMPILER % 10) +#else +# define COMPILER_VERSION_MAJOR DEC(__INTEL_LLVM_COMPILER/10000) +# define COMPILER_VERSION_MINOR DEC(__INTEL_LLVM_COMPILER/100 % 100) +# define COMPILER_VERSION_PATCH DEC(__INTEL_LLVM_COMPILER % 100) +#endif +#if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +#endif +#if defined(__GNUC__) +# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) +#elif defined(__GNUG__) +# define SIMULATE_VERSION_MAJOR DEC(__GNUG__) +#endif +#if defined(__GNUC_MINOR__) +# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) +#endif +#if defined(__GNUC_PATCHLEVEL__) +# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +#endif + +#elif defined(__PATHCC__) +# define COMPILER_ID "PathScale" +# define COMPILER_VERSION_MAJOR DEC(__PATHCC__) +# define COMPILER_VERSION_MINOR DEC(__PATHCC_MINOR__) +# if defined(__PATHCC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__PATHCC_PATCHLEVEL__) +# endif + +#elif defined(__BORLANDC__) && defined(__CODEGEARC_VERSION__) +# define COMPILER_ID "Embarcadero" +# define COMPILER_VERSION_MAJOR HEX(__CODEGEARC_VERSION__>>24 & 0x00FF) +# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) +# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) + +#elif defined(__BORLANDC__) +# define COMPILER_ID "Borland" + /* __BORLANDC__ = 0xVRR */ +# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) +# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) + +#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 +# define COMPILER_ID "Watcom" + /* __WATCOMC__ = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__WATCOMC__) +# define COMPILER_ID "OpenWatcom" + /* __WATCOMC__ = VVRP + 1100 */ +# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__SUNPRO_C) +# define COMPILER_ID "SunPro" +# if __SUNPRO_C >= 0x5100 + /* __SUNPRO_C = 0xVRRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>12) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xFF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) +# else + /* __SUNPRO_CC = 0xVRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_C>>8) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_C>>4 & 0xF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_C & 0xF) +# endif + +#elif defined(__HP_cc) +# define COMPILER_ID "HP" + /* __HP_cc = VVRRPP */ +# define COMPILER_VERSION_MAJOR DEC(__HP_cc/10000) +# define COMPILER_VERSION_MINOR DEC(__HP_cc/100 % 100) +# define COMPILER_VERSION_PATCH DEC(__HP_cc % 100) + +#elif defined(__DECC) +# define COMPILER_ID "Compaq" + /* __DECC_VER = VVRRTPPPP */ +# define COMPILER_VERSION_MAJOR DEC(__DECC_VER/10000000) +# define COMPILER_VERSION_MINOR DEC(__DECC_VER/100000 % 100) +# define COMPILER_VERSION_PATCH DEC(__DECC_VER % 10000) + +#elif defined(__IBMC__) && defined(__COMPILER_VER__) +# define COMPILER_ID "zOS" + /* __IBMC__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) + +#elif defined(__ibmxl__) && defined(__clang__) +# define COMPILER_ID "XLClang" +# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) +# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) +# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) +# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) + + +#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ >= 800 +# define COMPILER_ID "XL" + /* __IBMC__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) + +#elif defined(__IBMC__) && !defined(__COMPILER_VER__) && __IBMC__ < 800 +# define COMPILER_ID "VisualAge" + /* __IBMC__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMC__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMC__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMC__ % 10) + +#elif defined(__NVCOMPILER) +# define COMPILER_ID "NVHPC" +# define COMPILER_VERSION_MAJOR DEC(__NVCOMPILER_MAJOR__) +# define COMPILER_VERSION_MINOR DEC(__NVCOMPILER_MINOR__) +# if defined(__NVCOMPILER_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__NVCOMPILER_PATCHLEVEL__) +# endif + +#elif defined(__PGI) +# define COMPILER_ID "PGI" +# define COMPILER_VERSION_MAJOR DEC(__PGIC__) +# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) +# if defined(__PGIC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) +# endif + +#elif defined(_CRAYC) +# define COMPILER_ID "Cray" +# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) +# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) + +#elif defined(__TI_COMPILER_VERSION__) +# define COMPILER_ID "TI" + /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ +# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) +# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) +# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) + +#elif defined(__CLANG_FUJITSU) +# define COMPILER_ID "FujitsuClang" +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# define COMPILER_VERSION_INTERNAL_STR __clang_version__ + + +#elif defined(__FUJITSU) +# define COMPILER_ID "Fujitsu" +# if defined(__FCC_version__) +# define COMPILER_VERSION __FCC_version__ +# elif defined(__FCC_major__) +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# endif +# if defined(__fcc_version) +# define COMPILER_VERSION_INTERNAL DEC(__fcc_version) +# elif defined(__FCC_VERSION) +# define COMPILER_VERSION_INTERNAL DEC(__FCC_VERSION) +# endif + + +#elif defined(__ghs__) +# define COMPILER_ID "GHS" +/* __GHS_VERSION_NUMBER = VVVVRP */ +# ifdef __GHS_VERSION_NUMBER +# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) +# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) +# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) +# endif + +#elif defined(__TINYC__) +# define COMPILER_ID "TinyCC" + +#elif defined(__BCC__) +# define COMPILER_ID "Bruce" + +#elif defined(__SCO_VERSION__) +# define COMPILER_ID "SCO" + +#elif defined(__ARMCC_VERSION) && !defined(__clang__) +# define COMPILER_ID "ARMCC" +#if __ARMCC_VERSION >= 1000000 + /* __ARMCC_VERSION = VRRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#else + /* __ARMCC_VERSION = VRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#endif + + +#elif defined(__clang__) && defined(__apple_build_version__) +# define COMPILER_ID "AppleClang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif +# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) + +#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) +# define COMPILER_ID "ARMClang" + # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) +# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) + +#elif defined(__clang__) +# define COMPILER_ID "Clang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif + +#elif defined(__GNUC__) +# define COMPILER_ID "GNU" +# define COMPILER_VERSION_MAJOR DEC(__GNUC__) +# if defined(__GNUC_MINOR__) +# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) +# endif +# if defined(__GNUC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif + +#elif defined(_MSC_VER) +# define COMPILER_ID "MSVC" + /* _MSC_VER = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) +# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) +# if defined(_MSC_FULL_VER) +# if _MSC_VER >= 1400 + /* _MSC_FULL_VER = VVRRPPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) +# else + /* _MSC_FULL_VER = VVRRPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) +# endif +# endif +# if defined(_MSC_BUILD) +# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) +# endif + +#elif defined(__VISUALDSPVERSION__) || defined(__ADSPBLACKFIN__) || defined(__ADSPTS__) || defined(__ADSP21000__) +# define COMPILER_ID "ADSP" +#if defined(__VISUALDSPVERSION__) + /* __VISUALDSPVERSION__ = 0xVVRRPP00 */ +# define COMPILER_VERSION_MAJOR HEX(__VISUALDSPVERSION__>>24) +# define COMPILER_VERSION_MINOR HEX(__VISUALDSPVERSION__>>16 & 0xFF) +# define COMPILER_VERSION_PATCH HEX(__VISUALDSPVERSION__>>8 & 0xFF) +#endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# define COMPILER_ID "IAR" +# if defined(__VER__) && defined(__ICCARM__) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) +# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) +# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__) || defined(__ICCSTM8__)) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) +# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) +# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# endif + +#elif defined(__SDCC_VERSION_MAJOR) || defined(SDCC) +# define COMPILER_ID "SDCC" +# if defined(__SDCC_VERSION_MAJOR) +# define COMPILER_VERSION_MAJOR DEC(__SDCC_VERSION_MAJOR) +# define COMPILER_VERSION_MINOR DEC(__SDCC_VERSION_MINOR) +# define COMPILER_VERSION_PATCH DEC(__SDCC_VERSION_PATCH) +# else + /* SDCC = VRP */ +# define COMPILER_VERSION_MAJOR DEC(SDCC/100) +# define COMPILER_VERSION_MINOR DEC(SDCC/10 % 10) +# define COMPILER_VERSION_PATCH DEC(SDCC % 10) +# endif + + +/* These compilers are either not known or too old to define an + identification macro. Try to identify the platform and guess that + it is the native compiler. */ +#elif defined(__hpux) || defined(__hpua) +# define COMPILER_ID "HP" + +#else /* unknown compiler */ +# define COMPILER_ID "" +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; +#ifdef SIMULATE_ID +char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; +#endif + +#ifdef __QNXNTO__ +char const* qnxnto = "INFO" ":" "qnxnto[]"; +#endif + +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) +char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; +#endif + +#define STRINGIFY_HELPER(X) #X +#define STRINGIFY(X) STRINGIFY_HELPER(X) + +/* Identify known platforms by name. */ +#if defined(__linux) || defined(__linux__) || defined(linux) +# define PLATFORM_ID "Linux" + +#elif defined(__MSYS__) +# define PLATFORM_ID "MSYS" + +#elif defined(__CYGWIN__) +# define PLATFORM_ID "Cygwin" + +#elif defined(__MINGW32__) +# define PLATFORM_ID "MinGW" + +#elif defined(__APPLE__) +# define PLATFORM_ID "Darwin" + +#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) +# define PLATFORM_ID "Windows" + +#elif defined(__FreeBSD__) || defined(__FreeBSD) +# define PLATFORM_ID "FreeBSD" + +#elif defined(__NetBSD__) || defined(__NetBSD) +# define PLATFORM_ID "NetBSD" + +#elif defined(__OpenBSD__) || defined(__OPENBSD) +# define PLATFORM_ID "OpenBSD" + +#elif defined(__sun) || defined(sun) +# define PLATFORM_ID "SunOS" + +#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) +# define PLATFORM_ID "AIX" + +#elif defined(__hpux) || defined(__hpux__) +# define PLATFORM_ID "HP-UX" + +#elif defined(__HAIKU__) +# define PLATFORM_ID "Haiku" + +#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) +# define PLATFORM_ID "BeOS" + +#elif defined(__QNX__) || defined(__QNXNTO__) +# define PLATFORM_ID "QNX" + +#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) +# define PLATFORM_ID "Tru64" + +#elif defined(__riscos) || defined(__riscos__) +# define PLATFORM_ID "RISCos" + +#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) +# define PLATFORM_ID "SINIX" + +#elif defined(__UNIX_SV__) +# define PLATFORM_ID "UNIX_SV" + +#elif defined(__bsdos__) +# define PLATFORM_ID "BSDOS" + +#elif defined(_MPRAS) || defined(MPRAS) +# define PLATFORM_ID "MP-RAS" + +#elif defined(__osf) || defined(__osf__) +# define PLATFORM_ID "OSF1" + +#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) +# define PLATFORM_ID "SCO_SV" + +#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) +# define PLATFORM_ID "ULTRIX" + +#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) +# define PLATFORM_ID "Xenix" + +#elif defined(__WATCOMC__) +# if defined(__LINUX__) +# define PLATFORM_ID "Linux" + +# elif defined(__DOS__) +# define PLATFORM_ID "DOS" + +# elif defined(__OS2__) +# define PLATFORM_ID "OS2" + +# elif defined(__WINDOWS__) +# define PLATFORM_ID "Windows3x" + +# elif defined(__VXWORKS__) +# define PLATFORM_ID "VxWorks" + +# else /* unknown platform */ +# define PLATFORM_ID +# endif + +#elif defined(__INTEGRITY) +# if defined(INT_178B) +# define PLATFORM_ID "Integrity178" + +# else /* regular Integrity */ +# define PLATFORM_ID "Integrity" +# endif + +#else /* unknown platform */ +# define PLATFORM_ID + +#endif + +/* For windows compilers MSVC and Intel we can determine + the architecture of the compiler being used. This is because + the compilers do not have flags that can change the architecture, + but rather depend on which compiler is being used +*/ +#if defined(_WIN32) && defined(_MSC_VER) +# if defined(_M_IA64) +# define ARCHITECTURE_ID "IA64" + +# elif defined(_M_ARM64EC) +# define ARCHITECTURE_ID "ARM64EC" + +# elif defined(_M_X64) || defined(_M_AMD64) +# define ARCHITECTURE_ID "x64" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# elif defined(_M_ARM64) +# define ARCHITECTURE_ID "ARM64" + +# elif defined(_M_ARM) +# if _M_ARM == 4 +# define ARCHITECTURE_ID "ARMV4I" +# elif _M_ARM == 5 +# define ARCHITECTURE_ID "ARMV5I" +# else +# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) +# endif + +# elif defined(_M_MIPS) +# define ARCHITECTURE_ID "MIPS" + +# elif defined(_M_SH) +# define ARCHITECTURE_ID "SHx" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__WATCOMC__) +# if defined(_M_I86) +# define ARCHITECTURE_ID "I86" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# if defined(__ICCARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__ICCRX__) +# define ARCHITECTURE_ID "RX" + +# elif defined(__ICCRH850__) +# define ARCHITECTURE_ID "RH850" + +# elif defined(__ICCRL78__) +# define ARCHITECTURE_ID "RL78" + +# elif defined(__ICCRISCV__) +# define ARCHITECTURE_ID "RISCV" + +# elif defined(__ICCAVR__) +# define ARCHITECTURE_ID "AVR" + +# elif defined(__ICC430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__ICCV850__) +# define ARCHITECTURE_ID "V850" + +# elif defined(__ICC8051__) +# define ARCHITECTURE_ID "8051" + +# elif defined(__ICCSTM8__) +# define ARCHITECTURE_ID "STM8" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__ghs__) +# if defined(__PPC64__) +# define ARCHITECTURE_ID "PPC64" + +# elif defined(__ppc__) +# define ARCHITECTURE_ID "PPC" + +# elif defined(__ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__x86_64__) +# define ARCHITECTURE_ID "x64" + +# elif defined(__i386__) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__TI_COMPILER_VERSION__) +# if defined(__TI_ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__MSP430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__TMS320C28XX__) +# define ARCHITECTURE_ID "TMS320C28x" + +# elif defined(__TMS320C6X__) || defined(_TMS320C6X) +# define ARCHITECTURE_ID "TMS320C6x" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#else +# define ARCHITECTURE_ID +#endif + +/* Convert integer to decimal digit literals. */ +#define DEC(n) \ + ('0' + (((n) / 10000000)%10)), \ + ('0' + (((n) / 1000000)%10)), \ + ('0' + (((n) / 100000)%10)), \ + ('0' + (((n) / 10000)%10)), \ + ('0' + (((n) / 1000)%10)), \ + ('0' + (((n) / 100)%10)), \ + ('0' + (((n) / 10)%10)), \ + ('0' + ((n) % 10)) + +/* Convert integer to hex digit literals. */ +#define HEX(n) \ + ('0' + ((n)>>28 & 0xF)), \ + ('0' + ((n)>>24 & 0xF)), \ + ('0' + ((n)>>20 & 0xF)), \ + ('0' + ((n)>>16 & 0xF)), \ + ('0' + ((n)>>12 & 0xF)), \ + ('0' + ((n)>>8 & 0xF)), \ + ('0' + ((n)>>4 & 0xF)), \ + ('0' + ((n) & 0xF)) + +/* Construct a string literal encoding the version number. */ +#ifdef COMPILER_VERSION +char const* info_version = "INFO" ":" "compiler_version[" COMPILER_VERSION "]"; + +/* Construct a string literal encoding the version number components. */ +#elif defined(COMPILER_VERSION_MAJOR) +char const info_version[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', + COMPILER_VERSION_MAJOR, +# ifdef COMPILER_VERSION_MINOR + '.', COMPILER_VERSION_MINOR, +# ifdef COMPILER_VERSION_PATCH + '.', COMPILER_VERSION_PATCH, +# ifdef COMPILER_VERSION_TWEAK + '.', COMPILER_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct a string literal encoding the internal version number. */ +#ifdef COMPILER_VERSION_INTERNAL +char const info_version_internal[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', + 'i','n','t','e','r','n','a','l','[', + COMPILER_VERSION_INTERNAL,']','\0'}; +#elif defined(COMPILER_VERSION_INTERNAL_STR) +char const* info_version_internal = "INFO" ":" "compiler_version_internal[" COMPILER_VERSION_INTERNAL_STR "]"; +#endif + +/* Construct a string literal encoding the version number components. */ +#ifdef SIMULATE_VERSION_MAJOR +char const info_simulate_version[] = { + 'I', 'N', 'F', 'O', ':', + 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', + SIMULATE_VERSION_MAJOR, +# ifdef SIMULATE_VERSION_MINOR + '.', SIMULATE_VERSION_MINOR, +# ifdef SIMULATE_VERSION_PATCH + '.', SIMULATE_VERSION_PATCH, +# ifdef SIMULATE_VERSION_TWEAK + '.', SIMULATE_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; +char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; + + + +#if !defined(__STDC__) && !defined(__clang__) +# if defined(_MSC_VER) || defined(__ibmxl__) || defined(__IBMC__) +# define C_VERSION "90" +# else +# define C_VERSION +# endif +#elif __STDC_VERSION__ > 201710L +# define C_VERSION "23" +#elif __STDC_VERSION__ >= 201710L +# define C_VERSION "17" +#elif __STDC_VERSION__ >= 201000L +# define C_VERSION "11" +#elif __STDC_VERSION__ >= 199901L +# define C_VERSION "99" +#else +# define C_VERSION "90" +#endif +const char* info_language_standard_default = + "INFO" ":" "standard_default[" C_VERSION "]"; + +const char* info_language_extensions_default = "INFO" ":" "extensions_default[" +/* !defined(_MSC_VER) to exclude Clang's MSVC compatibility mode. */ +#if (defined(__clang__) || defined(__GNUC__) || \ + defined(__TI_COMPILER_VERSION__)) && \ + !defined(__STRICT_ANSI__) && !defined(_MSC_VER) + "ON" +#else + "OFF" +#endif +"]"; + +/*--------------------------------------------------------------------------*/ + +#ifdef ID_VOID_MAIN +void main() {} +#else +# if defined(__CLASSIC_C__) +int main(argc, argv) int argc; char *argv[]; +# else +int main(int argc, char* argv[]) +# endif +{ + int require = 0; + require += info_compiler[argc]; + require += info_platform[argc]; + require += info_arch[argc]; +#ifdef COMPILER_VERSION_MAJOR + require += info_version[argc]; +#endif +#ifdef COMPILER_VERSION_INTERNAL + require += info_version_internal[argc]; +#endif +#ifdef SIMULATE_ID + require += info_simulate[argc]; +#endif +#ifdef SIMULATE_VERSION_MAJOR + require += info_simulate_version[argc]; +#endif +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) + require += info_cray[argc]; +#endif + require += info_language_standard_default[argc]; + require += info_language_extensions_default[argc]; + (void)argv; + return require; +} +#endif diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CompilerIdC/a.out b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CompilerIdC/a.out new file mode 100644 index 0000000000000000000000000000000000000000..7873b2c373006850b7447b78a578338ad12249c0 Binary files /dev/null and b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CompilerIdC/a.out differ diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CompilerIdCXX/CMakeCXXCompilerId.cpp b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CompilerIdCXX/CMakeCXXCompilerId.cpp new file mode 100644 index 0000000000000000000000000000000000000000..25c62a8c3cb40764ac539370df9ec347bdd99b79 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CompilerIdCXX/CMakeCXXCompilerId.cpp @@ -0,0 +1,791 @@ +/* This source file must have a .cpp extension so that all C++ compilers + recognize the extension without flags. Borland does not know .cxx for + example. */ +#ifndef __cplusplus +# error "A C compiler has been selected for C++." +#endif + +#if !defined(__has_include) +/* If the compiler does not have __has_include, pretend the answer is + always no. */ +# define __has_include(x) 0 +#endif + + +/* Version number components: V=Version, R=Revision, P=Patch + Version date components: YYYY=Year, MM=Month, DD=Day */ + +#if defined(__COMO__) +# define COMPILER_ID "Comeau" + /* __COMO_VERSION__ = VRR */ +# define COMPILER_VERSION_MAJOR DEC(__COMO_VERSION__ / 100) +# define COMPILER_VERSION_MINOR DEC(__COMO_VERSION__ % 100) + +#elif defined(__INTEL_COMPILER) || defined(__ICC) +# define COMPILER_ID "Intel" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# if defined(__GNUC__) +# define SIMULATE_ID "GNU" +# endif + /* __INTEL_COMPILER = VRP prior to 2021, and then VVVV for 2021 and later, + except that a few beta releases use the old format with V=2021. */ +# if __INTEL_COMPILER < 2021 || __INTEL_COMPILER == 202110 || __INTEL_COMPILER == 202111 +# define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER/100) +# define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER/10 % 10) +# if defined(__INTEL_COMPILER_UPDATE) +# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER_UPDATE) +# else +# define COMPILER_VERSION_PATCH DEC(__INTEL_COMPILER % 10) +# endif +# else +# define COMPILER_VERSION_MAJOR DEC(__INTEL_COMPILER) +# define COMPILER_VERSION_MINOR DEC(__INTEL_COMPILER_UPDATE) + /* The third version component from --version is an update index, + but no macro is provided for it. */ +# define COMPILER_VERSION_PATCH DEC(0) +# endif +# if defined(__INTEL_COMPILER_BUILD_DATE) + /* __INTEL_COMPILER_BUILD_DATE = YYYYMMDD */ +# define COMPILER_VERSION_TWEAK DEC(__INTEL_COMPILER_BUILD_DATE) +# endif +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif +# if defined(__GNUC__) +# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) +# elif defined(__GNUG__) +# define SIMULATE_VERSION_MAJOR DEC(__GNUG__) +# endif +# if defined(__GNUC_MINOR__) +# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) +# endif +# if defined(__GNUC_PATCHLEVEL__) +# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif + +#elif (defined(__clang__) && defined(__INTEL_CLANG_COMPILER)) || defined(__INTEL_LLVM_COMPILER) +# define COMPILER_ID "IntelLLVM" +#if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +#endif +#if defined(__GNUC__) +# define SIMULATE_ID "GNU" +#endif +/* __INTEL_LLVM_COMPILER = VVVVRP prior to 2021.2.0, VVVVRRPP for 2021.2.0 and + * later. Look for 6 digit vs. 8 digit version number to decide encoding. + * VVVV is no smaller than the current year when a version is released. + */ +#if __INTEL_LLVM_COMPILER < 1000000L +# define COMPILER_VERSION_MAJOR DEC(__INTEL_LLVM_COMPILER/100) +# define COMPILER_VERSION_MINOR DEC(__INTEL_LLVM_COMPILER/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__INTEL_LLVM_COMPILER % 10) +#else +# define COMPILER_VERSION_MAJOR DEC(__INTEL_LLVM_COMPILER/10000) +# define COMPILER_VERSION_MINOR DEC(__INTEL_LLVM_COMPILER/100 % 100) +# define COMPILER_VERSION_PATCH DEC(__INTEL_LLVM_COMPILER % 100) +#endif +#if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +#endif +#if defined(__GNUC__) +# define SIMULATE_VERSION_MAJOR DEC(__GNUC__) +#elif defined(__GNUG__) +# define SIMULATE_VERSION_MAJOR DEC(__GNUG__) +#endif +#if defined(__GNUC_MINOR__) +# define SIMULATE_VERSION_MINOR DEC(__GNUC_MINOR__) +#endif +#if defined(__GNUC_PATCHLEVEL__) +# define SIMULATE_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +#endif + +#elif defined(__PATHCC__) +# define COMPILER_ID "PathScale" +# define COMPILER_VERSION_MAJOR DEC(__PATHCC__) +# define COMPILER_VERSION_MINOR DEC(__PATHCC_MINOR__) +# if defined(__PATHCC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__PATHCC_PATCHLEVEL__) +# endif + +#elif defined(__BORLANDC__) && defined(__CODEGEARC_VERSION__) +# define COMPILER_ID "Embarcadero" +# define COMPILER_VERSION_MAJOR HEX(__CODEGEARC_VERSION__>>24 & 0x00FF) +# define COMPILER_VERSION_MINOR HEX(__CODEGEARC_VERSION__>>16 & 0x00FF) +# define COMPILER_VERSION_PATCH DEC(__CODEGEARC_VERSION__ & 0xFFFF) + +#elif defined(__BORLANDC__) +# define COMPILER_ID "Borland" + /* __BORLANDC__ = 0xVRR */ +# define COMPILER_VERSION_MAJOR HEX(__BORLANDC__>>8) +# define COMPILER_VERSION_MINOR HEX(__BORLANDC__ & 0xFF) + +#elif defined(__WATCOMC__) && __WATCOMC__ < 1200 +# define COMPILER_ID "Watcom" + /* __WATCOMC__ = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(__WATCOMC__ / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__WATCOMC__) +# define COMPILER_ID "OpenWatcom" + /* __WATCOMC__ = VVRP + 1100 */ +# define COMPILER_VERSION_MAJOR DEC((__WATCOMC__ - 1100) / 100) +# define COMPILER_VERSION_MINOR DEC((__WATCOMC__ / 10) % 10) +# if (__WATCOMC__ % 10) > 0 +# define COMPILER_VERSION_PATCH DEC(__WATCOMC__ % 10) +# endif + +#elif defined(__SUNPRO_CC) +# define COMPILER_ID "SunPro" +# if __SUNPRO_CC >= 0x5100 + /* __SUNPRO_CC = 0xVRRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>12) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xFF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) +# else + /* __SUNPRO_CC = 0xVRP */ +# define COMPILER_VERSION_MAJOR HEX(__SUNPRO_CC>>8) +# define COMPILER_VERSION_MINOR HEX(__SUNPRO_CC>>4 & 0xF) +# define COMPILER_VERSION_PATCH HEX(__SUNPRO_CC & 0xF) +# endif + +#elif defined(__HP_aCC) +# define COMPILER_ID "HP" + /* __HP_aCC = VVRRPP */ +# define COMPILER_VERSION_MAJOR DEC(__HP_aCC/10000) +# define COMPILER_VERSION_MINOR DEC(__HP_aCC/100 % 100) +# define COMPILER_VERSION_PATCH DEC(__HP_aCC % 100) + +#elif defined(__DECCXX) +# define COMPILER_ID "Compaq" + /* __DECCXX_VER = VVRRTPPPP */ +# define COMPILER_VERSION_MAJOR DEC(__DECCXX_VER/10000000) +# define COMPILER_VERSION_MINOR DEC(__DECCXX_VER/100000 % 100) +# define COMPILER_VERSION_PATCH DEC(__DECCXX_VER % 10000) + +#elif defined(__IBMCPP__) && defined(__COMPILER_VER__) +# define COMPILER_ID "zOS" + /* __IBMCPP__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) + +#elif defined(__ibmxl__) && defined(__clang__) +# define COMPILER_ID "XLClang" +# define COMPILER_VERSION_MAJOR DEC(__ibmxl_version__) +# define COMPILER_VERSION_MINOR DEC(__ibmxl_release__) +# define COMPILER_VERSION_PATCH DEC(__ibmxl_modification__) +# define COMPILER_VERSION_TWEAK DEC(__ibmxl_ptf_fix_level__) + + +#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ >= 800 +# define COMPILER_ID "XL" + /* __IBMCPP__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) + +#elif defined(__IBMCPP__) && !defined(__COMPILER_VER__) && __IBMCPP__ < 800 +# define COMPILER_ID "VisualAge" + /* __IBMCPP__ = VRP */ +# define COMPILER_VERSION_MAJOR DEC(__IBMCPP__/100) +# define COMPILER_VERSION_MINOR DEC(__IBMCPP__/10 % 10) +# define COMPILER_VERSION_PATCH DEC(__IBMCPP__ % 10) + +#elif defined(__NVCOMPILER) +# define COMPILER_ID "NVHPC" +# define COMPILER_VERSION_MAJOR DEC(__NVCOMPILER_MAJOR__) +# define COMPILER_VERSION_MINOR DEC(__NVCOMPILER_MINOR__) +# if defined(__NVCOMPILER_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__NVCOMPILER_PATCHLEVEL__) +# endif + +#elif defined(__PGI) +# define COMPILER_ID "PGI" +# define COMPILER_VERSION_MAJOR DEC(__PGIC__) +# define COMPILER_VERSION_MINOR DEC(__PGIC_MINOR__) +# if defined(__PGIC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__PGIC_PATCHLEVEL__) +# endif + +#elif defined(_CRAYC) +# define COMPILER_ID "Cray" +# define COMPILER_VERSION_MAJOR DEC(_RELEASE_MAJOR) +# define COMPILER_VERSION_MINOR DEC(_RELEASE_MINOR) + +#elif defined(__TI_COMPILER_VERSION__) +# define COMPILER_ID "TI" + /* __TI_COMPILER_VERSION__ = VVVRRRPPP */ +# define COMPILER_VERSION_MAJOR DEC(__TI_COMPILER_VERSION__/1000000) +# define COMPILER_VERSION_MINOR DEC(__TI_COMPILER_VERSION__/1000 % 1000) +# define COMPILER_VERSION_PATCH DEC(__TI_COMPILER_VERSION__ % 1000) + +#elif defined(__CLANG_FUJITSU) +# define COMPILER_ID "FujitsuClang" +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# define COMPILER_VERSION_INTERNAL_STR __clang_version__ + + +#elif defined(__FUJITSU) +# define COMPILER_ID "Fujitsu" +# if defined(__FCC_version__) +# define COMPILER_VERSION __FCC_version__ +# elif defined(__FCC_major__) +# define COMPILER_VERSION_MAJOR DEC(__FCC_major__) +# define COMPILER_VERSION_MINOR DEC(__FCC_minor__) +# define COMPILER_VERSION_PATCH DEC(__FCC_patchlevel__) +# endif +# if defined(__fcc_version) +# define COMPILER_VERSION_INTERNAL DEC(__fcc_version) +# elif defined(__FCC_VERSION) +# define COMPILER_VERSION_INTERNAL DEC(__FCC_VERSION) +# endif + + +#elif defined(__ghs__) +# define COMPILER_ID "GHS" +/* __GHS_VERSION_NUMBER = VVVVRP */ +# ifdef __GHS_VERSION_NUMBER +# define COMPILER_VERSION_MAJOR DEC(__GHS_VERSION_NUMBER / 100) +# define COMPILER_VERSION_MINOR DEC(__GHS_VERSION_NUMBER / 10 % 10) +# define COMPILER_VERSION_PATCH DEC(__GHS_VERSION_NUMBER % 10) +# endif + +#elif defined(__SCO_VERSION__) +# define COMPILER_ID "SCO" + +#elif defined(__ARMCC_VERSION) && !defined(__clang__) +# define COMPILER_ID "ARMCC" +#if __ARMCC_VERSION >= 1000000 + /* __ARMCC_VERSION = VRRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#else + /* __ARMCC_VERSION = VRPPPP */ + # define COMPILER_VERSION_MAJOR DEC(__ARMCC_VERSION/100000) + # define COMPILER_VERSION_MINOR DEC(__ARMCC_VERSION/10000 % 10) + # define COMPILER_VERSION_PATCH DEC(__ARMCC_VERSION % 10000) +#endif + + +#elif defined(__clang__) && defined(__apple_build_version__) +# define COMPILER_ID "AppleClang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif +# define COMPILER_VERSION_TWEAK DEC(__apple_build_version__) + +#elif defined(__clang__) && defined(__ARMCOMPILER_VERSION) +# define COMPILER_ID "ARMClang" + # define COMPILER_VERSION_MAJOR DEC(__ARMCOMPILER_VERSION/1000000) + # define COMPILER_VERSION_MINOR DEC(__ARMCOMPILER_VERSION/10000 % 100) + # define COMPILER_VERSION_PATCH DEC(__ARMCOMPILER_VERSION % 10000) +# define COMPILER_VERSION_INTERNAL DEC(__ARMCOMPILER_VERSION) + +#elif defined(__clang__) +# define COMPILER_ID "Clang" +# if defined(_MSC_VER) +# define SIMULATE_ID "MSVC" +# endif +# define COMPILER_VERSION_MAJOR DEC(__clang_major__) +# define COMPILER_VERSION_MINOR DEC(__clang_minor__) +# define COMPILER_VERSION_PATCH DEC(__clang_patchlevel__) +# if defined(_MSC_VER) + /* _MSC_VER = VVRR */ +# define SIMULATE_VERSION_MAJOR DEC(_MSC_VER / 100) +# define SIMULATE_VERSION_MINOR DEC(_MSC_VER % 100) +# endif + +#elif defined(__GNUC__) || defined(__GNUG__) +# define COMPILER_ID "GNU" +# if defined(__GNUC__) +# define COMPILER_VERSION_MAJOR DEC(__GNUC__) +# else +# define COMPILER_VERSION_MAJOR DEC(__GNUG__) +# endif +# if defined(__GNUC_MINOR__) +# define COMPILER_VERSION_MINOR DEC(__GNUC_MINOR__) +# endif +# if defined(__GNUC_PATCHLEVEL__) +# define COMPILER_VERSION_PATCH DEC(__GNUC_PATCHLEVEL__) +# endif + +#elif defined(_MSC_VER) +# define COMPILER_ID "MSVC" + /* _MSC_VER = VVRR */ +# define COMPILER_VERSION_MAJOR DEC(_MSC_VER / 100) +# define COMPILER_VERSION_MINOR DEC(_MSC_VER % 100) +# if defined(_MSC_FULL_VER) +# if _MSC_VER >= 1400 + /* _MSC_FULL_VER = VVRRPPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 100000) +# else + /* _MSC_FULL_VER = VVRRPPPP */ +# define COMPILER_VERSION_PATCH DEC(_MSC_FULL_VER % 10000) +# endif +# endif +# if defined(_MSC_BUILD) +# define COMPILER_VERSION_TWEAK DEC(_MSC_BUILD) +# endif + +#elif defined(__VISUALDSPVERSION__) || defined(__ADSPBLACKFIN__) || defined(__ADSPTS__) || defined(__ADSP21000__) +# define COMPILER_ID "ADSP" +#if defined(__VISUALDSPVERSION__) + /* __VISUALDSPVERSION__ = 0xVVRRPP00 */ +# define COMPILER_VERSION_MAJOR HEX(__VISUALDSPVERSION__>>24) +# define COMPILER_VERSION_MINOR HEX(__VISUALDSPVERSION__>>16 & 0xFF) +# define COMPILER_VERSION_PATCH HEX(__VISUALDSPVERSION__>>8 & 0xFF) +#endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# define COMPILER_ID "IAR" +# if defined(__VER__) && defined(__ICCARM__) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 1000000) +# define COMPILER_VERSION_MINOR DEC(((__VER__) / 1000) % 1000) +# define COMPILER_VERSION_PATCH DEC((__VER__) % 1000) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# elif defined(__VER__) && (defined(__ICCAVR__) || defined(__ICCRX__) || defined(__ICCRH850__) || defined(__ICCRL78__) || defined(__ICC430__) || defined(__ICCRISCV__) || defined(__ICCV850__) || defined(__ICC8051__) || defined(__ICCSTM8__)) +# define COMPILER_VERSION_MAJOR DEC((__VER__) / 100) +# define COMPILER_VERSION_MINOR DEC((__VER__) - (((__VER__) / 100)*100)) +# define COMPILER_VERSION_PATCH DEC(__SUBVERSION__) +# define COMPILER_VERSION_INTERNAL DEC(__IAR_SYSTEMS_ICC__) +# endif + + +/* These compilers are either not known or too old to define an + identification macro. Try to identify the platform and guess that + it is the native compiler. */ +#elif defined(__hpux) || defined(__hpua) +# define COMPILER_ID "HP" + +#else /* unknown compiler */ +# define COMPILER_ID "" +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_compiler = "INFO" ":" "compiler[" COMPILER_ID "]"; +#ifdef SIMULATE_ID +char const* info_simulate = "INFO" ":" "simulate[" SIMULATE_ID "]"; +#endif + +#ifdef __QNXNTO__ +char const* qnxnto = "INFO" ":" "qnxnto[]"; +#endif + +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) +char const *info_cray = "INFO" ":" "compiler_wrapper[CrayPrgEnv]"; +#endif + +#define STRINGIFY_HELPER(X) #X +#define STRINGIFY(X) STRINGIFY_HELPER(X) + +/* Identify known platforms by name. */ +#if defined(__linux) || defined(__linux__) || defined(linux) +# define PLATFORM_ID "Linux" + +#elif defined(__MSYS__) +# define PLATFORM_ID "MSYS" + +#elif defined(__CYGWIN__) +# define PLATFORM_ID "Cygwin" + +#elif defined(__MINGW32__) +# define PLATFORM_ID "MinGW" + +#elif defined(__APPLE__) +# define PLATFORM_ID "Darwin" + +#elif defined(_WIN32) || defined(__WIN32__) || defined(WIN32) +# define PLATFORM_ID "Windows" + +#elif defined(__FreeBSD__) || defined(__FreeBSD) +# define PLATFORM_ID "FreeBSD" + +#elif defined(__NetBSD__) || defined(__NetBSD) +# define PLATFORM_ID "NetBSD" + +#elif defined(__OpenBSD__) || defined(__OPENBSD) +# define PLATFORM_ID "OpenBSD" + +#elif defined(__sun) || defined(sun) +# define PLATFORM_ID "SunOS" + +#elif defined(_AIX) || defined(__AIX) || defined(__AIX__) || defined(__aix) || defined(__aix__) +# define PLATFORM_ID "AIX" + +#elif defined(__hpux) || defined(__hpux__) +# define PLATFORM_ID "HP-UX" + +#elif defined(__HAIKU__) +# define PLATFORM_ID "Haiku" + +#elif defined(__BeOS) || defined(__BEOS__) || defined(_BEOS) +# define PLATFORM_ID "BeOS" + +#elif defined(__QNX__) || defined(__QNXNTO__) +# define PLATFORM_ID "QNX" + +#elif defined(__tru64) || defined(_tru64) || defined(__TRU64__) +# define PLATFORM_ID "Tru64" + +#elif defined(__riscos) || defined(__riscos__) +# define PLATFORM_ID "RISCos" + +#elif defined(__sinix) || defined(__sinix__) || defined(__SINIX__) +# define PLATFORM_ID "SINIX" + +#elif defined(__UNIX_SV__) +# define PLATFORM_ID "UNIX_SV" + +#elif defined(__bsdos__) +# define PLATFORM_ID "BSDOS" + +#elif defined(_MPRAS) || defined(MPRAS) +# define PLATFORM_ID "MP-RAS" + +#elif defined(__osf) || defined(__osf__) +# define PLATFORM_ID "OSF1" + +#elif defined(_SCO_SV) || defined(SCO_SV) || defined(sco_sv) +# define PLATFORM_ID "SCO_SV" + +#elif defined(__ultrix) || defined(__ultrix__) || defined(_ULTRIX) +# define PLATFORM_ID "ULTRIX" + +#elif defined(__XENIX__) || defined(_XENIX) || defined(XENIX) +# define PLATFORM_ID "Xenix" + +#elif defined(__WATCOMC__) +# if defined(__LINUX__) +# define PLATFORM_ID "Linux" + +# elif defined(__DOS__) +# define PLATFORM_ID "DOS" + +# elif defined(__OS2__) +# define PLATFORM_ID "OS2" + +# elif defined(__WINDOWS__) +# define PLATFORM_ID "Windows3x" + +# elif defined(__VXWORKS__) +# define PLATFORM_ID "VxWorks" + +# else /* unknown platform */ +# define PLATFORM_ID +# endif + +#elif defined(__INTEGRITY) +# if defined(INT_178B) +# define PLATFORM_ID "Integrity178" + +# else /* regular Integrity */ +# define PLATFORM_ID "Integrity" +# endif + +#else /* unknown platform */ +# define PLATFORM_ID + +#endif + +/* For windows compilers MSVC and Intel we can determine + the architecture of the compiler being used. This is because + the compilers do not have flags that can change the architecture, + but rather depend on which compiler is being used +*/ +#if defined(_WIN32) && defined(_MSC_VER) +# if defined(_M_IA64) +# define ARCHITECTURE_ID "IA64" + +# elif defined(_M_ARM64EC) +# define ARCHITECTURE_ID "ARM64EC" + +# elif defined(_M_X64) || defined(_M_AMD64) +# define ARCHITECTURE_ID "x64" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# elif defined(_M_ARM64) +# define ARCHITECTURE_ID "ARM64" + +# elif defined(_M_ARM) +# if _M_ARM == 4 +# define ARCHITECTURE_ID "ARMV4I" +# elif _M_ARM == 5 +# define ARCHITECTURE_ID "ARMV5I" +# else +# define ARCHITECTURE_ID "ARMV" STRINGIFY(_M_ARM) +# endif + +# elif defined(_M_MIPS) +# define ARCHITECTURE_ID "MIPS" + +# elif defined(_M_SH) +# define ARCHITECTURE_ID "SHx" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__WATCOMC__) +# if defined(_M_I86) +# define ARCHITECTURE_ID "I86" + +# elif defined(_M_IX86) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__IAR_SYSTEMS_ICC__) || defined(__IAR_SYSTEMS_ICC) +# if defined(__ICCARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__ICCRX__) +# define ARCHITECTURE_ID "RX" + +# elif defined(__ICCRH850__) +# define ARCHITECTURE_ID "RH850" + +# elif defined(__ICCRL78__) +# define ARCHITECTURE_ID "RL78" + +# elif defined(__ICCRISCV__) +# define ARCHITECTURE_ID "RISCV" + +# elif defined(__ICCAVR__) +# define ARCHITECTURE_ID "AVR" + +# elif defined(__ICC430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__ICCV850__) +# define ARCHITECTURE_ID "V850" + +# elif defined(__ICC8051__) +# define ARCHITECTURE_ID "8051" + +# elif defined(__ICCSTM8__) +# define ARCHITECTURE_ID "STM8" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__ghs__) +# if defined(__PPC64__) +# define ARCHITECTURE_ID "PPC64" + +# elif defined(__ppc__) +# define ARCHITECTURE_ID "PPC" + +# elif defined(__ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__x86_64__) +# define ARCHITECTURE_ID "x64" + +# elif defined(__i386__) +# define ARCHITECTURE_ID "X86" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#elif defined(__TI_COMPILER_VERSION__) +# if defined(__TI_ARM__) +# define ARCHITECTURE_ID "ARM" + +# elif defined(__MSP430__) +# define ARCHITECTURE_ID "MSP430" + +# elif defined(__TMS320C28XX__) +# define ARCHITECTURE_ID "TMS320C28x" + +# elif defined(__TMS320C6X__) || defined(_TMS320C6X) +# define ARCHITECTURE_ID "TMS320C6x" + +# else /* unknown architecture */ +# define ARCHITECTURE_ID "" +# endif + +#else +# define ARCHITECTURE_ID +#endif + +/* Convert integer to decimal digit literals. */ +#define DEC(n) \ + ('0' + (((n) / 10000000)%10)), \ + ('0' + (((n) / 1000000)%10)), \ + ('0' + (((n) / 100000)%10)), \ + ('0' + (((n) / 10000)%10)), \ + ('0' + (((n) / 1000)%10)), \ + ('0' + (((n) / 100)%10)), \ + ('0' + (((n) / 10)%10)), \ + ('0' + ((n) % 10)) + +/* Convert integer to hex digit literals. */ +#define HEX(n) \ + ('0' + ((n)>>28 & 0xF)), \ + ('0' + ((n)>>24 & 0xF)), \ + ('0' + ((n)>>20 & 0xF)), \ + ('0' + ((n)>>16 & 0xF)), \ + ('0' + ((n)>>12 & 0xF)), \ + ('0' + ((n)>>8 & 0xF)), \ + ('0' + ((n)>>4 & 0xF)), \ + ('0' + ((n) & 0xF)) + +/* Construct a string literal encoding the version number. */ +#ifdef COMPILER_VERSION +char const* info_version = "INFO" ":" "compiler_version[" COMPILER_VERSION "]"; + +/* Construct a string literal encoding the version number components. */ +#elif defined(COMPILER_VERSION_MAJOR) +char const info_version[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','[', + COMPILER_VERSION_MAJOR, +# ifdef COMPILER_VERSION_MINOR + '.', COMPILER_VERSION_MINOR, +# ifdef COMPILER_VERSION_PATCH + '.', COMPILER_VERSION_PATCH, +# ifdef COMPILER_VERSION_TWEAK + '.', COMPILER_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct a string literal encoding the internal version number. */ +#ifdef COMPILER_VERSION_INTERNAL +char const info_version_internal[] = { + 'I', 'N', 'F', 'O', ':', + 'c','o','m','p','i','l','e','r','_','v','e','r','s','i','o','n','_', + 'i','n','t','e','r','n','a','l','[', + COMPILER_VERSION_INTERNAL,']','\0'}; +#elif defined(COMPILER_VERSION_INTERNAL_STR) +char const* info_version_internal = "INFO" ":" "compiler_version_internal[" COMPILER_VERSION_INTERNAL_STR "]"; +#endif + +/* Construct a string literal encoding the version number components. */ +#ifdef SIMULATE_VERSION_MAJOR +char const info_simulate_version[] = { + 'I', 'N', 'F', 'O', ':', + 's','i','m','u','l','a','t','e','_','v','e','r','s','i','o','n','[', + SIMULATE_VERSION_MAJOR, +# ifdef SIMULATE_VERSION_MINOR + '.', SIMULATE_VERSION_MINOR, +# ifdef SIMULATE_VERSION_PATCH + '.', SIMULATE_VERSION_PATCH, +# ifdef SIMULATE_VERSION_TWEAK + '.', SIMULATE_VERSION_TWEAK, +# endif +# endif +# endif + ']','\0'}; +#endif + +/* Construct the string literal in pieces to prevent the source from + getting matched. Store it in a pointer rather than an array + because some compilers will just produce instructions to fill the + array rather than assigning a pointer to a static array. */ +char const* info_platform = "INFO" ":" "platform[" PLATFORM_ID "]"; +char const* info_arch = "INFO" ":" "arch[" ARCHITECTURE_ID "]"; + + + +#if defined(__INTEL_COMPILER) && defined(_MSVC_LANG) && _MSVC_LANG < 201403L +# if defined(__INTEL_CXX11_MODE__) +# if defined(__cpp_aggregate_nsdmi) +# define CXX_STD 201402L +# else +# define CXX_STD 201103L +# endif +# else +# define CXX_STD 199711L +# endif +#elif defined(_MSC_VER) && defined(_MSVC_LANG) +# define CXX_STD _MSVC_LANG +#else +# define CXX_STD __cplusplus +#endif + +const char* info_language_standard_default = "INFO" ":" "standard_default[" +#if CXX_STD > 202002L + "23" +#elif CXX_STD > 201703L + "20" +#elif CXX_STD >= 201703L + "17" +#elif CXX_STD >= 201402L + "14" +#elif CXX_STD >= 201103L + "11" +#else + "98" +#endif +"]"; + +const char* info_language_extensions_default = "INFO" ":" "extensions_default[" +/* !defined(_MSC_VER) to exclude Clang's MSVC compatibility mode. */ +#if (defined(__clang__) || defined(__GNUC__) || \ + defined(__TI_COMPILER_VERSION__)) && \ + !defined(__STRICT_ANSI__) && !defined(_MSC_VER) + "ON" +#else + "OFF" +#endif +"]"; + +/*--------------------------------------------------------------------------*/ + +int main(int argc, char* argv[]) +{ + int require = 0; + require += info_compiler[argc]; + require += info_platform[argc]; +#ifdef COMPILER_VERSION_MAJOR + require += info_version[argc]; +#endif +#ifdef COMPILER_VERSION_INTERNAL + require += info_version_internal[argc]; +#endif +#ifdef SIMULATE_ID + require += info_simulate[argc]; +#endif +#ifdef SIMULATE_VERSION_MAJOR + require += info_simulate_version[argc]; +#endif +#if defined(__CRAYXT_COMPUTE_LINUX_TARGET) + require += info_cray[argc]; +#endif + require += info_language_standard_default[argc]; + require += info_language_extensions_default[argc]; + (void)argv; + return require; +} diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CompilerIdCXX/a.out b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CompilerIdCXX/a.out new file mode 100644 index 0000000000000000000000000000000000000000..146208dc1744b80241653b13d63493a8766b32d5 Binary files /dev/null and b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CompilerIdCXX/a.out differ diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeDirectoryInformation.cmake b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeDirectoryInformation.cmake new file mode 100644 index 0000000000000000000000000000000000000000..18611c1a3181a71e5792abff5c1c77ebf78caa78 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeDirectoryInformation.cmake @@ -0,0 +1,16 @@ +# CMAKE generated file: DO NOT EDIT! +# Generated by "Unix Makefiles" Generator, CMake Version 3.22 + +# Relative path conversion top directories. +set(CMAKE_RELATIVE_PATH_TOP_SOURCE "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp") +set(CMAKE_RELATIVE_PATH_TOP_BINARY "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build") + +# Force unix paths in dependencies. +set(CMAKE_FORCE_UNIX_PATHS 1) + + +# The C and CXX include file regular expressions for this directory. +set(CMAKE_C_INCLUDE_REGEX_SCAN "^.*$") +set(CMAKE_C_INCLUDE_REGEX_COMPLAIN "^$") +set(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN}) +set(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN ${CMAKE_C_INCLUDE_REGEX_COMPLAIN}) diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeOutput.log b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeOutput.log new file mode 100644 index 0000000000000000000000000000000000000000..fc325057514bcf2cf98d792f22f84b0719229fc7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeOutput.log @@ -0,0 +1,844 @@ +The system is: Linux - 6.8.0-1057-aws - x86_64 +Compiling the C compiler identification source file "CMakeCCompilerId.c" succeeded. +Compiler: /usr/bin/cc +Build flags: +Id flags: + +The output was: +0 + + +Compilation of the C compiler identification source "CMakeCCompilerId.c" produced "a.out" + +The C compiler identification is GNU, found in "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CompilerIdC/a.out" + +Compiling the CXX compiler identification source file "CMakeCXXCompilerId.cpp" succeeded. +Compiler: /usr/bin/c++ +Build flags: +Id flags: + +The output was: +0 + + +Compilation of the CXX compiler identification source "CMakeCXXCompilerId.cpp" produced "a.out" + +The CXX compiler identification is GNU, found in "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/3.22.1/CompilerIdCXX/a.out" + +Detecting C compiler ABI info compiled with the following output: +Change Dir: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp + +Run Build Command(s):/usr/bin/gmake -f Makefile cmTC_1b267/fast && /usr/bin/gmake -f CMakeFiles/cmTC_1b267.dir/build.make CMakeFiles/cmTC_1b267.dir/build +gmake[1]: Entering directory '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp' +Building C object CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o +/usr/bin/cc -v -o CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o -c /usr/share/cmake-3.22/Modules/CMakeCCompilerABI.c +Using built-in specs. +COLLECT_GCC=/usr/bin/cc +OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa +OFFLOAD_TARGET_DEFAULT=1 +Target: x86_64-linux-gnu +Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2 +Thread model: posix +Supported LTO compression algorithms: zlib zstd +gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) +COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=generic' '-march=x86-64' '-dumpdir' 'CMakeFiles/cmTC_1b267.dir/' + /usr/lib/gcc/x86_64-linux-gnu/11/cc1 -quiet -v -imultiarch x86_64-linux-gnu /usr/share/cmake-3.22/Modules/CMakeCCompilerABI.c -quiet -dumpdir CMakeFiles/cmTC_1b267.dir/ -dumpbase CMakeCCompilerABI.c.c -dumpbase-ext .c -mtune=generic -march=x86-64 -version -fasynchronous-unwind-tables -fstack-protector-strong -Wformat -Wformat-security -fstack-clash-protection -fcf-protection -o /tmp/ccSfSg3L.s +GNU C17 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu) + compiled by GNU C version 11.4.0, GMP version 6.2.1, MPFR version 4.1.0, MPC version 1.2.1, isl version isl-0.24-GMP + +GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072 +ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu" +ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/include-fixed" +ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../x86_64-linux-gnu/include" +#include "..." search starts here: +#include <...> search starts here: + /usr/lib/gcc/x86_64-linux-gnu/11/include + /usr/local/include + /usr/include/x86_64-linux-gnu + /usr/include +End of search list. +GNU C17 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu) + compiled by GNU C version 11.4.0, GMP version 6.2.1, MPFR version 4.1.0, MPC version 1.2.1, isl version isl-0.24-GMP + +GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072 +Compiler executable checksum: 46ebede1f5b795a957a1e85cb61af9d8 +COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=generic' '-march=x86-64' '-dumpdir' 'CMakeFiles/cmTC_1b267.dir/' + as -v --64 -o CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o /tmp/ccSfSg3L.s +GNU assembler version 2.38 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.38 +COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/ +LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/ +COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=generic' '-march=x86-64' '-dumpdir' 'CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.' +Linking C executable cmTC_1b267 +/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_1b267.dir/link.txt --verbose=1 +/usr/bin/cc -v CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o -o cmTC_1b267 +Using built-in specs. +COLLECT_GCC=/usr/bin/cc +COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper +OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa +OFFLOAD_TARGET_DEFAULT=1 +Target: x86_64-linux-gnu +Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2 +Thread model: posix +Supported LTO compression algorithms: zlib zstd +gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) +COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/ +LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/ +COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_1b267' '-mtune=generic' '-march=x86-64' '-dumpdir' 'cmTC_1b267.' + /usr/lib/gcc/x86_64-linux-gnu/11/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/11/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper -plugin-opt=-fresolution=/tmp/ccuzAbQi.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_1b267 /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/11/crtbeginS.o -L/usr/lib/gcc/x86_64-linux-gnu/11 -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/11/../../.. CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o -lgcc --push-state --as-needed -lgcc_s --pop-state -lc -lgcc --push-state --as-needed -lgcc_s --pop-state /usr/lib/gcc/x86_64-linux-gnu/11/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crtn.o +COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_1b267' '-mtune=generic' '-march=x86-64' '-dumpdir' 'cmTC_1b267.' +gmake[1]: Leaving directory '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp' + + + +Parsed C implicit include dir info from above output: rv=done + found start of include info + found start of implicit include info + add: [/usr/lib/gcc/x86_64-linux-gnu/11/include] + add: [/usr/local/include] + add: [/usr/include/x86_64-linux-gnu] + add: [/usr/include] + end of search list found + collapse include dir [/usr/lib/gcc/x86_64-linux-gnu/11/include] ==> [/usr/lib/gcc/x86_64-linux-gnu/11/include] + collapse include dir [/usr/local/include] ==> [/usr/local/include] + collapse include dir [/usr/include/x86_64-linux-gnu] ==> [/usr/include/x86_64-linux-gnu] + collapse include dir [/usr/include] ==> [/usr/include] + implicit include dirs: [/usr/lib/gcc/x86_64-linux-gnu/11/include;/usr/local/include;/usr/include/x86_64-linux-gnu;/usr/include] + + +Parsed C implicit link information from above output: + link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] + ignore line: [Change Dir: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp] + ignore line: [] + ignore line: [Run Build Command(s):/usr/bin/gmake -f Makefile cmTC_1b267/fast && /usr/bin/gmake -f CMakeFiles/cmTC_1b267.dir/build.make CMakeFiles/cmTC_1b267.dir/build] + ignore line: [gmake[1]: Entering directory '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp'] + ignore line: [Building C object CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o] + ignore line: [/usr/bin/cc -v -o CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o -c /usr/share/cmake-3.22/Modules/CMakeCCompilerABI.c] + ignore line: [Using built-in specs.] + ignore line: [COLLECT_GCC=/usr/bin/cc] + ignore line: [OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa] + ignore line: [OFFLOAD_TARGET_DEFAULT=1] + ignore line: [Target: x86_64-linux-gnu] + ignore line: [Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c ada c++ go brig d fortran objc obj-c++ m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32 m64 mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2] + ignore line: [Thread model: posix] + ignore line: [Supported LTO compression algorithms: zlib zstd] + ignore line: [gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) ] + ignore line: [COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=generic' '-march=x86-64' '-dumpdir' 'CMakeFiles/cmTC_1b267.dir/'] + ignore line: [ /usr/lib/gcc/x86_64-linux-gnu/11/cc1 -quiet -v -imultiarch x86_64-linux-gnu /usr/share/cmake-3.22/Modules/CMakeCCompilerABI.c -quiet -dumpdir CMakeFiles/cmTC_1b267.dir/ -dumpbase CMakeCCompilerABI.c.c -dumpbase-ext .c -mtune=generic -march=x86-64 -version -fasynchronous-unwind-tables -fstack-protector-strong -Wformat -Wformat-security -fstack-clash-protection -fcf-protection -o /tmp/ccSfSg3L.s] + ignore line: [GNU C17 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu)] + ignore line: [ compiled by GNU C version 11.4.0 GMP version 6.2.1 MPFR version 4.1.0 MPC version 1.2.1 isl version isl-0.24-GMP] + ignore line: [] + ignore line: [GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072] + ignore line: [ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"] + ignore line: [ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/include-fixed"] + ignore line: [ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../x86_64-linux-gnu/include"] + ignore line: [#include "..." search starts here:] + ignore line: [#include <...> search starts here:] + ignore line: [ /usr/lib/gcc/x86_64-linux-gnu/11/include] + ignore line: [ /usr/local/include] + ignore line: [ /usr/include/x86_64-linux-gnu] + ignore line: [ /usr/include] + ignore line: [End of search list.] + ignore line: [GNU C17 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu)] + ignore line: [ compiled by GNU C version 11.4.0 GMP version 6.2.1 MPFR version 4.1.0 MPC version 1.2.1 isl version isl-0.24-GMP] + ignore line: [] + ignore line: [GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072] + ignore line: [Compiler executable checksum: 46ebede1f5b795a957a1e85cb61af9d8] + ignore line: [COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=generic' '-march=x86-64' '-dumpdir' 'CMakeFiles/cmTC_1b267.dir/'] + ignore line: [ as -v --64 -o CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o /tmp/ccSfSg3L.s] + ignore line: [GNU assembler version 2.38 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.38] + ignore line: [COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/] + ignore line: [LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/] + ignore line: [COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o' '-c' '-mtune=generic' '-march=x86-64' '-dumpdir' 'CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.'] + ignore line: [Linking C executable cmTC_1b267] + ignore line: [/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_1b267.dir/link.txt --verbose=1] + ignore line: [/usr/bin/cc -v CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o -o cmTC_1b267 ] + ignore line: [Using built-in specs.] + ignore line: [COLLECT_GCC=/usr/bin/cc] + ignore line: [COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper] + ignore line: [OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa] + ignore line: [OFFLOAD_TARGET_DEFAULT=1] + ignore line: [Target: x86_64-linux-gnu] + ignore line: [Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c ada c++ go brig d fortran objc obj-c++ m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32 m64 mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2] + ignore line: [Thread model: posix] + ignore line: [Supported LTO compression algorithms: zlib zstd] + ignore line: [gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) ] + ignore line: [COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/] + ignore line: [LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/] + ignore line: [COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_1b267' '-mtune=generic' '-march=x86-64' '-dumpdir' 'cmTC_1b267.'] + link line: [ /usr/lib/gcc/x86_64-linux-gnu/11/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/11/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper -plugin-opt=-fresolution=/tmp/ccuzAbQi.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_1b267 /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/11/crtbeginS.o -L/usr/lib/gcc/x86_64-linux-gnu/11 -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/11/../../.. CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o -lgcc --push-state --as-needed -lgcc_s --pop-state -lc -lgcc --push-state --as-needed -lgcc_s --pop-state /usr/lib/gcc/x86_64-linux-gnu/11/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crtn.o] + arg [/usr/lib/gcc/x86_64-linux-gnu/11/collect2] ==> ignore + arg [-plugin] ==> ignore + arg [/usr/lib/gcc/x86_64-linux-gnu/11/liblto_plugin.so] ==> ignore + arg [-plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper] ==> ignore + arg [-plugin-opt=-fresolution=/tmp/ccuzAbQi.res] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc_s] ==> ignore + arg [-plugin-opt=-pass-through=-lc] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc_s] ==> ignore + arg [--build-id] ==> ignore + arg [--eh-frame-hdr] ==> ignore + arg [-m] ==> ignore + arg [elf_x86_64] ==> ignore + arg [--hash-style=gnu] ==> ignore + arg [--as-needed] ==> ignore + arg [-dynamic-linker] ==> ignore + arg [/lib64/ld-linux-x86-64.so.2] ==> ignore + arg [-pie] ==> ignore + arg [-znow] ==> ignore + arg [-zrelro] ==> ignore + arg [-o] ==> ignore + arg [cmTC_1b267] ==> ignore + arg [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o] ==> obj [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o] + arg [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crti.o] ==> obj [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crti.o] + arg [/usr/lib/gcc/x86_64-linux-gnu/11/crtbeginS.o] ==> obj [/usr/lib/gcc/x86_64-linux-gnu/11/crtbeginS.o] + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11] + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu] + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib] + arg [-L/lib/x86_64-linux-gnu] ==> dir [/lib/x86_64-linux-gnu] + arg [-L/lib/../lib] ==> dir [/lib/../lib] + arg [-L/usr/lib/x86_64-linux-gnu] ==> dir [/usr/lib/x86_64-linux-gnu] + arg [-L/usr/lib/../lib] ==> dir [/usr/lib/../lib] + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11/../../..] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../..] + arg [CMakeFiles/cmTC_1b267.dir/CMakeCCompilerABI.c.o] ==> ignore + arg [-lgcc] ==> lib [gcc] + arg [--push-state] ==> ignore + arg [--as-needed] ==> ignore + arg [-lgcc_s] ==> lib [gcc_s] + arg [--pop-state] ==> ignore + arg [-lc] ==> lib [c] + arg [-lgcc] ==> lib [gcc] + arg [--push-state] ==> ignore + arg [--as-needed] ==> ignore + arg [-lgcc_s] ==> lib [gcc_s] + arg [--pop-state] ==> ignore + arg [/usr/lib/gcc/x86_64-linux-gnu/11/crtendS.o] ==> obj [/usr/lib/gcc/x86_64-linux-gnu/11/crtendS.o] + arg [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crtn.o] ==> obj [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crtn.o] + collapse obj [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o] ==> [/usr/lib/x86_64-linux-gnu/Scrt1.o] + collapse obj [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crti.o] ==> [/usr/lib/x86_64-linux-gnu/crti.o] + collapse obj [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crtn.o] ==> [/usr/lib/x86_64-linux-gnu/crtn.o] + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11] ==> [/usr/lib/gcc/x86_64-linux-gnu/11] + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu] ==> [/usr/lib/x86_64-linux-gnu] + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib] ==> [/usr/lib] + collapse library dir [/lib/x86_64-linux-gnu] ==> [/lib/x86_64-linux-gnu] + collapse library dir [/lib/../lib] ==> [/lib] + collapse library dir [/usr/lib/x86_64-linux-gnu] ==> [/usr/lib/x86_64-linux-gnu] + collapse library dir [/usr/lib/../lib] ==> [/usr/lib] + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../..] ==> [/usr/lib] + implicit libs: [gcc;gcc_s;c;gcc;gcc_s] + implicit objs: [/usr/lib/x86_64-linux-gnu/Scrt1.o;/usr/lib/x86_64-linux-gnu/crti.o;/usr/lib/gcc/x86_64-linux-gnu/11/crtbeginS.o;/usr/lib/gcc/x86_64-linux-gnu/11/crtendS.o;/usr/lib/x86_64-linux-gnu/crtn.o] + implicit dirs: [/usr/lib/gcc/x86_64-linux-gnu/11;/usr/lib/x86_64-linux-gnu;/usr/lib;/lib/x86_64-linux-gnu;/lib] + implicit fwks: [] + + +Detecting CXX compiler ABI info compiled with the following output: +Change Dir: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp + +Run Build Command(s):/usr/bin/gmake -f Makefile cmTC_e81db/fast && /usr/bin/gmake -f CMakeFiles/cmTC_e81db.dir/build.make CMakeFiles/cmTC_e81db.dir/build +gmake[1]: Entering directory '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp' +Building CXX object CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o +/usr/bin/c++ -v -o CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o -c /usr/share/cmake-3.22/Modules/CMakeCXXCompilerABI.cpp +Using built-in specs. +COLLECT_GCC=/usr/bin/c++ +OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa +OFFLOAD_TARGET_DEFAULT=1 +Target: x86_64-linux-gnu +Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2 +Thread model: posix +Supported LTO compression algorithms: zlib zstd +gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) +COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-dumpdir' 'CMakeFiles/cmTC_e81db.dir/' + /usr/lib/gcc/x86_64-linux-gnu/11/cc1plus -quiet -v -imultiarch x86_64-linux-gnu -D_GNU_SOURCE /usr/share/cmake-3.22/Modules/CMakeCXXCompilerABI.cpp -quiet -dumpdir CMakeFiles/cmTC_e81db.dir/ -dumpbase CMakeCXXCompilerABI.cpp.cpp -dumpbase-ext .cpp -mtune=generic -march=x86-64 -version -fasynchronous-unwind-tables -fstack-protector-strong -Wformat -Wformat-security -fstack-clash-protection -fcf-protection -o /tmp/ccth3fUT.s +GNU C++17 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu) + compiled by GNU C version 11.4.0, GMP version 6.2.1, MPFR version 4.1.0, MPC version 1.2.1, isl version isl-0.24-GMP + +GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072 +ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/11" +ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu" +ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/include-fixed" +ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../x86_64-linux-gnu/include" +#include "..." search starts here: +#include <...> search starts here: + /usr/include/c++/11 + /usr/include/x86_64-linux-gnu/c++/11 + /usr/include/c++/11/backward + /usr/lib/gcc/x86_64-linux-gnu/11/include + /usr/local/include + /usr/include/x86_64-linux-gnu + /usr/include +End of search list. +GNU C++17 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu) + compiled by GNU C version 11.4.0, GMP version 6.2.1, MPFR version 4.1.0, MPC version 1.2.1, isl version isl-0.24-GMP + +GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072 +Compiler executable checksum: ac7fa628ee459f217e6fdb88b3db0bde +COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-dumpdir' 'CMakeFiles/cmTC_e81db.dir/' + as -v --64 -o CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o /tmp/ccth3fUT.s +GNU assembler version 2.38 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.38 +COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/ +LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/ +COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-dumpdir' 'CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.' +Linking CXX executable cmTC_e81db +/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_e81db.dir/link.txt --verbose=1 +/usr/bin/c++ -v CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_e81db +Using built-in specs. +COLLECT_GCC=/usr/bin/c++ +COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper +OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa +OFFLOAD_TARGET_DEFAULT=1 +Target: x86_64-linux-gnu +Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2 +Thread model: posix +Supported LTO compression algorithms: zlib zstd +gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) +COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/ +LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/ +COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_e81db' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-dumpdir' 'cmTC_e81db.' + /usr/lib/gcc/x86_64-linux-gnu/11/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/11/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper -plugin-opt=-fresolution=/tmp/cc5I0jdX.res -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_e81db /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/11/crtbeginS.o -L/usr/lib/gcc/x86_64-linux-gnu/11 -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/11/../../.. CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o -lstdc++ -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/lib/gcc/x86_64-linux-gnu/11/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crtn.o +COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_e81db' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-dumpdir' 'cmTC_e81db.' +gmake[1]: Leaving directory '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp' + + + +Parsed CXX implicit include dir info from above output: rv=done + found start of include info + found start of implicit include info + add: [/usr/include/c++/11] + add: [/usr/include/x86_64-linux-gnu/c++/11] + add: [/usr/include/c++/11/backward] + add: [/usr/lib/gcc/x86_64-linux-gnu/11/include] + add: [/usr/local/include] + add: [/usr/include/x86_64-linux-gnu] + add: [/usr/include] + end of search list found + collapse include dir [/usr/include/c++/11] ==> [/usr/include/c++/11] + collapse include dir [/usr/include/x86_64-linux-gnu/c++/11] ==> [/usr/include/x86_64-linux-gnu/c++/11] + collapse include dir [/usr/include/c++/11/backward] ==> [/usr/include/c++/11/backward] + collapse include dir [/usr/lib/gcc/x86_64-linux-gnu/11/include] ==> [/usr/lib/gcc/x86_64-linux-gnu/11/include] + collapse include dir [/usr/local/include] ==> [/usr/local/include] + collapse include dir [/usr/include/x86_64-linux-gnu] ==> [/usr/include/x86_64-linux-gnu] + collapse include dir [/usr/include] ==> [/usr/include] + implicit include dirs: [/usr/include/c++/11;/usr/include/x86_64-linux-gnu/c++/11;/usr/include/c++/11/backward;/usr/lib/gcc/x86_64-linux-gnu/11/include;/usr/local/include;/usr/include/x86_64-linux-gnu;/usr/include] + + +Parsed CXX implicit link information from above output: + link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] + ignore line: [Change Dir: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp] + ignore line: [] + ignore line: [Run Build Command(s):/usr/bin/gmake -f Makefile cmTC_e81db/fast && /usr/bin/gmake -f CMakeFiles/cmTC_e81db.dir/build.make CMakeFiles/cmTC_e81db.dir/build] + ignore line: [gmake[1]: Entering directory '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp'] + ignore line: [Building CXX object CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o] + ignore line: [/usr/bin/c++ -v -o CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o -c /usr/share/cmake-3.22/Modules/CMakeCXXCompilerABI.cpp] + ignore line: [Using built-in specs.] + ignore line: [COLLECT_GCC=/usr/bin/c++] + ignore line: [OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa] + ignore line: [OFFLOAD_TARGET_DEFAULT=1] + ignore line: [Target: x86_64-linux-gnu] + ignore line: [Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c ada c++ go brig d fortran objc obj-c++ m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32 m64 mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2] + ignore line: [Thread model: posix] + ignore line: [Supported LTO compression algorithms: zlib zstd] + ignore line: [gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) ] + ignore line: [COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-dumpdir' 'CMakeFiles/cmTC_e81db.dir/'] + ignore line: [ /usr/lib/gcc/x86_64-linux-gnu/11/cc1plus -quiet -v -imultiarch x86_64-linux-gnu -D_GNU_SOURCE /usr/share/cmake-3.22/Modules/CMakeCXXCompilerABI.cpp -quiet -dumpdir CMakeFiles/cmTC_e81db.dir/ -dumpbase CMakeCXXCompilerABI.cpp.cpp -dumpbase-ext .cpp -mtune=generic -march=x86-64 -version -fasynchronous-unwind-tables -fstack-protector-strong -Wformat -Wformat-security -fstack-clash-protection -fcf-protection -o /tmp/ccth3fUT.s] + ignore line: [GNU C++17 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu)] + ignore line: [ compiled by GNU C version 11.4.0 GMP version 6.2.1 MPFR version 4.1.0 MPC version 1.2.1 isl version isl-0.24-GMP] + ignore line: [] + ignore line: [GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072] + ignore line: [ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/11"] + ignore line: [ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"] + ignore line: [ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/include-fixed"] + ignore line: [ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../x86_64-linux-gnu/include"] + ignore line: [#include "..." search starts here:] + ignore line: [#include <...> search starts here:] + ignore line: [ /usr/include/c++/11] + ignore line: [ /usr/include/x86_64-linux-gnu/c++/11] + ignore line: [ /usr/include/c++/11/backward] + ignore line: [ /usr/lib/gcc/x86_64-linux-gnu/11/include] + ignore line: [ /usr/local/include] + ignore line: [ /usr/include/x86_64-linux-gnu] + ignore line: [ /usr/include] + ignore line: [End of search list.] + ignore line: [GNU C++17 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu)] + ignore line: [ compiled by GNU C version 11.4.0 GMP version 6.2.1 MPFR version 4.1.0 MPC version 1.2.1 isl version isl-0.24-GMP] + ignore line: [] + ignore line: [GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072] + ignore line: [Compiler executable checksum: ac7fa628ee459f217e6fdb88b3db0bde] + ignore line: [COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-dumpdir' 'CMakeFiles/cmTC_e81db.dir/'] + ignore line: [ as -v --64 -o CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o /tmp/ccth3fUT.s] + ignore line: [GNU assembler version 2.38 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.38] + ignore line: [COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/] + ignore line: [LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/] + ignore line: [COLLECT_GCC_OPTIONS='-v' '-o' 'CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-dumpdir' 'CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.'] + ignore line: [Linking CXX executable cmTC_e81db] + ignore line: [/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_e81db.dir/link.txt --verbose=1] + ignore line: [/usr/bin/c++ -v CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o -o cmTC_e81db ] + ignore line: [Using built-in specs.] + ignore line: [COLLECT_GCC=/usr/bin/c++] + ignore line: [COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper] + ignore line: [OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa] + ignore line: [OFFLOAD_TARGET_DEFAULT=1] + ignore line: [Target: x86_64-linux-gnu] + ignore line: [Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c ada c++ go brig d fortran objc obj-c++ m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32 m64 mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2] + ignore line: [Thread model: posix] + ignore line: [Supported LTO compression algorithms: zlib zstd] + ignore line: [gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) ] + ignore line: [COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/] + ignore line: [LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/] + ignore line: [COLLECT_GCC_OPTIONS='-v' '-o' 'cmTC_e81db' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-dumpdir' 'cmTC_e81db.'] + link line: [ /usr/lib/gcc/x86_64-linux-gnu/11/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/11/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper -plugin-opt=-fresolution=/tmp/cc5I0jdX.res -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_e81db /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/11/crtbeginS.o -L/usr/lib/gcc/x86_64-linux-gnu/11 -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/11/../../.. CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o -lstdc++ -lm -lgcc_s -lgcc -lc -lgcc_s -lgcc /usr/lib/gcc/x86_64-linux-gnu/11/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crtn.o] + arg [/usr/lib/gcc/x86_64-linux-gnu/11/collect2] ==> ignore + arg [-plugin] ==> ignore + arg [/usr/lib/gcc/x86_64-linux-gnu/11/liblto_plugin.so] ==> ignore + arg [-plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper] ==> ignore + arg [-plugin-opt=-fresolution=/tmp/cc5I0jdX.res] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc_s] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc] ==> ignore + arg [-plugin-opt=-pass-through=-lc] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc_s] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc] ==> ignore + arg [--build-id] ==> ignore + arg [--eh-frame-hdr] ==> ignore + arg [-m] ==> ignore + arg [elf_x86_64] ==> ignore + arg [--hash-style=gnu] ==> ignore + arg [--as-needed] ==> ignore + arg [-dynamic-linker] ==> ignore + arg [/lib64/ld-linux-x86-64.so.2] ==> ignore + arg [-pie] ==> ignore + arg [-znow] ==> ignore + arg [-zrelro] ==> ignore + arg [-o] ==> ignore + arg [cmTC_e81db] ==> ignore + arg [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o] ==> obj [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o] + arg [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crti.o] ==> obj [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crti.o] + arg [/usr/lib/gcc/x86_64-linux-gnu/11/crtbeginS.o] ==> obj [/usr/lib/gcc/x86_64-linux-gnu/11/crtbeginS.o] + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11] + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu] + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib] + arg [-L/lib/x86_64-linux-gnu] ==> dir [/lib/x86_64-linux-gnu] + arg [-L/lib/../lib] ==> dir [/lib/../lib] + arg [-L/usr/lib/x86_64-linux-gnu] ==> dir [/usr/lib/x86_64-linux-gnu] + arg [-L/usr/lib/../lib] ==> dir [/usr/lib/../lib] + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11/../../..] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../..] + arg [CMakeFiles/cmTC_e81db.dir/CMakeCXXCompilerABI.cpp.o] ==> ignore + arg [-lstdc++] ==> lib [stdc++] + arg [-lm] ==> lib [m] + arg [-lgcc_s] ==> lib [gcc_s] + arg [-lgcc] ==> lib [gcc] + arg [-lc] ==> lib [c] + arg [-lgcc_s] ==> lib [gcc_s] + arg [-lgcc] ==> lib [gcc] + arg [/usr/lib/gcc/x86_64-linux-gnu/11/crtendS.o] ==> obj [/usr/lib/gcc/x86_64-linux-gnu/11/crtendS.o] + arg [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crtn.o] ==> obj [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crtn.o] + collapse obj [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o] ==> [/usr/lib/x86_64-linux-gnu/Scrt1.o] + collapse obj [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crti.o] ==> [/usr/lib/x86_64-linux-gnu/crti.o] + collapse obj [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crtn.o] ==> [/usr/lib/x86_64-linux-gnu/crtn.o] + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11] ==> [/usr/lib/gcc/x86_64-linux-gnu/11] + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu] ==> [/usr/lib/x86_64-linux-gnu] + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib] ==> [/usr/lib] + collapse library dir [/lib/x86_64-linux-gnu] ==> [/lib/x86_64-linux-gnu] + collapse library dir [/lib/../lib] ==> [/lib] + collapse library dir [/usr/lib/x86_64-linux-gnu] ==> [/usr/lib/x86_64-linux-gnu] + collapse library dir [/usr/lib/../lib] ==> [/usr/lib] + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../..] ==> [/usr/lib] + implicit libs: [stdc++;m;gcc_s;gcc;c;gcc_s;gcc] + implicit objs: [/usr/lib/x86_64-linux-gnu/Scrt1.o;/usr/lib/x86_64-linux-gnu/crti.o;/usr/lib/gcc/x86_64-linux-gnu/11/crtbeginS.o;/usr/lib/gcc/x86_64-linux-gnu/11/crtendS.o;/usr/lib/x86_64-linux-gnu/crtn.o] + implicit dirs: [/usr/lib/gcc/x86_64-linux-gnu/11;/usr/lib/x86_64-linux-gnu;/usr/lib;/lib/x86_64-linux-gnu;/lib] + implicit fwks: [] + + +Detecting C OpenMP compiler ABI info compiled with the following output: +Change Dir: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp + +Run Build Command(s):/usr/bin/gmake -f Makefile cmTC_a5198/fast && /usr/bin/gmake -f CMakeFiles/cmTC_a5198.dir/build.make CMakeFiles/cmTC_a5198.dir/build +gmake[1]: Entering directory '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp' +Building C object CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o +/usr/bin/cc -fopenmp -v -o CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o -c /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPTryFlag.c +Using built-in specs. +COLLECT_GCC=/usr/bin/cc +OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa +OFFLOAD_TARGET_DEFAULT=1 +Target: x86_64-linux-gnu +Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2 +Thread model: posix +Supported LTO compression algorithms: zlib zstd +gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) +COLLECT_GCC_OPTIONS='-fopenmp' '-v' '-o' 'CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o' '-c' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'CMakeFiles/cmTC_a5198.dir/' + /usr/lib/gcc/x86_64-linux-gnu/11/cc1 -quiet -v -imultiarch x86_64-linux-gnu -D_REENTRANT /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPTryFlag.c -quiet -dumpdir CMakeFiles/cmTC_a5198.dir/ -dumpbase OpenMPTryFlag.c.c -dumpbase-ext .c -mtune=generic -march=x86-64 -version -fopenmp -fasynchronous-unwind-tables -fstack-protector-strong -Wformat -Wformat-security -fstack-clash-protection -fcf-protection -o /tmp/cc63qu6S.s +GNU C17 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu) + compiled by GNU C version 11.4.0, GMP version 6.2.1, MPFR version 4.1.0, MPC version 1.2.1, isl version isl-0.24-GMP + +GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072 +ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu" +ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/include-fixed" +ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../x86_64-linux-gnu/include" +#include "..." search starts here: +#include <...> search starts here: + /usr/lib/gcc/x86_64-linux-gnu/11/include + /usr/local/include + /usr/include/x86_64-linux-gnu + /usr/include +End of search list. +GNU C17 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu) + compiled by GNU C version 11.4.0, GMP version 6.2.1, MPFR version 4.1.0, MPC version 1.2.1, isl version isl-0.24-GMP + +GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072 +Compiler executable checksum: 46ebede1f5b795a957a1e85cb61af9d8 +COLLECT_GCC_OPTIONS='-fopenmp' '-v' '-o' 'CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o' '-c' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'CMakeFiles/cmTC_a5198.dir/' + as -v --64 -o CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o /tmp/cc63qu6S.s +GNU assembler version 2.38 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.38 +COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/ +LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/ +COLLECT_GCC_OPTIONS='-fopenmp' '-v' '-o' 'CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o' '-c' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.' +Linking C executable cmTC_a5198 +/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_a5198.dir/link.txt --verbose=1 +/usr/bin/cc -fopenmp -v CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o -o cmTC_a5198 -v +Using built-in specs. +COLLECT_GCC=/usr/bin/cc +COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper +OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa +OFFLOAD_TARGET_DEFAULT=1 +Target: x86_64-linux-gnu +Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2 +Thread model: posix +Supported LTO compression algorithms: zlib zstd +gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) +COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/ +LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/ +Reading specs from /usr/lib/gcc/x86_64-linux-gnu/11/libgomp.spec +COLLECT_GCC_OPTIONS='-fopenmp' '-v' '-o' 'cmTC_a5198' '-v' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'cmTC_a5198.' + /usr/lib/gcc/x86_64-linux-gnu/11/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/11/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper -plugin-opt=-fresolution=/tmp/cc5PLFIf.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lpthread -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_a5198 /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/11/crtbeginS.o /usr/lib/gcc/x86_64-linux-gnu/11/crtoffloadbegin.o -L/usr/lib/gcc/x86_64-linux-gnu/11 -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/11/../../.. CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o -lgomp -lgcc --push-state --as-needed -lgcc_s --pop-state -lpthread -lc -lgcc --push-state --as-needed -lgcc_s --pop-state /usr/lib/gcc/x86_64-linux-gnu/11/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crtn.o /usr/lib/gcc/x86_64-linux-gnu/11/crtoffloadend.o +COLLECT_GCC_OPTIONS='-fopenmp' '-v' '-o' 'cmTC_a5198' '-v' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'cmTC_a5198.' +gmake[1]: Leaving directory '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp' + + + +Parsed C OpenMP implicit link information from above output: + link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] + ignore line: [Change Dir: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp] + ignore line: [] + ignore line: [Run Build Command(s):/usr/bin/gmake -f Makefile cmTC_a5198/fast && /usr/bin/gmake -f CMakeFiles/cmTC_a5198.dir/build.make CMakeFiles/cmTC_a5198.dir/build] + ignore line: [gmake[1]: Entering directory '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp'] + ignore line: [Building C object CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o] + ignore line: [/usr/bin/cc -fopenmp -v -o CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o -c /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPTryFlag.c] + ignore line: [Using built-in specs.] + ignore line: [COLLECT_GCC=/usr/bin/cc] + ignore line: [OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa] + ignore line: [OFFLOAD_TARGET_DEFAULT=1] + ignore line: [Target: x86_64-linux-gnu] + ignore line: [Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c ada c++ go brig d fortran objc obj-c++ m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32 m64 mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2] + ignore line: [Thread model: posix] + ignore line: [Supported LTO compression algorithms: zlib zstd] + ignore line: [gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) ] + ignore line: [COLLECT_GCC_OPTIONS='-fopenmp' '-v' '-o' 'CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o' '-c' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'CMakeFiles/cmTC_a5198.dir/'] + ignore line: [ /usr/lib/gcc/x86_64-linux-gnu/11/cc1 -quiet -v -imultiarch x86_64-linux-gnu -D_REENTRANT /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPTryFlag.c -quiet -dumpdir CMakeFiles/cmTC_a5198.dir/ -dumpbase OpenMPTryFlag.c.c -dumpbase-ext .c -mtune=generic -march=x86-64 -version -fopenmp -fasynchronous-unwind-tables -fstack-protector-strong -Wformat -Wformat-security -fstack-clash-protection -fcf-protection -o /tmp/cc63qu6S.s] + ignore line: [GNU C17 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu)] + ignore line: [ compiled by GNU C version 11.4.0 GMP version 6.2.1 MPFR version 4.1.0 MPC version 1.2.1 isl version isl-0.24-GMP] + ignore line: [] + ignore line: [GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072] + ignore line: [ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"] + ignore line: [ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/include-fixed"] + ignore line: [ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../x86_64-linux-gnu/include"] + ignore line: [#include "..." search starts here:] + ignore line: [#include <...> search starts here:] + ignore line: [ /usr/lib/gcc/x86_64-linux-gnu/11/include] + ignore line: [ /usr/local/include] + ignore line: [ /usr/include/x86_64-linux-gnu] + ignore line: [ /usr/include] + ignore line: [End of search list.] + ignore line: [GNU C17 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu)] + ignore line: [ compiled by GNU C version 11.4.0 GMP version 6.2.1 MPFR version 4.1.0 MPC version 1.2.1 isl version isl-0.24-GMP] + ignore line: [] + ignore line: [GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072] + ignore line: [Compiler executable checksum: 46ebede1f5b795a957a1e85cb61af9d8] + ignore line: [COLLECT_GCC_OPTIONS='-fopenmp' '-v' '-o' 'CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o' '-c' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'CMakeFiles/cmTC_a5198.dir/'] + ignore line: [ as -v --64 -o CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o /tmp/cc63qu6S.s] + ignore line: [GNU assembler version 2.38 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.38] + ignore line: [COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/] + ignore line: [LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/] + ignore line: [COLLECT_GCC_OPTIONS='-fopenmp' '-v' '-o' 'CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o' '-c' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.'] + ignore line: [Linking C executable cmTC_a5198] + ignore line: [/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_a5198.dir/link.txt --verbose=1] + ignore line: [/usr/bin/cc -fopenmp -v CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o -o cmTC_a5198 -v ] + ignore line: [Using built-in specs.] + ignore line: [COLLECT_GCC=/usr/bin/cc] + ignore line: [COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper] + ignore line: [OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa] + ignore line: [OFFLOAD_TARGET_DEFAULT=1] + ignore line: [Target: x86_64-linux-gnu] + ignore line: [Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c ada c++ go brig d fortran objc obj-c++ m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32 m64 mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2] + ignore line: [Thread model: posix] + ignore line: [Supported LTO compression algorithms: zlib zstd] + ignore line: [gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) ] + ignore line: [COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/] + ignore line: [LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/] + ignore line: [Reading specs from /usr/lib/gcc/x86_64-linux-gnu/11/libgomp.spec] + ignore line: [COLLECT_GCC_OPTIONS='-fopenmp' '-v' '-o' 'cmTC_a5198' '-v' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'cmTC_a5198.'] + link line: [ /usr/lib/gcc/x86_64-linux-gnu/11/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/11/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper -plugin-opt=-fresolution=/tmp/cc5PLFIf.res -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lpthread -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lgcc_s --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_a5198 /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/11/crtbeginS.o /usr/lib/gcc/x86_64-linux-gnu/11/crtoffloadbegin.o -L/usr/lib/gcc/x86_64-linux-gnu/11 -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/11/../../.. CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o -lgomp -lgcc --push-state --as-needed -lgcc_s --pop-state -lpthread -lc -lgcc --push-state --as-needed -lgcc_s --pop-state /usr/lib/gcc/x86_64-linux-gnu/11/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crtn.o /usr/lib/gcc/x86_64-linux-gnu/11/crtoffloadend.o] + arg [/usr/lib/gcc/x86_64-linux-gnu/11/collect2] ==> ignore + arg [-plugin] ==> ignore + arg [/usr/lib/gcc/x86_64-linux-gnu/11/liblto_plugin.so] ==> ignore + arg [-plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper] ==> ignore + arg [-plugin-opt=-fresolution=/tmp/cc5PLFIf.res] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc_s] ==> ignore + arg [-plugin-opt=-pass-through=-lpthread] ==> ignore + arg [-plugin-opt=-pass-through=-lc] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc_s] ==> ignore + arg [--build-id] ==> ignore + arg [--eh-frame-hdr] ==> ignore + arg [-m] ==> ignore + arg [elf_x86_64] ==> ignore + arg [--hash-style=gnu] ==> ignore + arg [--as-needed] ==> ignore + arg [-dynamic-linker] ==> ignore + arg [/lib64/ld-linux-x86-64.so.2] ==> ignore + arg [-pie] ==> ignore + arg [-znow] ==> ignore + arg [-zrelro] ==> ignore + arg [-o] ==> ignore + arg [cmTC_a5198] ==> ignore + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11] + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu] + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib] + arg [-L/lib/x86_64-linux-gnu] ==> dir [/lib/x86_64-linux-gnu] + arg [-L/lib/../lib] ==> dir [/lib/../lib] + arg [-L/usr/lib/x86_64-linux-gnu] ==> dir [/usr/lib/x86_64-linux-gnu] + arg [-L/usr/lib/../lib] ==> dir [/usr/lib/../lib] + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11/../../..] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../..] + arg [CMakeFiles/cmTC_a5198.dir/OpenMPTryFlag.c.o] ==> ignore + arg [-lgomp] ==> lib [gomp] + arg [-lgcc] ==> lib [gcc] + arg [--push-state] ==> ignore + arg [--as-needed] ==> ignore + arg [-lgcc_s] ==> lib [gcc_s] + arg [--pop-state] ==> ignore + arg [-lpthread] ==> lib [pthread] + arg [-lc] ==> lib [c] + arg [-lgcc] ==> lib [gcc] + arg [--push-state] ==> ignore + arg [--as-needed] ==> ignore + arg [-lgcc_s] ==> lib [gcc_s] + arg [--pop-state] ==> ignore + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11] ==> [/usr/lib/gcc/x86_64-linux-gnu/11] + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu] ==> [/usr/lib/x86_64-linux-gnu] + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib] ==> [/usr/lib] + collapse library dir [/lib/x86_64-linux-gnu] ==> [/lib/x86_64-linux-gnu] + collapse library dir [/lib/../lib] ==> [/lib] + collapse library dir [/usr/lib/x86_64-linux-gnu] ==> [/usr/lib/x86_64-linux-gnu] + collapse library dir [/usr/lib/../lib] ==> [/usr/lib] + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../..] ==> [/usr/lib] + implicit libs: [gomp;gcc;gcc_s;pthread;c;gcc;gcc_s] + implicit objs: [] + implicit dirs: [/usr/lib/gcc/x86_64-linux-gnu/11;/usr/lib/x86_64-linux-gnu;/usr/lib;/lib/x86_64-linux-gnu;/lib] + implicit fwks: [] + + +Detecting CXX OpenMP compiler ABI info compiled with the following output: +Change Dir: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp + +Run Build Command(s):/usr/bin/gmake -f Makefile cmTC_f6f2d/fast && /usr/bin/gmake -f CMakeFiles/cmTC_f6f2d.dir/build.make CMakeFiles/cmTC_f6f2d.dir/build +gmake[1]: Entering directory '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp' +Building CXX object CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o +/usr/bin/c++ -std=c++14 -fopenmp -g3 -O3 -fopenmp -v -o CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o -c /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPTryFlag.cpp +Using built-in specs. +COLLECT_GCC=/usr/bin/c++ +OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa +OFFLOAD_TARGET_DEFAULT=1 +Target: x86_64-linux-gnu +Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2 +Thread model: posix +Supported LTO compression algorithms: zlib zstd +gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) +COLLECT_GCC_OPTIONS='-std=c++14' '-g3' '-O3' '-fopenmp' '-v' '-o' 'CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'CMakeFiles/cmTC_f6f2d.dir/' + /usr/lib/gcc/x86_64-linux-gnu/11/cc1plus -quiet -v -imultiarch x86_64-linux-gnu -dD -D_GNU_SOURCE -D_REENTRANT /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPTryFlag.cpp -quiet -dumpdir CMakeFiles/cmTC_f6f2d.dir/ -dumpbase OpenMPTryFlag.cpp.cpp -dumpbase-ext .cpp -mtune=generic -march=x86-64 -g3 -O3 -std=c++14 -version -fopenmp -fasynchronous-unwind-tables -fstack-protector-strong -Wformat -Wformat-security -fstack-clash-protection -fcf-protection -o /tmp/cccxfRSr.s +GNU C++14 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu) + compiled by GNU C version 11.4.0, GMP version 6.2.1, MPFR version 4.1.0, MPC version 1.2.1, isl version isl-0.24-GMP + +GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072 +ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/11" +ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu" +ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/include-fixed" +ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../x86_64-linux-gnu/include" +#include "..." search starts here: +#include <...> search starts here: + /usr/include/c++/11 + /usr/include/x86_64-linux-gnu/c++/11 + /usr/include/c++/11/backward + /usr/lib/gcc/x86_64-linux-gnu/11/include + /usr/local/include + /usr/include/x86_64-linux-gnu + /usr/include +End of search list. +GNU C++14 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu) + compiled by GNU C version 11.4.0, GMP version 6.2.1, MPFR version 4.1.0, MPC version 1.2.1, isl version isl-0.24-GMP + +GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072 +Compiler executable checksum: ac7fa628ee459f217e6fdb88b3db0bde +COLLECT_GCC_OPTIONS='-std=c++14' '-g3' '-O3' '-fopenmp' '-v' '-o' 'CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'CMakeFiles/cmTC_f6f2d.dir/' + as -v --gdwarf-5 --64 -o CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o /tmp/cccxfRSr.s +GNU assembler version 2.38 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.38 +COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/ +LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/ +COLLECT_GCC_OPTIONS='-std=c++14' '-g3' '-O3' '-fopenmp' '-v' '-o' 'CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.' +Linking CXX executable cmTC_f6f2d +/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_f6f2d.dir/link.txt --verbose=1 +/usr/bin/c++ -std=c++14 -fopenmp -g3 -O3 -fopenmp -v CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o -o cmTC_f6f2d -v +Using built-in specs. +COLLECT_GCC=/usr/bin/c++ +COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper +OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa +OFFLOAD_TARGET_DEFAULT=1 +Target: x86_64-linux-gnu +Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2 +Thread model: posix +Supported LTO compression algorithms: zlib zstd +gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) +COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/ +LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/ +Reading specs from /usr/lib/gcc/x86_64-linux-gnu/11/libgomp.spec +COLLECT_GCC_OPTIONS='-std=c++14' '-g3' '-O3' '-fopenmp' '-v' '-o' 'cmTC_f6f2d' '-v' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'cmTC_f6f2d.' + /usr/lib/gcc/x86_64-linux-gnu/11/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/11/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper -plugin-opt=-fresolution=/tmp/ccqoivh3.res -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lpthread -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_f6f2d /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/11/crtbeginS.o /usr/lib/gcc/x86_64-linux-gnu/11/crtoffloadbegin.o -L/usr/lib/gcc/x86_64-linux-gnu/11 -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/11/../../.. CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o -lstdc++ -lm -lgomp -lgcc_s -lgcc -lpthread -lc -lgcc_s -lgcc /usr/lib/gcc/x86_64-linux-gnu/11/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crtn.o /usr/lib/gcc/x86_64-linux-gnu/11/crtoffloadend.o +COLLECT_GCC_OPTIONS='-std=c++14' '-g3' '-O3' '-fopenmp' '-v' '-o' 'cmTC_f6f2d' '-v' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'cmTC_f6f2d.' +gmake[1]: Leaving directory '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp' + + + +Parsed CXX OpenMP implicit link information from above output: + link line regex: [^( *|.*[/\])(ld|CMAKE_LINK_STARTFILE-NOTFOUND|([^/\]+-)?ld|collect2)[^/\]*( |$)] + ignore line: [Change Dir: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp] + ignore line: [] + ignore line: [Run Build Command(s):/usr/bin/gmake -f Makefile cmTC_f6f2d/fast && /usr/bin/gmake -f CMakeFiles/cmTC_f6f2d.dir/build.make CMakeFiles/cmTC_f6f2d.dir/build] + ignore line: [gmake[1]: Entering directory '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp'] + ignore line: [Building CXX object CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o] + ignore line: [/usr/bin/c++ -std=c++14 -fopenmp -g3 -O3 -fopenmp -v -o CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o -c /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPTryFlag.cpp] + ignore line: [Using built-in specs.] + ignore line: [COLLECT_GCC=/usr/bin/c++] + ignore line: [OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa] + ignore line: [OFFLOAD_TARGET_DEFAULT=1] + ignore line: [Target: x86_64-linux-gnu] + ignore line: [Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c ada c++ go brig d fortran objc obj-c++ m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32 m64 mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2] + ignore line: [Thread model: posix] + ignore line: [Supported LTO compression algorithms: zlib zstd] + ignore line: [gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) ] + ignore line: [COLLECT_GCC_OPTIONS='-std=c++14' '-g3' '-O3' '-fopenmp' '-v' '-o' 'CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'CMakeFiles/cmTC_f6f2d.dir/'] + ignore line: [ /usr/lib/gcc/x86_64-linux-gnu/11/cc1plus -quiet -v -imultiarch x86_64-linux-gnu -dD -D_GNU_SOURCE -D_REENTRANT /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPTryFlag.cpp -quiet -dumpdir CMakeFiles/cmTC_f6f2d.dir/ -dumpbase OpenMPTryFlag.cpp.cpp -dumpbase-ext .cpp -mtune=generic -march=x86-64 -g3 -O3 -std=c++14 -version -fopenmp -fasynchronous-unwind-tables -fstack-protector-strong -Wformat -Wformat-security -fstack-clash-protection -fcf-protection -o /tmp/cccxfRSr.s] + ignore line: [GNU C++14 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu)] + ignore line: [ compiled by GNU C version 11.4.0 GMP version 6.2.1 MPFR version 4.1.0 MPC version 1.2.1 isl version isl-0.24-GMP] + ignore line: [] + ignore line: [GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072] + ignore line: [ignoring duplicate directory "/usr/include/x86_64-linux-gnu/c++/11"] + ignore line: [ignoring nonexistent directory "/usr/local/include/x86_64-linux-gnu"] + ignore line: [ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/include-fixed"] + ignore line: [ignoring nonexistent directory "/usr/lib/gcc/x86_64-linux-gnu/11/../../../../x86_64-linux-gnu/include"] + ignore line: [#include "..." search starts here:] + ignore line: [#include <...> search starts here:] + ignore line: [ /usr/include/c++/11] + ignore line: [ /usr/include/x86_64-linux-gnu/c++/11] + ignore line: [ /usr/include/c++/11/backward] + ignore line: [ /usr/lib/gcc/x86_64-linux-gnu/11/include] + ignore line: [ /usr/local/include] + ignore line: [ /usr/include/x86_64-linux-gnu] + ignore line: [ /usr/include] + ignore line: [End of search list.] + ignore line: [GNU C++14 (Ubuntu 11.4.0-1ubuntu1~22.04.3) version 11.4.0 (x86_64-linux-gnu)] + ignore line: [ compiled by GNU C version 11.4.0 GMP version 6.2.1 MPFR version 4.1.0 MPC version 1.2.1 isl version isl-0.24-GMP] + ignore line: [] + ignore line: [GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072] + ignore line: [Compiler executable checksum: ac7fa628ee459f217e6fdb88b3db0bde] + ignore line: [COLLECT_GCC_OPTIONS='-std=c++14' '-g3' '-O3' '-fopenmp' '-v' '-o' 'CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'CMakeFiles/cmTC_f6f2d.dir/'] + ignore line: [ as -v --gdwarf-5 --64 -o CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o /tmp/cccxfRSr.s] + ignore line: [GNU assembler version 2.38 (x86_64-linux-gnu) using BFD version (GNU Binutils for Ubuntu) 2.38] + ignore line: [COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/] + ignore line: [LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/] + ignore line: [COLLECT_GCC_OPTIONS='-std=c++14' '-g3' '-O3' '-fopenmp' '-v' '-o' 'CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o' '-c' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.'] + ignore line: [Linking CXX executable cmTC_f6f2d] + ignore line: [/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_f6f2d.dir/link.txt --verbose=1] + ignore line: [/usr/bin/c++ -std=c++14 -fopenmp -g3 -O3 -fopenmp -v CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o -o cmTC_f6f2d -v ] + ignore line: [Using built-in specs.] + ignore line: [COLLECT_GCC=/usr/bin/c++] + ignore line: [COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper] + ignore line: [OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa] + ignore line: [OFFLOAD_TARGET_DEFAULT=1] + ignore line: [Target: x86_64-linux-gnu] + ignore line: [Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.4.0-1ubuntu1~22.04.3' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c ada c++ go brig d fortran objc obj-c++ m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32 m64 mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-nvptx/usr amdgcn-amdhsa=/build/gcc-11-0odw26/gcc-11-11.4.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2] + ignore line: [Thread model: posix] + ignore line: [Supported LTO compression algorithms: zlib zstd] + ignore line: [gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04.3) ] + ignore line: [COMPILER_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/] + ignore line: [LIBRARY_PATH=/usr/lib/gcc/x86_64-linux-gnu/11/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib/:/lib/x86_64-linux-gnu/:/lib/../lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/../lib/:/usr/lib/gcc/x86_64-linux-gnu/11/../../../:/lib/:/usr/lib/] + ignore line: [Reading specs from /usr/lib/gcc/x86_64-linux-gnu/11/libgomp.spec] + ignore line: [COLLECT_GCC_OPTIONS='-std=c++14' '-g3' '-O3' '-fopenmp' '-v' '-o' 'cmTC_f6f2d' '-v' '-shared-libgcc' '-mtune=generic' '-march=x86-64' '-pthread' '-dumpdir' 'cmTC_f6f2d.'] + link line: [ /usr/lib/gcc/x86_64-linux-gnu/11/collect2 -plugin /usr/lib/gcc/x86_64-linux-gnu/11/liblto_plugin.so -plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper -plugin-opt=-fresolution=/tmp/ccqoivh3.res -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc -plugin-opt=-pass-through=-lpthread -plugin-opt=-pass-through=-lc -plugin-opt=-pass-through=-lgcc_s -plugin-opt=-pass-through=-lgcc --build-id --eh-frame-hdr -m elf_x86_64 --hash-style=gnu --as-needed -dynamic-linker /lib64/ld-linux-x86-64.so.2 -pie -z now -z relro -o cmTC_f6f2d /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/11/crtbeginS.o /usr/lib/gcc/x86_64-linux-gnu/11/crtoffloadbegin.o -L/usr/lib/gcc/x86_64-linux-gnu/11 -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu -L/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib -L/lib/x86_64-linux-gnu -L/lib/../lib -L/usr/lib/x86_64-linux-gnu -L/usr/lib/../lib -L/usr/lib/gcc/x86_64-linux-gnu/11/../../.. CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o -lstdc++ -lm -lgomp -lgcc_s -lgcc -lpthread -lc -lgcc_s -lgcc /usr/lib/gcc/x86_64-linux-gnu/11/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/crtn.o /usr/lib/gcc/x86_64-linux-gnu/11/crtoffloadend.o] + arg [/usr/lib/gcc/x86_64-linux-gnu/11/collect2] ==> ignore + arg [-plugin] ==> ignore + arg [/usr/lib/gcc/x86_64-linux-gnu/11/liblto_plugin.so] ==> ignore + arg [-plugin-opt=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper] ==> ignore + arg [-plugin-opt=-fresolution=/tmp/ccqoivh3.res] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc_s] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc] ==> ignore + arg [-plugin-opt=-pass-through=-lpthread] ==> ignore + arg [-plugin-opt=-pass-through=-lc] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc_s] ==> ignore + arg [-plugin-opt=-pass-through=-lgcc] ==> ignore + arg [--build-id] ==> ignore + arg [--eh-frame-hdr] ==> ignore + arg [-m] ==> ignore + arg [elf_x86_64] ==> ignore + arg [--hash-style=gnu] ==> ignore + arg [--as-needed] ==> ignore + arg [-dynamic-linker] ==> ignore + arg [/lib64/ld-linux-x86-64.so.2] ==> ignore + arg [-pie] ==> ignore + arg [-znow] ==> ignore + arg [-zrelro] ==> ignore + arg [-o] ==> ignore + arg [cmTC_f6f2d] ==> ignore + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11] + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu] + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib] + arg [-L/lib/x86_64-linux-gnu] ==> dir [/lib/x86_64-linux-gnu] + arg [-L/lib/../lib] ==> dir [/lib/../lib] + arg [-L/usr/lib/x86_64-linux-gnu] ==> dir [/usr/lib/x86_64-linux-gnu] + arg [-L/usr/lib/../lib] ==> dir [/usr/lib/../lib] + arg [-L/usr/lib/gcc/x86_64-linux-gnu/11/../../..] ==> dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../..] + arg [CMakeFiles/cmTC_f6f2d.dir/OpenMPTryFlag.cpp.o] ==> ignore + arg [-lstdc++] ==> lib [stdc++] + arg [-lm] ==> lib [m] + arg [-lgomp] ==> lib [gomp] + arg [-lgcc_s] ==> lib [gcc_s] + arg [-lgcc] ==> lib [gcc] + arg [-lpthread] ==> lib [pthread] + arg [-lc] ==> lib [c] + arg [-lgcc_s] ==> lib [gcc_s] + arg [-lgcc] ==> lib [gcc] + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11] ==> [/usr/lib/gcc/x86_64-linux-gnu/11] + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu] ==> [/usr/lib/x86_64-linux-gnu] + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../../../lib] ==> [/usr/lib] + collapse library dir [/lib/x86_64-linux-gnu] ==> [/lib/x86_64-linux-gnu] + collapse library dir [/lib/../lib] ==> [/lib] + collapse library dir [/usr/lib/x86_64-linux-gnu] ==> [/usr/lib/x86_64-linux-gnu] + collapse library dir [/usr/lib/../lib] ==> [/usr/lib] + collapse library dir [/usr/lib/gcc/x86_64-linux-gnu/11/../../..] ==> [/usr/lib] + implicit libs: [stdc++;m;gomp;gcc_s;gcc;pthread;c;gcc_s;gcc] + implicit objs: [] + implicit dirs: [/usr/lib/gcc/x86_64-linux-gnu/11;/usr/lib/x86_64-linux-gnu;/usr/lib;/lib/x86_64-linux-gnu;/lib] + implicit fwks: [] + + +Performing C++ SOURCE FILE Test HAS_FLTO_AUTO succeeded with the following output: +Change Dir: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp + +Run Build Command(s):/usr/bin/gmake -f Makefile cmTC_a38bd/fast && /usr/bin/gmake -f CMakeFiles/cmTC_a38bd.dir/build.make CMakeFiles/cmTC_a38bd.dir/build +gmake[1]: Entering directory '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp' +Building CXX object CMakeFiles/cmTC_a38bd.dir/src.cxx.o +/usr/bin/c++ -DHAS_FLTO_AUTO -std=c++14 -fopenmp -g3 -O3 -flto=auto -fno-fat-lto-objects -o CMakeFiles/cmTC_a38bd.dir/src.cxx.o -c /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp/src.cxx +Linking CXX executable cmTC_a38bd +/usr/bin/cmake -E cmake_link_script CMakeFiles/cmTC_a38bd.dir/link.txt --verbose=1 +/usr/bin/c++ -std=c++14 -fopenmp -g3 -O3 CMakeFiles/cmTC_a38bd.dir/src.cxx.o -o cmTC_a38bd -flto=auto +gmake[1]: Leaving directory '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/CMakeTmp' + + +Source file was: +int main() { return 0; } diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPCheckVersion.c b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPCheckVersion.c new file mode 100644 index 0000000000000000000000000000000000000000..3321e6b19b3c52f8f3d0f5618c5b3602205d7c8f --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPCheckVersion.c @@ -0,0 +1,17 @@ + +#include +#include +const char ompver_str[] = { 'I', 'N', 'F', 'O', ':', 'O', 'p', 'e', 'n', 'M', + 'P', '-', 'd', 'a', 't', 'e', '[', + ('0' + ((_OPENMP/100000)%10)), + ('0' + ((_OPENMP/10000)%10)), + ('0' + ((_OPENMP/1000)%10)), + ('0' + ((_OPENMP/100)%10)), + ('0' + ((_OPENMP/10)%10)), + ('0' + ((_OPENMP/1)%10)), + ']', '\0' }; +int main(void) +{ + puts(ompver_str); + return 0; +} diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPCheckVersion.cpp b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPCheckVersion.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3321e6b19b3c52f8f3d0f5618c5b3602205d7c8f --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPCheckVersion.cpp @@ -0,0 +1,17 @@ + +#include +#include +const char ompver_str[] = { 'I', 'N', 'F', 'O', ':', 'O', 'p', 'e', 'n', 'M', + 'P', '-', 'd', 'a', 't', 'e', '[', + ('0' + ((_OPENMP/100000)%10)), + ('0' + ((_OPENMP/10000)%10)), + ('0' + ((_OPENMP/1000)%10)), + ('0' + ((_OPENMP/100)%10)), + ('0' + ((_OPENMP/10)%10)), + ('0' + ((_OPENMP/1)%10)), + ']', '\0' }; +int main(void) +{ + puts(ompver_str); + return 0; +} diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPTryFlag.c b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPTryFlag.c new file mode 100644 index 0000000000000000000000000000000000000000..4aea0b0914cbbad2c0156aa2215491e70bc84b13 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPTryFlag.c @@ -0,0 +1,12 @@ + +#include +int main(void) { +#ifdef _OPENMP + omp_get_max_threads(); + return 0; +#elif defined(__HIP_DEVICE_COMPILE__) + return 0; +#else + breaks_on_purpose +#endif +} diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPTryFlag.cpp b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPTryFlag.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4aea0b0914cbbad2c0156aa2215491e70bc84b13 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/OpenMPTryFlag.cpp @@ -0,0 +1,12 @@ + +#include +int main(void) { +#ifdef _OPENMP + omp_get_max_threads(); + return 0; +#elif defined(__HIP_DEVICE_COMPILE__) + return 0; +#else + breaks_on_purpose +#endif +} diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/ompver_C.bin b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/ompver_C.bin new file mode 100644 index 0000000000000000000000000000000000000000..58e7071300fd776d1479adf34e5f449830bdb535 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/ompver_C.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bbb78a224e63324df3dcd41fe2bc2a59a4a0e958a7907ce8eab52c08c2f03d43 +size 16240 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/ompver_CXX.bin b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/ompver_CXX.bin new file mode 100644 index 0000000000000000000000000000000000000000..0f1e1c48c05c6f53c91a6aa62ea4171377a04e04 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/FindOpenMP/ompver_CXX.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c3d07bb85346239ac6a93490f540f961f6aa148dfaddc5c671d6714c098199a +size 48888 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/Makefile.cmake b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/Makefile.cmake new file mode 100644 index 0000000000000000000000000000000000000000..cd5d61a54c7a47884cf76671f3427d913f8337a1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/Makefile.cmake @@ -0,0 +1,156 @@ +# CMAKE generated file: DO NOT EDIT! +# Generated by "Unix Makefiles" Generator, CMake Version 3.22 + +# The generator used is: +set(CMAKE_DEPENDS_GENERATOR "Unix Makefiles") + +# The top level Makefile was generated from the following files: +set(CMAKE_MAKEFILE_DEPENDS + "CMakeCache.txt" + "../CMakeLists.txt" + "CMakeFiles/3.22.1/CMakeCCompiler.cmake" + "CMakeFiles/3.22.1/CMakeCXXCompiler.cmake" + "CMakeFiles/3.22.1/CMakeSystem.cmake" + "CMakeFiles/FindOpenMP/OpenMPCheckVersion.c" + "CMakeFiles/FindOpenMP/OpenMPCheckVersion.cpp" + "CMakeFiles/FindOpenMP/OpenMPTryFlag.c" + "CMakeFiles/FindOpenMP/OpenMPTryFlag.cpp" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/Boost-1.82.0/BoostConfig.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/Boost-1.82.0/BoostConfigVersion.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/BoostDetectToolset-1.82.0.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/boost_headers-1.82.0/boost_headers-config-version.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/boost_headers-1.82.0/boost_headers-config.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/boost_program_options-1.82.0/boost_program_options-config-version.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/boost_program_options-1.82.0/boost_program_options-config.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/boost_program_options-1.82.0/libboost_program_options-variant-shared.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/boost_system-1.82.0/boost_system-config-version.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/boost_system-1.82.0/boost_system-config.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/cmake/boost_system-1.82.0/libboost_system-variant-shared.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/share/cmake/pybind11/FindPythonLibsNew.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/share/cmake/pybind11/pybind11Common.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/share/cmake/pybind11/pybind11Config.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/share/cmake/pybind11/pybind11ConfigVersion.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/share/cmake/pybind11/pybind11Targets.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/share/cmake/pybind11/pybind11Tools.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/share/eigen3/cmake/Eigen3Config.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/share/eigen3/cmake/Eigen3ConfigVersion.cmake" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/share/eigen3/cmake/Eigen3Targets.cmake" + "/usr/share/cmake-3.22/Modules/CMakeCCompiler.cmake.in" + "/usr/share/cmake-3.22/Modules/CMakeCCompilerABI.c" + "/usr/share/cmake-3.22/Modules/CMakeCInformation.cmake" + "/usr/share/cmake-3.22/Modules/CMakeCXXCompiler.cmake.in" + "/usr/share/cmake-3.22/Modules/CMakeCXXCompilerABI.cpp" + "/usr/share/cmake-3.22/Modules/CMakeCXXInformation.cmake" + "/usr/share/cmake-3.22/Modules/CMakeCheckCompilerFlagCommonPatterns.cmake" + "/usr/share/cmake-3.22/Modules/CMakeCommonLanguageInclude.cmake" + "/usr/share/cmake-3.22/Modules/CMakeCompilerIdDetection.cmake" + "/usr/share/cmake-3.22/Modules/CMakeDetermineCCompiler.cmake" + "/usr/share/cmake-3.22/Modules/CMakeDetermineCXXCompiler.cmake" + "/usr/share/cmake-3.22/Modules/CMakeDetermineCompileFeatures.cmake" + "/usr/share/cmake-3.22/Modules/CMakeDetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/CMakeDetermineCompilerABI.cmake" + "/usr/share/cmake-3.22/Modules/CMakeDetermineCompilerId.cmake" + "/usr/share/cmake-3.22/Modules/CMakeDetermineSystem.cmake" + "/usr/share/cmake-3.22/Modules/CMakeFindBinUtils.cmake" + "/usr/share/cmake-3.22/Modules/CMakeGenericSystem.cmake" + "/usr/share/cmake-3.22/Modules/CMakeInitializeConfigs.cmake" + "/usr/share/cmake-3.22/Modules/CMakeLanguageInformation.cmake" + "/usr/share/cmake-3.22/Modules/CMakeParseImplicitIncludeInfo.cmake" + "/usr/share/cmake-3.22/Modules/CMakeParseImplicitLinkInfo.cmake" + "/usr/share/cmake-3.22/Modules/CMakeParseLibraryArchitecture.cmake" + "/usr/share/cmake-3.22/Modules/CMakeSystem.cmake.in" + "/usr/share/cmake-3.22/Modules/CMakeSystemSpecificInformation.cmake" + "/usr/share/cmake-3.22/Modules/CMakeSystemSpecificInitialize.cmake" + "/usr/share/cmake-3.22/Modules/CMakeTestCCompiler.cmake" + "/usr/share/cmake-3.22/Modules/CMakeTestCXXCompiler.cmake" + "/usr/share/cmake-3.22/Modules/CMakeTestCompilerCommon.cmake" + "/usr/share/cmake-3.22/Modules/CMakeUnixFindMake.cmake" + "/usr/share/cmake-3.22/Modules/CheckCXXCompilerFlag.cmake" + "/usr/share/cmake-3.22/Modules/CheckCXXSourceCompiles.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/ADSP-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/ARMCC-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/ARMClang-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/AppleClang-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/Borland-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/Bruce-C-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/CMakeCommonCompilerMacros.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/Clang-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/Clang-DetermineCompilerInternal.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/Comeau-CXX-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/Compaq-C-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/Compaq-CXX-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/Cray-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/Embarcadero-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/Fujitsu-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/FujitsuClang-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/GHS-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/GNU-C-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/GNU-C.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/GNU-CXX-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/GNU-CXX.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/GNU-FindBinUtils.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/GNU.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/HP-C-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/HP-CXX-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/IAR-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/IBMCPP-C-DetermineVersionInternal.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/IBMCPP-CXX-DetermineVersionInternal.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/Intel-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/IntelLLVM-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/MSVC-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/NVHPC-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/NVIDIA-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/OpenWatcom-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/PGI-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/PathScale-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/SCO-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/SDCC-C-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/SunPro-C-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/SunPro-CXX-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/TI-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/TinyCC-C-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/VisualAge-C-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/VisualAge-CXX-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/Watcom-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/XL-C-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/XL-CXX-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/XLClang-C-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/XLClang-CXX-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/zOS-C-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/Compiler/zOS-CXX-DetermineCompiler.cmake" + "/usr/share/cmake-3.22/Modules/FindBoost.cmake" + "/usr/share/cmake-3.22/Modules/FindOpenMP.cmake" + "/usr/share/cmake-3.22/Modules/FindPackageHandleStandardArgs.cmake" + "/usr/share/cmake-3.22/Modules/FindPackageMessage.cmake" + "/usr/share/cmake-3.22/Modules/FindPythonInterp.cmake" + "/usr/share/cmake-3.22/Modules/Internal/CheckCompilerFlag.cmake" + "/usr/share/cmake-3.22/Modules/Internal/CheckSourceCompiles.cmake" + "/usr/share/cmake-3.22/Modules/Internal/FeatureTesting.cmake" + "/usr/share/cmake-3.22/Modules/Platform/Linux-Determine-CXX.cmake" + "/usr/share/cmake-3.22/Modules/Platform/Linux-GNU-C.cmake" + "/usr/share/cmake-3.22/Modules/Platform/Linux-GNU-CXX.cmake" + "/usr/share/cmake-3.22/Modules/Platform/Linux-GNU.cmake" + "/usr/share/cmake-3.22/Modules/Platform/Linux.cmake" + "/usr/share/cmake-3.22/Modules/Platform/UnixPaths.cmake" + ) + +# The corresponding makefile is: +set(CMAKE_MAKEFILE_OUTPUTS + "Makefile" + "CMakeFiles/cmake.check_cache" + ) + +# Byproducts of CMake generate step: +set(CMAKE_MAKEFILE_PRODUCTS + "CMakeFiles/3.22.1/CMakeSystem.cmake" + "CMakeFiles/3.22.1/CMakeCCompiler.cmake" + "CMakeFiles/3.22.1/CMakeCXXCompiler.cmake" + "CMakeFiles/3.22.1/CMakeCCompiler.cmake" + "CMakeFiles/3.22.1/CMakeCXXCompiler.cmake" + "CMakeFiles/CMakeDirectoryInformation.cmake" + ) + +# Dependency information for all targets: +set(CMAKE_DEPEND_INFO_FILES + "CMakeFiles/mycpp.dir/DependInfo.cmake" + ) diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/Makefile2 b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/Makefile2 new file mode 100644 index 0000000000000000000000000000000000000000..2b9e1d679dac22dbdef07f4a8c8c35c314235477 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/Makefile2 @@ -0,0 +1,112 @@ +# CMAKE generated file: DO NOT EDIT! +# Generated by "Unix Makefiles" Generator, CMake Version 3.22 + +# Default target executed when no arguments are given to make. +default_target: all +.PHONY : default_target + +#============================================================================= +# Special targets provided by cmake. + +# Disable implicit rules so canonical targets will work. +.SUFFIXES: + +# Disable VCS-based implicit rules. +% : %,v + +# Disable VCS-based implicit rules. +% : RCS/% + +# Disable VCS-based implicit rules. +% : RCS/%,v + +# Disable VCS-based implicit rules. +% : SCCS/s.% + +# Disable VCS-based implicit rules. +% : s.% + +.SUFFIXES: .hpux_make_needs_suffix_list + +# Command-line flag to silence nested $(MAKE). +$(VERBOSE)MAKESILENT = -s + +#Suppress display of executed commands. +$(VERBOSE).SILENT: + +# A target that is always out of date. +cmake_force: +.PHONY : cmake_force + +#============================================================================= +# Set environment variables for the build. + +# The shell in which to execute make rules. +SHELL = /bin/sh + +# The CMake executable. +CMAKE_COMMAND = /usr/bin/cmake + +# The command to remove a file. +RM = /usr/bin/cmake -E rm -f + +# Escaping for special characters. +EQUALS = = + +# The top-level source directory on which CMake was run. +CMAKE_SOURCE_DIR = /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp + +# The top-level build directory on which CMake was run. +CMAKE_BINARY_DIR = /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build + +#============================================================================= +# Directory level rules for the build root directory + +# The main recursive "all" target. +all: CMakeFiles/mycpp.dir/all +.PHONY : all + +# The main recursive "preinstall" target. +preinstall: +.PHONY : preinstall + +# The main recursive "clean" target. +clean: CMakeFiles/mycpp.dir/clean +.PHONY : clean + +#============================================================================= +# Target rules for target CMakeFiles/mycpp.dir + +# All Build rule for target. +CMakeFiles/mycpp.dir/all: + $(MAKE) $(MAKESILENT) -f CMakeFiles/mycpp.dir/build.make CMakeFiles/mycpp.dir/depend + $(MAKE) $(MAKESILENT) -f CMakeFiles/mycpp.dir/build.make CMakeFiles/mycpp.dir/build + @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --progress-dir=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles --progress-num=1,2,3 "Built target mycpp" +.PHONY : CMakeFiles/mycpp.dir/all + +# Build rule for subdir invocation for target. +CMakeFiles/mycpp.dir/rule: cmake_check_build_system + $(CMAKE_COMMAND) -E cmake_progress_start /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles 3 + $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 CMakeFiles/mycpp.dir/all + $(CMAKE_COMMAND) -E cmake_progress_start /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles 0 +.PHONY : CMakeFiles/mycpp.dir/rule + +# Convenience name for target. +mycpp: CMakeFiles/mycpp.dir/rule +.PHONY : mycpp + +# clean rule for target. +CMakeFiles/mycpp.dir/clean: + $(MAKE) $(MAKESILENT) -f CMakeFiles/mycpp.dir/build.make CMakeFiles/mycpp.dir/clean +.PHONY : CMakeFiles/mycpp.dir/clean + +#============================================================================= +# Special targets to cleanup operation of make. + +# Special rule to run CMake to check the build system integrity. +# No rule that depends on this can have commands that come from listfiles +# because they might be regenerated. +cmake_check_build_system: + $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 +.PHONY : cmake_check_build_system + diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/TargetDirectories.txt b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/TargetDirectories.txt new file mode 100644 index 0000000000000000000000000000000000000000..7adc6bce42d41bfcf915b9fef16691e579169304 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/TargetDirectories.txt @@ -0,0 +1,3 @@ +/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir +/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/edit_cache.dir +/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/rebuild_cache.dir diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/cmake.check_cache b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/cmake.check_cache new file mode 100644 index 0000000000000000000000000000000000000000..3dccd731726d7faa8b29d8d7dba3b981a53ca497 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/cmake.check_cache @@ -0,0 +1 @@ +# This file is generated by cmake for dependency checking of the CMakeCache.txt file diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/DependInfo.cmake b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/DependInfo.cmake new file mode 100644 index 0000000000000000000000000000000000000000..ace6fa2dc6f09ea4342da0c0de5d193cfddd806d --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/DependInfo.cmake @@ -0,0 +1,20 @@ + +# Consider dependencies only in project. +set(CMAKE_DEPENDS_IN_PROJECT_ONLY OFF) + +# The set of languages for which implicit dependencies are needed: +set(CMAKE_DEPENDS_LANGUAGES + ) + +# The set of dependency files which are needed: +set(CMAKE_DEPENDS_DEPENDENCY_FILES + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/Utils.cpp" "CMakeFiles/mycpp.dir/src/Utils.cpp.o" "gcc" "CMakeFiles/mycpp.dir/src/Utils.cpp.o.d" + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/app/pybind_api.cpp" "CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o" "gcc" "CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o.d" + ) + +# Targets to which this target links. +set(CMAKE_TARGET_LINKED_INFO_FILES + ) + +# Fortran module output directory. +set(CMAKE_Fortran_TARGET_MODULE_DIR "") diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/build.make b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/build.make new file mode 100644 index 0000000000000000000000000000000000000000..5e4c53f1340bb3e274e04b657b993792c13507ce --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/build.make @@ -0,0 +1,129 @@ +# CMAKE generated file: DO NOT EDIT! +# Generated by "Unix Makefiles" Generator, CMake Version 3.22 + +# Delete rule output on recipe failure. +.DELETE_ON_ERROR: + +#============================================================================= +# Special targets provided by cmake. + +# Disable implicit rules so canonical targets will work. +.SUFFIXES: + +# Disable VCS-based implicit rules. +% : %,v + +# Disable VCS-based implicit rules. +% : RCS/% + +# Disable VCS-based implicit rules. +% : RCS/%,v + +# Disable VCS-based implicit rules. +% : SCCS/s.% + +# Disable VCS-based implicit rules. +% : s.% + +.SUFFIXES: .hpux_make_needs_suffix_list + +# Command-line flag to silence nested $(MAKE). +$(VERBOSE)MAKESILENT = -s + +#Suppress display of executed commands. +$(VERBOSE).SILENT: + +# A target that is always out of date. +cmake_force: +.PHONY : cmake_force + +#============================================================================= +# Set environment variables for the build. + +# The shell in which to execute make rules. +SHELL = /bin/sh + +# The CMake executable. +CMAKE_COMMAND = /usr/bin/cmake + +# The command to remove a file. +RM = /usr/bin/cmake -E rm -f + +# Escaping for special characters. +EQUALS = = + +# The top-level source directory on which CMake was run. +CMAKE_SOURCE_DIR = /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp + +# The top-level build directory on which CMake was run. +CMAKE_BINARY_DIR = /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build + +# Include any dependencies generated for this target. +include CMakeFiles/mycpp.dir/depend.make +# Include any dependencies generated by the compiler for this target. +include CMakeFiles/mycpp.dir/compiler_depend.make + +# Include the progress variables for this target. +include CMakeFiles/mycpp.dir/progress.make + +# Include the compile flags for this target's objects. +include CMakeFiles/mycpp.dir/flags.make + +CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o: CMakeFiles/mycpp.dir/flags.make +CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o: ../src/app/pybind_api.cpp +CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o: CMakeFiles/mycpp.dir/compiler_depend.ts + @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_1) "Building CXX object CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o" + /usr/bin/c++ $(CXX_DEFINES) $(CXX_INCLUDES) $(CXX_FLAGS) -MD -MT CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o -MF CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o.d -o CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o -c /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/app/pybind_api.cpp + +CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.i: cmake_force + @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Preprocessing CXX source to CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.i" + /usr/bin/c++ $(CXX_DEFINES) $(CXX_INCLUDES) $(CXX_FLAGS) -E /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/app/pybind_api.cpp > CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.i + +CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.s: cmake_force + @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Compiling CXX source to assembly CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.s" + /usr/bin/c++ $(CXX_DEFINES) $(CXX_INCLUDES) $(CXX_FLAGS) -S /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/app/pybind_api.cpp -o CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.s + +CMakeFiles/mycpp.dir/src/Utils.cpp.o: CMakeFiles/mycpp.dir/flags.make +CMakeFiles/mycpp.dir/src/Utils.cpp.o: ../src/Utils.cpp +CMakeFiles/mycpp.dir/src/Utils.cpp.o: CMakeFiles/mycpp.dir/compiler_depend.ts + @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_2) "Building CXX object CMakeFiles/mycpp.dir/src/Utils.cpp.o" + /usr/bin/c++ $(CXX_DEFINES) $(CXX_INCLUDES) $(CXX_FLAGS) -MD -MT CMakeFiles/mycpp.dir/src/Utils.cpp.o -MF CMakeFiles/mycpp.dir/src/Utils.cpp.o.d -o CMakeFiles/mycpp.dir/src/Utils.cpp.o -c /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/Utils.cpp + +CMakeFiles/mycpp.dir/src/Utils.cpp.i: cmake_force + @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Preprocessing CXX source to CMakeFiles/mycpp.dir/src/Utils.cpp.i" + /usr/bin/c++ $(CXX_DEFINES) $(CXX_INCLUDES) $(CXX_FLAGS) -E /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/Utils.cpp > CMakeFiles/mycpp.dir/src/Utils.cpp.i + +CMakeFiles/mycpp.dir/src/Utils.cpp.s: cmake_force + @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Compiling CXX source to assembly CMakeFiles/mycpp.dir/src/Utils.cpp.s" + /usr/bin/c++ $(CXX_DEFINES) $(CXX_INCLUDES) $(CXX_FLAGS) -S /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/Utils.cpp -o CMakeFiles/mycpp.dir/src/Utils.cpp.s + +# Object files for target mycpp +mycpp_OBJECTS = \ +"CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o" \ +"CMakeFiles/mycpp.dir/src/Utils.cpp.o" + +# External object files for target mycpp +mycpp_EXTERNAL_OBJECTS = + +mycpp.cpython-311-x86_64-linux-gnu.so: CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o +mycpp.cpython-311-x86_64-linux-gnu.so: CMakeFiles/mycpp.dir/src/Utils.cpp.o +mycpp.cpython-311-x86_64-linux-gnu.so: CMakeFiles/mycpp.dir/build.make +mycpp.cpython-311-x86_64-linux-gnu.so: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/libboost_system.so.1.82.0 +mycpp.cpython-311-x86_64-linux-gnu.so: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/libboost_program_options.so.1.82.0 +mycpp.cpython-311-x86_64-linux-gnu.so: CMakeFiles/mycpp.dir/link.txt + @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --bold --progress-dir=/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_3) "Linking CXX shared module mycpp.cpython-311-x86_64-linux-gnu.so" + $(CMAKE_COMMAND) -E cmake_link_script CMakeFiles/mycpp.dir/link.txt --verbose=$(VERBOSE) + /usr/bin/strip /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/mycpp.cpython-311-x86_64-linux-gnu.so + +# Rule to build all files generated by this target. +CMakeFiles/mycpp.dir/build: mycpp.cpython-311-x86_64-linux-gnu.so +.PHONY : CMakeFiles/mycpp.dir/build + +CMakeFiles/mycpp.dir/clean: + $(CMAKE_COMMAND) -P CMakeFiles/mycpp.dir/cmake_clean.cmake +.PHONY : CMakeFiles/mycpp.dir/clean + +CMakeFiles/mycpp.dir/depend: + cd /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build && $(CMAKE_COMMAND) -E cmake_depends "Unix Makefiles" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/DependInfo.cmake --color=$(COLOR) +.PHONY : CMakeFiles/mycpp.dir/depend + diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/cmake_clean.cmake b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/cmake_clean.cmake new file mode 100644 index 0000000000000000000000000000000000000000..46e8d581cbbf4d0a4e1ace7ad2c1efd230884ae9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/cmake_clean.cmake @@ -0,0 +1,13 @@ +file(REMOVE_RECURSE + "CMakeFiles/mycpp.dir/src/Utils.cpp.o" + "CMakeFiles/mycpp.dir/src/Utils.cpp.o.d" + "CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o" + "CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o.d" + "mycpp.cpython-311-x86_64-linux-gnu.so" + "mycpp.pdb" +) + +# Per-language clean rules from dependency scanning. +foreach(lang CXX) + include(CMakeFiles/mycpp.dir/cmake_clean_${lang}.cmake OPTIONAL) +endforeach() diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/compiler_depend.make b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/compiler_depend.make new file mode 100644 index 0000000000000000000000000000000000000000..1568eaf9e35563f411d276ca31aed385bc419b99 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/compiler_depend.make @@ -0,0 +1,2 @@ +# Empty compiler generated dependencies file for mycpp. +# This may be replaced when dependencies are built. diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/compiler_depend.ts b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/compiler_depend.ts new file mode 100644 index 0000000000000000000000000000000000000000..60fdeea38de8b7fbde146ea4bf0d947d98275444 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/compiler_depend.ts @@ -0,0 +1,2 @@ +# CMAKE generated file: DO NOT EDIT! +# Timestamp file for compiler generated dependencies management for mycpp. diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/depend.make b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/depend.make new file mode 100644 index 0000000000000000000000000000000000000000..0e267ac63f34a5457487b6775b3a3987bbe4efb4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/depend.make @@ -0,0 +1,2 @@ +# Empty dependencies file for mycpp. +# This may be replaced when dependencies are built. diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/flags.make b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/flags.make new file mode 100644 index 0000000000000000000000000000000000000000..2f73a378b86bbe37eae223e16b8c9407661e94ed --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/flags.make @@ -0,0 +1,10 @@ +# CMAKE generated file: DO NOT EDIT! +# Generated by "Unix Makefiles" Generator, CMake Version 3.22 + +# compile CXX with /usr/bin/c++ +CXX_DEFINES = -DBOOST_PROGRAM_OPTIONS_DYN_LINK -DBOOST_PROGRAM_OPTIONS_NO_LIB -DBOOST_SYSTEM_DYN_LINK -DBOOST_SYSTEM_NO_LIB -Dmycpp_EXPORTS + +CXX_INCLUDES = -I/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/include -isystem /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include -isystem /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11 -isystem /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include -isystem /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3 + +CXX_FLAGS = -std=c++14 -fopenmp -g3 -O3 -O3 -DNDEBUG -fPIC -fvisibility=hidden -flto=auto -fno-fat-lto-objects + diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/link.txt b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/link.txt new file mode 100644 index 0000000000000000000000000000000000000000..5a0cdd461a3725e78946d42e7d356ca733ecfeee --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/link.txt @@ -0,0 +1 @@ +/usr/bin/c++ -fPIC -std=c++14 -fopenmp -g3 -O3 -O3 -DNDEBUG -flto=auto -shared -o mycpp.cpython-311-x86_64-linux-gnu.so CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o CMakeFiles/mycpp.dir/src/Utils.cpp.o -Wl,-rpath,/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/libboost_system.so.1.82.0 /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/libboost_program_options.so.1.82.0 -fopenmp diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/progress.make b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/progress.make new file mode 100644 index 0000000000000000000000000000000000000000..6a9dc74f48190611094be92ae37d081d83beb533 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/progress.make @@ -0,0 +1,4 @@ +CMAKE_PROGRESS_1 = 1 +CMAKE_PROGRESS_2 = 2 +CMAKE_PROGRESS_3 = 3 + diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/Utils.cpp.o b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/Utils.cpp.o new file mode 100644 index 0000000000000000000000000000000000000000..4cefc9e22bbdb21ac3f570eb302ce5cd5033a269 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/Utils.cpp.o @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:81272a4e2db504d66962d66513351eae27253db8c2e88d51b9c775c21a1794c6 +size 2344752 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/Utils.cpp.o.d b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/Utils.cpp.o.d new file mode 100644 index 0000000000000000000000000000000000000000..85cda1c2661aa331ee5592d15121b1c2d312f6f7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/Utils.cpp.o.d @@ -0,0 +1,892 @@ +CMakeFiles/mycpp.dir/src/Utils.cpp.o: \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/Utils.cpp \ + /usr/include/stdc-predef.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/include/Utils.h \ + /usr/include/c++/11/iostream \ + /usr/include/x86_64-linux-gnu/c++/11/bits/c++config.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/os_defines.h \ + /usr/include/features.h /usr/include/features-time64.h \ + /usr/include/x86_64-linux-gnu/bits/wordsize.h \ + /usr/include/x86_64-linux-gnu/bits/timesize.h \ + /usr/include/x86_64-linux-gnu/sys/cdefs.h \ + /usr/include/x86_64-linux-gnu/bits/long-double.h \ + /usr/include/x86_64-linux-gnu/gnu/stubs.h \ + /usr/include/x86_64-linux-gnu/gnu/stubs-64.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/cpu_defines.h \ + /usr/include/c++/11/ostream /usr/include/c++/11/ios \ + /usr/include/c++/11/iosfwd /usr/include/c++/11/bits/stringfwd.h \ + /usr/include/c++/11/bits/memoryfwd.h /usr/include/c++/11/bits/postypes.h \ + /usr/include/c++/11/cwchar /usr/include/wchar.h \ + /usr/include/x86_64-linux-gnu/bits/libc-header-start.h \ + /usr/include/x86_64-linux-gnu/bits/floatn.h \ + /usr/include/x86_64-linux-gnu/bits/floatn-common.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/stddef.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/stdarg.h \ + /usr/include/x86_64-linux-gnu/bits/wchar.h \ + /usr/include/x86_64-linux-gnu/bits/types/wint_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/mbstate_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/__mbstate_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/__FILE.h \ + /usr/include/x86_64-linux-gnu/bits/types/FILE.h \ + /usr/include/x86_64-linux-gnu/bits/types/locale_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/__locale_t.h \ + /usr/include/x86_64-linux-gnu/bits/wchar2.h \ + /usr/include/c++/11/exception /usr/include/c++/11/bits/exception.h \ + /usr/include/c++/11/bits/exception_ptr.h \ + /usr/include/c++/11/bits/exception_defines.h \ + /usr/include/c++/11/bits/cxxabi_init_exception.h \ + /usr/include/c++/11/typeinfo /usr/include/c++/11/bits/hash_bytes.h \ + /usr/include/c++/11/new /usr/include/c++/11/bits/move.h \ + /usr/include/c++/11/type_traits \ + /usr/include/c++/11/bits/nested_exception.h \ + /usr/include/c++/11/bits/char_traits.h \ + /usr/include/c++/11/bits/stl_algobase.h \ + /usr/include/c++/11/bits/functexcept.h \ + /usr/include/c++/11/bits/cpp_type_traits.h \ + /usr/include/c++/11/ext/type_traits.h \ + /usr/include/c++/11/ext/numeric_traits.h \ + /usr/include/c++/11/bits/stl_pair.h \ + /usr/include/c++/11/bits/stl_iterator_base_types.h \ + /usr/include/c++/11/bits/stl_iterator_base_funcs.h \ + /usr/include/c++/11/bits/concept_check.h \ + /usr/include/c++/11/debug/assertions.h \ + /usr/include/c++/11/bits/stl_iterator.h \ + /usr/include/c++/11/bits/ptr_traits.h /usr/include/c++/11/debug/debug.h \ + /usr/include/c++/11/bits/predefined_ops.h /usr/include/c++/11/cstdint \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/stdint.h /usr/include/stdint.h \ + /usr/include/x86_64-linux-gnu/bits/types.h \ + /usr/include/x86_64-linux-gnu/bits/typesizes.h \ + /usr/include/x86_64-linux-gnu/bits/time64.h \ + /usr/include/x86_64-linux-gnu/bits/stdint-intn.h \ + /usr/include/x86_64-linux-gnu/bits/stdint-uintn.h \ + /usr/include/c++/11/bits/localefwd.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/c++locale.h \ + /usr/include/c++/11/clocale /usr/include/locale.h \ + /usr/include/x86_64-linux-gnu/bits/locale.h /usr/include/c++/11/cctype \ + /usr/include/ctype.h /usr/include/x86_64-linux-gnu/bits/endian.h \ + /usr/include/x86_64-linux-gnu/bits/endianness.h \ + /usr/include/c++/11/bits/ios_base.h /usr/include/c++/11/ext/atomicity.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/gthr.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/gthr-default.h \ + /usr/include/pthread.h /usr/include/sched.h \ + /usr/include/x86_64-linux-gnu/bits/types/time_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct_timespec.h \ + /usr/include/x86_64-linux-gnu/bits/sched.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct_sched_param.h \ + /usr/include/x86_64-linux-gnu/bits/cpu-set.h /usr/include/time.h \ + /usr/include/x86_64-linux-gnu/bits/time.h \ + /usr/include/x86_64-linux-gnu/bits/timex.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct_timeval.h \ + /usr/include/x86_64-linux-gnu/bits/types/clock_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct_tm.h \ + /usr/include/x86_64-linux-gnu/bits/types/clockid_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/timer_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct_itimerspec.h \ + /usr/include/x86_64-linux-gnu/bits/pthreadtypes.h \ + /usr/include/x86_64-linux-gnu/bits/thread-shared-types.h \ + /usr/include/x86_64-linux-gnu/bits/pthreadtypes-arch.h \ + /usr/include/x86_64-linux-gnu/bits/atomic_wide_counter.h \ + /usr/include/x86_64-linux-gnu/bits/struct_mutex.h \ + /usr/include/x86_64-linux-gnu/bits/struct_rwlock.h \ + /usr/include/x86_64-linux-gnu/bits/setjmp.h \ + /usr/include/x86_64-linux-gnu/bits/types/__sigset_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct___jmp_buf_tag.h \ + /usr/include/x86_64-linux-gnu/bits/pthread_stack_min-dynamic.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/atomic_word.h \ + /usr/include/x86_64-linux-gnu/sys/single_threaded.h \ + /usr/include/c++/11/bits/locale_classes.h /usr/include/c++/11/string \ + /usr/include/c++/11/bits/allocator.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/c++allocator.h \ + /usr/include/c++/11/ext/new_allocator.h \ + /usr/include/c++/11/bits/ostream_insert.h \ + /usr/include/c++/11/bits/cxxabi_forced.h \ + /usr/include/c++/11/bits/stl_function.h \ + /usr/include/c++/11/backward/binders.h \ + /usr/include/c++/11/bits/range_access.h \ + /usr/include/c++/11/initializer_list \ + /usr/include/c++/11/bits/basic_string.h \ + /usr/include/c++/11/ext/alloc_traits.h \ + /usr/include/c++/11/bits/alloc_traits.h \ + /usr/include/c++/11/bits/stl_construct.h \ + /usr/include/c++/11/ext/string_conversions.h /usr/include/c++/11/cstdlib \ + /usr/include/stdlib.h /usr/include/x86_64-linux-gnu/bits/waitflags.h \ + /usr/include/x86_64-linux-gnu/bits/waitstatus.h \ + /usr/include/x86_64-linux-gnu/sys/types.h /usr/include/endian.h \ + /usr/include/x86_64-linux-gnu/bits/byteswap.h \ + /usr/include/x86_64-linux-gnu/bits/uintn-identity.h \ + /usr/include/x86_64-linux-gnu/sys/select.h \ + /usr/include/x86_64-linux-gnu/bits/select.h \ + /usr/include/x86_64-linux-gnu/bits/types/sigset_t.h \ + /usr/include/x86_64-linux-gnu/bits/select2.h /usr/include/alloca.h \ + /usr/include/x86_64-linux-gnu/bits/stdlib-bsearch.h \ + /usr/include/x86_64-linux-gnu/bits/stdlib-float.h \ + /usr/include/x86_64-linux-gnu/bits/stdlib.h \ + /usr/include/c++/11/bits/std_abs.h /usr/include/c++/11/cstdio \ + /usr/include/stdio.h /usr/include/x86_64-linux-gnu/bits/types/__fpos_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/__fpos64_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct_FILE.h \ + /usr/include/x86_64-linux-gnu/bits/types/cookie_io_functions_t.h \ + /usr/include/x86_64-linux-gnu/bits/stdio_lim.h \ + /usr/include/x86_64-linux-gnu/bits/stdio.h \ + /usr/include/x86_64-linux-gnu/bits/stdio2.h /usr/include/c++/11/cerrno \ + /usr/include/errno.h /usr/include/x86_64-linux-gnu/bits/errno.h \ + /usr/include/linux/errno.h /usr/include/x86_64-linux-gnu/asm/errno.h \ + /usr/include/asm-generic/errno.h /usr/include/asm-generic/errno-base.h \ + /usr/include/x86_64-linux-gnu/bits/types/error_t.h \ + /usr/include/c++/11/bits/charconv.h \ + /usr/include/c++/11/bits/functional_hash.h \ + /usr/include/c++/11/bits/basic_string.tcc \ + /usr/include/c++/11/bits/locale_classes.tcc \ + /usr/include/c++/11/system_error \ + /usr/include/x86_64-linux-gnu/c++/11/bits/error_constants.h \ + /usr/include/c++/11/stdexcept /usr/include/c++/11/streambuf \ + /usr/include/c++/11/bits/streambuf.tcc \ + /usr/include/c++/11/bits/basic_ios.h \ + /usr/include/c++/11/bits/locale_facets.h /usr/include/c++/11/cwctype \ + /usr/include/wctype.h /usr/include/x86_64-linux-gnu/bits/wctype-wchar.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/ctype_base.h \ + /usr/include/c++/11/bits/streambuf_iterator.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/ctype_inline.h \ + /usr/include/c++/11/bits/locale_facets.tcc \ + /usr/include/c++/11/bits/basic_ios.tcc \ + /usr/include/c++/11/bits/ostream.tcc /usr/include/c++/11/istream \ + /usr/include/c++/11/bits/istream.tcc /usr/include/c++/11/map \ + /usr/include/c++/11/bits/stl_tree.h \ + /usr/include/c++/11/ext/aligned_buffer.h \ + /usr/include/c++/11/bits/stl_map.h /usr/include/c++/11/tuple \ + /usr/include/c++/11/utility /usr/include/c++/11/bits/stl_relops.h \ + /usr/include/c++/11/array /usr/include/c++/11/bits/uses_allocator.h \ + /usr/include/c++/11/bits/invoke.h \ + /usr/include/c++/11/bits/stl_multimap.h \ + /usr/include/c++/11/bits/erase_if.h /usr/include/c++/11/vector \ + /usr/include/c++/11/bits/stl_uninitialized.h \ + /usr/include/c++/11/bits/stl_vector.h \ + /usr/include/c++/11/bits/stl_bvector.h \ + /usr/include/c++/11/bits/vector.tcc /usr/include/c++/11/cmath \ + /usr/include/math.h /usr/include/x86_64-linux-gnu/bits/math-vector.h \ + /usr/include/x86_64-linux-gnu/bits/libm-simd-decl-stubs.h \ + /usr/include/x86_64-linux-gnu/bits/flt-eval-method.h \ + /usr/include/x86_64-linux-gnu/bits/fp-logb.h \ + /usr/include/x86_64-linux-gnu/bits/fp-fast.h \ + /usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h \ + /usr/include/x86_64-linux-gnu/bits/mathcalls.h \ + /usr/include/x86_64-linux-gnu/bits/mathcalls-narrow.h \ + /usr/include/x86_64-linux-gnu/bits/iscanonical.h \ + /usr/include/c++/11/queue /usr/include/c++/11/deque \ + /usr/include/c++/11/bits/stl_deque.h /usr/include/c++/11/bits/deque.tcc \ + /usr/include/c++/11/bits/stl_heap.h /usr/include/c++/11/bits/stl_queue.h \ + /usr/include/c++/11/climits \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/limits.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/syslimits.h \ + /usr/include/limits.h /usr/include/x86_64-linux-gnu/bits/posix1_lim.h \ + /usr/include/x86_64-linux-gnu/bits/local_lim.h \ + /usr/include/linux/limits.h \ + /usr/include/x86_64-linux-gnu/bits/posix2_lim.h \ + /usr/include/x86_64-linux-gnu/bits/xopen_lim.h \ + /usr/include/x86_64-linux-gnu/bits/uio_lim.h \ + /usr/include/c++/11/unordered_map /usr/include/c++/11/bits/hashtable.h \ + /usr/include/c++/11/bits/hashtable_policy.h \ + /usr/include/c++/11/bits/enable_special_members.h \ + /usr/include/c++/11/bits/unordered_map.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/vector.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/list_inserter.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/detail/workaround.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/workaround.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/user.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/detail/select_compiler_config.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/compiler/gcc.hpp \ + /usr/include/c++/11/cstddef \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/detail/select_stdlib_config.hpp \ + /usr/include/c++/11/version \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/stdlib/libstdcpp3.hpp \ + /usr/include/unistd.h /usr/include/x86_64-linux-gnu/bits/posix_opt.h \ + /usr/include/x86_64-linux-gnu/bits/environments.h \ + /usr/include/x86_64-linux-gnu/bits/confname.h \ + /usr/include/x86_64-linux-gnu/bits/getopt_posix.h \ + /usr/include/x86_64-linux-gnu/bits/getopt_core.h \ + /usr/include/x86_64-linux-gnu/bits/unistd.h \ + /usr/include/x86_64-linux-gnu/bits/unistd_ext.h \ + /usr/include/linux/close_range.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/detail/select_platform_config.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/platform/linux.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/detail/posix_features.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/detail/suffix.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/helper_macros.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/detail/cxx_composite.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/conditional.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_same.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/integral_constant.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/begin.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/config.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/iterator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/range_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/mutable_iterator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/extract_optional_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/cat.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/config/config.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/has_xxx.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/bool.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/bool_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/adl_barrier.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/adl.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/msvc.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/intel.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/gcc.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/workaround.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/integral_c_tag.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/static_constant.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/na_spec.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/lambda_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/void_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/na.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/na_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/ctps.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/lambda.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/ttp.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/int.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/int_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/nttp_decl.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/nttp.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/integral_wrapper.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/static_cast.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/lambda_arity_param.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/template_arity_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/arity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/dtp.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessor/params.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/preprocessor.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/comma_if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/punctuation/comma_if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/iif.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/logical/bool.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/config/limits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/logical/limits/bool_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/facilities/empty.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/punctuation/comma.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repeat.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/repeat.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/debug/error.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/detail/auto_rec.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/detail/limits/auto_rec_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/tuple/eat.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/limits/repeat_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/inc.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/inc.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/limits/inc_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessor/enum.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessor/def_params_tail.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/limits/arity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/logical/and.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/logical/bitand.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/identity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/facilities/identity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/empty.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/add.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/dec.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/limits/dec_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/while.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/fold_left.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/detail/fold_left.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/expr_iif.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/adt.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/detail/is_binary.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/detail/check.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/logical/compl.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/detail/limits/fold_left_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/limits/fold_left_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/fold_right.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/detail/fold_right.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/reverse.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/detail/limits/fold_right_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/detail/while.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/detail/limits/while_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/limits/while_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/logical/bitor.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/tuple/elem.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/facilities/expand.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/facilities/overload.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/variadic/size.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/facilities/check_empty.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/variadic/has_opt.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/variadic/limits/size_64.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/tuple/rem.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/tuple/detail/is_single_return.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/variadic/elem.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/variadic/limits/elem_64.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/detail/is_maximum_number.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/comparison/equal.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/comparison/not_equal.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/comparison/limits/not_equal_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/detail/maximum_number.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/detail/is_minimum_number.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/logical/not.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/sub.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/eti.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/overload_resolution.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/type_wrapper.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/yes_no.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/arrays.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/has_xxx.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/msvc_typename.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/array/elem.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/array/data.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/array/size.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/enum_params.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/enum_trailing_params.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/remove_reference.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/iterator_traits.hpp \ + /usr/include/c++/11/iterator /usr/include/c++/11/bits/stream_iterator.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/msvc_has_iterator_workaround.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/const_iterator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/remove_const.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_const.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/eval_if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/value_wknd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/integral.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/lambda_support.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/end.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/implementation_help.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/common.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/sfinae.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_array.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/detail/yes_no_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_void.hpp \ + /usr/include/string.h /usr/include/strings.h \ + /usr/include/x86_64-linux-gnu/bits/strings_fortified.h \ + /usr/include/x86_64-linux-gnu/bits/string_fortified.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/utility.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/detail/config_begin.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/detail/workaround.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/utility_core.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/core.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/detail/config_end.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/detail/meta_utils.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/detail/meta_utils_core.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/detail/addressof.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/detail/type_traits.hpp \ + /usr/include/c++/11/cassert /usr/include/assert.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/deque.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/list.hpp \ + /usr/include/c++/11/list /usr/include/c++/11/bits/stl_list.h \ + /usr/include/c++/11/bits/allocated_ptr.h \ + /usr/include/c++/11/bits/list.tcc \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/slist.hpp \ + /usr/include/c++/11/ext/slist /usr/include/c++/11/algorithm \ + /usr/include/c++/11/bits/stl_algo.h \ + /usr/include/c++/11/bits/algorithmfwd.h \ + /usr/include/c++/11/bits/stl_tempbuf.h \ + /usr/include/c++/11/bits/uniform_int_dist.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/stack.hpp \ + /usr/include/c++/11/stack /usr/include/c++/11/bits/stl_stack.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/queue.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/set.hpp \ + /usr/include/c++/11/set /usr/include/c++/11/bits/stl_set.h \ + /usr/include/c++/11/bits/stl_multiset.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/map.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/list_of.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/assignment_exception.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/iterator_range.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/iterator_range_core.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assert.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/iterator_facade.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/interoperable.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/or.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/use_preprocessed.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/nested_type_wknd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/include_preprocessed.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/compiler.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/stringize.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/or.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_convertible.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/intrinsics.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/detail/config.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/version.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_complete.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/declval.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/add_rvalue_reference.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_reference.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_lvalue_reference.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_rvalue_reference.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_function.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/detail/is_function_cxx_11.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/static_assert.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_arithmetic.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_integral.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_floating_point.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_abstract.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/add_lvalue_reference.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/add_reference.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/detail/config_def.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/detail/config_undef.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/iterator_categories.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/identity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/placeholders.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/arg.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/arg_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/na_assert.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/assert.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/not.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/gpu.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/pp_counter.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/arity_spec.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/arg_typedef.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/arg.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/placeholders.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/detail/facade_iterator_category.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/use_default.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/and.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/and.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/detail/indirect_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_pointer.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_class.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_volatile.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_member_function_pointer.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/detail/is_member_function_pointer_cxx_11.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_member_pointer.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/remove_cv.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/remove_pointer.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/detail/select_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/detail/enable_if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/addressof.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/add_const.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/add_pointer.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_pod.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_scalar.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_enum.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/always.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessor/default_params.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/apply.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/apply_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/apply_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/apply_wrap.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/has_apply.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/has_apply.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/msvc_never_true.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/apply_wrap.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/lambda.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/bind.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/bind_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/bind.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/bind_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/next.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/next_prior.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/common_name_wknd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/protect.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/bind.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/full_lambda.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/quote.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/void.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/has_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/bcc.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/quote.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/template_arity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/template_arity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/full_lambda.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/apply.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_base_and_derived.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/functions.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/size.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/size_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/difference_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/has_range_iterator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/enable_if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/enable_if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/concepts.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept_check.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept/assert.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept/detail/general.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept/detail/backward_compatibility.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept/detail/has_constraints.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/conversion_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept/usage.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept/detail/concept_def.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/for_each_i.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/for.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/detail/for.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/detail/limits/for_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/limits/for_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/seq.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/elem.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/limits/elem_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/size.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/limits/size_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/detail/is_empty.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/enum.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/limits/enum_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept/detail/concept_undef.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/iterator_concepts.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/limits.hpp \ + /usr/include/c++/11/limits \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/value_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/misc_concept.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/make_unsigned.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_signed.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_unsigned.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/add_volatile.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/has_member_size.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/cstdint.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/base_from_member.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/enum_binary_params.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/repeat_from_to.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/binary.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/deduce_d.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/cat.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/fold_left.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/limits/fold_left_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/transform.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/mod.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/detail/div_base.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/comparison/less_equal.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/detail/is_1_number.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/identity_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/function_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/checked_delete.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/noncopyable.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/distance.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/distance.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/empty.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/rbegin.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/reverse_iterator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/reverse_iterator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/iterator_adaptor.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/rend.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/algorithm/equal.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/safe_bool.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/next_prior.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_plus.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/detail/has_binary_operator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/make_void.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_plus_assign.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_minus.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_minus_assign.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/advance.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/iterator_range_io.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/tuple/tuple.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/ref.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/ref.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/tuple/detail/tuple_basic.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/cv_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/add_cv.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/remove_volatile.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/swap.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/swap.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/throw_exception.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/exception/exception.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assert/source_location.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/current_function.hpp \ + /usr/include/c++/11/cstring \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/decay.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/remove_bounds.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/remove_extent.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/declval.hpp \ + /usr/include/c++/11/thread /usr/include/c++/11/bits/std_thread.h \ + /usr/include/c++/11/bits/refwrap.h /usr/include/c++/11/bits/unique_ptr.h \ + /usr/include/c++/11/bits/this_thread_sleep.h /usr/include/c++/11/chrono \ + /usr/include/c++/11/ratio /usr/include/c++/11/ctime \ + /usr/include/c++/11/bits/parse_numbers.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Dense \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Core \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/DisableStupidWarnings.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/Macros.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/ConfigureVectorization.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/mmintrin.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/emmintrin.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/xmmintrin.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/mm_malloc.h \ + /usr/include/c++/11/stdlib.h /usr/include/c++/11/complex \ + /usr/include/c++/11/sstream /usr/include/c++/11/bits/sstream.tcc \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/MKL_support.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/omp.h \ + /usr/include/c++/11/functional /usr/include/c++/11/bits/std_function.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/Constants.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/Meta.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/ForwardDeclarations.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/StaticAssert.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/XprHelper.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/Memory.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/IntegralConstant.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/SymbolicIndex.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/NumTraits.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/MathFunctions.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/GenericPacketMath.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/MathFunctionsImpl.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/Default/ConjHelper.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/Default/Half.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/Default/BFloat16.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/Default/TypeCasting.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/Default/GenericPacketMathFunctionsFwd.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/SSE/PacketMath.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/SSE/TypeCasting.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/SSE/MathFunctions.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/SSE/Complex.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/Default/Settings.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/Default/GenericPacketMathFunctions.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/functors/TernaryFunctors.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/functors/BinaryFunctors.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/functors/UnaryFunctors.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/functors/NullaryFunctors.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/functors/StlFunctors.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/functors/AssignmentFunctors.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/IndexedViewHelper.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/ReshapedHelper.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/ArithmeticSequence.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/IO.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/DenseCoeffsBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/DenseBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/CommonCwiseUnaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/BlockMethods.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/IndexedViewMethods.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/IndexedViewMethods.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/ReshapedMethods.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/ReshapedMethods.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/MatrixBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/CommonCwiseBinaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/MatrixCwiseUnaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/MatrixCwiseBinaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/EigenBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Product.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CoreEvaluators.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/AssignEvaluator.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Assign.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/ArrayBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/ArrayCwiseUnaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/ArrayCwiseBinaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/BlasUtil.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/DenseStorage.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/NestByValue.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/ReturnByValue.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/NoAlias.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/PlainObjectBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Matrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Array.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CwiseTernaryOp.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CwiseBinaryOp.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CwiseUnaryOp.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CwiseNullaryOp.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CwiseUnaryView.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/SelfCwiseBinaryOp.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Dot.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/StableNorm.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Stride.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/MapBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Map.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Ref.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Block.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/VectorBlock.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/IndexedView.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Reshaped.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Transpose.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/DiagonalMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Diagonal.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/DiagonalProduct.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Redux.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Visitor.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Fuzzy.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Swap.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CommaInitializer.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/GeneralProduct.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Solve.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Inverse.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/SolverBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/PermutationMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Transpositions.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/TriangularMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/SelfAdjointView.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/GeneralBlockPanelKernel.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/Parallelizer.h \ + /usr/include/c++/11/atomic /usr/include/c++/11/bits/atomic_base.h \ + /usr/include/c++/11/bits/atomic_lockfree_defines.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/ProductEvaluators.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/GeneralMatrixVector.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/GeneralMatrixMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/SolveTriangular.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/GeneralMatrixMatrixTriangular.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/SelfadjointMatrixVector.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/SelfadjointMatrixMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/SelfadjointProduct.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/SelfadjointRank2Update.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/TriangularMatrixVector.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/TriangularMatrixMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/TriangularSolverMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/TriangularSolverVector.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/BandMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CoreIterators.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/ConditionEstimator.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/BooleanRedux.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Select.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/VectorwiseOp.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/PartialReduxEvaluator.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Random.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Replicate.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Reverse.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/ArrayWrapper.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/StlIterators.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/GlobalFunctions.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/ReenableStupidWarnings.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/LU \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/misc/Kernel.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/misc/Image.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/LU/FullPivLU.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/LU/PartialPivLU.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/LU/Determinant.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/LU/InverseImpl.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/LU/arch/InverseSize4.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Cholesky \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Jacobi \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Jacobi/Jacobi.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Cholesky/LLT.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Cholesky/LDLT.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/QR \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Householder \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Householder/Householder.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Householder/HouseholderSequence.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Householder/BlockHouseholder.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/QR/HouseholderQR.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/QR/FullPivHouseholderQR.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/QR/ColPivHouseholderQR.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/QR/CompleteOrthogonalDecomposition.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/SVD \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/misc/RealSvd2x2.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SVD/UpperBidiagonalization.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SVD/SVDBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SVD/JacobiSVD.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SVD/BDCSVD.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Geometry \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/OrthoMethods.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/EulerAngles.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Homogeneous.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/RotationBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Rotation2D.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Quaternion.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/AngleAxis.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Transform.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Translation.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Scaling.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Hyperplane.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/ParametrizedLine.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/AlignedBox.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Umeyama.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/arch/Geometry_SIMD.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Eigenvalues \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/Tridiagonalization.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/RealSchur.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/HessenbergDecomposition.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/EigenSolver.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/RealSchur.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/SelfAdjointEigenSolver.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/Tridiagonalization.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/GeneralizedSelfAdjointEigenSolver.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/HessenbergDecomposition.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/ComplexSchur.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/ComplexEigenSolver.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/ComplexSchur.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/RealQZ.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/GeneralizedEigenSolver.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/RealQZ.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/MatrixBaseEigenvalues.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Geometry \ + /usr/include/c++/11/memory \ + /usr/include/c++/11/bits/stl_raw_storage_iter.h \ + /usr/include/c++/11/bits/align.h /usr/include/c++/11/bit \ + /usr/include/c++/11/bits/shared_ptr.h \ + /usr/include/c++/11/bits/shared_ptr_base.h \ + /usr/include/c++/11/ext/concurrence.h \ + /usr/include/c++/11/bits/shared_ptr_atomic.h \ + /usr/include/c++/11/backward/auto_ptr.h /usr/include/c++/11/math.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format.hpp \ + /usr/include/c++/11/locale \ + /usr/include/c++/11/bits/locale_facets_nonio.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/time_members.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/messages_members.h \ + /usr/include/libintl.h /usr/include/c++/11/bits/codecvt.h \ + /usr/include/c++/11/bits/locale_facets_nonio.tcc \ + /usr/include/c++/11/bits/locale_conv.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/detail/compat_workarounds.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/detail/config_macros.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/detail/workarounds_gcc-2_95.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/detail/workarounds_stlport.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/format_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/internals_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/internals.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/ignore_unused.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/optional.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/explicit_operator_bool.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/bad_optional_access.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/alignment_of.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/conjunction.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/disjunction.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_nothrow_constructor.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_default_constructible.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/type_with_alignment.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_assignable.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_base_of.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_constructible.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_destructible.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_nothrow_move_assignable.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_trivial_move_assign.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_nothrow_assign.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/enable_if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_nothrow_move_constructible.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/none.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/none_t.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/compare_pointees.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/result_of.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/type_identity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/detail/result_of_variadic.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/optional_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_config.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_factory_support.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_aligned_storage.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_hash.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_trivially_copyable_base.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_reference_spec.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_relops.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_swap.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/alt_sstream.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/allocator_access.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/pointer_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/shared_ptr.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/shared_ptr.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/requires_cxx11.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/pragma_message.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/shared_count.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/bad_weak_ptr.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_counted_base.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_has_gcc_intrinsics.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_has_sync_intrinsics.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_counted_base_gcc_atomic.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_typeinfo_.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_counted_impl.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_noexcept.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_disable_deprecated.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_convertible.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_nullptr_t.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/spinlock_pool.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/spinlock.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/spinlock_gcc_atomic.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/yield_k.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_thread_pause.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_thread_sleep.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/operator_bool.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/local_sp_deleter.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/local_counted_base.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/alt_sstream_impl.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/format_class.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/exceptions.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/format_implementation.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/group.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/feed_args.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/detail/msvc_disambiguater.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/parsing.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/free_funcs.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/detail/unset_macros.hpp \ + /usr/include/c++/11/numeric /usr/include/c++/11/bits/stl_numeric.h diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o new file mode 100644 index 0000000000000000000000000000000000000000..6c1789ee3eb359c219b15a7852d531b0452aeb27 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc70092d8bb3d9ece849a0602607bb92893b98fd637954b9eaec79a578496f7e +size 7775200 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o.d b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o.d new file mode 100644 index 0000000000000000000000000000000000000000..55e27b1d1247100f73aa8753f1c48a21cc8e49b0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o.d @@ -0,0 +1,1190 @@ +CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o: \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/app/pybind_api.cpp \ + /usr/include/stdc-predef.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/include/Utils.h \ + /usr/include/c++/11/iostream \ + /usr/include/x86_64-linux-gnu/c++/11/bits/c++config.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/os_defines.h \ + /usr/include/features.h /usr/include/features-time64.h \ + /usr/include/x86_64-linux-gnu/bits/wordsize.h \ + /usr/include/x86_64-linux-gnu/bits/timesize.h \ + /usr/include/x86_64-linux-gnu/sys/cdefs.h \ + /usr/include/x86_64-linux-gnu/bits/long-double.h \ + /usr/include/x86_64-linux-gnu/gnu/stubs.h \ + /usr/include/x86_64-linux-gnu/gnu/stubs-64.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/cpu_defines.h \ + /usr/include/c++/11/ostream /usr/include/c++/11/ios \ + /usr/include/c++/11/iosfwd /usr/include/c++/11/bits/stringfwd.h \ + /usr/include/c++/11/bits/memoryfwd.h /usr/include/c++/11/bits/postypes.h \ + /usr/include/c++/11/cwchar /usr/include/wchar.h \ + /usr/include/x86_64-linux-gnu/bits/libc-header-start.h \ + /usr/include/x86_64-linux-gnu/bits/floatn.h \ + /usr/include/x86_64-linux-gnu/bits/floatn-common.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/stddef.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/stdarg.h \ + /usr/include/x86_64-linux-gnu/bits/wchar.h \ + /usr/include/x86_64-linux-gnu/bits/types/wint_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/mbstate_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/__mbstate_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/__FILE.h \ + /usr/include/x86_64-linux-gnu/bits/types/FILE.h \ + /usr/include/x86_64-linux-gnu/bits/types/locale_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/__locale_t.h \ + /usr/include/x86_64-linux-gnu/bits/wchar2.h \ + /usr/include/c++/11/exception /usr/include/c++/11/bits/exception.h \ + /usr/include/c++/11/bits/exception_ptr.h \ + /usr/include/c++/11/bits/exception_defines.h \ + /usr/include/c++/11/bits/cxxabi_init_exception.h \ + /usr/include/c++/11/typeinfo /usr/include/c++/11/bits/hash_bytes.h \ + /usr/include/c++/11/new /usr/include/c++/11/bits/move.h \ + /usr/include/c++/11/type_traits \ + /usr/include/c++/11/bits/nested_exception.h \ + /usr/include/c++/11/bits/char_traits.h \ + /usr/include/c++/11/bits/stl_algobase.h \ + /usr/include/c++/11/bits/functexcept.h \ + /usr/include/c++/11/bits/cpp_type_traits.h \ + /usr/include/c++/11/ext/type_traits.h \ + /usr/include/c++/11/ext/numeric_traits.h \ + /usr/include/c++/11/bits/stl_pair.h \ + /usr/include/c++/11/bits/stl_iterator_base_types.h \ + /usr/include/c++/11/bits/stl_iterator_base_funcs.h \ + /usr/include/c++/11/bits/concept_check.h \ + /usr/include/c++/11/debug/assertions.h \ + /usr/include/c++/11/bits/stl_iterator.h \ + /usr/include/c++/11/bits/ptr_traits.h /usr/include/c++/11/debug/debug.h \ + /usr/include/c++/11/bits/predefined_ops.h /usr/include/c++/11/cstdint \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/stdint.h /usr/include/stdint.h \ + /usr/include/x86_64-linux-gnu/bits/types.h \ + /usr/include/x86_64-linux-gnu/bits/typesizes.h \ + /usr/include/x86_64-linux-gnu/bits/time64.h \ + /usr/include/x86_64-linux-gnu/bits/stdint-intn.h \ + /usr/include/x86_64-linux-gnu/bits/stdint-uintn.h \ + /usr/include/c++/11/bits/localefwd.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/c++locale.h \ + /usr/include/c++/11/clocale /usr/include/locale.h \ + /usr/include/x86_64-linux-gnu/bits/locale.h /usr/include/c++/11/cctype \ + /usr/include/ctype.h /usr/include/x86_64-linux-gnu/bits/endian.h \ + /usr/include/x86_64-linux-gnu/bits/endianness.h \ + /usr/include/c++/11/bits/ios_base.h /usr/include/c++/11/ext/atomicity.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/gthr.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/gthr-default.h \ + /usr/include/pthread.h /usr/include/sched.h \ + /usr/include/x86_64-linux-gnu/bits/types/time_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct_timespec.h \ + /usr/include/x86_64-linux-gnu/bits/sched.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct_sched_param.h \ + /usr/include/x86_64-linux-gnu/bits/cpu-set.h /usr/include/time.h \ + /usr/include/x86_64-linux-gnu/bits/time.h \ + /usr/include/x86_64-linux-gnu/bits/timex.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct_timeval.h \ + /usr/include/x86_64-linux-gnu/bits/types/clock_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct_tm.h \ + /usr/include/x86_64-linux-gnu/bits/types/clockid_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/timer_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct_itimerspec.h \ + /usr/include/x86_64-linux-gnu/bits/pthreadtypes.h \ + /usr/include/x86_64-linux-gnu/bits/thread-shared-types.h \ + /usr/include/x86_64-linux-gnu/bits/pthreadtypes-arch.h \ + /usr/include/x86_64-linux-gnu/bits/atomic_wide_counter.h \ + /usr/include/x86_64-linux-gnu/bits/struct_mutex.h \ + /usr/include/x86_64-linux-gnu/bits/struct_rwlock.h \ + /usr/include/x86_64-linux-gnu/bits/setjmp.h \ + /usr/include/x86_64-linux-gnu/bits/types/__sigset_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct___jmp_buf_tag.h \ + /usr/include/x86_64-linux-gnu/bits/pthread_stack_min-dynamic.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/atomic_word.h \ + /usr/include/x86_64-linux-gnu/sys/single_threaded.h \ + /usr/include/c++/11/bits/locale_classes.h /usr/include/c++/11/string \ + /usr/include/c++/11/bits/allocator.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/c++allocator.h \ + /usr/include/c++/11/ext/new_allocator.h \ + /usr/include/c++/11/bits/ostream_insert.h \ + /usr/include/c++/11/bits/cxxabi_forced.h \ + /usr/include/c++/11/bits/stl_function.h \ + /usr/include/c++/11/backward/binders.h \ + /usr/include/c++/11/bits/range_access.h \ + /usr/include/c++/11/initializer_list \ + /usr/include/c++/11/bits/basic_string.h \ + /usr/include/c++/11/ext/alloc_traits.h \ + /usr/include/c++/11/bits/alloc_traits.h \ + /usr/include/c++/11/bits/stl_construct.h \ + /usr/include/c++/11/ext/string_conversions.h /usr/include/c++/11/cstdlib \ + /usr/include/stdlib.h /usr/include/x86_64-linux-gnu/bits/waitflags.h \ + /usr/include/x86_64-linux-gnu/bits/waitstatus.h \ + /usr/include/x86_64-linux-gnu/sys/types.h /usr/include/endian.h \ + /usr/include/x86_64-linux-gnu/bits/byteswap.h \ + /usr/include/x86_64-linux-gnu/bits/uintn-identity.h \ + /usr/include/x86_64-linux-gnu/sys/select.h \ + /usr/include/x86_64-linux-gnu/bits/select.h \ + /usr/include/x86_64-linux-gnu/bits/types/sigset_t.h \ + /usr/include/x86_64-linux-gnu/bits/select2.h /usr/include/alloca.h \ + /usr/include/x86_64-linux-gnu/bits/stdlib-bsearch.h \ + /usr/include/x86_64-linux-gnu/bits/stdlib-float.h \ + /usr/include/x86_64-linux-gnu/bits/stdlib.h \ + /usr/include/c++/11/bits/std_abs.h /usr/include/c++/11/cstdio \ + /usr/include/stdio.h /usr/include/x86_64-linux-gnu/bits/types/__fpos_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/__fpos64_t.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct_FILE.h \ + /usr/include/x86_64-linux-gnu/bits/types/cookie_io_functions_t.h \ + /usr/include/x86_64-linux-gnu/bits/stdio_lim.h \ + /usr/include/x86_64-linux-gnu/bits/stdio.h \ + /usr/include/x86_64-linux-gnu/bits/stdio2.h /usr/include/c++/11/cerrno \ + /usr/include/errno.h /usr/include/x86_64-linux-gnu/bits/errno.h \ + /usr/include/linux/errno.h /usr/include/x86_64-linux-gnu/asm/errno.h \ + /usr/include/asm-generic/errno.h /usr/include/asm-generic/errno-base.h \ + /usr/include/x86_64-linux-gnu/bits/types/error_t.h \ + /usr/include/c++/11/bits/charconv.h \ + /usr/include/c++/11/bits/functional_hash.h \ + /usr/include/c++/11/bits/basic_string.tcc \ + /usr/include/c++/11/bits/locale_classes.tcc \ + /usr/include/c++/11/system_error \ + /usr/include/x86_64-linux-gnu/c++/11/bits/error_constants.h \ + /usr/include/c++/11/stdexcept /usr/include/c++/11/streambuf \ + /usr/include/c++/11/bits/streambuf.tcc \ + /usr/include/c++/11/bits/basic_ios.h \ + /usr/include/c++/11/bits/locale_facets.h /usr/include/c++/11/cwctype \ + /usr/include/wctype.h /usr/include/x86_64-linux-gnu/bits/wctype-wchar.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/ctype_base.h \ + /usr/include/c++/11/bits/streambuf_iterator.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/ctype_inline.h \ + /usr/include/c++/11/bits/locale_facets.tcc \ + /usr/include/c++/11/bits/basic_ios.tcc \ + /usr/include/c++/11/bits/ostream.tcc /usr/include/c++/11/istream \ + /usr/include/c++/11/bits/istream.tcc /usr/include/c++/11/map \ + /usr/include/c++/11/bits/stl_tree.h \ + /usr/include/c++/11/ext/aligned_buffer.h \ + /usr/include/c++/11/bits/stl_map.h /usr/include/c++/11/tuple \ + /usr/include/c++/11/utility /usr/include/c++/11/bits/stl_relops.h \ + /usr/include/c++/11/array /usr/include/c++/11/bits/uses_allocator.h \ + /usr/include/c++/11/bits/invoke.h \ + /usr/include/c++/11/bits/stl_multimap.h \ + /usr/include/c++/11/bits/erase_if.h /usr/include/c++/11/vector \ + /usr/include/c++/11/bits/stl_uninitialized.h \ + /usr/include/c++/11/bits/stl_vector.h \ + /usr/include/c++/11/bits/stl_bvector.h \ + /usr/include/c++/11/bits/vector.tcc /usr/include/c++/11/cmath \ + /usr/include/math.h /usr/include/x86_64-linux-gnu/bits/math-vector.h \ + /usr/include/x86_64-linux-gnu/bits/libm-simd-decl-stubs.h \ + /usr/include/x86_64-linux-gnu/bits/flt-eval-method.h \ + /usr/include/x86_64-linux-gnu/bits/fp-logb.h \ + /usr/include/x86_64-linux-gnu/bits/fp-fast.h \ + /usr/include/x86_64-linux-gnu/bits/mathcalls-helper-functions.h \ + /usr/include/x86_64-linux-gnu/bits/mathcalls.h \ + /usr/include/x86_64-linux-gnu/bits/mathcalls-narrow.h \ + /usr/include/x86_64-linux-gnu/bits/iscanonical.h \ + /usr/include/c++/11/queue /usr/include/c++/11/deque \ + /usr/include/c++/11/bits/stl_deque.h /usr/include/c++/11/bits/deque.tcc \ + /usr/include/c++/11/bits/stl_heap.h /usr/include/c++/11/bits/stl_queue.h \ + /usr/include/c++/11/climits \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/limits.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/syslimits.h \ + /usr/include/limits.h /usr/include/x86_64-linux-gnu/bits/posix1_lim.h \ + /usr/include/x86_64-linux-gnu/bits/local_lim.h \ + /usr/include/linux/limits.h \ + /usr/include/x86_64-linux-gnu/bits/posix2_lim.h \ + /usr/include/x86_64-linux-gnu/bits/xopen_lim.h \ + /usr/include/x86_64-linux-gnu/bits/uio_lim.h \ + /usr/include/c++/11/unordered_map /usr/include/c++/11/bits/hashtable.h \ + /usr/include/c++/11/bits/hashtable_policy.h \ + /usr/include/c++/11/bits/enable_special_members.h \ + /usr/include/c++/11/bits/unordered_map.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/vector.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/list_inserter.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/detail/workaround.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/workaround.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/user.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/detail/select_compiler_config.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/compiler/gcc.hpp \ + /usr/include/c++/11/cstddef \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/detail/select_stdlib_config.hpp \ + /usr/include/c++/11/version \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/stdlib/libstdcpp3.hpp \ + /usr/include/unistd.h /usr/include/x86_64-linux-gnu/bits/posix_opt.h \ + /usr/include/x86_64-linux-gnu/bits/environments.h \ + /usr/include/x86_64-linux-gnu/bits/confname.h \ + /usr/include/x86_64-linux-gnu/bits/getopt_posix.h \ + /usr/include/x86_64-linux-gnu/bits/getopt_core.h \ + /usr/include/x86_64-linux-gnu/bits/unistd.h \ + /usr/include/x86_64-linux-gnu/bits/unistd_ext.h \ + /usr/include/linux/close_range.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/detail/select_platform_config.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/platform/linux.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/detail/posix_features.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/detail/suffix.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/helper_macros.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/detail/cxx_composite.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/conditional.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_same.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/integral_constant.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/begin.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/config.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/iterator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/range_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/mutable_iterator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/extract_optional_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/cat.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/config/config.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/has_xxx.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/bool.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/bool_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/adl_barrier.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/adl.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/msvc.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/intel.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/gcc.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/workaround.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/integral_c_tag.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/static_constant.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/na_spec.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/lambda_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/void_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/na.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/na_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/ctps.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/lambda.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/ttp.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/int.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/int_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/nttp_decl.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/nttp.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/integral_wrapper.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/static_cast.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/lambda_arity_param.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/template_arity_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/arity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/dtp.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessor/params.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/preprocessor.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/comma_if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/punctuation/comma_if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/iif.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/logical/bool.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/config/limits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/logical/limits/bool_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/facilities/empty.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/punctuation/comma.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repeat.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/repeat.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/debug/error.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/detail/auto_rec.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/detail/limits/auto_rec_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/tuple/eat.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/limits/repeat_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/inc.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/inc.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/limits/inc_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessor/enum.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessor/def_params_tail.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/limits/arity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/logical/and.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/logical/bitand.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/identity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/facilities/identity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/empty.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/add.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/dec.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/limits/dec_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/while.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/fold_left.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/detail/fold_left.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/expr_iif.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/adt.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/detail/is_binary.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/detail/check.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/logical/compl.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/detail/limits/fold_left_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/limits/fold_left_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/fold_right.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/detail/fold_right.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/reverse.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/list/detail/limits/fold_right_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/detail/while.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/detail/limits/while_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/limits/while_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/logical/bitor.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/tuple/elem.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/facilities/expand.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/facilities/overload.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/variadic/size.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/facilities/check_empty.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/variadic/has_opt.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/variadic/limits/size_64.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/tuple/rem.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/tuple/detail/is_single_return.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/variadic/elem.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/variadic/limits/elem_64.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/detail/is_maximum_number.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/comparison/equal.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/comparison/not_equal.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/comparison/limits/not_equal_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/detail/maximum_number.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/detail/is_minimum_number.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/logical/not.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/sub.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/eti.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/overload_resolution.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/type_wrapper.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/yes_no.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/arrays.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/has_xxx.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/msvc_typename.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/array/elem.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/array/data.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/array/size.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/enum_params.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/enum_trailing_params.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/remove_reference.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/iterator_traits.hpp \ + /usr/include/c++/11/iterator /usr/include/c++/11/bits/stream_iterator.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/msvc_has_iterator_workaround.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/const_iterator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/remove_const.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_const.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/eval_if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/value_wknd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/integral.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/lambda_support.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/end.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/implementation_help.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/common.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/sfinae.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_array.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/detail/yes_no_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_void.hpp \ + /usr/include/string.h /usr/include/strings.h \ + /usr/include/x86_64-linux-gnu/bits/strings_fortified.h \ + /usr/include/x86_64-linux-gnu/bits/string_fortified.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/utility.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/detail/config_begin.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/detail/workaround.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/utility_core.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/core.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/detail/config_end.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/detail/meta_utils.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/detail/meta_utils_core.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/detail/addressof.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/move/detail/type_traits.hpp \ + /usr/include/c++/11/cassert /usr/include/assert.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/deque.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/list.hpp \ + /usr/include/c++/11/list /usr/include/c++/11/bits/stl_list.h \ + /usr/include/c++/11/bits/allocated_ptr.h \ + /usr/include/c++/11/bits/list.tcc \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/slist.hpp \ + /usr/include/c++/11/ext/slist /usr/include/c++/11/algorithm \ + /usr/include/c++/11/bits/stl_algo.h \ + /usr/include/c++/11/bits/algorithmfwd.h \ + /usr/include/c++/11/bits/stl_tempbuf.h \ + /usr/include/c++/11/bits/uniform_int_dist.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/stack.hpp \ + /usr/include/c++/11/stack /usr/include/c++/11/bits/stl_stack.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/queue.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/set.hpp \ + /usr/include/c++/11/set /usr/include/c++/11/bits/stl_set.h \ + /usr/include/c++/11/bits/stl_multiset.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/std/map.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/list_of.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assign/assignment_exception.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/iterator_range.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/iterator_range_core.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assert.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/iterator_facade.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/interoperable.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/or.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/use_preprocessed.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/nested_type_wknd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/include_preprocessed.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/compiler.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/stringize.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/or.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_convertible.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/intrinsics.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/detail/config.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/version.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_complete.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/declval.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/add_rvalue_reference.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_reference.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_lvalue_reference.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_rvalue_reference.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_function.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/detail/is_function_cxx_11.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/static_assert.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_arithmetic.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_integral.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_floating_point.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_abstract.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/add_lvalue_reference.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/add_reference.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/detail/config_def.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/detail/config_undef.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/iterator_categories.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/identity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/placeholders.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/arg.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/arg_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/na_assert.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/assert.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/not.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/gpu.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/pp_counter.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/arity_spec.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/arg_typedef.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/arg.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/placeholders.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/detail/facade_iterator_category.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/use_default.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/and.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/and.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/detail/indirect_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_pointer.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_class.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_volatile.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_member_function_pointer.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/detail/is_member_function_pointer_cxx_11.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_member_pointer.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/remove_cv.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/remove_pointer.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/detail/select_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/detail/enable_if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/addressof.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/add_const.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/add_pointer.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_pod.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_scalar.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_enum.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/always.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessor/default_params.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/apply.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/apply_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/apply_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/apply_wrap.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/has_apply.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/has_apply.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/msvc_never_true.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/apply_wrap.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/lambda.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/bind.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/bind_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/bind.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/bind_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/next.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/next_prior.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/common_name_wknd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/protect.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/bind.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/full_lambda.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/quote.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/void.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/has_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/config/bcc.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/quote.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/template_arity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/template_arity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/full_lambda.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/aux_/preprocessed/gcc/apply.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_base_and_derived.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/functions.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/size.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/size_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/difference_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/has_range_iterator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/enable_if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/enable_if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/concepts.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept_check.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept/assert.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept/detail/general.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept/detail/backward_compatibility.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept/detail/has_constraints.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/conversion_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept/usage.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept/detail/concept_def.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/for_each_i.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/for.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/detail/for.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/detail/limits/for_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/limits/for_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/seq.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/elem.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/limits/elem_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/size.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/limits/size_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/detail/is_empty.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/enum.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/limits/enum_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/concept/detail/concept_undef.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/iterator_concepts.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/limits.hpp \ + /usr/include/c++/11/limits \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/value_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/misc_concept.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/make_unsigned.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_signed.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_unsigned.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/add_volatile.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/has_member_size.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/cstdint.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/base_from_member.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/enum_binary_params.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/repeat_from_to.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/binary.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/control/deduce_d.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/cat.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/fold_left.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/limits/fold_left_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/seq/transform.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/mod.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/detail/div_base.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/comparison/less_equal.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/arithmetic/detail/is_1_number.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/identity_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/function_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/checked_delete.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/noncopyable.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/distance.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/distance.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/empty.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/rbegin.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/reverse_iterator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/reverse_iterator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/iterator_adaptor.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/rend.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/algorithm/equal.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/safe_bool.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/next_prior.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_plus.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/detail/has_binary_operator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/make_void.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_plus_assign.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_minus.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_minus_assign.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/advance.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/iterator_range_io.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/tuple/tuple.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/ref.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/ref.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/tuple/detail/tuple_basic.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/cv_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/add_cv.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/remove_volatile.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/swap.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/swap.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/throw_exception.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/exception/exception.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/assert/source_location.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/current_function.hpp \ + /usr/include/c++/11/cstring \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/decay.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/remove_bounds.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/remove_extent.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/declval.hpp \ + /usr/include/c++/11/thread /usr/include/c++/11/bits/std_thread.h \ + /usr/include/c++/11/bits/refwrap.h /usr/include/c++/11/bits/unique_ptr.h \ + /usr/include/c++/11/bits/this_thread_sleep.h /usr/include/c++/11/chrono \ + /usr/include/c++/11/ratio /usr/include/c++/11/ctime \ + /usr/include/c++/11/bits/parse_numbers.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Dense \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Core \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/DisableStupidWarnings.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/Macros.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/ConfigureVectorization.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/mmintrin.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/emmintrin.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/xmmintrin.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/mm_malloc.h \ + /usr/include/c++/11/stdlib.h /usr/include/c++/11/complex \ + /usr/include/c++/11/sstream /usr/include/c++/11/bits/sstream.tcc \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/MKL_support.h \ + /usr/lib/gcc/x86_64-linux-gnu/11/include/omp.h \ + /usr/include/c++/11/functional /usr/include/c++/11/bits/std_function.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/Constants.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/Meta.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/ForwardDeclarations.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/StaticAssert.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/XprHelper.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/Memory.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/IntegralConstant.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/SymbolicIndex.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/NumTraits.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/MathFunctions.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/GenericPacketMath.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/MathFunctionsImpl.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/Default/ConjHelper.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/Default/Half.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/Default/BFloat16.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/Default/TypeCasting.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/Default/GenericPacketMathFunctionsFwd.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/SSE/PacketMath.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/SSE/TypeCasting.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/SSE/MathFunctions.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/SSE/Complex.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/Default/Settings.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/arch/Default/GenericPacketMathFunctions.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/functors/TernaryFunctors.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/functors/BinaryFunctors.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/functors/UnaryFunctors.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/functors/NullaryFunctors.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/functors/StlFunctors.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/functors/AssignmentFunctors.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/IndexedViewHelper.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/ReshapedHelper.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/ArithmeticSequence.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/IO.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/DenseCoeffsBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/DenseBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/CommonCwiseUnaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/BlockMethods.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/IndexedViewMethods.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/IndexedViewMethods.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/ReshapedMethods.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/ReshapedMethods.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/MatrixBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/CommonCwiseBinaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/MatrixCwiseUnaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/MatrixCwiseBinaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/EigenBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Product.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CoreEvaluators.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/AssignEvaluator.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Assign.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/ArrayBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/ArrayCwiseUnaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/ArrayCwiseBinaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/BlasUtil.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/DenseStorage.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/NestByValue.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/ReturnByValue.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/NoAlias.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/PlainObjectBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Matrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Array.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CwiseTernaryOp.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CwiseBinaryOp.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CwiseUnaryOp.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CwiseNullaryOp.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CwiseUnaryView.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/SelfCwiseBinaryOp.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Dot.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/StableNorm.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Stride.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/MapBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Map.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Ref.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Block.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/VectorBlock.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/IndexedView.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Reshaped.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Transpose.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/DiagonalMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Diagonal.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/DiagonalProduct.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Redux.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Visitor.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Fuzzy.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Swap.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CommaInitializer.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/GeneralProduct.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Solve.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Inverse.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/SolverBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/PermutationMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Transpositions.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/TriangularMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/SelfAdjointView.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/GeneralBlockPanelKernel.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/Parallelizer.h \ + /usr/include/c++/11/atomic /usr/include/c++/11/bits/atomic_base.h \ + /usr/include/c++/11/bits/atomic_lockfree_defines.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/ProductEvaluators.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/GeneralMatrixVector.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/GeneralMatrixMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/SolveTriangular.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/GeneralMatrixMatrixTriangular.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/SelfadjointMatrixVector.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/SelfadjointMatrixMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/SelfadjointProduct.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/SelfadjointRank2Update.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/TriangularMatrixVector.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/TriangularMatrixMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/TriangularSolverMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/products/TriangularSolverVector.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/BandMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/CoreIterators.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/ConditionEstimator.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/BooleanRedux.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Select.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/VectorwiseOp.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/PartialReduxEvaluator.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Random.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Replicate.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/Reverse.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/ArrayWrapper.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/StlIterators.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/GlobalFunctions.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Core/util/ReenableStupidWarnings.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/LU \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/misc/Kernel.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/misc/Image.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/LU/FullPivLU.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/LU/PartialPivLU.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/LU/Determinant.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/LU/InverseImpl.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/LU/arch/InverseSize4.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Cholesky \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Jacobi \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Jacobi/Jacobi.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Cholesky/LLT.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Cholesky/LDLT.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/QR \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Householder \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Householder/Householder.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Householder/HouseholderSequence.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Householder/BlockHouseholder.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/QR/HouseholderQR.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/QR/FullPivHouseholderQR.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/QR/ColPivHouseholderQR.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/QR/CompleteOrthogonalDecomposition.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/SVD \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/misc/RealSvd2x2.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SVD/UpperBidiagonalization.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SVD/SVDBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SVD/JacobiSVD.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SVD/BDCSVD.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Geometry \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/OrthoMethods.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/EulerAngles.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Homogeneous.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/RotationBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Rotation2D.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Quaternion.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/AngleAxis.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Transform.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Translation.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Scaling.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Hyperplane.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/ParametrizedLine.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/AlignedBox.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/Umeyama.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Geometry/arch/Geometry_SIMD.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Eigenvalues \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/Tridiagonalization.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/RealSchur.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/HessenbergDecomposition.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/EigenSolver.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/RealSchur.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/SelfAdjointEigenSolver.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/Tridiagonalization.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/GeneralizedSelfAdjointEigenSolver.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/HessenbergDecomposition.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/ComplexSchur.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/ComplexEigenSolver.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/ComplexSchur.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/RealQZ.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/GeneralizedEigenSolver.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/RealQZ.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/Eigenvalues/MatrixBaseEigenvalues.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Geometry \ + /usr/include/c++/11/memory \ + /usr/include/c++/11/bits/stl_raw_storage_iter.h \ + /usr/include/c++/11/bits/align.h /usr/include/c++/11/bit \ + /usr/include/c++/11/bits/shared_ptr.h \ + /usr/include/c++/11/bits/shared_ptr_base.h \ + /usr/include/c++/11/ext/concurrence.h \ + /usr/include/c++/11/bits/shared_ptr_atomic.h \ + /usr/include/c++/11/backward/auto_ptr.h /usr/include/c++/11/math.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format.hpp \ + /usr/include/c++/11/locale \ + /usr/include/c++/11/bits/locale_facets_nonio.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/time_members.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/messages_members.h \ + /usr/include/libintl.h /usr/include/c++/11/bits/codecvt.h \ + /usr/include/c++/11/bits/locale_facets_nonio.tcc \ + /usr/include/c++/11/bits/locale_conv.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/detail/compat_workarounds.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/detail/config_macros.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/detail/workarounds_gcc-2_95.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/detail/workarounds_stlport.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/format_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/internals_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/internals.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/ignore_unused.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/optional.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/explicit_operator_bool.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/bad_optional_access.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/alignment_of.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/conjunction.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/disjunction.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_nothrow_constructor.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_default_constructible.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/type_with_alignment.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_assignable.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_base_of.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_constructible.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_destructible.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_nothrow_move_assignable.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_trivial_move_assign.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_nothrow_assign.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/enable_if.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_nothrow_move_constructible.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/none.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/none_t.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/compare_pointees.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/result_of.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/type_identity.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/utility/detail/result_of_variadic.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/optional_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_config.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_factory_support.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_aligned_storage.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_hash.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_trivially_copyable_base.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_reference_spec.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_relops.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/optional/detail/optional_swap.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/alt_sstream.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/allocator_access.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/pointer_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/shared_ptr.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/shared_ptr.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/requires_cxx11.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/pragma_message.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/shared_count.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/bad_weak_ptr.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_counted_base.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_has_gcc_intrinsics.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_has_sync_intrinsics.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_counted_base_gcc_atomic.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_typeinfo_.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_counted_impl.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_noexcept.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_disable_deprecated.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_convertible.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_nullptr_t.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/spinlock_pool.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/spinlock.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/spinlock_gcc_atomic.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/yield_k.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_thread_pause.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/sp_thread_sleep.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/operator_bool.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/local_sp_deleter.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/smart_ptr/detail/local_counted_base.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/alt_sstream_impl.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/format_class.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/exceptions.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/format_implementation.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/group.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/feed_args.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/detail/msvc_disambiguater.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/parsing.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/free_funcs.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/format/detail/unset_macros.hpp \ + /usr/include/c++/11/numeric /usr/include/c++/11/bits/stl_numeric.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/std_containers_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/std/string_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/yes_no_type.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/sequence_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/std/list_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/std/slist_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/config.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/trim.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/as_literal.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/range/detail/str_types.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/detail/trim.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/classification.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/detail/classification.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/predicate_facade.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/case_conv.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/iterator/transform_iterator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/detail/case_conv.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/predicate.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/compare.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/find.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/finder.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/constants.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/detail/finder.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/detail/predicate.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/split.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/iter_find.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/concept.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/find_iterator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/detail/find_iterator.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/function.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/iterate.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/iteration/iterate.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/slot/slot.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/slot/detail/def.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/function/detail/prologue.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/function/detail/requires_cxx11.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/no_tr1/functional.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/function/function_base.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/function/function_fwd.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/function_equal.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/typeinfo.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/demangle.hpp \ + /usr/include/c++/11/cxxabi.h \ + /usr/include/x86_64-linux-gnu/c++/11/bits/cxxabi_tweaks.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_trivial_copy.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_copy_constructible.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/has_trivial_destructor.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/composite_traits.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/type_traits/is_union.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mem_fn.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/bind/mem_fn.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/bind/detail/requires_cxx11.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/get_pointer.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/config/no_tr1/memory.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/bind/mem_fn_template.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/bind/mem_fn_cc.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/enum.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/repetition/enum.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/enum_params.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/iteration/detail/iter/forward1.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/iteration/detail/bounds/lower1.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/slot/detail/shared.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/iteration/detail/bounds/upper1.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/preprocessor/iteration/detail/iter/limits/forward1_256.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/function/detail/function_iterate.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/function/detail/maybe_include.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/function/function_template.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/core/no_exceptions_support.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/function/detail/epilogue.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/detail/util.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/join.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/detail/sequence.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/mpl/logical.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/replace.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/find_format.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/detail/find_format.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/detail/find_format_store.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/detail/replace_storage.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/detail/find_format_all.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/formatter.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/detail/formatter.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/boost/algorithm/string/erase.hpp \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/pybind11.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/class.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/attr.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/common.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/conduit/wrap_include_python_h.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/Python.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/patchlevel.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pyconfig.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pymacconfig.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pyport.h \ + /usr/include/inttypes.h /usr/include/x86_64-linux-gnu/sys/time.h \ + /usr/include/x86_64-linux-gnu/sys/stat.h \ + /usr/include/x86_64-linux-gnu/bits/stat.h \ + /usr/include/x86_64-linux-gnu/bits/struct_stat.h \ + /usr/include/x86_64-linux-gnu/bits/statx.h /usr/include/linux/stat.h \ + /usr/include/linux/types.h /usr/include/x86_64-linux-gnu/asm/types.h \ + /usr/include/asm-generic/types.h /usr/include/asm-generic/int-ll64.h \ + /usr/include/x86_64-linux-gnu/asm/bitsperlong.h \ + /usr/include/asm-generic/bitsperlong.h /usr/include/linux/posix_types.h \ + /usr/include/linux/stddef.h \ + /usr/include/x86_64-linux-gnu/asm/posix_types.h \ + /usr/include/x86_64-linux-gnu/asm/posix_types_64.h \ + /usr/include/asm-generic/posix_types.h \ + /usr/include/x86_64-linux-gnu/bits/statx-generic.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct_statx_timestamp.h \ + /usr/include/x86_64-linux-gnu/bits/types/struct_statx.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/exports.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pymacro.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pymath.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pymem.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/pymem.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pytypedefs.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pybuffer.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/object.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/object.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/objimpl.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/objimpl.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/typeslots.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pyhash.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/pydebug.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/bytearrayobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/bytearrayobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/bytesobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/bytesobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/unicodeobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/unicodeobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/code.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/initconfig.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pystate.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/pystate.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pyerrors.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/pyerrors.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/longobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/longobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/longintrepr.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/boolobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/floatobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/floatobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/complexobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/complexobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/rangeobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/memoryobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/tupleobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/tupleobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/listobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/listobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/dictobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/dictobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/odictobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/enumobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/setobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/setobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/methodobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/methodobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/moduleobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/funcobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/classobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/fileobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/fileobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pycapsule.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pyframe.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/pyframe.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/traceback.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/traceback.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/sliceobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/cellobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/iterobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/genobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/descrobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/descrobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/genericaliasobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/warnings.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/warnings.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/weakrefobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/weakrefobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/structseq.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/picklebufobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/pytime.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/codecs.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pythread.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/pythread.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/context.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/modsupport.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/modsupport.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/compile.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/compile.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pythonrun.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/pythonrun.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pylifecycle.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/pylifecycle.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/ceval.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/ceval.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/sysmodule.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/sysmodule.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/osmodule.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/intrcheck.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/import.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/import.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/abstract.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/abstract.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/bltinmodule.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/pyctype.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pystrtod.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pystrcmp.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/fileutils.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/fileutils.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/pyfpe.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/tracemalloc.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/frameobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/cpython/frameobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11/pythread.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/pybind11_namespace_macros.h \ + /usr/include/c++/11/forward_list /usr/include/c++/11/bits/forward_list.h \ + /usr/include/c++/11/bits/forward_list.tcc /usr/include/c++/11/typeindex \ + /usr/include/c++/11/unordered_set \ + /usr/include/c++/11/bits/unordered_set.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/cast.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/argument_vector.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/pytypes.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/buffer_info.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/descr.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/holder_caster_foreign_helpers.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/gil.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/internals.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/conduit/pybind11_platform_abi_id.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/gil_simple.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/trampoline_self_life_support.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/using_smart_holder.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/struct_smart_holder.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/value_and_holder.h \ + /usr/include/c++/11/mutex /usr/include/c++/11/bits/std_mutex.h \ + /usr/include/c++/11/bits/unique_lock.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/native_enum_data.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/type_caster_base.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/cpp_conduit.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/dynamic_raw_ptr_cast_if_possible.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/typeid.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/options.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/exception_translation.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/function_record_pyobject.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/function_ref.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/detail/init.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/gil_safe_call_once.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/typing.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/stl.h \ + /usr/include/c++/11/valarray /usr/include/c++/11/bits/valarray_array.h \ + /usr/include/c++/11/bits/valarray_array.tcc \ + /usr/include/c++/11/bits/valarray_before.h \ + /usr/include/c++/11/bits/slice_array.h \ + /usr/include/c++/11/bits/valarray_after.h \ + /usr/include/c++/11/bits/gslice.h \ + /usr/include/c++/11/bits/gslice_array.h \ + /usr/include/c++/11/bits/mask_array.h \ + /usr/include/c++/11/bits/indirect_array.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/eigen.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/eigen/matrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/numpy.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/complex.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include/pybind11/eigen/common.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/Core \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/SparseCore \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseUtil.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseMatrixBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/CommonCwiseUnaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/CommonCwiseBinaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/MatrixCwiseUnaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/MatrixCwiseBinaryOps.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/plugins/BlockMethods.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseAssign.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/CompressedStorage.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/AmbiVector.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseCompressedBase.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseMap.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/MappedSparseMatrix.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseVector.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseRef.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseCwiseUnaryOp.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseCwiseBinaryOp.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseTranspose.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseBlock.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseDot.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseRedux.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseView.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseDiagonalProduct.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/ConservativeSparseSparseProduct.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseSparseProductWithPruning.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseProduct.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseDenseProduct.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseSelfAdjointView.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseTriangularView.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/TriangularSolver.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparsePermutation.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseFuzzy.h \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3/Eigen/src/SparseCore/SparseSolverBase.h diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/progress.marks b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/progress.marks new file mode 100644 index 0000000000000000000000000000000000000000..00750edc07d6415dcc07ae0351e9397b0222b7ba --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/progress.marks @@ -0,0 +1 @@ +3 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/Makefile b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..df772873063feeeb7f62924344108a7731351540 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/Makefile @@ -0,0 +1,208 @@ +# CMAKE generated file: DO NOT EDIT! +# Generated by "Unix Makefiles" Generator, CMake Version 3.22 + +# Default target executed when no arguments are given to make. +default_target: all +.PHONY : default_target + +# Allow only one "make -f Makefile2" at a time, but pass parallelism. +.NOTPARALLEL: + +#============================================================================= +# Special targets provided by cmake. + +# Disable implicit rules so canonical targets will work. +.SUFFIXES: + +# Disable VCS-based implicit rules. +% : %,v + +# Disable VCS-based implicit rules. +% : RCS/% + +# Disable VCS-based implicit rules. +% : RCS/%,v + +# Disable VCS-based implicit rules. +% : SCCS/s.% + +# Disable VCS-based implicit rules. +% : s.% + +.SUFFIXES: .hpux_make_needs_suffix_list + +# Command-line flag to silence nested $(MAKE). +$(VERBOSE)MAKESILENT = -s + +#Suppress display of executed commands. +$(VERBOSE).SILENT: + +# A target that is always out of date. +cmake_force: +.PHONY : cmake_force + +#============================================================================= +# Set environment variables for the build. + +# The shell in which to execute make rules. +SHELL = /bin/sh + +# The CMake executable. +CMAKE_COMMAND = /usr/bin/cmake + +# The command to remove a file. +RM = /usr/bin/cmake -E rm -f + +# Escaping for special characters. +EQUALS = = + +# The top-level source directory on which CMake was run. +CMAKE_SOURCE_DIR = /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp + +# The top-level build directory on which CMake was run. +CMAKE_BINARY_DIR = /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build + +#============================================================================= +# Targets provided globally by CMake. + +# Special rule for the target edit_cache +edit_cache: + @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "No interactive CMake dialog available..." + /usr/bin/cmake -E echo No\ interactive\ CMake\ dialog\ available. +.PHONY : edit_cache + +# Special rule for the target edit_cache +edit_cache/fast: edit_cache +.PHONY : edit_cache/fast + +# Special rule for the target rebuild_cache +rebuild_cache: + @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." + /usr/bin/cmake --regenerate-during-build -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) +.PHONY : rebuild_cache + +# Special rule for the target rebuild_cache +rebuild_cache/fast: rebuild_cache +.PHONY : rebuild_cache/fast + +# The main all target +all: cmake_check_build_system + $(CMAKE_COMMAND) -E cmake_progress_start /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build//CMakeFiles/progress.marks + $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 all + $(CMAKE_COMMAND) -E cmake_progress_start /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles 0 +.PHONY : all + +# The main clean target +clean: + $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 clean +.PHONY : clean + +# The main clean target +clean/fast: clean +.PHONY : clean/fast + +# Prepare targets for installation. +preinstall: all + $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 preinstall +.PHONY : preinstall + +# Prepare targets for installation. +preinstall/fast: + $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 preinstall +.PHONY : preinstall/fast + +# clear depends +depend: + $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 +.PHONY : depend + +#============================================================================= +# Target rules for targets named mycpp + +# Build rule for target. +mycpp: cmake_check_build_system + $(MAKE) $(MAKESILENT) -f CMakeFiles/Makefile2 mycpp +.PHONY : mycpp + +# fast build rule for target. +mycpp/fast: + $(MAKE) $(MAKESILENT) -f CMakeFiles/mycpp.dir/build.make CMakeFiles/mycpp.dir/build +.PHONY : mycpp/fast + +src/Utils.o: src/Utils.cpp.o +.PHONY : src/Utils.o + +# target to build an object file +src/Utils.cpp.o: + $(MAKE) $(MAKESILENT) -f CMakeFiles/mycpp.dir/build.make CMakeFiles/mycpp.dir/src/Utils.cpp.o +.PHONY : src/Utils.cpp.o + +src/Utils.i: src/Utils.cpp.i +.PHONY : src/Utils.i + +# target to preprocess a source file +src/Utils.cpp.i: + $(MAKE) $(MAKESILENT) -f CMakeFiles/mycpp.dir/build.make CMakeFiles/mycpp.dir/src/Utils.cpp.i +.PHONY : src/Utils.cpp.i + +src/Utils.s: src/Utils.cpp.s +.PHONY : src/Utils.s + +# target to generate assembly for a file +src/Utils.cpp.s: + $(MAKE) $(MAKESILENT) -f CMakeFiles/mycpp.dir/build.make CMakeFiles/mycpp.dir/src/Utils.cpp.s +.PHONY : src/Utils.cpp.s + +src/app/pybind_api.o: src/app/pybind_api.cpp.o +.PHONY : src/app/pybind_api.o + +# target to build an object file +src/app/pybind_api.cpp.o: + $(MAKE) $(MAKESILENT) -f CMakeFiles/mycpp.dir/build.make CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o +.PHONY : src/app/pybind_api.cpp.o + +src/app/pybind_api.i: src/app/pybind_api.cpp.i +.PHONY : src/app/pybind_api.i + +# target to preprocess a source file +src/app/pybind_api.cpp.i: + $(MAKE) $(MAKESILENT) -f CMakeFiles/mycpp.dir/build.make CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.i +.PHONY : src/app/pybind_api.cpp.i + +src/app/pybind_api.s: src/app/pybind_api.cpp.s +.PHONY : src/app/pybind_api.s + +# target to generate assembly for a file +src/app/pybind_api.cpp.s: + $(MAKE) $(MAKESILENT) -f CMakeFiles/mycpp.dir/build.make CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.s +.PHONY : src/app/pybind_api.cpp.s + +# Help Target +help: + @echo "The following are some of the valid targets for this Makefile:" + @echo "... all (the default if no target is provided)" + @echo "... clean" + @echo "... depend" + @echo "... edit_cache" + @echo "... rebuild_cache" + @echo "... mycpp" + @echo "... src/Utils.o" + @echo "... src/Utils.i" + @echo "... src/Utils.s" + @echo "... src/app/pybind_api.o" + @echo "... src/app/pybind_api.i" + @echo "... src/app/pybind_api.s" +.PHONY : help + + + +#============================================================================= +# Special targets to cleanup operation of make. + +# Special rule to run CMake to check the build system integrity. +# No rule that depends on this can have commands that come from listfiles +# because they might be regenerated. +cmake_check_build_system: + $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 +.PHONY : cmake_check_build_system + diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/cmake_install.cmake b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/cmake_install.cmake new file mode 100644 index 0000000000000000000000000000000000000000..e877b041269b26a6bba0b53e9d01890f2675ad0a --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/cmake_install.cmake @@ -0,0 +1,54 @@ +# Install script for directory: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp + +# Set the install prefix +if(NOT DEFINED CMAKE_INSTALL_PREFIX) + set(CMAKE_INSTALL_PREFIX "/usr/local") +endif() +string(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") + +# Set the install configuration name. +if(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) + if(BUILD_TYPE) + string(REGEX REPLACE "^[^A-Za-z0-9_]+" "" + CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") + else() + set(CMAKE_INSTALL_CONFIG_NAME "Release") + endif() + message(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") +endif() + +# Set the component getting installed. +if(NOT CMAKE_INSTALL_COMPONENT) + if(COMPONENT) + message(STATUS "Install component: \"${COMPONENT}\"") + set(CMAKE_INSTALL_COMPONENT "${COMPONENT}") + else() + set(CMAKE_INSTALL_COMPONENT) + endif() +endif() + +# Install shared libraries without execute permission? +if(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) + set(CMAKE_INSTALL_SO_NO_EXE "1") +endif() + +# Is this installation the result of a crosscompile? +if(NOT DEFINED CMAKE_CROSSCOMPILING) + set(CMAKE_CROSSCOMPILING "FALSE") +endif() + +# Set default install directory permissions. +if(NOT DEFINED CMAKE_OBJDUMP) + set(CMAKE_OBJDUMP "/usr/bin/objdump") +endif() + +if(CMAKE_INSTALL_COMPONENT) + set(CMAKE_INSTALL_MANIFEST "install_manifest_${CMAKE_INSTALL_COMPONENT}.txt") +else() + set(CMAKE_INSTALL_MANIFEST "install_manifest.txt") +endif() + +string(REPLACE ";" "\n" CMAKE_INSTALL_MANIFEST_CONTENT + "${CMAKE_INSTALL_MANIFEST_FILES}") +file(WRITE "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/${CMAKE_INSTALL_MANIFEST}" + "${CMAKE_INSTALL_MANIFEST_CONTENT}") diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/compile_commands.json b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/compile_commands.json new file mode 100644 index 0000000000000000000000000000000000000000..5a73a1941cea923c6be2d873b1173b3904253022 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/compile_commands.json @@ -0,0 +1,12 @@ +[ +{ + "directory": "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build", + "command": "/usr/bin/c++ -DBOOST_PROGRAM_OPTIONS_DYN_LINK -DBOOST_PROGRAM_OPTIONS_NO_LIB -DBOOST_SYSTEM_DYN_LINK -DBOOST_SYSTEM_NO_LIB -Dmycpp_EXPORTS -I/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/include -isystem /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include -isystem /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11 -isystem /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include -isystem /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3 -std=c++14 -fopenmp -g3 -O3 -O3 -DNDEBUG -fPIC -fvisibility=hidden -flto=auto -fno-fat-lto-objects -o CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o -c /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/app/pybind_api.cpp", + "file": "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/app/pybind_api.cpp" +}, +{ + "directory": "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build", + "command": "/usr/bin/c++ -DBOOST_PROGRAM_OPTIONS_DYN_LINK -DBOOST_PROGRAM_OPTIONS_NO_LIB -DBOOST_SYSTEM_DYN_LINK -DBOOST_SYSTEM_NO_LIB -Dmycpp_EXPORTS -I/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/include -isystem /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/lib/python3.11/site-packages/pybind11/include -isystem /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/python3.11 -isystem /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include -isystem /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/include/eigen3 -std=c++14 -fopenmp -g3 -O3 -O3 -DNDEBUG -fPIC -fvisibility=hidden -flto=auto -fno-fat-lto-objects -o CMakeFiles/mycpp.dir/src/Utils.cpp.o -c /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/Utils.cpp", + "file": "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/Utils.cpp" +} +] \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/mycpp.cpython-311-x86_64-linux-gnu.so b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/mycpp.cpython-311-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..369b5129680f09e0e2e2801968bfcf4eb36fe963 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/mycpp.cpython-311-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb18fc36010f305f9b435ad69d9c4b6b6ef2177f3c99dfdac2314ae20de6822c +size 168040 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/include/Utils.h b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/include/Utils.h new file mode 100644 index 0000000000000000000000000000000000000000..41703f5b51039b47b2dfe863edde1b448cdff882 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/include/Utils.h @@ -0,0 +1,46 @@ +/*Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. +*/ + + +#pragma once + +// STL +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +using vectorMatrix4f = std::vector>; + + +namespace Utils +{ +float rotationGeodesicDistance(const Eigen::Matrix3f &R1, const Eigen::Matrix3f &R2); + +} // namespace Utils diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/Utils.cpp b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/Utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1455d54b3fab9b602b1e68c4955001d6fc221b9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/Utils.cpp @@ -0,0 +1,29 @@ +/* +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. +*/ + + +#include "Utils.h" + + + +namespace Utils +{ + + +// Difference angle in radian +float rotationGeodesicDistance(const Eigen::Matrix3f &R1, const Eigen::Matrix3f &R2) +{ + float cos = ((R1 * R2.transpose()).trace()-1) / 2.0; + cos = std::max(std::min(cos, 1.0f), -1.0f); + return std::acos(cos); +} + + +} // namespace Utils diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/app/pybind_api.cpp b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/app/pybind_api.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6a415c317dcf7ac16d482d80d330b16a0f186e12 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/mycpp/src/app/pybind_api.cpp @@ -0,0 +1,77 @@ +/* +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. +*/ + + +#include "Utils.h" +#include +#include +#include +#include + +namespace py = pybind11; + + + +//@angle_diff: unit is degree +//@dist_diff: unit is meter +vectorMatrix4f cluster_poses(float angle_diff, float dist_diff, const vectorMatrix4f &poses_in, const vectorMatrix4f &symmetry_tfs) +{ + printf("num original candidates = %d\n",poses_in.size()); + vectorMatrix4f poses_out; + poses_out.push_back(poses_in[0]); + + const float radian_thres = angle_diff/180.0*M_PI; + + for (int i=1;i=dist_diff) + { + continue; + } + + for (const auto &tf: symmetry_tfs) + { + Eigen::Matrix4f cur_pose_tmp = cur_pose*tf; + float rot_diff = Utils::rotationGeodesicDistance(cur_pose_tmp.block(0,0,3,3), cluster.block(0,0,3,3)); + if (rot_diff < radian_thres) + { + isnew = false; + break; + } + } + + if (!isnew) break; + } + + if (isnew) + { + poses_out.push_back(poses_in[i]); + } + } + + printf("num of pose after clustering: %d\n",poses_out.size()); + return poses_out; +} + + + + + +PYBIND11_MODULE(mycpp, m) +{ + m.def("cluster_poses", &cluster_poses, py::call_guard()); +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/offscreen_renderer.py b/OVOW/engine/oneposeviagen/fpose/fpose/offscreen_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..54e2faf581f610c77820faf8e7f27b80636c873e --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/offscreen_renderer.py @@ -0,0 +1,79 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +import os,sys,time,socket +code_path = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(code_path) +import open3d as o3d +import numpy as np +from PIL import Image +import cv2,imageio +import time +import trimesh +import pyrender +from transformations import * +import numpy as np +from PIL import Image +import cv2 +import time +import argparse,pickle +from Utils import * + + +cvcam_in_glcam = np.array([[1,0,0,0], + [0,-1,0,0], + [0,0,-1,0], + [0,0,0,1]]) + +class ModelRendererOffscreen: + def __init__(self, cam_K, H,W, zfar=100): + ''' + @window_sizes: H,W + ''' + self.K = cam_K + self.scene = pyrender.Scene(ambient_light=[1., 1., 1.],bg_color=[0,0,0]) + self.camera = pyrender.IntrinsicsCamera(fx=cam_K[0,0],fy=cam_K[1,1],cx=cam_K[0,2],cy=cam_K[1,2],znear=0.001,zfar=zfar) + self.cam_node = self.scene.add(self.camera, pose=np.eye(4), name='cam') + self.mesh_nodes = [] + + self.H = H + self.W = W + self.r = pyrender.OffscreenRenderer(self.W, self.H) + + + def set_cam_pose(self, cam_pose): + self.cam_node.matrix = cam_pose + + def add_mesh(self, mesh): + mesh = pyrender.Mesh.from_trimesh(mesh, smooth=False) + mesh_node = self.scene.add(mesh,pose=np.eye(4), name='ob') # Object pose parent is cam + self.mesh_nodes.append(mesh_node) + + + def add_point_light(self, intensity=3): + light = pyrender.DirectionalLight(color=[1.0, 1.0, 1.0], intensity=intensity) + self.scene.add(light, pose=np.eye(4)) # Same as camera position + + + def clear_mesh_nodes(self): + for n in self.mesh_nodes: + self.scene.remove_node(n) + + + def render(self,mesh=None,ob_in_cvcam=None, get_normal=False): + if mesh is not None: + mesh = mesh.copy() + mesh.apply_transform(cvcam_in_glcam@ob_in_cvcam) + mesh = pyrender.Mesh.from_trimesh(mesh, smooth=False) + mesh_node = self.scene.add(mesh, pose=np.eye(4), name='ob') # Object pose parent is cam + color, depth = self.r.render(self.scene) # depth: float + if mesh is not None: + self.scene.remove_node(mesh_node) + + return color, depth diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/readme.md b/OVOW/engine/oneposeviagen/fpose/fpose/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..6c163ab593cd0b5a1e3d3c0cb244a89f8f1f084e --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/readme.md @@ -0,0 +1,222 @@ +# FoundationPose: Unified 6D Pose Estimation and Tracking of Novel Objects +[[Paper]](https://arxiv.org/abs/2312.08344) [[Website]](https://nvlabs.github.io/FoundationPose/) + +This is the official implementation of our paper to be appeared in CVPR 2024 (Highlight) + +Contributors: Bowen Wen, Wei Yang, Jan Kautz, Stan Birchfield + +We present FoundationPose, a unified foundation model for 6D object pose estimation and tracking, supporting both model-based and model-free setups. Our approach can be instantly applied at test-time to a novel object without fine-tuning, as long as its CAD model is given, or a small number of reference images are captured. We bridge the gap between these two setups with a neural implicit representation that allows for effective novel view synthesis, keeping the downstream pose estimation modules invariant under the same unified framework. Strong generalizability is achieved via large-scale synthetic training, aided by a large language model (LLM), a novel transformer-based architecture, and contrastive learning formulation. Extensive evaluation on multiple public datasets involving challenging scenarios and objects indicate our unified approach outperforms existing methods specialized for each task by a large margin. In addition, it even achieves comparable results to instance-level methods despite the reduced assumptions. + + + + +**🤖 For ROS version, please check [Isaac ROS Pose Estimation](https://github.com/NVIDIA-ISAAC-ROS/isaac_ros_pose_estimation), which enjoys TRT fast inference and C++ speed up.** + +\ +**🥇 No. 1 on the world-wide [BOP leaderboard](https://bop.felk.cvut.cz/leaderboards/pose-estimation-unseen-bop23/core-datasets/) (as of 2024/03) for model-based novel object pose estimation.** + + +## Demos + +Robotic Applications: + +https://github.com/NVlabs/FoundationPose/assets/23078192/aa341004-5a15-4293-b3da-000471fd74ed + + +AR Applications: + +https://github.com/NVlabs/FoundationPose/assets/23078192/80e96855-a73c-4bee-bcef-7cba92df55ca + + +Results on YCB-Video dataset: + +https://github.com/NVlabs/FoundationPose/assets/23078192/9b5bedde-755b-44ed-a973-45ec85a10bbe + + + +# Bibtex +```bibtex +@InProceedings{foundationposewen2024, +author = {Bowen Wen, Wei Yang, Jan Kautz, Stan Birchfield}, +title = {{FoundationPose}: Unified 6D Pose Estimation and Tracking of Novel Objects}, +booktitle = {CVPR}, +year = {2024}, +} +``` + +If you find the model-free setup useful, please also consider cite: + +```bibtex +@InProceedings{bundlesdfwen2023, +author = {Bowen Wen and Jonathan Tremblay and Valts Blukis and Stephen Tyree and Thomas M\"{u}ller and Alex Evans and Dieter Fox and Jan Kautz and Stan Birchfield}, +title = {{BundleSDF}: {N}eural 6-{DoF} Tracking and {3D} Reconstruction of Unknown Objects}, +booktitle = {CVPR}, +year = {2023}, +} +``` + +# Data prepare + + +1) Download all network weights from [here](https://drive.google.com/drive/folders/1DFezOAD0oD1BblsXVxqDsl8fj0qzB82i?usp=sharing) and put them under the folder `weights/`. For the refiner, you will need `2023-10-28-18-33-37`. For scorer, you will need `2024-01-11-20-02-45`. + +1) [Download demo data](https://drive.google.com/drive/folders/1pRyFmxYXmAnpku7nGRioZaKrVJtIsroP?usp=sharing) and extract them under the folder `demo_data/` + +1) [Optional] Download our large-scale training data: ["FoundationPose Dataset"](https://drive.google.com/drive/folders/1s4pB6p4ApfWMiMjmTXOFco8dHbNXikp-?usp=sharing) + +1) [Optional] Download our preprocessed reference views [here](https://drive.google.com/drive/folders/1PXXCOJqHXwQTbwPwPbGDN9_vLVe0XpFS?usp=sharing) in order to run model-free few-shot version. + +# Env setup option 1: docker (recommended) + ``` + cd docker/ + docker pull wenbowen123/foundationpose && docker tag wenbowen123/foundationpose foundationpose # Or to build from scratch: docker build --network host -t foundationpose . + bash docker/run_container.sh + ``` + + +If it's the first time you launch the container, you need to build extensions. Run this command *inside* the Docker container. +``` +bash build_all.sh +``` + +Later you can execute into the container without re-build. +``` +docker exec -it foundationpose bash +``` + +For more recent GPU such as 4090, refer to [this](https://github.com/NVlabs/FoundationPose/issues/27). +In short, do the following: +``` +docker pull shingarey/foundationpose_custom_cuda121:latest +``` +Then modify the bash script to use this image instead of `foundationpose:latest`. + + +# Env setup option 2: conda (experimental) + +- Setup conda environment + +```bash +# create conda environment +conda create -n foundationpose python=3.9 + +# activate conda environment +conda activate foundationpose + +# Install Eigen3 3.4.0 under conda environment +conda install conda-forge::eigen=3.4.0 +export CMAKE_PREFIX_PATH="$CMAKE_PREFIX_PATH:/eigen/path/under/conda" + +# install dependencies +python -m pip install -r requirements.txt + +# Install NVDiffRast +python -m pip install --quiet --no-cache-dir git+https://github.com/NVlabs/nvdiffrast.git + +# Kaolin (Optional, needed if running model-free setup) +python -m pip install --quiet --no-cache-dir kaolin==0.15.0 -f https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.0.0_cu118.html + +# PyTorch3D +python -m pip install --quiet --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/py39_cu118_pyt200/download.html + +# Build extensions +CMAKE_PREFIX_PATH=$CONDA_PREFIX/lib/python3.9/site-packages/pybind11/share/cmake/pybind11 bash build_all_conda.sh +``` + + +# Run model-based demo +The paths have been set in argparse by default. If you need to change the scene, you can pass the args accordingly. By running on the demo data, you should be able to see the robot manipulating the mustard bottle. Pose estimation is conducted on the first frame, then it automatically switches to tracking mode for the rest of the video. The resulting visualizations will be saved to the `debug_dir` specified in the argparse. (Note the first time running could be slower due to online compilation) +``` +python run_demo.py +``` + + + + + +Feel free to try on other objects (**no need to retrain**) such as driller, by changing the paths in argparse. + + + + +# Run on public datasets (LINEMOD, YCB-Video) + +For this you first need to download LINEMOD dataset and YCB-Video dataset. + +To run model-based version on these two datasets respectively, set the paths based on where you download. The results will be saved to `debug` folder +``` +python run_linemod.py --linemod_dir /path/to/DATASET/LINEMOD --use_reconstructed_mesh 0 + +python run_ycb_video.py --ycbv_dir /path/to/DATASET/YCB_Video --use_reconstructed_mesh 0 +``` + +To run model-free few-shot version. You first need to train Neural Object Field. `ref_view_dir` is based on where you download in the above "Data prepare" section. Set the `dataset` flag to your interested dataset. +``` +python bundlesdf/run_nerf.py --ref_view_dir /path/to/DATASET/YCB_Video/bowen_addon/ref_views_16 --dataset ycbv +``` + +Then run the similar command as the model-based version with some small modifications. Here we are using YCB-Video as example: +``` +python run_ycb_video.py --ycbv_dir /path/to/DATASET/YCB_Video --use_reconstructed_mesh 1 --ref_view_dir /path/to/DATASET/YCB_Video/bowen_addon/ref_views_16 +``` + +# Troubleshooting + + +- For more recent GPU such as 4090, refer to [this](https://github.com/NVlabs/FoundationPose/issues/27). + +- For setting up on Windows, refer to [this](https://github.com/NVlabs/FoundationPose/issues/148). + +- If you are getting unreasonable results, check [this](https://github.com/NVlabs/FoundationPose/issues/44#issuecomment-2048141043) and [this](https://github.com/030422Lee/FoundationPose_manual) + +# Training data download +Our training data include scenes using 3D assets from GSO and Objaverse, rendered with high quality photo-realism and large domain randomization. Each data point includes **RGB, depth, object pose, camera pose, instance segmentation, 2D bounding box**. [[Google Drive]](https://drive.google.com/drive/folders/1s4pB6p4ApfWMiMjmTXOFco8dHbNXikp-?usp=sharing). + + + +- To parse the camera params including extrinsics and intrinsics + ``` + glcam_in_cvcam = np.array([[1,0,0,0], + [0,-1,0,0], + [0,0,-1,0], + [0,0,0,1]]).astype(float) + W, H = camera_params["renderProductResolution"] + with open(f'{base_dir}/camera_params/camera_params_000000.json','r') as ff: + camera_params = json.load(ff) + world_in_glcam = np.array(camera_params['cameraViewTransform']).reshape(4,4).T + cam_in_world = np.linalg.inv(world_in_glcam)@glcam_in_cvcam + world_in_cam = np.linalg.inv(cam_in_world) + focal_length = camera_params["cameraFocalLength"] + horiz_aperture = camera_params["cameraAperture"][0] + vert_aperture = H / W * horiz_aperture + focal_y = H * focal_length / vert_aperture + focal_x = W * focal_length / horiz_aperture + center_y = H * 0.5 + center_x = W * 0.5 + + fx, fy, cx, cy = focal_x, focal_y, center_x, center_y + K = np.eye(3) + K[0,0] = fx + K[1,1] = fy + K[0,2] = cx + K[1,2] = cy + ``` + + + +# Notes +Due to the legal restrictions of Stable-Diffusion that is trained on LAION dataset, we are not able to release the diffusion-based texture augmented data, nor the pretrained weights using it. We thus release the version without training on diffusion-augmented data. Slight performance degradation is expected. + +# Acknowledgement + +We would like to thank Jeff Smith for helping with the code release; NVIDIA Isaac Sim and Omniverse team for the support on synthetic data generation; Tianshi Cao for the valuable discussions. Finally, we are also grateful for the positive feebacks and constructive suggestions brought up by reviewers and AC at CVPR. + + + + +# License +The code and data are released under the NVIDIA Source Code License. Copyright © 2024, NVIDIA Corporation. All rights reserved. + + +# Contact +For questions, please contact [Bowen Wen](https://wenbowen123.github.io/). diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/recover_scale.py b/OVOW/engine/oneposeviagen/fpose/fpose/recover_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..10fa8823cfe0b01d692c10e03cb80b291e86f25f --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/recover_scale.py @@ -0,0 +1,205 @@ +import os +import sys +os.environ["PYOPENGL_PLATFORM"] = "egl" +sys.path.append(os.getcwd()) +import trimesh +import copy +import numpy as np +import imageio +import cv2 +import logging +from oneposeviagen.locate.fit_object_scale import get_scale +from fpose.estimater import * +from fpose.datareader import * + +def get_all_pose(test_scene_dir, mesh, topic, debug, track_refine_iter=8, est_refine_iter=5): + set_logging_format() + set_seed(0) + code_dir = os.path.dirname(os.path.realpath(__file__)) + + debug_dir = os.path.join(code_dir, "results", topic) + os.system(f'rm -rf {debug_dir}/* && mkdir -p {debug_dir}/track_vis {debug_dir}/{topic}') + + to_origin, extents = trimesh.bounds.oriented_bounds(mesh) + bbox = np.stack([-extents/2, extents/2], axis=0).reshape(2,3) + + scorer = get_cached_scorer() + refiner = get_cached_refiner() + glctx = get_cached_glctx() + est = FoundationPose(model_pts=mesh.vertices, model_normals=mesh.vertex_normals, mesh=mesh, scorer=scorer, refiner=refiner, debug_dir=debug_dir, debug=debug, glctx=glctx) + logging.info("estimator initialization done") + + reader = YcbineoatReader(video_dir=test_scene_dir, shorter_side=None, zfar=np.inf) + + for i in range(len(reader.color_files)): + logging.info(f'i:{i}') + color = reader.get_color(i) + depth = reader.get_depth(i) + if i==0: + mask = reader.get_mask(0).astype(bool) + pose = est.register(K=reader.K, rgb=color, depth=depth, ob_mask=mask, iteration=est_refine_iter) + + if debug>=3: + m = mesh.copy() + m.apply_transform(pose) + m.export(f'{debug_dir}/model_tf.obj') + xyz_map = depth2xyzmap(depth, reader.K) + valid = depth>=0.001 + pcd = toOpen3dCloud(xyz_map[valid], color[valid]) + o3d.io.write_point_cloud(f'{debug_dir}/scene_complete.ply', pcd) + else: + pose = est.track_one(rgb=color, depth=depth, K=reader.K, iteration=track_refine_iter) + + os.makedirs(f'{debug_dir}/{topic}', exist_ok=True) + np.savetxt(f'{debug_dir}/{topic}/{reader.id_strs[i]}.txt', pose.reshape(4,4)) + + if debug>=1: + center_pose = pose@np.linalg.inv(to_origin) + vis = draw_posed_3d_box(reader.K, img=color, ob_in_cam=center_pose, bbox=bbox) + vis = draw_xyz_axis(color, ob_in_cam=center_pose, scale=0.1, K=reader.K, thickness=3, transparency=0, is_input_rgb=True) + # cv2.imshow('1', vis[...,::-1]) + # cv2.waitKey(1) + + + if debug>=2: + os.makedirs(f'{debug_dir}/track_vis', exist_ok=True) + imageio.imwrite(f'{debug_dir}/track_vis/{reader.id_strs[i]}.png', vis) + +def get_single_pose(raw_img, depth, mask, intrinsic, mesh, topic, num, debug, est_refine_iter=5): + set_logging_format() + set_seed(0) + code_dir = os.path.dirname(os.path.realpath(__file__)) + + debug_dir = os.path.join(code_dir, "results", topic) + + to_origin, extents = trimesh.bounds.oriented_bounds(mesh) + bbox = np.stack([-extents/2, extents/2], axis=0).reshape(2,3) + + scorer = get_cached_scorer() + refiner = get_cached_refiner() + glctx = get_cached_glctx() + est = FoundationPose(model_pts=mesh.vertices, model_normals=mesh.vertex_normals, mesh=mesh, scorer=scorer, refiner=refiner, debug_dir=debug_dir, debug=debug, glctx=glctx) + logging.info("estimator initialization done") + +# reader = YcbineoatReader(video_dir=test_scene_dir, shorter_side=None, zfar=np.inf) + + # color = reader.get_color(i) + color = cv2.imread(raw_img) + # depth = reader.get_depth(i) + depth = cv2.imread(depth,-1)/1e3 + # mask = reader.get_mask(0).astype(bool) + mask = cv2.imread(mask,-1) + K = intrinsic + if len(mask.shape)==3: + for c in range(3): + if mask[...,c].sum()>0: + mask = mask[...,c] + break + mask = mask.astype(bool) + pose = est.register(K=K, rgb=color, depth=depth, ob_mask=mask, iteration=est_refine_iter) + + os.makedirs(f'{debug_dir}/{topic}', exist_ok=True) + np.savetxt(f'{debug_dir}/{topic}/{num}.txt', pose.reshape(4,4)) + + if debug>=1: + center_pose = pose@np.linalg.inv(to_origin) + vis = draw_posed_3d_box(K, img=color, ob_in_cam=center_pose, bbox=bbox) + vis = draw_xyz_axis(color, ob_in_cam=center_pose, scale=0.1, K=K, thickness=3, transparency=0, is_input_rgb=True) + # cv2.imshow('1', vis[...,::-1]) + # cv2.waitKey(1) + + if debug>=2: + os.makedirs(f'{debug_dir}/track_vis', exist_ok=True) + imageio.imwrite(f'{debug_dir}/track_vis/{num}.png', vis) + + return pose.reshape(4,4) + +def recover_scale(mesh_file, depth_file, raw_img, mask_file, intrinsic_file, topic, out_dir, refine_iters=None): + # OPG_SCALE_REFINE_ITERS: FoundationPose+PnP refine 轮数。romav2 匹配下初始 PnP 已收敛 + # (各轮 scale 修正 <2%,渲染像素差 <3/255),可设 0 直接采用首次结果。 + if refine_iters is None: + refine_iters = int(os.environ.get("OPG_SCALE_REFINE_ITERS", "3")) + mesh = trimesh.load(mesh_file, force='mesh') + mesh_rotated = mesh.copy() + + scales = [] + poses = [] + pose = None + + #进行模型缩放比例和位姿的确定 + M, intrinsic_numpy, scale = get_scale(mesh_file, depth_file, raw_img, mask_file, out_dir, intrinsic_file) + # 保存 PnP 位姿供下游做锚帧初始化(M = S @ world_2_cam,作用于当时的网格状态) + np.savez(os.path.join(out_dir, 'anchor_pose_pnp.npz'), + M=M, K=intrinsic_numpy, scale=scale, mesh_state='initial') + scales.append(scale) + scale_matrix = np.array([[scale, 0, 0, 0], + [0, scale, 0, 0], + [0, 0, scale, 0], + [0, 0, 0, 1]]) + logging.info(f"initial scale: {scale}") + + #进行模型放缩 + mesh.apply_transform(scale_matrix) + mesh_rotated.apply_transform(scale_matrix) + + #按照初次缩放的位姿进行refine + for i in range(refine_iters): + #使用Foundationpose进行位姿估计 + pose = get_single_pose(raw_img, depth_file, mask_file, intrinsic_numpy, mesh_rotated, topic, i, debug=0, est_refine_iter=3) + poses.append(pose) + + #进行模型旋转 + rotation_matrix = np.eye(4) + rotation_matrix[0:3, 0:3] = pose[0:3, 0:3] + mesh_rotated.apply_transform(rotation_matrix) + mesh_rotated.export(os.path.join(out_dir, "rotated_model.obj")) + rotated_mesh_dir = os.path.join(out_dir, "rotated_model.obj") + + #根据得到的位姿再次进行转换矩阵估计 + scale_output = os.path.join(out_dir, f"iteration_{i+1}") + os.makedirs(scale_output, exist_ok=True) + M, intrinsic_numpy, scale = get_scale(rotated_mesh_dir, depth_file, raw_img, mask_file, scale_output, intrinsic_file) + if scale > 1.5 or scale < 0.5: + i = i - 1 + continue + # 该轮 PnP 求解的网格状态正是当前导出的 rotated_model.obj + np.savez(os.path.join(out_dir, 'anchor_pose_pnp.npz'), + M=M, K=intrinsic_numpy, scale=scale, mesh_state='rotated') + scales.append(scale) + scale_matrix = np.array([[scale, 0, 0, 0], + [0, scale, 0, 0], + [0, 0, scale, 0], + [0, 0, 0, 1]]) + logging.info(f"iter{i} scale: {scale}") + + #进行模型缩放 + mesh.apply_transform(scale_matrix) + mesh_rotated.apply_transform(scale_matrix) + + print(f"final scale: {scales}") + print(f"final pose: {poses}") + final_scale = 1.0 + for scale in scales: + final_scale *= scale + return mesh, pose, final_scale + +if __name__ == "__main__": + #输入mesh,ref_img, mask, depth, intrinsic_file + mesh_file = "/baai-cwm-1/baai_cwm_ml/cwm/yuhao.duan/gz/TRELLIS/output/custom_datasets/gun/original_model/output.obj" + depth_file = "/baai-cwm-1/baai_cwm_ml/cwm/yuhao.duan/gz/blenderproc_geng/output/custom_datasets/scene_easy_small/gun/bop_with_true_imgs/lm/train_pbr/000000/depth/000308.png" + raw_img = "/baai-cwm-1/baai_cwm_ml/cwm/yuhao.duan/gz/blenderproc_geng/output/custom_datasets/scene_easy_small/gun/bop_with_true_imgs/lm/train_pbr/000000/rgb/000308.png" + mask_file = "/baai-cwm-1/baai_cwm_ml/cwm/yuhao.duan/gz/blenderproc_geng/output/custom_datasets/scene_easy_small/gun/bop_with_true_imgs/lm/train_pbr/000000/mask/000308_000000.png" + out_path = "results" + intrinsic_file = "/baai-cwm-1/baai_cwm_ml/cwm/yuhao.duan/gz/blenderproc_geng/output/custom_datasets/scene_easy_small/gun/bop_with_true_imgs/lm/train_pbr/000000/scene_camera.json" + topic = "test" + out_dir = os.path.join(out_path, topic) + ref_img = os.path.join(out_dir, "ref_img.png") + + os.system(f'rm -rf {out_dir}/* && mkdir -p {out_dir}/track_vis {out_dir}/{topic}') + os.makedirs(out_dir, exist_ok=True) + + recover_scale(mesh_file, depth_file, raw_img, mask_file, intrinsic_file, topic, out_dir, ref_img) + + + + #进行最终的位姿估计 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/requirements.txt b/OVOW/engine/oneposeviagen/fpose/fpose/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..bc43341c0547221ed9e4a72d3baf90d37bc002c5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/requirements.txt @@ -0,0 +1,82 @@ +# PyTorch 2.1.1 +--extra-index-url https://download.pytorch.org/whl/cu118 +# torch==2.1.1+cu118 +# torchvision==0.16.1+cu118 +torch==2.0.0+cu118 +torchvision==0.15.1+cu118 +torchaudio==2.0.1+cu118 + + +# JupyterLab +jupyterlab==4.1.5 +ipywidgets==8.1.2 + + +# Common Libraries +numpy==1.26.4 +scipy==1.12.0 +scikit-learn==1.4.1.post1 +scikit-image==0.22.0 +pyyaml==6.0.1 +ruamel.yaml==0.18.6 +ninja==1.11.1.1 +h5py==3.10.0 +numba==0.59.1 +pybind11==2.12.0 + +# CV Libraries +imageio==2.34.0 +opencv-python==4.9.0.80 +opencv-contrib-python==4.9.0.80 +plotly==5.20.0 +open3d==0.18.0 +pyglet==1.5.28 +pysdf==0.1.9 + +# Trimesh +trimesh==4.2.2 +xatlas==0.0.9 +rtree==1.2.0 + +# PyRender +pyrender==0.1.45 +pyOpenGL>=3.1.0 +pyOpenGL_accelerate>=3.1.0 + +meshcat==0.3.2 +webdataset==0.2.86 +omegaconf==2.3.0 +pypng==0.20220715.0 +Panda3D==1.10.14 +simplejson==3.19.2 +bokeh==3.4.0 +roma==1.4.4 +seaborn==0.13.2 +pin==2.7.0 +openpyxl==3.1.2 +torchnet==0.0.4 +wandb==0.16.5 +colorama==0.4.6 +GPUtil==1.4.0 +imgaug==0.4.0 +xlsxwriter==3.2.0 +timm==0.9.16 +albumentations==1.4.2 +xatlas==0.0.9 +nodejs==0.1.1 +jupyterlab==4.1.5 +objaverse==0.1.7 +g4f==0.2.7.1 +ultralytics==8.0.120 +pycocotools==2.0.7 +py-spy==0.3.14 +pybullet==3.2.6 +videoio==0.2.8 +kornia==0.7.2 +einops==0.7.0 +transformations==2024.6.1 +joblib==1.3.2 +warp-lang==1.0.2 + +# For PyTorch3D +fvcore==0.1.5.post20221221 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/results/deform/deform/0.txt b/OVOW/engine/oneposeviagen/fpose/fpose/results/deform/deform/0.txt new file mode 100644 index 0000000000000000000000000000000000000000..23e62e99a8605343f5890904d5a11c6781112ecd --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/results/deform/deform/0.txt @@ -0,0 +1,4 @@ +9.662745594978332520e-01 2.528445124626159668e-01 4.881707206368446350e-02 3.025155980139970779e-03 +-9.849511086940765381e-03 2.257202416658401489e-01 -9.741423726081848145e-01 -1.156270597130060196e-02 +-2.573256194591522217e-01 9.408082365989685059e-01 2.205980718135833740e-01 2.502532005310058594e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/results/deform/deform/1.txt b/OVOW/engine/oneposeviagen/fpose/fpose/results/deform/deform/1.txt new file mode 100644 index 0000000000000000000000000000000000000000..c315a97cfc8551ce3f826d8634e9ed0f5769cb4c --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/results/deform/deform/1.txt @@ -0,0 +1,4 @@ +9.988508224487304688e-01 3.408528119325637817e-02 -3.369095176458358765e-02 1.127464976161718369e-02 +-4.115035757422447205e-02 9.703100919723510742e-01 -2.383379191160202026e-01 -1.748510077595710754e-02 +2.456687018275260925e-02 2.394504398107528687e-01 9.705977439880371094e-01 2.433279305696487427e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/results/deform/deform/2.txt b/OVOW/engine/oneposeviagen/fpose/fpose/results/deform/deform/2.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc14af82755aa0a90d3536ed2b0da7ebf8af521e --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/results/deform/deform/2.txt @@ -0,0 +1,4 @@ +9.992311000823974609e-01 -3.846050426363945007e-02 -7.611790671944618225e-03 4.546598065644502640e-03 +3.919254615902900696e-02 9.850473403930664062e-01 1.677667647600173950e-01 -1.398470252752304077e-02 +1.045582583174109459e-03 -1.679361015558242798e-01 9.857973456382751465e-01 2.491606622934341431e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/results/test/test/0.txt b/OVOW/engine/oneposeviagen/fpose/fpose/results/test/test/0.txt new file mode 100644 index 0000000000000000000000000000000000000000..bbf622c5b285443e06cf8f4cd97c5689364a3a97 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/results/test/test/0.txt @@ -0,0 +1,4 @@ +-5.363692641258239746e-01 8.359221816062927246e-01 -1.163702234625816345e-01 1.398308575153350830e-01 +5.676269531250000000e-01 2.552543580532073975e-01 -7.827163338661193848e-01 7.767391204833984375e-02 +-6.245859265327453613e-01 -4.858798086643218994e-01 -6.114026308059692383e-01 7.357901930809020996e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/results/test/test/1.txt b/OVOW/engine/oneposeviagen/fpose/fpose/results/test/test/1.txt new file mode 100644 index 0000000000000000000000000000000000000000..352aa68db8ba9d72c404c14ba5cbf5284f2f932a --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/results/test/test/1.txt @@ -0,0 +1,4 @@ +9.992273449897766113e-01 -3.693978860974311829e-02 1.342283468693494797e-02 1.406092047691345215e-01 +3.664965927600860596e-02 9.991021156311035156e-01 2.125319093465805054e-02 7.718347012996673584e-02 +-1.419586781412363052e-02 -2.074482105672359467e-02 9.996839761734008789e-01 7.381798028945922852e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/results/test/test/2.txt b/OVOW/engine/oneposeviagen/fpose/fpose/results/test/test/2.txt new file mode 100644 index 0000000000000000000000000000000000000000..f60f0d7fdcd964a274d1acf2421cb033c58978ca --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/results/test/test/2.txt @@ -0,0 +1,4 @@ +9.975408911705017090e-01 -2.938508056104183197e-02 6.362880021333694458e-02 1.407950669527053833e-01 +2.635798603296279907e-02 9.985041618347167969e-01 4.790219664573669434e-02 7.645531743764877319e-02 +-6.494123488664627075e-02 -4.610724374651908875e-02 9.968232512474060059e-01 7.398648262023925781e-01 +0.000000000000000000e+00 0.000000000000000000e+00 0.000000000000000000e+00 1.000000000000000000e+00 diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/run_demo.py b/OVOW/engine/oneposeviagen/fpose/fpose/run_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..9196b94bfeef75ddf50d30697e87db4eafa33706 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/run_demo.py @@ -0,0 +1,79 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from fpose.estimater import * +from fpose.datareader import * +import argparse + + +if __name__=='__main__': + parser = argparse.ArgumentParser() + code_dir = os.path.dirname(os.path.realpath(__file__)) + parser.add_argument('--mesh_file', type=str, default=f'{code_dir}/demo_data/mustard/mesh/textured_simple.obj') + parser.add_argument('--test_scene_dir', type=str, default=f'{code_dir}/demo_data/mustard') + parser.add_argument('--est_refine_iter', type=int, default=5) + parser.add_argument('--track_refine_iter', type=int, default=2) + parser.add_argument('--debug', type=int, default=1) + parser.add_argument('--debug_dir', type=str, default=f'{code_dir}/debug') + args = parser.parse_args() + + set_logging_format() + set_seed(0) + + mesh = trimesh.load(args.mesh_file) + + debug = args.debug + debug_dir = args.debug_dir + os.system(f'rm -rf {debug_dir}/* && mkdir -p {debug_dir}/track_vis {debug_dir}/ob_in_cam') + + to_origin, extents = trimesh.bounds.oriented_bounds(mesh) + bbox = np.stack([-extents/2, extents/2], axis=0).reshape(2,3) + + scorer = ScorePredictor() + refiner = PoseRefinePredictor() + glctx = dr.RasterizeCudaContext() + est = FoundationPose(model_pts=mesh.vertices, model_normals=mesh.vertex_normals, mesh=mesh, scorer=scorer, refiner=refiner, debug_dir=debug_dir, debug=debug, glctx=glctx) + logging.info("estimator initialization done") + + reader = YcbineoatReader(video_dir=args.test_scene_dir, shorter_side=None, zfar=np.inf) + + for i in range(len(reader.color_files)): + logging.info(f'i:{i}') + color = reader.get_color(i) + depth = reader.get_depth(i) + if i==0: + mask = reader.get_mask(0).astype(bool) + pose = est.register(K=reader.K, rgb=color, depth=depth, ob_mask=mask, iteration=args.est_refine_iter) + + if debug>=3: + m = mesh.copy() + m.apply_transform(pose) + m.export(f'{debug_dir}/model_tf.obj') + xyz_map = depth2xyzmap(depth, reader.K) + valid = depth>=0.001 + pcd = toOpen3dCloud(xyz_map[valid], color[valid]) + o3d.io.write_point_cloud(f'{debug_dir}/scene_complete.ply', pcd) + else: + pose = est.track_one(rgb=color, depth=depth, K=reader.K, iteration=args.track_refine_iter) + + os.makedirs(f'{debug_dir}/ob_in_cam', exist_ok=True) + np.savetxt(f'{debug_dir}/ob_in_cam/{reader.id_strs[i]}.txt', pose.reshape(4,4)) + + if debug>=1: + center_pose = pose@np.linalg.inv(to_origin) + vis = draw_posed_3d_box(reader.K, img=color, ob_in_cam=center_pose, bbox=bbox) + vis = draw_xyz_axis(color, ob_in_cam=center_pose, scale=0.1, K=reader.K, thickness=3, transparency=0, is_input_rgb=True) + # cv2.imshow('1', vis[...,::-1]) + # cv2.waitKey(1) + + + if debug>=2: + os.makedirs(f'{debug_dir}/track_vis', exist_ok=True) + imageio.imwrite(f'{debug_dir}/track_vis/{reader.id_strs[i]}.png', vis) + diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/run_linemod.py b/OVOW/engine/oneposeviagen/fpose/fpose/run_linemod.py new file mode 100644 index 0000000000000000000000000000000000000000..d7f9723932547a1db57e63ed8510453f6822d6fc --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/run_linemod.py @@ -0,0 +1,149 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from Utils import * +import json,uuid,joblib,os,sys +import scipy.spatial as spatial +from multiprocessing import Pool +import multiprocessing +from functools import partial +from itertools import repeat +import itertools +from datareader import * +from estimater import * +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/mycpp/build') +import yaml + + + +def get_mask(reader, i_frame, ob_id, detect_type): + if detect_type=='box': + mask = reader.get_mask(i_frame, ob_id) + H,W = mask.shape[:2] + vs,us = np.where(mask>0) + umin = us.min() + umax = us.max() + vmin = vs.min() + vmax = vs.max() + valid = np.zeros((H,W), dtype=bool) + valid[vmin:vmax,umin:umax] = 1 + elif detect_type=='mask': + mask = reader.get_mask(i_frame, ob_id) + if mask is None: + return None + valid = mask>0 + elif detect_type=='detected': + mask = cv2.imread(reader.color_files[i_frame].replace('rgb','mask_cosypose'), -1) + valid = mask==ob_id + else: + raise RuntimeError + return valid + + + +def run_pose_estimation_worker(reader, i_frames, est:FoundationPose=None, debug=0, ob_id=None, device='cuda:0'): + torch.cuda.set_device(device) + est.to_device(device) + est.glctx = dr.RasterizeCudaContext(device=device) + + result = NestDict() + + for i, i_frame in enumerate(i_frames): + logging.info(f"{i}/{len(i_frames)}, i_frame:{i_frame}, ob_id:{ob_id}") + video_id = reader.get_video_id() + color = reader.get_color(i_frame) + depth = reader.get_depth(i_frame) + id_str = reader.id_strs[i_frame] + H,W = color.shape[:2] + + debug_dir =est.debug_dir + + ob_mask = get_mask(reader, i_frame, ob_id, detect_type=detect_type) + if ob_mask is None: + logging.info("ob_mask not found, skip") + result[video_id][id_str][ob_id] = np.eye(4) + return result + + est.gt_pose = reader.get_gt_pose(i_frame, ob_id) + + pose = est.register(K=reader.K, rgb=color, depth=depth, ob_mask=ob_mask, ob_id=ob_id) + logging.info(f"pose:\n{pose}") + + if debug>=3: + m = est.mesh_ori.copy() + tmp = m.copy() + tmp.apply_transform(pose) + tmp.export(f'{debug_dir}/model_tf.obj') + + result[video_id][id_str][ob_id] = pose + + return result + + +def run_pose_estimation(): + wp.force_load(device='cuda') + reader_tmp = LinemodReader(f'{opt.linemod_dir}/lm_test_all/test/000002', split=None) + + debug = opt.debug + use_reconstructed_mesh = opt.use_reconstructed_mesh + debug_dir = opt.debug_dir + + res = NestDict() + glctx = dr.RasterizeCudaContext() + mesh_tmp = trimesh.primitives.Box(extents=np.ones((3)), transform=np.eye(4)).to_mesh() + est = FoundationPose(model_pts=mesh_tmp.vertices.copy(), model_normals=mesh_tmp.vertex_normals.copy(), symmetry_tfs=None, mesh=mesh_tmp, scorer=None, refiner=None, glctx=glctx, debug_dir=debug_dir, debug=debug) + + for ob_id in reader_tmp.ob_ids: + ob_id = int(ob_id) + if use_reconstructed_mesh: + mesh = reader_tmp.get_reconstructed_mesh(ob_id, ref_view_dir=opt.ref_view_dir) + else: + mesh = reader_tmp.get_gt_mesh(ob_id) + symmetry_tfs = reader_tmp.symmetry_tfs[ob_id] + + args = [] + + video_dir = f'{opt.linemod_dir}/lm_test_all/test/{ob_id:06d}' + reader = LinemodReader(video_dir, split=None) + video_id = reader.get_video_id() + est.reset_object(model_pts=mesh.vertices.copy(), model_normals=mesh.vertex_normals.copy(), symmetry_tfs=symmetry_tfs, mesh=mesh) + + for i in range(len(reader.color_files)): + args.append((reader, [i], est, debug, ob_id, "cuda:0")) + + outs = [] + for arg in args: + out = run_pose_estimation_worker(*arg) + outs.append(out) + + for out in outs: + for video_id in out: + for id_str in out[video_id]: + for ob_id in out[video_id][id_str]: + res[video_id][id_str][ob_id] = out[video_id][id_str][ob_id] + + with open(f'{opt.debug_dir}/linemod_res.yml','w') as ff: + yaml.safe_dump(make_yaml_dumpable(res), ff) + + +if __name__=='__main__': + parser = argparse.ArgumentParser() + code_dir = os.path.dirname(os.path.realpath(__file__)) + parser.add_argument('--linemod_dir', type=str, default="/path/to/DATASET/LINEMOD", help="linemod root dir") + parser.add_argument('--use_reconstructed_mesh', type=int, default=0) + parser.add_argument('--ref_view_dir', type=str, default="/path/to/DATASET/YCB_Video/bowen_addon/ref_views_16") + parser.add_argument('--debug', type=int, default=0) + parser.add_argument('--debug_dir', type=str, default=f'{code_dir}/debug') + opt = parser.parse_args() + set_seed(0) + + detect_type = 'mask' # mask / box / detected + + run_pose_estimation() diff --git a/OVOW/engine/oneposeviagen/fpose/fpose/run_ycb_video.py b/OVOW/engine/oneposeviagen/fpose/fpose/run_ycb_video.py new file mode 100644 index 0000000000000000000000000000000000000000..c7d71fcd1df92c46a903a86ff3aa4830f90f3135 --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/fpose/run_ycb_video.py @@ -0,0 +1,149 @@ +# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. +# +# NVIDIA CORPORATION and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION is strictly prohibited. + + +from Utils import * +import json,uuid,joblib,os,sys,argparse +from datareader import * +from estimater import * +code_dir = os.path.dirname(os.path.realpath(__file__)) +sys.path.append(f'{code_dir}/mycpp/build') +import yaml + + +def get_mask(reader, i_frame, ob_id, detect_type): + if detect_type=='box': + mask = reader.get_mask(i_frame, ob_id) + H,W = mask.shape[:2] + vs,us = np.where(mask>0) + umin = us.min() + umax = us.max() + vmin = vs.min() + vmax = vs.max() + valid = np.zeros((H,W), dtype=bool) + valid[vmin:vmax,umin:umax] = 1 + elif detect_type=='mask': + mask = reader.get_mask(i_frame, ob_id, type='mask_visib') + valid = mask>0 + elif detect_type=='cnos': #https://github.com/nv-nguyen/cnos + mask = cv2.imread(reader.color_files[i_frame].replace('rgb','mask_cnos'), -1) + valid = mask==ob_id + else: + raise RuntimeError + + return valid + + + +def run_pose_estimation_worker(reader, i_frames, est:FoundationPose, debug=False, ob_id=None, device:int=0): + result = NestDict() + torch.cuda.set_device(device) + est.to_device(f'cuda:{device}') + est.glctx = dr.RasterizeCudaContext(device) + debug_dir = est.debug_dir + + for i in range(len(i_frames)): + i_frame = i_frames[i] + id_str = reader.id_strs[i_frame] + logging.info(f"{i}/{len(i_frames)}, video:{reader.get_video_id()}, id_str:{id_str}") + color = reader.get_color(i_frame) + depth = reader.get_depth(i_frame) + + H,W = color.shape[:2] + scene_ob_ids = reader.get_instance_ids_in_image(i_frame) + video_id = reader.get_video_id() + + logging.info(f"video:{reader.get_video_id()}, id_str:{id_str}, ob_id:{ob_id}") + if ob_id not in scene_ob_ids: + logging.info(f'skip {ob_id} as it does not exist in this scene') + continue + ob_mask = get_mask(reader, i_frame, ob_id, detect_type=detect_type) + + est.gt_pose = reader.get_gt_pose(i_frame, ob_id) + pose = est.register(K=reader.K, rgb=color, depth=depth, ob_mask=ob_mask, ob_id=ob_id, iteration=5) + logging.info(f"pose:\n{pose}") + + + if debug>=3: + tmp = est.mesh_ori.copy() + tmp.apply_transform(pose) + tmp.export(f'{debug_dir}/model_tf.obj') + + result[video_id][id_str][ob_id] = pose + + return result + + +def run_pose_estimation(): + wp.force_load(device='cuda') + video_dirs = sorted(glob.glob(f'{opt.ycbv_dir}/test/*')) + res = NestDict() + + debug = opt.debug + use_reconstructed_mesh = opt.use_reconstructed_mesh + debug_dir = opt.debug_dir + + reader_tmp = YcbVideoReader(video_dirs[0]) + glctx = dr.RasterizeCudaContext() + mesh_tmp = trimesh.primitives.Box(extents=np.ones((3)), transform=np.eye(4)) + est = FoundationPose(model_pts=mesh_tmp.vertices.copy(), model_normals=mesh_tmp.vertex_normals.copy(), symmetry_tfs=None, mesh=mesh_tmp, scorer=None, refiner=None, glctx=glctx, debug_dir=debug_dir, debug=debug) + + ob_ids = reader_tmp.ob_ids + + for ob_id in ob_ids: + if use_reconstructed_mesh: + mesh = reader_tmp.get_reconstructed_mesh(ob_id, ref_view_dir=opt.ref_view_dir) + else: + mesh = reader_tmp.get_gt_mesh(ob_id) + symmetry_tfs = reader_tmp.symmetry_tfs[ob_id] + + args = [] + for video_dir in video_dirs: + reader = YcbVideoReader(video_dir, zfar=1.5) + scene_ob_ids = reader.get_instance_ids_in_image(0) + if ob_id not in scene_ob_ids: + continue + video_id = reader.get_video_id() + + for i in range(len(reader.color_files)): + if not reader.is_keyframe(i): + continue + args.append((reader, [i], est, debug, ob_id, 0)) + + est.reset_object(model_pts=mesh.vertices.copy(), model_normals=mesh.vertex_normals.copy(), symmetry_tfs=symmetry_tfs, mesh=mesh) + outs = [] + for arg in args: + out = run_pose_estimation_worker(*arg) + outs.append(out) + + for out in outs: + for video_id in out: + for id_str in out[video_id]: + res[video_id][id_str][ob_id] = out[video_id][id_str][ob_id] + + with open(f'{opt.debug_dir}/ycbv_res.yml','w') as ff: + yaml.safe_dump(make_yaml_dumpable(res), ff) + + + +if __name__=='__main__': + parser = argparse.ArgumentParser() + code_dir = os.path.dirname(os.path.realpath(__file__)) + parser.add_argument('--ycbv_dir', type=str, default="/path/to/DATASET/YCB_Video", help="data dir") + parser.add_argument('--use_reconstructed_mesh', type=int, default=0) + parser.add_argument('--ref_view_dir', type=str, default="/path/to/DATASET/YCB_Video/bowen_addon/ref_views_16") + parser.add_argument('--debug', type=int, default=0) + parser.add_argument('--debug_dir', type=str, default=f'{code_dir}/debug') + opt = parser.parse_args() + os.environ["YCB_VIDEO_DIR"] = opt.ycbv_dir + + set_seed(0) + + detect_type = 'mask' # mask / box / detected + + run_pose_estimation() diff --git a/OVOW/engine/oneposeviagen/fpose/setup.py b/OVOW/engine/oneposeviagen/fpose/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..a17480969841a6b97eb14b91f8e44465a06e9b1e --- /dev/null +++ b/OVOW/engine/oneposeviagen/fpose/setup.py @@ -0,0 +1,8 @@ +from setuptools import setup, find_packages + +setup( + name='fpose', + version='0.1', + package_dir={'fpose': 'fpose'}, + packages=find_packages(where='fpose', include=['fpose*']), +) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/locate/__init__.py b/OVOW/engine/oneposeviagen/locate/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/OVOW/engine/oneposeviagen/locate/fit_object_scale.py b/OVOW/engine/oneposeviagen/locate/fit_object_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..69ab249d00f0ee62cb1ac3c549edc709e7a164b3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/locate/fit_object_scale.py @@ -0,0 +1,543 @@ +import os +import open3d as o3d +import numpy as np +import matplotlib.pyplot as plt +import trimesh +import cv2 +import sys +import json +import torch +from scipy.optimize import minimize +from PIL import Image +os.environ["PYOPENGL_PLATFORM"] = "egl" +sys.path.append(os.getcwd()) +from oneposeviagen.locate.match_pairs import image_pair_matching +from pytorch3d.renderer import (look_at_view_transform, PerspectiveCameras, + PointLights, RasterizationSettings, BlendParams, + MeshRenderer, MeshRasterizer, SoftPhongShader, + SoftSilhouetteShader, TexturesVertex) +from pytorch3d.io import load_objs_as_meshes + + +def crop_object_with_mask(image_path, mask_path): + # 读取原图和mask图片 + image = cv2.imread(image_path) + mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE) + + if image is None or mask is None: + raise ValueError("Error loading images. Please check the paths.") + + # 确保mask的尺寸与原图一致 + if image.shape[:2] != mask.shape: + raise ValueError("Image and mask must have the same dimensions.") + + # 找到轮廓 + contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + + if not contours: + raise ValueError("No contours found in the mask.") + + # 获取最大的轮廓(假设物体是最大的区域) + largest_contour = max(contours, key=cv2.contourArea) + + # 创建一个与原图大小相同的空白掩码 + result_mask = np.zeros_like(mask) + + # 在空白掩码上绘制找到的轮廓 + cv2.drawContours(result_mask, [largest_contour], -1, (255), thickness=cv2.FILLED) + + # 使用掩码从原图中提取物体 + cropped_image = cv2.bitwise_and(image, image, mask=result_mask) + + # 计算最大轮廓的边界框 + x, y, w, h = cv2.boundingRect(largest_contour) + + # 根据边界框裁剪提取出的物体 + cropped_object = cropped_image[y:y+h, x:x+w] + + return cropped_object + + +def calculate_bbox_from_mask(binary_mask): + """ + 从二值化掩码中计算边界框 + :param binary_mask: 二维numpy数组,表示二值化掩码 + :return: 边界框 (xmin, ymin, width, height) + """ + coords = np.argwhere(binary_mask) + xmin, ymin = coords.min(axis=0) + xmax, ymax = coords.max(axis=0) + + return [xmin, ymin, xmax, ymax] + +def select_point(pcd, match_points_on_raw, img_size): + points = np.asarray(pcd.points) + projection = points / points[:, 2:3] + projection = projection[:, :2] + # plt.plot(projection[:, 0], projection[:, 1], 'o') + # plt.show() + + # bounding box of projection + min_x, max_x = np.min(projection[:, 0]), np.max(projection[:, 0]) + min_y, max_y = np.min(projection[:, 1]), np.max(projection[:, 1]) + + # project to image + projection[:, 0] = (projection[:, 0] - min_x) / (max_x - min_x) * img_size[1] + projection[:, 1] = (projection[:, 1] - min_y) / (max_y - min_y) * img_size[0] + + # select points closest to match points + closest_points = [] + for raw_point in match_points_on_raw: + distances = np.linalg.norm(projection - raw_point, axis=1) + closest_index = np.argmin(distances) + closest_points.append(points[closest_index]) + + # show the selected points in 3D + selected = o3d.geometry.PointCloud() + selected.points = o3d.utility.Vector3dVector(closest_points) + # o3d.visualization.draw_geometries([pcd, selected]) + return closest_points + +def sample_camera_poses(radius, num_samples, num_up_samples=4, device='cpu'): + ''' + Generate camera poses around a sphere with a given radius. + camera_poses: A list of 4x4 transformation matrices representing the camera poses. + camera_view_coord = word_coord @ camera_pose + ''' + camera_poses = [] + phi = np.linspace(0, np.pi, num_samples) # Elevation angle + phi = phi[1:-1] # Exclude poles + theta = np.linspace(0, 2 * np.pi, num_samples) # Azimuthal angle + + # Generate different up vectors + up_vectors = [np.array([0, 0, 1])] # z-axis is up + for i in range(1, num_up_samples): + angle = (i / num_up_samples) * np.pi * 2 + up = np.array([np.sin(angle), 0, np.cos(angle)]) # Rotate around y-axis + up_vectors.append(up) + + for p in phi: + for t in theta: + for up in up_vectors: + x = radius * np.sin(p) * np.cos(t) + y = radius * np.sin(p) * np.sin(t) + z = radius * np.cos(p) + position = np.array([x, y, z])[None, :] + lookat = np.array([0, 0, 0])[None, :] + up = up[None, :] + # import pdb + # pdb.set_trace() + R, T = look_at_view_transform(radius, t, p, False, position, lookat, up, device="cuda:0") + camera_pose = np.eye(4) + camera_pose[:3, :3] = R.detach().cpu().numpy() + camera_pose[3, :3] = T.detach().cpu().numpy() + camera_poses.append(camera_pose) + + # # Attention! Negative! Not normal forward! + # forward = -(lookat - position) / np.linalg.norm(lookat - position) + # right = np.cross(up, forward) + # if np.linalg.norm(right) < 1e-6: # Check for collinearity + # right = np.array([1, 0, 0]) + # right = right / np.linalg.norm(right) + # up = np.cross(forward, right) + + # camera_pose = np.eye(4) + # camera_pose[:3, 0] = right + # camera_pose[:3, 1] = up + # camera_pose[:3, 2] = forward + # camera_pose[:3, 3] = position + # print('old', camera_pose[:3, :3], position) + # print('total poses', len(camera_poses)) + return torch.tensor(np.array(camera_poses), device=device) + +def render_image(mesh, camera_poses, width=640, height=480, fov=1, device='cpu'): + camera_poses = torch.tensor(camera_poses, device=device) + if len(camera_poses.shape) == 2: + camera_poses = camera_poses[None, :] + # Render and save images from different camera poses + prev_device_type = torch.tensor(0.0).device.type + prev_dtype = torch.get_default_dtype() + try: + # ensure pytorch3d builds intermediate tensors on CPU even if default tensor type was set to CUDA + torch.set_default_tensor_type(torch.FloatTensor) + mesh = load_objs_as_meshes([mesh]) + finally: + torch.set_default_dtype(prev_dtype) + if prev_device_type == 'cuda': + torch.set_default_tensor_type(torch.cuda.FloatTensor) + else: + torch.set_default_tensor_type(torch.FloatTensor) + mesh = mesh.to(device) + # PyTorch3D will create a Meshes without textures when OBJ has no MTL/texture. + # SoftPhongShader requires textures for sampling; fallback to a constant vertex color. + if mesh.textures is None: + verts_rgb = torch.ones_like(mesh.verts_padded(), device=device) + mesh.textures = TexturesVertex(verts_features=verts_rgb) + R = camera_poses[:, :3, :3] + T = camera_poses[:, 3, :3] + num_poses = camera_poses.shape[0] + cameras = PerspectiveCameras(R=R, T=T, device=device, + focal_length=torch.ones(num_poses, 1) * 0.5 * width / np.tan(fov / 2), # Calculate focal length from FOV in radians + principal_point=torch.tensor((width/2, height/2)).repeat(num_poses).reshape(-1, 2), #different order from image_size!! + image_size=torch.tensor((height, width)).repeat(num_poses).reshape(-1, 2), + in_ndc=False) + # print(cameras.get_world_to_view_transform().get_matrix()) # T is matrix[3, :3] + light_location = torch.linalg.inv(camera_poses)[:, 3, :3] + lights = PointLights(location=light_location, device=device) + raster_settings = RasterizationSettings( + image_size=(height, width), + blur_radius=0.0, + faces_per_pixel=1, + bin_size=0, + ) + renderer = MeshRenderer( + rasterizer=MeshRasterizer( + cameras=cameras, + raster_settings=raster_settings, + ), + shader=SoftPhongShader( + device=device, + blend_params=BlendParams(background_color=(0,0,0)), + cameras=cameras, + lights=lights + ) + ) + fragments = renderer.rasterizer(mesh.extend(num_poses)) + depth = fragments.zbuf.squeeze().cpu().numpy() + rendered_images = renderer(mesh.extend(num_poses)) + color = (rendered_images[..., :3].cpu().numpy() * 255).astype(np.uint8) + # if num_poses>1: + # for i in range(num_poses): + # plt.imsave(f'locate/render_result/rendered_image_{i}.png', color[i]) + # plt.imsave(f'locate/render_result/depth_image_{i}.png', depth[i]) + return color, depth + +def render_multi_images(mesh, width=640, height=480, fov=1, radius=3.0, num_samples=6, num_ups=2, sample_flag = 0, input_pose = np.eye(4), device='cpu'): + # Sample camera poses + camera_poses = sample_camera_poses(radius, num_samples, num_ups, device) + + # Calculate intrinsics + # aspect_ratio = width / height # modified + fx = 0.5 * width / np.tan(fov / 2) + fy = fx # * aspect_ratio + cx, cy = width / 2, height / 2 + camera_intrinsics = np.array([ + [fx, 0, cx], + [0, fy, cy], + [0, 0, 1] + ]) + + color, depth = render_image(mesh, camera_poses, width, height, fov, device) + return color, depth, camera_poses, camera_intrinsics + +def project_2d_to_3d(image_points, depth, camera_intrinsics, camera_pose): + """ + Project 2D image points to 3D space using the depth map, camera intrinsics, and pose. + + :param image_points: Nx2 array of image points + :param depth: Depth map + :param camera_intrinsics: Camera intrinsic matrix + :param camera_pose: 4x4 camera pose matrix + :return: Nx3 array of 3D points in world coordinates + """ + fx, fy = camera_intrinsics[0, 0], camera_intrinsics[1, 1] + cx, cy = camera_intrinsics[0, 2], camera_intrinsics[1, 2] + # Convert image points to normalized device coordinates (NDC) + ndc_points = np.zeros((image_points.shape[0], 3)) + for i, (u, v) in enumerate(image_points): + z = depth[int(v), int(u)] + x = - (u - cx) * z / fx + y = - (v - cy) * z / fy + ndc_points[i] = [x, y, z] + valid_mask = ndc_points[:, 2] > 0 + ndc_points = ndc_points[valid_mask] + # ndc_points = np.vstack((ndc_points, np.zeros(3), [[0, 0, 0]])) # modified + # Convert from camera coordinates to world coordinates + ndc_points_homogeneous = np.hstack((ndc_points, np.ones((ndc_points.shape[0], 1)))) + world_points_homogeneous = ndc_points_homogeneous @ np.linalg.inv(camera_pose) + return world_points_homogeneous[:, :3], valid_mask + +def plot_mesh_with_points(mesh, points, filename): + fig = plt.figure() + ax = fig.add_subplot(111, projection='3d') + ax.plot_trisurf(mesh.vertices[:, 0], mesh.vertices[:, 1], mesh.vertices[:, 2], + triangles=mesh.faces, alpha=0.5, edgecolor='none', color='lightgrey') + ax.scatter(points[:, 0], points[:, 1], points[:, 2], color='red', s=10) + # ax.scatter([2.853], [0], [0.927], color='green', s=100) + ax.set_xlabel('X') + ax.set_ylabel('Y') + ax.set_zlabel('Z') + ax.set_aspect('equal') + ax.set_title('3D Mesh with Projected Points') + # for i in range(10): + # angle = 360 / 5 * i + # ax.view_init(elev=10., azim=angle) + # plt.savefig(filename.split('.')[0] + f'_{i}.png') + plt.savefig(filename) + plt.clf() + # new_mesh = mesh.copy() + # new_vertices = np.vstack((new_mesh.vertices, points)) + # new_faces = new_mesh.faces.copy() + # new_mesh = trimesh.Trimesh(vertices=new_vertices, faces=new_faces, process=False) + # new_mesh.export(filename.split('.')[0] + '.ply', file_type='ply') + +def plot_image_with_points(image, points, save_dir): + plt.imshow(image) + plt.scatter(points[:, 0], points[:, 1], color='red', s=5) + plt.xlabel('X') + plt.ylabel('Y') + plt.title('Points on Original Image') + plt.savefig(save_dir) + plt.clf() + +def fit_plane(pcd, filter_z=1, distance_threshold=0.002): + points = np.asarray(pcd.points) + # 原逻辑:过滤远距离点 + mask = points[:, 2] <= filter_z + pcd_filtered = pcd.select_by_index(np.where(mask)[0]) + + def _segment_or_raise(cloud): + return cloud.segment_plane( + distance_threshold=distance_threshold, + ransac_n=3, + num_iterations=1000, + ) + + if len(pcd_filtered.points) >= 3: + plane_model, inliers = _segment_or_raise(pcd_filtered) + else: + # 回退逻辑:针对 DA3 等深度整体 > filter_z 的情况,放弃过滤直接用全量点 + if points.shape[0] >= 3 and points[:, 2].max() > filter_z: + # 先尝试自适应阈值(用深度分布的 p90,避免直接全量带入远处背景) + p90 = np.percentile(points[:, 2], 90) + adaptive_z = min(max(p90, filter_z), 10.0) # 上限 10m,避免过远 + mask_adapt = points[:, 2] <= adaptive_z + pcd_adapt = pcd.select_by_index(np.where(mask_adapt)[0]) + if len(pcd_adapt.points) >= 3: + plane_model, inliers = _segment_or_raise(pcd_adapt) + elif len(pcd.points) >= 3: + plane_model, inliers = _segment_or_raise(pcd) + else: + return None, None + else: + # 点仍不足,返回占位并让上游自行处理 + return None, None + points = np.asarray(pcd.points) + projection = points / points[:, 2:3] + projection = projection[:, :2] + # plt.plot(projection[:, 0], projection[:, 1], 'o') + # plt.show() + + # bounding box of projection + min_x, max_x = np.min(projection[:, 0]), np.max(projection[:, 0]) + min_y, max_y = np.min(projection[:, 1]), np.max(projection[:, 1]) + field_of_view = np.array([min_x, min_y, max_x, max_y]) + return plane_model, field_of_view + +def estimate_pose(mesh_file, pcd_file, ref_img, raw_img, mask_box, out_dir, num_samples=8, num_ups=1, sample_flag = 0, input_pose = np.eye(4), mask_file=None): + # load + device = 'cuda:0' if torch.cuda.is_available() else 'cpu' + mesh = trimesh.load(mesh_file) + ref_img = cv2.imread(ref_img, cv2.IMREAD_GRAYSCALE) + raw_img = cv2.imread(raw_img) + raw_img = cv2.cvtColor(raw_img, cv2.COLOR_BGR2RGB) + # pcd = o3d.io.read_point_cloud(pcd_file) + pcd = pcd_file #gengzheng : correct + plane_model, field_of_view = fit_plane(pcd, 1, 0.002) + fov = np.arctan((field_of_view[2] - field_of_view[0]) / 2) * 2 + + # Calculate suitable radius + bounding_box = mesh.bounds + center = (bounding_box[0] + bounding_box[1]) / 2 + max_dimension = np.linalg.norm(bounding_box[1] - bounding_box[0]) + fov_radians = fov / 2 + radius = (max_dimension / 2) / np.tan(fov_radians) + radius = 2 * radius + print('rendering radius', radius) + + # Render multimle images and feature matching + print('rendering objects...') + colors, depths, camera_poses, camera_intrinsics = render_multi_images(mesh_file, + raw_img.shape[1], + raw_img.shape[0], fov, radius=radius, + num_samples=num_samples, num_ups=num_ups, device=device, sample_flag=sample_flag, input_pose=input_pose) + grays = [cv2.cvtColor(color, cv2.COLOR_BGR2GRAY) for color in colors] + print('matching features...') + best_pose, match_result = image_pair_matching(grays, ref_img, out_dir, + resize=[-1], viz=False, save=False, keypoint_threshold=0.001, match_threshold=0.01) + chosen_pose = camera_poses[best_pose].cpu().numpy() + # print('best_pose', np.array2string(chosen_pose, separator=', ')) + # print('matched point number', np.sum(match_result['matches']>-1)) + plt.imsave(os.path.join(out_dir, 'initial_pose.png'), colors[0]) + plt.imsave(os.path.join(out_dir, 'best_pose_rendering.png'), colors[best_pose]) + # chosen_pose[:, 1:3] = -chosen_pose[:, 1:3] # Change due to pyrender's special coordinates + + # Matched points on mesh + image_points = match_result['keypoints0'][match_result['matches']>-1] + world_points, valid_mask = project_2d_to_3d(image_points, depths[best_pose], + camera_intrinsics, chosen_pose) + image_points = image_points[valid_mask] + plot_mesh_with_points(mesh, world_points, os.path.join(out_dir, 'points_on_3D.png')) + plot_image_with_points(depths[best_pose], image_points, os.path.join(out_dir, 'points_on_2D.png')) + + # Matched points on original picture + match_points_on_mask = match_result['keypoints1'][match_result['matches'][match_result['matches']>-1]] + match_points_on_mask = match_points_on_mask[valid_mask] + sclae_x = (mask_box[3]-mask_box[1]) / ref_img.shape[1] + sclae_y = (mask_box[2]-mask_box[0]) / ref_img.shape[0] + match_points_on_raw = match_points_on_mask * np.array([sclae_x, sclae_y]) + np.array([mask_box[1], mask_box[0]]) + plot_image_with_points(raw_img, match_points_on_raw, os.path.join(out_dir, 'points_original.png')) + + success, rvec, tvec, _ = cv2.solvePnPRansac( + np.float32(world_points), + np.float32(match_points_on_raw), + np.float32(camera_intrinsics), + distCoeffs=np.zeros(4, dtype=np.float32), + iterationsCount=100, # 最大迭代次数 + reprojectionError=8.0, # 投影误差阈值 + confidence=0.99, # 置信度 + flags=cv2.SOLVEPNP_ITERATIVE # 可替换为 SOLVEPNP_EPNP 等 + ) + # assert success + rotation_matrix, _ = cv2.Rodrigues(rvec) + world_2_cam = np.eye(4, dtype=np.float32) + world_2_cam[:3, :3] = rotation_matrix + world_2_cam[:3, 3] = tvec.squeeze() + # print('Optimized pose', world_2_cam) + + world_2_cam_render = np.eye(4, dtype=np.float32) + world_2_cam_render[:3, :3] = np.linalg.inv(rotation_matrix) + world_2_cam_render[3, :3] = tvec.squeeze() # change due to pytorch3D setting + world_2_cam_render[:, :2] = -world_2_cam_render[:, :2] # change due to pytorch3D setting + # print('Optimized pose for rendering', np.array2string(world_2_cam_render, separator=', ')) + color, _ = render_image(mesh_file, world_2_cam_render, raw_img.shape[1], raw_img.shape[0], fov, device) + plt.imsave(os.path.join(out_dir, 'optimized_rendering.png'), color[0]) + + # rescaled mesh points + # mesh points in camera space + mesh_points = np.hstack((world_points, np.ones((world_points.shape[0], 1)))) @ (world_2_cam).T + mesh_points = mesh_points[:, :3] + pcd_points = select_point(pcd, match_points_on_raw, raw_img.shape) + + def objective(scale, mesh_points, pcd_points, plane_model): + scale_val = float(scale) + transformed_points = scale_val * mesh_points + l3d = np.sum(np.sum((transformed_points - pcd_points) ** 2, axis=1)) + return l3d + + initial_scale = 0.25 + result = minimize(objective, initial_scale, args=(mesh_points, pcd_points, plane_model), method='L-BFGS-B') + optimal_scale = result.x[0] + # print('Rescale:', optimal_scale) + + # combine pose and transformation + S = np.array([[optimal_scale, 0, 0, 0], + [0, optimal_scale, 0, 0], + [0, 0, optimal_scale, 0], + [0, 0, 0, 1]]) + M = np.dot(S, world_2_cam) + # print('final matrix') + # print(np.array2string(M, separator=', ')) + # print('plane model') + # print(np.array2string(plane_model, separator=', ')) + # print('field of view') + # print(np.array2string(field_of_view, separator=', ')) + return optimal_scale, M, plane_model, field_of_view + +def get_intrinsic(intrinsic_file): + if intrinsic_file.endswith('.json'): + with open(intrinsic_file, 'r') as file: + intrinsic_data = json.load(file) + + if len(intrinsic_data) != 7: + intrinsic_data = intrinsic_data['0'] + intrinsic_numpy = np.array(intrinsic_data['cam_K']).reshape(3,3) + intrinsic_tensor = o3d.core.Tensor(intrinsic_numpy) + else: + cx = intrinsic_data['cx'] + cy = intrinsic_data['cy'] + fx = intrinsic_data['fx'] + fy = intrinsic_data['fy'] + + intrinsic_tensor = o3d.core.Tensor([ + [fx, 0, cx], + [0, fy, cy], + [0, 0, 1] + ]) + + intrinsic_numpy = np.array([ + [fx, 0, cx], + [0, fy, cy], + [0, 0, 1] + ]) + else: + intrinsic_numpy = np.loadtxt(intrinsic_file) + intrinsic_tensor = o3d.core.Tensor(intrinsic_numpy) + + return intrinsic_tensor, intrinsic_numpy + +def rgbd_to_pointcloud(rgb_file, depth_file, intrinsic, out_dir): + color_image = o3d.t.io.read_image(rgb_file) + depth_image = o3d.t.io.read_image(depth_file) # 读取深度图 + + rgbd = o3d.t.geometry.RGBDImage(color_image, depth_image) + + pcd = o3d.t.geometry.PointCloud.create_from_rgbd_image(rgbd, + intrinsics=intrinsic, + depth_scale=1000, + depth_max=10.0) + + # 保存点云文件 + pcd_legacy = pcd.to_legacy() + pcd_path = os.path.join(out_dir, 'pointcloud.ply') + o3d.io.write_point_cloud(pcd_path, pcd_legacy) + + return pcd + +def get_scale(mesh, depth_file, raw_img, mask_file, out_dir, intrinsic_file, sample_flag=0, input_pose=np.eye(4)): + intrinsic_tensor, intrinsic_numpy = get_intrinsic(intrinsic_file) + + pcd = rgbd_to_pointcloud(raw_img, depth_file, intrinsic_tensor, out_dir) + pcd_file = pcd.to_legacy() + + mask_image = Image.open(mask_file).convert('L') # 转换为灰度图 + binary_mask = np.array(mask_image) > 0 # 将非零像素视为前景 + + mask_box = calculate_bbox_from_mask(binary_mask) + # print(mask_box) + + ref_img = os.path.join(out_dir, 'ref_img.png') + ref = crop_object_with_mask(raw_img, mask_file) + cv2.imwrite(ref_img, ref) + + optimal_scale, M, plane_model, field_of_view = estimate_pose( + mesh, + pcd_file, + ref_img, + raw_img, + mask_box, + out_dir, + sample_flag=sample_flag, + input_pose=input_pose, + mask_file=mask_file, + ) + return M, intrinsic_numpy, optimal_scale + +if __name__ == "__main__": + mesh_file = "/baai-cwm-1/baai_cwm_ml/cwm/yuhao.duan/gz/TRELLIS/output/custom_datasets/gun/original_model/output.obj" + depth_file = "/baai-cwm-1/baai_cwm_ml/cwm/yuhao.duan/gz/blenderproc_geng/output/custom_datasets/scene_easy_small/gun/bop_with_true_imgs/lm/train_pbr/000000/depth/000308.png" + raw_img = "/baai-cwm-1/baai_cwm_ml/cwm/yuhao.duan/datasets/scene/HO3Dv3/evaluation/AP13/rgb/0000.jpg" + ref_img = "results/scale/ref_img.png" + mask_file = "/baai-cwm-1/baai_cwm_ml/cwm/yuhao.duan/datasets/scene/HO3Dv3/evaluation/AP13/masks/0000.png" + out_dir = "results/scale" + intrinsic_file = "/baai-cwm-1/baai_cwm_ml/cwm/yuhao.duan/gz/blenderproc_geng/output/custom_datasets/scene_easy_small/gun/bop_with_true_imgs/lm/train_pbr/000000/scene_camera.json" + + os.makedirs(out_dir, exist_ok=True) + + M = get_scale(mesh_file, depth_file, raw_img, ref_img, mask_file, out_dir, intrinsic_file) + + # Save the final matrix M to a text file + M_output_path = os.path.join(out_dir, "final_matrix.txt") + np.savetxt(M_output_path, M, fmt="%.6f") + print(f"Final matrix M saved to {M_output_path}") + diff --git a/OVOW/engine/oneposeviagen/locate/match_pairs.py b/OVOW/engine/oneposeviagen/locate/match_pairs.py new file mode 100644 index 0000000000000000000000000000000000000000..fdea034c47e10e04dcbed25f8e2596e65287f20b --- /dev/null +++ b/OVOW/engine/oneposeviagen/locate/match_pairs.py @@ -0,0 +1,197 @@ +#! /usr/bin/env python3 +# 渲染视图 <-> 参考图 的特征匹配(scale 恢复 / PnP 关键帧矫正用)。 +# +# 匹配器为 RoMaV2(稠密匹配,MIT 许可,third_party/RoMaV2)。 +# 历史上曾支持 OPG_MATCHER=superglue(Magic Leap SuperGlue/SuperPoint), +# 但其许可禁止再分发,已从本仓库移除;如需自行对比,请从上游 +# https://github.com/magicleap/SuperGluePretrainedNetwork 获取并遵守其许可。 +# +# 两种运行模式: +# - 子进程(默认关闭 inproc 时):romav2 跑在独立 conda env(torch 2.8), +# 通过一次性子进程批量匹配(tools/romav2_match_worker.py)。 +# - 进程内(OPG_ROMAV2_INPROC=1,发布默认):RoMaV2 在 opg 的 +# torch2.4/numpy1.x/py3.11 上直接运行(仅需 nn.Buffer shim), +# 常驻 = 加载一次、跨物体复用,省掉每次调用的子进程冷启动(~35s/次)。 + +from pathlib import Path +import os +import sys + +import numpy as np +import torch + +ROMAV2_PYTHON_DEFAULT = "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python" +ROMAV2_WORKER = str(Path(__file__).resolve().parents[2] / "tools" / "romav2_match_worker.py") +ROMAV2_SRC_DEFAULT = "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/third_party/RoMaV2/src" +_ROMAV2_INPROC = {} # 缓存已加载的模型 + + +def _install_nn_buffer_shim(): + """RoMaV2 用了 torch>=2.6 的 nn.Buffer;在 torch2.4 上补一个等价实现。""" + import torch.nn as nn + if hasattr(nn, "Buffer"): + return + + class Buffer(torch.Tensor): + def __new__(cls, data=None, *, persistent=True): + if data is None: + data = torch.empty(0) + t = torch.Tensor._make_subclass(cls, data, data.requires_grad) + t._persistent = persistent + return t + + nn.Buffer = Buffer + _orig_setattr = nn.Module.__setattr__ + + def _setattr(self, name, value): + # nn.Buffer 在 torch>=2.6 由 Module.__setattr__ 自动注册为 buffer;这里手动补上 + if isinstance(value, Buffer): + self.register_buffer(name, torch.as_tensor(value), + persistent=getattr(value, "_persistent", True)) + return + _orig_setattr(self, name, value) + + nn.Module.__setattr__ = _setattr + + +def _ensure_romav2_inproc(): + if "model" not in _ROMAV2_INPROC: + src = os.environ.get("ROMAV2_SRC", ROMAV2_SRC_DEFAULT) + if src not in sys.path: + sys.path.insert(0, src) + _install_nn_buffer_shim() + from romav2 import RoMaV2 # noqa: WPS433 + model = RoMaV2() + model.apply_setting(os.environ.get("ROMAV2_SETTING", "precise")) + _ROMAV2_INPROC["model"] = model + print("[romav2] in-process model loaded (resident, torch " + f"{torch.__version__})") + return _ROMAV2_INPROC["model"] + + +def _to_gray_array(image): + import cv2 + if isinstance(image, (str, Path)): + arr = cv2.imread(str(image), cv2.IMREAD_GRAYSCALE) + if arr is None: + raise IOError(f"cannot read image: {image}") + return arr + arr = np.asarray(image) + if arr.ndim == 3: + arr = cv2.cvtColor(arr, cv2.COLOR_BGR2GRAY) + if arr.dtype != np.uint8: + arr = np.clip(arr, 0, 255).astype(np.uint8) + return arr + + +def _romav2_match_inproc(input_images, ref_image, output_dir, save=True): + """与 _image_pair_matching_romav2 同契约,但在本进程内匹配(不起子进程)。""" + output_dir = Path(output_dir) + output_dir.mkdir(exist_ok=True, parents=True) + num_matches = int(os.environ.get("ROMAV2_NUM_MATCHES", "2000")) + cert_th = float(os.environ.get("ROMAV2_CERT_TH", "0.3")) + + model = _ensure_romav2_inproc() + + def _to_rgb(a): + return np.ascontiguousarray(np.stack([a] * 3, axis=-1) if a.ndim == 2 else a) + + ref_rgb = _to_rgb(_to_gray_array(ref_image)) + H_B, W_B = ref_rgb.shape[:2] + counts, per_view = [], [] + for im in input_images: + render_rgb = _to_rgb(_to_gray_array(im)) + H_A, W_A = render_rgb.shape[:2] + try: + with torch.no_grad(): + preds = model.match(render_rgb, ref_rgb) + matches, conf, _, _ = model.sample(preds, num_matches) + ka, kb = model.to_pixel_coordinates(matches, H_A, W_A, H_B, W_B) + keep = conf > cert_th + ka = ka[keep].cpu().numpy().astype(np.float32) + kb = kb[keep].cpu().numpy().astype(np.float32) + cf = conf[keep].cpu().numpy().astype(np.float32) + except Exception as exc: # noqa: BLE001 + print(f"[romav2-inproc] view failed: {exc}") + ka = np.zeros((0, 2), np.float32) + kb = np.zeros((0, 2), np.float32) + cf = np.zeros((0,), np.float32) + per_view.append((ka, kb, cf)) + counts.append(len(ka)) + + best_pose = int(np.argmax(counts)) if counts else 0 + mk0, mk1, conf = per_view[best_pose] + print(f"[romav2] (in-proc) per-view confident matches: {counts} -> best view {best_pose}") + match_result = { + "keypoints0": mk0.astype(np.float32), + "keypoints1": mk1.astype(np.float32), + "matches": np.arange(len(mk0), dtype=np.int64), + "match_confidence": conf.astype(np.float32), + } + if save: + np.savez(str(output_dir / f"matches_romav2_{best_pose}.npz"), **match_result) + return best_pose, match_result + + +def _image_pair_matching_romav2(input_images, ref_image, output_dir, save=True): + # OPG_ROMAV2_INPROC=1:进程内常驻匹配(加载一次,跨物体复用),省子进程冷启动。 + if os.environ.get("OPG_ROMAV2_INPROC", "0") == "1": + return _romav2_match_inproc(input_images, ref_image, output_dir, save=save) + import subprocess + output_dir = Path(output_dir) + output_dir.mkdir(exist_ok=True, parents=True) + + renders = np.stack([_to_gray_array(im) for im in input_images]) + ref = _to_gray_array(ref_image) + + in_npz = output_dir / "romav2_worker_input.npz" + out_npz = output_dir / "romav2_worker_output.npz" + np.savez(str(in_npz), renders=renders, ref=ref) + + py = os.environ.get("ROMAV2_PYTHON", ROMAV2_PYTHON_DEFAULT) + cmd = [py, ROMAV2_WORKER, "--input", str(in_npz), "--output", str(out_npz), + "--num-matches", os.environ.get("ROMAV2_NUM_MATCHES", "2000"), + "--cert-th", os.environ.get("ROMAV2_CERT_TH", "0.3")] + print(f"[romav2] launching worker for {len(input_images)} views ...") + subprocess.run(cmd, check=True, timeout=1800) + + res = np.load(str(out_npz)) + counts = res["counts"] + best_pose = int(np.argmax(counts)) + mk0 = res[f"mkpts0_{best_pose}"] + mk1 = res[f"mkpts1_{best_pose}"] + conf = res[f"conf_{best_pose}"] + print(f"[romav2] per-view confident matches: {counts.tolist()} -> best view {best_pose}") + + # matches 为 1:1 的索引映射(与下游 kpts1[matches[valid]] 的取法兼容) + match_result = { + "keypoints0": mk0.astype(np.float32), + "keypoints1": mk1.astype(np.float32), + "matches": np.arange(len(mk0), dtype=np.int64), + "match_confidence": conf.astype(np.float32), + } + if save: + np.savez(str(output_dir / f"matches_romav2_{best_pose}.npz"), **match_result) + return best_pose, match_result + + +@torch.no_grad() +def image_pair_matching(input_images, ref_image, output_dir, save=True, + matcher=None, **_legacy_kwargs): + """渲染候选视图 vs 参考图匹配,返回 (best_view_idx, match_result)。 + + match_result: keypoints0/keypoints1/matches/match_confidence, + 其中 matches 为 keypoints0 -> keypoints1 的索引(-1 表示无匹配)。 + **_legacy_kwargs 吸收旧 SuperGlue 时代的调参参数(resize/viz/ + keypoint_threshold/match_threshold 等),对 RoMaV2 无效,静默忽略。 + """ + matcher = (matcher or os.environ.get("OPG_MATCHER", "romav2")).lower() + if matcher != "romav2": + raise RuntimeError( + f"OPG_MATCHER={matcher!r} is not available in this release. " + "SuperGlue/SuperPoint (Magic Leap) are not redistributable and were " + "removed; only 'romav2' is bundled. To experiment with SuperGlue, " + "obtain it from https://github.com/magicleap/SuperGluePretrainedNetwork " + "under its own license and wire it in locally." + ) + return _image_pair_matching_romav2(input_images, ref_image, output_dir, save=save) diff --git a/OVOW/engine/oneposeviagen/scripts/download_weights.py b/OVOW/engine/oneposeviagen/scripts/download_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..06961bbf33133bca3d723a5c40f54d0524dcb0ad --- /dev/null +++ b/OVOW/engine/oneposeviagen/scripts/download_weights.py @@ -0,0 +1,33 @@ +from huggingface_hub import snapshot_download +import urllib.request +import os + +def download_model_from_hf(repo_id, out_dir): + print(f"✅ Download {repo_id} to {out_dir}") + snapshot_download( + repo_id=repo_id, + repo_type="model", + local_dir=out_dir, + local_dir_use_symlinks=False, + endpoint="https://hf-mirror.com/" + ) + +def download_file_from_google(url, filename): + """Download a file from a given URL and save it as filename.""" + print(f"Downloading {filename}...") + try: + urllib.request.urlretrieve(url, filename) + print(f"Saved to {filename}") + except Exception as e: + raise RuntimeError(f"Failed to download checkpoint from {url}") from e + +# 模型仓库ID +repo_id_OnePoseViaGen = "ZhengGeng/OnePoseViaGen" + +# output_dir +hf_model_dict = { + repo_id_OnePoseViaGen : "checkpoints/OnePoseViaGen" +} + +for key,value in hf_model_dict.items(): + download_model_from_hf(key, value) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/scripts/estimate_depth_and_intrinsic.py b/OVOW/engine/oneposeviagen/scripts/estimate_depth_and_intrinsic.py new file mode 100644 index 0000000000000000000000000000000000000000..f9be12159c20609584dd9fe16bcdd8c174fafcc5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/scripts/estimate_depth_and_intrinsic.py @@ -0,0 +1,209 @@ +from models.SpaTrackV2.models.predictor import Predictor +import numpy as np +import cv2 +import torch +import torchvision.transforms as T +from PIL import Image +from models.SpaTrackV2.models.utils import get_points_on_a_grid +from rich import print +from torchvision import transforms as TF +import decord +from models.SpaTrackV2.models.vggt4track.models.vggt_moe import VGGT4Track +from models.SpaTrackV2.models.vggt4track.utils.load_fn import preprocess_image + +def load_and_preprocess_numpy_img(depth_path, mode="crop", test_mode=False): + # Validate mode + if mode not in ["crop", "pad"]: + raise ValueError("Mode must be either 'crop' or 'pad'") + + images = [] + shapes = set() + to_tensor = TF.ToTensor() + target_size = 518 + + # First process all images and collect their shapes + # Open image + img = Image.open(depth_path) + + if img.mode == "RGBA": + # Create white background + background = Image.new("RGBA", img.size, (255, 255, 255, 255)) + # Alpha composite onto the white background + img = Image.alpha_composite(background, img) + + # Now convert to "RGB" (this step assigns white for transparent areas) + img = img.convert("RGB") + + width, height = img.size + + if mode == "pad": + # Make the largest dimension 518px while maintaining aspect ratio + if width >= height: + new_width = target_size + new_height = round(height * (new_width / width) / 14) * 14 # Make divisible by 14 + else: + new_height = target_size + new_width = round(width * (new_height / height) / 14) * 14 # Make divisible by 14 + else: # mode == "crop" + # Original behavior: set width to 518px + new_width = target_size + # Calculate height maintaining aspect ratio, divisible by 14 + new_height = round(height * (new_width / width) / 14) * 14 + + # Resize with new dimensions (width, height) + img = img.resize((new_width, new_height), Image.Resampling.BICUBIC) + if test_mode: + img.save(f"output/test/middle_images/resized_depth_image.png") + img = to_tensor(img) # Convert to tensor (0, 1) + + # Center crop height if it's larger than 518 (only in crop mode) + if mode == "crop" and new_height > target_size: + start_y = (new_height - target_size) // 2 + img = img[:, start_y : start_y + target_size, :] + + # For pad mode, pad to make a square of target_size x target_size + if mode == "pad": + h_padding = target_size - img.shape[1] + w_padding = target_size - img.shape[2] + + if h_padding > 0 or w_padding > 0: + pad_top = h_padding // 2 + pad_bottom = h_padding - pad_top + pad_left = w_padding // 2 + pad_right = w_padding - pad_left + + # Pad with white (value=1.0) + img = torch.nn.functional.pad( + img, (pad_left, pad_right, pad_top, pad_bottom), mode="constant", value=1.0 + ) + + shapes.add((img.shape[1], img.shape[2])) + images.append(img) + if test_mode: + img_np = img.detach().cpu().numpy() + img_np = (img_np * 255).astype(np.uint8) + + # Step 2: CHW -> HWC 转换 + img_np = np.transpose(img_np, (1, 2, 0)) + + # Step 3: 创建 PIL 图像并保存 + pil_img = Image.fromarray(img_np) + pil_img.save("output/test/middle_images/cropped_depth_image.png") + + # Check if we have different shapes + # In theory our model can also work well with different shapes + if len(shapes) > 1: + print(f"Warning: Found images with different shapes: {shapes}") + # Find maximum dimensions + max_height = max(shape[0] for shape in shapes) + max_width = max(shape[1] for shape in shapes) + + # Pad images if necessary + padded_images = [] + for img in images: + h_padding = max_height - img.shape[1] + w_padding = max_width - img.shape[2] + + if h_padding > 0 or w_padding > 0: + pad_top = h_padding // 2 + pad_bottom = h_padding - pad_top + pad_left = w_padding // 2 + pad_right = w_padding - pad_left + + img = torch.nn.functional.pad( + img, (pad_left, pad_right, pad_top, pad_bottom), mode="constant", value=1.0 + ) + padded_images.append(img) + images = padded_images + + images = torch.stack(images) # concatenate images + + image = images[0].permute(1, 2, 0).cpu().numpy() # CHW -> HWC,并转为 numpy + image = (image * 255).clip(0, 255).astype(np.uint8) # 归一化到 [0, 255] 并转为 uint8 + + return image + +def process_img_to_vggt_format(image_names, output_path): + """ + Load and preprocess an image to the format expected by the VGGT model. + + Args: + image_path (str): Path to the input image file. + + Returns: + torch.Tensor: Preprocessed image tensor. + """ + # Load and preprocess the image + processed_image_names = [] + for i,image_name in enumerate(image_names): + image = load_and_preprocess_numpy_img(image_name) + #convert to PIL Image for saving + image = Image.fromarray(image) + image.save(f'{output_path}/{i:06d}.jpg') + processed_image_names.append(f'{output_path}/{i:06d}.jpg') + return processed_image_names # Add batch dimension + +def initialize_vggt_model(device, vo_points=756): + vggt4track_model = VGGT4Track.from_pretrained("Yuxihenry/SpatialTrackerV2_Front") + vggt4track_model.eval() + vggt4track_model = vggt4track_model.to(device) + + model = Predictor.from_pretrained("Yuxihenry/SpatialTrackerV2-Offline") + model.spatrack.track_num = vo_points + model.eval() + model.to("cuda") + + return vggt4track_model, model + +def estimate_depth_and_intrinsic(vggt4track_model, model, vid_dir, output_path, fps=1, grid_size=10, device='cuda'): + video_reader = decord.VideoReader(vid_dir) + video_tensor = torch.from_numpy(video_reader.get_batch(range(len(video_reader))).asnumpy()).permute(0, 3, 1, 2) # Convert to tensor and permute to (N, C, H, W) + video_tensor = video_tensor[::fps].float() + + # process the image tensor + video_tensor = preprocess_image(video_tensor)[None] + with torch.no_grad(): + with torch.cuda.amp.autocast(dtype=torch.bfloat16): + # Predict attributes including cameras, depth maps, and point maps. + predictions = vggt4track_model(video_tensor.cuda()/255) + extrinsic, intrinsic = predictions["poses_pred"], predictions["intrs"] + depth_map, depth_conf = predictions["points_map"][..., 2], predictions["unc_metric"] + + depth_tensor = depth_map.squeeze().cpu().numpy() + extrs = np.eye(4)[None].repeat(len(depth_tensor), axis=0) + extrs = extrinsic.squeeze().cpu().numpy() + intrs = intrinsic.squeeze().cpu().numpy() + video_tensor = video_tensor.squeeze() + #NOTE: 20% of the depth is not reliable + # threshold = depth_conf.squeeze()[0].view(-1).quantile(0.6).item() + unc_metric = depth_conf.squeeze().cpu().numpy() > 0.5 + + frame_H, frame_W = video_tensor.shape[2:] + grid_pts = get_points_on_a_grid(grid_size, (frame_H, frame_W), device="cpu") + query_xyt = torch.cat([torch.zeros_like(grid_pts[:, :, :1]), grid_pts], dim=2)[0].numpy() + + # Run model inference + with torch.amp.autocast(device_type="cuda", dtype=torch.bfloat16): + ( + c2w_traj, intrs, point_map, conf_depth, + track3d_pred, track2d_pred, vis_pred, conf_pred, video + ) = model.forward(video_tensor, depth=depth_tensor, + intrs=intrs, extrs=extrs, + queries=query_xyt, + fps=1, full_point=False, iters_track=4, + query_no_BA=True, fixed_cam=False, stage=1, unc_metric=unc_metric, + support_frame=len(video_tensor)-1, replace_ratio=0.2) + + intrinsics = intrs.cpu().numpy() + depth_save = point_map[:,2,...] + depth_save[conf_depth<0.5] = 0 + depth_maps = depth_save.cpu().numpy() + + depth_names = [] + for frame_id, depth_map in enumerate(depth_maps): + depth_map_mm = (depth_map * 1000).astype('uint16') + depth_path = f"{output_path}/{frame_id:06d}.png" + cv2.imwrite(depth_path, depth_map_mm) + depth_names.append(depth_path) + + return depth_names, intrinsics \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/scripts/estimate_poses.py b/OVOW/engine/oneposeviagen/scripts/estimate_poses.py new file mode 100644 index 0000000000000000000000000000000000000000..169028f2392f67444ce00cddf64c26f7c65d74f5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/scripts/estimate_poses.py @@ -0,0 +1,298 @@ +from fpose.estimater import * + +import json as _json +from pathlib import Path + +from scipy.spatial.transform import Rotation as _Rot + + +def _load_frame(rgb_path, depth_path, mask_path, mask_inputs): + color = cv2.imread(rgb_path) + depth = cv2.imread(depth_path, -1) / 1e3 + mask = cv2.imread(mask_path, -1) + if len(mask.shape) == 3: + for c in range(3): + if mask[..., c].sum() > 0: + mask = mask[..., c] + break + mask = mask.astype(bool) + if mask_inputs: + # 强约束:只在 mask 内保留 RGB/Depth,避免多实例相似物体时漂移到 mask 外目标 + color = color.copy() + color[~mask] = 0 + depth = depth.copy() + depth[~mask] = 0 + return color, depth, mask + + +def _smooth_pose_list(poses, window=5): + """Sliding-window smoothing on SE(3): mean translation + normalized mean quaternion.""" + n = len(poses) + if n < 3 or window < 3: + return list(poses) + ts = np.stack([p[:3, 3] for p in poses]) + quats = _Rot.from_matrix(np.stack([p[:3, :3] for p in poses])).as_quat() + for i in range(1, n): + if np.dot(quats[i], quats[i - 1]) < 0: + quats[i] = -quats[i] + half = max(1, int(window) // 2) + out = [] + for i in range(n): + lo, hi = max(0, i - half), min(n, i + half + 1) + t = ts[lo:hi].mean(axis=0) + q = quats[lo:hi].mean(axis=0) + norm = np.linalg.norm(q) + if norm < 1e-8: + q = quats[i] + norm = np.linalg.norm(q) + q = q / norm + m = np.eye(4) + m[:3, :3] = _Rot.from_quat(q).as_matrix() + m[:3, 3] = t + out.append(m) + return out + + +def _pose_mask_bbox_iou(pose, verts, K, mask): + """Project mesh verts with pose, compare projected bbox vs mask bbox. Returns (iou, center_err_px).""" + P = (pose[:3, :3] @ verts.T).T + pose[:3, 3] + z = P[:, 2] + if (z <= 1e-6).all(): + return 0.0, 1e9 + uv = (K @ P.T).T + uv = uv[:, :2] / np.clip(uv[:, 2:3], 1e-6, None) + ys, xs = np.where(mask) + if len(xs) == 0: + return 0.0, 1e9 + pb = np.array([uv[:, 0].min(), uv[:, 1].min(), uv[:, 0].max(), uv[:, 1].max()]) + mb = np.array([xs.min(), ys.min(), xs.max(), ys.max()]) + ix1, iy1 = max(pb[0], mb[0]), max(pb[1], mb[1]) + ix2, iy2 = min(pb[2], mb[2]), min(pb[3], mb[3]) + inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1) + a1 = max(0.0, (pb[2] - pb[0]) * (pb[3] - pb[1])) + a2 = max(0.0, (mb[2] - mb[0]) * (mb[3] - mb[1])) + iou = inter / max(a1 + a2 - inter, 1e-6) + pc = uv.mean(0) + mc = np.array([xs.mean(), ys.mean()]) + return float(iou), float(np.linalg.norm(pc - mc)) + + +def estimate_poses( + npz_path, + query_image_names, + query_depth_names, + query_mask_names, + query_intrinsics, + scaled_model_path, + output_dir, + debug=0, + est_refine_iter=5, + mask_inputs: bool = False, + anchor_idx: int = None, + track_refine_iter: int = 3, + smooth_window: int = 0, + reinit_jump_frac: float = 0.5, + quality_gate: bool = True, + quality_iou_th: float = 0.3, + min_mask_pix: int = 50, + pnp_anchor_pose=None, +): + """Estimate per-frame object poses. + + Register once at the anchor frame, then propagate with track_one() + forward and backward. Quality gate: per-frame projected-bbox IoU vs + mask; below-threshold frames are re-registered with mask-gated inputs, + and frames that still fail (or have no mask) are flagged in + pose_quality.json next to poses.json. Optional SE(3) smoothing + (smooth_window>=3) runs on gate-passing frames only. + """ + debug_dir = output_dir + mesh = trimesh.load(scaled_model_path, force='mesh') + + to_origin, extents = trimesh.bounds.oriented_bounds(mesh) + bbox = np.stack([-extents/2, extents/2], axis=0).reshape(2,3) + + scorer = get_cached_scorer() + refiner = get_cached_refiner() + glctx = get_cached_glctx() + est = FoundationPose(model_pts=mesh.vertices, model_normals=mesh.vertex_normals, mesh=mesh, scorer=scorer, refiner=refiner, debug_dir=debug_dir, debug=debug, glctx=glctx) + + num_frames = len(query_image_names) + verts = np.asarray(mesh.vertices) + + mask_areas = [] + for mp in query_mask_names: + m = cv2.imread(mp, -1) + mask_areas.append(int((m > 0).sum()) if m is not None else 0) + + if anchor_idx is None or not (0 <= int(anchor_idx) < num_frames) or mask_areas[int(anchor_idx)] <= 0: + anchor_idx = int(np.argmax(mask_areas)) + anchor_idx = int(anchor_idx) + + jump_th = max(float(reinit_jump_frac) * float(est.diameter), 1e-3) + + poses = [None] * num_frames + quality = [None] * num_frames + + def _gate(i, pose, color, depth, mask, source): + """Evaluate pose; retry with mask-gated register if poor. Returns (pose, record).""" + K = np.array(query_intrinsics[i]) + npix = int(mask.sum()) + if npix < min_mask_pix: + return pose, {"frame": i, "mask_pix": npix, "status": "no_mask", "source": source, + "iou": None, "center_err_px": None} + iou, cerr = _pose_mask_bbox_iou(pose, verts, K, mask) + rec = {"frame": i, "mask_pix": npix, "source": source, "iou": round(iou, 3), + "center_err_px": round(cerr, 1)} + if not quality_gate or iou >= quality_iou_th: + rec["status"] = "ok" + return pose, rec + # 质量门不过:用 mask 门控输入重新 register + pl_backup = est.pose_last.clone() if torch.is_tensor(est.pose_last) else est.pose_last + c2 = color.copy(); c2[~mask] = 0 + d2 = depth.copy(); d2[~mask] = 0 + pose2 = np.asarray( + est.register(K=K, rgb=c2, depth=d2, ob_mask=mask, iteration=est_refine_iter) + ).reshape(4, 4) + iou2, cerr2 = _pose_mask_bbox_iou(pose2, verts, K, mask) + rec["iou_reregister"] = round(iou2, 3) + rec["center_err_px_reregister"] = round(cerr2, 1) + if iou2 >= max(iou, quality_iou_th * 0.5): + rec["status"] = "reregistered" if iou2 >= quality_iou_th else "low_quality" + return pose2, rec + # 重注册更差:回退 track 结果,并恢复 pose_last 以免污染后续帧 + est.pose_last = pl_backup + rec["status"] = "low_quality" + return pose, rec + + def _set_pose_last(pose_ext): + """pose_last 是居中网格坐标系:P_ext = pose_last @ tf_to_center。""" + tf = est.get_tf_to_centered_mesh() + tf_inv = torch.linalg.inv(tf) + est.pose_last = (torch.as_tensor(pose_ext, device='cuda', dtype=torch.float) @ tf_inv) + + def _register_at(i): + color, depth, mask = _load_frame( + query_image_names[i], query_depth_names[i], query_mask_names[i], mask_inputs + ) + K = np.array(query_intrinsics[i]) + pose = np.asarray( + est.register(K=K, rgb=color, depth=depth, ob_mask=mask, iteration=est_refine_iter) + ).reshape(4, 4) + pose, rec = _gate(i, pose, color, depth, mask, source="register_anchor") + + # 锚帧候选对比:scale 恢复阶段的 PnP 位姿(含 FoundationPose refine 后的版本) + # 与 register 结果同指标打分取优。FP register 对深色/近对称物体易 180° 翻转, + # PnP 来自纹理匹配点,可在这类失败时兜底。 + if pnp_anchor_pose is not None and mask.sum() >= min_mask_pix: + fp_backup = est.pose_last.clone() if torch.is_tensor(est.pose_last) else est.pose_last + cands = [] + pnp_raw = np.asarray(pnp_anchor_pose, dtype=np.float64).reshape(4, 4) + iou_raw, cerr_raw = _pose_mask_bbox_iou(pnp_raw, verts, K, mask) + cands.append(("pnp_raw", pnp_raw, iou_raw, cerr_raw)) + try: + _set_pose_last(pnp_raw) + pnp_ref = np.asarray( + est.track_one(rgb=color, depth=depth, K=K, iteration=est_refine_iter) + ).reshape(4, 4) + iou_ref, cerr_ref = _pose_mask_bbox_iou(pnp_ref, verts, K, mask) + cands.append(("pnp_refined", pnp_ref, iou_ref, cerr_ref)) + except Exception as ex: # noqa: BLE001 + logging.info(f"pnp candidate refine failed: {ex}") + rec["pnp_candidates"] = {n: {"iou": round(io, 3), "center_err_px": round(ce, 1)} + for n, _, io, ce in cands} + best = max(cands, key=lambda c: (c[2], -c[3])) + # _gate 可能已换成 re-register 的位姿,rec["iou"] 不一定对应当前 pose,直接重算 + cur_iou, _ = _pose_mask_bbox_iou(pose, verts, K, mask) + # 仅在明显更优时替换,避免噪声抖动 + if best[2] > cur_iou + 0.02: + pose = best[1] + rec["source"] = f"anchor_best:{best[0]}" + rec["iou"], rec["center_err_px"] = round(best[2], 3), round(best[3], 1) + rec["status"] = "ok" if (not quality_gate or best[2] >= quality_iou_th) else "low_quality" + _set_pose_last(pose) + else: + est.pose_last = fp_backup + return pose, rec + + def _track_at(i, prev_pose): + color, depth, mask = _load_frame( + query_image_names[i], query_depth_names[i], query_mask_names[i], mask_inputs + ) + K = np.array(query_intrinsics[i]) + pose = np.asarray( + est.track_one(rgb=color, depth=depth, K=K, iteration=track_refine_iter) + ).reshape(4, 4) + if prev_pose is not None and mask.sum() >= min_mask_pix: + if np.linalg.norm(pose[:3, 3] - prev_pose[:3, 3]) > jump_th: + pose = np.asarray( + est.register(K=K, rgb=color, depth=depth, ob_mask=mask, iteration=est_refine_iter) + ).reshape(4, 4) + return _gate(i, pose, color, depth, mask, source="track") + + poses[anchor_idx], quality[anchor_idx] = _register_at(anchor_idx) + anchor_pose_last = est.pose_last.clone() if torch.is_tensor(est.pose_last) else est.pose_last + + for i in range(anchor_idx + 1, num_frames): + poses[i], quality[i] = _track_at(i, poses[i - 1]) + + if anchor_idx > 0: + est.pose_last = anchor_pose_last.clone() if torch.is_tensor(anchor_pose_last) else anchor_pose_last + for i in range(anchor_idx - 1, -1, -1): + poses[i], quality[i] = _track_at(i, poses[i + 1]) + + n_ok = sum(1 for q in quality if q and q["status"] in ("ok", "reregistered")) + n_rereg = sum(1 for q in quality if q and q["status"] == "reregistered") + n_bad = sum(1 for q in quality if q and q["status"] == "low_quality") + n_nomask = sum(1 for q in quality if q and q["status"] == "no_mask") + logging.info( + f"pose quality gate: anchor={anchor_idx}, ok={n_ok} (reregistered={n_rereg}), " + f"low_quality={n_bad}, no_mask={n_nomask}, total={num_frames}" + ) + + if smooth_window and smooth_window >= 3: + good = [i for i, q in enumerate(quality) if q and q["status"] in ("ok", "reregistered")] + if len(good) >= 3: + smoothed_good = _smooth_pose_list([poses[i] for i in good], window=smooth_window) + for j, i in enumerate(good): + poses[i] = smoothed_good[j] + poses = [np.asarray(p).reshape(4, 4) for p in poses] + + quality_path = Path(output_dir).parent / "pose_result" / "pose_quality.json" + try: + quality_path.parent.mkdir(parents=True, exist_ok=True) + quality_path.write_text(_json.dumps({ + "anchor_idx": anchor_idx, + "quality_gate": bool(quality_gate), + "quality_iou_th": quality_iou_th, + "smooth_window": int(smooth_window), + "summary": {"ok": n_ok, "reregistered": n_rereg, "low_quality": n_bad, "no_mask": n_nomask}, + "frames": quality, + }, indent=2)) + except Exception as ex: # noqa: BLE001 + logging.info(f"failed to write pose_quality.json: {ex}") + + # 重绘可视化 + rgbs = [] + depths = [] + for frame_id in range(num_frames): + color = cv2.imread(query_image_names[frame_id]) + depth = cv2.imread(query_depth_names[frame_id], -1) / 1e3 + K = np.array(query_intrinsics[frame_id]) + center_pose = poses[frame_id] @ np.linalg.inv(to_origin) + rgb_vis, dep_vis = draw_posed_3d_box_with_depth(K, img=color, depth=depth, ob_in_cam=center_pose, bbox=bbox) + rgb_new, dep_new = draw_xyz_axis_with_depth(rgb_vis, depth=dep_vis, ob_in_cam=center_pose, scale=0.3, K=K, thickness=3, transparency=0, is_input_rgb=True) + st = quality[frame_id]["status"] if quality[frame_id] else "?" + if st in ("low_quality", "no_mask"): + rgb_new = np.ascontiguousarray(rgb_new) + cv2.putText(rgb_new, st, (12, 36), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 255), 3) + rgb_new = np.transpose(rgb_new, (2, 0, 1))/255 + rgbs.append(rgb_new) + depths.append(dep_new) + + data = dict(np.load(npz_path)) + # 替换指定字段 + data['depths'] = depths + data['video'] = rgbs + np.savez(npz_path, **data) + return poses # Return the list of estimated poses for each image diff --git a/OVOW/engine/oneposeviagen/scripts/get_frames.py b/OVOW/engine/oneposeviagen/scripts/get_frames.py new file mode 100644 index 0000000000000000000000000000000000000000..33e697a9271d291aaa82d1a942778a57a77eb38c --- /dev/null +++ b/OVOW/engine/oneposeviagen/scripts/get_frames.py @@ -0,0 +1,46 @@ +import cv2 +import os + +def extract_frames(video_path, output_folder): + """ + 从视频中提取所有帧,并按顺序保存为 frame_000000.png 格式。 + + 参数: + video_path (str): 视频文件的路径。 + output_folder (str): 保存帧图像的输出目录。 + + 返回: + int: 提取并保存的总帧数。 + """ + # 创建输出文件夹(如果不存在) + os.makedirs(output_folder, exist_ok=True) + + # 打开视频文件 + cap = cv2.VideoCapture(video_path) + + if not cap.isOpened(): + raise ValueError(f"无法打开视频文件: {video_path}") + + frame_idx = 0 + file_names = [] + while True: + ret, frame = cap.read() + + if not ret: + break + + # 构造文件名,例如:frame_000000.png + filename = os.path.join(output_folder, f"{frame_idx:06d}.png") + file_names.append(filename) + + # 保存帧为图像文件 + cv2.imwrite(filename, frame) + + frame_idx += 1 + + # 释放资源 + cap.release() + + print(f"共保存 {frame_idx} 帧图像到 '{output_folder}'。") + return file_names + diff --git a/OVOW/engine/oneposeviagen/scripts/render_multi_objects.py b/OVOW/engine/oneposeviagen/scripts/render_multi_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..42fb688b0407117ccf6727c79d9233a72d6ae457 --- /dev/null +++ b/OVOW/engine/oneposeviagen/scripts/render_multi_objects.py @@ -0,0 +1,184 @@ +#!/usr/bin/env python +""" +Render multiple objects into a single frame using their poses/intrinsics. +Supports black background or compositing onto the original RGB. +Outputs one PNG per frame. +""" +import argparse +import json +import os +import sys +from pathlib import Path +from typing import Dict, List, Tuple + +import cv2 +import numpy as np +import torch +from tqdm import tqdm +import nvdiffrast.torch as dr + +REPO_ROOT = Path(__file__).resolve().parents[2] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from oneposeviagen.fpose.fpose.Utils import nvdiffrast_render, make_mesh_tensors +from oneposeviagen.scripts.render_rgb_views import load_mesh_with_fallback, find_rgb + + +def load_json(path: Path) -> Dict: + with open(path, "r") as f: + return json.load(f) + + +def pick_mesh_path(obj_dir: Path) -> Path: + """Choose the best mesh candidate in an object directory.""" + candidates: List[Path] = [] + candidates.append(obj_dir / "mid_files" / "scaled_mesh.obj") + candidates.extend(sorted((obj_dir / "model" / "middle_file").glob("*_high_mesh.obj"))) + candidates.append(obj_dir / "model" / "model.obj") + for c in candidates: + if c.exists(): + return c + raise FileNotFoundError(f"No mesh found in {obj_dir}") + + +def render_multi(objects_root: Path, intrinsics_path: Path, rgb_dir: Path, out_dir: Path, + device: str = "cuda", background: str = "black", use_light: bool = False, + scale_intrinsics: bool = False, pose_name: str = "poses.json"): + out_dir.mkdir(parents=True, exist_ok=True) + + intrinsics = load_json(intrinsics_path) + + # load per-object data + obj_dirs = sorted([d for d in objects_root.iterdir() if d.is_dir()]) + objects = [] + for d in obj_dirs: + pose_path = d / "pose_result" / pose_name + if not pose_path.exists(): + fallback = d / "pose_result" / "poses.json" + if pose_name != "poses.json" and fallback.exists(): + print(f"[Fallback] {d} missing {pose_name}, use poses.json") + pose_path = fallback + else: + print(f"[Skip] {d} missing {pose_name}") + continue + poses = load_json(pose_path) + mesh_path = pick_mesh_path(d) + mesh, mesh_src = load_mesh_with_fallback(mesh_path) + mesh_tensors = make_mesh_tensors(mesh, device=device) + objects.append({ + 'name': d.name, + 'poses': poses, + 'mesh_tensors': mesh_tensors, + 'mesh_src': mesh_src, + }) + print(f"[Load] {d.name}: poses {len(poses)}, mesh {mesh_src}") + + if not objects: + raise RuntimeError("No valid objects to render") + + # frame ids intersection + frame_ids = set(objects[0]['poses'].keys()) + for obj in objects[1:]: + frame_ids &= set(obj['poses'].keys()) + if not frame_ids: + raise RuntimeError("No common frame ids across objects") + frame_ids = sorted(frame_ids, key=lambda x: int(x)) + print(f"[Info] Rendering {len(frame_ids)} frames: {frame_ids}") + + # optional intrinsics scaling + meta_shape = None + meta_path = rgb_dir.parent / "frame_meta.json" + if scale_intrinsics and meta_path.exists(): + try: + meta = load_json(meta_path) + if 'shape' in meta and len(meta['shape']) >= 2: + meta_shape = meta['shape'] + print(f"[Render] Detected original frame shape from {meta_path}: {meta_shape}") + except Exception as e: + print(f"[Render] Warning: failed to read frame_meta.json: {e}") + + # context + if device.startswith('cuda'): + glctx = dr.RasterizeCudaContext() + context = 'cuda' + else: + glctx = dr.RasterizeGLContext() + context = 'gl' + + for fid in tqdm(frame_ids, desc="Rendering multi-objects"): + rgb_path = find_rgb(rgb_dir, fid) + rgb_bgr = cv2.imread(str(rgb_path)) + if rgb_bgr is None: + raise RuntimeError(f"Failed to read RGB at {rgb_path}") + H, W = rgb_bgr.shape[:2] + + # base canvas + if background == 'rgb': + base_rgb = cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB) + else: + base_rgb = np.zeros_like(rgb_bgr[..., ::-1]) # RGB zeros + + for obj in objects: + pose = torch.tensor(np.array(obj['poses'][fid], dtype=np.float32), device=device).unsqueeze(0) + K = np.array(intrinsics[fid], dtype=np.float32) + + if meta_shape is not None: + H0, W0 = int(meta_shape[0]), int(meta_shape[1]) + sx, sy = W / W0, H / H0 + if not np.isclose(sx, 1.0) or not np.isclose(sy, 1.0): + K = K.copy() + K[0, 0] *= sx; K[0, 2] *= sx + K[1, 1] *= sy; K[1, 2] *= sy + + color, depth, _ = nvdiffrast_render( + K=K, + H=H, + W=W, + ob_in_cams=pose, + glctx=glctx, + context=context, + get_normal=False, + mesh_tensors=obj['mesh_tensors'], + output_size=(H, W), + use_light=use_light, + ) + color_np = (color[0].detach().cpu().numpy() * 255).astype(np.uint8) # RGB + mask = color_np.sum(axis=2) > 0 + base_rgb[mask] = color_np[mask] + + out_bgr = cv2.cvtColor(base_rgb, cv2.COLOR_RGB2BGR) + cv2.imwrite(str(out_dir / f"{int(fid):06d}.png"), out_bgr) + + +def parse_args(): + parser = argparse.ArgumentParser(description="Render multiple objects into one frame") + parser.add_argument('--objects_root', required=True, type=Path, help='Directory containing object subfolders') + parser.add_argument('--intrinsics', required=True, type=Path, help='scene intrinsics.json') + parser.add_argument('--rgb_dir', required=True, type=Path, help='RGB frames directory') + parser.add_argument('--out_dir', required=True, type=Path, help='Output directory for combined frames') + parser.add_argument('--device', default='cuda', help='cuda or cpu') + parser.add_argument('--background', choices=['black', 'rgb'], default='black', help='black: render on black; rgb: composite on original RGB') + parser.add_argument('--light', action='store_true', help='Enable diffuse lighting') + parser.add_argument('--scale_intrinsics', action='store_true', help='Scale K if rgb resized (uses frame_meta.json)') + parser.add_argument('--pose_name', default='poses.json', help='Pose json filename under pose_result (default: poses.json)') + return parser.parse_args() + + +def main(): + args = parse_args() + render_multi( + objects_root=args.objects_root, + intrinsics_path=args.intrinsics, + rgb_dir=args.rgb_dir, + out_dir=args.out_dir, + device=args.device, + background=args.background, + use_light=args.light, + scale_intrinsics=args.scale_intrinsics, + pose_name=args.pose_name, + ) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/oneposeviagen/scripts/render_multi_scenes.py b/OVOW/engine/oneposeviagen/scripts/render_multi_scenes.py new file mode 100644 index 0000000000000000000000000000000000000000..5c6c979005b9aceca9a5988f95c606619a03b47f --- /dev/null +++ b/OVOW/engine/oneposeviagen/scripts/render_multi_scenes.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python +""" +Batch render multiple scenes (each with multiple objects) into combined frames. +Scene spec supports single number (e.g., 15 or 02) or ranges/commas +(e.g., 1-5,8,12 or 01-05,08,12). Leading zeros are preserved so folders +named like scene_02 are handled correctly. Background can be black or +the original RGB. +""" +import argparse +import sys +from pathlib import Path +from typing import List + +# ensure repo root on path +REPO_ROOT = Path(__file__).resolve().parents[2] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from oneposeviagen.scripts.render_multi_objects import render_multi # type: ignore + + +def parse_scene_spec(spec: str) -> List[str]: + """ + Parse scene specification while preserving leading zeros. + Returns a list of scene id strings (e.g., ["02", "03"]). + """ + scenes: List[str] = [] + for part in spec.split(','): + part = part.strip() + if not part: + continue + if '-' in part: + a_str, b_str = [p.strip() for p in part.split('-', 1)] + try: + a_int, b_int = int(a_str), int(b_str) + except ValueError: + raise ValueError(f"Invalid scene range: {part}") + width = max(len(a_str), len(b_str)) + step = 1 if b_int >= a_int else -1 + for n in range(a_int, b_int + step, step): + scenes.append(str(n).zfill(width)) + else: + try: + num = int(part) + except ValueError: + raise ValueError(f"Invalid scene id: {part}") + width = len(part) + scenes.append(str(num).zfill(width)) + # preserve order while deduping + seen = set() + ordered_unique: List[str] = [] + for s in scenes: + if s not in seen: + seen.add(s) + ordered_unique.append(s) + return ordered_unique + + +def main(): + ap = argparse.ArgumentParser(description="Batch render multi-object scenes") + ap.add_argument('--batch_root', required=True, type=Path, help='Root dir containing scene_xx folders') + ap.add_argument('--scenes', required=True, type=str, help='Scene spec, e.g., 1,3,5-7') + ap.add_argument('--background', choices=['black', 'rgb'], default='black') + ap.add_argument('--device', default='cuda') + ap.add_argument('--light', action='store_true') + ap.add_argument('--scale_intrinsics', action='store_true', help='Scale K if rgb resized (uses frame_meta.json)') + ap.add_argument('--output_root', required=True, type=Path, help='Where to store rendered outputs by scene') + args = ap.parse_args() + + scene_ids = parse_scene_spec(args.scenes) + if not scene_ids: + raise SystemExit("No scenes parsed from spec") + + for sid in scene_ids: + # try padded id first, then fallback to non-padded for compatibility + candidates = [sid] + unpadded = str(int(sid)) if sid.lstrip('0') != '' else sid + if unpadded != sid: + candidates.append(unpadded) + + scene_dir = None + for cid in candidates: + candidate_path = args.batch_root / f"scene_{cid}" + if candidate_path.exists(): + scene_dir = candidate_path + sid = cid # use the actual matched id for logging/output + break + if scene_dir is None: + print(f"[Skip] scene_{sid} not found under {args.batch_root}") + continue + intrinsics = scene_dir / 'intrinsics.json' + rgb_dir = scene_dir / 'rgb' + objects_root = scene_dir / 'objects' + if not intrinsics.exists() or not rgb_dir.exists() or not objects_root.exists(): + print(f"[Skip] {scene_dir} missing required files") + continue + out_dir = args.output_root / f"scene_{sid}" / f"render_multi_{args.background}" + print(f"[Scene {sid}] rendering to {out_dir} (bg={args.background})") + render_multi( + objects_root=objects_root, + intrinsics_path=intrinsics, + rgb_dir=rgb_dir, + out_dir=out_dir, + device=args.device, + background=args.background, + use_light=args.light, + scale_intrinsics=args.scale_intrinsics, + ) + + +if __name__ == '__main__': + main() diff --git a/OVOW/engine/oneposeviagen/scripts/render_normals.py b/OVOW/engine/oneposeviagen/scripts/render_normals.py new file mode 100644 index 0000000000000000000000000000000000000000..a7a982e2fd4d6fb2452f19a5573a1c1018ed25b2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/scripts/render_normals.py @@ -0,0 +1,237 @@ +import cv2 +import os +import numpy as np +import torch +from pytorch3d.renderer import (look_at_view_transform, PerspectiveCameras, + PointLights, RasterizationSettings, BlendParams, + MeshRenderer, MeshRasterizer, SoftPhongShader) +from pytorch3d.io import load_objs_as_meshes + + +import torch +import numpy as np +from pytorch3d.io import load_objs_as_meshes +from pytorch3d.renderer import ( + PerspectiveCameras, + MeshRenderer, + MeshRasterizer, + RasterizationSettings, + PointLights +) +from pytorch3d.structures import Meshes + +import numpy as np + +def compute_fov(K, width, height, degrees=False): + """ + 根据相机内参矩阵 K 和图像尺寸计算 FoV + + 参数: + K (np.ndarray): 3x3 相机内参矩阵 + width (int): 图像宽度(像素) + height (int): 图像高度(像素) + degrees (bool): 是否返回角度,默认 True + + 返回: + fovx (float): 水平视场角 + fovy (float): 垂直视场角 + """ + fx = K[0, 0] + fy = K[1, 1] + + fovx = 2 * np.arctan(width / (2 * fx)) + fovy = 2 * np.arctan(height / (2 * fy)) + + if degrees: + fovx = np.degrees(fovx) + fovy = np.degrees(fovy) + + return fovx, fovy + +def render_normal_map(mesh_path, model_pose, width=640, height=480, fov=1, device='cpu'): + """ + 渲染指定位姿下的模型法线图 + :param mesh_path: str, 模型路径 (.obj) + :param model_pose: numpy array [4,4], 世界坐标到相机坐标的变换矩阵 (OpenCV 格式) + :param width: 输出图像宽度 + :param height: 输出图像高度 + :param fov: 视场角(弧度) + :param device: 'cpu' or 'cuda' + :return: normal_map: numpy array of shape (H, W, 3) in [0, 255] + """ + + # --------------------------- + # Step 1: Load Mesh + # --------------------------- + mesh = load_objs_as_meshes([mesh_path], device=device) + + # --------------------------- + # Step 2: Convert OpenCV pose to PyTorch3D camera matrix + # --------------------------- + rotation_matrix = model_pose[:3, :3] + tvec = model_pose[:3, 3] + + world_2_cam_render = np.eye(4, dtype=np.float32) + world_2_cam_render[:3, :3] = np.linalg.inv(rotation_matrix) + world_2_cam_render[3, :3] = tvec + world_2_cam_render[:, :2] = -world_2_cam_render[:, :2] # PyTorch3D 坐标系适配 + + camera_pose = torch.tensor(world_2_cam_render, device=device).unsqueeze(0) # (1, 4, 4) + + R = camera_pose[:, :3, :3] + T = camera_pose[:, 3, :3] + + # --------------------------- + # Step 3: Setup Camera + # --------------------------- + focal_length = torch.ones(1, 1, device=device) * 0.5 * width / np.tan(fov / 2) + principal_point = torch.tensor([[width / 2, height / 2]], device=device).repeat(1, 1) + image_size = torch.tensor([[height, width]], device=device).repeat(1, 1) + + cameras = PerspectiveCameras( + R=R, + T=T, + focal_length=focal_length, + principal_point=principal_point, + image_size=image_size, + in_ndc=False, + device=device + ) + + # --------------------------- + # Step 4: Set up Rasterizer + # --------------------------- + raster_settings = RasterizationSettings( + image_size=(height, width), + blur_radius=0.0, + faces_per_pixel=1, + bin_size=0, + ) + + rasterizer = MeshRasterizer( + cameras=cameras, + raster_settings=raster_settings + ) + + # --------------------------- + # Step 5: Rasterize and Interpolate Normals + # --------------------------- + fragments = rasterizer(mesh) + pix_to_face = fragments.pix_to_face # (N, H, W, K) + bary_coords = fragments.bary_coords # (N, H, W, K, 1) + mesh_faces_normals = mesh.faces_normals_packed() # (F, 3) + + N, H, W, K = pix_to_face.shape + + # Flatten for indexing + pix_to_face_flat = pix_to_face.view(N, H * W, K) + bary_coords_flat = bary_coords.view(N, H * W, K, 3) + + # Get valid normals using face indices + mask = pix_to_face_flat >= 0 + normals = torch.zeros((N, H * W, K, 3), device=device) + for i in range(K): + valid_idx = pix_to_face_flat[:, :, i][mask[:, :, i]] + if len(valid_idx) > 0: + normals[:, :, i, :][mask[:, :, i]] = mesh_faces_normals[valid_idx] + + # Interpolate per-pixel normals + pixel_normals = (normals * bary_coords_flat).sum(dim=2) # (N, H*W, 3) + pixel_normals = pixel_normals.view(N, H, W, 3) # (N, H, W, 3) + + # Normalize and convert to RGB + pixel_normals = torch.nn.functional.normalize(pixel_normals, dim=-1) + pixel_normals = (pixel_normals + 1.0) / 2.0 # [-1,1] -> [0,1] + normal_map = (pixel_normals[0].cpu().numpy() * 255).astype(np.uint8) + + return normal_map + +def render_normals_to_video(poses, query_image_names, query_intrinsics, scaled_model_path, output_video_path, fps = 15, device='cpu'): + video_frames = [] + + for i, pose in enumerate(poses): + rgb_path = query_image_names[i] + intrinsic = np.array(query_intrinsics[i]) + pose = np.array(pose) + + # 读取 RGB 图像 + rgb_img = cv2.imread(rgb_path) + height, width = rgb_img.shape[:2] + fovx, fovy = compute_fov(intrinsic, width, height) + # 渲染模型法线图 + normal_map = render_normal_map(scaled_model_path, pose, width=width, height=height, fov=fovx, device=device) + + # 将法线图叠加到RGB图像上(可选) + # 注意:normal_map 应该是 [H, W, 3] 的 numpy 数组 + alpha = 0.8 # 调整透明度 + overlay = cv2.addWeighted(normal_map, alpha, rgb_img, 1 - alpha, 0) + + # 或者直接使用法线图作为输出帧 + frame = overlay if normal_map is not None else rgb_img + + # 添加到视频帧列表中 + video_frames.append(frame) + + # 获取第一帧的尺寸信息 + height, width, layers = video_frames[0].shape + + # 定义视频编码器 + fourcc = cv2.VideoWriter_fourcc(*'mp4v') + video_writer = cv2.VideoWriter(output_video_path, fourcc, fps, (width, height)) + + # 写入视频帧 + for frame in video_frames: + video_writer.write(frame) + + # 释放视频写入器 + video_writer.release() + +def render_high_model_to_normal_video(poses, query_image_names, query_intrinsics, high_mesh_path, output_video_path, fps = 15, device='cpu'): + import trimesh + from oneposeviagen.fpose.fpose.Utils import nvdiffrast_render, make_mesh_tensors + import torch + video_frames = [] + mesh = trimesh.load(high_mesh_path, force='mesh') + mesh_tensors = make_mesh_tensors(mesh, device='cuda') + glctx = None # 让nvdiffrast_render自动创建 + + for i, pose in enumerate(poses): + rgb_path = query_image_names[i] + intrinsic = np.array(query_intrinsics[i]) + pose = np.array(pose) + rgb_img = cv2.imread(rgb_path) + height, width = rgb_img.shape[:2] + # nvdiffrast_render 需要 torch 格式的 pose + pose_tensor = torch.tensor(pose, dtype=torch.float32, device='cuda').unsqueeze(0) # (1,4,4) + # 渲染法线图 + _, _, normal_map = nvdiffrast_render( + K=intrinsic, + H=height, + W=width, + ob_in_cams=pose_tensor, + glctx=glctx, + context='cuda', + get_normal=True, + mesh_tensors=mesh_tensors, + mesh=None, + projection_mat=None, + bbox2d=None, + output_size=(height, width), + use_light=False + ) + # normal_map: (1, H, W, 3), [-1,1],需转为[0,255] uint8 + normal_map = normal_map[0].detach().cpu().numpy() + normal_map = (-normal_map + 1.0) / 2.0 # [-1,1] -> [0,1] + normal_map = (normal_map * 255).astype(np.uint8) + # 叠加到RGB + alpha = 0.7 + overlay = cv2.addWeighted(normal_map, alpha, rgb_img, 1 - alpha, 0) + frame = overlay if normal_map is not None else rgb_img + video_frames.append(frame) + + height, width, layers = video_frames[0].shape + fourcc = cv2.VideoWriter_fourcc(*'mp4v') + video_writer = cv2.VideoWriter(output_video_path, fourcc, fps, (width, height)) + for frame in video_frames: + video_writer.write(frame) + video_writer.release() \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/scripts/render_rgb_views.py b/OVOW/engine/oneposeviagen/scripts/render_rgb_views.py new file mode 100644 index 0000000000000000000000000000000000000000..0620407a76ef6bc13d027ef05412c0d8a60144f7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/scripts/render_rgb_views.py @@ -0,0 +1,186 @@ +""" +Render a textured OBJ using precomputed poses/intrinsics to per-frame PNGs. +Supports black background or overlay onto original RGBs. +""" +import argparse +import json +import os +import sys +from pathlib import Path +from typing import Dict, List, Tuple + +import cv2 +import numpy as np +import torch +import trimesh +from tqdm import tqdm + +# Make repo root importable +REPO_ROOT = Path(__file__).resolve().parents[2] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from oneposeviagen.fpose.fpose.Utils import nvdiffrast_render, make_mesh_tensors +import nvdiffrast.torch as dr + + +def load_json(path: Path) -> Dict: + with open(path, "r") as f: + return json.load(f) + + +def _has_uv(mesh: trimesh.Trimesh) -> bool: + return isinstance(mesh.visual, trimesh.visual.texture.TextureVisuals) and mesh.visual.uv is not None + + +def load_mesh_with_fallback(mesh_path: Path) -> Tuple[trimesh.Trimesh, str]: + """Load mesh; if missing UVs try a nearby textured mesh; else fall back to vertex colors.""" + mesh = trimesh.load(mesh_path, force='mesh') + if _has_uv(mesh): + return mesh, str(mesh_path) + + # try fallback candidates that likely have UVs + candidates = [] + # e.g., .../objects/xxx/model/middle_file/high_mesh.obj -> .../objects/xxx/mid_files/scaled_mesh.obj + if mesh_path.parent.name == 'middle_file': + candidates.append(mesh_path.parent.parent.parent / 'mid_files' / 'scaled_mesh.obj') + candidates.append(mesh_path.parent.parent / 'model.obj') # .../model/model.obj + # also try sibling model.obj + candidates.append(mesh_path.parent / 'model.obj') + + for cand in candidates: + if cand.exists(): + cand_mesh = trimesh.load(cand, force='mesh') + if _has_uv(cand_mesh): + return cand_mesh, str(cand) + + # final fallback: strip texture visuals to avoid None UV and use vertex colors + mesh = mesh.copy() + mesh.visual = mesh.visual.to_color() + return mesh, f"{mesh_path} (no UV; converted to vertex color)" + + +def find_rgb(rgb_dir: Path, idx: str) -> Path: + # try zero-padded jpg first + candidates: List[Path] = [rgb_dir / f"{int(idx):06d}.jpg", rgb_dir / f"{int(idx):06d}.png"] + # fallbacks: non-padded + candidates += [rgb_dir / f"{idx}.jpg", rgb_dir / f"{idx}.png"] + for c in candidates: + if c.exists(): + return c + raise FileNotFoundError(f"RGB frame for id {idx} not found in {rgb_dir}") + + +def render_frames(mesh_path: Path, poses_path: Path, intrinsics_path: Path, rgb_dir: Path, out_dir: Path, + device: str = "cuda", background: str = "black", use_light: bool = False, + scale_intrinsics: bool = False): + out_dir.mkdir(parents=True, exist_ok=True) + + mesh, mesh_source = load_mesh_with_fallback(mesh_path) + print(f"[Render] Using mesh: {mesh_source}") + mesh_tensors = make_mesh_tensors(mesh, device=device) + + poses = load_json(poses_path) + intrinsics = load_json(intrinsics_path) + + frame_ids = sorted(poses.keys(), key=lambda x: int(x)) + + # optional intrinsics scaling if frame_meta.json (original H,W) exists + meta_path = rgb_dir.parent / "frame_meta.json" + meta_shape = None + if scale_intrinsics and meta_path.exists(): + try: + meta = load_json(meta_path) + if 'shape' in meta and len(meta['shape']) >= 2: + meta_shape = meta['shape'] + print(f"[Render] Detected original frame shape from {meta_path}: {meta_shape}") + except Exception as e: + print(f"[Render] Warning: failed to read frame_meta.json: {e}") + + # Create reusable rasterizer context + if device.startswith('cuda'): + glctx = dr.RasterizeCudaContext() + context = 'cuda' + else: + glctx = dr.RasterizeGLContext() + context = 'gl' + + for fid in tqdm(frame_ids, desc="Rendering"): + pose = torch.tensor(np.array(poses[fid], dtype=np.float32), device=device).unsqueeze(0) + K = np.array(intrinsics[fid], dtype=np.float32) + + rgb_path = find_rgb(rgb_dir, fid) + rgb_bgr = cv2.imread(str(rgb_path)) + if rgb_bgr is None: + raise RuntimeError(f"Failed to read RGB at {rgb_path}") + H, W = rgb_bgr.shape[:2] + + if meta_shape is not None: + H0, W0 = int(meta_shape[0]), int(meta_shape[1]) + sx, sy = W / W0, H / H0 + if not np.isclose(sx, 1.0) or not np.isclose(sy, 1.0): + K = K.copy() + K[0, 0] *= sx + K[0, 2] *= sx + K[1, 1] *= sy + K[1, 2] *= sy + # optional log + # print(f"[Render] Scaled intrinsics by (sx={sx:.3f}, sy={sy:.3f}) for frame {fid}") + + color, depth, _ = nvdiffrast_render( + K=K, + H=H, + W=W, + ob_in_cams=pose, + glctx=glctx, + context=context, + get_normal=False, + mesh_tensors=mesh_tensors, + output_size=(H, W), + use_light=use_light, + ) + color_np = (color[0].detach().cpu().numpy() * 255).astype(np.uint8) # RGB + + if background == 'overlay': + rgb_rgb = cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB) + mask = color_np.sum(axis=2) > 0 # where mesh rendered + rgb_rgb[mask] = color_np[mask] + out_rgb = rgb_rgb + else: + out_rgb = color_np + + out_bgr = cv2.cvtColor(out_rgb, cv2.COLOR_RGB2BGR) + cv2.imwrite(str(out_dir / f"{int(fid):06d}.png"), out_bgr) + + +def parse_args(): + parser = argparse.ArgumentParser(description="Render OBJ with given poses/intrinsics to PNG frames") + parser.add_argument('--mesh', required=True, type=Path, help='Path to textured OBJ') + parser.add_argument('--poses', required=True, type=Path, help='poses.json (OpenCV world->cam 4x4)') + parser.add_argument('--intrinsics', required=True, type=Path, help='intrinsics.json keyed by frame id') + parser.add_argument('--rgb_dir', required=True, type=Path, help='Directory containing source RGB frames') + parser.add_argument('--out_dir', required=True, type=Path, help='Output directory for PNGs') + parser.add_argument('--device', default='cuda', help='cuda or cpu') + parser.add_argument('--background', choices=['black', 'overlay'], default='black', help='black: pure render; overlay: fill background with original RGB') + parser.add_argument('--light', action='store_true', help='Enable simple diffuse lighting') + parser.add_argument('--scale_intrinsics', action='store_true', help='Scale K if rgb is resized (uses frame_meta.json)') + return parser.parse_args() + + +def main(): + args = parse_args() + render_frames( + mesh_path=args.mesh, + poses_path=args.poses, + intrinsics_path=args.intrinsics, + rgb_dir=args.rgb_dir, + out_dir=args.out_dir, + device=args.device, + background=args.background, + use_light=args.light, + scale_intrinsics=args.scale_intrinsics, + ) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/oneposeviagen/trellis/.gitattributes b/OVOW/engine/oneposeviagen/trellis/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..a6344aac8c09253b3b630fb776ae94478aa0275b --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/.gitattributes @@ -0,0 +1,35 @@ +*.7z filter=lfs diff=lfs merge=lfs -text +*.arrow filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text +*.bz2 filter=lfs diff=lfs merge=lfs -text +*.ckpt filter=lfs diff=lfs merge=lfs -text +*.ftz filter=lfs diff=lfs merge=lfs -text +*.gz filter=lfs diff=lfs merge=lfs -text +*.h5 filter=lfs diff=lfs merge=lfs -text +*.joblib filter=lfs diff=lfs merge=lfs -text +*.lfs.* filter=lfs diff=lfs merge=lfs -text +*.mlmodel filter=lfs diff=lfs merge=lfs -text +*.model filter=lfs diff=lfs merge=lfs -text +*.msgpack filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text +*.ot filter=lfs diff=lfs merge=lfs -text +*.parquet filter=lfs diff=lfs merge=lfs -text +*.pb filter=lfs diff=lfs merge=lfs -text +*.pickle filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text +*.pth filter=lfs diff=lfs merge=lfs -text +*.rar filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +saved_model/**/* filter=lfs diff=lfs merge=lfs -text +*.tar.* filter=lfs diff=lfs merge=lfs -text +*.tar filter=lfs diff=lfs merge=lfs -text +*.tflite filter=lfs diff=lfs merge=lfs -text +*.tgz filter=lfs diff=lfs merge=lfs -text +*.wasm filter=lfs diff=lfs merge=lfs -text +*.xz 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 diff --git a/OVOW/engine/oneposeviagen/trellis/.gitignore b/OVOW/engine/oneposeviagen/trellis/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ef696f54f4bdf1acff36febbdf7d6f36e8e3d94b --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/.gitignore @@ -0,0 +1,28 @@ +weights +__pycache__ +StableNormal +examples +.gradio +outputs +scripts +wheels/controlnet_aux-master +wheels/diffoctreerast +wheels/image_gen_aux-main +wheels/mip-splatting +wheels/Orient_Anything +wheels/ml-depth-pro +wheels/controlnet_aux-master.zip +wheels/image_gen_aux-main.zip +logs +outputs +data +pre_outputs +output +splits +lightning_logs +checkpoints +assets +render_data +data_dreamverse2_sslatent +more_data +results \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/.vscode-upload.json b/OVOW/engine/oneposeviagen/trellis/.vscode-upload.json new file mode 100644 index 0000000000000000000000000000000000000000..b9db564507fa51e79d2a7f7764e0ecb522c73487 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/.vscode-upload.json @@ -0,0 +1,21 @@ +[{ + "name":"", + "host": "", + "port": 22, + "username": "", + "password": "", + "remotePath": "", + "localPath": "", + "disable": false, + "private_key": "~/.ssh/id_rsa" +},{ + "name":"", + "host": "", + "port": 22, + "username": "", + "password": "", + "remotePath": "", + "localPath": "", + "disable": false, + "private_key": "~/.ssh/id_rsa" +}] \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/LICENSE b/OVOW/engine/oneposeviagen/trellis/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..79656060de00aa4659ad2c276d5be8830664d544 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/app.py b/OVOW/engine/oneposeviagen/trellis/app.py new file mode 100644 index 0000000000000000000000000000000000000000..e5c10c550079f7d3ba609235fbd3133ef65c321e --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/app.py @@ -0,0 +1,204 @@ +import gradio as gr +import spaces +import os +os.environ['SPCONV_ALGO'] = 'native' +import numpy as np +import imageio +import uuid +from PIL import Image +from trellis.pipelines import TrellisImageTo3DPipeline +from trellis.utils import render_utils, postprocessing_utils +import trimesh +import torch + +MAX_SEED = np.iinfo(np.int32).max +TMP_DIR = "./tmp/Trellis-demo" + +import os +os.environ["PATH"] += os.path.join(os.getcwd(), "binvox") +os.makedirs(TMP_DIR, exist_ok=True) + +def preprocess_mesh(mesh_prompt): + print("Processing mesh") + trimesh_mesh = trimesh.load_mesh(mesh_prompt) + trimesh_mesh.export(mesh_prompt+'.glb') + return mesh_prompt+'.glb' + +def preprocess_image(image): + image = pipeline.preprocess_image(image, resolution=1024) + return image + +def save_slat(slat, save_path: str): + """Save SLAT features and coordinates to a npz file.""" + feats_numpy = slat.feats.detach().cpu().numpy() + coords_numpy = slat.coords.detach().cpu().numpy() + + np.savez( + save_path, + feats=feats_numpy, + coords=coords_numpy + ) + +@spaces.GPU +def generate_3d(image: Image.Image, neg_image_prompt: Image.Image, mesh_prompt, + export_format: str, seed: int = -1, + ss_guidance_strength: float = 7.5, ss_sampling_steps: int = 12, + slat_guidance_strength: float = 15, slat_sampling_steps: int = 25): + """Generate 3D model and preview video from input image.""" + if seed == -1: + seed = np.random.randint(0, MAX_SEED) + + + # Handle mesh prompt if provided + if mesh_prompt is not None: + trimesh_mesh = trimesh.load_mesh(mesh_prompt) + rotation_matrix = np.array([ + [1, 0, 0], + [0, 0, -1], + [0, 1, 0] + ]) + transformation_matrix = np.eye(4) + transformation_matrix[:3, :3] = rotation_matrix + + # Convert scene to mesh if necessary + if hasattr(trimesh_mesh, 'geometry'): + # If it's a scene, get the first mesh + # Assuming the scene has at least one mesh + mesh_name = list(trimesh_mesh.geometry.keys())[0] + trimesh_mesh = trimesh_mesh.geometry[mesh_name] + trimesh_mesh = postprocessing_utils.normalize_trimesh(trimesh_mesh) + trimesh_mesh.apply_transform(transformation_matrix) + + outputs = pipeline.run( + image, + ref_image=neg_image_prompt, + init_mesh=trimesh_mesh, + seed=seed, + formats=["mesh", "gaussian"], + preprocess_image=True, + sparse_structure_sampler_params={ + "steps": ss_sampling_steps, + "cfg_strength": ss_guidance_strength, + }, + slat_sampler_params={ + "steps": slat_sampling_steps, + "cfg_strength": slat_guidance_strength, + }, + ) + generated_mesh = outputs['mesh'][0] + generated_gs = outputs['gaussian'][0] + + else: + outputs = pipeline.run( + image, + seed=seed, + formats=["mesh", "gaussian"], + preprocess_image=True, + sparse_structure_sampler_params={ + "steps": ss_sampling_steps, + "cfg_strength": ss_guidance_strength, + }, + slat_sampler_params={ + "steps": slat_sampling_steps, + "cfg_strength": slat_guidance_strength, + }, + ) + generated_mesh = outputs['mesh'][0] + generated_gs = outputs['gaussian'][0] + + # Save video and mesh + output_id = str(uuid.uuid4()) + video_path = f"{TMP_DIR}/{output_id}_preview.mp4" + mesh_path = f"{TMP_DIR}/{output_id}.{export_format}" + gs_path = f"{TMP_DIR}/{output_id}.ply" + slat_path = f"{TMP_DIR}/{output_id}.npz" + generated_slat = outputs['slat'][0] + + save_slat(generated_slat, slat_path) + # Save video + video_geo = render_utils.render_video(generated_mesh, resolution=1024, num_frames=120)['color'] + imageio.mimsave(video_path, video_geo, fps=15) + + generated_gs = generated_gs.save_ply(gs_path) + + # Export mesh in selected format + trimesh_mesh = generated_mesh.to_trimesh(transform_pose=True) + trimesh_mesh.export(mesh_path) + + return video_path, gs_path, slat_path + +with gr.Blocks() as demo: + with gr.Row(): + with gr.Column(): + # Input controls + image_prompt = gr.Image(label="Image Prompt", image_mode="RGBA", type="pil") + neg_image_prompt = gr.Image(label="Negative Image Prompt", image_mode="RGBA", type="pil") + mesh_prompt = gr.Model3D(label="Model Prompt (Optional)") + + with gr.Accordion("Advanced Settings", open=False): + seed = gr.Slider(-1, MAX_SEED, label="Seed", value=0, step=1) + export_format = gr.Dropdown( + choices=["obj", "glb", "ply"], + value="glb", + label="Export Format", + info="Choose the format for the exported 3D model" + ) + + gr.Markdown("Stage 1: Sparse Structure Generation") + with gr.Row(): + ss_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=3, step=0.1) + ss_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=50, step=1) + gr.Markdown("Stage 2: Structured Latent Generation") + with gr.Row(): + slat_guidance_strength = gr.Slider(0.0, 10.0, label="Guidance Strength", value=3, step=0.1) + slat_sampling_steps = gr.Slider(1, 50, label="Sampling Steps", value=12, step=1) + + generate_btn = gr.Button("Generate 3D Model") + + with gr.Column(): + # Output displays + video_output = gr.Video(label="Preview", autoplay=True, loop=True) + model_output = gr.Model3D(label="3D Model (Mesh)") + slat_output = gr.File(label="SLAT Features", file_count="single") + + image_prompt.upload( + preprocess_image, + inputs=[image_prompt], + outputs=[image_prompt] + ) + neg_image_prompt.upload( + preprocess_image, + inputs=[neg_image_prompt], + outputs=[neg_image_prompt] + ) + mesh_prompt.upload( + preprocess_mesh, + inputs=[mesh_prompt], + outputs=[mesh_prompt], + ) + generate_btn.click( + generate_3d, + inputs=[ + image_prompt, neg_image_prompt, mesh_prompt, export_format, seed, + ss_guidance_strength, ss_sampling_steps, slat_guidance_strength, slat_sampling_steps + ], + outputs=[video_output, model_output, slat_output] + ) + +if __name__ == "__main__": + from peft import LoraConfig, get_peft_model + # peft_config = LoraConfig( + # r=512, + # lora_alpha=512, + # lora_dropout=0.0, + # target_modules=["to_q", "to_kv", "to_out", "to_qkv"] + # ) + # from peft import LoraConfig, get_peft_model + # pipeline = TrellisImageTo3DPipeline.from_pretrained("jetx/TRELLIS-image-large") + # pipeline.slat_flow_model = get_peft_model(pipeline.models['slat_flow_model'], peft_config) + # pipeline.slat_flow_model.print_trainable_parameters() + # pipeline.models['slat_flow_model'] = pipeline.slat_flow_model + # pipeline.load_model("slat_flow_model", "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/code/pose/One23Pose/checkpoints/Stable3DGen/epoch=49-step=123100.ckpt") + pipeline = TrellisImageTo3DPipeline.from_pretrained("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/code/pose/One23Pose_amodal3r/checkpoints/Stable3DGen") + pipeline.cuda() + demo.launch(share=False, server_name="0.0.0.0", server_port=9944, auth=("bbcc", "bbcc")) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/dataset.py b/OVOW/engine/oneposeviagen/trellis/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..681a2facab962fca06421a50d4f3a220e3e3dddc --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/dataset.py @@ -0,0 +1,498 @@ +import json +import cv2 +import numpy as np +import os +from torch.utils.data import Dataset +import random +import pdb +import PIL.Image as Image +import torchvision.transforms as T +import torch +import torch.nn.functional as F +import torchvision.transforms.functional as TF +import math +from trellis.modules import sparse as sp +from torch.utils.data import DataLoader +from trellis.utils import render_utils +import utils3d + +def get_camera_param_list(num_frames=40, r=2, fov=40, inverse_direction=False, pitch=-1): + if inverse_direction: + yaws = torch.linspace(3.1415, -3.1415, num_frames) + # pitch = 0.25 + 0.5 * torch.sin(torch.linspace(2 * 3.1415, 0, num_frames)) + else: + yaws = torch.linspace(0, 2 * 3.1415, num_frames) + if pitch != -1: + pitch = pitch * torch.ones(num_frames) + else: + pitch = 0.25 + 0.5 * torch.sin(torch.linspace(0, 2 * 3.1415, num_frames)) + yaws = yaws.tolist() + pitch = pitch.tolist() + extrinsics, intrinsics = render_utils.yaw_pitch_r_fov_to_extrinsics_intrinsics(yaws, pitch, r, fov, 'cpu') + return extrinsics, intrinsics + +class NpzDatasetAug(Dataset): + def __init__(self, json_files=None, stage=2, + source_aug=None, source_aug_prob=0.1, + task='normal', random_sample=-1, num_views=1): + self.data = [] + for json_file in json_files: + with open(json_file, "r") as f: + data_dir = os.path.dirname(json_file) + for line in f: + data_term = json.loads(line) + data_term['data_dir'] = data_dir + self.data += [data_term] + self.to_Tensor = T.ToTensor() + self.source_aug = source_aug + self.source_aug_prob = source_aug_prob + self.task = task + self.random_sample = random_sample + self.num_views = num_views + if self.num_views > 1: + self.extrinsics, self.intrinsics = get_camera_param_list() + self.stage = stage + + def __len__(self): + return len(self.data) + + def __getitem__(self, idx): + while True: + try: + return self._load_item(idx) + except Exception as e: + # print("Error loading item", e) + idx = random.randint(0, len(self.data) - 1) + + def _load_item(self, idx): + item = self.data[idx] + data_dir = item['data_dir'] + if self.stage == 1: + ss_data_dir = os.path.join(os.path.dirname(item['data_dir']), 'data_dreamverse2_sslatent') + + _target_data = np.load(os.path.join(ss_data_dir, item['target_slat'].replace('slat.npz', 'ss.npz'))) + target_ss_latents = torch.from_numpy(_target_data['mean']) + + else: + _target_data = np.load(os.path.join(data_dir, item['target_slat'])) + target_feats, target_coords = torch.from_numpy(_target_data['feats']), torch.from_numpy(_target_data['coords']) + if self.random_sample > 0: + random_sample = min(self.random_sample, target_feats.shape[0]) + idxs = np.random.choice(target_feats.shape[0], random_sample, replace=False) + target_feats = target_feats[idxs] + target_coords = target_coords[idxs] + + # Load and convert images to tensors + source_data = np.load(os.path.join(data_dir, item['source_image'])) + _data_len = len(source_data[self.task]) + + random_idx = random.randint(0, _data_len - 1) + if self.num_views > 1: + if random.random() < 1: + rand_interval = random.randint(0,4) + random_idx = [(random_idx + i * rand_interval) % _data_len for i in range(self.num_views)] + else: + random_idx = np.random.choice(_data_len, self.num_views, replace=False).tolist() + # random_idx = np.random.choice(_data_len, self.num_views, replace=False).tolist() + source = torch.stack([self.to_Tensor(source_data[self.task][i]).float() for i in random_idx]) + ref = torch.stack([self.to_Tensor(source_data['colors'][i]).float() for i in random_idx]) + # ref = ref.permute(0,2,3,1) + # ref[(ref[...,0] == 0.) & (ref[...,1] == 0.) & (ref[...,2] == 0.)] = 1. + # ref = ref.permute(0,3,1,2) + sample_extrinsics = torch.stack([self.extrinsics[i] for i in random_idx]) + sample_intrinsics = torch.stack([self.intrinsics[i] for i in random_idx]) + else: + source = self.to_Tensor(source_data[self.task][random_idx]).float() + ref = self.to_Tensor(source_data['colors'][random_idx]).float() + # ref = ref.permute(1,2,0) + # ref[(ref[...,0] == 0.) & (ref[...,1] == 0.) & (ref[...,2] == 0.)] = 1. + # ref = ref.permute(2,0,1) + + if source.max() > 1: + source /= 255.0 + if ref.max() > 1: + ref /= 255.0 + + # Apply source augmentation if specified + if self.source_aug is not None and random.random() < self.source_aug_prob: + source = self.source_aug(source) + + # Return with random condition + data_dict = dict(source_image=source, ref_image=ref) + if self.stage == 1: + data_dict.update(target_ss_latents=target_ss_latents) + if self.num_views > 1: + # data_dict.update(batch_extrinsics=sample_extrinsics, batch_intrinsics=sample_intrinsics, volume_resolution=volume_resolution) + data_dict.update(batch_extrinsics=sample_extrinsics, batch_intrinsics=sample_intrinsics) + else: + data_dict.update(target_feats=target_feats, target_coords=target_coords) + if self.num_views > 1: + # data_dict.update(batch_extrinsics=sample_extrinsics, batch_intrinsics=sample_intrinsics, volume_resolution=volume_resolution) + data_dict.update(batch_extrinsics=sample_extrinsics, batch_intrinsics=sample_intrinsics) + return data_dict + +def blender_world_normal_2_camera(normals_world: np.ndarray, c2w: np.ndarray) -> np.ndarray: + """ + Transform normal from world space to camera space. + :param normal: The normal in world space. + :param c2w: The camera to world matrix. + :return: The normal in camera space. + """ + assert len(normals_world.shape) == 3, "Normal must be a 3D vector." + H, W, C = normals_world.shape + + normals_camera = np.zeros((H, W, C), dtype=np.float32) + + if C == 4: + normals_world = normals_world[..., :3] + + R_c2w = c2w[:3, :3] + R_convert = np.array([ + [1, 0, 0], + [0, 0, 1], + [0, -1, 0] + ], dtype=np.float32) + + R_opencv = R_c2w @ R_convert + R_opencv = R_opencv.T + + transformed_normals = normals_world.reshape(-1, 3).T + transformed_normals = R_opencv @ transformed_normals + transformed_normals = transformed_normals.T + transformed_normals = transformed_normals.reshape(H, W, 3) + + normals_camera[..., :1] = transformed_normals[..., :1] * 0.5 + 0.5 + normals_camera[..., 2:3] = transformed_normals[..., 1:2] * -0.5 + 0.5 + normals_camera[..., 1:2] = transformed_normals[..., 2:3] * 0.5 + 0.5 + + return normals_camera + +def blender_depth_2_nocs(depth_map: np.ndarray, K: np.ndarray, c2w: np.ndarray) -> np.ndarray: + """ + 批量将深度图转换为点云。 + + 参数: + - depth_map: 深度图,形状为 (b, h, w),每个样本的深度图。 + - K: 相机内参矩阵,形状为 (b, 3, 3),每个样本的相机内参。 + - pose: 相机外参矩阵,形状为 (b, 4, 4),每个样本的相机外参。 + + 返回: + - points: 每个样本对应的点云,形状为 (b, N, 3), N为每个深度图的点数。 + """ + b, h, w = depth_map.shape + # depth_map[depth_map == 65504.] = 0. + + # 生成像素坐标网格 + u, v = np.meshgrid(np.arange(w), np.arange(h)) + # u = u.astype(float) + # v = v.astype(float) + + # 将深度图转换为相机坐标系下的三维坐标 + Z = depth_map.reshape(b, h * w) # (b, h * w,) + X = (u.flatten()[None] - K[:, 0, 2][:,None]) * Z / K[:, 0, 0][:,None] + Y = (v.flatten()[None] - K[:, 1, 2][:,None]) * Z / K[:, 1, 1][:,None] + + # 组合相机坐标系下的三维坐标 + camera_points = np.stack((X, Y, Z, np.ones_like(Z)), axis=2).reshape(b, h * w, 4, 1) # (b, h * w, 4, 1) + + # 将相机坐标系下的点转换到世界坐标系 + c2w[:, :3, 1:3] *= -1 + # pose_inv = np.linalg.inv(c2w)[:, None] # (b, 1, 4, 4) + pose_inv = c2w[:, None] # (b, 1, 4, 4) + world_points = np.matmul(pose_inv, camera_points) # (b, h * w, 4, 1) + world_points = world_points[:, :, :3, 0] # (b, h * w, 3) + + # 将点云添加到列表 + point_clouds = world_points.reshape(b, h, w, 3) + masks_0 = ((depth_map != 65504.) & (depth_map != 0.) & (depth_map != 1000.5496)).astype(np.uint8) + masks = [] + for i in range(b): + kernel = np.ones((3,3),np.uint8) + eroded = cv2.erode( + masks_0[i], # 确保输入类型正确 + kernel, + iterations=1, + ) + masks.append(np.array(eroded)) + masks = np.stack(masks, axis=0) + point_clouds[masks < 0.5] = 127/255 - 0.5 + + return (point_clouds + 0.5).clip(0,1) + +import json, pyexr +class JsonDatasetAug(Dataset): + def __init__(self, json_files=None, stage=2, + source_aug=None, source_aug_prob=0.1, + task='normal', random_sample=-1, num_views=1, rayembedding=False): + self.data = [] + for json_file in json_files: + with open(json_file, "r") as f: + data_dir = os.path.dirname(json_file) + for line in f: + data_term = json.loads(line) + data_term['data_dir'] = data_dir + self.data += [data_term] + self.to_Tensor = T.ToTensor() + self.source_aug = source_aug + self.source_aug_prob = source_aug_prob + self.task = task + self.random_sample = random_sample + self.num_views = num_views + self.rayembedding = rayembedding + self.default_image_size = 518 + if self.num_views > 1: + self.extrinsics, self.intrinsics = get_camera_param_list() + self.stage = stage + + def __len__(self): + return len(self.data) + + def __getitem__(self, idx): + while True: + try: + return self._load_item(idx) + except Exception as e: + print("Error loading item", e) + idx = random.randint(0, len(self.data) - 1) + + def _load_item(self, idx): + item = self.data[idx] + data_dir = item['data_dir'] + if self.stage == 1: + _target_data = np.load(os.path.join(data_dir, item['target_slat'].replace('slat', 'ss'))) + target_ss_latents = torch.from_numpy(_target_data['mean']) + if torch.isnan(target_ss_latents).any(): + raise ValueError("NaN values found in target_ss_latents") + else: + _target_data = np.load(os.path.join(data_dir, item['target_slat'])) + target_feats, target_coords = torch.from_numpy(_target_data['feats']), torch.from_numpy(_target_data['coords']) + if self.random_sample > 0: + random_sample = min(self.random_sample, target_feats.shape[0]) + idxs = np.random.choice(target_feats.shape[0], random_sample, replace=False) + target_feats = target_feats[idxs] + target_coords = target_coords[idxs] + + if torch.isnan(target_feats).any() or torch.isnan(target_coords).any(): + raise ValueError("NaN values found in target_feats or target_coords") + + # Load and convert images to tensors + source_data_path = os.path.join(data_dir, item['source_image']) + source_data = json.load(open(source_data_path, "r")) + + data_dir = os.path.dirname(source_data_path) + _data_len = len(source_data["frames"]) + random_idx = random.randint(0, _data_len - 1) + + if self.num_views > 1: + # if random.random() < 1.: + # rand_interval = random.randint(1,4) + # random_idxs = [(random_idx + i * rand_interval) % _data_len for i in range(self.num_views)] + # else: + # random_idxs = np.random.choice(_data_len, self.num_views, replace=False).tolist() + random_idxs = np.random.choice(_data_len, self.num_views, replace=False).tolist() + _frame_ids = [source_data["frames"][i]["file_path"].split("/")[-1].split(".")[0] for i in random_idxs] + sample_extrinsics = np.concatenate([np.array(source_data["frames"][i]["transform_matrix"])[None] for i in random_idxs], axis=0) + ref_paths = [os.path.join(data_dir, _frame_id + ".png") for _frame_id in _frame_ids] + ref = torch.cat([TF.to_tensor(Image.open(ref_path)).float()[None] for ref_path in ref_paths], dim=0) + ref = ref[:,:3] * ref[:,3:] # + (1 - ref[:,3:]) + if self.task == "normal": + exit("Not implemented") + elif self.task == "color": + source=ref + elif self.task == "nocs": + source_paths = [os.path.join(data_dir, "depth", _frame_id + "_depth.exr") for _frame_id in _frame_ids] + source = np.concatenate([pyexr.read(source_path)[...,0][None] for source_path in source_paths], axis=0) + cam_fov = torch.cat([torch.tensor(source_data["frames"][random_idx]["camera_angle_x"])[None] for random_idx in random_idxs], dim=0) + sample_intrinsics = utils3d.torch.intrinsics_from_fov_xy(cam_fov, cam_fov) + sample_intrinsics[..., :2, :] *= source.shape[1] + source = blender_depth_2_nocs(source, sample_intrinsics.numpy(), sample_extrinsics) + sample_extrinsics = torch.inverse(torch.from_numpy(sample_extrinsics).float()) + sample_intrinsics[..., :2, :] /= source.shape[1] + source = torch.from_numpy(source).permute(0, 3, 1, 2).float() + else: + _light_name = list(source_data["frames"].keys())[random_idx] + _light_data = source_data["frames"][_light_name] + random_view_idx = random.randint(0, len(_light_data) - 1) + _frame_data = _light_data[random_view_idx] + _frame_id = f"{random_view_idx:03d}_hdri_{random_idx:02d}" + _gt_frame_id = f"{random_view_idx:03d}" + _transform_matrix = _frame_data["transform_matrix"] + _transform_matrix = np.array(_transform_matrix) + ref_path = os.path.join(data_dir, _frame_id + ".png") + ref = Image.open(ref_path) + ref = TF.to_tensor(ref).float() + ref = ref[:3] * ref[3] # + (1 - ref[3]) + if self.task == "normal": + source_path = os.path.join(data_dir, "normal", _gt_frame_id + "_normal.exr") + source = pyexr.read(source_path) + source = blender_world_normal_2_camera(source, _transform_matrix) + source = torch.from_numpy(source).permute(2, 0, 1).float() + elif self.task == "color": + source=ref + elif self.task == "nocs": + source_path = os.path.join(data_dir, "depth", _gt_frame_id + "_depth.exr") + source = pyexr.read(source_path)[...,0] + cam_fov = _frame_data["camera_angle_x"] + intrinsics = utils3d.torch.intrinsics_from_fov_xy(torch.tensor(cam_fov), torch.tensor(cam_fov)) + intrinsics[..., :2, :] *= source.shape[0] + source = blender_depth_2_nocs(source[None], intrinsics.numpy()[None], _transform_matrix[None])[0] + source = torch.from_numpy(source).permute(2, 0, 1).float() + if self.rayembedding: + blender_cam_fov = torch.tensor(_frame_data["camera_angle_x"]).float() + blender_cam_transform = torch.from_numpy(_transform_matrix).float() + + # Apply source augmentation if specified + if self.source_aug is not None and random.random() < self.source_aug_prob: + source = self.source_aug(source) + + # Return with random condition + data_dict = dict(source_image=source, ref_image=ref) + if self.stage == 1: + data_dict.update(target_ss_latents=target_ss_latents) + if self.num_views > 1: + data_dict.update(batch_extrinsics=sample_extrinsics, batch_intrinsics=sample_intrinsics) + else: + data_dict.update(target_feats=target_feats, target_coords=target_coords) + if self.num_views > 1: + data_dict.update(batch_extrinsics=sample_extrinsics, batch_intrinsics=sample_intrinsics) + if self.rayembedding: + data_dict.update(blender_cam_fov=blender_cam_fov, blender_cam_transform=blender_cam_transform) + return data_dict + +def custom_collate(batch): + """ + Custom collate function that handles sparse tensors along with other batch elements. + + Args: + batch: List of dictionaries containing 'target_feats', 'target_coords', 'condition_feats', 'condition_coords', 'source' and 'ref' + + Returns: + Dictionary with batched data + """ + # Initialize lists to hold the batched data + if 'target_ss_latents' in batch[0]: + batched_ss_latents = [] + else: + batched_feats = [] + batched_coords = [] + batched_source = [] + batched_ref = [] + if 'batch_extrinsics' in batch[0] and 'batch_intrinsics' in batch[0]: + batched_extrinsics = [] + batched_intrinsics = [] + if 'blender_cam_fov' in batch[0] and 'blender_cam_transform' in batch[0]: + batched_blender_cam_fov = [] + batched_blender_cam_transform = [] + batch_size = len(batch) + for idx, sample in enumerate(batch): + # Handle target sparse tensor components + if 'target_ss_latents' in sample: + ss_latents = sample['target_ss_latents'] + batched_ss_latents.append(ss_latents) + else: + feats = sample['target_feats'] + coords = sample['target_coords'][..., 1:] + + # Add batch dimension to coordinates + batch_coords = torch.full((coords.shape[0], 1), idx, dtype=coords.dtype) + + batched_feats.append(feats) + batched_coords.append(torch.cat([batch_coords, coords], dim=1)) + + # Handle other batch elements + batched_source.append(sample['source_image']) + batched_ref.append(sample['ref_image']) + + if 'batch_extrinsics' in sample and 'batch_intrinsics' in sample: + batched_extrinsics.append(sample['batch_extrinsics']) + batched_intrinsics.append(sample['batch_intrinsics']) + + if 'blender_cam_fov' in sample and 'blender_cam_transform' in sample: + batched_blender_cam_fov.append(sample['blender_cam_fov']) + batched_blender_cam_transform.append(sample['blender_cam_transform']) + + # Stack source tensors + batched_source = torch.stack(batched_source, dim=0) + batched_ref = torch.stack(batched_ref, dim=0) + batch_data_dict = {'source_image': batched_source, + 'ref_image': batched_ref} + + # Concatenate target features and coordinates + if 'target_ss_latents' in batch[0]: + batched_ss_latents = torch.stack(batched_ss_latents, dim=0) + batch_data_dict['target_ss_latents'] = batched_ss_latents + else: + batched_feats = torch.cat(batched_feats, dim=0) + batched_coords = torch.cat(batched_coords, dim=0) + batch_data_dict['target_feats'] = batched_feats + batch_data_dict['target_coords'] = batched_coords + + if 'batch_extrinsics' in batch[0] and 'batch_intrinsics' in batch[0]: + batched_extrinsics = torch.stack(batched_extrinsics, dim=0) + batched_intrinsics = torch.stack(batched_intrinsics, dim=0) + batch_data_dict['batch_extrinsics'] = batched_extrinsics + batch_data_dict['batch_intrinsics'] = batched_intrinsics + + if 'blender_cam_fov' in batch[0] and 'blender_cam_transform' in batch[0]: + batched_blender_cam_fov = torch.stack(batched_blender_cam_fov, dim=0) + batched_blender_cam_transform = torch.stack(batched_blender_cam_transform, dim=0) + batch_data_dict['blender_cam_fov'] = batched_blender_cam_fov + batch_data_dict['blender_cam_transform'] = batched_blender_cam_transform + + return batch_data_dict + +if __name__ == '__main__': + import matplotlib.pyplot as plt + from tqdm import tqdm + # from augmentation import RandomOcclusion + # Create output directory + output_dir = './dataset_test_results' + os.makedirs(output_dir, exist_ok=True) + + # Initialize dataset + # dataset = NpzDatasetAug( + # json_files=['./data/train.jsonl'], + # random_sample=30720, + # num_views=4, + # task='nocs', + # ) + # dataset = JsonDatasetAug(json_files=['./render_data/train_randombg.jsonl'], task='color', num_views=1, source_aug=RandomOcclusion(occlusion_prob=1.0)) + dataset = JsonDatasetAug(json_files=['./objaverse_data/train_pbr_eevee_evenbg.jsonl'], num_views=6,task='nocs') + + sample = dataset[2] + print(f"Dataset size: {len(dataset)}") + with open(os.path.join(output_dir, 'dataset_info.txt'), 'w') as f: + f.write(f"Dataset size: {len(dataset)}\n") + + sample = dataset[0] + f.write("\nSample keys: " + str(sample.keys()) + "\n") + f.write("\nShapes:\n") + for key, value in sample.items(): + if isinstance(value, torch.Tensor): + f.write(f"{key}: {value.shape}\n") + + # Save sample visualizations + for i in range(min(5, len(dataset))): # Save first 5 samples + fig = plt.figure(figsize=(15, 5)) + sample = dataset[i] + + plt.subplot(132) + plt.imshow(sample['source_image'].permute(1, 2, 0).numpy()) + plt.title('Source') + plt.axis('off') + + from mpl_toolkits.mplot3d import Axes3D + ax = fig.add_subplot(133, projection='3d') + coords = sample['target_coords'][..., 1:].numpy() # [N, 3] + ax.scatter(coords[:, 0], coords[:, 1], coords[:, 2], s=1) + ax.set_xlim([0, 63]) + ax.set_ylim([0, 63]) + ax.set_zlim([0, 63]) + + plt.savefig(os.path.join(output_dir, f'sample_{i}.png'), + bbox_inches='tight', + pad_inches=0.1, + dpi=300) + plt.close(fig) + + print(f"Results saved to {output_dir}") \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/build_metadata.py b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/build_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..0c1f6396a9d11ca99be8eb8ffae22e64472f4ec8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/build_metadata.py @@ -0,0 +1,270 @@ +import os +import shutil +import sys +import time +import importlib +import argparse +import numpy as np +import pandas as pd +from tqdm import tqdm +from easydict import EasyDict as edict +from concurrent.futures import ThreadPoolExecutor +import utils3d + +def get_first_directory(path): + with os.scandir(path) as it: + for entry in it: + if entry.is_dir(): + return entry.name + return None + +def need_process(key): + return key in opt.field or opt.field == ['all'] + +if __name__ == '__main__': + dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}') + + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--field', type=str, default='all', + help='Fields to process, separated by commas') + parser.add_argument('--from_file', action='store_true', + help='Build metadata from file instead of from records of processings.' + + 'Useful when some processing fail to generate records but file already exists.') + dataset_utils.add_args(parser) + opt = parser.parse_args(sys.argv[2:]) + opt = edict(vars(opt)) + + os.makedirs(opt.output_dir, exist_ok=True) + os.makedirs(os.path.join(opt.output_dir, 'merged_records'), exist_ok=True) + + opt.field = opt.field.split(',') + + timestamp = str(int(time.time())) + + # get file list + if os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')): + print('Loading previous metadata...') + metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv')) + else: + metadata = dataset_utils.get_metadata(**opt) + metadata.set_index('sha256', inplace=True) + + # merge downloaded + df_files = [f for f in os.listdir(opt.output_dir) if f.startswith('downloaded_') and f.endswith('.csv')] + df_parts = [] + for f in df_files: + try: + df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f))) + except: + pass + if len(df_parts) > 0: + df = pd.concat(df_parts) + df.set_index('sha256', inplace=True) + if 'local_path' in metadata.columns: + metadata.update(df, overwrite=True) + else: + metadata = metadata.join(df, on='sha256', how='left') + for f in df_files: + shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}')) + + # detect models + image_models = [] + if os.path.exists(os.path.join(opt.output_dir, 'features')): + image_models = os.listdir(os.path.join(opt.output_dir, 'features')) + latent_models = [] + if os.path.exists(os.path.join(opt.output_dir, 'latents')): + latent_models = os.listdir(os.path.join(opt.output_dir, 'latents')) + ss_latent_models = [] + if os.path.exists(os.path.join(opt.output_dir, 'ss_latents')): + ss_latent_models = os.listdir(os.path.join(opt.output_dir, 'ss_latents')) + print(f'Image models: {image_models}') + print(f'Latent models: {latent_models}') + print(f'Sparse Structure latent models: {ss_latent_models}') + + if 'rendered' not in metadata.columns: + metadata['rendered'] = [False] * len(metadata) + if 'voxelized' not in metadata.columns: + metadata['voxelized'] = [False] * len(metadata) + if 'num_voxels' not in metadata.columns: + metadata['num_voxels'] = [0] * len(metadata) + if 'cond_rendered' not in metadata.columns: + metadata['cond_rendered'] = [False] * len(metadata) + for model in image_models: + if f'feature_{model}' not in metadata.columns: + metadata[f'feature_{model}'] = [False] * len(metadata) + for model in latent_models: + if f'latent_{model}' not in metadata.columns: + metadata[f'latent_{model}'] = [False] * len(metadata) + for model in ss_latent_models: + if f'ss_latent_{model}' not in metadata.columns: + metadata[f'ss_latent_{model}'] = [False] * len(metadata) + + # merge rendered + df_files = [f for f in os.listdir(opt.output_dir) if f.startswith('rendered_') and f.endswith('.csv')] + df_parts = [] + for f in df_files: + try: + df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f))) + except: + pass + if len(df_parts) > 0: + df = pd.concat(df_parts) + df.set_index('sha256', inplace=True) + metadata.update(df, overwrite=True) + for f in df_files: + shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}')) + + # merge voxelized + df_files = [f for f in os.listdir(opt.output_dir) if f.startswith('voxelized_') and f.endswith('.csv')] + df_parts = [] + for f in df_files: + try: + df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f))) + except: + pass + if len(df_parts) > 0: + df = pd.concat(df_parts) + df.set_index('sha256', inplace=True) + metadata.update(df, overwrite=True) + for f in df_files: + shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}')) + + # merge cond_rendered + df_files = [f for f in os.listdir(opt.output_dir) if f.startswith('cond_rendered_') and f.endswith('.csv')] + df_parts = [] + for f in df_files: + try: + df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f))) + except: + pass + if len(df_parts) > 0: + df = pd.concat(df_parts) + df.set_index('sha256', inplace=True) + metadata.update(df, overwrite=True) + for f in df_files: + shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}')) + + # merge features + for model in image_models: + df_files = [f for f in os.listdir(opt.output_dir) if f.startswith(f'feature_{model}_') and f.endswith('.csv')] + df_parts = [] + for f in df_files: + try: + df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f))) + except: + pass + if len(df_parts) > 0: + df = pd.concat(df_parts) + df.set_index('sha256', inplace=True) + metadata.update(df, overwrite=True) + for f in df_files: + shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}')) + + # merge latents + for model in latent_models: + df_files = [f for f in os.listdir(opt.output_dir) if f.startswith(f'latent_{model}_') and f.endswith('.csv')] + df_parts = [] + for f in df_files: + try: + df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f))) + except: + pass + if len(df_parts) > 0: + df = pd.concat(df_parts) + df.set_index('sha256', inplace=True) + metadata.update(df, overwrite=True) + for f in df_files: + shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}')) + + # merge sparse structure latents + for model in ss_latent_models: + df_files = [f for f in os.listdir(opt.output_dir) if f.startswith(f'ss_latent_{model}_') and f.endswith('.csv')] + df_parts = [] + for f in df_files: + try: + df_parts.append(pd.read_csv(os.path.join(opt.output_dir, f))) + except: + pass + if len(df_parts) > 0: + df = pd.concat(df_parts) + df.set_index('sha256', inplace=True) + metadata.update(df, overwrite=True) + for f in df_files: + shutil.move(os.path.join(opt.output_dir, f), os.path.join(opt.output_dir, 'merged_records', f'{timestamp}_{f}')) + + # build metadata from files + if opt.from_file: + with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor, \ + tqdm(total=len(metadata), desc="Building metadata") as pbar: + def worker(sha256): + try: + if need_process('rendered') and metadata.loc[sha256, 'rendered'] == False and \ + os.path.exists(os.path.join(opt.output_dir, 'renders', sha256, 'transforms.json')): + metadata.loc[sha256, 'rendered'] = True + if need_process('voxelized') and metadata.loc[sha256, 'rendered'] == True and metadata.loc[sha256, 'voxelized'] == False and \ + os.path.exists(os.path.join(opt.output_dir, 'voxels', f'{sha256}.ply')): + try: + pts = utils3d.io.read_ply(os.path.join(opt.output_dir, 'voxels', f'{sha256}.ply'))[0] + metadata.loc[sha256, 'voxelized'] = True + metadata.loc[sha256, 'num_voxels'] = len(pts) + except Exception as e: + pass + if need_process('cond_rendered') and metadata.loc[sha256, 'cond_rendered'] == False and \ + os.path.exists(os.path.join(opt.output_dir, 'renders_cond', sha256, 'transforms.json')): + metadata.loc[sha256, 'cond_rendered'] = True + for model in image_models: + if need_process(f'feature_{model}') and \ + metadata.loc[sha256, f'feature_{model}'] == False and \ + metadata.loc[sha256, 'rendered'] == True and \ + metadata.loc[sha256, 'voxelized'] == True and \ + os.path.exists(os.path.join(opt.output_dir, 'features', model, f'{sha256}.npz')): + metadata.loc[sha256, f'feature_{model}'] = True + for model in latent_models: + if need_process(f'latent_{model}') and \ + metadata.loc[sha256, f'latent_{model}'] == False and \ + metadata.loc[sha256, 'rendered'] == True and \ + metadata.loc[sha256, 'voxelized'] == True and \ + os.path.exists(os.path.join(opt.output_dir, 'latents', model, f'{sha256}.npz')): + metadata.loc[sha256, f'latent_{model}'] = True + for model in ss_latent_models: + if need_process(f'ss_latent_{model}') and \ + metadata.loc[sha256, f'ss_latent_{model}'] == False and \ + metadata.loc[sha256, 'voxelized'] == True and \ + os.path.exists(os.path.join(opt.output_dir, 'ss_latents', model, f'{sha256}.npz')): + metadata.loc[sha256, f'ss_latent_{model}'] = True + pbar.update() + except Exception as e: + print(f'Error processing {sha256}: {e}') + pbar.update() + + executor.map(worker, metadata.index) + executor.shutdown(wait=True) + + # statistics + metadata.to_csv(os.path.join(opt.output_dir, 'metadata.csv')) + num_downloaded = metadata['local_path'].count() if 'local_path' in metadata.columns else 0 + with open(os.path.join(opt.output_dir, 'statistics.txt'), 'w') as f: + f.write('Statistics:\n') + f.write(f' - Number of assets: {len(metadata)}\n') + f.write(f' - Number of assets downloaded: {num_downloaded}\n') + f.write(f' - Number of assets rendered: {metadata["rendered"].sum()}\n') + f.write(f' - Number of assets voxelized: {metadata["voxelized"].sum()}\n') + if len(image_models) != 0: + f.write(f' - Number of assets with image features extracted:\n') + for model in image_models: + f.write(f' - {model}: {metadata[f"feature_{model}"].sum()}\n') + if len(latent_models) != 0: + f.write(f' - Number of assets with latents extracted:\n') + for model in latent_models: + f.write(f' - {model}: {metadata[f"latent_{model}"].sum()}\n') + if len(ss_latent_models) != 0: + f.write(f' - Number of assets with sparse structure latents extracted:\n') + for model in ss_latent_models: + f.write(f' - {model}: {metadata[f"ss_latent_{model}"].sum()}\n') + f.write(f' - Number of assets with captions: {metadata["captions"].count()}\n') + f.write(f' - Number of assets with image conditions: {metadata["cond_rendered"].sum()}\n') + + with open(os.path.join(opt.output_dir, 'statistics.txt'), 'r') as f: + print(f.read()) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/datasets/3D-FUTURE.py b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/datasets/3D-FUTURE.py new file mode 100644 index 0000000000000000000000000000000000000000..a5ccc632de8e5a1d4f4a3b2b3024b8a3361e12c4 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/datasets/3D-FUTURE.py @@ -0,0 +1,97 @@ +import os +import re +import argparse +import zipfile +from concurrent.futures import ThreadPoolExecutor +from tqdm import tqdm +import pandas as pd +from utils import get_file_hash + + +def add_args(parser: argparse.ArgumentParser): + pass + + +def get_metadata(**kwargs): + metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/3D-FUTURE.csv") + return metadata + + +def download(metadata, output_dir, **kwargs): + os.makedirs(output_dir, exist_ok=True) + + if not os.path.exists(os.path.join(output_dir, 'raw', '3D-FUTURE-model.zip')): + print("\033[93m") + print("3D-FUTURE have to be downloaded manually") + print(f"Please download the 3D-FUTURE-model.zip file and place it in the {output_dir}/raw directory") + print("Visit https://tianchi.aliyun.com/specials/promotion/alibaba-3d-future for more information") + print("\033[0m") + raise FileNotFoundError("3D-FUTURE-model.zip not found") + + downloaded = {} + metadata = metadata.set_index("file_identifier") + with zipfile.ZipFile(os.path.join(output_dir, 'raw', '3D-FUTURE-model.zip')) as zip_ref: + all_names = zip_ref.namelist() + instances = [instance[:-1] for instance in all_names if re.match(r"^3D-FUTURE-model/[^/]+/$", instance)] + instances = list(filter(lambda x: x in metadata.index, instances)) + + with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor, \ + tqdm(total=len(instances), desc="Extracting") as pbar: + def worker(instance: str) -> str: + try: + instance_files = list(filter(lambda x: x.startswith(f"{instance}/") and not x.endswith("/"), all_names)) + zip_ref.extractall(os.path.join(output_dir, 'raw'), members=instance_files) + sha256 = get_file_hash(os.path.join(output_dir, 'raw', f"{instance}/image.jpg")) + pbar.update() + return sha256 + except Exception as e: + pbar.update() + print(f"Error extracting for {instance}: {e}") + return None + + sha256s = executor.map(worker, instances) + executor.shutdown(wait=True) + + for k, sha256 in zip(instances, sha256s): + if sha256 is not None: + if sha256 == metadata.loc[k, "sha256"]: + downloaded[sha256] = os.path.join("raw", f"{k}/raw_model.obj") + else: + print(f"Error downloading {k}: sha256s do not match") + + return pd.DataFrame(downloaded.items(), columns=['sha256', 'local_path']) + + +def foreach_instance(metadata, output_dir, func, max_workers=None, desc='Processing objects') -> pd.DataFrame: + import os + from concurrent.futures import ThreadPoolExecutor + from tqdm import tqdm + + # load metadata + metadata = metadata.to_dict('records') + + # processing objects + records = [] + max_workers = max_workers or os.cpu_count() + try: + with ThreadPoolExecutor(max_workers=max_workers) as executor, \ + tqdm(total=len(metadata), desc=desc) as pbar: + def worker(metadatum): + try: + local_path = metadatum['local_path'] + sha256 = metadatum['sha256'] + file = os.path.join(output_dir, local_path) + record = func(file, sha256) + if record is not None: + records.append(record) + pbar.update() + except Exception as e: + print(f"Error processing object {sha256}: {e}") + pbar.update() + + executor.map(worker, metadata) + executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + return pd.DataFrame.from_records(records) diff --git a/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/datasets/ABO.py b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/datasets/ABO.py new file mode 100644 index 0000000000000000000000000000000000000000..b0aba22c2c4980b024091058a458811ab93805dd --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/datasets/ABO.py @@ -0,0 +1,96 @@ +import os +import re +import argparse +import tarfile +from concurrent.futures import ThreadPoolExecutor +from tqdm import tqdm +import pandas as pd +from utils import get_file_hash + + +def add_args(parser: argparse.ArgumentParser): + pass + + +def get_metadata(**kwargs): + metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/ABO.csv") + return metadata + + +def download(metadata, output_dir, **kwargs): + os.makedirs(os.path.join(output_dir, 'raw'), exist_ok=True) + + if not os.path.exists(os.path.join(output_dir, 'raw', 'abo-3dmodels.tar')): + try: + os.makedirs(os.path.join(output_dir, 'raw'), exist_ok=True) + os.system(f"wget -O {output_dir}/raw/abo-3dmodels.tar https://amazon-berkeley-objects.s3.amazonaws.com/archives/abo-3dmodels.tar") + except: + print("\033[93m") + print("Error downloading ABO dataset. Please check your internet connection and try again.") + print("Or, you can manually download the abo-3dmodels.tar file and place it in the {output_dir}/raw directory") + print("Visit https://amazon-berkeley-objects.s3.amazonaws.com/index.html for more information") + print("\033[0m") + raise FileNotFoundError("Error downloading ABO dataset") + + downloaded = {} + metadata = metadata.set_index("file_identifier") + with tarfile.open(os.path.join(output_dir, 'raw', 'abo-3dmodels.tar')) as tar: + with ThreadPoolExecutor(max_workers=1) as executor, \ + tqdm(total=len(metadata), desc="Extracting") as pbar: + def worker(instance: str) -> str: + try: + tar.extract(f"3dmodels/original/{instance}", path=os.path.join(output_dir, 'raw')) + sha256 = get_file_hash(os.path.join(output_dir, 'raw/3dmodels/original', instance)) + pbar.update() + return sha256 + except Exception as e: + pbar.update() + print(f"Error extracting for {instance}: {e}") + return None + + sha256s = executor.map(worker, metadata.index) + executor.shutdown(wait=True) + + for k, sha256 in zip(metadata.index, sha256s): + if sha256 is not None: + if sha256 == metadata.loc[k, "sha256"]: + downloaded[sha256] = os.path.join('raw/3dmodels/original', k) + else: + print(f"Error downloading {k}: sha256s do not match") + + return pd.DataFrame(downloaded.items(), columns=['sha256', 'local_path']) + + +def foreach_instance(metadata, output_dir, func, max_workers=None, desc='Processing objects') -> pd.DataFrame: + import os + from concurrent.futures import ThreadPoolExecutor + from tqdm import tqdm + + # load metadata + metadata = metadata.to_dict('records') + + # processing objects + records = [] + max_workers = max_workers or os.cpu_count() + try: + with ThreadPoolExecutor(max_workers=max_workers) as executor, \ + tqdm(total=len(metadata), desc=desc) as pbar: + def worker(metadatum): + try: + local_path = metadatum['local_path'] + sha256 = metadatum['sha256'] + file = os.path.join(output_dir, local_path) + record = func(file, sha256) + if record is not None: + records.append(record) + pbar.update() + except Exception as e: + print(f"Error processing object {sha256}: {e}") + pbar.update() + + executor.map(worker, metadata) + executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + return pd.DataFrame.from_records(records) diff --git a/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/datasets/HSSD.py b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/datasets/HSSD.py new file mode 100644 index 0000000000000000000000000000000000000000..465e6a140010d0b33ba6435e8129825599dda5db --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/datasets/HSSD.py @@ -0,0 +1,103 @@ +import os +import re +import argparse +import tarfile +from concurrent.futures import ThreadPoolExecutor +from tqdm import tqdm +import pandas as pd +import huggingface_hub +from utils import get_file_hash + + +def add_args(parser: argparse.ArgumentParser): + pass + + +def get_metadata(**kwargs): + metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/HSSD.csv") + return metadata + + +def download(metadata, output_dir, **kwargs): + os.makedirs(os.path.join(output_dir, 'raw'), exist_ok=True) + + # check login + try: + huggingface_hub.whoami() + except: + print("\033[93m") + print("Haven't logged in to the Hugging Face Hub.") + print("Visit https://huggingface.co/settings/tokens to get a token.") + print("\033[0m") + huggingface_hub.login() + + try: + huggingface_hub.hf_hub_download(repo_id="hssd/hssd-models", filename="README.md", repo_type="dataset") + except: + print("\033[93m") + print("Error downloading HSSD dataset.") + print("Check if you have access to the HSSD dataset.") + print("Visit https://huggingface.co/datasets/hssd/hssd-models for more information") + print("\033[0m") + + downloaded = {} + metadata = metadata.set_index("file_identifier") + with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor, \ + tqdm(total=len(metadata), desc="Downloading") as pbar: + def worker(instance: str) -> str: + try: + huggingface_hub.hf_hub_download(repo_id="hssd/hssd-models", filename=instance, repo_type="dataset", local_dir=os.path.join(output_dir, 'raw')) + sha256 = get_file_hash(os.path.join(output_dir, 'raw', instance)) + pbar.update() + return sha256 + except Exception as e: + pbar.update() + print(f"Error extracting for {instance}: {e}") + return None + + sha256s = executor.map(worker, metadata.index) + executor.shutdown(wait=True) + + for k, sha256 in zip(metadata.index, sha256s): + if sha256 is not None: + if sha256 == metadata.loc[k, "sha256"]: + downloaded[sha256] = os.path.join('raw', k) + else: + print(f"Error downloading {k}: sha256s do not match") + + return pd.DataFrame(downloaded.items(), columns=['sha256', 'local_path']) + + +def foreach_instance(metadata, output_dir, func, max_workers=None, desc='Processing objects') -> pd.DataFrame: + import os + from concurrent.futures import ThreadPoolExecutor + from tqdm import tqdm + + # load metadata + metadata = metadata.to_dict('records') + + # processing objects + records = [] + max_workers = max_workers or os.cpu_count() + try: + with ThreadPoolExecutor(max_workers=max_workers) as executor, \ + tqdm(total=len(metadata), desc=desc) as pbar: + def worker(metadatum): + try: + local_path = metadatum['local_path'] + sha256 = metadatum['sha256'] + file = os.path.join(output_dir, local_path) + record = func(file, sha256) + if record is not None: + records.append(record) + pbar.update() + except Exception as e: + print(f"Error processing object {sha256}: {e}") + pbar.update() + + executor.map(worker, metadata) + executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + return pd.DataFrame.from_records(records) diff --git a/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/datasets/ObjaverseXL.py b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/datasets/ObjaverseXL.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f5c76c07701b198a20af32fc87c81614ae7f79 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/datasets/ObjaverseXL.py @@ -0,0 +1,92 @@ +import os +import argparse +from concurrent.futures import ThreadPoolExecutor +from tqdm import tqdm +import pandas as pd +import objaverse.xl as oxl +from utils import get_file_hash + + +def add_args(parser: argparse.ArgumentParser): + parser.add_argument('--source', type=str, default='sketchfab', + help='Data source to download annotations from (github, sketchfab)') + + +def get_metadata(source, **kwargs): + if source == 'sketchfab': + metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/ObjaverseXL_sketchfab.csv") + elif source == 'github': + metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/ObjaverseXL_github.csv") + else: + raise ValueError(f"Invalid source: {source}") + return metadata + + +def download(metadata, output_dir, **kwargs): + os.makedirs(os.path.join(output_dir, 'raw'), exist_ok=True) + + # download annotations + annotations = oxl.get_annotations() + annotations = annotations[annotations['sha256'].isin(metadata['sha256'].values)] + + # download and render objects + file_paths = oxl.download_objects( + annotations, + download_dir=os.path.join(output_dir, "raw"), + save_repo_format="zip", + ) + + downloaded = {} + metadata = metadata.set_index("file_identifier") + for k, v in file_paths.items(): + sha256 = metadata.loc[k, "sha256"] + downloaded[sha256] = os.path.relpath(v, output_dir) + + return pd.DataFrame(downloaded.items(), columns=['sha256', 'local_path']) + + +def foreach_instance(metadata, output_dir, func, max_workers=None, desc='Processing objects') -> pd.DataFrame: + import os + from concurrent.futures import ThreadPoolExecutor + from tqdm import tqdm + import tempfile + import zipfile + + # load metadata + metadata = metadata.to_dict('records') + + # processing objects + records = [] + max_workers = max_workers or os.cpu_count() + try: + with ThreadPoolExecutor(max_workers=max_workers) as executor, \ + tqdm(total=len(metadata), desc=desc) as pbar: + def worker(metadatum): + try: + local_path = metadatum['local_path'] + sha256 = metadatum['sha256'] + if local_path.startswith('raw/github/repos/'): + path_parts = local_path.split('/') + file_name = os.path.join(*path_parts[5:]) + zip_file = os.path.join(output_dir, *path_parts[:5]) + with tempfile.TemporaryDirectory() as tmp_dir: + with zipfile.ZipFile(zip_file, 'r') as zip_ref: + zip_ref.extractall(tmp_dir) + file = os.path.join(tmp_dir, file_name) + record = func(file, sha256) + else: + file = os.path.join(output_dir, local_path) + record = func(file, sha256) + if record is not None: + records.append(record) + pbar.update() + except Exception as e: + print(f"Error processing object {sha256}: {e}") + pbar.update() + + executor.map(worker, metadata) + executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + return pd.DataFrame.from_records(records) diff --git a/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/datasets/Toys4k.py b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/datasets/Toys4k.py new file mode 100644 index 0000000000000000000000000000000000000000..378afdaa87b1b2a5962a33e7e55efa9540f28436 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/datasets/Toys4k.py @@ -0,0 +1,92 @@ +import os +import re +import argparse +import zipfile +from concurrent.futures import ThreadPoolExecutor +from tqdm import tqdm +import pandas as pd +from utils import get_file_hash + + +def add_args(parser: argparse.ArgumentParser): + pass + + +def get_metadata(**kwargs): + metadata = pd.read_csv("hf://datasets/JeffreyXiang/TRELLIS-500K/Toys4k.csv") + return metadata + + +def download(metadata, output_dir, **kwargs): + os.makedirs(output_dir, exist_ok=True) + + if not os.path.exists(os.path.join(output_dir, 'raw', 'toys4k_blend_files.zip')): + print("\033[93m") + print("Toys4k have to be downloaded manually") + print(f"Please download the toys4k_blend_files.zip file and place it in the {output_dir}/raw directory") + print("Visit https://github.com/rehg-lab/lowshot-shapebias/tree/main/toys4k for more information") + print("\033[0m") + raise FileNotFoundError("toys4k_blend_files.zip not found") + + downloaded = {} + metadata = metadata.set_index("file_identifier") + with zipfile.ZipFile(os.path.join(output_dir, 'raw', 'toys4k_blend_files.zip')) as zip_ref: + with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor, \ + tqdm(total=len(metadata), desc="Extracting") as pbar: + def worker(instance: str) -> str: + try: + zip_ref.extract(os.path.join('toys4k_blend_files', instance), os.path.join(output_dir, 'raw')) + sha256 = get_file_hash(os.path.join(output_dir, 'raw/toys4k_blend_files', instance)) + pbar.update() + return sha256 + except Exception as e: + pbar.update() + print(f"Error extracting for {instance}: {e}") + return None + + sha256s = executor.map(worker, metadata.index) + executor.shutdown(wait=True) + + for k, sha256 in zip(metadata.index, sha256s): + if sha256 is not None: + if sha256 == metadata.loc[k, "sha256"]: + downloaded[sha256] = os.path.join("raw/toys4k_blend_files", k) + else: + print(f"Error downloading {k}: sha256s do not match") + + return pd.DataFrame(downloaded.items(), columns=['sha256', 'local_path']) + + +def foreach_instance(metadata, output_dir, func, max_workers=None, desc='Processing objects') -> pd.DataFrame: + import os + from concurrent.futures import ThreadPoolExecutor + from tqdm import tqdm + + # load metadata + metadata = metadata.to_dict('records') + + # processing objects + records = [] + max_workers = max_workers or os.cpu_count() + try: + with ThreadPoolExecutor(max_workers=max_workers) as executor, \ + tqdm(total=len(metadata), desc=desc) as pbar: + def worker(metadatum): + try: + local_path = metadatum['local_path'] + sha256 = metadatum['sha256'] + file = os.path.join(output_dir, local_path) + record = func(file, sha256) + if record is not None: + records.append(record) + pbar.update() + except Exception as e: + print(f"Error processing object {sha256}: {e}") + pbar.update() + + executor.map(worker, metadata) + executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + return pd.DataFrame.from_records(records) diff --git a/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/download.py b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/download.py new file mode 100644 index 0000000000000000000000000000000000000000..36e684ff5e61105d8c69c101291dc8fa4415af3d --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/download.py @@ -0,0 +1,52 @@ +import os +import copy +import sys +import importlib +import argparse +import pandas as pd +from easydict import EasyDict as edict + +if __name__ == '__main__': + dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}') + + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + dataset_utils.add_args(parser) + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + opt = parser.parse_args(sys.argv[2:]) + opt = edict(vars(opt)) + + os.makedirs(opt.output_dir, exist_ok=True) + + # get file list + if not os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')): + raise ValueError('metadata.csv not found') + metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv')) + if opt.instances is None: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + if 'local_path' in metadata.columns: + metadata = metadata[metadata['local_path'].isna()] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + + print(f'Processing {len(metadata)} objects...') + + # process objects + downloaded = dataset_utils.download(metadata, **opt) + downloaded.to_csv(os.path.join(opt.output_dir, f'downloaded_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/encode_latent.py b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/encode_latent.py new file mode 100644 index 0000000000000000000000000000000000000000..d8c4770909d56ca3820f7aacd09bcf9b8988b9ac --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/encode_latent.py @@ -0,0 +1,127 @@ +import os +import sys +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) +import copy +import json +import argparse +import torch +import numpy as np +import pandas as pd +from tqdm import tqdm +from easydict import EasyDict as edict +from concurrent.futures import ThreadPoolExecutor +from queue import Queue + +import trellis.models as models +import trellis.modules.sparse as sp + + +torch.set_grad_enabled(False) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--feat_model', type=str, default='dinov2_vitl14_reg', + help='Feature model') + parser.add_argument('--enc_pretrained', type=str, default='JeffreyXiang/TRELLIS-image-large/ckpts/slat_enc_swin8_B_64l8_fp16', + help='Pretrained encoder model') + parser.add_argument('--model_root', type=str, default='results', + help='Root directory of models') + parser.add_argument('--enc_model', type=str, default=None, + help='Encoder model. if specified, use this model instead of pretrained model') + parser.add_argument('--ckpt', type=str, default=None, + help='Checkpoint to load') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + opt = parser.parse_args() + opt = edict(vars(opt)) + + if opt.enc_model is None: + latent_name = f'{opt.feat_model}_{opt.enc_pretrained.split("/")[-1]}' + encoder = models.from_pretrained(opt.enc_pretrained).eval().cuda() + else: + latent_name = f'{opt.feat_model}_{opt.enc_model}_{opt.ckpt}' + cfg = edict(json.load(open(os.path.join(opt.model_root, opt.enc_model, 'config.json'), 'r'))) + encoder = getattr(models, cfg.models.encoder.name)(**cfg.models.encoder.args).cuda() + ckpt_path = os.path.join(opt.model_root, opt.enc_model, 'ckpts', f'encoder_{opt.ckpt}.pt') + encoder.load_state_dict(torch.load(ckpt_path), strict=False) + encoder.eval() + print(f'Loaded model from {ckpt_path}') + + os.makedirs(os.path.join(opt.output_dir, 'latents', latent_name), exist_ok=True) + + # get file list + if os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')): + metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv')) + else: + raise ValueError('metadata.csv not found') + if opt.instances is not None: + with open(opt.instances, 'r') as f: + sha256s = [line.strip() for line in f] + metadata = metadata[metadata['sha256'].isin(sha256s)] + else: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + metadata = metadata[metadata[f'feature_{opt.feat_model}'] == True] + if f'latent_{latent_name}' in metadata.columns: + metadata = metadata[metadata[f'latent_{latent_name}'] == False] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + # filter out objects that are already processed + sha256s = list(metadata['sha256'].values) + for sha256 in copy.copy(sha256s): + if os.path.exists(os.path.join(opt.output_dir, 'latents', latent_name, f'{sha256}.npz')): + records.append({'sha256': sha256, f'latent_{latent_name}': True}) + sha256s.remove(sha256) + + # encode latents + load_queue = Queue(maxsize=4) + try: + with ThreadPoolExecutor(max_workers=32) as loader_executor, \ + ThreadPoolExecutor(max_workers=32) as saver_executor: + def loader(sha256): + try: + feats = np.load(os.path.join(opt.output_dir, 'features', opt.feat_model, f'{sha256}.npz')) + load_queue.put((sha256, feats)) + except Exception as e: + print(f"Error loading features for {sha256}: {e}") + loader_executor.map(loader, sha256s) + + def saver(sha256, pack): + save_path = os.path.join(opt.output_dir, 'latents', latent_name, f'{sha256}.npz') + np.savez_compressed(save_path, **pack) + records.append({'sha256': sha256, f'latent_{latent_name}': True}) + + for _ in tqdm(range(len(sha256s)), desc="Extracting latents"): + sha256, feats = load_queue.get() + feats = sp.SparseTensor( + feats = torch.from_numpy(feats['patchtokens']).float(), + coords = torch.cat([ + torch.zeros(feats['patchtokens'].shape[0], 1).int(), + torch.from_numpy(feats['indices']).int(), + ], dim=1), + ).cuda() + latent = encoder(feats, sample_posterior=False) + assert torch.isfinite(latent.feats).all(), "Non-finite latent" + pack = { + 'feats': latent.feats.cpu().numpy().astype(np.float32), + 'coords': latent.coords[:, 1:].cpu().numpy().astype(np.uint8), + } + saver_executor.submit(saver, sha256, pack) + + saver_executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + records = pd.DataFrame.from_records(records) + records.to_csv(os.path.join(opt.output_dir, f'latent_{latent_name}_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/encode_ss_latent.py b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/encode_ss_latent.py new file mode 100644 index 0000000000000000000000000000000000000000..c5af5df048524218308dbb4e3a29580fc3b41c20 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/encode_ss_latent.py @@ -0,0 +1,128 @@ +import os +import sys +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) +import copy +import json +import argparse +import torch +import numpy as np +import pandas as pd +import utils3d +from tqdm import tqdm +from easydict import EasyDict as edict +from concurrent.futures import ThreadPoolExecutor +from queue import Queue + +import trellis.models as models + + +torch.set_grad_enabled(False) + + +def get_voxels(instance): + position = utils3d.io.read_ply(os.path.join(opt.output_dir, 'voxels', f'{instance}.ply'))[0] + coords = ((torch.tensor(position) + 0.5) * opt.resolution).int().contiguous() + ss = torch.zeros(1, opt.resolution, opt.resolution, opt.resolution, dtype=torch.long) + ss[:, coords[:, 0], coords[:, 1], coords[:, 2]] = 1 + return ss + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--enc_pretrained', type=str, default='JeffreyXiang/TRELLIS-image-large/ckpts/ss_enc_conv3d_16l8_fp16', + help='Pretrained encoder model') + parser.add_argument('--model_root', type=str, default='results', + help='Root directory of models') + parser.add_argument('--enc_model', type=str, default=None, + help='Encoder model. if specified, use this model instead of pretrained model') + parser.add_argument('--ckpt', type=str, default=None, + help='Checkpoint to load') + parser.add_argument('--resolution', type=int, default=64, + help='Resolution') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + opt = parser.parse_args() + opt = edict(vars(opt)) + + if opt.enc_model is None: + latent_name = f'{opt.enc_pretrained.split("/")[-1]}' + encoder = models.from_pretrained(opt.enc_pretrained).eval().cuda() + else: + latent_name = f'{opt.enc_model}_{opt.ckpt}' + cfg = edict(json.load(open(os.path.join(opt.model_root, opt.enc_model, 'config.json'), 'r'))) + encoder = getattr(models, cfg.models.encoder.name)(**cfg.models.encoder.args).cuda() + ckpt_path = os.path.join(opt.model_root, opt.enc_model, 'ckpts', f'encoder_{opt.ckpt}.pt') + encoder.load_state_dict(torch.load(ckpt_path), strict=False) + encoder.eval() + print(f'Loaded model from {ckpt_path}') + + os.makedirs(os.path.join(opt.output_dir, 'ss_latents', latent_name), exist_ok=True) + + # get file list + if os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')): + metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv')) + else: + raise ValueError('metadata.csv not found') + if opt.instances is not None: + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + metadata = metadata[metadata['sha256'].isin(instances)] + else: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + metadata = metadata[metadata['voxelized'] == True] + if f'ss_latent_{latent_name}' in metadata.columns: + metadata = metadata[metadata[f'ss_latent_{latent_name}'] == False] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + # filter out objects that are already processed + sha256s = list(metadata['sha256'].values) + for sha256 in copy.copy(sha256s): + if os.path.exists(os.path.join(opt.output_dir, 'ss_latents', latent_name, f'{sha256}.npz')): + records.append({'sha256': sha256, f'ss_latent_{latent_name}': True}) + sha256s.remove(sha256) + + # encode latents + load_queue = Queue(maxsize=4) + try: + with ThreadPoolExecutor(max_workers=32) as loader_executor, \ + ThreadPoolExecutor(max_workers=32) as saver_executor: + def loader(sha256): + try: + ss = get_voxels(sha256)[None].float() + load_queue.put((sha256, ss)) + except Exception as e: + print(f"Error loading features for {sha256}: {e}") + loader_executor.map(loader, sha256s) + + def saver(sha256, pack): + save_path = os.path.join(opt.output_dir, 'ss_latents', latent_name, f'{sha256}.npz') + np.savez_compressed(save_path, **pack) + records.append({'sha256': sha256, f'ss_latent_{latent_name}': True}) + + for _ in tqdm(range(len(sha256s)), desc="Extracting latents"): + sha256, ss = load_queue.get() + ss = ss.cuda().float() + latent = encoder(ss, sample_posterior=False) + assert torch.isfinite(latent).all(), "Non-finite latent" + pack = { + 'mean': latent[0].cpu().numpy(), + } + saver_executor.submit(saver, sha256, pack) + + saver_executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + records = pd.DataFrame.from_records(records) + records.to_csv(os.path.join(opt.output_dir, f'ss_latent_{latent_name}_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/extract_feature.py b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/extract_feature.py new file mode 100644 index 0000000000000000000000000000000000000000..7e32caf946c7ca5f18c64e168e110bb67861bf90 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/extract_feature.py @@ -0,0 +1,188 @@ +import os +import copy +import sys +import json +import importlib +import argparse +import torch +import torch.nn.functional as F +import numpy as np +import pandas as pd +import utils3d +from tqdm import tqdm +from easydict import EasyDict as edict +from concurrent.futures import ThreadPoolExecutor +from queue import Queue +from torchvision import transforms +from PIL import Image +from tqdm import tqdm +from concurrent.futures import ThreadPoolExecutor, as_completed + +torch.set_grad_enabled(False) + + +def get_data(frames, sha256): + with ThreadPoolExecutor(max_workers=1) as executor: + def worker(view): + image_path = os.path.join(opt.output_dir, f'render_{subset_name}', sha256, view['file_path'].split('/')[-1]) + try: + image = Image.open(image_path) + except: + print(f"Error loading image {image_path}") + return None + image = image.resize((518, 518), Image.Resampling.LANCZOS) + image = np.array(image).astype(np.float32) / 255 + image = image[:, :, :3] * image[:, :, 3:] + image = torch.from_numpy(image).permute(2, 0, 1).float() + + c2w = torch.tensor(view['transform_matrix']) + c2w[:3, 1:3] *= -1 + extrinsics = torch.inverse(c2w) + fov = view['camera_angle_x'] + intrinsics = utils3d.torch.intrinsics_from_fov_xy(torch.tensor(fov), torch.tensor(fov)) + + return { + 'image': image, + 'extrinsics': extrinsics, + 'intrinsics': intrinsics + } + + datas = executor.map(worker, frames) + for data in datas: + if data is not None: + yield data + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--model', type=str, default='dinov2_vitl14_reg', + help='Feature extraction model') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--batch_size', type=int, default=4) + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + parser.add_argument("subset_name") + opt = parser.parse_args() + opt = edict(vars(opt)) + + subset_name = opt.subset_name + feature_name = opt.model + os.makedirs(os.path.join(opt.output_dir, f'features_{subset_name}', feature_name), exist_ok=True) + + # load model + dinov2_model = torch.hub.load(os.path.join(torch.hub.get_dir(), 'facebookresearch_dinov2_main'), opt.model, source='local',pretrained=True) + # dinov2_model = torch.hub.load('facebookresearch/dinov2', opt.model) + dinov2_model.eval().cuda() + transform = transforms.Compose([ + transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), + ]) + n_patch = 518 // 14 + + # get file list + if os.path.exists(os.path.join(opt.output_dir, f'metadata.csv')): + metadata = pd.read_csv(os.path.join(opt.output_dir, f'metadata.csv')) + else: + raise ValueError(f'metadata.csv not found') + if opt.instances is not None: + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + metadata = metadata[metadata['sha256'].isin(instances)] + else: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + if f'feature_{feature_name}' in metadata.columns: + metadata = metadata[metadata[f'feature_{feature_name}'] == False] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + # filter out objects that are already processed + sha256s = list(metadata['sha256'].values) + valid_sha256s = [] + render_dir = os.path.join(opt.output_dir, f'render_{subset_name}') + + def check_transforms(sha256): + return sha256, os.path.exists(os.path.join(render_dir, sha256, 'transforms.json')) + with ThreadPoolExecutor(max_workers=64) as executor: + futures = [executor.submit(check_transforms, sha256) for sha256 in sha256s] + for future in tqdm(as_completed(futures), total=len(futures), desc="Validating transforms.json"): + sha256, exists = future.result() + if exists: + valid_sha256s.append(sha256) + sha256s = valid_sha256s + + # extract features + load_queue = Queue(maxsize=4) + try: + with ThreadPoolExecutor(max_workers=8) as loader_executor, \ + ThreadPoolExecutor(max_workers=8) as saver_executor: + def loader(sha256): + try: + with open(os.path.join(opt.output_dir, f'render_{subset_name}', sha256, 'transforms.json'), 'r') as f: + metadata = json.load(f) + frames = metadata['frames'] + data = [] + for datum in get_data(frames, sha256): + datum['image'] = transform(datum['image']) + data.append(datum) + positions = utils3d.io.read_ply(os.path.join(opt.output_dir, 'voxels', f'{sha256}.ply'))[0] + load_queue.put((sha256, data, positions)) + except Exception as e: + print(f"Error loading data for {sha256}: {e}") + + loader_executor.map(loader, sha256s) + + def saver(sha256, pack, patchtokens, uv): + pack['patchtokens'] = F.grid_sample( + patchtokens, + uv.unsqueeze(1), + mode='bilinear', + align_corners=False, + ).squeeze(2).permute(0, 2, 1).cpu().numpy() + pack['patchtokens'] = np.mean(pack['patchtokens'], axis=0).astype(np.float16) + save_path = os.path.join(opt.output_dir, f'features_{subset_name}', feature_name, f'{sha256}.npz') + np.savez_compressed(save_path, **pack) + records.append({'sha256': sha256, f'feature_{feature_name}' : True}) + + for _ in tqdm(range(len(sha256s)), desc="Extracting features"): + sha256, data, positions = load_queue.get() + positions = torch.from_numpy(positions).float().cuda() + indices = ((positions + 0.5) * 64).long() + assert torch.all(indices >= 0) and torch.all(indices < 64), "Some vertices are out of bounds" + n_views = len(data) + N = positions.shape[0] + pack = { + 'indices': indices.cpu().numpy().astype(np.uint8), + } + patchtokens_lst = [] + uv_lst = [] + for i in range(0, n_views, opt.batch_size): + batch_data = data[i:i+opt.batch_size] + bs = len(batch_data) + batch_images = torch.stack([d['image'] for d in batch_data]).cuda() + batch_extrinsics = torch.stack([d['extrinsics'] for d in batch_data]).cuda() + batch_intrinsics = torch.stack([d['intrinsics'] for d in batch_data]).cuda() + features = dinov2_model(batch_images, is_training=True) + uv = utils3d.torch.project_cv(positions, batch_extrinsics, batch_intrinsics)[0] * 2 - 1 + patchtokens = features['x_prenorm'][:, dinov2_model.num_register_tokens + 1:].permute(0, 2, 1).reshape(bs, 1024, n_patch, n_patch) + patchtokens_lst.append(patchtokens) + uv_lst.append(uv) + patchtokens = torch.cat(patchtokens_lst, dim=0) + uv = torch.cat(uv_lst, dim=0) + # save features + saver_executor.submit(saver, sha256, pack, patchtokens, uv) + + saver_executor.shutdown(wait=True) + except: + print("Error happened during processing.") + + records = pd.DataFrame.from_records(records) + records.to_csv(os.path.join(opt.output_dir, f'feature_{feature_name}_{opt.rank}.csv'), index=False) + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/extract_ss_latent_dreamverse.py b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/extract_ss_latent_dreamverse.py new file mode 100644 index 0000000000000000000000000000000000000000..daa6cb02131e256325caf5566e4cd569f17c60f8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/extract_ss_latent_dreamverse.py @@ -0,0 +1,129 @@ +import os +import sys +sys.path.append(os.path.join(os.path.dirname(__file__), '..')) +import copy +import json +import argparse +import torch +import numpy as np +import pandas as pd +import utils3d +from tqdm import tqdm +from easydict import EasyDict as edict +from concurrent.futures import ThreadPoolExecutor +from queue import Queue +from tqdm import tqdm + +import trellis.models as models + + +torch.set_grad_enabled(False) + + +def get_voxels(instance): + + position = np.load(os.path.join(opt.output_dir, instance['target_slat']))['coords'] + coords = torch.from_numpy(position[:,1:]).int().contiguous() + ss = torch.zeros(1, opt.resolution, opt.resolution, opt.resolution, dtype=torch.long) + ss[:, coords[:, 0], coords[:, 1], coords[:, 2]] = 1 + return ss + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--save_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--enc_pretrained', type=str, default='weights/TRELLIS-image-large/ckpts/ss_enc_conv3d_16l8_fp16', + help='Pretrained encoder model') + # parser.add_argument('--dec_pretrained', type=str, default='weights/TRELLIS-image-large/ckpts/ss_dec_conv3d_16l8_fp16', + # help='Pretrained encoder model') + parser.add_argument('--model_root', type=str, default='results', + help='Root directory of models') + parser.add_argument('--enc_model', type=str, default=None, + help='Encoder model. if specified, use this model instead of pretrained model') + parser.add_argument('--ckpt', type=str, default=None, + help='Checkpoint to load') + parser.add_argument('--resolution', type=int, default=64, + help='Resolution') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--batch_size', type=str, default=128, + help='Batch size to process') + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + opt = parser.parse_args() + opt = edict(vars(opt)) + + if opt.enc_model is None: + latent_name = f'{opt.enc_pretrained.split("/")[-1]}' + encoder = models.from_pretrained(opt.enc_pretrained).eval().cuda() + # decoder = models.from_pretrained(opt.dec_pretrained).eval().cuda() + else: + latent_name = f'{opt.enc_model}_{opt.ckpt}' + cfg = edict(json.load(open(os.path.join(opt.model_root, opt.enc_model, 'config.json'), 'r'))) + encoder = getattr(models, cfg.models.encoder.name)(**cfg.models.encoder.args).cuda() + ckpt_path = os.path.join(opt.model_root, opt.enc_model, 'ckpts', f'encoder_{opt.ckpt}.pt') + encoder.load_state_dict(torch.load(ckpt_path), strict=False) + encoder.eval() + print(f'Loaded model from {ckpt_path}') + + metadata = [] + with open(os.path.join(opt.output_dir, "train.jsonl"), "r") as f: + for line in f: + data_term = json.loads(line) + metadata += [data_term] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + # metadata = metadata[0:8192] + records = [] + + # filter out objects that are already processed + for data_dict in copy.copy(metadata): + if os.path.exists(os.path.join(opt.save_dir, os.path.dirname(data_dict['target_slat']), 'ss.npz')): + records.append({'obj_index': os.path.dirname(data_dict['source_image']), f'ss_latent_{latent_name}': True}) + metadata.remove(data_dict) + + def loader(data): + try: + ss = get_voxels(data)[None].float() + load_queue.put((os.path.join(os.path.dirname(instance['target_slat']), 'ss.npz'), ss)) + except Exception as e: + print(f"Error loading features for {sha256}: {e}") + + def saver(save_rel_path, pack): + save_path = os.path.join(opt.save_dir, save_rel_path) + os.makedirs(os.path.dirname(save_path), exist_ok=True) + np.savez_compressed(save_path, **pack) + records.append({'obj_index': os.path.dirname(save_rel_path), f'ss_latent_{latent_name}': True}) + + # encode latents + num_iterations = len(metadata) // opt.batch_size + 1 if len(metadata) % opt.batch_size != 0 else len(metadata) // opt.batch_size + for i in tqdm(range(num_iterations)): + try: + instance = metadata[i * opt.batch_size: (i + 1) * opt.batch_size] + ss_batch = [] + for data_dict in instance: + ss = get_voxels(data_dict)[None].float() + ss_batch.append(ss) + ss_batch = torch.cat(ss_batch, dim=0) + ss_batch = ss_batch.cuda().float() + latent = encoder(ss_batch, sample_posterior=False) + # coords = torch.argwhere(decoder(latent)>0)[:, [0, 2, 3, 4]].int() + assert torch.isfinite(latent).all(), "Non-finite latent" + for j, data_dict in enumerate(instance): + pack = { + 'mean': latent[j].cpu().numpy(), + } + saver(os.path.join(os.path.dirname(data_dict['target_slat']).split('/')[-1], 'ss.npz'), pack) + except Exception as e: + continue + print(f"Error loading features for {i * opt.batch_size + start} to {(i + 1) * opt.batch_size + start}: {e}") + + records = pd.DataFrame.from_records(records) + records.to_csv(os.path.join(opt.save_dir, f'ss_latent_{latent_name}_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/stat_latent.py b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/stat_latent.py new file mode 100644 index 0000000000000000000000000000000000000000..7f27a062bb8be898ef6c705a3f3d9488f94299fe --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/stat_latent.py @@ -0,0 +1,66 @@ +import os +import json +import argparse +import numpy as np +import pandas as pd +from tqdm import tqdm +from easydict import EasyDict as edict +from concurrent.futures import ThreadPoolExecutor + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--model', type=str, default='dinov2_vitl14_reg_slat_enc_swin8_B_64l8_fp16', + help='Latent model to use') + parser.add_argument('--num_samples', type=int, default=50000, + help='Number of samples to use for calculating stats') + opt = parser.parse_args() + opt = edict(vars(opt)) + + # get file list + if os.path.exists(os.path.join(opt.output_dir, 'metadata.csv')): + metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata.csv')) + else: + raise ValueError('metadata.csv not found') + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + metadata = metadata[metadata[f'latent_{opt.model}'] == True] + sha256s = metadata['sha256'].values + sha256s = np.random.choice(sha256s, min(opt.num_samples, len(sha256s)), replace=False) + + # stats + means = [] + mean2s = [] + with ThreadPoolExecutor(max_workers=16) as executor, \ + tqdm(total=len(sha256s), desc="Extracting features") as pbar: + def worker(sha256): + try: + feats = np.load(os.path.join(opt.output_dir, 'latents', opt.model, f'{sha256}.npz')) + feats = feats['feats'] + means.append(feats.mean(axis=0)) + mean2s.append((feats ** 2).mean(axis=0)) + pbar.update() + except Exception as e: + print(f"Error extracting features for {sha256}: {e}") + pbar.update() + + executor.map(worker, sha256s) + executor.shutdown(wait=True) + + mean = np.array(means).mean(axis=0) + mean2 = np.array(mean2s).mean(axis=0) + std = np.sqrt(mean2 - mean ** 2) + + print('mean:', mean) + print('std:', std) + + with open(os.path.join(opt.output_dir, 'latents', opt.model, 'stats.json'), 'w') as f: + json.dump({ + 'mean': mean.tolist(), + 'std': std.tolist(), + }, f, indent=4) + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/utils.py b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..69830845d40697bd2c4e7c68e64e54b4d4091a81 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/utils.py @@ -0,0 +1,43 @@ +from typing import * +import hashlib +import numpy as np + + +def get_file_hash(file: str) -> str: + sha256 = hashlib.sha256() + # Read the file from the path + with open(file, "rb") as f: + # Update the hash with the file content + for byte_block in iter(lambda: f.read(4096), b""): + sha256.update(byte_block) + return sha256.hexdigest() + +# ===============LOW DISCREPANCY SEQUENCES================ + +PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53] + +def radical_inverse(base, n): + val = 0 + inv_base = 1.0 / base + inv_base_n = inv_base + while n > 0: + digit = n % base + val += digit * inv_base_n + n //= base + inv_base_n *= inv_base + return val + +def halton_sequence(dim, n): + return [radical_inverse(PRIMES[dim], n) for dim in range(dim)] + +def hammersley_sequence(dim, n, num_samples): + return [n / num_samples] + halton_sequence(dim - 1, n) + +def sphere_hammersley_sequence(n, num_samples, offset=(0, 0)): + u, v = hammersley_sequence(2, n, num_samples) + u += offset[0] / num_samples + v += offset[1] + u = 2 * u if u < 0.25 else 2 / 3 * u + 1 / 3 + theta = np.arccos(1 - 2 * u) - np.pi / 2 + phi = v * 2 * np.pi + return [phi, theta] diff --git a/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/voxelize.py b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/voxelize.py new file mode 100644 index 0000000000000000000000000000000000000000..012dc0059925c8ad72a92a850c945aec043610d6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/dataset_toolkits/voxelize.py @@ -0,0 +1,103 @@ +import os +import copy +import sys +import importlib +import argparse +import pandas as pd +from easydict import EasyDict as edict +from functools import partial +import numpy as np +import open3d as o3d +import utils3d +from tqdm import tqdm + +def _voxelize(file, sha256, output_dir): + mesh = o3d.io.read_triangle_mesh(os.path.join(output_dir, 'render_all_eevee_1024_150views_evenbg', sha256, 'mesh.ply')) + # clamp vertices to the range [-0.5, 0.5] + vertices = np.clip(np.asarray(mesh.vertices), -0.5 + 1e-6, 0.5 - 1e-6) + mesh.vertices = o3d.utility.Vector3dVector(vertices) + voxel_grid = o3d.geometry.VoxelGrid.create_from_triangle_mesh_within_bounds(mesh, voxel_size=1/64, min_bound=(-0.5, -0.5, -0.5), max_bound=(0.5, 0.5, 0.5)) + vertices = np.array([voxel.grid_index for voxel in voxel_grid.get_voxels()]) + assert np.all(vertices >= 0) and np.all(vertices < 64), "Some vertices are out of bounds" + vertices = (vertices + 0.5) / 64 - 0.5 + utils3d.io.write_ply(os.path.join(output_dir, 'voxels', f'{sha256}.ply'), vertices) + return {'sha256': sha256, 'voxelized': True, 'num_voxels': len(vertices)} + + +if __name__ == '__main__': + dataset_utils = importlib.import_module(f'datasets.{sys.argv[1]}') + + parser = argparse.ArgumentParser() + parser.add_argument('--output_dir', type=str, required=True, + help='Directory to save the metadata') + parser.add_argument('--filter_low_aesthetic_score', type=float, default=None, + help='Filter objects with aesthetic score lower than this value') + parser.add_argument('--instances', type=str, default=None, + help='Instances to process') + parser.add_argument('--num_views', type=int, default=150, + help='Number of views to render') + dataset_utils.add_args(parser) + parser.add_argument('--rank', type=int, default=0) + parser.add_argument('--world_size', type=int, default=1) + parser.add_argument('--max_workers', type=int, default=None) + opt = parser.parse_args(sys.argv[2:]) + opt = edict(vars(opt)) + + # get file list + metadata = pd.read_csv(os.path.join(opt.output_dir, 'metadata_all_eevee_1024_150views_evenbg')) + if opt.instances is None: + if opt.filter_low_aesthetic_score is not None: + metadata = metadata[metadata['aesthetic_score'] >= opt.filter_low_aesthetic_score] + if 'rendered' not in metadata.columns: + raise ValueError('metadata.csv does not have "rendered" column, please run "build_metadata.py" first') + metadata = metadata[metadata['rendered'] == False] + if 'voxelized' in metadata.columns: + metadata = metadata[metadata['voxelized'] == False] + else: + if os.path.exists(opt.instances): + with open(opt.instances, 'r') as f: + instances = f.read().splitlines() + else: + instances = opt.instances.split(',') + metadata = metadata[metadata['sha256'].isin(instances)] + + start = len(metadata) * opt.rank // opt.world_size + end = len(metadata) * (opt.rank + 1) // opt.world_size + metadata = metadata[start:end] + records = [] + + os.makedirs(os.path.join(opt.output_dir, 'voxels'), exist_ok=True) + # filter out objects that are already processed + import concurrent.futures + + def process_sha256(sha256): + path = os.path.join(opt.output_dir, 'voxels', f'{sha256}.ply') + if os.path.exists(path): + try: + pts = utils3d.io.read_ply(path)[0] + return sha256, len(pts) + except Exception: + return None + return None + + results = [] + with concurrent.futures.ThreadPoolExecutor(max_workers=opt.max_workers or 16) as executor: + futures = {executor.submit(process_sha256, sha): sha for sha in metadata['sha256'].values} + for future in tqdm(concurrent.futures.as_completed(futures), total=len(futures), desc="Checking cached voxels"): + result = future.result() + if result is not None: + results.append(result) + + # update records and filter out processed sha256 from metadata + for sha256, num_voxels in results: + records.append({'sha256': sha256, 'voxelized': True, 'num_voxels': num_voxels}) + processed_set = {rec['sha256'] for rec in records} + metadata = metadata[~metadata['sha256'].isin(processed_set)] + + print(f'Processing {len(metadata)} objects...') + + # process objects + func = partial(_voxelize, output_dir=opt.output_dir) + voxelized = dataset_utils.foreach_instance(metadata, opt.output_dir, func, max_workers=opt.max_workers, desc='Voxelizing') + voxelized = pd.concat([voxelized, pd.DataFrame.from_records(records)]) + voxelized.to_csv(os.path.join(opt.output_dir, f'voxelized_{opt.rank}.csv'), index=False) diff --git a/OVOW/engine/oneposeviagen/trellis/pyrightconfig.json b/OVOW/engine/oneposeviagen/trellis/pyrightconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..dd1959e1a5cdd7bdf7ee93a4b09bc4b0ba6609a3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/pyrightconfig.json @@ -0,0 +1,15 @@ +{ + "exclude": [ + "data", + "data_dreamvserse2_sslatent", + "lightning_logs", + "render_data", + "more_data", + "assets", + "checkpoints", + "dataset_test_results", + "weights", + "examples", + "results" + ] +} \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/requirements.txt b/OVOW/engine/oneposeviagen/trellis/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..990e3a933994bb8bb21f95e3a4b9f6a871cc97ed --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/requirements.txt @@ -0,0 +1,25 @@ +# torch==2.0.1 +# torchvision==0.15.2 +open3d +gradio +spaces +pillow==10.4.0 +imageio==2.36.1 +imageio-ffmpeg==0.5.1 +tqdm==4.67.1 +easydict==1.13 +opencv-python-headless==4.10.0.84 +scipy +trimesh==4.5.3 +xformers==0.0.21 +spconv-cu118==2.3.6 +transformers==4.46.3 +plyfile +kornia +timm +pytorch-lightning==2.1.3 +diso +# torch-scatter==2.1.2+pt20cu118 -f https://data.pyg.org/whl/torch-2.0.0+cu118.html +# gsplat --index-url https://docs.gsplat.studio/whl/pt20cu118 +# git+https://github.com/EasternJournalist/utils3d.git +# git+https://github.com/NVlabs/nvdiffrast \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/requirements_flux.txt b/OVOW/engine/oneposeviagen/trellis/requirements_flux.txt new file mode 100644 index 0000000000000000000000000000000000000000..0de592c901b069abe6a7b8e790c0785b8340a790 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/requirements_flux.txt @@ -0,0 +1,25 @@ +torch==2.3.0 +torchvision==0.18.0 +gradio +spaces +open3d +pillow==10.4.0 +imageio==2.36.1 +imageio-ffmpeg==0.5.1 +tqdm==4.67.1 +easydict==1.13 +opencv-python-headless==4.10.0.84 +scipy +trimesh==4.5.3 +xformers==0.0.21 +spconv-cu118==2.3.6 +transformers==4.46.3 +plyfile +kornia +timm +pytorch-lightning==2.1.3 +diso +# torch-scatter==2.1.2+pt20cu118 -f https://data.pyg.org/whl/torch-2.0.0+cu118.html +# gsplat --index-url https://docs.gsplat.studio/whl/pt20cu118 +# git+https://github.com/EasternJournalist/utils3d.git +# git+https://github.com/NVlabs/nvdiffrast \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/set_env.sh b/OVOW/engine/oneposeviagen/trellis/set_env.sh new file mode 100644 index 0000000000000000000000000000000000000000..85ad7a978d548ec8963793700cc98785124b2b77 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/set_env.sh @@ -0,0 +1,10 @@ +export HF_ENDPOINT=https://hf-mirror.com +export HF_HOME=/gen3d-high/chongjie/cache +export TORCH_HOME=/gen3d-high/chongjie/cache/torch +# export PATH="/gen3d-high/chongjie/envs/trellis-a800/bin:$PATH" +# export PATH="/gen3d-high/chongjie/envs/torch23/bin:$PATH" +export PATH="/gen3d-high/chongjie/envs/trellis-a800/bin:$PATH" + +export GRADIO_TEMP_DIR=/gen3d-high/chongjie/cache/gradio +export PATH=${HOME}/cuda/cuda/bin:$PATH +export LD_LIBRARY_PATH=${HOME}/cuda/cuda/lib64:$LD_LIBRARY_PATH diff --git a/OVOW/engine/oneposeviagen/trellis/setup.py b/OVOW/engine/oneposeviagen/trellis/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..54dd3589507ad2813946816792d2050339dc3daf --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/setup.py @@ -0,0 +1,9 @@ +# src/fpose/setup.py +from setuptools import setup, find_packages + +setup( + name='trellis', + version='0.1', + package_dir={'trellis': 'trellis'}, + packages=find_packages(where='trellis', include=['trellis*']), +) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis.egg-info/PKG-INFO b/OVOW/engine/oneposeviagen/trellis/trellis.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..8e13920c958a8daa1aadf60248b6939e9041c530 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis.egg-info/PKG-INFO @@ -0,0 +1,5 @@ +Metadata-Version: 2.4 +Name: trellis +Version: 0.1 +License-File: LICENSE +Dynamic: license-file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis.egg-info/SOURCES.txt b/OVOW/engine/oneposeviagen/trellis/trellis.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..e9ca5092198d4b7ebbbdb3ff21d0abf44a697f4f --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis.egg-info/SOURCES.txt @@ -0,0 +1,6 @@ +LICENSE +setup.py +trellis.egg-info/PKG-INFO +trellis.egg-info/SOURCES.txt +trellis.egg-info/dependency_links.txt +trellis.egg-info/top_level.txt \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis.egg-info/dependency_links.txt b/OVOW/engine/oneposeviagen/trellis/trellis.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/OVOW/engine/oneposeviagen/trellis/trellis.egg-info/top_level.txt b/OVOW/engine/oneposeviagen/trellis/trellis.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis.egg-info/top_level.txt @@ -0,0 +1 @@ + diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..20d240afc9c26a21aee76954628b3d4ef9a1ccbd --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/__init__.py @@ -0,0 +1,6 @@ +from . import models +from . import modules +from . import pipelines +from . import renderers +from . import representations +from . import utils diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/datasets/DreamVerse.py b/OVOW/engine/oneposeviagen/trellis/trellis/datasets/DreamVerse.py new file mode 100644 index 0000000000000000000000000000000000000000..a5f51d65ee9b4ce7e5c7c452ab8f7bab8e48dc72 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/datasets/DreamVerse.py @@ -0,0 +1,101 @@ +import math +import os +import json +import re +import cv2 +from dataclasses import dataclass, field + +import pytorch_lightning as pl +import torch +import torch.nn.functional as F +from torch.utils.data import DataLoader +from torch.utils.data import default_collate + +from .base import BaseDataset + +class DreamVerseDataset(BaseDataset): + def collate_fn(self, batch): + batched_condition_feats = [] + batched_condition_coords = [] + batched_target_feats = [] + batched_target_coords = [] + other_keys = {} + + for idx, sample in enumerate(batch): + condition_feats = sample['conditional_slat']['feats'] + condition_coords = sample['conditional_slat']['coords'][..., 1:] + target_feats = sample['target_slat']['feats'] + target_coords = sample['target_slat']['coords'][..., 1:] + + batch_coords = torch.full((condition_coords.shape[0], 1), idx, dtype=condition_coords.dtype) + + batched_condition_feats.append(condition_feats) + batched_condition_coords.append(torch.cat([batch_coords, condition_coords], dim=1)) + batched_target_feats.append(target_feats) + batched_target_coords.append(torch.cat([batch_coords, target_coords], dim=1)) + + for key, value in sample.items(): + if not key.endswith('slat'): + if key not in other_keys: + other_keys[key] = [] + other_keys[key].append(value) + + batched_condition_feats = torch.cat(batched_condition_feats, dim=0) + batched_condition_coords = torch.cat(batched_condition_coords, dim=0) + batched_target_feats = torch.cat(batched_target_feats, dim=0) + batched_target_coords = torch.cat(batched_target_coords, dim=0) + + batched_data = { + 'conditional_slat': { + 'feats': batched_condition_feats, + 'coords': batched_condition_coords + }, + 'target_slat': { + 'feats': batched_target_feats, + 'coords': batched_target_coords + } + } + + for key, value in other_keys.items(): + batched_data[key] = default_collate(value) + + return batched_data + +@register("DreamVerse-datamodule") +class DreamVerseDataModule(pl.LightningDataModule): + def __init__(self, cfg = None) -> None: + super().__init__() + + def setup(self, data_dirs, stage=None) -> None: + if stage in [None, "fit"]: + self.train_dataset = DreamVerseDataset(data_dirs, "train") + if stage in [None, "fit", "validate"]: + self.val_dataset = DreamVerseDataset(data_dirs, "val") + if stage in [None, "test", "predict"]: + self.test_dataset = DreamVerseDataset(data_dirs, "test") + + def prepare_data(self): + pass + + def general_loader(self, dataset, batch_size, collate_fn=None, num_workers=0) -> DataLoader: + return DataLoader( + dataset, batch_size=batch_size, collate_fn=collate_fn, num_workers=num_workers + ) + + def train_dataloader(self) -> DataLoader: + return self.general_loader( + self.train_dataset, + batch_size=self.cfg.batch_size, + collate_fn=self.train_dataset.collate, + num_workers=self.cfg.num_workers + ) + + def val_dataloader(self) -> DataLoader: + return self.general_loader(self.val_dataset, batch_size=1) + + def test_dataloader(self) -> DataLoader: + return self.general_loader(self.test_dataset, batch_size=1) + + def predict_dataloader(self) -> DataLoader: + return self.general_loader(self.test_dataset, batch_size=1) + diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/datasets/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/datasets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4333fac78ab9c7237382f1e053530b86eccaf790 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/datasets/__init__.py @@ -0,0 +1,90 @@ +datasets = {} +import numpy as np +from PIL import Image +import dataclasses +import math +import os +import torch +import torch.nn.functional as F + +def register(name): + def decorator(cls): + datasets[name] = cls + return cls + return decorator + + +def make(config): + if isinstance(config, str): + name = config + config = {} + else: + name = config.get('name') + + if name not in datasets: + raise ValueError(f'Unknown dataset: {name}') + + dataset = datasets[name](config) + return dataset + + +if __name__ == '__main__': + import matplotlib.pyplot as plt + # Create output directory + output_dir = './dataset_test_results' + os.makedirs(output_dir, exist_ok=True) + + # Initialize dataset + dataset = NpzDatasetAug(json_files=['./data/objaverse_add/processed/train_3d.jsonl']) + + # Create a DataLoader + batch_size = 4 # You can choose an appropriate batch size + dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, collate_fn=custom_collate) + + for batch_idx, batch_data in enumerate(dataloader): + target_feats = batch_data['target_feats'] + target_coords = batch_data['target_coords'] + txt = batch_data['txt'] + source = batch_data['source'] + + print(f"Batch {batch_idx}:") + print(f" Target shape: {target_feats.shape}, {target_coords.shape} (if applicable, depending on the type of target)") + print(f" Text (prompt): {txt}") + print(f" Text (prompt): {txt}") + print(f" Source shape: {source.shape}") + + # You can add more processing or checks here depending on your requirements + if batch_idx >= 2: # Just loop through a few batches for testing + break + + # Test single item and save info + # print(f"Dataset size: {len(dataset)}") + # with open(os.path.join(output_dir, 'dataset_info.txt'), 'w') as f: + # f.write(f"Dataset size: {len(dataset)}\n") + + # sample = dataset[0] + # f.write("\nSample keys: " + str(sample.keys()) + "\n") + # f.write("\nShapes:\n") + # for key, value in sample.items(): + # if isinstance(value, torch.Tensor): + # f.write(f"{key}: {value.shape}\n") + + + # # Save sample visualizations + # for i in range(min(5, len(dataset))): # Save first 5 samples + # sample = dataset[i] + + # plt.figure(figsize=(15, 5)) + + # plt.subplot(132) + # plt.imshow((sample['source'].numpy() + 1) / 2) + # plt.title('Source') + # plt.axis('off') + + # plt.savefig(os.path.join(output_dir, f'sample_{i}.png'), + # bbox_inches='tight', + # pad_inches=0.1, + # dpi=300) + # plt.close() + + # print(f"Results saved to {output_dir}") \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/datasets/base.py b/OVOW/engine/oneposeviagen/trellis/trellis/datasets/base.py new file mode 100644 index 0000000000000000000000000000000000000000..e8133d3f8bd8e463119f6ea8e6363cc369d4d86c --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/datasets/base.py @@ -0,0 +1,210 @@ +import json +import cv2 +import numpy as np +import os +from torch.utils.data import Dataset +import random +import pdb +import PIL.Image as Image +import torchvision.transforms as T +import torch +import torch.nn.functional as F +import torchvision.transforms.functional as TF +import math +from trellis.modules import sparse as sp +from torch.utils.data import DataLoader + +class BaseDataset(Dataset): + VALID_ASSETS = [ + 'normal', + 'depth', + 'albedo', + 'lighting', + 'mask'] + + def __init__(self, + data_dirs=None, + split='train', + source_aug=None, + resolution=518, + task='normal'): + self.data = [] + for data_dir in data_dirs: + json_file = os.path.join(data_dir, f'{split}.jsonl') + with open(json_file, "r") as f: + for line in f: + data_term = json.loads(line) + data_term['data_dir'] = data_dir + self.data += [data_term] + self.to_Tensor = T.ToTensor() + self.source_aug = source_aug + self.task = task + self.resolution = resolution + self.resize_transform = T.Resize(self.resolution) + + def __len__(self): + return len(self.data) + + def __getitem__(self, idx): + try: + return self._load_item(idx) + except Exception as e: + random_idx = random.randint(0, len(self.data) - 1) + return self._load_item(random_idx) + + def _load_item(self, idx): + item = self.data[idx] + data_dir = item['data_dir'] + data_dict = {} + + if 'source_slat' in item: + source_slat = np.load(os.path.join(data_dir, item['source_slat'])) + data_dict['source_slat'] = {key: torch.from_numpy(source_slat[key]) for key in source_slat.keys()} + + if 'target_slat' in item: + target_slat = np.load(os.path.join(data_dir, item['target_slat'])) + data_dict['target_slat'] = {key: torch.from_numpy(target_slat[key]) for key in target_slat.keys()} + + if 'source_image' in item: + if item['source_image'].endswith('.npz'): + source_image = np.load(os.path.join(data_dir, item['source_image']))[self.task] + if source_image.dtype == np.uint8: + source_image = source_image.astype(np.float32) / 255.0 + source_image = torch.tensor(source_image).permute(0, 3, 1, 2) + source_image_path = item['source_image'] + elif item['source_image'].endswith('.png') or item['source_image'].endswith('.jpg'): + source_image = Image.open(os.path.join(data_dir, item['source_image'])) + source_image /= 255.0 + source_image = self.to_Tensor(source_image).unsqueeze(0).float() + + if self.source_aug is not None: + source_image = self.source_aug(source_image) + data_dict['source_image'] = self.resize_transform(source_image) + + if 'reference_image' in item: + if item['reference_image'].endswith('.npz'): + reference_image = np.load(os.path.join(data_dir, item['reference_image']))[self.task] + reference_image = torch.tensor(reference_image).float().permute(0, 3, 1, 2) + elif item['reference_image'].endswith('.png') or item['reference_image'].endswith('.jpg'): + reference_image = Image.open(os.path.join(data_dir, item['reference_image'])) + reference_image = self.to_Tensor(reference_image).unsqueeze(0).float() + if reference_image.max() > 1: + reference_image /= 255.0 + data_dict['reference_image'] = self.resize_transform(reference_image) + + return data_dict + +def custom_collate(batch): + """ + Custom collate function that handles sparse tensors along with other batch elements. + + Args: + batch: List of dictionaries containing 'target_feats', 'target_coords', 'condition_feats', 'condition_coords', 'source' and 'ref' + + Returns: + Dictionary with batched data + """ + # Initialize lists to hold the batched data + batched_feats = [] + batched_coords = [] + batched_condition_feats = [] + batched_condition_coords = [] + batched_source = [] + batched_ref = [] + + batch_size = len(batch) + for idx, sample in enumerate(batch): + # Handle target sparse tensor components + feats = sample['target_feats'] + coords = sample['target_coords'][..., 1:] + + # Add batch dimension to coordinates + batch_coords = torch.full((coords.shape[0], 1), idx, dtype=coords.dtype) + + batched_feats.append(feats) + batched_coords.append(torch.cat([batch_coords, coords], dim=1)) + + # Handle condition sparse tensor components + condition_feats = sample['condition_feats'] + condition_coords = sample['condition_coords'][..., 1:] + + batched_condition_feats.append(condition_feats) + batched_condition_coords.append(torch.cat([batch_coords, condition_coords], dim=1)) + + # Handle other batch elements + batched_source.append(sample['source']) + batched_ref.append(sample['ref']) + + # Concatenate target features and coordinates + batched_feats = torch.cat(batched_feats, dim=0) + batched_coords = torch.cat(batched_coords, dim=0) + + # Concatenate condition features and coordinates + batched_condition_feats = torch.cat(batched_condition_feats, dim=0) + batched_condition_coords = torch.cat(batched_condition_coords, dim=0) + + # Stack source tensors + batched_source = torch.stack(batched_source, dim=0) + batched_ref = torch.stack(batched_ref, dim=0) + + return { + 'target_feats': batched_feats, + 'target_coords': batched_coords, + 'condition_feats': batched_condition_feats, + 'condition_coords': batched_condition_coords, + 'source': batched_source, + 'ref': batched_ref + } + + +if __name__ == '__main__': + import matplotlib.pyplot as plt + # Create output directory + output_dir = './dataset_test_results' + os.makedirs(output_dir, exist_ok=True) + + # Initialize dataset + dataset = BaseDataset(json_files=['./data/train.jsonl']) + + # Create a DataLoader + # batch_size = 4 # You can choose an appropriate batch size + # dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True, collate_fn=custom_collate) + + # Test single item and save info + print(f"Dataset size: {len(dataset)}") + with open(os.path.join(output_dir, 'dataset_info.txt'), 'w') as f: + f.write(f"Dataset size: {len(dataset)}\n") + + sample = dataset[0] + f.write("\nSample keys: " + str(sample.keys()) + "\n") + f.write("\nShapes:\n") + for key, value in sample.items(): + if isinstance(value, torch.Tensor): + f.write(f"{key}: {value.shape}\n") + + + # Save sample visualizations + for i in range(min(5, len(dataset))): # Save first 5 samples + fig = plt.figure(figsize=(15, 5)) + sample = dataset[i] + + plt.subplot(132) + plt.imshow(sample['source_image'][0].permute(1, 2, 0).numpy()) + plt.title('Source') + plt.axis('off') + + from mpl_toolkits.mplot3d import Axes3D + ax = fig.add_subplot(133, projection='3d') + coords = sample['target_slat']['coords'][..., 1:].numpy() # [N, 3] + ax.scatter(coords[:, 0], coords[:, 1], coords[:, 2], s=1) + ax.set_xlim([0, 63]) + ax.set_ylim([0, 63]) + ax.set_zlim([0, 63]) + + plt.savefig(os.path.join(output_dir, f'sample_{i}.png'), + bbox_inches='tight', + pad_inches=0.1, + dpi=300) + plt.close(fig) + + print(f"Results saved to {output_dir}") \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/models/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d4d2e7101b152dce88e52a38c8eebd2589d0517e --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/models/__init__.py @@ -0,0 +1,87 @@ +import importlib + +__attributes = { + 'SparseStructureEncoder': 'sparse_structure_vae', + 'SparseStructureDecoder': 'sparse_structure_vae', + 'SparseStructureFlowModel': 'sparse_structure_flow', + 'SLatEncoder': 'structured_latent_vae', + 'SLatGaussianDecoder': 'structured_latent_vae', + 'SLatMeshDecoder': 'structured_latent_vae', + 'SLatFlowModel': 'structured_latent_flow', +} + +__submodules = [] + +__all__ = list(__attributes.keys()) + __submodules + +def __getattr__(name): + if name not in globals(): + if name in __attributes: + module_name = __attributes[name] + module = importlib.import_module(f".{module_name}", __name__) + globals()[name] = getattr(module, name) + elif name in __submodules: + module = importlib.import_module(f".{name}", __name__) + globals()[name] = module + else: + raise AttributeError(f"module {__name__} has no attribute {name}") + return globals()[name] + + +def from_pretrained(path: str, **kwargs): + """ + Load a model from a pretrained checkpoint. + + Args: + path: The path to the checkpoint. Can be either local path or a Hugging Face model name. + NOTE: config file and model file should take the name f'{path}.json' and f'{path}.safetensors' respectively. + **kwargs: Additional arguments for the model constructor. + """ + import os + import json + from safetensors.torch import load_file + is_local = os.path.exists(f"{path}.json") and os.path.exists(f"{path}.safetensors") + + if is_local: + config_file = f"{path}.json" + model_file = f"{path}.safetensors" + else: + from huggingface_hub import hf_hub_download + path_parts = path.split('/') + repo_id = f'{path_parts[0]}/{path_parts[1]}' + model_name = '/'.join(path_parts[2:]) + config_file = hf_hub_download(repo_id, f"{model_name}.json") + model_file = hf_hub_download(repo_id, f"{model_name}.safetensors") + + with open(config_file, 'r') as f: + config = json.load(f) + model = __getattr__(config['name'])(**config['args'], **kwargs) + model.load_state_dict(load_file(model_file), strict=False) + + return model + +def save_finetuned_model(model, output_dir: str): + """ + Save a fine-tuned model's state_dict as safetensors with a timestamp. + + Args: + model: The model to be saved. + output_dir: The directory where the model's state_dict will be saved. + The file will be saved as f'{output_dir}/{timestamp}.safetensors'. + """ + from safetensors.torch import save_file + import os + from datetime import datetime + + if not os.path.exists(output_dir): + os.makedirs(output_dir) + + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + save_file(model.state_dict(), f"{output_dir}/{timestamp}.safetensors") + +# For Pylance +if __name__ == '__main__': + from .sparse_structure_vae import SparseStructureEncoder, SparseStructureDecoder + from .sparse_structure_flow import SparseStructureFlowModel + from .structured_latent_vae import SLatEncoder, SLatGaussianDecoder, SLatMeshDecoder + from .structured_latent_flow import SLatFlowModel diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/models/heads/camera_head.py b/OVOW/engine/oneposeviagen/trellis/trellis/models/heads/camera_head.py new file mode 100644 index 0000000000000000000000000000000000000000..176d76fb5baeb3a42fa3675a1d1fb14010f2904d --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/models/heads/camera_head.py @@ -0,0 +1,162 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +import numpy as np + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from vggt.layers import Mlp +from vggt.layers.block import Block +from vggt.heads.head_act import activate_pose + + +class CameraHead(nn.Module): + """ + CameraHead predicts camera parameters from token representations using iterative refinement. + + It applies a series of transformer blocks (the "trunk") to dedicated camera tokens. + """ + + def __init__( + self, + dim_in: int = 2048, + trunk_depth: int = 4, + pose_encoding_type: str = "absT_quaR_FoV", + num_heads: int = 16, + mlp_ratio: int = 4, + init_values: float = 0.01, + trans_act: str = "linear", + quat_act: str = "linear", + fl_act: str = "relu", # Field of view activations: ensures FOV values are positive. + ): + super().__init__() + + if pose_encoding_type == "absT_quaR_FoV": + self.target_dim = 9 + else: + raise ValueError(f"Unsupported camera encoding type: {pose_encoding_type}") + + self.trans_act = trans_act + self.quat_act = quat_act + self.fl_act = fl_act + self.trunk_depth = trunk_depth + + # Build the trunk using a sequence of transformer blocks. + self.trunk = nn.Sequential( + *[ + Block( + dim=dim_in, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + init_values=init_values, + ) + for _ in range(trunk_depth) + ] + ) + + # Normalizations for camera token and trunk output. + self.token_norm = nn.LayerNorm(dim_in) + self.trunk_norm = nn.LayerNorm(dim_in) + + # Learnable empty camera pose token. + self.empty_pose_tokens = nn.Parameter(torch.zeros(1, 1, self.target_dim)) + self.embed_pose = nn.Linear(self.target_dim, dim_in) + + # Module for producing modulation parameters: shift, scale, and a gate. + self.poseLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim_in, 3 * dim_in, bias=True)) + + # Adaptive layer normalization without affine parameters. + self.adaln_norm = nn.LayerNorm(dim_in, elementwise_affine=False, eps=1e-6) + self.pose_branch = Mlp( + in_features=dim_in, + hidden_features=dim_in // 2, + out_features=self.target_dim, + drop=0, + ) + + def forward(self, aggregated_tokens_list: list, num_iterations: int = 4) -> list: + """ + Forward pass to predict camera parameters. + + Args: + aggregated_tokens_list (list): List of token tensors from the network; + the last tensor is used for prediction. + num_iterations (int, optional): Number of iterative refinement steps. Defaults to 4. + + Returns: + list: A list of predicted camera encodings (post-activation) from each iteration. + """ + # Use tokens from the last block for camera prediction. + tokens = aggregated_tokens_list[-1] + + # Extract the camera tokens + pose_tokens = tokens[:, :, 0] + pose_tokens = self.token_norm(pose_tokens) + + pred_pose_enc_list = self.trunk_fn(pose_tokens, num_iterations) + return pred_pose_enc_list + + def trunk_fn(self, pose_tokens: torch.Tensor, num_iterations: int) -> list: + """ + Iteratively refine camera pose predictions. + + Args: + pose_tokens (torch.Tensor): Normalized camera tokens with shape [B, 1, C]. + num_iterations (int): Number of refinement iterations. + + Returns: + list: List of activated camera encodings from each iteration. + """ + B, S, C = pose_tokens.shape # S is expected to be 1. + pred_pose_enc = None + pred_pose_enc_list = [] + + for _ in range(num_iterations): + # Use a learned empty pose for the first iteration. + if pred_pose_enc is None: + module_input = self.embed_pose(self.empty_pose_tokens.expand(B, S, -1)) + else: + # Detach the previous prediction to avoid backprop through time. + pred_pose_enc = pred_pose_enc.detach() + module_input = self.embed_pose(pred_pose_enc) + + # Generate modulation parameters and split them into shift, scale, and gate components. + shift_msa, scale_msa, gate_msa = self.poseLN_modulation(module_input).chunk(3, dim=-1) + + # Adaptive layer normalization and modulation. + pose_tokens_modulated = gate_msa * modulate(self.adaln_norm(pose_tokens), shift_msa, scale_msa) + pose_tokens_modulated = pose_tokens_modulated + pose_tokens + + pose_tokens_modulated = self.trunk(pose_tokens_modulated) + # Compute the delta update for the pose encoding. + pred_pose_enc_delta = self.pose_branch(self.trunk_norm(pose_tokens_modulated)) + + if pred_pose_enc is None: + pred_pose_enc = pred_pose_enc_delta + else: + pred_pose_enc = pred_pose_enc + pred_pose_enc_delta + + # Apply final activation functions for translation, quaternion, and field-of-view. + activated_pose = activate_pose( + pred_pose_enc, + trans_act=self.trans_act, + quat_act=self.quat_act, + fl_act=self.fl_act, + ) + pred_pose_enc_list.append(activated_pose) + + return pred_pose_enc_list + + +def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor) -> torch.Tensor: + """ + Modulate the input tensor using scaling and shifting parameters. + """ + # modified from https://github.com/facebookresearch/DiT/blob/796c29e532f47bba17c5b9c5eb39b9354b8b7c64/models.py#L19 + return x * (1 + scale) + shift diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/models/heads/dpt_head.py b/OVOW/engine/oneposeviagen/trellis/trellis/models/heads/dpt_head.py new file mode 100644 index 0000000000000000000000000000000000000000..390b6dab2ee2e9e5ed274b92a0d418a91261a21f --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/models/heads/dpt_head.py @@ -0,0 +1,497 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + + +# Inspired by https://github.com/DepthAnything/Depth-Anything-V2 + + +import os +from typing import List, Dict, Tuple, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from .head_act import activate_head +from .utils import create_uv_grid, position_grid_to_embed + + +class DPTHead(nn.Module): + """ + DPT Head for dense prediction tasks. + + This implementation follows the architecture described in "Vision Transformers for Dense Prediction" + (https://arxiv.org/abs/2103.13413). The DPT head processes features from a vision transformer + backbone and produces dense predictions by fusing multi-scale features. + + Args: + dim_in (int): Input dimension (channels). + patch_size (int, optional): Patch size. Default is 14. + output_dim (int, optional): Number of output channels. Default is 4. + activation (str, optional): Activation type. Default is "inv_log". + conf_activation (str, optional): Confidence activation type. Default is "expp1". + features (int, optional): Feature channels for intermediate representations. Default is 256. + out_channels (List[int], optional): Output channels for each intermediate layer. + intermediate_layer_idx (List[int], optional): Indices of layers from aggregated tokens used for DPT. + pos_embed (bool, optional): Whether to use positional embedding. Default is True. + feature_only (bool, optional): If True, return features only without the last several layers and activation head. Default is False. + down_ratio (int, optional): Downscaling factor for the output resolution. Default is 1. + """ + + def __init__( + self, + dim_in: int, + patch_size: int = 14, + output_dim: int = 4, + activation: str = "inv_log", + conf_activation: str = "expp1", + features: int = 256, + out_channels: List[int] = [256, 512, 1024, 1024], + intermediate_layer_idx: List[int] = [4, 11, 17, 23], + pos_embed: bool = True, + feature_only: bool = False, + down_ratio: int = 1, + ) -> None: + super(DPTHead, self).__init__() + self.patch_size = patch_size + self.activation = activation + self.conf_activation = conf_activation + self.pos_embed = pos_embed + self.feature_only = feature_only + self.down_ratio = down_ratio + self.intermediate_layer_idx = intermediate_layer_idx + + self.norm = nn.LayerNorm(dim_in) + + # Projection layers for each output channel from tokens. + self.projects = nn.ModuleList( + [ + nn.Conv2d( + in_channels=dim_in, + out_channels=oc, + kernel_size=1, + stride=1, + padding=0, + ) + for oc in out_channels + ] + ) + + # Resize layers for upsampling feature maps. + self.resize_layers = nn.ModuleList( + [ + nn.ConvTranspose2d( + in_channels=out_channels[0], out_channels=out_channels[0], kernel_size=4, stride=4, padding=0 + ), + nn.ConvTranspose2d( + in_channels=out_channels[1], out_channels=out_channels[1], kernel_size=2, stride=2, padding=0 + ), + nn.Identity(), + nn.Conv2d( + in_channels=out_channels[3], out_channels=out_channels[3], kernel_size=3, stride=2, padding=1 + ), + ] + ) + + self.scratch = _make_scratch( + out_channels, + features, + expand=False, + ) + + # Attach additional modules to scratch. + self.scratch.stem_transpose = None + self.scratch.refinenet1 = _make_fusion_block(features) + self.scratch.refinenet2 = _make_fusion_block(features) + self.scratch.refinenet3 = _make_fusion_block(features) + self.scratch.refinenet4 = _make_fusion_block(features, has_residual=False) + + head_features_1 = features + head_features_2 = 32 + + if feature_only: + self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1, kernel_size=3, stride=1, padding=1) + else: + self.scratch.output_conv1 = nn.Conv2d( + head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1 + ) + conv2_in_channels = head_features_1 // 2 + + self.scratch.output_conv2 = nn.Sequential( + nn.Conv2d(conv2_in_channels, head_features_2, kernel_size=3, stride=1, padding=1), + nn.ReLU(inplace=True), + nn.Conv2d(head_features_2, output_dim, kernel_size=1, stride=1, padding=0), + ) + + def forward( + self, + aggregated_tokens_list: List[torch.Tensor], + images: torch.Tensor, + patch_start_idx: int, + frames_chunk_size: int = 8, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: + """ + Forward pass through the DPT head, supports processing by chunking frames. + Args: + aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers. + images (Tensor): Input images with shape [B, S, 3, H, W], in range [0, 1]. + patch_start_idx (int): Starting index for patch tokens in the token sequence. + Used to separate patch tokens from other tokens (e.g., camera or register tokens). + frames_chunk_size (int, optional): Number of frames to process in each chunk. + If None or larger than S, all frames are processed at once. Default: 8. + + Returns: + Tensor or Tuple[Tensor, Tensor]: + - If feature_only=True: Feature maps with shape [B, S, C, H, W] + - Otherwise: Tuple of (predictions, confidence) both with shape [B, S, 1, H, W] + """ + B, S, _, H, W = images.shape + + # If frames_chunk_size is not specified or greater than S, process all frames at once + if frames_chunk_size is None or frames_chunk_size >= S: + return self._forward_impl(aggregated_tokens_list, images, patch_start_idx) + + # Otherwise, process frames in chunks to manage memory usage + assert frames_chunk_size > 0 + + # Process frames in batches + all_preds = [] + all_conf = [] + + for frames_start_idx in range(0, S, frames_chunk_size): + frames_end_idx = min(frames_start_idx + frames_chunk_size, S) + + # Process batch of frames + if self.feature_only: + chunk_output = self._forward_impl( + aggregated_tokens_list, images, patch_start_idx, frames_start_idx, frames_end_idx + ) + all_preds.append(chunk_output) + else: + chunk_preds, chunk_conf = self._forward_impl( + aggregated_tokens_list, images, patch_start_idx, frames_start_idx, frames_end_idx + ) + all_preds.append(chunk_preds) + all_conf.append(chunk_conf) + + # Concatenate results along the sequence dimension + if self.feature_only: + return torch.cat(all_preds, dim=1) + else: + return torch.cat(all_preds, dim=1), torch.cat(all_conf, dim=1) + + def _forward_impl( + self, + aggregated_tokens_list: List[torch.Tensor], + images: torch.Tensor, + patch_start_idx: int, + frames_start_idx: int = None, + frames_end_idx: int = None, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: + """ + Implementation of the forward pass through the DPT head. + + This method processes a specific chunk of frames from the sequence. + + Args: + aggregated_tokens_list (List[Tensor]): List of token tensors from different transformer layers. + images (Tensor): Input images with shape [B, S, 3, H, W]. + patch_start_idx (int): Starting index for patch tokens. + frames_start_idx (int, optional): Starting index for frames to process. + frames_end_idx (int, optional): Ending index for frames to process. + + Returns: + Tensor or Tuple[Tensor, Tensor]: Feature maps or (predictions, confidence). + """ + if frames_start_idx is not None and frames_end_idx is not None: + images = images[:, frames_start_idx:frames_end_idx].contiguous() + + B, S, _, H, W = images.shape + + patch_h, patch_w = H // self.patch_size, W // self.patch_size + + out = [] + dpt_idx = 0 + + for layer_idx in self.intermediate_layer_idx: + x = aggregated_tokens_list[layer_idx][:, :, patch_start_idx:] + + # Select frames if processing a chunk + if frames_start_idx is not None and frames_end_idx is not None: + x = x[:, frames_start_idx:frames_end_idx] + + x = x.view(B * S, -1, x.shape[-1]) + + x = self.norm(x) + + x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w)) + + x = self.projects[dpt_idx](x) + if self.pos_embed: + x = self._apply_pos_embed(x, W, H) + x = self.resize_layers[dpt_idx](x) + + out.append(x) + dpt_idx += 1 + + # Fuse features from multiple layers. + out = self.scratch_forward(out) + # Interpolate fused output to match target image resolution. + out = custom_interpolate( + out, + (int(patch_h * self.patch_size / self.down_ratio), int(patch_w * self.patch_size / self.down_ratio)), + mode="bilinear", + align_corners=True, + ) + + if self.pos_embed: + out = self._apply_pos_embed(out, W, H) + + if self.feature_only: + return out.view(B, S, *out.shape[1:]) + + out = self.scratch.output_conv2(out) + preds, conf = activate_head(out, activation=self.activation, conf_activation=self.conf_activation) + + preds = preds.view(B, S, *preds.shape[1:]) + conf = conf.view(B, S, *conf.shape[1:]) + return preds, conf + + def _apply_pos_embed(self, x: torch.Tensor, W: int, H: int, ratio: float = 0.1) -> torch.Tensor: + """ + Apply positional embedding to tensor x. + """ + patch_w = x.shape[-1] + patch_h = x.shape[-2] + pos_embed = create_uv_grid(patch_w, patch_h, aspect_ratio=W / H, dtype=x.dtype, device=x.device) + pos_embed = position_grid_to_embed(pos_embed, x.shape[1]) + pos_embed = pos_embed * ratio + pos_embed = pos_embed.permute(2, 0, 1)[None].expand(x.shape[0], -1, -1, -1) + return x + pos_embed + + def scratch_forward(self, features: List[torch.Tensor]) -> torch.Tensor: + """ + Forward pass through the fusion blocks. + + Args: + features (List[Tensor]): List of feature maps from different layers. + + Returns: + Tensor: Fused feature map. + """ + layer_1, layer_2, layer_3, layer_4 = features + + layer_1_rn = self.scratch.layer1_rn(layer_1) + layer_2_rn = self.scratch.layer2_rn(layer_2) + layer_3_rn = self.scratch.layer3_rn(layer_3) + layer_4_rn = self.scratch.layer4_rn(layer_4) + + out = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:]) + del layer_4_rn, layer_4 + + out = self.scratch.refinenet3(out, layer_3_rn, size=layer_2_rn.shape[2:]) + del layer_3_rn, layer_3 + + out = self.scratch.refinenet2(out, layer_2_rn, size=layer_1_rn.shape[2:]) + del layer_2_rn, layer_2 + + out = self.scratch.refinenet1(out, layer_1_rn) + del layer_1_rn, layer_1 + + out = self.scratch.output_conv1(out) + return out + + +################################################################################ +# Modules +################################################################################ + + +def _make_fusion_block(features: int, size: int = None, has_residual: bool = True, groups: int = 1) -> nn.Module: + return FeatureFusionBlock( + features, + nn.ReLU(inplace=True), + deconv=False, + bn=False, + expand=False, + align_corners=True, + size=size, + has_residual=has_residual, + groups=groups, + ) + + +def _make_scratch(in_shape: List[int], out_shape: int, groups: int = 1, expand: bool = False) -> nn.Module: + scratch = nn.Module() + out_shape1 = out_shape + out_shape2 = out_shape + out_shape3 = out_shape + if len(in_shape) >= 4: + out_shape4 = out_shape + + if expand: + out_shape1 = out_shape + out_shape2 = out_shape * 2 + out_shape3 = out_shape * 4 + if len(in_shape) >= 4: + out_shape4 = out_shape * 8 + + scratch.layer1_rn = nn.Conv2d( + in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + scratch.layer2_rn = nn.Conv2d( + in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + scratch.layer3_rn = nn.Conv2d( + in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + if len(in_shape) >= 4: + scratch.layer4_rn = nn.Conv2d( + in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups + ) + return scratch + + +class ResidualConvUnit(nn.Module): + """Residual convolution module.""" + + def __init__(self, features, activation, bn, groups=1): + """Init. + + Args: + features (int): number of features + """ + super().__init__() + + self.bn = bn + self.groups = groups + self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups) + self.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups) + + self.norm1 = None + self.norm2 = None + + self.activation = activation + self.skip_add = nn.quantized.FloatFunctional() + + def forward(self, x): + """Forward pass. + + Args: + x (tensor): input + + Returns: + tensor: output + """ + + out = self.activation(x) + out = self.conv1(out) + if self.norm1 is not None: + out = self.norm1(out) + + out = self.activation(out) + out = self.conv2(out) + if self.norm2 is not None: + out = self.norm2(out) + + return self.skip_add.add(out, x) + + +class FeatureFusionBlock(nn.Module): + """Feature fusion block.""" + + def __init__( + self, + features, + activation, + deconv=False, + bn=False, + expand=False, + align_corners=True, + size=None, + has_residual=True, + groups=1, + ): + """Init. + + Args: + features (int): number of features + """ + super(FeatureFusionBlock, self).__init__() + + self.deconv = deconv + self.align_corners = align_corners + self.groups = groups + self.expand = expand + out_features = features + if self.expand == True: + out_features = features // 2 + + self.out_conv = nn.Conv2d( + features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=self.groups + ) + + if has_residual: + self.resConfUnit1 = ResidualConvUnit(features, activation, bn, groups=self.groups) + + self.has_residual = has_residual + self.resConfUnit2 = ResidualConvUnit(features, activation, bn, groups=self.groups) + + self.skip_add = nn.quantized.FloatFunctional() + self.size = size + + def forward(self, *xs, size=None): + """Forward pass. + + Returns: + tensor: output + """ + output = xs[0] + + if self.has_residual: + res = self.resConfUnit1(xs[1]) + output = self.skip_add.add(output, res) + + output = self.resConfUnit2(output) + + if (size is None) and (self.size is None): + modifier = {"scale_factor": 2} + elif size is None: + modifier = {"size": self.size} + else: + modifier = {"size": size} + + output = custom_interpolate(output, **modifier, mode="bilinear", align_corners=self.align_corners) + output = self.out_conv(output) + + return output + + +def custom_interpolate( + x: torch.Tensor, + size: Tuple[int, int] = None, + scale_factor: float = None, + mode: str = "bilinear", + align_corners: bool = True, +) -> torch.Tensor: + """ + Custom interpolate to avoid INT_MAX issues in nn.functional.interpolate. + """ + if size is None: + size = (int(x.shape[-2] * scale_factor), int(x.shape[-1] * scale_factor)) + + INT_MAX = 1610612736 + + input_elements = size[0] * size[1] * x.shape[0] * x.shape[1] + + if input_elements > INT_MAX: + chunks = torch.chunk(x, chunks=(input_elements // INT_MAX) + 1, dim=0) + interpolated_chunks = [ + nn.functional.interpolate(chunk, size=size, mode=mode, align_corners=align_corners) for chunk in chunks + ] + x = torch.cat(interpolated_chunks, dim=0) + return x.contiguous() + else: + return nn.functional.interpolate(x, size=size, mode=mode, align_corners=align_corners) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/models/heads/head_act.py b/OVOW/engine/oneposeviagen/trellis/trellis/models/heads/head_act.py new file mode 100644 index 0000000000000000000000000000000000000000..5b33511408cac0dbbe75825b382b47e58ed42588 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/models/heads/head_act.py @@ -0,0 +1,126 @@ + +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + + +import torch +import torch.nn.functional as F + + +def activate_pose(pred_pose_enc, trans_act="linear", quat_act="linear", fl_act="linear"): + """ + Activate pose parameters with specified activation functions. + + Args: + pred_pose_enc: Tensor containing encoded pose parameters [translation, quaternion, focal length] + trans_act: Activation type for translation component + quat_act: Activation type for quaternion component + fl_act: Activation type for focal length component + + Returns: + Activated pose parameters tensor + """ + T = pred_pose_enc[..., :3] + quat = pred_pose_enc[..., 3:7] + fl = pred_pose_enc[..., 7:] # or fov + + T = base_pose_act(T, trans_act) + quat = base_pose_act(quat, quat_act) + fl = base_pose_act(fl, fl_act) # or fov + + pred_pose_enc = torch.cat([T, quat, fl], dim=-1) + + return pred_pose_enc + + +def base_pose_act(pose_enc, act_type="linear"): + """ + Apply basic activation function to pose parameters. + + Args: + pose_enc: Tensor containing encoded pose parameters + act_type: Activation type ("linear", "inv_log", "exp", "relu") + + Returns: + Activated pose parameters + """ + if act_type == "linear": + return pose_enc + elif act_type == "inv_log": + return inverse_log_transform(pose_enc) + elif act_type == "exp": + return torch.exp(pose_enc) + elif act_type == "relu": + return F.relu(pose_enc) + else: + raise ValueError(f"Unknown act_type: {act_type}") + + +def activate_head(out, activation="norm_exp", conf_activation="expp1"): + """ + Process network output to extract 3D points and confidence values. + + Args: + out: Network output tensor (B, C, H, W) + activation: Activation type for 3D points + conf_activation: Activation type for confidence values + + Returns: + Tuple of (3D points tensor, confidence tensor) + """ + # Move channels from last dim to the 4th dimension => (B, H, W, C) + fmap = out.permute(0, 2, 3, 1) # B,H,W,C expected + + # Split into xyz (first C-1 channels) and confidence (last channel) + xyz = fmap[:, :, :, :-1] + conf = fmap[:, :, :, -1] + + if activation == "norm_exp": + d = xyz.norm(dim=-1, keepdim=True).clamp(min=1e-8) + xyz_normed = xyz / d + pts3d = xyz_normed * torch.expm1(d) + elif activation == "norm": + pts3d = xyz / xyz.norm(dim=-1, keepdim=True) + elif activation == "exp": + pts3d = torch.exp(xyz) + elif activation == "relu": + pts3d = F.relu(xyz) + elif activation == "inv_log": + pts3d = inverse_log_transform(xyz) + elif activation == "xy_inv_log": + xy, z = xyz.split([2, 1], dim=-1) + z = inverse_log_transform(z) + pts3d = torch.cat([xy * z, z], dim=-1) + elif activation == "sigmoid": + pts3d = torch.sigmoid(xyz) + elif activation == "linear": + pts3d = xyz + else: + raise ValueError(f"Unknown activation: {activation}") + + if conf_activation == "expp1": + conf_out = 1 + conf.exp() + elif conf_activation == "expp0": + conf_out = conf.exp() + elif conf_activation == "sigmoid": + conf_out = torch.sigmoid(conf) + else: + raise ValueError(f"Unknown conf_activation: {conf_activation}") + + return pts3d, conf_out + + +def inverse_log_transform(y): + """ + Apply inverse log transform: sign(y) * (exp(|y|) - 1) + + Args: + y: Input tensor + + Returns: + Transformed tensor + """ + return torch.sign(y) * (torch.expm1(torch.abs(y))) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/models/heads/utils.py b/OVOW/engine/oneposeviagen/trellis/trellis/models/heads/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..26a22ef30e26bb340f34dcd083333aaaf205c2d9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/models/heads/utils.py @@ -0,0 +1,108 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn + + +def position_grid_to_embed(pos_grid: torch.Tensor, embed_dim: int, omega_0: float = 100) -> torch.Tensor: + """ + Convert 2D position grid (HxWx2) to sinusoidal embeddings (HxWxC) + + Args: + pos_grid: Tensor of shape (H, W, 2) containing 2D coordinates + embed_dim: Output channel dimension for embeddings + + Returns: + Tensor of shape (H, W, embed_dim) with positional embeddings + """ + H, W, grid_dim = pos_grid.shape + assert grid_dim == 2 + pos_flat = pos_grid.reshape(-1, grid_dim) # Flatten to (H*W, 2) + + # Process x and y coordinates separately + emb_x = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 0], omega_0=omega_0) # [1, H*W, D/2] + emb_y = make_sincos_pos_embed(embed_dim // 2, pos_flat[:, 1], omega_0=omega_0) # [1, H*W, D/2] + + # Combine and reshape + emb = torch.cat([emb_x, emb_y], dim=-1) # [1, H*W, D] + + return emb.view(H, W, embed_dim) # [H, W, D] + + +def make_sincos_pos_embed(embed_dim: int, pos: torch.Tensor, omega_0: float = 100) -> torch.Tensor: + """ + This function generates a 1D positional embedding from a given grid using sine and cosine functions. + + Args: + - embed_dim: The embedding dimension. + - pos: The position to generate the embedding from. + + Returns: + - emb: The generated 1D positional embedding. + """ + assert embed_dim % 2 == 0 + omega = torch.arange(embed_dim // 2, dtype=torch.double, device=pos.device) + omega /= embed_dim / 2.0 + omega = 1.0 / omega_0**omega # (D/2,) + + pos = pos.reshape(-1) # (M,) + out = torch.einsum("m,d->md", pos, omega) # (M, D/2), outer product + + emb_sin = torch.sin(out) # (M, D/2) + emb_cos = torch.cos(out) # (M, D/2) + + emb = torch.cat([emb_sin, emb_cos], dim=1) # (M, D) + return emb.float() + + +# Inspired by https://github.com/microsoft/moge + + +def create_uv_grid( + width: int, height: int, aspect_ratio: float = None, dtype: torch.dtype = None, device: torch.device = None +) -> torch.Tensor: + """ + Create a normalized UV grid of shape (width, height, 2). + + The grid spans horizontally and vertically according to an aspect ratio, + ensuring the top-left corner is at (-x_span, -y_span) and the bottom-right + corner is at (x_span, y_span), normalized by the diagonal of the plane. + + Args: + width (int): Number of points horizontally. + height (int): Number of points vertically. + aspect_ratio (float, optional): Width-to-height ratio. Defaults to width/height. + dtype (torch.dtype, optional): Data type of the resulting tensor. + device (torch.device, optional): Device on which the tensor is created. + + Returns: + torch.Tensor: A (width, height, 2) tensor of UV coordinates. + """ + # Derive aspect ratio if not explicitly provided + if aspect_ratio is None: + aspect_ratio = float(width) / float(height) + + # Compute normalized spans for X and Y + diag_factor = (aspect_ratio**2 + 1.0) ** 0.5 + span_x = aspect_ratio / diag_factor + span_y = 1.0 / diag_factor + + # Establish the linspace boundaries + left_x = -span_x * (width - 1) / width + right_x = span_x * (width - 1) / width + top_y = -span_y * (height - 1) / height + bottom_y = span_y * (height - 1) / height + + # Generate 1D coordinates + x_coords = torch.linspace(left_x, right_x, steps=width, dtype=dtype, device=device) + y_coords = torch.linspace(top_y, bottom_y, steps=height, dtype=dtype, device=device) + + # Create 2D meshgrid (width x height) and stack into UV + uu, vv = torch.meshgrid(x_coords, y_coords, indexing="xy") + uv_grid = torch.stack((uu, vv), dim=-1) + + return uv_grid \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/models/sparse_structure_flow.py b/OVOW/engine/oneposeviagen/trellis/trellis/models/sparse_structure_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..2b1b210231ace2e22f1c7b31eef26e3fb2976091 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/models/sparse_structure_flow.py @@ -0,0 +1,230 @@ +from typing import * +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from ..modules.utils import convert_module_to_f16, convert_module_to_f32, convert_module_to_bf16 +from ..modules.transformer import AbsolutePositionEmbedder, ModulatedTransformerCrossBlock +from ..modules.spatial import patchify, unpatchify + + +class TimestepEmbedder(nn.Module): + """ + Embeds scalar timesteps into vector representations. + """ + def __init__(self, hidden_size, frequency_embedding_size=256): + super().__init__() + self.mlp = nn.Sequential( + nn.Linear(frequency_embedding_size, hidden_size, bias=True), + nn.SiLU(), + nn.Linear(hidden_size, hidden_size, bias=True), + ) + self.frequency_embedding_size = frequency_embedding_size + + @staticmethod + def timestep_embedding(t, dim, max_period=10000): + """ + Create sinusoidal timestep embeddings. + + Args: + t: a 1-D Tensor of N indices, one per batch element. + These may be fractional. + dim: the dimension of the output. + max_period: controls the minimum frequency of the embeddings. + + Returns: + an (N, D) Tensor of positional embeddings. + """ + # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py + half = dim // 2 + freqs = torch.exp( + -np.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half + ).to(device=t.device) + args = t[:, None].float() * freqs[None] + embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) + if dim % 2: + embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) + return embedding + + def forward(self, t): + t_freq = self.timestep_embedding(t, self.frequency_embedding_size) + t_emb = self.mlp(t_freq) + return t_emb + + +class SparseStructureFlowModel(nn.Module): + def __init__( + self, + resolution: int, + in_channels: int, + model_channels: int, + cond_channels: int, + out_channels: int, + num_blocks: int, + num_heads: Optional[int] = None, + num_head_channels: Optional[int] = 64, + mlp_ratio: float = 4, + patch_size: int = 2, + pe_mode: Literal["ape", "rope"] = "ape", + use_fp16: bool = False, + use_bf16: bool = False, + use_checkpoint: bool = False, + share_mod: bool = False, + qk_rms_norm: bool = False, + qk_rms_norm_cross: bool = False, + ): + super().__init__() + self.resolution = resolution + self.in_channels = in_channels + self.model_channels = model_channels + self.cond_channels = cond_channels + self.out_channels = out_channels + self.num_blocks = num_blocks + self.num_heads = num_heads or model_channels // num_head_channels + self.mlp_ratio = mlp_ratio + self.patch_size = patch_size + self.pe_mode = pe_mode + self.use_fp16 = use_fp16 + self.use_bf16 = use_bf16 + self.use_checkpoint = use_checkpoint + self.share_mod = share_mod + self.qk_rms_norm = qk_rms_norm + self.qk_rms_norm_cross = qk_rms_norm_cross + if use_fp16: + self.dtype = torch.float16 + elif use_bf16: + self.dtype = torch.bfloat16 + else: + self.dtype = torch.float32 + + self.t_embedder = TimestepEmbedder(model_channels) + if share_mod: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(model_channels, 6 * model_channels, bias=True) + ) + + if pe_mode == "ape": + self.pos_embedder = AbsolutePositionEmbedder(model_channels, 3) + coords = torch.meshgrid(*[torch.arange(res, device=self.device) for res in [resolution // patch_size] * 3], indexing='ij') + coords = torch.stack(coords, dim=-1).reshape(-1, 3) + pos_emb = self.pos_embedder(coords) + self.register_buffer("pos_emb", pos_emb) + + self.input_layer = nn.Linear(in_channels * patch_size**3, model_channels) + + self.blocks = nn.ModuleList([ + ModulatedTransformerCrossBlock( + model_channels, + cond_channels, + num_heads=self.num_heads, + mlp_ratio=self.mlp_ratio, + attn_mode='full', + use_checkpoint=self.use_checkpoint, + use_rope=(pe_mode == "rope"), + share_mod=share_mod, + qk_rms_norm=self.qk_rms_norm, + qk_rms_norm_cross=self.qk_rms_norm_cross, + ) + for _ in range(num_blocks) + ]) + + self.out_layer = nn.Linear(model_channels, out_channels * patch_size**3) + + self.initialize_weights() + if use_fp16: + self.convert_to_fp16() + elif use_bf16: + self.convert_to_bf16() + + @property + def device(self) -> torch.device: + """ + Return the device of the model. + """ + return next(self.parameters()).device + + def convert_to_fp16(self) -> None: + """ + Convert the torso of the model to float16. + """ + self.use_fp16 = True + self.use_bf16 = False + self.dtype = torch.float16 + self.blocks.apply(convert_module_to_f16) + + def convert_to_bf16(self) -> None: + """ + Convert the torso of the model to bfloat16. + """ + self.use_fp16 = False + self.use_bf16 = True + self.dtype = torch.bfloat16 + self.blocks.apply(convert_module_to_bf16) + + def convert_to_fp32(self) -> None: + """ + Convert the torso of the model to float32. + """ + self.use_fp16 = False + self.use_bf16 = False + self.dtype = torch.float32 + self.blocks.apply(convert_module_to_f32) + + def initialize_weights(self) -> None: + # Initialize transformer layers: + def _basic_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + self.apply(_basic_init) + + # Initialize timestep embedding MLP: + nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) + nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02) + + # Zero-out adaLN modulation layers in DiT blocks: + if self.share_mod: + nn.init.constant_(self.adaLN_modulation[-1].weight, 0) + nn.init.constant_(self.adaLN_modulation[-1].bias, 0) + else: + for block in self.blocks: + nn.init.constant_(block.adaLN_modulation[-1].weight, 0) + nn.init.constant_(block.adaLN_modulation[-1].bias, 0) + + # Zero-out output layers: + nn.init.constant_(self.out_layer.weight, 0) + nn.init.constant_(self.out_layer.bias, 0) + + def forward(self, x: torch.Tensor, t: torch.Tensor, cond: torch.Tensor) -> torch.Tensor: + assert [*x.shape] == [x.shape[0], self.in_channels, *[self.resolution] * 3], \ + f"Input shape mismatch, got {x.shape}, expected {[x.shape[0], self.in_channels, *[self.resolution] * 3]}" + + h = patchify(x, self.patch_size) + h = h.view(*h.shape[:2], -1).permute(0, 2, 1).contiguous() + + h = self.input_layer(h) + h = h + self.pos_emb[None] + t_emb = self.t_embedder(t) + if self.share_mod: + t_emb = self.adaLN_modulation(t_emb) + t_emb = t_emb.type(self.dtype) + h = h.type(self.dtype) + if isinstance(cond, list): + for i in range(len(cond)): + cond_tmp = cond[i].type(self.dtype) + for block in self.blocks: + h = block(h, t_emb, cond_tmp) + else: + cond = cond.type(self.dtype) + for block in self.blocks: + h = block(h, t_emb, cond) + h = h.type(x.dtype) + h = F.layer_norm(h, h.shape[-1:]) + h = self.out_layer(h) + + h = h.permute(0, 2, 1).view(h.shape[0], h.shape[2], *[self.resolution // self.patch_size] * 3) + h = unpatchify(h, self.patch_size).contiguous() + + return h diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/models/sparse_structure_vae.py b/OVOW/engine/oneposeviagen/trellis/trellis/models/sparse_structure_vae.py new file mode 100644 index 0000000000000000000000000000000000000000..0e1f0da68a699e4d44fa337a40b77e1ea4021eba --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/models/sparse_structure_vae.py @@ -0,0 +1,394 @@ +from typing import * +import torch +import torch.nn as nn +import torch.nn.functional as F +from ..modules.norm import GroupNorm32, ChannelLayerNorm32 +from ..modules.spatial import pixel_shuffle_3d +from ..modules.utils import zero_module, convert_module_to_f16, convert_module_to_f32, convert_module_to_bf16 + + +def norm_layer(norm_type: str, *args, **kwargs) -> nn.Module: + """ + Return a normalization layer. + """ + if norm_type == "group": + return GroupNorm32(32, *args, **kwargs) + elif norm_type == "layer": + return ChannelLayerNorm32(*args, **kwargs) + else: + raise ValueError(f"Invalid norm type {norm_type}") + + +class ResBlock3d(nn.Module): + def __init__( + self, + channels: int, + out_channels: Optional[int] = None, + norm_type: Literal["group", "layer"] = "layer", + ): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + + self.norm1 = norm_layer(norm_type, channels) + self.norm2 = norm_layer(norm_type, self.out_channels) + self.conv1 = nn.Conv3d(channels, self.out_channels, 3, padding=1) + self.conv2 = zero_module(nn.Conv3d(self.out_channels, self.out_channels, 3, padding=1)) + self.skip_connection = nn.Conv3d(channels, self.out_channels, 1) if channels != self.out_channels else nn.Identity() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + h = self.norm1(x) + h = F.silu(h) + h = self.conv1(h) + h = self.norm2(h) + h = F.silu(h) + h = self.conv2(h) + h = h + self.skip_connection(x) + return h + + +class DownsampleBlock3d(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + mode: Literal["conv", "avgpool"] = "conv", + ): + assert mode in ["conv", "avgpool"], f"Invalid mode {mode}" + + super().__init__() + self.in_channels = in_channels + self.out_channels = out_channels + + if mode == "conv": + self.conv = nn.Conv3d(in_channels, out_channels, 2, stride=2) + elif mode == "avgpool": + assert in_channels == out_channels, "Pooling mode requires in_channels to be equal to out_channels" + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if hasattr(self, "conv"): + return self.conv(x) + else: + return F.avg_pool3d(x, 2) + +class ResBlock2d(nn.Module): + def __init__( + self, + channels: int, + out_channels: Optional[int] = None, + norm_type: Literal["group", "layer"] = "layer", + ): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + + self.norm1 = norm_layer(norm_type, channels) + self.norm2 = norm_layer(norm_type, self.out_channels) + self.conv1 = nn.Conv2d(channels, self.out_channels, 3, padding=1) + self.conv2 = zero_module(nn.Conv2d(self.out_channels, self.out_channels, 3, padding=1)) + self.skip_connection = nn.Conv2d(channels, self.out_channels, 1) if channels != self.out_channels else nn.Identity() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + h = self.norm1(x) + h = F.silu(h) + h = self.conv1(h) + h = self.norm2(h) + h = F.silu(h) + h = self.conv2(h) + h = h + self.skip_connection(x) + return h + + +class DownsampleBlock2d(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + mode: Literal["conv", "avgpool"] = "conv", + ): + assert mode in ["conv", "avgpool"], f"Invalid mode {mode}" + + super().__init__() + self.in_channels = in_channels + self.out_channels = out_channels + + if mode == "conv": + self.conv = nn.Conv2d(in_channels, out_channels, 2, stride=2) + elif mode == "avgpool": + assert in_channels == out_channels, "Pooling mode requires in_channels to be equal to out_channels" + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if hasattr(self, "conv"): + return self.conv(x) + else: + return F.avg_pool2d(x, 2) + +class UpsampleBlock3d(nn.Module): + def __init__( + self, + in_channels: int, + out_channels: int, + mode: Literal["conv", "nearest"] = "conv", + ): + assert mode in ["conv", "nearest"], f"Invalid mode {mode}" + + super().__init__() + self.in_channels = in_channels + self.out_channels = out_channels + + if mode == "conv": + self.conv = nn.Conv3d(in_channels, out_channels*8, 3, padding=1) + elif mode == "nearest": + assert in_channels == out_channels, "Nearest mode requires in_channels to be equal to out_channels" + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if hasattr(self, "conv"): + x = self.conv(x) + return pixel_shuffle_3d(x, 2) + else: + return F.interpolate(x, scale_factor=2, mode="nearest") + + +class SparseStructureEncoder(nn.Module): + """ + Encoder for Sparse Structure (\mathcal{E}_S in the paper Sec. 3.3). + + Args: + in_channels (int): Channels of the input. + latent_channels (int): Channels of the latent representation. + num_res_blocks (int): Number of residual blocks at each resolution. + channels (List[int]): Channels of the encoder blocks. + num_res_blocks_middle (int): Number of residual blocks in the middle. + norm_type (Literal["group", "layer"]): Type of normalization layer. + use_fp16 (bool): Whether to use FP16. + """ + def __init__( + self, + in_channels: int, + latent_channels: int, + num_res_blocks: int, + channels: List[int], + num_res_blocks_middle: int = 2, + norm_type: Literal["group", "layer"] = "layer", + use_fp16: bool = False, + use_bf16: bool = False, + ): + super().__init__() + self.in_channels = in_channels + self.latent_channels = latent_channels + self.num_res_blocks = num_res_blocks + self.channels = channels + self.num_res_blocks_middle = num_res_blocks_middle + self.norm_type = norm_type + self.use_fp16 = use_fp16 + self.use_bf16 = use_bf16 + if use_fp16: + self.dtype = torch.float16 + elif use_bf16: + self.dtype = torch.bfloat16 + else: + self.dtype = torch.float32 + + self.input_layer = nn.Conv3d(in_channels, channels[0], 3, padding=1) + + self.blocks = nn.ModuleList([]) + for i, ch in enumerate(channels): + self.blocks.extend([ + ResBlock3d(ch, ch) + for _ in range(num_res_blocks) + ]) + if i < len(channels) - 1: + self.blocks.append( + DownsampleBlock3d(ch, channels[i+1]) + ) + + self.middle_block = nn.Sequential(*[ + ResBlock3d(channels[-1], channels[-1]) + for _ in range(num_res_blocks_middle) + ]) + + self.out_layer = nn.Sequential( + norm_layer(norm_type, channels[-1]), + nn.SiLU(), + nn.Conv3d(channels[-1], latent_channels*2, 3, padding=1) + ) + + if use_fp16: + self.convert_to_fp16() + elif use_bf16: + self.convert_to_bf16() + + @property + def device(self) -> torch.device: + """ + Return the device of the model. + """ + return next(self.parameters()).device + + def convert_to_fp16(self) -> None: + """ + Convert the torso of the model to float16. + """ + self.use_fp16 = True + self.dtype = torch.float16 + self.blocks.apply(convert_module_to_f16) + self.middle_block.apply(convert_module_to_f16) + + def convert_to_bf16(self) -> None: + """ + Convert the torso of the model to float16. + """ + self.use_bf16 = True + self.dtype = torch.bfloat16 + self.blocks.apply(convert_module_to_bf16) + self.middle_block.apply(convert_module_to_bf16) + + def convert_to_fp32(self) -> None: + """ + Convert the torso of the model to float32. + """ + self.use_fp16 = False + self.dtype = torch.float32 + self.blocks.apply(convert_module_to_f32) + self.middle_block.apply(convert_module_to_f32) + + def forward(self, x: torch.Tensor, sample_posterior: bool = False, return_raw: bool = False) -> torch.Tensor: + h = self.input_layer(x) + h = h.type(self.dtype) + + for block in self.blocks: + h = block(h) + h = self.middle_block(h) + + h = h.type(x.dtype) + h = self.out_layer(h) + + mean, logvar = h.chunk(2, dim=1) + + if sample_posterior: + std = torch.exp(0.5 * logvar) + z = mean + std * torch.randn_like(std) + else: + z = mean + + if return_raw: + return z, mean, logvar + return z + + +class SparseStructureDecoder(nn.Module): + """ + Decoder for Sparse Structure (\mathcal{D}_S in the paper Sec. 3.3). + + Args: + out_channels (int): Channels of the output. + latent_channels (int): Channels of the latent representation. + num_res_blocks (int): Number of residual blocks at each resolution. + channels (List[int]): Channels of the decoder blocks. + num_res_blocks_middle (int): Number of residual blocks in the middle. + norm_type (Literal["group", "layer"]): Type of normalization layer. + use_fp16 (bool): Whether to use FP16. + """ + def __init__( + self, + out_channels: int, + latent_channels: int, + num_res_blocks: int, + channels: List[int], + num_res_blocks_middle: int = 2, + norm_type: Literal["group", "layer"] = "layer", + use_fp16: bool = False, + use_bf16: bool = False, + ): + super().__init__() + self.out_channels = out_channels + self.latent_channels = latent_channels + self.num_res_blocks = num_res_blocks + self.channels = channels + self.num_res_blocks_middle = num_res_blocks_middle + self.norm_type = norm_type + self.use_fp16 = use_fp16 + self.use_bf16 = use_bf16 + if use_fp16: + self.dtype = torch.float16 + elif use_bf16: + self.dtype = torch.bfloat16 + else: + self.dtype = torch.float32 + + self.input_layer = nn.Conv3d(latent_channels, channels[0], 3, padding=1) + + self.middle_block = nn.Sequential(*[ + ResBlock3d(channels[0], channels[0]) + for _ in range(num_res_blocks_middle) + ]) + + self.blocks = nn.ModuleList([]) + for i, ch in enumerate(channels): + self.blocks.extend([ + ResBlock3d(ch, ch) + for _ in range(num_res_blocks) + ]) + if i < len(channels) - 1: + self.blocks.append( + UpsampleBlock3d(ch, channels[i+1]) + ) + + self.out_layer = nn.Sequential( + norm_layer(norm_type, channels[-1]), + nn.SiLU(), + nn.Conv3d(channels[-1], out_channels, 3, padding=1) + ) + + if use_fp16: + self.convert_to_fp16() + elif use_bf16: + self.convert_to_bf16() + + @property + def device(self) -> torch.device: + """ + Return the device of the model. + """ + return next(self.parameters()).device + + def convert_to_fp16(self) -> None: + """ + Convert the torso of the model to float16. + """ + self.use_fp16 = True + self.dtype = torch.float16 + self.blocks.apply(convert_module_to_f16) + self.middle_block.apply(convert_module_to_f16) + + def convert_to_bf16(self) -> None: + """ + Convert the torso of the model to bfloat16. + """ + self.use_bf16 = True + self.dtype = torch.bfloat16 + self.blocks.apply(convert_module_to_bf16) + self.middle_block.apply(convert_module_to_bf16) + + def convert_to_fp32(self) -> None: + """ + Convert the torso of the model to float32. + """ + self.use_fp16 = False + self.use_bf16 = False + self.dtype = torch.float32 + self.blocks.apply(convert_module_to_f32) + self.middle_block.apply(convert_module_to_f32) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + h = self.input_layer(x) + + h = h.type(self.dtype) + + h = self.middle_block(h) + for block in self.blocks: + h = block(h) + + h = h.type(x.dtype) + h = self.out_layer(h) + return h diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_flow.py b/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..e6468aa4f65415b301eb5d44b8babb7c5e78d3ce --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_flow.py @@ -0,0 +1,342 @@ +from typing import * +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from ..modules.utils import zero_module, convert_module_to_f16, convert_module_to_f32, convert_module_to_bf16 +from ..modules.transformer import AbsolutePositionEmbedder +from ..modules.norm import LayerNorm32 +from ..modules import sparse as sp +from ..modules.sparse.transformer import ModulatedSparseTransformerCrossBlock +from .sparse_structure_flow import TimestepEmbedder + + +class SparseResBlock3d(nn.Module): + def __init__( + self, + channels: int, + emb_channels: int, + out_channels: Optional[int] = None, + downsample: bool = False, + upsample: bool = False, + ): + super().__init__() + self.channels = channels + self.emb_channels = emb_channels + self.out_channels = out_channels or channels + self.downsample = downsample + self.upsample = upsample + + assert not (downsample and upsample), "Cannot downsample and upsample at the same time" + + self.norm1 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6) + self.norm2 = LayerNorm32(self.out_channels, elementwise_affine=False, eps=1e-6) + self.conv1 = sp.SparseConv3d(channels, self.out_channels, 3) + self.conv2 = zero_module(sp.SparseConv3d(self.out_channels, self.out_channels, 3)) + self.emb_layers = nn.Sequential( + nn.SiLU(), + nn.Linear(emb_channels, 2 * self.out_channels, bias=True), + ) + self.skip_connection = sp.SparseLinear(channels, self.out_channels) if channels != self.out_channels else nn.Identity() + self.updown = None + if self.downsample: + self.updown = sp.SparseDownsample(2) + elif self.upsample: + self.updown = sp.SparseUpsample(2) + + def _updown(self, x: sp.SparseTensor) -> sp.SparseTensor: + if self.updown is not None: + x = self.updown(x) + return x + + def forward(self, x: sp.SparseTensor, emb: torch.Tensor) -> sp.SparseTensor: + emb_out = self.emb_layers(emb).type(x.dtype) + scale, shift = torch.chunk(emb_out, 2, dim=1) + + x = self._updown(x) + h = x.replace(self.norm1(x.feats)) + h = h.replace(F.silu(h.feats)) + h = self.conv1(h) + h = h.replace(self.norm2(h.feats)) * (1 + scale) + shift + h = h.replace(F.silu(h.feats)) + h = self.conv2(h) + h = h + self.skip_connection(x) + + return h + +class SparseResBlock3dwoT(nn.Module): + def __init__( + self, + channels: int, + out_channels: Optional[int] = None, + downsample: bool = False, + upsample: bool = False, + ): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.downsample = downsample + self.upsample = upsample + + assert not (downsample and upsample), "Cannot downsample and upsample at the same time" + + self.norm1 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6) + self.norm2 = LayerNorm32(self.out_channels, elementwise_affine=False, eps=1e-6) + self.conv1 = sp.SparseConv3d(channels, self.out_channels, 3) + self.conv2 = zero_module(sp.SparseConv3d(self.out_channels, self.out_channels, 3)) + self.skip_connection = sp.SparseLinear(channels, self.out_channels) if channels != self.out_channels else nn.Identity() + self.updown = None + if self.downsample: + self.updown = sp.SparseDownsample(2) + elif self.upsample: + self.updown = sp.SparseUpsample(2) + + def _updown(self, x: sp.SparseTensor) -> sp.SparseTensor: + if self.updown is not None: + x = self.updown(x) + return x + + def forward(self, x: sp.SparseTensor) -> sp.SparseTensor: + + x = self._updown(x) + h = x.replace(self.norm1(x.feats)) + h = h.replace(F.silu(h.feats)) + h = self.conv1(h) + h = h.replace(F.silu(h.feats)) + h = self.conv2(h) + h = h + self.skip_connection(x) + + return h + +class SLatFlowModel(nn.Module): + def __init__( + self, + resolution: int, + in_channels: int, + model_channels: int, + cond_channels: int, + out_channels: int, + num_blocks: int, + num_heads: Optional[int] = None, + num_head_channels: Optional[int] = 64, + mlp_ratio: float = 4, + patch_size: int = 2, + num_io_res_blocks: int = 2, + io_block_channels: List[int] = None, + pe_mode: Literal["ape", "rope"] = "ape", + use_fp16: bool = False, + use_bf16: bool = False, + use_checkpoint: bool = False, + use_skip_connection: bool = True, + share_mod: bool = False, + qk_rms_norm: bool = False, + qk_rms_norm_cross: bool = False, + ): + super().__init__() + self.resolution = resolution + self.in_channels = in_channels + self.model_channels = model_channels + self.cond_channels = cond_channels + self.out_channels = out_channels + self.num_blocks = num_blocks + self.num_heads = num_heads or model_channels // num_head_channels + self.mlp_ratio = mlp_ratio + self.patch_size = patch_size + self.num_io_res_blocks = num_io_res_blocks + self.io_block_channels = io_block_channels + self.pe_mode = pe_mode + self.use_fp16 = use_fp16 + self.use_bf16 = use_bf16 + self.use_checkpoint = use_checkpoint + self.use_skip_connection = use_skip_connection + self.share_mod = share_mod + self.qk_rms_norm = qk_rms_norm + self.qk_rms_norm_cross = qk_rms_norm_cross + if use_fp16: + self.dtype = torch.float16 + elif use_bf16: + self.dtype = torch.bfloat16 + else: + self.dtype = torch.float32 + + assert int(np.log2(patch_size)) == np.log2(patch_size), "Patch size must be a power of 2" + assert np.log2(patch_size) == len(io_block_channels), "Number of IO ResBlocks must match the number of stages" + + self.t_embedder = TimestepEmbedder(model_channels) + if share_mod: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(model_channels, 6 * model_channels, bias=True) + ) + + if pe_mode == "ape": + self.pos_embedder = AbsolutePositionEmbedder(model_channels) + + self.input_layer = sp.SparseLinear(in_channels, io_block_channels[0]) + self.input_blocks = nn.ModuleList([]) + for chs, next_chs in zip(io_block_channels, io_block_channels[1:] + [model_channels]): + self.input_blocks.extend([ + SparseResBlock3d( + chs, + model_channels, + out_channels=chs, + ) + for _ in range(num_io_res_blocks-1) + ]) + self.input_blocks.append( + SparseResBlock3d( + chs, + model_channels, + out_channels=next_chs, + downsample=True, + ) + ) + + self.blocks = nn.ModuleList([ + ModulatedSparseTransformerCrossBlock( + model_channels, + cond_channels, + num_heads=self.num_heads, + mlp_ratio=self.mlp_ratio, + attn_mode='full', + use_checkpoint=self.use_checkpoint, + use_rope=(pe_mode == "rope"), + share_mod=self.share_mod, + qk_rms_norm=self.qk_rms_norm, + qk_rms_norm_cross=self.qk_rms_norm_cross, + ) + for _ in range(num_blocks) + ]) + + self.out_blocks = nn.ModuleList([]) + for chs, prev_chs in zip(reversed(io_block_channels), [model_channels] + list(reversed(io_block_channels[1:]))): + self.out_blocks.append( + SparseResBlock3d( + prev_chs * 2 if self.use_skip_connection else prev_chs, + model_channels, + out_channels=chs, + upsample=True, + ) + ) + self.out_blocks.extend([ + SparseResBlock3d( + chs * 2 if self.use_skip_connection else chs, + model_channels, + out_channels=chs, + ) + for _ in range(num_io_res_blocks-1) + ]) + self.out_layer = sp.SparseLinear(io_block_channels[0], out_channels) + + self.initialize_weights() + if use_fp16: + self.convert_to_fp16() + elif use_bf16: + self.convert_to_bf16() + else: + self.convert_to_fp32() + + + + @property + def device(self) -> torch.device: + """ + Return the device of the model. + """ + return next(self.parameters()).device + + def convert_to_fp16(self) -> None: + """ + Convert the torso of the model to float16. + """ + self.use_fp16 = True + self.use_bf16 = False + self.dtype = torch.float16 + self.input_blocks.apply(convert_module_to_f16) + self.blocks.apply(convert_module_to_f16) + self.out_blocks.apply(convert_module_to_f16) + + def convert_to_bf16(self) -> None: + """ + Convert the torso of the model to bfloat16. + """ + self.use_fp16 = False + self.use_bf16 = True + self.dtype = torch.bfloat16 + self.input_blocks.apply(convert_module_to_bf16) + self.blocks.apply(convert_module_to_bf16) + self.out_blocks.apply(convert_module_to_bf16) + + def convert_to_fp32(self) -> None: + """ + Convert the torso of the model to float32. + """ + self.use_fp16 = False + self.use_bf16 = False + self.dtype = torch.float32 + self.input_blocks.apply(convert_module_to_f32) + self.blocks.apply(convert_module_to_f32) + self.out_blocks.apply(convert_module_to_f32) + + def initialize_weights(self) -> None: + # Initialize transformer layers: + def _basic_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + self.apply(_basic_init) + + # Initialize timestep embedding MLP: + nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) + nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02) + + # Zero-out adaLN modulation layers in DiT blocks: + if self.share_mod: + nn.init.constant_(self.adaLN_modulation[-1].weight, 0) + nn.init.constant_(self.adaLN_modulation[-1].bias, 0) + else: + for block in self.blocks: + nn.init.constant_(block.adaLN_modulation[-1].weight, 0) + nn.init.constant_(block.adaLN_modulation[-1].bias, 0) + + # Zero-out output layers: + nn.init.constant_(self.out_layer.weight, 0) + nn.init.constant_(self.out_layer.bias, 0) + + def forward(self, x: sp.SparseTensor, t: torch.Tensor, cond: torch.Tensor) -> sp.SparseTensor: + h = self.input_layer(x).type(self.dtype) + t_emb = self.t_embedder(t) + if self.share_mod: + t_emb = self.adaLN_modulation(t_emb) + t_emb = t_emb.type(self.dtype) + + skips = [] + # pack with input blocks + for block in self.input_blocks: + h = block(h, t_emb) + skips.append(h.feats) + + if self.pe_mode == "ape": + h = h + self.pos_embedder(h.coords[:, 1:]).type(self.dtype) + + if isinstance(cond, list): + for i in range(len(cond)): + cond_tmp = cond[i].type(self.dtype) + for block in self.blocks: + h = block(h, t_emb, cond_tmp) + else: + cond = cond.type(self.dtype) + for block in self.blocks: + h = block(h, t_emb, cond) + + # unpack with output blocks + for block, skip in zip(self.out_blocks, reversed(skips)): + if self.use_skip_connection: + h = block(h.replace(torch.cat([h.feats, skip], dim=1)), t_emb) + else: + h = block(h, t_emb) + + h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:])) + h = self.out_layer(h.type(x.dtype)) + return h diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_vae/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_vae/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f5778511aeb082e11bf86543e6dbbe9f0dacb9a8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_vae/__init__.py @@ -0,0 +1,3 @@ +from .encoder import SLatEncoder +from .decoder_gs import SLatGaussianDecoder +from .decoder_mesh import SLatMeshDecoder diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_vae/base.py b/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_vae/base.py new file mode 100644 index 0000000000000000000000000000000000000000..d53b7945f35804d2669d02d1d0e799a3b840424d --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_vae/base.py @@ -0,0 +1,139 @@ +from typing import * +import torch +import torch.nn as nn +from ...modules.utils import convert_module_to_f16, convert_module_to_f32, convert_module_to_bf16 +from ...modules import sparse as sp +from ...modules.transformer import AbsolutePositionEmbedder +from ...modules.sparse.transformer import SparseTransformerBlock + + +def block_attn_config(self): + """ + Return the attention configuration of the model. + """ + for i in range(self.num_blocks): + if self.attn_mode == "shift_window": + yield "serialized", self.window_size, 0, (16 * (i % 2),) * 3, sp.SerializeMode.Z_ORDER + elif self.attn_mode == "shift_sequence": + yield "serialized", self.window_size, self.window_size // 2 * (i % 2), (0, 0, 0), sp.SerializeMode.Z_ORDER + elif self.attn_mode == "shift_order": + yield "serialized", self.window_size, 0, (0, 0, 0), sp.SerializeModes[i % 4] + elif self.attn_mode == "full": + yield "full", None, None, None, None + elif self.attn_mode == "swin": + yield "windowed", self.window_size, None, self.window_size // 2 * (i % 2), None + + +class SparseTransformerBase(nn.Module): + """ + Sparse Transformer without output layers. + Serve as the base class for encoder and decoder. + """ + def __init__( + self, + in_channels: int, + model_channels: int, + num_blocks: int, + num_heads: Optional[int] = None, + num_head_channels: Optional[int] = 64, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "full", + window_size: Optional[int] = None, + pe_mode: Literal["ape", "rope"] = "ape", + use_fp16: bool = False, + use_bf16: bool = False, + use_checkpoint: bool = False, + qk_rms_norm: bool = False, + ): + super().__init__() + self.in_channels = in_channels + self.model_channels = model_channels + self.num_blocks = num_blocks + self.window_size = window_size + self.num_heads = num_heads or model_channels // num_head_channels + self.mlp_ratio = mlp_ratio + self.attn_mode = attn_mode + self.pe_mode = pe_mode + self.use_fp16 = use_fp16 + self.use_bf16 = use_bf16 + self.use_checkpoint = use_checkpoint + self.qk_rms_norm = qk_rms_norm + if use_fp16: + self.dtype = torch.float16 + elif use_bf16: + self.dtype = torch.bfloat16 + else: + self.dtype = torch.float32 + + if pe_mode == "ape": + self.pos_embedder = AbsolutePositionEmbedder(model_channels) + + self.input_layer = sp.SparseLinear(in_channels, model_channels) + self.blocks = nn.ModuleList([ + SparseTransformerBlock( + model_channels, + num_heads=self.num_heads, + mlp_ratio=self.mlp_ratio, + attn_mode=attn_mode, + window_size=window_size, + shift_sequence=shift_sequence, + shift_window=shift_window, + serialize_mode=serialize_mode, + use_checkpoint=self.use_checkpoint, + use_rope=(pe_mode == "rope"), + qk_rms_norm=self.qk_rms_norm, + ) + for attn_mode, window_size, shift_sequence, shift_window, serialize_mode in block_attn_config(self) + ]) + + @property + def device(self) -> torch.device: + """ + Return the device of the model. + """ + return next(self.parameters()).device + + def convert_to_fp16(self) -> None: + """ + Convert the torso of the model to float16. + """ + self.use_fp16 = True + self.use_bf16 = False + self.dtype = torch.float16 + self.blocks.apply(convert_module_to_f16) + + def convert_to_bf16(self) -> None: + """ + Convert the torso of the model to bfloat16. + """ + self.use_fp16 = False + self.use_bf16 = True + self.dtype = torch.bfloat16 + self.blocks.apply(convert_module_to_bf16) + + def convert_to_fp32(self) -> None: + """ + Convert the torso of the model to float32. + """ + self.use_fp16 = False + self.use_bf16 = False + self.dtype = torch.float32 + self.blocks.apply(convert_module_to_f32) + + def initialize_weights(self) -> None: + # Initialize transformer layers: + def _basic_init(module): + if isinstance(module, nn.Linear): + torch.nn.init.xavier_uniform_(module.weight) + if module.bias is not None: + nn.init.constant_(module.bias, 0) + self.apply(_basic_init) + + def forward(self, x: sp.SparseTensor) -> sp.SparseTensor: + h = self.input_layer(x) + if self.pe_mode == "ape": + h = h + self.pos_embedder(x.coords[:, 1:]) + h = h.type(self.dtype) + for block in self.blocks: + h = block(h) + return h diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_vae/decoder_gs.py b/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_vae/decoder_gs.py new file mode 100644 index 0000000000000000000000000000000000000000..64af7ee785dc0877624a20ccea9bd160d313dccf --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_vae/decoder_gs.py @@ -0,0 +1,126 @@ +from typing import * +import torch +import torch.nn as nn +import torch.nn.functional as F +from ...modules import sparse as sp +from ...utils.random_utils import hammersley_sequence +from .base import SparseTransformerBase +from ...representations import Gaussian + + +class SLatGaussianDecoder(SparseTransformerBase): + def __init__( + self, + resolution: int, + model_channels: int, + latent_channels: int, + num_blocks: int, + num_heads: Optional[int] = None, + num_head_channels: Optional[int] = 64, + mlp_ratio: float = 4, + attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "swin", + window_size: int = 8, + pe_mode: Literal["ape", "rope"] = "ape", + use_fp16: bool = False, + use_bf16: bool = False, + use_checkpoint: bool = False, + qk_rms_norm: bool = False, + representation_config: dict = None, + ): + super().__init__( + in_channels=latent_channels, + model_channels=model_channels, + num_blocks=num_blocks, + num_heads=num_heads, + num_head_channels=num_head_channels, + mlp_ratio=mlp_ratio, + attn_mode=attn_mode, + window_size=window_size, + pe_mode=pe_mode, + use_fp16=use_fp16, + use_bf16=use_bf16, + use_checkpoint=use_checkpoint, + qk_rms_norm=qk_rms_norm, + ) + self.resolution = resolution + self.rep_config = representation_config + self._calc_layout() + self.out_layer = sp.SparseLinear(model_channels, self.out_channels) + self._build_perturbation() + + self.initialize_weights() + if use_fp16: + self.convert_to_fp16() + elif use_bf16: + self.convert_to_bf16() + + def initialize_weights(self) -> None: + super().initialize_weights() + # Zero-out output layers: + nn.init.constant_(self.out_layer.weight, 0) + nn.init.constant_(self.out_layer.bias, 0) + + def _build_perturbation(self) -> None: + perturbation = [hammersley_sequence(3, i, self.rep_config['num_gaussians']) for i in range(self.rep_config['num_gaussians'])] + perturbation = torch.tensor(perturbation).float() * 2 - 1 + perturbation = perturbation / self.rep_config['voxel_size'] + perturbation = torch.atanh(perturbation).to(self.device) + self.register_buffer('offset_perturbation', perturbation) + + def _calc_layout(self) -> None: + self.layout = { + '_xyz' : {'shape': (self.rep_config['num_gaussians'], 3), 'size': self.rep_config['num_gaussians'] * 3}, + '_features_dc' : {'shape': (self.rep_config['num_gaussians'], 1, 3), 'size': self.rep_config['num_gaussians'] * 3}, + '_scaling' : {'shape': (self.rep_config['num_gaussians'], 3), 'size': self.rep_config['num_gaussians'] * 3}, + '_rotation' : {'shape': (self.rep_config['num_gaussians'], 4), 'size': self.rep_config['num_gaussians'] * 4}, + '_opacity' : {'shape': (self.rep_config['num_gaussians'], 1), 'size': self.rep_config['num_gaussians']}, + } + start = 0 + for k, v in self.layout.items(): + v['range'] = (start, start + v['size']) + start += v['size'] + self.out_channels = start + + def to_representation(self, x: sp.SparseTensor) -> List[Gaussian]: + """ + Convert a batch of network outputs to 3D representations. + + Args: + x: The [N x * x C] sparse tensor output by the network. + + Returns: + list of representations + """ + ret = [] + for i in range(x.shape[0]): + representation = Gaussian( + sh_degree=0, + aabb=[-0.5, -0.5, -0.5, 1.0, 1.0, 1.0], + mininum_kernel_size = self.rep_config['3d_filter_kernel_size'], + scaling_bias = self.rep_config['scaling_bias'], + opacity_bias = self.rep_config['opacity_bias'], + scaling_activation = self.rep_config['scaling_activation'] + ) + xyz = (x.coords[x.layout[i]][:, 1:].float() + 0.5) / self.resolution + for k, v in self.layout.items(): + if k == '_xyz': + offset = x.feats[x.layout[i]][:, v['range'][0]:v['range'][1]].reshape(-1, *v['shape']) + offset = offset * self.rep_config['lr'][k] + if self.rep_config['perturb_offset']: + offset = offset + self.offset_perturbation + offset = torch.tanh(offset) / self.resolution * 0.5 * self.rep_config['voxel_size'] + _xyz = xyz.unsqueeze(1) + offset + setattr(representation, k, _xyz.flatten(0, 1)) + else: + feats = x.feats[x.layout[i]][:, v['range'][0]:v['range'][1]].reshape(-1, *v['shape']).flatten(0, 1) + feats = feats * self.rep_config['lr'][k] + setattr(representation, k, feats) + ret.append(representation) + return ret + + def forward(self, x: sp.SparseTensor) -> List[Gaussian]: + h = super().forward(x) + h = h.type(x.dtype) + h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:])) + h = self.out_layer(h) + return self.to_representation(h) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_vae/decoder_mesh.py b/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_vae/decoder_mesh.py new file mode 100644 index 0000000000000000000000000000000000000000..958dc3a73b4aa367162c850707bb393163b79e5a --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_vae/decoder_mesh.py @@ -0,0 +1,197 @@ +from typing import * +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from ...modules.utils import zero_module, convert_module_to_f16, convert_module_to_f32, convert_module_to_bf16 +from ...modules import sparse as sp +from .base import SparseTransformerBase +from ...representations import MeshExtractResult +from ...representations.mesh import SparseFeatures2Mesh + + +class SparseSubdivideBlock3d(nn.Module): + """ + A 3D subdivide block that can subdivide the sparse tensor. + + Args: + channels: channels in the inputs and outputs. + out_channels: if specified, the number of output channels. + num_groups: the number of groups for the group norm. + """ + def __init__( + self, + channels: int, + resolution: int, + out_channels: Optional[int] = None, + num_groups: int = 32 + ): + super().__init__() + self.channels = channels + self.resolution = resolution + self.out_resolution = resolution * 2 + self.out_channels = out_channels or channels + + self.act_layers = nn.Sequential( + sp.SparseGroupNorm32(num_groups, channels), + sp.SparseSiLU() + ) + + self.sub = sp.SparseSubdivide() + + self.out_layers = nn.Sequential( + sp.SparseConv3d(channels, self.out_channels, 3, indice_key=f"res_{self.out_resolution}"), + sp.SparseGroupNorm32(num_groups, self.out_channels), + sp.SparseSiLU(), + zero_module(sp.SparseConv3d(self.out_channels, self.out_channels, 3, indice_key=f"res_{self.out_resolution}")), + ) + + if self.out_channels == channels: + self.skip_connection = nn.Identity() + else: + self.skip_connection = sp.SparseConv3d(channels, self.out_channels, 1, indice_key=f"res_{self.out_resolution}") + + def forward(self, x: sp.SparseTensor) -> sp.SparseTensor: + """ + Apply the block to a Tensor, conditioned on a timestep embedding. + + Args: + x: an [N x C x ...] Tensor of features. + Returns: + an [N x C x ...] Tensor of outputs. + """ + h = self.act_layers(x) + h = self.sub(h) + x = self.sub(x) + h = self.out_layers(h) + h = h + self.skip_connection(x) + return h + + +class SLatMeshDecoder(SparseTransformerBase): + def __init__( + self, + resolution: int, + model_channels: int, + latent_channels: int, + num_blocks: int, + num_heads: Optional[int] = None, + num_head_channels: Optional[int] = 64, + mlp_ratio: float = 4, + attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "swin", + window_size: int = 8, + pe_mode: Literal["ape", "rope"] = "ape", + use_fp16: bool = False, + use_bf16: bool = False, + use_checkpoint: bool = False, + qk_rms_norm: bool = False, + representation_config: dict = None, + mesh_extractor: str = "fc", + ): + super().__init__( + in_channels=latent_channels, + model_channels=model_channels, + num_blocks=num_blocks, + num_heads=num_heads, + num_head_channels=num_head_channels, + mlp_ratio=mlp_ratio, + attn_mode=attn_mode, + window_size=window_size, + pe_mode=pe_mode, + use_fp16=use_fp16, + use_bf16=use_bf16, + use_checkpoint=use_checkpoint, + qk_rms_norm=qk_rms_norm, + ) + self.resolution = resolution + self.rep_config = representation_config + if mesh_extractor == "mc": + try: + from ...representations.mesh import SparseFeatures2MCMesh + self.mesh_extractor = SparseFeatures2MCMesh(res=self.resolution*4, use_color=self.rep_config.get('use_color', False)) + except ImportError: + raise ValueError("SparseFeatures2MCMesh is not available. Please install the 'mc2mesh' extra.") + elif mesh_extractor == "fc": + self.mesh_extractor = SparseFeatures2Mesh(res=self.resolution*4, use_color=self.rep_config.get('use_color', False)) + else: + raise ValueError(f"Invalid mesh extractor {mesh_extractor}") + self.out_channels = self.mesh_extractor.feats_channels + self.upsample = nn.ModuleList([ + SparseSubdivideBlock3d( + channels=model_channels, + resolution=resolution, + out_channels=model_channels // 4 + ), + SparseSubdivideBlock3d( + channels=model_channels // 4, + resolution=resolution * 2, + out_channels=model_channels // 8 + ) + ]) + self.out_layer = sp.SparseLinear(model_channels // 8, self.out_channels) + + self.initialize_weights() + if use_fp16: + self.convert_to_fp16() + elif use_bf16: + self.convert_to_bf16() + + def initialize_weights(self) -> None: + super().initialize_weights() + # Zero-out output layers: + nn.init.constant_(self.out_layer.weight, 0) + nn.init.constant_(self.out_layer.bias, 0) + + def convert_to_fp16(self) -> None: + """ + Convert the torso of the model to float16. + """ + self.use_fp16 = True + self.use_bf16 = False + self.dtype = torch.float16 + super().convert_to_fp16() + self.upsample.apply(convert_module_to_f16) + + def convert_to_bf16(self) -> None: + """ + Convert the torso of the model to bfloat16. + """ + self.use_fp16 = False + self.use_bf16 = True + self.dtype = torch.bfloat16 + super().convert_to_bf16() + self.upsample.apply(convert_module_to_bf16) + + def convert_to_fp32(self) -> None: + """ + Convert the torso of the model to float32. + """ + self.use_fp16 = False + self.use_bf16 = False + self.dtype = torch.float32 + super().convert_to_fp32() + self.upsample.apply(convert_module_to_f32) + + def to_representation(self, x: sp.SparseTensor) -> List[MeshExtractResult]: + """ + Convert a batch of network outputs to 3D representations. + + Args: + x: The [N x * x C] sparse tensor output by the network. + + Returns: + list of representations + """ + ret = [] + for i in range(x.shape[0]): + mesh = self.mesh_extractor(x[i], training=self.training) + ret.append(mesh) + return ret + + def forward(self, x: sp.SparseTensor) -> List[MeshExtractResult]: + h = super().forward(x) + for block in self.upsample: + h = block(h) + h = h.type(x.dtype) + h = self.out_layer(h) + return self.to_representation(h) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_vae/encoder.py b/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_vae/encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..fd6eb07f66cec833ba0ea228b77f3645431ed0d1 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/models/structured_latent_vae/encoder.py @@ -0,0 +1,76 @@ +from typing import * +import torch +import torch.nn as nn +import torch.nn.functional as F +from ...modules import sparse as sp +from .base import SparseTransformerBase + + +class SLatEncoder(SparseTransformerBase): + def __init__( + self, + resolution: int, + in_channels: int, + model_channels: int, + latent_channels: int, + num_blocks: int, + num_heads: Optional[int] = None, + num_head_channels: Optional[int] = 64, + mlp_ratio: float = 4, + attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "swin", + window_size: int = 8, + pe_mode: Literal["ape", "rope"] = "ape", + use_fp16: bool = False, + use_bf16: bool = False, + use_checkpoint: bool = False, + qk_rms_norm: bool = False, + ): + super().__init__( + in_channels=in_channels, + model_channels=model_channels, + num_blocks=num_blocks, + num_heads=num_heads, + num_head_channels=num_head_channels, + mlp_ratio=mlp_ratio, + attn_mode=attn_mode, + window_size=window_size, + pe_mode=pe_mode, + use_fp16=use_fp16, + use_bf16=use_bf16, + use_checkpoint=use_checkpoint, + qk_rms_norm=qk_rms_norm, + ) + self.resolution = resolution + self.out_layer = sp.SparseLinear(model_channels, 2 * latent_channels) + + self.initialize_weights() + if use_fp16: + self.convert_to_fp16() + elif use_bf16: + self.convert_to_bf16() + + def initialize_weights(self) -> None: + super().initialize_weights() + # Zero-out output layers: + nn.init.constant_(self.out_layer.weight, 0) + nn.init.constant_(self.out_layer.bias, 0) + + def forward(self, x: sp.SparseTensor, sample_posterior=True, return_raw=False): + h = super().forward(x) + h = h.type(x.dtype) + h = h.replace(F.layer_norm(h.feats, h.feats.shape[-1:])) + h = self.out_layer(h) + + # Sample from the posterior distribution + mean, logvar = h.feats.chunk(2, dim=-1) + if sample_posterior: + std = torch.exp(0.5 * logvar) + z = mean + std * torch.randn_like(std) + else: + z = mean + z = h.replace(z) + + if return_raw: + return z, mean, logvar + else: + return z diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/attention/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/attention/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..beb3911636c62306acfd463cc891337bf303705c --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/attention/__init__.py @@ -0,0 +1,38 @@ +from typing import * + +BACKEND = 'xformers' +# BACKEND = 'flash_attn' + +DEBUG = False + +def __from_env(): + import os + + global BACKEND + global DEBUG + + env_attn_backend = os.environ.get('ATTN_BACKEND') + env_sttn_debug = os.environ.get('ATTN_DEBUG') + + if env_attn_backend is not None and env_attn_backend in ['xformers', 'flash_attn', 'sdpa', 'naive']: + BACKEND = env_attn_backend + if env_sttn_debug is not None: + DEBUG = env_sttn_debug == '1' + + print(f"[ATTENTION] Using backend: {BACKEND}") + + +__from_env() + + +def set_backend(backend: Literal['xformers', 'flash_attn']): + global BACKEND + BACKEND = backend + +def set_debug(debug: bool): + global DEBUG + DEBUG = debug + + +from .full_attn import * +from .modules import * diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/attention/full_attn.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/attention/full_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..d9ebf6380a78906d4c6e969c63223fb7b398e5a7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/attention/full_attn.py @@ -0,0 +1,140 @@ +from typing import * +import torch +import math +from . import DEBUG, BACKEND + +if BACKEND == 'xformers': + import xformers.ops as xops +elif BACKEND == 'flash_attn': + import flash_attn +elif BACKEND == 'sdpa': + from torch.nn.functional import scaled_dot_product_attention as sdpa +elif BACKEND == 'naive': + pass +else: + raise ValueError(f"Unknown attention backend: {BACKEND}") + + +__all__ = [ + 'scaled_dot_product_attention', +] + + +def _naive_sdpa(q, k, v): + """ + Naive implementation of scaled dot product attention. + """ + q = q.permute(0, 2, 1, 3) # [N, H, L, C] + k = k.permute(0, 2, 1, 3) # [N, H, L, C] + v = v.permute(0, 2, 1, 3) # [N, H, L, C] + scale_factor = 1 / math.sqrt(q.size(-1)) + attn_weight = q @ k.transpose(-2, -1) * scale_factor + attn_weight = torch.softmax(attn_weight, dim=-1) + out = attn_weight @ v + out = out.permute(0, 2, 1, 3) # [N, L, H, C] + return out + + +@overload +def scaled_dot_product_attention(qkv: torch.Tensor) -> torch.Tensor: + """ + Apply scaled dot product attention. + + Args: + qkv (torch.Tensor): A [N, L, 3, H, C] tensor containing Qs, Ks, and Vs. + """ + ... + +@overload +def scaled_dot_product_attention(q: torch.Tensor, kv: torch.Tensor) -> torch.Tensor: + """ + Apply scaled dot product attention. + + Args: + q (torch.Tensor): A [N, L, H, C] tensor containing Qs. + kv (torch.Tensor): A [N, L, 2, H, C] tensor containing Ks and Vs. + """ + ... + +@overload +def scaled_dot_product_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor: + """ + Apply scaled dot product attention. + + Args: + q (torch.Tensor): A [N, L, H, Ci] tensor containing Qs. + k (torch.Tensor): A [N, L, H, Ci] tensor containing Ks. + v (torch.Tensor): A [N, L, H, Co] tensor containing Vs. + + Note: + k and v are assumed to have the same coordinate map. + """ + ... + +def scaled_dot_product_attention(*args, **kwargs): + arg_names_dict = { + 1: ['qkv'], + 2: ['q', 'kv'], + 3: ['q', 'k', 'v'] + } + num_all_args = len(args) + len(kwargs) + assert num_all_args in arg_names_dict, f"Invalid number of arguments, got {num_all_args}, expected 1, 2, or 3" + for key in arg_names_dict[num_all_args][len(args):]: + assert key in kwargs, f"Missing argument {key}" + + if num_all_args == 1: + qkv = args[0] if len(args) > 0 else kwargs['qkv'] + assert len(qkv.shape) == 5 and qkv.shape[2] == 3, f"Invalid shape for qkv, got {qkv.shape}, expected [N, L, 3, H, C]" + device = qkv.device + + elif num_all_args == 2: + q = args[0] if len(args) > 0 else kwargs['q'] + kv = args[1] if len(args) > 1 else kwargs['kv'] + assert q.shape[0] == kv.shape[0], f"Batch size mismatch, got {q.shape[0]} and {kv.shape[0]}" + assert len(q.shape) == 4, f"Invalid shape for q, got {q.shape}, expected [N, L, H, C]" + assert len(kv.shape) == 5, f"Invalid shape for kv, got {kv.shape}, expected [N, L, 2, H, C]" + device = q.device + + elif num_all_args == 3: + q = args[0] if len(args) > 0 else kwargs['q'] + k = args[1] if len(args) > 1 else kwargs['k'] + v = args[2] if len(args) > 2 else kwargs['v'] + assert q.shape[0] == k.shape[0] == v.shape[0], f"Batch size mismatch, got {q.shape[0]}, {k.shape[0]}, and {v.shape[0]}" + assert len(q.shape) == 4, f"Invalid shape for q, got {q.shape}, expected [N, L, H, Ci]" + assert len(k.shape) == 4, f"Invalid shape for k, got {k.shape}, expected [N, L, H, Ci]" + assert len(v.shape) == 4, f"Invalid shape for v, got {v.shape}, expected [N, L, H, Co]" + device = q.device + + if BACKEND == 'xformers': + if num_all_args == 1: + q, k, v = qkv.unbind(dim=2) + elif num_all_args == 2: + k, v = kv.unbind(dim=2) + out = xops.memory_efficient_attention(q, k, v) + elif BACKEND == 'flash_attn': + if num_all_args == 1: + out = flash_attn.flash_attn_qkvpacked_func(qkv) + elif num_all_args == 2: + out = flash_attn.flash_attn_kvpacked_func(q, kv) + elif num_all_args == 3: + out = flash_attn.flash_attn_func(q, k, v) + elif BACKEND == 'sdpa': + if num_all_args == 1: + q, k, v = qkv.unbind(dim=2) + elif num_all_args == 2: + k, v = kv.unbind(dim=2) + q = q.permute(0, 2, 1, 3) # [N, H, L, C] + k = k.permute(0, 2, 1, 3) # [N, H, L, C] + v = v.permute(0, 2, 1, 3) # [N, H, L, C] + out = sdpa(q, k, v) # [N, H, L, C] + out = out.permute(0, 2, 1, 3) # [N, L, H, C] + elif BACKEND == 'naive': + if num_all_args == 1: + q, k, v = qkv.unbind(dim=2) + elif num_all_args == 2: + k, v = kv.unbind(dim=2) + out = _naive_sdpa(q, k, v) + else: + raise ValueError(f"Unknown attention module: {BACKEND}") + + return out diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/attention/modules.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/attention/modules.py new file mode 100644 index 0000000000000000000000000000000000000000..dbe6235c27134f0477e48d3e12de3068c6a500ef --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/attention/modules.py @@ -0,0 +1,146 @@ +from typing import * +import torch +import torch.nn as nn +import torch.nn.functional as F +from .full_attn import scaled_dot_product_attention + + +class MultiHeadRMSNorm(nn.Module): + def __init__(self, dim: int, heads: int): + super().__init__() + self.scale = dim ** 0.5 + self.gamma = nn.Parameter(torch.ones(heads, dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return (F.normalize(x.float(), dim = -1) * self.gamma * self.scale).to(x.dtype) + + +class RotaryPositionEmbedder(nn.Module): + def __init__(self, hidden_size: int, in_channels: int = 3): + super().__init__() + assert hidden_size % 2 == 0, "Hidden size must be divisible by 2" + self.hidden_size = hidden_size + self.in_channels = in_channels + self.freq_dim = hidden_size // in_channels // 2 + self.freqs = torch.arange(self.freq_dim, dtype=torch.float32) / self.freq_dim + self.freqs = 1.0 / (10000 ** self.freqs) + + def _get_phases(self, indices: torch.Tensor) -> torch.Tensor: + self.freqs = self.freqs.to(indices.device) + phases = torch.outer(indices, self.freqs) + phases = torch.polar(torch.ones_like(phases), phases) + return phases + + def _rotary_embedding(self, x: torch.Tensor, phases: torch.Tensor) -> torch.Tensor: + x_complex = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2)) + x_rotated = x_complex * phases + x_embed = torch.view_as_real(x_rotated).reshape(*x_rotated.shape[:-1], -1).to(x.dtype) + return x_embed + + def forward(self, q: torch.Tensor, k: torch.Tensor, indices: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Args: + q (sp.SparseTensor): [..., N, D] tensor of queries + k (sp.SparseTensor): [..., N, D] tensor of keys + indices (torch.Tensor): [..., N, C] tensor of spatial positions + """ + if indices is None: + indices = torch.arange(q.shape[-2], device=q.device) + if len(q.shape) > 2: + indices = indices.unsqueeze(0).expand(q.shape[:-2] + (-1,)) + + phases = self._get_phases(indices.reshape(-1)).reshape(*indices.shape[:-1], -1) + if phases.shape[1] < self.hidden_size // 2: + phases = torch.cat([phases, torch.polar( + torch.ones(*phases.shape[:-1], self.hidden_size // 2 - phases.shape[1], device=phases.device), + torch.zeros(*phases.shape[:-1], self.hidden_size // 2 - phases.shape[1], device=phases.device) + )], dim=-1) + q_embed = self._rotary_embedding(q, phases) + k_embed = self._rotary_embedding(k, phases) + return q_embed, k_embed + + +class MultiHeadAttention(nn.Module): + def __init__( + self, + channels: int, + num_heads: int, + ctx_channels: Optional[int]=None, + type: Literal["self", "cross"] = "self", + attn_mode: Literal["full", "windowed"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + qkv_bias: bool = True, + use_rope: bool = False, + qk_rms_norm: bool = False, + ): + super().__init__() + assert channels % num_heads == 0 + assert type in ["self", "cross"], f"Invalid attention type: {type}" + assert attn_mode in ["full", "windowed"], f"Invalid attention mode: {attn_mode}" + assert type == "self" or attn_mode == "full", "Cross-attention only supports full attention" + + if attn_mode == "windowed": + raise NotImplementedError("Windowed attention is not yet implemented") + + self.channels = channels + self.head_dim = channels // num_heads + self.ctx_channels = ctx_channels if ctx_channels is not None else channels + self.num_heads = num_heads + self._type = type + self.attn_mode = attn_mode + self.window_size = window_size + self.shift_window = shift_window + self.use_rope = use_rope + self.qk_rms_norm = qk_rms_norm + + if self._type == "self": + self.to_qkv = nn.Linear(channels, channels * 3, bias=qkv_bias) + else: + self.to_q = nn.Linear(channels, channels, bias=qkv_bias) + self.to_kv = nn.Linear(self.ctx_channels, channels * 2, bias=qkv_bias) + + if self.qk_rms_norm: + self.q_rms_norm = MultiHeadRMSNorm(self.head_dim, num_heads) + self.k_rms_norm = MultiHeadRMSNorm(self.head_dim, num_heads) + + self.to_out = nn.Linear(channels, channels) + + if use_rope: + self.rope = RotaryPositionEmbedder(channels) + + def forward(self, x: torch.Tensor, context: Optional[torch.Tensor] = None, indices: Optional[torch.Tensor] = None) -> torch.Tensor: + B, L, C = x.shape + if self._type == "self": + qkv = self.to_qkv(x) + qkv = qkv.reshape(B, L, 3, self.num_heads, -1) + if self.use_rope: + q, k, v = qkv.unbind(dim=2) + q, k = self.rope(q, k, indices) + qkv = torch.stack([q, k, v], dim=2) + if self.attn_mode == "full": + if self.qk_rms_norm: + q, k, v = qkv.unbind(dim=2) + q = self.q_rms_norm(q) + k = self.k_rms_norm(k) + h = scaled_dot_product_attention(q, k, v) + else: + h = scaled_dot_product_attention(qkv) + elif self.attn_mode == "windowed": + raise NotImplementedError("Windowed attention is not yet implemented") + else: + Lkv = context.shape[1] + q = self.to_q(x) + kv = self.to_kv(context) + q = q.reshape(B, L, self.num_heads, -1) + kv = kv.reshape(B, Lkv, 2, self.num_heads, -1) + if self.qk_rms_norm: + q = self.q_rms_norm(q) + k, v = kv.unbind(dim=2) + k = self.k_rms_norm(k) + h = scaled_dot_product_attention(q, k, v) + else: + h = scaled_dot_product_attention(q, kv) + h = h.reshape(B, L, -1) + h = self.to_out(h) + return h diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/norm.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/norm.py new file mode 100644 index 0000000000000000000000000000000000000000..09035726081fb7afda2c62504d5474cfa483c58f --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/norm.py @@ -0,0 +1,25 @@ +import torch +import torch.nn as nn + + +class LayerNorm32(nn.LayerNorm): + def forward(self, x: torch.Tensor) -> torch.Tensor: + return super().forward(x.float()).type(x.dtype) + + +class GroupNorm32(nn.GroupNorm): + """ + A GroupNorm layer that converts to float32 before the forward pass. + """ + def forward(self, x: torch.Tensor) -> torch.Tensor: + return super().forward(x.float()).type(x.dtype) + + +class ChannelLayerNorm32(LayerNorm32): + def forward(self, x: torch.Tensor) -> torch.Tensor: + DIM = x.dim() + x = x.permute(0, *range(2, DIM), 1).contiguous() + x = super().forward(x) + x = x.permute(0, DIM-1, *range(1, DIM-1)).contiguous() + return x + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..77108a63b6e577568d878c1a92e6f777fce5c9b6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/__init__.py @@ -0,0 +1,102 @@ +from typing import * + +BACKEND = 'spconv' +DEBUG = False +ATTN = 'xformers' + +def __from_env(): + import os + + global BACKEND + global DEBUG + global ATTN + + env_sparse_backend = os.environ.get('SPARSE_BACKEND') + env_sparse_debug = os.environ.get('SPARSE_DEBUG') + env_sparse_attn = os.environ.get('SPARSE_ATTN_BACKEND') + if env_sparse_attn is None: + env_sparse_attn = os.environ.get('ATTN_BACKEND') + + if env_sparse_backend is not None and env_sparse_backend in ['spconv', 'torchsparse']: + BACKEND = env_sparse_backend + if env_sparse_debug is not None: + DEBUG = env_sparse_debug == '1' + if env_sparse_attn is not None and env_sparse_attn in ['xformers', 'flash_attn']: + ATTN = env_sparse_attn + + print(f"[SPARSE] Backend: {BACKEND}, Attention: {ATTN}") + + +__from_env() + + +def set_backend(backend: Literal['spconv', 'torchsparse']): + global BACKEND + BACKEND = backend + +def set_debug(debug: bool): + global DEBUG + DEBUG = debug + +def set_attn(attn: Literal['xformers', 'flash_attn']): + global ATTN + ATTN = attn + + +import importlib + +__attributes = { + 'SparseTensor': 'basic', + 'sparse_batch_broadcast': 'basic', + 'sparse_batch_op': 'basic', + 'sparse_cat': 'basic', + 'sparse_unbind': 'basic', + 'SparseGroupNorm': 'norm', + 'SparseLayerNorm': 'norm', + 'SparseGroupNorm32': 'norm', + 'SparseLayerNorm32': 'norm', + 'SparseReLU': 'nonlinearity', + 'SparseSiLU': 'nonlinearity', + 'SparseGELU': 'nonlinearity', + 'SparseActivation': 'nonlinearity', + 'SparseLinear': 'linear', + 'sparse_scaled_dot_product_attention': 'attention', + 'SerializeMode': 'attention', + 'sparse_serialized_scaled_dot_product_self_attention': 'attention', + 'sparse_windowed_scaled_dot_product_self_attention': 'attention', + 'SparseMultiHeadAttention': 'attention', + 'SparseConv3d': 'conv', + 'SparseInverseConv3d': 'conv', + 'SparseDownsample': 'spatial', + 'SparseUpsample': 'spatial', + 'SparseSubdivide' : 'spatial' +} + +__submodules = ['transformer'] + +__all__ = list(__attributes.keys()) + __submodules + +def __getattr__(name): + if name not in globals(): + if name in __attributes: + module_name = __attributes[name] + module = importlib.import_module(f".{module_name}", __name__) + globals()[name] = getattr(module, name) + elif name in __submodules: + module = importlib.import_module(f".{name}", __name__) + globals()[name] = module + else: + raise AttributeError(f"module {__name__} has no attribute {name}") + return globals()[name] + + +# For Pylance +if __name__ == '__main__': + from .basic import * + from .norm import * + from .nonlinearity import * + from .linear import * + from .attention import * + from .conv import * + from .spatial import * + import transformer diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/attention/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/attention/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..32b3c2c837c613e41755ac4c85f9ed057a6f5bfb --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/attention/__init__.py @@ -0,0 +1,4 @@ +from .full_attn import * +from .serialized_attn import * +from .windowed_attn import * +from .modules import * diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/attention/full_attn.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/attention/full_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..99e6516e3d74e9c19c01aab341b16bc11c9e44ef --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/attention/full_attn.py @@ -0,0 +1,215 @@ +from typing import * +import torch +from .. import SparseTensor +from .. import DEBUG, ATTN + +if ATTN == 'xformers': + import xformers.ops as xops +elif ATTN == 'flash_attn': + import flash_attn +else: + raise ValueError(f"Unknown attention module: {ATTN}") + + +__all__ = [ + 'sparse_scaled_dot_product_attention', +] + + +@overload +def sparse_scaled_dot_product_attention(qkv: SparseTensor) -> SparseTensor: + """ + Apply scaled dot product attention to a sparse tensor. + + Args: + qkv (SparseTensor): A [N, *, 3, H, C] sparse tensor containing Qs, Ks, and Vs. + """ + ... + +@overload +def sparse_scaled_dot_product_attention(q: SparseTensor, kv: Union[SparseTensor, torch.Tensor]) -> SparseTensor: + """ + Apply scaled dot product attention to a sparse tensor. + + Args: + q (SparseTensor): A [N, *, H, C] sparse tensor containing Qs. + kv (SparseTensor or torch.Tensor): A [N, *, 2, H, C] sparse tensor or a [N, L, 2, H, C] dense tensor containing Ks and Vs. + """ + ... + +@overload +def sparse_scaled_dot_product_attention(q: torch.Tensor, kv: SparseTensor) -> torch.Tensor: + """ + Apply scaled dot product attention to a sparse tensor. + + Args: + q (SparseTensor): A [N, L, H, C] dense tensor containing Qs. + kv (SparseTensor or torch.Tensor): A [N, *, 2, H, C] sparse tensor containing Ks and Vs. + """ + ... + +@overload +def sparse_scaled_dot_product_attention(q: SparseTensor, k: SparseTensor, v: SparseTensor) -> SparseTensor: + """ + Apply scaled dot product attention to a sparse tensor. + + Args: + q (SparseTensor): A [N, *, H, Ci] sparse tensor containing Qs. + k (SparseTensor): A [N, *, H, Ci] sparse tensor containing Ks. + v (SparseTensor): A [N, *, H, Co] sparse tensor containing Vs. + + Note: + k and v are assumed to have the same coordinate map. + """ + ... + +@overload +def sparse_scaled_dot_product_attention(q: SparseTensor, k: torch.Tensor, v: torch.Tensor) -> SparseTensor: + """ + Apply scaled dot product attention to a sparse tensor. + + Args: + q (SparseTensor): A [N, *, H, Ci] sparse tensor containing Qs. + k (torch.Tensor): A [N, L, H, Ci] dense tensor containing Ks. + v (torch.Tensor): A [N, L, H, Co] dense tensor containing Vs. + """ + ... + +@overload +def sparse_scaled_dot_product_attention(q: torch.Tensor, k: SparseTensor, v: SparseTensor) -> torch.Tensor: + """ + Apply scaled dot product attention to a sparse tensor. + + Args: + q (torch.Tensor): A [N, L, H, Ci] dense tensor containing Qs. + k (SparseTensor): A [N, *, H, Ci] sparse tensor containing Ks. + v (SparseTensor): A [N, *, H, Co] sparse tensor containing Vs. + """ + ... + +def sparse_scaled_dot_product_attention(*args, **kwargs): + arg_names_dict = { + 1: ['qkv'], + 2: ['q', 'kv'], + 3: ['q', 'k', 'v'] + } + num_all_args = len(args) + len(kwargs) + assert num_all_args in arg_names_dict, f"Invalid number of arguments, got {num_all_args}, expected 1, 2, or 3" + for key in arg_names_dict[num_all_args][len(args):]: + assert key in kwargs, f"Missing argument {key}" + + if num_all_args == 1: + qkv = args[0] if len(args) > 0 else kwargs['qkv'] + assert isinstance(qkv, SparseTensor), f"qkv must be a SparseTensor, got {type(qkv)}" + assert len(qkv.shape) == 4 and qkv.shape[1] == 3, f"Invalid shape for qkv, got {qkv.shape}, expected [N, *, 3, H, C]" + device = qkv.device + + s = qkv + q_seqlen = [qkv.layout[i].stop - qkv.layout[i].start for i in range(qkv.shape[0])] + kv_seqlen = q_seqlen + qkv = qkv.feats # [T, 3, H, C] + + elif num_all_args == 2: + q = args[0] if len(args) > 0 else kwargs['q'] + kv = args[1] if len(args) > 1 else kwargs['kv'] + assert isinstance(q, SparseTensor) and isinstance(kv, (SparseTensor, torch.Tensor)) or \ + isinstance(q, torch.Tensor) and isinstance(kv, SparseTensor), \ + f"Invalid types, got {type(q)} and {type(kv)}" + assert q.shape[0] == kv.shape[0], f"Batch size mismatch, got {q.shape[0]} and {kv.shape[0]}" + device = q.device + + if isinstance(q, SparseTensor): + assert len(q.shape) == 3, f"Invalid shape for q, got {q.shape}, expected [N, *, H, C]" + s = q + q_seqlen = [q.layout[i].stop - q.layout[i].start for i in range(q.shape[0])] + q = q.feats # [T_Q, H, C] + else: + assert len(q.shape) == 4, f"Invalid shape for q, got {q.shape}, expected [N, L, H, C]" + s = None + N, L, H, C = q.shape + q_seqlen = [L] * N + q = q.reshape(N * L, H, C) # [T_Q, H, C] + + if isinstance(kv, SparseTensor): + assert len(kv.shape) == 4 and kv.shape[1] == 2, f"Invalid shape for kv, got {kv.shape}, expected [N, *, 2, H, C]" + kv_seqlen = [kv.layout[i].stop - kv.layout[i].start for i in range(kv.shape[0])] + kv = kv.feats # [T_KV, 2, H, C] + else: + assert len(kv.shape) == 5, f"Invalid shape for kv, got {kv.shape}, expected [N, L, 2, H, C]" + N, L, _, H, C = kv.shape + kv_seqlen = [L] * N + kv = kv.reshape(N * L, 2, H, C) # [T_KV, 2, H, C] + + elif num_all_args == 3: + q = args[0] if len(args) > 0 else kwargs['q'] + k = args[1] if len(args) > 1 else kwargs['k'] + v = args[2] if len(args) > 2 else kwargs['v'] + assert isinstance(q, SparseTensor) and isinstance(k, (SparseTensor, torch.Tensor)) and type(k) == type(v) or \ + isinstance(q, torch.Tensor) and isinstance(k, SparseTensor) and isinstance(v, SparseTensor), \ + f"Invalid types, got {type(q)}, {type(k)}, and {type(v)}" + assert q.shape[0] == k.shape[0] == v.shape[0], f"Batch size mismatch, got {q.shape[0]}, {k.shape[0]}, and {v.shape[0]}" + device = q.device + + if isinstance(q, SparseTensor): + assert len(q.shape) == 3, f"Invalid shape for q, got {q.shape}, expected [N, *, H, Ci]" + s = q + q_seqlen = [q.layout[i].stop - q.layout[i].start for i in range(q.shape[0])] + q = q.feats # [T_Q, H, Ci] + else: + assert len(q.shape) == 4, f"Invalid shape for q, got {q.shape}, expected [N, L, H, Ci]" + s = None + N, L, H, CI = q.shape + q_seqlen = [L] * N + q = q.reshape(N * L, H, CI) # [T_Q, H, Ci] + + if isinstance(k, SparseTensor): + assert len(k.shape) == 3, f"Invalid shape for k, got {k.shape}, expected [N, *, H, Ci]" + assert len(v.shape) == 3, f"Invalid shape for v, got {v.shape}, expected [N, *, H, Co]" + kv_seqlen = [k.layout[i].stop - k.layout[i].start for i in range(k.shape[0])] + k = k.feats # [T_KV, H, Ci] + v = v.feats # [T_KV, H, Co] + else: + assert len(k.shape) == 4, f"Invalid shape for k, got {k.shape}, expected [N, L, H, Ci]" + assert len(v.shape) == 4, f"Invalid shape for v, got {v.shape}, expected [N, L, H, Co]" + N, L, H, CI, CO = *k.shape, v.shape[-1] + kv_seqlen = [L] * N + k = k.reshape(N * L, H, CI) # [T_KV, H, Ci] + v = v.reshape(N * L, H, CO) # [T_KV, H, Co] + + if DEBUG: + if s is not None: + for i in range(s.shape[0]): + assert (s.coords[s.layout[i]] == i).all(), f"SparseScaledDotProductSelfAttention: batch index mismatch" + if num_all_args in [2, 3]: + assert q.shape[:2] == [1, sum(q_seqlen)], f"SparseScaledDotProductSelfAttention: q shape mismatch" + if num_all_args == 3: + assert k.shape[:2] == [1, sum(kv_seqlen)], f"SparseScaledDotProductSelfAttention: k shape mismatch" + assert v.shape[:2] == [1, sum(kv_seqlen)], f"SparseScaledDotProductSelfAttention: v shape mismatch" + + if ATTN == 'xformers': + if num_all_args == 1: + q, k, v = qkv.unbind(dim=1) + elif num_all_args == 2: + k, v = kv.unbind(dim=1) + q = q.unsqueeze(0) + k = k.unsqueeze(0) + v = v.unsqueeze(0) + mask = xops.fmha.attn_bias.BlockDiagonalMask.from_seqlens(q_seqlen, kv_seqlen) + out = xops.memory_efficient_attention(q, k, v, mask)[0] + elif ATTN == 'flash_attn': + cu_seqlens_q = torch.cat([torch.tensor([0]), torch.cumsum(torch.tensor(q_seqlen), dim=0)]).int().to(device) + if num_all_args in [2, 3]: + cu_seqlens_kv = torch.cat([torch.tensor([0]), torch.cumsum(torch.tensor(kv_seqlen), dim=0)]).int().to(device) + if num_all_args == 1: + out = flash_attn.flash_attn_varlen_qkvpacked_func(qkv, cu_seqlens_q, max(q_seqlen)) + elif num_all_args == 2: + out = flash_attn.flash_attn_varlen_kvpacked_func(q, kv, cu_seqlens_q, cu_seqlens_kv, max(q_seqlen), max(kv_seqlen)) + elif num_all_args == 3: + out = flash_attn.flash_attn_varlen_func(q, k, v, cu_seqlens_q, cu_seqlens_kv, max(q_seqlen), max(kv_seqlen)) + else: + raise ValueError(f"Unknown attention module: {ATTN}") + + if s is not None: + return s.replace(out) + else: + return out.reshape(N, L, H, -1) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/attention/modules.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/attention/modules.py new file mode 100644 index 0000000000000000000000000000000000000000..5d2fe782b0947700e308e9ec0325e7e91c84e3c2 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/attention/modules.py @@ -0,0 +1,139 @@ +from typing import * +import torch +import torch.nn as nn +import torch.nn.functional as F +from .. import SparseTensor +from .full_attn import sparse_scaled_dot_product_attention +from .serialized_attn import SerializeMode, sparse_serialized_scaled_dot_product_self_attention +from .windowed_attn import sparse_windowed_scaled_dot_product_self_attention +from ...attention import RotaryPositionEmbedder + + +class SparseMultiHeadRMSNorm(nn.Module): + def __init__(self, dim: int, heads: int): + super().__init__() + self.scale = dim ** 0.5 + self.gamma = nn.Parameter(torch.ones(heads, dim)) + + def forward(self, x: Union[SparseTensor, torch.Tensor]) -> Union[SparseTensor, torch.Tensor]: + x_type = x.dtype + x = x.float() + if isinstance(x, SparseTensor): + x = x.replace(F.normalize(x.feats, dim=-1)) + else: + x = F.normalize(x, dim=-1) + return (x * self.gamma * self.scale).to(x_type) + + +class SparseMultiHeadAttention(nn.Module): + def __init__( + self, + channels: int, + num_heads: int, + ctx_channels: Optional[int] = None, + type: Literal["self", "cross"] = "self", + attn_mode: Literal["full", "serialized", "windowed"] = "full", + window_size: Optional[int] = None, + shift_sequence: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + serialize_mode: Optional[SerializeMode] = None, + qkv_bias: bool = True, + use_rope: bool = False, + qk_rms_norm: bool = False, + ): + super().__init__() + assert channels % num_heads == 0 + assert type in ["self", "cross"], f"Invalid attention type: {type}" + assert attn_mode in ["full", "serialized", "windowed"], f"Invalid attention mode: {attn_mode}" + assert type == "self" or attn_mode == "full", "Cross-attention only supports full attention" + assert type == "self" or use_rope is False, "Rotary position embeddings only supported for self-attention" + self.channels = channels + self.ctx_channels = ctx_channels if ctx_channels is not None else channels + self.num_heads = num_heads + self._type = type + self.attn_mode = attn_mode + self.window_size = window_size + self.shift_sequence = shift_sequence + self.shift_window = shift_window + self.serialize_mode = serialize_mode + self.use_rope = use_rope + self.qk_rms_norm = qk_rms_norm + + if self._type == "self": + self.to_qkv = nn.Linear(channels, channels * 3, bias=qkv_bias) + else: + self.to_q = nn.Linear(channels, channels, bias=qkv_bias) + self.to_kv = nn.Linear(self.ctx_channels, channels * 2, bias=qkv_bias) + + if self.qk_rms_norm: + self.q_rms_norm = SparseMultiHeadRMSNorm(channels // num_heads, num_heads) + self.k_rms_norm = SparseMultiHeadRMSNorm(channels // num_heads, num_heads) + + self.to_out = nn.Linear(channels, channels) + + if use_rope: + self.rope = RotaryPositionEmbedder(channels) + + @staticmethod + def _linear(module: nn.Linear, x: Union[SparseTensor, torch.Tensor]) -> Union[SparseTensor, torch.Tensor]: + if isinstance(x, SparseTensor): + return x.replace(module(x.feats)) + else: + return module(x) + + @staticmethod + def _reshape_chs(x: Union[SparseTensor, torch.Tensor], shape: Tuple[int, ...]) -> Union[SparseTensor, torch.Tensor]: + if isinstance(x, SparseTensor): + return x.reshape(*shape) + else: + return x.reshape(*x.shape[:2], *shape) + + def _fused_pre(self, x: Union[SparseTensor, torch.Tensor], num_fused: int) -> Union[SparseTensor, torch.Tensor]: + if isinstance(x, SparseTensor): + x_feats = x.feats.unsqueeze(0) + else: + x_feats = x + x_feats = x_feats.reshape(*x_feats.shape[:2], num_fused, self.num_heads, -1) + return x.replace(x_feats.squeeze(0)) if isinstance(x, SparseTensor) else x_feats + + def _rope(self, qkv: SparseTensor) -> SparseTensor: + q, k, v = qkv.feats.unbind(dim=1) # [T, H, C] + q, k = self.rope(q, k, qkv.coords[:, 1:]) + qkv = qkv.replace(torch.stack([q, k, v], dim=1)) + return qkv + + def forward(self, x: Union[SparseTensor, torch.Tensor], context: Optional[Union[SparseTensor, torch.Tensor]] = None) -> Union[SparseTensor, torch.Tensor]: + if self._type == "self": + qkv = self._linear(self.to_qkv, x) + qkv = self._fused_pre(qkv, num_fused=3) + if self.use_rope: + qkv = self._rope(qkv) + if self.qk_rms_norm: + q, k, v = qkv.unbind(dim=1) + q = self.q_rms_norm(q) + k = self.k_rms_norm(k) + qkv = qkv.replace(torch.stack([q.feats, k.feats, v.feats], dim=1)) + if self.attn_mode == "full": + h = sparse_scaled_dot_product_attention(qkv) + elif self.attn_mode == "serialized": + h = sparse_serialized_scaled_dot_product_self_attention( + qkv, self.window_size, serialize_mode=self.serialize_mode, shift_sequence=self.shift_sequence, shift_window=self.shift_window + ) + elif self.attn_mode == "windowed": + h = sparse_windowed_scaled_dot_product_self_attention( + qkv, self.window_size, shift_window=self.shift_window + ) + else: + q = self._linear(self.to_q, x) + q = self._reshape_chs(q, (self.num_heads, -1)) + kv = self._linear(self.to_kv, context) + kv = self._fused_pre(kv, num_fused=2) + if self.qk_rms_norm: + q = self.q_rms_norm(q) + k, v = kv.unbind(dim=1) + k = self.k_rms_norm(k) + kv = kv.replace(torch.stack([k.feats, v.feats], dim=1)) + h = sparse_scaled_dot_product_attention(q, kv) + h = self._reshape_chs(h, (-1,)) + h = self._linear(self.to_out, h) + return h diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/attention/serialized_attn.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/attention/serialized_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..ca37a16214f31671b44d2a915a2f73059bda916d --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/attention/serialized_attn.py @@ -0,0 +1,193 @@ +from typing import * +from enum import Enum +import torch +import math +from .. import SparseTensor +from .. import DEBUG, ATTN + +if ATTN == 'xformers': + import xformers.ops as xops +elif ATTN == 'flash_attn': + import flash_attn +else: + raise ValueError(f"Unknown attention module: {ATTN}") + + +__all__ = [ + 'sparse_serialized_scaled_dot_product_self_attention', +] + + +class SerializeMode(Enum): + Z_ORDER = 0 + Z_ORDER_TRANSPOSED = 1 + HILBERT = 2 + HILBERT_TRANSPOSED = 3 + + +SerializeModes = [ + SerializeMode.Z_ORDER, + SerializeMode.Z_ORDER_TRANSPOSED, + SerializeMode.HILBERT, + SerializeMode.HILBERT_TRANSPOSED +] + + +def calc_serialization( + tensor: SparseTensor, + window_size: int, + serialize_mode: SerializeMode = SerializeMode.Z_ORDER, + shift_sequence: int = 0, + shift_window: Tuple[int, int, int] = (0, 0, 0) +) -> Tuple[torch.Tensor, torch.Tensor, List[int]]: + """ + Calculate serialization and partitioning for a set of coordinates. + + Args: + tensor (SparseTensor): The input tensor. + window_size (int): The window size to use. + serialize_mode (SerializeMode): The serialization mode to use. + shift_sequence (int): The shift of serialized sequence. + shift_window (Tuple[int, int, int]): The shift of serialized coordinates. + + Returns: + (torch.Tensor, torch.Tensor): Forwards and backwards indices. + """ + fwd_indices = [] + bwd_indices = [] + seq_lens = [] + seq_batch_indices = [] + offsets = [0] + + if 'vox2seq' not in globals(): + import vox2seq + + # Serialize the input + serialize_coords = tensor.coords[:, 1:].clone() + serialize_coords += torch.tensor(shift_window, dtype=torch.int32, device=tensor.device).reshape(1, 3) + if serialize_mode == SerializeMode.Z_ORDER: + code = vox2seq.encode(serialize_coords, mode='z_order', permute=[0, 1, 2]) + elif serialize_mode == SerializeMode.Z_ORDER_TRANSPOSED: + code = vox2seq.encode(serialize_coords, mode='z_order', permute=[1, 0, 2]) + elif serialize_mode == SerializeMode.HILBERT: + code = vox2seq.encode(serialize_coords, mode='hilbert', permute=[0, 1, 2]) + elif serialize_mode == SerializeMode.HILBERT_TRANSPOSED: + code = vox2seq.encode(serialize_coords, mode='hilbert', permute=[1, 0, 2]) + else: + raise ValueError(f"Unknown serialize mode: {serialize_mode}") + + for bi, s in enumerate(tensor.layout): + num_points = s.stop - s.start + num_windows = (num_points + window_size - 1) // window_size + valid_window_size = num_points / num_windows + to_ordered = torch.argsort(code[s.start:s.stop]) + if num_windows == 1: + fwd_indices.append(to_ordered) + bwd_indices.append(torch.zeros_like(to_ordered).scatter_(0, to_ordered, torch.arange(num_points, device=tensor.device))) + fwd_indices[-1] += s.start + bwd_indices[-1] += offsets[-1] + seq_lens.append(num_points) + seq_batch_indices.append(bi) + offsets.append(offsets[-1] + seq_lens[-1]) + else: + # Partition the input + offset = 0 + mids = [(i + 0.5) * valid_window_size + shift_sequence for i in range(num_windows)] + split = [math.floor(i * valid_window_size + shift_sequence) for i in range(num_windows + 1)] + bwd_index = torch.zeros((num_points,), dtype=torch.int64, device=tensor.device) + for i in range(num_windows): + mid = mids[i] + valid_start = split[i] + valid_end = split[i + 1] + padded_start = math.floor(mid - 0.5 * window_size) + padded_end = padded_start + window_size + fwd_indices.append(to_ordered[torch.arange(padded_start, padded_end, device=tensor.device) % num_points]) + offset += valid_start - padded_start + bwd_index.scatter_(0, fwd_indices[-1][valid_start-padded_start:valid_end-padded_start], torch.arange(offset, offset + valid_end - valid_start, device=tensor.device)) + offset += padded_end - valid_start + fwd_indices[-1] += s.start + seq_lens.extend([window_size] * num_windows) + seq_batch_indices.extend([bi] * num_windows) + bwd_indices.append(bwd_index + offsets[-1]) + offsets.append(offsets[-1] + num_windows * window_size) + + fwd_indices = torch.cat(fwd_indices) + bwd_indices = torch.cat(bwd_indices) + + return fwd_indices, bwd_indices, seq_lens, seq_batch_indices + + +def sparse_serialized_scaled_dot_product_self_attention( + qkv: SparseTensor, + window_size: int, + serialize_mode: SerializeMode = SerializeMode.Z_ORDER, + shift_sequence: int = 0, + shift_window: Tuple[int, int, int] = (0, 0, 0) +) -> SparseTensor: + """ + Apply serialized scaled dot product self attention to a sparse tensor. + + Args: + qkv (SparseTensor): [N, *, 3, H, C] sparse tensor containing Qs, Ks, and Vs. + window_size (int): The window size to use. + serialize_mode (SerializeMode): The serialization mode to use. + shift_sequence (int): The shift of serialized sequence. + shift_window (Tuple[int, int, int]): The shift of serialized coordinates. + shift (int): The shift to use. + """ + assert len(qkv.shape) == 4 and qkv.shape[1] == 3, f"Invalid shape for qkv, got {qkv.shape}, expected [N, *, 3, H, C]" + + serialization_spatial_cache_name = f'serialization_{serialize_mode}_{window_size}_{shift_sequence}_{shift_window}' + serialization_spatial_cache = qkv.get_spatial_cache(serialization_spatial_cache_name) + if serialization_spatial_cache is None: + fwd_indices, bwd_indices, seq_lens, seq_batch_indices = calc_serialization(qkv, window_size, serialize_mode, shift_sequence, shift_window) + qkv.register_spatial_cache(serialization_spatial_cache_name, (fwd_indices, bwd_indices, seq_lens, seq_batch_indices)) + else: + fwd_indices, bwd_indices, seq_lens, seq_batch_indices = serialization_spatial_cache + + M = fwd_indices.shape[0] + T = qkv.feats.shape[0] + H = qkv.feats.shape[2] + C = qkv.feats.shape[3] + + qkv_feats = qkv.feats[fwd_indices] # [M, 3, H, C] + + if DEBUG: + start = 0 + qkv_coords = qkv.coords[fwd_indices] + for i in range(len(seq_lens)): + assert (qkv_coords[start:start+seq_lens[i], 0] == seq_batch_indices[i]).all(), f"SparseWindowedScaledDotProductSelfAttention: batch index mismatch" + start += seq_lens[i] + + if all([seq_len == window_size for seq_len in seq_lens]): + B = len(seq_lens) + N = window_size + qkv_feats = qkv_feats.reshape(B, N, 3, H, C) + if ATTN == 'xformers': + q, k, v = qkv_feats.unbind(dim=2) # [B, N, H, C] + out = xops.memory_efficient_attention(q, k, v) # [B, N, H, C] + elif ATTN == 'flash_attn': + out = flash_attn.flash_attn_qkvpacked_func(qkv_feats) # [B, N, H, C] + else: + raise ValueError(f"Unknown attention module: {ATTN}") + out = out.reshape(B * N, H, C) # [M, H, C] + else: + if ATTN == 'xformers': + q, k, v = qkv_feats.unbind(dim=1) # [M, H, C] + q = q.unsqueeze(0) # [1, M, H, C] + k = k.unsqueeze(0) # [1, M, H, C] + v = v.unsqueeze(0) # [1, M, H, C] + mask = xops.fmha.attn_bias.BlockDiagonalMask.from_seqlens(seq_lens) + out = xops.memory_efficient_attention(q, k, v, mask)[0] # [M, H, C] + elif ATTN == 'flash_attn': + cu_seqlens = torch.cat([torch.tensor([0]), torch.cumsum(torch.tensor(seq_lens), dim=0)], dim=0) \ + .to(qkv.device).int() + out = flash_attn.flash_attn_varlen_qkvpacked_func(qkv_feats, cu_seqlens, max(seq_lens)) # [M, H, C] + + out = out[bwd_indices] # [T, H, C] + + if DEBUG: + qkv_coords = qkv_coords[bwd_indices] + assert torch.equal(qkv_coords, qkv.coords), "SparseWindowedScaledDotProductSelfAttention: coordinate mismatch" + + return qkv.replace(out) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/attention/windowed_attn.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/attention/windowed_attn.py new file mode 100644 index 0000000000000000000000000000000000000000..a704c9ea92502ee85773ba92fb15889d7e71b319 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/attention/windowed_attn.py @@ -0,0 +1,135 @@ +from typing import * +import torch +import math +from .. import SparseTensor +from .. import DEBUG, ATTN + +if ATTN == 'xformers': + import xformers.ops as xops +elif ATTN == 'flash_attn': + import flash_attn +else: + raise ValueError(f"Unknown attention module: {ATTN}") + + +__all__ = [ + 'sparse_windowed_scaled_dot_product_self_attention', +] + + +def calc_window_partition( + tensor: SparseTensor, + window_size: Union[int, Tuple[int, ...]], + shift_window: Union[int, Tuple[int, ...]] = 0 +) -> Tuple[torch.Tensor, torch.Tensor, List[int], List[int]]: + """ + Calculate serialization and partitioning for a set of coordinates. + + Args: + tensor (SparseTensor): The input tensor. + window_size (int): The window size to use. + shift_window (Tuple[int, ...]): The shift of serialized coordinates. + + Returns: + (torch.Tensor): Forwards indices. + (torch.Tensor): Backwards indices. + (List[int]): Sequence lengths. + (List[int]): Sequence batch indices. + """ + DIM = tensor.coords.shape[1] - 1 + shift_window = (shift_window,) * DIM if isinstance(shift_window, int) else shift_window + window_size = (window_size,) * DIM if isinstance(window_size, int) else window_size + shifted_coords = tensor.coords.clone().detach() + shifted_coords[:, 1:] += torch.tensor(shift_window, device=tensor.device, dtype=torch.int32).unsqueeze(0) + + MAX_COORDS = shifted_coords[:, 1:].max(dim=0).values.tolist() + NUM_WINDOWS = [math.ceil((mc + 1) / ws) for mc, ws in zip(MAX_COORDS, window_size)] + OFFSET = torch.cumprod(torch.tensor([1] + NUM_WINDOWS[::-1]), dim=0).tolist()[::-1] + + shifted_coords[:, 1:] //= torch.tensor(window_size, device=tensor.device, dtype=torch.int32).unsqueeze(0) + shifted_indices = (shifted_coords * torch.tensor(OFFSET, device=tensor.device, dtype=torch.int32).unsqueeze(0)).sum(dim=1) + fwd_indices = torch.argsort(shifted_indices) + bwd_indices = torch.empty_like(fwd_indices) + bwd_indices[fwd_indices] = torch.arange(fwd_indices.shape[0], device=tensor.device) + seq_lens = torch.bincount(shifted_indices) + seq_batch_indices = torch.arange(seq_lens.shape[0], device=tensor.device, dtype=torch.int32) // OFFSET[0] + mask = seq_lens != 0 + seq_lens = seq_lens[mask].tolist() + seq_batch_indices = seq_batch_indices[mask].tolist() + + return fwd_indices, bwd_indices, seq_lens, seq_batch_indices + + +def sparse_windowed_scaled_dot_product_self_attention( + qkv: SparseTensor, + window_size: int, + shift_window: Tuple[int, int, int] = (0, 0, 0) +) -> SparseTensor: + """ + Apply windowed scaled dot product self attention to a sparse tensor. + + Args: + qkv (SparseTensor): [N, *, 3, H, C] sparse tensor containing Qs, Ks, and Vs. + window_size (int): The window size to use. + shift_window (Tuple[int, int, int]): The shift of serialized coordinates. + shift (int): The shift to use. + """ + assert len(qkv.shape) == 4 and qkv.shape[1] == 3, f"Invalid shape for qkv, got {qkv.shape}, expected [N, *, 3, H, C]" + + serialization_spatial_cache_name = f'window_partition_{window_size}_{shift_window}' + serialization_spatial_cache = qkv.get_spatial_cache(serialization_spatial_cache_name) + if serialization_spatial_cache is None: + fwd_indices, bwd_indices, seq_lens, seq_batch_indices = calc_window_partition(qkv, window_size, shift_window) + qkv.register_spatial_cache(serialization_spatial_cache_name, (fwd_indices, bwd_indices, seq_lens, seq_batch_indices)) + else: + fwd_indices, bwd_indices, seq_lens, seq_batch_indices = serialization_spatial_cache + + M = fwd_indices.shape[0] + T = qkv.feats.shape[0] + H = qkv.feats.shape[2] + C = qkv.feats.shape[3] + + qkv_feats = qkv.feats[fwd_indices] # [M, 3, H, C] + + if DEBUG: + start = 0 + qkv_coords = qkv.coords[fwd_indices] + for i in range(len(seq_lens)): + seq_coords = qkv_coords[start:start+seq_lens[i]] + assert (seq_coords[:, 0] == seq_batch_indices[i]).all(), f"SparseWindowedScaledDotProductSelfAttention: batch index mismatch" + assert (seq_coords[:, 1:].max(dim=0).values - seq_coords[:, 1:].min(dim=0).values < window_size).all(), \ + f"SparseWindowedScaledDotProductSelfAttention: window size exceeded" + start += seq_lens[i] + + if all([seq_len == window_size for seq_len in seq_lens]): + B = len(seq_lens) + N = window_size + qkv_feats = qkv_feats.reshape(B, N, 3, H, C) + if ATTN == 'xformers': + q, k, v = qkv_feats.unbind(dim=2) # [B, N, H, C] + out = xops.memory_efficient_attention(q, k, v) # [B, N, H, C] + elif ATTN == 'flash_attn': + out = flash_attn.flash_attn_qkvpacked_func(qkv_feats) # [B, N, H, C] + else: + raise ValueError(f"Unknown attention module: {ATTN}") + out = out.reshape(B * N, H, C) # [M, H, C] + else: + if ATTN == 'xformers': + q, k, v = qkv_feats.unbind(dim=1) # [M, H, C] + q = q.unsqueeze(0) # [1, M, H, C] + k = k.unsqueeze(0) # [1, M, H, C] + v = v.unsqueeze(0) # [1, M, H, C] + mask = xops.fmha.attn_bias.BlockDiagonalMask.from_seqlens(seq_lens) + out = xops.memory_efficient_attention(q, k, v, mask)[0] # [M, H, C] + elif ATTN == 'flash_attn': + cu_seqlens = torch.cat([torch.tensor([0]), torch.cumsum(torch.tensor(seq_lens), dim=0)], dim=0) \ + .to(qkv.device).int() + out = flash_attn.flash_attn_varlen_qkvpacked_func(qkv_feats, cu_seqlens, max(seq_lens)) # [M, H, C] + + out = out[bwd_indices] # [T, H, C] + + if DEBUG: + qkv_coords = qkv_coords[bwd_indices] + assert torch.equal(qkv_coords, qkv.coords), "SparseWindowedScaledDotProductSelfAttention: coordinate mismatch" + + return qkv.replace(out) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/basic.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..8837f44052f6d573d09e3bfb897e659e10516bb5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/basic.py @@ -0,0 +1,459 @@ +from typing import * +import torch +import torch.nn as nn +from . import BACKEND, DEBUG +SparseTensorData = None # Lazy import + + +__all__ = [ + 'SparseTensor', + 'sparse_batch_broadcast', + 'sparse_batch_op', + 'sparse_cat', + 'sparse_unbind', +] + + +class SparseTensor: + """ + Sparse tensor with support for both torchsparse and spconv backends. + + Parameters: + - feats (torch.Tensor): Features of the sparse tensor. + - coords (torch.Tensor): Coordinates of the sparse tensor. + - shape (torch.Size): Shape of the sparse tensor. + - layout (List[slice]): Layout of the sparse tensor for each batch + - data (SparseTensorData): Sparse tensor data used for convolusion + + NOTE: + - Data corresponding to a same batch should be contiguous. + - Coords should be in [0, 1023] + """ + @overload + def __init__(self, feats: torch.Tensor, coords: torch.Tensor, shape: Optional[torch.Size] = None, layout: Optional[List[slice]] = None, **kwargs): ... + + @overload + def __init__(self, data, shape: Optional[torch.Size] = None, layout: Optional[List[slice]] = None, **kwargs): ... + + def __init__(self, *args, **kwargs): + # Lazy import of sparse tensor backend + global SparseTensorData + if SparseTensorData is None: + import importlib + if BACKEND == 'torchsparse': + SparseTensorData = importlib.import_module('torchsparse').SparseTensor + elif BACKEND == 'spconv': + SparseTensorData = importlib.import_module('spconv.pytorch').SparseConvTensor + + method_id = 0 + if len(args) != 0: + method_id = 0 if isinstance(args[0], torch.Tensor) else 1 + else: + method_id = 1 if 'data' in kwargs else 0 + + if method_id == 0: + feats, coords, shape, layout = args + (None,) * (4 - len(args)) + if 'feats' in kwargs: + feats = kwargs['feats'] + del kwargs['feats'] + if 'coords' in kwargs: + coords = kwargs['coords'] + del kwargs['coords'] + if 'shape' in kwargs: + shape = kwargs['shape'] + del kwargs['shape'] + if 'layout' in kwargs: + layout = kwargs['layout'] + del kwargs['layout'] + + if shape is None: + shape = self.__cal_shape(feats, coords) + if layout is None: + layout = self.__cal_layout(coords, shape[0]) + if BACKEND == 'torchsparse': + self.data = SparseTensorData(feats, coords, **kwargs) + elif BACKEND == 'spconv': + spatial_shape = list(coords.max(0)[0] + 1)[1:] + self.data = SparseTensorData(feats.reshape(feats.shape[0], -1), coords, spatial_shape, shape[0], **kwargs) + self.data._features = feats + elif method_id == 1: + data, shape, layout = args + (None,) * (3 - len(args)) + if 'data' in kwargs: + data = kwargs['data'] + del kwargs['data'] + if 'shape' in kwargs: + shape = kwargs['shape'] + del kwargs['shape'] + if 'layout' in kwargs: + layout = kwargs['layout'] + del kwargs['layout'] + + self.data = data + if shape is None: + shape = self.__cal_shape(self.feats, self.coords) + if layout is None: + layout = self.__cal_layout(self.coords, shape[0]) + + self._shape = shape + self._layout = layout + self._scale = kwargs.get('scale', (1, 1, 1)) + self._spatial_cache = kwargs.get('spatial_cache', {}) + + if DEBUG: + try: + assert self.feats.shape[0] == self.coords.shape[0], f"Invalid feats shape: {self.feats.shape}, coords shape: {self.coords.shape}" + assert self.shape == self.__cal_shape(self.feats, self.coords), f"Invalid shape: {self.shape}" + assert self.layout == self.__cal_layout(self.coords, self.shape[0]), f"Invalid layout: {self.layout}" + for i in range(self.shape[0]): + assert torch.all(self.coords[self.layout[i], 0] == i), f"The data of batch {i} is not contiguous" + except Exception as e: + print('Debugging information:') + print(f"- Shape: {self.shape}") + print(f"- Layout: {self.layout}") + print(f"- Scale: {self._scale}") + print(f"- Coords: {self.coords}") + raise e + + def __cal_shape(self, feats, coords): + shape = [] + shape.append(coords[:, 0].max().item() + 1) + shape.extend([*feats.shape[1:]]) + return torch.Size(shape) + + def __cal_layout(self, coords, batch_size): + seq_len = torch.bincount(coords[:, 0], minlength=batch_size) + offset = torch.cumsum(seq_len, dim=0) + layout = [slice((offset[i] - seq_len[i]).item(), offset[i].item()) for i in range(batch_size)] + return layout + + @property + def shape(self) -> torch.Size: + return self._shape + + def dim(self) -> int: + return len(self.shape) + + @property + def layout(self) -> List[slice]: + return self._layout + + @property + def feats(self) -> torch.Tensor: + if BACKEND == 'torchsparse': + return self.data.F + elif BACKEND == 'spconv': + return self.data.features + + @feats.setter + def feats(self, value: torch.Tensor): + if BACKEND == 'torchsparse': + self.data.F = value + elif BACKEND == 'spconv': + self.data.features = value + + @property + def coords(self) -> torch.Tensor: + if BACKEND == 'torchsparse': + return self.data.C + elif BACKEND == 'spconv': + return self.data.indices + + @coords.setter + def coords(self, value: torch.Tensor): + if BACKEND == 'torchsparse': + self.data.C = value + elif BACKEND == 'spconv': + self.data.indices = value + + @property + def dtype(self): + return self.feats.dtype + + @property + def device(self): + return self.feats.device + + @overload + def to(self, dtype: torch.dtype) -> 'SparseTensor': ... + + @overload + def to(self, device: Optional[Union[str, torch.device]] = None, dtype: Optional[torch.dtype] = None) -> 'SparseTensor': ... + + def to(self, *args, **kwargs) -> 'SparseTensor': + device = None + dtype = None + if len(args) == 2: + device, dtype = args + elif len(args) == 1: + if isinstance(args[0], torch.dtype): + dtype = args[0] + else: + device = args[0] + if 'dtype' in kwargs: + assert dtype is None, "to() received multiple values for argument 'dtype'" + dtype = kwargs['dtype'] + if 'device' in kwargs: + assert device is None, "to() received multiple values for argument 'device'" + device = kwargs['device'] + + new_feats = self.feats.to(device=device, dtype=dtype) + new_coords = self.coords.to(device=device) + return self.replace(new_feats, new_coords) + + def type(self, dtype): + new_feats = self.feats.type(dtype) + return self.replace(new_feats) + + def cpu(self) -> 'SparseTensor': + new_feats = self.feats.cpu() + new_coords = self.coords.cpu() + return self.replace(new_feats, new_coords) + + def cuda(self) -> 'SparseTensor': + new_feats = self.feats.cuda() + new_coords = self.coords.cuda() + return self.replace(new_feats, new_coords) + + def half(self) -> 'SparseTensor': + new_feats = self.feats.half() + return self.replace(new_feats) + + def float(self) -> 'SparseTensor': + new_feats = self.feats.float() + return self.replace(new_feats) + + def detach(self) -> 'SparseTensor': + new_coords = self.coords.detach() + new_feats = self.feats.detach() + return self.replace(new_feats, new_coords) + + def dense(self) -> torch.Tensor: + if BACKEND == 'torchsparse': + return self.data.dense() + elif BACKEND == 'spconv': + return self.data.dense() + + def reshape(self, *shape) -> 'SparseTensor': + new_feats = self.feats.reshape(self.feats.shape[0], *shape) + return self.replace(new_feats) + + def unbind(self, dim: int) -> List['SparseTensor']: + return sparse_unbind(self, dim) + + def replace(self, feats: torch.Tensor, coords: Optional[torch.Tensor] = None) -> 'SparseTensor': + new_shape = [self.shape[0]] + new_shape.extend(feats.shape[1:]) + if BACKEND == 'torchsparse': + new_data = SparseTensorData( + feats=feats, + coords=self.data.coords if coords is None else coords, + stride=self.data.stride, + spatial_range=self.data.spatial_range, + ) + new_data._caches = self.data._caches + elif BACKEND == 'spconv': + new_data = SparseTensorData( + self.data.features.reshape(self.data.features.shape[0], -1), + self.data.indices, + self.data.spatial_shape, + self.data.batch_size, + self.data.grid, + self.data.voxel_num, + self.data.indice_dict + ) + new_data._features = feats + new_data.benchmark = self.data.benchmark + new_data.benchmark_record = self.data.benchmark_record + new_data.thrust_allocator = self.data.thrust_allocator + new_data._timer = self.data._timer + new_data.force_algo = self.data.force_algo + new_data.int8_scale = self.data.int8_scale + if coords is not None: + new_data.indices = coords + new_tensor = SparseTensor(new_data, shape=torch.Size(new_shape), layout=self.layout, scale=self._scale, spatial_cache=self._spatial_cache) + return new_tensor + + @staticmethod + def full(aabb, dim, value, dtype=torch.float32, device=None) -> 'SparseTensor': + N, C = dim + x = torch.arange(aabb[0], aabb[3] + 1) + y = torch.arange(aabb[1], aabb[4] + 1) + z = torch.arange(aabb[2], aabb[5] + 1) + coords = torch.stack(torch.meshgrid(x, y, z, indexing='ij'), dim=-1).reshape(-1, 3) + coords = torch.cat([ + torch.arange(N).view(-1, 1).repeat(1, coords.shape[0]).view(-1, 1), + coords.repeat(N, 1), + ], dim=1).to(dtype=torch.int32, device=device) + feats = torch.full((coords.shape[0], C), value, dtype=dtype, device=device) + return SparseTensor(feats=feats, coords=coords) + + def __merge_sparse_cache(self, other: 'SparseTensor') -> dict: + new_cache = {} + for k in set(list(self._spatial_cache.keys()) + list(other._spatial_cache.keys())): + if k in self._spatial_cache: + new_cache[k] = self._spatial_cache[k] + if k in other._spatial_cache: + if k not in new_cache: + new_cache[k] = other._spatial_cache[k] + else: + new_cache[k].update(other._spatial_cache[k]) + return new_cache + + def __neg__(self) -> 'SparseTensor': + return self.replace(-self.feats) + + def __elemwise__(self, other: Union[torch.Tensor, 'SparseTensor'], op: callable) -> 'SparseTensor': + if isinstance(other, torch.Tensor): + try: + other = torch.broadcast_to(other, self.shape) + other = sparse_batch_broadcast(self, other) + except: + pass + if isinstance(other, SparseTensor): + other = other.feats + new_feats = op(self.feats, other) + new_tensor = self.replace(new_feats) + if isinstance(other, SparseTensor): + new_tensor._spatial_cache = self.__merge_sparse_cache(other) + return new_tensor + + def __add__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor': + return self.__elemwise__(other, torch.add) + + def __radd__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor': + return self.__elemwise__(other, torch.add) + + def __sub__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor': + return self.__elemwise__(other, torch.sub) + + def __rsub__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor': + return self.__elemwise__(other, lambda x, y: torch.sub(y, x)) + + def __mul__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor': + return self.__elemwise__(other, torch.mul) + + def __rmul__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor': + return self.__elemwise__(other, torch.mul) + + def __truediv__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor': + return self.__elemwise__(other, torch.div) + + def __rtruediv__(self, other: Union[torch.Tensor, 'SparseTensor', float]) -> 'SparseTensor': + return self.__elemwise__(other, lambda x, y: torch.div(y, x)) + + def __getitem__(self, idx): + if isinstance(idx, int): + idx = [idx] + elif isinstance(idx, slice): + idx = range(*idx.indices(self.shape[0])) + elif isinstance(idx, torch.Tensor): + if idx.dtype == torch.bool: + assert idx.shape == (self.shape[0],), f"Invalid index shape: {idx.shape}" + idx = idx.nonzero().squeeze(1) + elif idx.dtype in [torch.int32, torch.int64]: + assert len(idx.shape) == 1, f"Invalid index shape: {idx.shape}" + else: + raise ValueError(f"Unknown index type: {idx.dtype}") + else: + raise ValueError(f"Unknown index type: {type(idx)}") + + coords = [] + feats = [] + for new_idx, old_idx in enumerate(idx): + coords.append(self.coords[self.layout[old_idx]].clone()) + coords[-1][:, 0] = new_idx + feats.append(self.feats[self.layout[old_idx]]) + coords = torch.cat(coords, dim=0).contiguous() + feats = torch.cat(feats, dim=0).contiguous() + return SparseTensor(feats=feats, coords=coords) + + def register_spatial_cache(self, key, value) -> None: + """ + Register a spatial cache. + The spatial cache can be any thing you want to cache. + The registery and retrieval of the cache is based on current scale. + """ + scale_key = str(self._scale) + if scale_key not in self._spatial_cache: + self._spatial_cache[scale_key] = {} + self._spatial_cache[scale_key][key] = value + + def get_spatial_cache(self, key=None): + """ + Get a spatial cache. + """ + scale_key = str(self._scale) + cur_scale_cache = self._spatial_cache.get(scale_key, {}) + if key is None: + return cur_scale_cache + return cur_scale_cache.get(key, None) + + +def sparse_batch_broadcast(input: SparseTensor, other: torch.Tensor) -> torch.Tensor: + """ + Broadcast a 1D tensor to a sparse tensor along the batch dimension then perform an operation. + + Args: + input (torch.Tensor): 1D tensor to broadcast. + target (SparseTensor): Sparse tensor to broadcast to. + op (callable): Operation to perform after broadcasting. Defaults to torch.add. + """ + coords, feats = input.coords, input.feats + broadcasted = torch.zeros_like(feats) + for k in range(input.shape[0]): + broadcasted[input.layout[k]] = other[k] + return broadcasted + + +def sparse_batch_op(input: SparseTensor, other: torch.Tensor, op: callable = torch.add) -> SparseTensor: + """ + Broadcast a 1D tensor to a sparse tensor along the batch dimension then perform an operation. + + Args: + input (torch.Tensor): 1D tensor to broadcast. + target (SparseTensor): Sparse tensor to broadcast to. + op (callable): Operation to perform after broadcasting. Defaults to torch.add. + """ + return input.replace(op(input.feats, sparse_batch_broadcast(input, other))) + + +def sparse_cat(inputs: List[SparseTensor], dim: int = 0) -> SparseTensor: + """ + Concatenate a list of sparse tensors. + + Args: + inputs (List[SparseTensor]): List of sparse tensors to concatenate. + """ + if dim == 0: + start = 0 + coords = [] + for input in inputs: + coords.append(input.coords.clone()) + coords[-1][:, 0] += start + start += input.shape[0] + coords = torch.cat(coords, dim=0) + feats = torch.cat([input.feats for input in inputs], dim=0) + output = SparseTensor( + coords=coords, + feats=feats, + ) + else: + feats = torch.cat([input.feats for input in inputs], dim=dim) + output = inputs[0].replace(feats) + + return output + + +def sparse_unbind(input: SparseTensor, dim: int) -> List[SparseTensor]: + """ + Unbind a sparse tensor along a dimension. + + Args: + input (SparseTensor): Sparse tensor to unbind. + dim (int): Dimension to unbind. + """ + if dim == 0: + return [input[i] for i in range(input.shape[0])] + else: + feats = input.feats.unbind(dim) + return [input.replace(f) for f in feats] diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/conv/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/conv/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..340a87126a8de574ee0276feb96b49824a2ce234 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/conv/__init__.py @@ -0,0 +1,21 @@ +from .. import BACKEND + + +SPCONV_ALGO = 'auto' # 'auto', 'implicit_gemm', 'native' + +def __from_env(): + import os + + global SPCONV_ALGO + env_spconv_algo = os.environ.get('SPCONV_ALGO') + if env_spconv_algo is not None and env_spconv_algo in ['auto', 'implicit_gemm', 'native']: + SPCONV_ALGO = env_spconv_algo + print(f"[SPARSE][CONV] spconv algo: {SPCONV_ALGO}") + + +__from_env() + +if BACKEND == 'torchsparse': + from .conv_torchsparse import * +elif BACKEND == 'spconv': + from .conv_spconv import * diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/conv/conv_spconv.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/conv/conv_spconv.py new file mode 100644 index 0000000000000000000000000000000000000000..524bcd4a845b2d6bd090a5f74bc8859978727528 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/conv/conv_spconv.py @@ -0,0 +1,80 @@ +import torch +import torch.nn as nn +from .. import SparseTensor +from .. import DEBUG +from . import SPCONV_ALGO + +class SparseConv3d(nn.Module): + def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, padding=None, bias=True, indice_key=None): + super(SparseConv3d, self).__init__() + if 'spconv' not in globals(): + import spconv.pytorch as spconv + algo = None + if SPCONV_ALGO == 'native': + algo = spconv.ConvAlgo.Native + elif SPCONV_ALGO == 'implicit_gemm': + algo = spconv.ConvAlgo.MaskImplicitGemm + if stride == 1 and (padding is None): + self.conv = spconv.SubMConv3d(in_channels, out_channels, kernel_size, dilation=dilation, bias=bias, indice_key=indice_key, algo=algo) + else: + self.conv = spconv.SparseConv3d(in_channels, out_channels, kernel_size, stride=stride, dilation=dilation, padding=padding, bias=bias, indice_key=indice_key, algo=algo) + self.stride = tuple(stride) if isinstance(stride, (list, tuple)) else (stride, stride, stride) + self.padding = padding + + def forward(self, x: SparseTensor) -> SparseTensor: + spatial_changed = any(s != 1 for s in self.stride) or (self.padding is not None) + new_data = self.conv(x.data) + new_shape = [x.shape[0], self.conv.out_channels] + new_layout = None if spatial_changed else x.layout + + if spatial_changed and (x.shape[0] != 1): + # spconv was non-1 stride will break the contiguous of the output tensor, sort by the coords + fwd = new_data.indices[:, 0].argsort() + bwd = torch.zeros_like(fwd).scatter_(0, fwd, torch.arange(fwd.shape[0], device=fwd.device)) + sorted_feats = new_data.features[fwd] + sorted_coords = new_data.indices[fwd] + unsorted_data = new_data + new_data = spconv.SparseConvTensor(sorted_feats, sorted_coords, unsorted_data.spatial_shape, unsorted_data.batch_size) # type: ignore + + out = SparseTensor( + new_data, shape=torch.Size(new_shape), layout=new_layout, + scale=tuple([s * stride for s, stride in zip(x._scale, self.stride)]), + spatial_cache=x._spatial_cache, + ) + + if spatial_changed and (x.shape[0] != 1): + out.register_spatial_cache(f'conv_{self.stride}_unsorted_data', unsorted_data) + out.register_spatial_cache(f'conv_{self.stride}_sort_bwd', bwd) + + return out + + +class SparseInverseConv3d(nn.Module): + def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, bias=True, indice_key=None): + super(SparseInverseConv3d, self).__init__() + if 'spconv' not in globals(): + import spconv.pytorch as spconv + self.conv = spconv.SparseInverseConv3d(in_channels, out_channels, kernel_size, bias=bias, indice_key=indice_key) + self.stride = tuple(stride) if isinstance(stride, (list, tuple)) else (stride, stride, stride) + + def forward(self, x: SparseTensor) -> SparseTensor: + spatial_changed = any(s != 1 for s in self.stride) + if spatial_changed: + # recover the original spconv order + data = x.get_spatial_cache(f'conv_{self.stride}_unsorted_data') + bwd = x.get_spatial_cache(f'conv_{self.stride}_sort_bwd') + data = data.replace_feature(x.feats[bwd]) + if DEBUG: + assert torch.equal(data.indices, x.coords[bwd]), 'Recover the original order failed' + else: + data = x.data + + new_data = self.conv(data) + new_shape = [x.shape[0], self.conv.out_channels] + new_layout = None if spatial_changed else x.layout + out = SparseTensor( + new_data, shape=torch.Size(new_shape), layout=new_layout, + scale=tuple([s // stride for s, stride in zip(x._scale, self.stride)]), + spatial_cache=x._spatial_cache, + ) + return out diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/conv/conv_torchsparse.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/conv/conv_torchsparse.py new file mode 100644 index 0000000000000000000000000000000000000000..1d612582d4b31f90aca3c00b693bbbc2550dc62c --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/conv/conv_torchsparse.py @@ -0,0 +1,38 @@ +import torch +import torch.nn as nn +from .. import SparseTensor + + +class SparseConv3d(nn.Module): + def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, bias=True, indice_key=None): + super(SparseConv3d, self).__init__() + if 'torchsparse' not in globals(): + import torchsparse + self.conv = torchsparse.nn.Conv3d(in_channels, out_channels, kernel_size, stride, 0, dilation, bias) + + def forward(self, x: SparseTensor) -> SparseTensor: + out = self.conv(x.data) + new_shape = [x.shape[0], self.conv.out_channels] + out = SparseTensor(out, shape=torch.Size(new_shape), layout=x.layout if all(s == 1 for s in self.conv.stride) else None) + out._spatial_cache = x._spatial_cache + out._scale = tuple([s * stride for s, stride in zip(x._scale, self.conv.stride)]) + return out + + +class SparseInverseConv3d(nn.Module): + def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, bias=True, indice_key=None): + super(SparseInverseConv3d, self).__init__() + if 'torchsparse' not in globals(): + import torchsparse + self.conv = torchsparse.nn.Conv3d(in_channels, out_channels, kernel_size, stride, 0, dilation, bias, transposed=True) + + def forward(self, x: SparseTensor) -> SparseTensor: + out = self.conv(x.data) + new_shape = [x.shape[0], self.conv.out_channels] + out = SparseTensor(out, shape=torch.Size(new_shape), layout=x.layout if all(s == 1 for s in self.conv.stride) else None) + out._spatial_cache = x._spatial_cache + out._scale = tuple([s // stride for s, stride in zip(x._scale, self.conv.stride)]) + return out + + + diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/linear.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/linear.py new file mode 100644 index 0000000000000000000000000000000000000000..a854e77ce87d1a190b9730d91f363a821ff250bd --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/linear.py @@ -0,0 +1,15 @@ +import torch +import torch.nn as nn +from . import SparseTensor + +__all__ = [ + 'SparseLinear' +] + + +class SparseLinear(nn.Linear): + def __init__(self, in_features, out_features, bias=True): + super(SparseLinear, self).__init__(in_features, out_features, bias) + + def forward(self, input: SparseTensor) -> SparseTensor: + return input.replace(super().forward(input.feats)) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/nonlinearity.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/nonlinearity.py new file mode 100644 index 0000000000000000000000000000000000000000..f200098dd82011a3aeee1688b9eb17018fa78295 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/nonlinearity.py @@ -0,0 +1,35 @@ +import torch +import torch.nn as nn +from . import SparseTensor + +__all__ = [ + 'SparseReLU', + 'SparseSiLU', + 'SparseGELU', + 'SparseActivation' +] + + +class SparseReLU(nn.ReLU): + def forward(self, input: SparseTensor) -> SparseTensor: + return input.replace(super().forward(input.feats)) + + +class SparseSiLU(nn.SiLU): + def forward(self, input: SparseTensor) -> SparseTensor: + return input.replace(super().forward(input.feats)) + + +class SparseGELU(nn.GELU): + def forward(self, input: SparseTensor) -> SparseTensor: + return input.replace(super().forward(input.feats)) + + +class SparseActivation(nn.Module): + def __init__(self, activation: nn.Module): + super().__init__() + self.activation = activation + + def forward(self, input: SparseTensor) -> SparseTensor: + return input.replace(self.activation(input.feats)) + diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/norm.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/norm.py new file mode 100644 index 0000000000000000000000000000000000000000..6b38a36682c098210000dc31d68ddc31ccd2929d --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/norm.py @@ -0,0 +1,58 @@ +import torch +import torch.nn as nn +from . import SparseTensor +from . import DEBUG + +__all__ = [ + 'SparseGroupNorm', + 'SparseLayerNorm', + 'SparseGroupNorm32', + 'SparseLayerNorm32', +] + + +class SparseGroupNorm(nn.GroupNorm): + def __init__(self, num_groups, num_channels, eps=1e-5, affine=True): + super(SparseGroupNorm, self).__init__(num_groups, num_channels, eps, affine) + + def forward(self, input: SparseTensor) -> SparseTensor: + nfeats = torch.zeros_like(input.feats) + for k in range(input.shape[0]): + if DEBUG: + assert (input.coords[input.layout[k], 0] == k).all(), f"SparseGroupNorm: batch index mismatch" + bfeats = input.feats[input.layout[k]] + bfeats = bfeats.permute(1, 0).reshape(1, input.shape[1], -1) + bfeats = super().forward(bfeats) + bfeats = bfeats.reshape(input.shape[1], -1).permute(1, 0) + nfeats[input.layout[k]] = bfeats + return input.replace(nfeats) + + +class SparseLayerNorm(nn.LayerNorm): + def __init__(self, normalized_shape, eps=1e-5, elementwise_affine=True): + super(SparseLayerNorm, self).__init__(normalized_shape, eps, elementwise_affine) + + def forward(self, input: SparseTensor) -> SparseTensor: + nfeats = torch.zeros_like(input.feats) + for k in range(input.shape[0]): + bfeats = input.feats[input.layout[k]] + bfeats = bfeats.permute(1, 0).reshape(1, input.shape[1], -1) + bfeats = super().forward(bfeats) + bfeats = bfeats.reshape(input.shape[1], -1).permute(1, 0) + nfeats[input.layout[k]] = bfeats + return input.replace(nfeats) + + +class SparseGroupNorm32(SparseGroupNorm): + """ + A GroupNorm layer that converts to float32 before the forward pass. + """ + def forward(self, x: SparseTensor) -> SparseTensor: + return super().forward(x.float()).type(x.dtype) + +class SparseLayerNorm32(SparseLayerNorm): + """ + A LayerNorm layer that converts to float32 before the forward pass. + """ + def forward(self, x: SparseTensor) -> SparseTensor: + return super().forward(x.float()).type(x.dtype) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/spatial.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/spatial.py new file mode 100644 index 0000000000000000000000000000000000000000..ad7121473f335b307e2f7ea5f05c964d3aec0440 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/spatial.py @@ -0,0 +1,110 @@ +from typing import * +import torch +import torch.nn as nn +from . import SparseTensor + +__all__ = [ + 'SparseDownsample', + 'SparseUpsample', + 'SparseSubdivide' +] + + +class SparseDownsample(nn.Module): + """ + Downsample a sparse tensor by a factor of `factor`. + Implemented as average pooling. + """ + def __init__(self, factor: Union[int, Tuple[int, ...], List[int]]): + super(SparseDownsample, self).__init__() + self.factor = tuple(factor) if isinstance(factor, (list, tuple)) else factor + + def forward(self, input: SparseTensor) -> SparseTensor: + DIM = input.coords.shape[-1] - 1 + factor = self.factor if isinstance(self.factor, tuple) else (self.factor,) * DIM + assert DIM == len(factor), 'Input coordinates must have the same dimension as the downsample factor.' + + coord = list(input.coords.unbind(dim=-1)) + for i, f in enumerate(factor): + coord[i+1] = coord[i+1] // f + + MAX = [coord[i+1].max().item() + 1 for i in range(DIM)] + OFFSET = torch.cumprod(torch.tensor(MAX[::-1]), 0).tolist()[::-1] + [1] + code = sum([c * o for c, o in zip(coord, OFFSET)]) + code, idx = code.unique(return_inverse=True) + + new_feats = torch.scatter_reduce( + torch.zeros(code.shape[0], input.feats.shape[1], device=input.feats.device, dtype=input.feats.dtype), + dim=0, + index=idx.unsqueeze(1).expand(-1, input.feats.shape[1]), + src=input.feats, + reduce='mean' + ) + new_coords = torch.stack( + [code // OFFSET[0]] + + [(code // OFFSET[i+1]) % MAX[i] for i in range(DIM)], + dim=-1 + ) + out = SparseTensor(new_feats, new_coords, input.shape,) + out._scale = tuple([s // f for s, f in zip(input._scale, factor)]) + out._spatial_cache = input._spatial_cache + + out.register_spatial_cache(f'upsample_{factor}_coords', input.coords) + out.register_spatial_cache(f'upsample_{factor}_layout', input.layout) + out.register_spatial_cache(f'upsample_{factor}_idx', idx) + + return out + + +class SparseUpsample(nn.Module): + """ + Upsample a sparse tensor by a factor of `factor`. + Implemented as nearest neighbor interpolation. + """ + def __init__(self, factor: Union[int, Tuple[int, int, int], List[int]]): + super(SparseUpsample, self).__init__() + self.factor = tuple(factor) if isinstance(factor, (list, tuple)) else factor + + def forward(self, input: SparseTensor) -> SparseTensor: + DIM = input.coords.shape[-1] - 1 + factor = self.factor if isinstance(self.factor, tuple) else (self.factor,) * DIM + assert DIM == len(factor), 'Input coordinates must have the same dimension as the upsample factor.' + + new_coords = input.get_spatial_cache(f'upsample_{factor}_coords') + new_layout = input.get_spatial_cache(f'upsample_{factor}_layout') + idx = input.get_spatial_cache(f'upsample_{factor}_idx') + if any([x is None for x in [new_coords, new_layout, idx]]): + raise ValueError('Upsample cache not found. SparseUpsample must be paired with SparseDownsample.') + new_feats = input.feats[idx] + out = SparseTensor(new_feats, new_coords, input.shape, new_layout) + out._scale = tuple([s * f for s, f in zip(input._scale, factor)]) + out._spatial_cache = input._spatial_cache + return out + +class SparseSubdivide(nn.Module): + """ + Upsample a sparse tensor by a factor of `factor`. + Implemented as nearest neighbor interpolation. + """ + def __init__(self): + super(SparseSubdivide, self).__init__() + + def forward(self, input: SparseTensor) -> SparseTensor: + DIM = input.coords.shape[-1] - 1 + # upsample scale=2^DIM + n_cube = torch.ones([2] * DIM, device=input.device, dtype=torch.int) + n_coords = torch.nonzero(n_cube) + n_coords = torch.cat([torch.zeros_like(n_coords[:, :1]), n_coords], dim=-1) + factor = n_coords.shape[0] + assert factor == 2 ** DIM + # print(n_coords.shape) + new_coords = input.coords.clone() + new_coords[:, 1:] *= 2 + new_coords = new_coords.unsqueeze(1) + n_coords.unsqueeze(0).to(new_coords.dtype) + + new_feats = input.feats.unsqueeze(1).expand(input.feats.shape[0], factor, *input.feats.shape[1:]) + out = SparseTensor(new_feats.flatten(0, 1), new_coords.flatten(0, 1), input.shape) + out._scale = input._scale * 2 + out._spatial_cache = input._spatial_cache + return out + diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/transformer/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/transformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b08b0d4e5bc24060a2cdc8df75d06dce122972bd --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/transformer/__init__.py @@ -0,0 +1,2 @@ +from .blocks import * +from .modulated import * \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/transformer/blocks.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/transformer/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..9d037a49bf83e1c2dfb2f8c4b23d2e9d6c51e9f0 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/transformer/blocks.py @@ -0,0 +1,151 @@ +from typing import * +import torch +import torch.nn as nn +from ..basic import SparseTensor +from ..linear import SparseLinear +from ..nonlinearity import SparseGELU +from ..attention import SparseMultiHeadAttention, SerializeMode +from ...norm import LayerNorm32 + + +class SparseFeedForwardNet(nn.Module): + def __init__(self, channels: int, mlp_ratio: float = 4.0): + super().__init__() + self.mlp = nn.Sequential( + SparseLinear(channels, int(channels * mlp_ratio)), + SparseGELU(approximate="tanh"), + SparseLinear(int(channels * mlp_ratio), channels), + ) + + def forward(self, x: SparseTensor) -> SparseTensor: + return self.mlp(x) + + +class SparseTransformerBlock(nn.Module): + """ + Sparse Transformer block (MSA + FFN). + """ + def __init__( + self, + channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "full", + window_size: Optional[int] = None, + shift_sequence: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + serialize_mode: Optional[SerializeMode] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + qk_rms_norm: bool = False, + qkv_bias: bool = True, + ln_affine: bool = False, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.norm1 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.attn = SparseMultiHeadAttention( + channels, + num_heads=num_heads, + attn_mode=attn_mode, + window_size=window_size, + shift_sequence=shift_sequence, + shift_window=shift_window, + serialize_mode=serialize_mode, + qkv_bias=qkv_bias, + use_rope=use_rope, + qk_rms_norm=qk_rms_norm, + ) + self.mlp = SparseFeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + + def _forward(self, x: SparseTensor) -> SparseTensor: + h = x.replace(self.norm1(x.feats)) + h = self.attn(h) + x = x + h + h = x.replace(self.norm2(x.feats)) + h = self.mlp(h) + x = x + h + return x + + def forward(self, x: SparseTensor) -> SparseTensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, use_reentrant=False) + else: + return self._forward(x) + + +class SparseTransformerCrossBlock(nn.Module): + """ + Sparse Transformer cross-attention block (MSA + MCA + FFN). + """ + def __init__( + self, + channels: int, + ctx_channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "full", + window_size: Optional[int] = None, + shift_sequence: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + serialize_mode: Optional[SerializeMode] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + qk_rms_norm: bool = False, + qk_rms_norm_cross: bool = False, + qkv_bias: bool = True, + ln_affine: bool = False, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.norm1 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.norm3 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.self_attn = SparseMultiHeadAttention( + channels, + num_heads=num_heads, + type="self", + attn_mode=attn_mode, + window_size=window_size, + shift_sequence=shift_sequence, + shift_window=shift_window, + serialize_mode=serialize_mode, + qkv_bias=qkv_bias, + use_rope=use_rope, + qk_rms_norm=qk_rms_norm, + ) + self.cross_attn = SparseMultiHeadAttention( + channels, + ctx_channels=ctx_channels, + num_heads=num_heads, + type="cross", + attn_mode="full", + qkv_bias=qkv_bias, + qk_rms_norm=qk_rms_norm_cross, + ) + self.mlp = SparseFeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + + def _forward(self, x: SparseTensor, mod: torch.Tensor, context: torch.Tensor): + h = x.replace(self.norm1(x.feats)) + h = self.self_attn(h) + x = x + h + h = x.replace(self.norm2(x.feats)) + h = self.cross_attn(h, context) + x = x + h + h = x.replace(self.norm3(x.feats)) + h = self.mlp(h) + x = x + h + return x + + def forward(self, x: SparseTensor, context: torch.Tensor): + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, context, use_reentrant=False) + else: + return self._forward(x, context) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/transformer/modulated.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/transformer/modulated.py new file mode 100644 index 0000000000000000000000000000000000000000..4a8416559f39acbed9e5996e9891c97f95c80c8f --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/sparse/transformer/modulated.py @@ -0,0 +1,166 @@ +from typing import * +import torch +import torch.nn as nn +from ..basic import SparseTensor +from ..attention import SparseMultiHeadAttention, SerializeMode +from ...norm import LayerNorm32 +from .blocks import SparseFeedForwardNet + + +class ModulatedSparseTransformerBlock(nn.Module): + """ + Sparse Transformer block (MSA + FFN) with adaptive layer norm conditioning. + """ + def __init__( + self, + channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "full", + window_size: Optional[int] = None, + shift_sequence: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + serialize_mode: Optional[SerializeMode] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + qk_rms_norm: bool = False, + qkv_bias: bool = True, + share_mod: bool = False, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.share_mod = share_mod + self.norm1 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.attn = SparseMultiHeadAttention( + channels, + num_heads=num_heads, + attn_mode=attn_mode, + window_size=window_size, + shift_sequence=shift_sequence, + shift_window=shift_window, + serialize_mode=serialize_mode, + qkv_bias=qkv_bias, + use_rope=use_rope, + qk_rms_norm=qk_rms_norm, + ) + self.mlp = SparseFeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + if not share_mod: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(channels, 6 * channels, bias=True) + ) + + def _forward(self, x: SparseTensor, mod: torch.Tensor) -> SparseTensor: + if self.share_mod: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = mod.chunk(6, dim=1) + else: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(mod).chunk(6, dim=1) + h = x.replace(self.norm1(x.feats)) + h = h * (1 + scale_msa) + shift_msa + h = self.attn(h) + h = h * gate_msa + x = x + h + h = x.replace(self.norm2(x.feats)) + h = h * (1 + scale_mlp) + shift_mlp + h = self.mlp(h) + h = h * gate_mlp + x = x + h + return x + + def forward(self, x: SparseTensor, mod: torch.Tensor) -> SparseTensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, mod, use_reentrant=False) + else: + return self._forward(x, mod) + + +class ModulatedSparseTransformerCrossBlock(nn.Module): + """ + Sparse Transformer cross-attention block (MSA + MCA + FFN) with adaptive layer norm conditioning. + """ + def __init__( + self, + channels: int, + ctx_channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "shift_window", "shift_sequence", "shift_order", "swin"] = "full", + window_size: Optional[int] = None, + shift_sequence: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + serialize_mode: Optional[SerializeMode] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + qk_rms_norm: bool = False, + qk_rms_norm_cross: bool = False, + qkv_bias: bool = True, + share_mod: bool = False, + + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.share_mod = share_mod + self.norm1 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6) + self.norm3 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.self_attn = SparseMultiHeadAttention( + channels, + num_heads=num_heads, + type="self", + attn_mode=attn_mode, + window_size=window_size, + shift_sequence=shift_sequence, + shift_window=shift_window, + serialize_mode=serialize_mode, + qkv_bias=qkv_bias, + use_rope=use_rope, + qk_rms_norm=qk_rms_norm, + ) + self.cross_attn = SparseMultiHeadAttention( + channels, + ctx_channels=ctx_channels, + num_heads=num_heads, + type="cross", + attn_mode="full", + qkv_bias=qkv_bias, + qk_rms_norm=qk_rms_norm_cross, + ) + self.mlp = SparseFeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + if not share_mod: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(channels, 6 * channels, bias=True) + ) + + def _forward(self, x: SparseTensor, mod: torch.Tensor, context: torch.Tensor) -> SparseTensor: + if self.share_mod: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = mod.chunk(6, dim=1) + else: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(mod).chunk(6, dim=1) + h = x.replace(self.norm1(x.feats)) + h = h * (1 + scale_msa) + shift_msa + h = self.self_attn(h) + h = h * gate_msa + x = x + h + h = x.replace(self.norm2(x.feats)) + h = self.cross_attn(h, context) + x = x + h + h = x.replace(self.norm3(x.feats)) + h = h * (1 + scale_mlp) + shift_mlp + h = self.mlp(h) + h = h * gate_mlp + x = x + h + return x + + def forward(self, x: SparseTensor, mod: torch.Tensor, context: torch.Tensor) -> SparseTensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, mod, context, use_reentrant=False) + else: + return self._forward(x, mod, context) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/spatial.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/spatial.py new file mode 100644 index 0000000000000000000000000000000000000000..79e268d36c2ba49b0275744022a1a1e19983dae3 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/spatial.py @@ -0,0 +1,48 @@ +import torch + + +def pixel_shuffle_3d(x: torch.Tensor, scale_factor: int) -> torch.Tensor: + """ + 3D pixel shuffle. + """ + B, C, H, W, D = x.shape + C_ = C // scale_factor**3 + x = x.reshape(B, C_, scale_factor, scale_factor, scale_factor, H, W, D) + x = x.permute(0, 1, 5, 2, 6, 3, 7, 4) + x = x.reshape(B, C_, H*scale_factor, W*scale_factor, D*scale_factor) + return x + + +def patchify(x: torch.Tensor, patch_size: int): + """ + Patchify a tensor. + + Args: + x (torch.Tensor): (N, C, *spatial) tensor + patch_size (int): Patch size + """ + DIM = x.dim() - 2 + for d in range(2, DIM + 2): + assert x.shape[d] % patch_size == 0, f"Dimension {d} of input tensor must be divisible by patch size, got {x.shape[d]} and {patch_size}" + + x = x.reshape(*x.shape[:2], *sum([[x.shape[d] // patch_size, patch_size] for d in range(2, DIM + 2)], [])) + x = x.permute(0, 1, *([2 * i + 3 for i in range(DIM)] + [2 * i + 2 for i in range(DIM)])) + x = x.reshape(x.shape[0], x.shape[1] * (patch_size ** DIM), *(x.shape[-DIM:])) + return x + + +def unpatchify(x: torch.Tensor, patch_size: int): + """ + Unpatchify a tensor. + + Args: + x (torch.Tensor): (N, C, *spatial) tensor + patch_size (int): Patch size + """ + DIM = x.dim() - 2 + assert x.shape[1] % (patch_size ** DIM) == 0, f"Second dimension of input tensor must be divisible by patch size to unpatchify, got {x.shape[1]} and {patch_size ** DIM}" + + x = x.reshape(x.shape[0], x.shape[1] // (patch_size ** DIM), *([patch_size] * DIM), *(x.shape[-DIM:])) + x = x.permute(0, 1, *(sum([[2 + DIM + i, 2 + i] for i in range(DIM)], []))) + x = x.reshape(x.shape[0], x.shape[1], *[x.shape[2 + 2 * i] * patch_size for i in range(DIM)]) + return x diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/transformer/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/transformer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b08b0d4e5bc24060a2cdc8df75d06dce122972bd --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/transformer/__init__.py @@ -0,0 +1,2 @@ +from .blocks import * +from .modulated import * \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/transformer/blocks.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/transformer/blocks.py new file mode 100644 index 0000000000000000000000000000000000000000..c37eb7ed92f4aacfc9e974a63b247589d95977da --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/transformer/blocks.py @@ -0,0 +1,182 @@ +from typing import * +import torch +import torch.nn as nn +from ..attention import MultiHeadAttention +from ..norm import LayerNorm32 + + +class AbsolutePositionEmbedder(nn.Module): + """ + Embeds spatial positions into vector representations. + """ + def __init__(self, channels: int, in_channels: int = 3): + super().__init__() + self.channels = channels + self.in_channels = in_channels + self.freq_dim = channels // in_channels // 2 + self.freqs = torch.arange(self.freq_dim, dtype=torch.float32) / self.freq_dim + self.freqs = 1.0 / (10000 ** self.freqs) + + def _sin_cos_embedding(self, x: torch.Tensor) -> torch.Tensor: + """ + Create sinusoidal position embeddings. + + Args: + x: a 1-D Tensor of N indices + + Returns: + an (N, D) Tensor of positional embeddings. + """ + self.freqs = self.freqs.to(x.device) + out = torch.outer(x, self.freqs) + out = torch.cat([torch.sin(out), torch.cos(out)], dim=-1) + return out + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Args: + x (torch.Tensor): (N, D) tensor of spatial positions + """ + N, D = x.shape + assert D == self.in_channels, "Input dimension must match number of input channels" + embed = self._sin_cos_embedding(x.reshape(-1)) + embed = embed.reshape(N, -1) + if embed.shape[1] < self.channels: + embed = torch.cat([embed, torch.zeros(N, self.channels - embed.shape[1], device=embed.device)], dim=-1) + return embed + + +class FeedForwardNet(nn.Module): + def __init__(self, channels: int, mlp_ratio: float = 4.0): + super().__init__() + self.mlp = nn.Sequential( + nn.Linear(channels, int(channels * mlp_ratio)), + nn.GELU(approximate="tanh"), + nn.Linear(int(channels * mlp_ratio), channels), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.mlp(x) + + +class TransformerBlock(nn.Module): + """ + Transformer block (MSA + FFN). + """ + def __init__( + self, + channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "windowed"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[int] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + qk_rms_norm: bool = False, + qkv_bias: bool = True, + ln_affine: bool = False, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.norm1 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.attn = MultiHeadAttention( + channels, + num_heads=num_heads, + attn_mode=attn_mode, + window_size=window_size, + shift_window=shift_window, + qkv_bias=qkv_bias, + use_rope=use_rope, + qk_rms_norm=qk_rms_norm, + ) + self.mlp = FeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + + def _forward(self, x: torch.Tensor) -> torch.Tensor: + h = self.norm1(x) + h = self.attn(h) + x = x + h + h = self.norm2(x) + h = self.mlp(h) + x = x + h + return x + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, use_reentrant=False) + else: + return self._forward(x) + + +class TransformerCrossBlock(nn.Module): + """ + Transformer cross-attention block (MSA + MCA + FFN). + """ + def __init__( + self, + channels: int, + ctx_channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "windowed"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + qk_rms_norm: bool = False, + qk_rms_norm_cross: bool = False, + qkv_bias: bool = True, + ln_affine: bool = False, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.norm1 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.norm3 = LayerNorm32(channels, elementwise_affine=ln_affine, eps=1e-6) + self.self_attn = MultiHeadAttention( + channels, + num_heads=num_heads, + type="self", + attn_mode=attn_mode, + window_size=window_size, + shift_window=shift_window, + qkv_bias=qkv_bias, + use_rope=use_rope, + qk_rms_norm=qk_rms_norm, + ) + self.cross_attn = MultiHeadAttention( + channels, + ctx_channels=ctx_channels, + num_heads=num_heads, + type="cross", + attn_mode="full", + qkv_bias=qkv_bias, + qk_rms_norm=qk_rms_norm_cross, + ) + self.mlp = FeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + + def _forward(self, x: torch.Tensor, context: torch.Tensor): + h = self.norm1(x) + h = self.self_attn(h) + x = x + h + h = self.norm2(x) + h = self.cross_attn(h, context) + x = x + h + h = self.norm3(x) + h = self.mlp(h) + x = x + h + return x + + def forward(self, x: torch.Tensor, context: torch.Tensor): + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, context, use_reentrant=False) + else: + return self._forward(x, context) + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/transformer/modulated.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/transformer/modulated.py new file mode 100644 index 0000000000000000000000000000000000000000..4faf8932198b49b4aaf29f60c9c32971ed26c5fb --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/transformer/modulated.py @@ -0,0 +1,333 @@ +from typing import * +import torch +import torch.nn as nn +from ..attention import MultiHeadAttention +from ..norm import LayerNorm32 +from .blocks import FeedForwardNet + + +class ModulatedTransformerBlock(nn.Module): + """ + Transformer block (MSA + FFN) with adaptive layer norm conditioning. + """ + def __init__( + self, + channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "windowed"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + qk_rms_norm: bool = False, + qkv_bias: bool = True, + share_mod: bool = False, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.share_mod = share_mod + self.norm1 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.attn = MultiHeadAttention( + channels, + num_heads=num_heads, + attn_mode=attn_mode, + window_size=window_size, + shift_window=shift_window, + qkv_bias=qkv_bias, + use_rope=use_rope, + qk_rms_norm=qk_rms_norm, + ) + self.mlp = FeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + if not share_mod: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(channels, 6 * channels, bias=True) + ) + + def _forward(self, x: torch.Tensor, mod: torch.Tensor) -> torch.Tensor: + if self.share_mod: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = mod.chunk(6, dim=1) + else: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(mod).chunk(6, dim=1) + h = self.norm1(x) + h = h * (1 + scale_msa.unsqueeze(1)) + shift_msa.unsqueeze(1) + h = self.attn(h) + h = h * gate_msa.unsqueeze(1) + x = x + h + h = self.norm2(x) + h = h * (1 + scale_mlp.unsqueeze(1)) + shift_mlp.unsqueeze(1) + h = self.mlp(h) + h = h * gate_mlp.unsqueeze(1) + x = x + h + return x + + def forward(self, x: torch.Tensor, mod: torch.Tensor) -> torch.Tensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, mod, use_reentrant=False) + else: + return self._forward(x, mod) + + +class ModulatedTransformerCrossBlock(nn.Module): + """ + Transformer cross-attention block (MSA + MCA + FFN) with adaptive layer norm conditioning. + """ + def __init__( + self, + channels: int, + ctx_channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "windowed"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + qk_rms_norm: bool = False, + qk_rms_norm_cross: bool = False, + qkv_bias: bool = True, + share_mod: bool = False, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.share_mod = share_mod + self.norm1 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6) + self.norm3 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.self_attn = MultiHeadAttention( + channels, + num_heads=num_heads, + type="self", + attn_mode=attn_mode, + window_size=window_size, + shift_window=shift_window, + qkv_bias=qkv_bias, + use_rope=use_rope, + qk_rms_norm=qk_rms_norm, + ) + self.cross_attn = MultiHeadAttention( + channels, + ctx_channels=ctx_channels, + num_heads=num_heads, + type="cross", + attn_mode="full", + qkv_bias=qkv_bias, + qk_rms_norm=qk_rms_norm_cross, + ) + self.mlp = FeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + if not share_mod: + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), + nn.Linear(channels, 6 * channels, bias=True) + ) + + def _forward(self, x: torch.Tensor, mod: torch.Tensor, context: torch.Tensor): + if self.share_mod: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = mod.chunk(6, dim=1) + else: + shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(mod).chunk(6, dim=1) + h = self.norm1(x) + h = h * (1 + scale_msa.unsqueeze(1)) + shift_msa.unsqueeze(1) + h = self.self_attn(h) + h = h * gate_msa.unsqueeze(1) + x = x + h + h = self.norm2(x) + h = self.cross_attn(h, context) + x = x + h + h = self.norm3(x) + h = h * (1 + scale_mlp.unsqueeze(1)) + shift_mlp.unsqueeze(1) + h = self.mlp(h) + h = h * gate_mlp.unsqueeze(1) + x = x + h + return x + + def forward(self, x: torch.Tensor, mod: torch.Tensor, context: torch.Tensor): + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, mod, context, use_reentrant=False) + else: + return self._forward(x, mod, context) + +class ModulatedPosedTransformerBlock(nn.Module): + """ + Transformer block (MSA + FFN) with adaptive layer norm conditioning. + """ + def __init__( + self, + channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "windowed"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + qk_rms_norm: bool = False, + qkv_bias: bool = True, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.norm1 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.attn = MultiHeadAttention( + channels, + num_heads=num_heads, + attn_mode=attn_mode, + window_size=window_size, + shift_window=shift_window, + qkv_bias=qkv_bias, + use_rope=use_rope, + qk_rms_norm=qk_rms_norm, + ) + self.mlp = FeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + + def _forward(self, x: torch.Tensor) -> torch.Tensor: + h = self.norm1(x) + h = self.attn(h) + x = x + h + h = self.norm2(x) + h = self.mlp(h) + x = x + h + return x + + def forward(self, x: torch.Tensor) -> torch.Tensor: + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, use_reentrant=False) + else: + return self._forward(x) + +class ModulatedTransformerCrossBlock_woT(nn.Module): + """ + Transformer cross-attention block (MSA + MCA + FFN) with adaptive layer norm conditioning. + """ + def __init__( + self, + channels: int, + ctx_channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "windowed"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + qk_rms_norm: bool = False, + qk_rms_norm_cross: bool = False, + qkv_bias: bool = True, + share_mod: bool = False, + ): + super().__init__() + self.use_checkpoint = use_checkpoint + self.share_mod = share_mod + self.norm1 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.norm2 = LayerNorm32(channels, elementwise_affine=True, eps=1e-6) + self.norm3 = LayerNorm32(channels, elementwise_affine=False, eps=1e-6) + self.self_attn = MultiHeadAttention( + channels, + num_heads=num_heads, + type="self", + attn_mode=attn_mode, + window_size=window_size, + shift_window=shift_window, + qkv_bias=qkv_bias, + use_rope=use_rope, + qk_rms_norm=qk_rms_norm, + ) + self.cross_attn = MultiHeadAttention( + channels, + ctx_channels=ctx_channels, + num_heads=num_heads, + type="cross", + attn_mode="full", + qkv_bias=qkv_bias, + qk_rms_norm=qk_rms_norm_cross, + ) + self.mlp = FeedForwardNet( + channels, + mlp_ratio=mlp_ratio, + ) + + def _forward(self, x: torch.Tensor, context: torch.Tensor): + + h = self.norm1(x) + h = self.self_attn(h) + x = x + h + h = self.norm2(x) + h = self.cross_attn(h, context) + x = x + h + h = self.norm3(x) + h = self.mlp(h) + x = x + h + return x + + def forward(self, x: torch.Tensor, context: torch.Tensor): + if self.use_checkpoint: + return torch.utils.checkpoint.checkpoint(self._forward, x, context, use_reentrant=False) + else: + return self._forward(x, context) + +class ModulatedMultiViewCond(nn.Module): + """ + Transformer cross-attention block (MSA + MCA + FFN) with adaptive layer norm conditioning. + """ + def __init__( + self, + channels: int, + ctx_channels: int, + num_heads: int, + mlp_ratio: float = 4.0, + attn_mode: Literal["full", "windowed"] = "full", + window_size: Optional[int] = None, + shift_window: Optional[Tuple[int, int, int]] = None, + use_checkpoint: bool = False, + use_rope: bool = False, + qk_rms_norm: bool = False, + qk_rms_norm_cross: bool = False, + qkv_bias: bool = True, + share_mod: bool = False, + num_init_tokens: int = 4096, + dtype: Optional[torch.dtype] = torch.float32, + ): + super().__init__() + self.cond_blocks = nn.ModuleList([ + ModulatedTransformerCrossBlock_woT( + channels, + ctx_channels, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + attn_mode=attn_mode, + use_checkpoint=use_checkpoint, + use_rope=use_rope, + share_mod=share_mod, + qk_rms_norm=qk_rms_norm, + qk_rms_norm_cross=qk_rms_norm_cross, + ) + for _ in range(4) + ]) + self.multiview_cond_tokens = nn.Parameter(torch.randn(1, num_init_tokens, channels).to(dtype)) + nn.init.normal_(self.multiview_cond_tokens, std=1e-6) + self.intermediate_layer_idx = [4, 11, 17, 23] + + def forward(self, aggregated_tokens_list: List, image_cond: torch.Tensor): + + b = aggregated_tokens_list[0].shape[0] + patch_start_idx = 5 + idx = 0 + cond = self.multiview_cond_tokens.repeat(b, 1, 1) + for layer_idx in self.intermediate_layer_idx: + x = aggregated_tokens_list[layer_idx][:, :, patch_start_idx:] + # x = x.reshape(b, -1, 2048) + torch.cat([image_cond.reshape(b, -1, 1024), image_cond.reshape(b, -1, 1024)],dim=-1) + x = torch.cat([x.reshape(b, -1, 2048), image_cond.reshape(b, -1, 1024)],dim=-1) + cond = self.cond_blocks[idx](cond, x) + idx = idx + 1 + return cond \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/modules/utils.py b/OVOW/engine/oneposeviagen/trellis/trellis/modules/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..79aad7b08b1cb00db06d60d8215c7156926e80ac --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/modules/utils.py @@ -0,0 +1,75 @@ +import torch.nn as nn +from ..modules import sparse as sp +import torch + +FP16_MODULES = ( + nn.Conv1d, + nn.Conv2d, + nn.Conv3d, + nn.ConvTranspose1d, + nn.ConvTranspose2d, + nn.ConvTranspose3d, + nn.Linear, + sp.SparseConv3d, + sp.SparseInverseConv3d, + sp.SparseLinear, +) + +BF16_MODULES = ( + nn.Conv1d, + nn.Conv2d, + nn.Conv3d, + nn.ConvTranspose1d, + nn.ConvTranspose2d, + nn.ConvTranspose3d, + nn.Linear, + sp.SparseConv3d, + sp.SparseInverseConv3d, + sp.SparseLinear, +) + +def convert_module_to_f16(l): + """ + Convert primitive modules to float16. + """ + if isinstance(l, FP16_MODULES): + for p in l.parameters(): + p.data = p.data.half() + +def convert_module_to_bf16(l): + """ + Convert primitive modules to bfloat16. + """ + if isinstance(l, BF16_MODULES): + for p in l.parameters(): + p.data = p.data.type(torch.bfloat16) + +def convert_module_to_f32(l): + """ + Convert primitive modules to float32, undoing convert_module_to_f16(). + """ + if isinstance(l, FP16_MODULES): + for p in l.parameters(): + p.data = p.data.float() + + +def zero_module(module): + """ + Zero out the parameters of a module and return it. + """ + for p in module.parameters(): + p.detach().zero_() + return module + + +def scale_module(module, scale): + """ + Scale the parameters of a module and return it. + """ + for p in module.parameters(): + p.detach().mul_(scale) + return module + + +def modulate(x, shift, scale): + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..00c2172c78e25a1a488e1fa4d2fea8d8d8a15bb8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/__init__.py @@ -0,0 +1,24 @@ +from . import samplers +from .trellis_image_to_3d import TrellisImageTo3DPipeline, TrellisVGGTLORATo3DPipeline +from .trellis_image_to_ss import TrellisImageToSSPipeline, TrellisVGGTLORAToSSPipeline + +def from_pretrained(path: str): + """ + Load a pipeline from a model folder or a Hugging Face model hub. + + Args: + path: The path to the model. Can be either local path or a Hugging Face model name. + """ + import os + import json + is_local = os.path.exists(f"{path}/pipeline.json") + + if is_local: + config_file = f"{path}/pipeline.json" + else: + from huggingface_hub import hf_hub_download + config_file = hf_hub_download(path, "pipeline.json") + + with open(config_file, 'r') as f: + config = json.load(f) + return globals()[config['name']].from_pretrained(path) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/base.py b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/base.py new file mode 100644 index 0000000000000000000000000000000000000000..86d051185491c0d809fdf77149bca656583b0f61 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/base.py @@ -0,0 +1,134 @@ +from typing import * +import torch +import torch.nn as nn +from .. import models +import pytorch_lightning as pl +from ..modules import sparse as sp + +class Pipeline(pl.LightningModule): + """ + A base class for pipelines. + """ + def __init__( + self, + models: dict[str, nn.Module] = None, + ): + super().__init__() # Initialize the LightningModule + self.t_scheduler = 'uniform' + if models is None: + return + self.models = models + for model in self.models.values(): + model.eval() + if 'slat_flow_model' in self.models: + self.slat_flow_model = self.models['slat_flow_model'] + if 'sparse_structure_flow_model' in self.models: + self.sparse_structure_flow_model = self.models['sparse_structure_flow_model'] + + @staticmethod + def from_pretrained(path: str) -> "Pipeline": + """ + Load a pretrained model. + """ + import os + import json + is_local = os.path.exists(f"{path}/pipeline.json") + + if is_local: + config_file = f"{path}/pipeline.json" + else: + from huggingface_hub import hf_hub_download + config_file = hf_hub_download(path, "pipeline.json") + + with open(config_file, 'r') as f: + args = json.load(f)['args'] + + _models = { + k: models.from_pretrained(f"{path}/{v}") + for k, v in args['models'].items() + } + + new_pipeline = Pipeline(_models) + new_pipeline._pretrained_args = args + return new_pipeline + + def load_model(self, name: str, path: str): + _model = self.models[name] + states = torch.load(path) + if 'state_dict' in states: + states = states['state_dict'] + states = {k.replace(f"{name}.", ""): v for k, v in states.items()} + _model.load_state_dict(states, False) + self.models[name] = _model + + @property + def device(self) -> torch.device: + for model in self.models.values(): + if hasattr(model, 'device'): + return model.device + for model in self.models.values(): + if hasattr(model, 'parameters'): + return next(model.parameters()).device + raise RuntimeError("No device found.") + + def to(self, device: torch.device = None, dtype: torch.dtype = None) -> None: + for model in self.models.values(): + if dtype is not None and device is not None: + model.to(device, dtype) + elif device is not None: + model.to(device) + elif dtype is not None: + model.type(dtype) + + def cuda(self) -> None: + self.to(torch.device("cuda")) + + def cpu(self) -> None: + self.to(torch.device("cpu")) + + def forward(self, x: torch.Tensor, t: torch.Tensor, cond: torch.Tensor) -> torch.Tensor: + raise NotImplementedError + + def p_losses(self, x_0, cond, t, noise): + x_t, gt_v = self.slat_sampler._get_model_gt(x_0, t, noise) + + t = torch.tensor([1000 * t] * x_t.shape[0], device=x_t.device, dtype=torch.float32) + pred_v = self(x_t, t, cond) + loss_dict = {} + prefix = 'train' if self.training else 'val' + loss_simple = self.mse_loss_sparse(pred_v, gt_v) + + # Ignore NaN losses + valid_loss_simple = loss_simple[~torch.isnan(loss_simple)] + loss_dict.update({f'{prefix}/loss_simple': valid_loss_simple.mean()}) + loss = valid_loss_simple.mean() + + return loss, loss_dict + + def mse_loss_sparse(self, pred, target): + diff = pred.feats - target.feats + return diff ** 2 + + def training_step(self, batch, batch_idx): + if self.t_scheduler == 'uniform': + t = torch.rand(1).item() + elif type(self.t_scheduler)==float: + t = self.t_scheduler + else: + assert False, 'Not implemented' + + targets, cond, noise = self.get_input(batch) + loss, loss_dict = self.p_losses(targets, cond, t, noise) + self.log('train_loss', loss, prog_bar=True) + return loss + + def validation_step(self, batch, batch_idx): + t = 0.9 # Use fixed t=0.5 for validation + targets, cond, noise = self.get_input(batch) + loss, loss_dict = self.p_losses(targets, cond, t, noise) + self.log('val_loss', loss, prog_bar=True) + + return loss + + def configure_optimizers(self): + raise NotImplementedError \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/samplers/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/samplers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..54d412fc5d8eb662081a92a56ad078243988c2f9 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/samplers/__init__.py @@ -0,0 +1,2 @@ +from .base import Sampler +from .flow_euler import FlowEulerSampler, FlowEulerCfgSampler, FlowEulerGuidanceIntervalSampler \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/samplers/base.py b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/samplers/base.py new file mode 100644 index 0000000000000000000000000000000000000000..1966ce787009a5ee0c1ed06dce491525ff1dbcbf --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/samplers/base.py @@ -0,0 +1,20 @@ +from typing import * +from abc import ABC, abstractmethod + + +class Sampler(ABC): + """ + A base class for samplers. + """ + + @abstractmethod + def sample( + self, + model, + **kwargs + ): + """ + Sample from a model. + """ + pass + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/samplers/classifier_free_guidance_mixin.py b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/samplers/classifier_free_guidance_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..5701b25f5d7a2197612eb256f8ee13e8c489da1f --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/samplers/classifier_free_guidance_mixin.py @@ -0,0 +1,12 @@ +from typing import * + + +class ClassifierFreeGuidanceSamplerMixin: + """ + A mixin class for samplers that apply classifier-free guidance. + """ + + def _inference_model(self, model, x_t, t, cond, neg_cond, cfg_strength, **kwargs): + pred = super()._inference_model(model, x_t, t, cond, **kwargs) + neg_pred = super()._inference_model(model, x_t, t, neg_cond, **kwargs) + return (1 + cfg_strength) * pred - cfg_strength * neg_pred diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/samplers/flow_euler.py b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/samplers/flow_euler.py new file mode 100644 index 0000000000000000000000000000000000000000..64a459ab7623a20e1214980d4fff656b5581be2d --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/samplers/flow_euler.py @@ -0,0 +1,471 @@ +from typing import * +import torch +import numpy as np +from tqdm import tqdm +from easydict import EasyDict as edict +from .base import Sampler +from .classifier_free_guidance_mixin import ClassifierFreeGuidanceSamplerMixin +from .guidance_interval_mixin import GuidanceIntervalSamplerMixin +import trellis.modules.sparse as sp +from trellis.modules.spatial import patchify, unpatchify + +class FlowEulerSampler(Sampler): + """ + Generate samples from a flow-matching model using Euler sampling. + + Args: + sigma_min: The minimum scale of noise in flow. + """ + def __init__( + self, + sigma_min: float, + ): + self.sigma_min = sigma_min + + def _eps_to_xstart(self, x_t, t, eps): + assert x_t.shape == eps.shape + return (x_t - (self.sigma_min + (1 - self.sigma_min) * t) * eps) / (1 - t) + + def _xstart_to_x_t(self, x_0, t, eps): + assert x_0.shape == eps.shape + return (1-t) * x_0 + (self.sigma_min + (1 - self.sigma_min) * t) * eps + + def _xstart_to_x_t(self, x_0, t, eps): + assert x_0.shape == eps.shape + return (1-t) * x_0 + (self.sigma_min + (1 - self.sigma_min) * t) * eps + + def _xstart_to_eps(self, x_t, t, x_0): + assert x_t.shape == x_0.shape + return (x_t - (1 - t) * x_0) / (self.sigma_min + (1 - self.sigma_min) * t) + + def _v_to_xstart_eps(self, x_t, t, v): + assert x_t.shape == v.shape + eps = (1 - t) * v + x_t + x_0 = (1 - self.sigma_min) * x_t - (self.sigma_min + (1 - self.sigma_min) * t) * v + return x_0, eps + + def _xstart_to_v(self, x_0, x_t, t): + assert x_0.shape == x_t.shape + return (x_t - (1 - self.sigma_min) * x_0) / (self.sigma_min + (1 - self.sigma_min) * t) + + + def _inference_model(self, model, x_t, t, cond=None, **kwargs): + t = torch.tensor([1000 * t] * x_t.shape[0], device=x_t.device, dtype=torch.float32) + return model(x_t.to(torch.float32), t, cond, **kwargs) + + def _get_model_prediction(self, model, x_t, t, cond=None, **kwargs): + param = kwargs.pop("parameterization", "v") + if param == "v": + pred_v = self._inference_model(model, x_t, t, cond, **kwargs) + pred_x_0, pred_eps = self._v_to_xstart_eps(x_t=x_t, t=t, v=pred_v) + elif param == "x0": + pred_x_0 = self._inference_model(model, x_t, t, cond, **kwargs) + pred_v = self._xstart_to_v(x_0=pred_x_0, x_t=x_t, t=t) + return pred_x_0, None, pred_v + + def _get_model_gt(self, x_0, t, noise): + gt_x_t = self._xstart_to_x_t(x_0, t, noise) + gt_v = self._xstart_to_v(x_0, gt_x_t, t) + return gt_x_t, gt_v + + @torch.no_grad() + def sample_once( + self, + model, + x_t, + t: float, + t_prev: float, + cond: Optional[Any] = None, + **kwargs + ): + """ + Sample x_{t-1} from the model using Euler method. + + Args: + model: The model to sample from. + x_t: The [N x C x ...] tensor of noisy inputs at time t. + t: The current timestep. + t_prev: The previous timestep. + cond: conditional information. + **kwargs: Additional arguments for model inference. + + Returns: + a dict containing the following + - 'pred_x_prev': x_{t-1}. + - 'pred_x_0': a prediction of x_0. + """ + pred_x_0, pred_eps, pred_v = self._get_model_prediction(model, x_t, t, cond, **kwargs) + pred_x_prev = x_t - (t - t_prev) * pred_v + return edict({"pred_x_prev": pred_x_prev, "pred_x_0": pred_x_0, "pred_eps": pred_eps}) + + @torch.no_grad() + def sample_once_featurevolume( + self, + model, + cond_model, + x_t, + t: float, + t_prev: float, + cond: Optional[Any] = None, + **kwargs + ): + """ + Sample x_{t-1} from the model using Euler method. + + Args: + model: The model to sample from. + x_t: The [N x C x ...] tensor of noisy inputs at time t. + t: The current timestep. + t_prev: The previous timestep. + cond: conditional information. + **kwargs: Additional arguments for model inference. + + Returns: + a dict containing the following + - 'pred_x_prev': x_{t-1}. + - 'pred_x_0': a prediction of x_0. + """ + if isinstance(cond, sp.SparseTensor): + t_tmp = torch.tensor([1000 * t] * x_t.shape[0], device=x_t.device, dtype=x_t.dtype) + t_embed = model.t_embedder(t_tmp).to(x_t.dtype) + for block in cond_model: + cond = block(cond, t_embed) + if model.pe_mode == "ape": + cond = cond + model.pos_embedder(cond.coords[:, 1:]).to(x_t.dtype) + if 'neg_cond' in kwargs.keys(): + neg_cond = kwargs['neg_cond'] + for block in cond_model: + neg_cond = block(neg_cond, t_embed) + if model.pe_mode == "ape": + neg_cond = neg_cond + model.pos_embedder(neg_cond.coords[:, 1:]).to(x_t.dtype) + kwargs['neg_cond'] = neg_cond + else: + for block in cond_model: + cond = block(cond) + cond = patchify(cond, model.patch_size) + cond = cond.view(*cond.shape[:2], -1).permute(0, 2, 1).contiguous() + cond = cond + model.pos_emb[None].type(model.dtype) + if 'neg_cond' in kwargs.keys(): + neg_cond = kwargs['neg_cond'] + for block in cond_model: + neg_cond = block(neg_cond) + neg_cond = patchify(neg_cond, model.patch_size) + neg_cond = neg_cond.view(*neg_cond.shape[:2], -1).permute(0, 2, 1).contiguous() + neg_cond = neg_cond + model.pos_emb[None].type(model.dtype) + kwargs['neg_cond'] = neg_cond + pred_x_0, pred_eps, pred_v = self._get_model_prediction(model, x_t, t, cond, **kwargs) + pred_x_prev = x_t - (t - t_prev) * pred_v + return edict({"pred_x_prev": pred_x_prev, "pred_x_0": pred_x_0, "pred_eps": pred_eps}) + + @torch.no_grad() + def sample_featurevolume( + self, + model, + cond_model, + noise, + cond: Optional[Any] = None, + steps: int = 50, + rescale_t: float = 1.0, + verbose: bool = True, + **kwargs + ): + """ + Generate samples from the model using Euler method. + + Args: + model: The model to sample from. + noise: The initial noise tensor. + cond: conditional information. + steps: The number of steps to sample. + rescale_t: The rescale factor for t. + verbose: If True, show a progress bar. + **kwargs: Additional arguments for model_inference. + + Returns: + a dict containing the following + - 'samples': the model samples. + - 'pred_x_t': a list of prediction of x_t. + - 'pred_x_0': a list of prediction of x_0. + """ + sample = noise + t_seq = np.linspace(1, 0, steps + 1) + t_seq = rescale_t * t_seq / (1 + (rescale_t - 1) * t_seq) + t_pairs = list((t_seq[i], t_seq[i + 1]) for i in range(steps)) + ret = edict({"samples": None, "pred_x_t": [], "pred_x_0": []}) + for t, t_prev in tqdm(t_pairs, desc="Sampling", disable=not verbose): + out = self.sample_once_featurevolume(model, cond_model, sample, t, t_prev, cond, **kwargs) + sample = out.pred_x_prev + ret.pred_x_t.append(out.pred_x_prev) + ret.pred_x_0.append(out.pred_x_0) + ret.samples = sample + return ret + + @torch.no_grad() + def sample( + self, + model, + noise, + cond: Optional[Any] = None, + steps: int = 50, + rescale_t: float = 1.0, + verbose: bool = True, + **kwargs + ): + """ + Generate samples from the model using Euler method. + + Args: + model: The model to sample from. + noise: The initial noise tensor. + cond: conditional information. + steps: The number of steps to sample. + rescale_t: The rescale factor for t. + verbose: If True, show a progress bar. + **kwargs: Additional arguments for model_inference. + + Returns: + a dict containing the following + - 'samples': the model samples. + - 'pred_x_t': a list of prediction of x_t. + - 'pred_x_0': a list of prediction of x_0. + """ + sample = noise + t_seq = np.linspace(1, 0, steps + 1) + t_seq = rescale_t * t_seq / (1 + (rescale_t - 1) * t_seq) + t_pairs = list((t_seq[i], t_seq[i + 1]) for i in range(steps)) + ret = edict({"samples": None, "pred_x_t": [], "pred_x_0": []}) + for t, t_prev in tqdm(t_pairs, desc="Sampling", disable=not verbose): + out = self.sample_once(model, sample, t, t_prev, cond, **kwargs) + sample = out.pred_x_prev + ret.pred_x_t.append(out.pred_x_prev) + ret.pred_x_0.append(out.pred_x_0) + ret.samples = sample + return ret + + +class FlowMatchingSampler(FlowEulerSampler): + """ + Implementation of Flow Matching using Euler sampling. + Inherits from FlowEulerSampler and modifies key methods for flow matching. + """ + def __init__(self, sigma_min: float = 0.0): + super().__init__(sigma_min=sigma_min) + + def _compute_velocity(self, x_t: torch.Tensor, x_0: torch.Tensor, t: float) -> torch.Tensor: + return ((1 - self.sigma_min) * x_t - x_0 ) / (self.sigma_min + (1 - self.sigma_min) * t) + + def _get_model_gt(self, x_1: torch.Tensor, t: float, x_0: torch.Tensor = None): + # TODO: Implement this method + pass + # """ + # Get ground truth for training. + # Args: + # x_1: Target endpoint + # t: Time point + # noise: Initial noise to use as x_0 + # """ + # x_t = (1 - t) * x_0 + t * x_1 + # v = self._compute_velocity(x_t, x_0, t) + # eps = x_t + (1 - t) * v # Convert velocity to noise + # return x_t, eps, v + + def _v_to_xstart_eps(self, x_t: torch.Tensor, t: float, v: torch.Tensor): + """Convert velocity to x_0 and noise predictions""" + eps = x_t + (1 - t) * v + x_0 = self._eps_to_xstart(x_t, t, eps) + return x_0, eps + + @torch.no_grad() + def sample( + self, + model, + x_1: torch.Tensor, + cond: Optional[Any] = None, + steps: int = 50, + rescale_t: float = 1.0, + verbose: bool = True, + **kwargs + ) -> Dict[str, torch.Tensor]: + """ + Generate samples by following the flow from noise to x_1. + Args: + model: The model to sample from + x_1: Target endpoint + cond: Conditional information + steps: Number of sampling steps + rescale_t: Time rescaling factor + verbose: Whether to show progress bar + **kwargs: Additional model arguments + Returns: + Dictionary containing sampling trajectory and predictions + """ + # Initialize with noise as x_0 + noise = torch.randn_like(x_1) + current_x = noise + + t_seq = np.linspace(1, 0, steps + 1) + t_seq = rescale_t * t_seq / (1 + (rescale_t - 1) * t_seq) + t_pairs = list(zip(t_seq[:-1], t_seq[1:])) + + ret = edict({ + "samples": None, + "pred_x_t": [], + "pred_x_0": [] + }) + + for t, t_prev in tqdm(t_pairs, desc="Sampling", disable=not verbose): + out = self.sample_once(model, current_x, t, t_prev, cond, **kwargs) + current_x = out.pred_x_prev + ret.pred_x_t.append(out.pred_x_prev) + ret.pred_x_0.append(out.pred_x_0) + + ret.samples = current_x + return ret + + def sample_once( + self, + model, + x_t: torch.Tensor, + t: float, + t_prev: float, + cond: Optional[Any] = None, + **kwargs + ) -> Dict: + """ + Sample x_{t-1} from the model using Euler method. + Args: + model: The model to sample from + x_t: Current state + t: Current time + t_prev: Next time step + cond: Conditional information + **kwargs: Additional model arguments + Returns: + Dictionary containing predictions + """ + pred_x_0, pred_eps, pred_v = self._get_model_prediction(model, x_t, t, cond, **kwargs) + pred_x_prev = x_t + (t_prev - t) * pred_v + return edict({ + "pred_x_prev": pred_x_prev, + "pred_x_0": pred_x_0, + "pred_eps": pred_eps + }) + +class FlowEulerCfgSampler(ClassifierFreeGuidanceSamplerMixin, FlowEulerSampler): + """ + Generate samples from a flow-matching model using Euler sampling with classifier-free guidance. + """ + @torch.no_grad() + def sample( + self, + model, + noise, + cond, + neg_cond, + steps: int = 50, + rescale_t: float = 1.0, + cfg_strength: float = 3.0, + verbose: bool = True, + **kwargs + ): + """ + Generate samples from the model using Euler method. + + Args: + model: The model to sample from. + noise: The initial noise tensor. + cond: conditional information. + neg_cond: negative conditional information. + steps: The number of steps to sample. + rescale_t: The rescale factor for t. + cfg_strength: The strength of classifier-free guidance. + verbose: If True, show a progress bar. + **kwargs: Additional arguments for model_inference. + + Returns: + a dict containing the following + - 'samples': the model samples. + - 'pred_x_t': a list of prediction of x_t. + - 'pred_x_0': a list of prediction of x_0. + """ + return super().sample(model, noise, cond, steps, rescale_t, verbose, neg_cond=neg_cond, cfg_strength=cfg_strength, **kwargs) + + +class FlowEulerGuidanceIntervalSampler(GuidanceIntervalSamplerMixin, FlowEulerSampler): + """ + Generate samples from a flow-matching model using Euler sampling with classifier-free guidance and interval. + """ + @torch.no_grad() + def sample( + self, + model, + noise, + cond, + neg_cond, + steps: int = 50, + rescale_t: float = 1.0, + cfg_strength: float = 3.0, + cfg_interval: Tuple[float, float] = (0.0, 1.0), + verbose: bool = True, + **kwargs + ): + """ + Generate samples from the model using Euler method. + + Args: + model: The model to sample from. + noise: The initial noise tensor. + cond: conditional information. + neg_cond: negative conditional information. + steps: The number of steps to sample. + rescale_t: The rescale factor for t. + cfg_strength: The strength of classifier-free guidance. + cfg_interval: The interval for classifier-free guidance. + verbose: If True, show a progress bar. + **kwargs: Additional arguments for model_inference. + + Returns: + a dict containing the following + - 'samples': the model samples. + - 'pred_x_t': a list of prediction of x_t. + - 'pred_x_0': a list of prediction of x_0. + """ + return super().sample(model, noise, cond, steps, rescale_t, verbose, neg_cond=neg_cond, cfg_strength=cfg_strength, cfg_interval=cfg_interval, **kwargs) + + @torch.no_grad() + def sample_featurevolume( + self, + model, + cond_model, + noise, + cond, + neg_cond, + steps: int = 50, + rescale_t: float = 1.0, + cfg_strength: float = 3.0, + cfg_interval: Tuple[float, float] = (0.0, 1.0), + verbose: bool = True, + **kwargs + ): + """ + Generate samples from the model using Euler method. + + Args: + model: The model to sample from. + noise: The initial noise tensor. + cond: conditional information. + neg_cond: negative conditional information. + steps: The number of steps to sample. + rescale_t: The rescale factor for t. + cfg_strength: The strength of classifier-free guidance. + cfg_interval: The interval for classifier-free guidance. + verbose: If True, show a progress bar. + **kwargs: Additional arguments for model_inference. + + Returns: + a dict containing the following + - 'samples': the model samples. + - 'pred_x_t': a list of prediction of x_t. + - 'pred_x_0': a list of prediction of x_0. + """ + return super().sample_featurevolume(model, cond_model, noise, cond, steps, rescale_t, verbose, neg_cond=neg_cond, cfg_strength=cfg_strength, cfg_interval=cfg_interval, **kwargs) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/samplers/guidance_interval_mixin.py b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/samplers/guidance_interval_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..7074a4d5fea20a8f799416aa6571faca4f9eea06 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/samplers/guidance_interval_mixin.py @@ -0,0 +1,15 @@ +from typing import * + + +class GuidanceIntervalSamplerMixin: + """ + A mixin class for samplers that apply classifier-free guidance with interval. + """ + + def _inference_model(self, model, x_t, t, cond, neg_cond, cfg_strength, cfg_interval, **kwargs): + if cfg_interval[0] <= t <= cfg_interval[1]: + pred = super()._inference_model(model, x_t, t, cond, **kwargs) + neg_pred = super()._inference_model(model, x_t, t, neg_cond, **kwargs) + return (1 + cfg_strength) * pred - cfg_strength * neg_pred + else: + return super()._inference_model(model, x_t, t, cond, **kwargs) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/trellis_image_to_3d.py b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/trellis_image_to_3d.py new file mode 100644 index 0000000000000000000000000000000000000000..2067d39fda94492219c746c4965130e8673c782a --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/trellis_image_to_3d.py @@ -0,0 +1,984 @@ +from typing import * +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from tqdm import tqdm +from easydict import EasyDict as edict +from torchvision import transforms +from PIL import Image +import trimesh +import os +from scipy.spatial import cKDTree +import pytorch_lightning as pl +import random +import open3d as o3d +import utils3d +from trellis.modules.sparse.attention import SparseMultiHeadAttention +from trellis.models.structured_latent_flow import SparseResBlock3d, SparseResBlock3dwoT +import trellis.modules.sparse as sp +from trellis.models.sparse_structure_vae import * +from ..modules.spatial import patchify, unpatchify +from deepspeed.ops.adam import FusedAdam +from trellis.modules.utils import convert_module_to_bf16, convert_module_to_f16, convert_module_to_f32 +from contextlib import contextmanager +import trellis.models as models +from trellis.modules.transformer import ModulatedPosedTransformerBlock + +import sys +# sys.path.append("wheels/vggt") +# from wheels.vggt.vggt.models.vggt import VGGT +from typing import * +from scipy.spatial.transform import Rotation +from trellis.modules.transformer import ModulatedMultiViewCond + +def export_point_cloud(xyz, color): + # Convert tensors to numpy arrays if needed + if isinstance(xyz, torch.Tensor): + xyz = xyz.detach().cpu().numpy() + if isinstance(color, torch.Tensor): + color = color.detach().cpu().numpy() + + color = (color * 255).astype(np.uint8) + + # Create point cloud using trimesh + point_cloud = trimesh.PointCloud(vertices=xyz, colors=color) + + return point_cloud + +def normalize_trimesh(mesh): + # Calculate the mesh centroid and bounding box extents + centroid = mesh.centroid + # Determine the scale based on the largest extent to fit into unit cube + # Normalizing: Center and scale the vertices + mesh.vertices -= centroid + + extents = mesh.extents + scale = max(extents) + mesh.vertices /= scale + + return mesh + +def random_sample_rotation(rotation_factor: float = 1.0) -> np.ndarray: + # angle_z, angle_y, angle_x + euler = np.random.rand(3) * np.pi * 2 / rotation_factor # (0, 2 * pi / rotation_range) + rotation = Rotation.from_euler('zyx', euler).as_matrix() + return rotation + +from scipy.ndimage import binary_dilation +def voxelize_trimesh(mesh, resolution=(64, 64, 64), stride=4): + """ + Voxelize a given trimesh object with the specified resolution, incorporating 4x anti-aliasing. + First voxelizes at a 4x resolution and then downsamples to the target resolution. + + Args: + mesh (trimesh.Trimesh): The input trimesh object to be voxelized. + resolution (tuple): The voxel grid resolution as (x, y, z). Default is (64, 64, 64). + + Returns: + np.ndarray: A boolean numpy array representing the voxel grid where True indicates + the presence of the mesh in that voxel and False otherwise. + """ + target_density = max(resolution) + target_edge_length = 1.0 / target_density + max_edge_for_subdivision = target_edge_length / 2 + + # Calculate the higher resolution for 4x anti-aliasing + anti_aliasing_density = target_density * stride + anti_aliasing_edge_length = 1.0 / anti_aliasing_density + anti_aliasing_max_edge_for_subdivision = anti_aliasing_edge_length / 2 + + # Get the vertices and faces of the mesh + vertices = mesh.vertices + faces = mesh.faces + + # Subdivide the mesh for the higher resolution voxelization + try: + new_vertices, new_faces = trimesh.remesh.subdivide_to_size( + vertices, faces, anti_aliasing_max_edge_for_subdivision + ) + subdivided_mesh = trimesh.Trimesh(vertices=new_vertices, faces=new_faces) + except Exception as e: + print(f"Unexpected error during mesh subdivision for anti-aliasing: {e}") + raise + + # Voxelize the subdivided mesh at the higher resolution + try: + high_res_voxel_grid = subdivided_mesh.voxelized( + pitch=anti_aliasing_edge_length, method="binvox", exact=True + ) + except: + print("Voxelization using 'binvox' method failed for anti-aliasing") + high_res_voxel_grid = subdivided_mesh.voxelized(pitch=anti_aliasing_edge_length) + print("Falling back to default voxelization method for anti-aliasing.") + high_res_boolean_array = high_res_voxel_grid.matrix.astype(bool) + + x_stride, y_stride, z_stride = [int(anti_aliasing_density / target_density)] * 3 + downsampled_shape = ( + high_res_boolean_array.shape[0] // x_stride, + high_res_boolean_array.shape[1] // y_stride, + high_res_boolean_array.shape[2] // z_stride + ) + downsampled_array = np.zeros(downsampled_shape, dtype=bool) + + # Use NumPy's strided tricks to efficiently access sub-cubes for downsampling + shape = (downsampled_shape[0], downsampled_shape[1], downsampled_shape[2], x_stride, y_stride, z_stride) + strides = (x_stride * high_res_boolean_array.strides[0], + y_stride * high_res_boolean_array.strides[1], + z_stride * high_res_boolean_array.strides[2], + high_res_boolean_array.strides[0], + high_res_boolean_array.strides[1], + high_res_boolean_array.strides[2]) + sub_cubes = np.lib.stride_tricks.as_strided(high_res_boolean_array, shape=shape, strides=strides) + downsampled_array = np.any(sub_cubes, axis=(3, 4, 5)) + + return downsampled_array + +def get_occupied_coordinates(voxel_grid): + # Find the indices of occupied voxels + occupied_indices = np.argwhere(voxel_grid) + + coords = torch.tensor(occupied_indices, dtype=torch.int8) # Use float for scaling operations + + # Add a leading dimension for batch size or any additional data associations + coords = torch.cat([torch.zeros(coords.shape[0], 1, dtype=torch.int32), coords + 1], dim=1) + + # Move to GPU if required + coords = coords.to('cuda:0') + + return coords + +from .base import Pipeline +from . import samplers +from ..modules import sparse as sp + + +class TrellisImageTo3DPipeline(Pipeline): + """ + Pipeline for inferring Trellis image-to-3D models. + + Args: + models (dict[str, nn.Module]): The models to use in the pipeline. + sparse_structure_sampler (samplers.Sampler): The sampler for the sparse structure. + slat_sampler (samplers.Sampler): The sampler for the structured latent. + slat_normalization (dict): The normalization parameters for the structured latent. + image_cond_model (str): The name of the image conditioning model. + """ + default_image_resolution = 518 + def __init__( + self, + models: dict[str, nn.Module] = None, + sparse_structure_sampler: samplers.Sampler = None, + slat_sampler: samplers.Sampler = None, + slat_normalization: dict = None, + image_cond_model: str = None, + ): + if models is None: + return + super().__init__(models) + self.sparse_structure_sampler = sparse_structure_sampler + self.slat_sampler = slat_sampler + self.sparse_structure_sampler_params = {} + self.slat_sampler_params = {} + self.slat_normalization = slat_normalization + self._init_image_cond_model(image_cond_model) + + @staticmethod + def from_pretrained(path: str) -> "TrellisImageTo3DPipeline": + """ + Load a pretrained model. + + Args: + path (str): The path to the model. Can be either local path or a Hugging Face repository. + """ + pipeline = super(TrellisImageTo3DPipeline, TrellisImageTo3DPipeline).from_pretrained(path) + new_pipeline = TrellisImageTo3DPipeline() + new_pipeline.__dict__ = pipeline.__dict__ + args = pipeline._pretrained_args + + new_pipeline.sparse_structure_sampler = getattr(samplers, args['sparse_structure_sampler']['name'])(**args['sparse_structure_sampler']['args']) + new_pipeline.sparse_structure_sampler_params = args['sparse_structure_sampler']['params'] + + new_pipeline.slat_sampler = getattr(samplers, args['slat_sampler']['name'])(**args['slat_sampler']['args']) + new_pipeline.slat_sampler_params = args['slat_sampler']['params'] + + new_pipeline.slat_normalization = args['slat_normalization'] + + new_pipeline._init_image_cond_model(args['image_cond_model']) + + return new_pipeline + + def _init_image_cond_model(self, name: str): + """ + Initialize the image conditioning model. + """ + try: + dinov2_model = torch.hub.load(os.path.join(torch.hub.get_dir(), 'facebookresearch_dinov2_main'), name, source='local',pretrained=True) + except: + dinov2_model = torch.hub.load('facebookresearch/dinov2', name, pretrained=True) + dinov2_model.eval() + self.models['image_cond_model'] = dinov2_model + transform = transforms.Compose([ + transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), + ]) + self.image_cond_model_transform = transform + + def preprocess_image(self, input: Image.Image, resolution=518, no_background=True) -> Image.Image: + """ + Preprocess the input image using BiRefNet for background removal. + Includes padding to maintain aspect ratio when resizing to 518x518. + """ + # if has alpha channel, use it directly + has_alpha = False + if input.mode == 'RGBA': + alpha = np.array(input)[:, :, -1] + if not np.all(alpha == 255): + has_alpha = True + + if has_alpha: + output = input + else: + input = input.convert('RGB') + max_size = max(input.size) + scale = min(1, 1024 / max_size) + if scale < 1: + input = input.resize((int(input.width * scale), int(input.height * scale)), Image.Resampling.LANCZOS) + + # Load BiRefNet model if not already loaded + if getattr(self, 'birefnet_model', None) is None: + self._lazy_load_birefnet() + + # Get mask using BiRefNet + mask = self._get_birefnet_mask(input) + + # Convert input to RGBA and apply mask + input_rgba = input.convert('RGBA') + input_array = np.array(input_rgba) + input_array[:, :, 3] = mask * 255 # Apply mask to alpha channel + output = Image.fromarray(input_array) + + # Process the output image + output_np = np.array(output) + alpha = output_np[:, :, 3] + + # Find bounding box of non-transparent pixels + bbox = np.argwhere(alpha > 0.8 * 255) + if len(bbox) == 0: # Handle case where no foreground is detected + return input.convert('RGB') + + bbox = np.min(bbox[:, 1]), np.min(bbox[:, 0]), np.max(bbox[:, 1]), np.max(bbox[:, 0]) + center = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2] + size = max(bbox[2] - bbox[0], bbox[3] - bbox[1]) + size = int(size * 1.2) + + # Calculate and apply crop bbox + if not no_background: + height, width = alpha.shape + if height > width: + center[0] = width / 2 + if center[1] < width / 2: + center[1] = width / 2 + elif center[1] > height - width / 2: + center[1] = height - width / 2 + else: + center[1] = height / 2 + if center[0] < height / 2: + center[0] = height / 2 + elif center[0] > width - height / 2: + center[0] = width - height / 2 + + size = min(center[0], center[1], input.width - center[0], input.height - center[1], size) * 2 + + bbox = ( + int(center[0] - size // 2), + int(center[1] - size // 2), + int(center[0] + size // 2), + int(center[1] + size // 2) + ) + + # Ensure bbox is within image bounds + bbox = ( + max(0, bbox[0]), + max(0, bbox[1]), + min(output.width, bbox[2]), + min(output.height, bbox[3]) + ) + + output = output.crop(bbox) + + # Add padding to maintain aspect ratio + width, height = output.size + if width > height: + new_height = width + padding = (width - height) // 2 + padded_output = Image.new('RGBA', (width, new_height), (0, 0, 0, 0)) + padded_output.paste(output, (0, padding)) + else: + new_width = height + padding = (height - width) // 2 + padded_output = Image.new('RGBA', (new_width, height), (0, 0, 0, 0)) + padded_output.paste(output, (padding, 0)) + + # Resize padded image to target size + # padded_output = padded_output.resize((resolution, resolution), Image.Resampling.LANCZOS) + padded_output = torch.from_numpy(np.array(padded_output).astype(np.float32)) / 255 + padded_output = F.interpolate(padded_output.unsqueeze(0).permute(0, 3, 1, 2), (resolution, resolution), mode='bilinear', align_corners=False)[0].permute(1, 2, 0) + + # Final processing + output = padded_output.cpu().numpy() + if no_background: + output = np.dstack(( + output[:, :, :3] * (output[:, :, 3:4] > 0.8), # RGB channels premultiplied by alpha + output[:, :, 3] # Original alpha channel + )) + output = Image.fromarray((output * 255).astype(np.uint8), mode='RGBA') + + return output + + def _lazy_load_birefnet(self): + """Lazy loading of the BiRefNet model""" + from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation, AutoModelForImageSegmentation + self.birefnet_model = AutoModelForImageSegmentation.from_pretrained( + 'ZhengPeng7/BiRefNet', + trust_remote_code=True + ).to(self.device) + self.birefnet_model.eval() + + def _get_birefnet_mask(self, image: Image.Image) -> np.ndarray: + """Get object mask using BiRefNet""" + image_size = (1024, 1024) + transform_image = transforms.Compose([ + transforms.Resize(image_size), + transforms.ToTensor(), + transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) + ]) + + input_images = transform_image(image).unsqueeze(0).to(self.device) + + with torch.no_grad(): + preds = self.birefnet_model(input_images)[-1].sigmoid().cpu() + + pred = preds[0].squeeze() + pred_pil = transforms.ToPILImage()(pred) + mask = pred_pil.resize(image.size) + mask_np = np.array(mask) + + return (mask_np > 128).astype(np.uint8) + + @torch.no_grad() + def encode_image(self, image: Union[torch.Tensor, list[Image.Image]], w_layernorm=True) -> torch.Tensor: + """ + Encode the image. + + Args: + image (Union[torch.Tensor, list[Image.Image]]): The image to encode + + Returns: + torch.Tensor: The encoded features. + """ + if isinstance(image, torch.Tensor): + assert image.ndim == 4, "Image tensor should be batched (B, C, H, W)" + image = F.interpolate(image, self.default_image_resolution, mode='bilinear', align_corners=False) + elif isinstance(image, list): + assert all(isinstance(i, Image.Image) for i in image), "Image list should be list of PIL images" + image = [i.resize((self.default_image_resolution, self.default_image_resolution), Image.LANCZOS) for i in image] + image = [np.array(i.convert('RGB')).astype(np.float32) / 255 for i in image] + image = [torch.from_numpy(i).permute(2, 0, 1).float() for i in image] + image = torch.stack(image).to(self.device) + else: + raise ValueError(f"Unsupported type of image: {type(image)}") + + image = self.image_cond_model_transform(image).to(self.device) + features = self.models['image_cond_model'](image, is_training=True)['x_prenorm'] + if w_layernorm: + features = F.layer_norm(features, features.shape[-1:]) + return features + + def get_cond(self, image: Union[torch.Tensor, list[Image.Image]]) -> dict: + """ + Get the conditioning information for the model. + + Args: + image (Union[torch.Tensor, list[Image.Image]]): The image prompts. + + Returns: + dict: The conditioning information + """ + cond = self.encode_image(image) + neg_cond = torch.zeros_like(cond) + return { + 'cond': cond, + 'neg_cond': neg_cond, + } + + def sample_sparse_structure( + self, + cond: dict, + num_samples: int = 1, + sampler_params: dict = {}, + ) -> torch.Tensor: + """ + Sample sparse structures with the given conditioning. + + Args: + cond (dict): The conditioning information. + num_samples (int): The number of samples to generate. + sampler_params (dict): Additional parameters for the sampler. + """ + # Sample occupancy latent + flow_model = self.models['sparse_structure_flow_model'] + reso = flow_model.resolution + noise = torch.randn(num_samples, flow_model.in_channels, reso, reso, reso).to(self.device) + sampler_params = {**self.sparse_structure_sampler_params, **sampler_params} + z_s = self.sparse_structure_sampler.sample( + flow_model, + noise, + **cond, + **sampler_params, + verbose=True + ).samples + + # Decode occupancy latent + decoder = self.models['sparse_structure_decoder'] + coords = torch.argwhere(decoder(z_s)>0)[:, [0, 2, 3, 4]].int() + + return coords + + def encode_slat( + self, + slat: sp.SparseTensor, + ): + ret = {} + slat = self.models['slat_encoder'](slat, sample_posterior=False) + ret['slat'] = slat + return ret + + @torch.no_grad() + def decode_slat( + self, + slat: sp.SparseTensor, + formats: List[str] = ['mesh', 'gaussian', 'radiance_field'], + ) -> dict: + """ + Decode the structured latent. + + Args: + slat (sp.SparseTensor): The structured latent. + formats (List[str]): The formats to decode the structured latent to. + + Returns: + dict: The decoded structured latent. + """ + ret = {} + ret['slat'] = slat + if 'gaussian' in formats: + ret['gaussian'] = self.models['slat_decoder_gs'](slat) + if 'mesh' in formats: + ret['mesh'] = self.models['slat_decoder_mesh'](slat) + if 'radiance_field' in formats: + ret['radiance_field'] = self.models['slat_decoder_rf'](slat) + return ret + + def sample_slat( + self, + cond: dict, + coords: torch.Tensor, + sampler_params: dict = {}, + ) -> sp.SparseTensor: + """ + Sample structured latent with the given conditioning. + + Args: + cond (dict): The conditioning information. + coords (torch.Tensor): The coordinates of the sparse structure. + sampler_params (dict): Additional parameters for the sampler. + """ + # Sample structured latent + flow_model = self.models['slat_flow_model'] + noise = sp.SparseTensor( + feats=torch.randn(coords.shape[0], flow_model.in_channels).to(self.device), + coords=coords, + ) + sampler_params = {**self.slat_sampler_params, **sampler_params} + slat = self.slat_sampler.sample( + flow_model, + noise, + **cond, + **sampler_params, + verbose=True + ).samples + + std = torch.tensor(self.slat_normalization['std'])[None].to(slat.device) + mean = torch.tensor(self.slat_normalization['mean'])[None].to(slat.device) + slat = slat * std + mean + + return slat + + def get_input(self, batch_data): + std = torch.tensor(self.slat_normalization['std'])[None].to(self.device) + mean = torch.tensor(self.slat_normalization['mean'])[None].to(self.device) + + images = batch_data['source_image'] + cond = self.encode_image(images) + if random.random() > 0.5: + cond = torch.zeros_like(cond) + + target_feats = batch_data['target_feats'] + target_coords = batch_data['target_coords'] + targets = sp.SparseTensor(target_feats, target_coords).to(self.device) + targets = (targets - mean) / std + + noise = sp.SparseTensor( + feats=torch.randn_like(target_feats).to(self.device), + coords=target_coords.to(self.device), + ) + return targets, cond, noise + + @torch.no_grad() + def batch_run(self, + images: torch.Tensor, + coords: torch.Tensor, + feats: torch.Tensor = None, + ref_images: torch.Tensor = None, + seed: int = 42, + slat_sampler_params: dict = {}, + formats: List[str] = [], + ) -> Dict[str, Any]: + # Get image conditioning + + flow_model = self.models['slat_flow_model'] + torch.manual_seed(seed) + + if ref_images is not None: + cond = { + 'cond': self.encode_image(images), + 'neg_cond': self.encode_image(ref_images), + } + else: + cond = self.get_cond(images) + + # Process input data + if feats is not None: + init_slat = sp.SparseTensor(feats, coords).to(self.device) + std = torch.tensor(self.slat_normalization['std'])[None].to(init_slat.device) + mean = torch.tensor(self.slat_normalization['mean'])[None].to(init_slat.device) + init_slat = (init_slat - mean) / std + noise = sp.SparseTensor( + feats=torch.randn(coords.shape[0], flow_model.in_channels).to(self.device), + coords=coords, + ) + noise = self.slat_sampler._xstart_to_x_t(init_slat, 1, noise) + else: + noise = sp.SparseTensor( + feats=torch.randn(coords.shape[0], flow_model.in_channels).to(self.device), + coords=coords.to(self.device), + ) + + # Sample structured latent + slat_sampler_params = {**self.slat_sampler_params, **slat_sampler_params} + slat = self.slat_sampler.sample( + flow_model, + noise, + **cond, + **slat_sampler_params, + verbose=False + ).samples + + std = torch.tensor(self.slat_normalization['std'])[None].to(slat.device) + mean = torch.tensor(self.slat_normalization['mean'])[None].to(slat.device) + slat = slat * std + mean + return self.decode_slat(slat, formats) + + def forward(self, x: torch.Tensor, t: torch.Tensor, cond: torch.Tensor) -> torch.Tensor: + return self.slat_flow_model(x, t, cond) + + @contextmanager + def inject_sampler_multi_image( + self, + sampler_name: str, + num_images: int, + num_steps: int, + mode: Literal['stochastic', 'multidiffusion'] = 'stochastic', + ): + """ + Inject a sampler with multiple images as condition. + + Args: + sampler_name (str): The name of the sampler to inject. + num_images (int): The number of images to condition on. + num_steps (int): The number of steps to run the sampler for. + """ + sampler = getattr(self, sampler_name) + setattr(sampler, f'_old_inference_model', sampler._inference_model) + + if mode == 'stochastic': + if num_images > num_steps: + print(f"\033[93mWarning: number of conditioning images is greater than number of steps for {sampler_name}. " + "This may lead to performance degradation.\033[0m") + + cond_indices = (np.arange(num_steps) % num_images).tolist() + def _new_inference_model(self, model, x_t, t, cond, **kwargs): + cond_idx = cond_indices.pop(0) + cond_i = cond[cond_idx:cond_idx+1] + return self._old_inference_model(model, x_t, t, cond=cond_i, **kwargs) + + elif mode =='multidiffusion': + from .samplers import FlowEulerSampler + def _new_inference_model(self, model, x_t, t, cond, neg_cond, cfg_strength, cfg_interval, **kwargs): + if cfg_interval[0] <= t <= cfg_interval[1]: + preds = [] + for i in range(len(cond)): + preds.append(FlowEulerSampler._inference_model(self, model, x_t, t, cond[i:i+1], **kwargs)) + pred = sum(preds) / len(preds) + neg_pred = FlowEulerSampler._inference_model(self, model, x_t, t, neg_cond, **kwargs) + return (1 + cfg_strength) * pred - cfg_strength * neg_pred + else: + preds = [] + for i in range(len(cond)): + preds.append(FlowEulerSampler._inference_model(self, model, x_t, t, cond[i:i+1], **kwargs)) + pred = sum(preds) / len(preds) + return pred + + else: + raise ValueError(f"Unsupported mode: {mode}") + + sampler._inference_model = _new_inference_model.__get__(sampler, type(sampler)) + + yield + + sampler._inference_model = sampler._old_inference_model + delattr(sampler, f'_old_inference_model') + + @torch.no_grad() + def run( + self, + image: Image.Image, + ref_image: Image.Image = None, + num_samples: int = 1, + seed: int = 42, + sparse_structure_sampler_params: dict = {}, + slat_sampler_params: dict = {}, + formats: List[str] = ['mesh'], + preprocess_image: bool = True, + init_mesh: trimesh.Trimesh = None, + coords: torch.Tensor = None, + normalize_init_mesh: bool = False, + init_resolution: int = 62, + init_stride: int = 4 + ) -> dict: + """ + Run the pipeline. + + Args: + image (Image.Image): The image prompt. + num_samples (int): The number of samples to generate. + sparse_structure_sampler_params (dict): Additional parameters for the sparse structure sampler. + slat_sampler_params (dict): Additional parameters for the structured latent sampler. + preprocess_image (bool): Whether to preprocess the image. + """ + if preprocess_image: + image = self.preprocess_image(image) + if ref_image is not None: + cond = self.encode_image([image, ref_image]) + neg_cond = torch.zeros_like(cond[0:1]) + sparse_cond = slat_cond = { + 'cond': 0.5 * cond[0:1] + 0.5 * cond[1:2], + 'neg_cond': neg_cond, + } + else: + sparse_cond = slat_cond = self.get_cond([image]) + + torch.manual_seed(seed) + if init_mesh is not None: + mesh_o3d = o3d.geometry.TriangleMesh() + mesh_o3d.vertices = o3d.utility.Vector3dVector(init_mesh.vertices) + mesh_o3d.triangles = o3d.utility.Vector3iVector(init_mesh.faces) + if normalize_init_mesh: + vertices = np.asarray(mesh_o3d.vertices) + init_mesh = normalize_trimesh(init_mesh) + center = (vertices.max(axis=0) + vertices.min(axis=0)) / 2 + vertices = vertices - center + diag = np.linalg.norm(vertices.max(axis=0) - vertices.min(axis=0)) + vertices = vertices / diag + mesh_o3d.vertices = o3d.utility.Vector3dVector(vertices) + + vertices = np.clip(np.asarray(mesh_o3d.vertices), -0.5 + 1e-6, 0.5 - 1e-6) + mesh_o3d.vertices = o3d.utility.Vector3dVector(vertices) + + voxel_grid = o3d.geometry.VoxelGrid.create_from_triangle_mesh_within_bounds( + mesh_o3d, + voxel_size=1/64, + min_bound=(-0.5, -0.5, -0.5), + max_bound=(0.5, 0.5, 0.5) + ) + + voxel_indices = np.array([voxel.grid_index for voxel in voxel_grid.get_voxels()]) + coords = torch.cat([torch.zeros(len(voxel_indices), 1), torch.tensor(voxel_indices)], dim=1).int().to(self.device) + elif coords is not None: + coords = coords + else: + coords = self.sample_sparse_structure(sparse_cond, num_samples, sparse_structure_sampler_params) + slat = self.sample_slat(slat_cond, coords, slat_sampler_params) + return self.decode_slat(slat, formats) + + def configure_optimizers(self): + params = list(self.slat_flow_model.parameters()) + opt = torch.optim.AdamW(params, lr=1e-4, weight_decay=0.0) + return opt + +def zero_module(module): + """ + Zero out the parameters of a module and return it. + """ + for p in module.parameters(): + p.detach().zero_() + return module + +class TrellisVGGTLORATo3DPipeline(TrellisImageTo3DPipeline): + + def get_input(self, batch_data): + + std = torch.tensor(self.slat_normalization['std'])[None].to(self.device) + mean = torch.tensor(self.slat_normalization['mean'])[None].to(self.device) + + images = batch_data['ref_image'].to(self.VGGT_dtype) + b,n,c,h,w = images.shape + n = random.randint(1, n) + images = images[:,:n] + images = F.interpolate(images.reshape(b*n,c,h,w), 518, mode='bilinear') + coords = F.interpolate(batch_data['source_image'][:,:n].to(self.VGGT_dtype).reshape(b*n,3,h,w), 518, mode='nearest') + h, w = images.shape[-2:] + images = images.reshape(b,n,c,h,w) + coords = coords.reshape(b,n,3,h,w) + mask = ((coords.permute(0,1,3,4,2)[...,0] == 127/255) & (coords.permute(0,1,3,4,2)[...,1] == 127/255) & (coords.permute(0,1,3,4,2)[...,2] == 127/255)) + mask = ~mask + + with torch.no_grad(): + with torch.cuda.amp.autocast(dtype=self.VGGT_dtype): + # Predict attributes including cameras, depth maps, and point maps. + aggregated_tokens_list, ps_idx = self.VGGT_model.aggregator(images) + + image_cond = self.encode_image(images.reshape(b*n,c,h,w)).reshape(b, n, -1, 1024)[:, :, 5:] + cond = self.multiview_cond_3d(aggregated_tokens_list, image_cond) + if random.random() < 0.3: + cond = torch.zeros_like(cond) + + target_feats = batch_data['target_feats'] + target_coords = batch_data['target_coords'] + targets = sp.SparseTensor(target_feats, target_coords).to(self.device) + targets = (targets - mean) / std + + noise = sp.SparseTensor( + feats=torch.randn_like(target_feats).to(self.device), + coords=target_coords.to(self.device), + ) + return targets, cond, noise + + def get_ss_cond(self, image_cond: torch.Tensor, aggregated_tokens_list: List, num_samples: int) -> dict: + """ + Get the conditioning information for the model. + + Args: + image (Union[torch.Tensor, list[Image.Image]]): The image prompts. + + Returns: + dict: The conditioning information + """ + cond = self.multiview_cond(aggregated_tokens_list, image_cond) + neg_cond = torch.zeros_like(cond) + return { + 'cond': cond, + 'neg_cond': neg_cond, + } + + def get_cond(self, image_cond: torch.Tensor, aggregated_tokens_list: List, num_samples: int, data_type=torch.float32) -> dict: + """ + Get the conditioning information for the model. + + Args: + image (Union[torch.Tensor, list[Image.Image]]): The image prompts. + + Returns: + dict: The conditioning information + """ + cond = self.multiview_cond_3d(aggregated_tokens_list, image_cond) + neg_cond = torch.zeros_like(cond) + return { + 'cond': cond, + 'neg_cond': neg_cond, + } + + @torch.no_grad() + def vggt_feat(self, image: Union[torch.Tensor, list[Image.Image]]) -> List: + """ + Encode the image. + + Args: + image (Union[torch.Tensor, list[Image.Image]]): The image to encode + + Returns: + torch.Tensor: The encoded features. + """ + if isinstance(image, torch.Tensor): + assert image.ndim == 4, "Image tensor should be batched (B, C, H, W)" + image = F.interpolate(image, self.default_image_resolution, mode='bilinear', align_corners=False) + elif isinstance(image, list): + assert all(isinstance(i, Image.Image) for i in image), "Image list should be list of PIL images" + image = [i.resize((self.default_image_resolution, self.default_image_resolution), Image.LANCZOS) for i in image] + image = [np.array(i.convert('RGB')).astype(np.float32) / 255 for i in image] + image = [torch.from_numpy(i).permute(2, 0, 1).float() for i in image] + image = torch.stack(image).to(self.device) + else: + raise ValueError(f"Unsupported type of image: {type(image)}") + + with torch.no_grad(): + with torch.cuda.amp.autocast(dtype=self.VGGT_dtype): + # Predict attributes including cameras, depth maps, and point maps. + aggregated_tokens_list, _ = self.VGGT_model.aggregator(image[None]) + + return aggregated_tokens_list + + def whole_run( + self, + image: Union[torch.Tensor, list[Image.Image]], + coords: torch.Tensor = None, + num_samples: int = 1, + seed: int = 42, + sparse_structure_sampler_params: dict = {}, + slat_sampler_params: dict = {}, + formats: List[str] = ['mesh'], + preprocess_image: bool = True, + mode: Literal['stochastic', 'multidiffusion'] = 'stochastic', + ) -> sp.SparseTensor: + + aggregated_tokens_list = self.vggt_feat(image) + b, n, _, _ = aggregated_tokens_list[0].shape + image_cond = self.encode_image(image).reshape(b, n, -1, 1024) + if coords is None: + ss_flow_model = self.models['sparse_structure_flow_model'] + ss_cond = self.get_ss_cond(image_cond[:, :, 5:], aggregated_tokens_list, num_samples) + # Sample structured latent + ss_sampler_params = {**self.sparse_structure_sampler_params, **sparse_structure_sampler_params} + reso = ss_flow_model.resolution + ss_noise = torch.randn(num_samples, ss_flow_model.in_channels, reso, reso, reso).to(self.device) + ss_slat = self.sparse_structure_sampler.sample( + ss_flow_model, + ss_noise, + **ss_cond, + **ss_sampler_params, + verbose=True + ).samples + + decoder = self.models['sparse_structure_decoder'] + coords = torch.argwhere(decoder(ss_slat)>0)[:, [0, 2, 3, 4]].int() + + import torchvision + for i, img in enumerate(image): + if isinstance(img, Image.Image): + img.save('tmp_{i}.png'.format(i=i)) + else: + torchvision.utils.save_image(img, 'tmp_{i}.png'.format(i=i)) + + import open3d as o3d + pcd = o3d.geometry.PointCloud() + pcd.points = o3d.utility.Vector3dVector(coords[:,1:].cpu().numpy()) + o3d.io.write_point_cloud('tmp.ply', pcd) + + + cond = { + 'cond': image_cond.reshape(n, -1, 1024), + 'neg_cond': torch.zeros_like(image_cond.reshape(n, -1, 1024))[:1], + } + + slat_steps = {**self.slat_sampler_params, **slat_sampler_params}.get('steps') + with self.inject_sampler_multi_image('slat_sampler', len(image), slat_steps, mode=mode): + slat = self.sample_slat(cond, coords, slat_sampler_params) + return self.decode_slat(slat, formats) + + @staticmethod + def from_pretrained(path: str, whole_pipeline: bool=False, resume_path=None) -> "TrellisVGGTLORATo3DPipeline": + """ + Load a pretrained model. + + Args: + path (str): The path to the model. Can be either local path or a Hugging Face repository. + """ + pipeline = super(TrellisImageTo3DPipeline, TrellisImageTo3DPipeline).from_pretrained(path) + new_pipeline = TrellisVGGTLORATo3DPipeline() + new_pipeline.__dict__ = pipeline.__dict__ + args = pipeline._pretrained_args + + new_pipeline.multiview_cond_3d = ModulatedMultiViewCond( + 1024, + 3072, + num_heads=16, + mlp_ratio=4, + attn_mode='full', + use_checkpoint=False, + use_rope=False, + share_mod=False, + qk_rms_norm=True, + qk_rms_norm_cross=False, + ).to(new_pipeline.device) + + if not whole_pipeline: + for key in ['sparse_structure_flow_model', 'slat_encoder', 'slat_decoder_gs', 'slat_decoder_mesh', 'slat_decoder_rf']: + if key in new_pipeline.models: + del new_pipeline.models[key] + + if hasattr(new_pipeline, 'sparse_structure_flow_model'): + del new_pipeline.sparse_structure_flow_model + + if resume_path is not None: + states = torch.load(resume_path) + if 'state_dict' in states: + states = states['state_dict'] + new_pipeline.models['slat_flow_model'].load_state_dict({k.replace(f"slat_flow_model.", ""): v for k, v in states.items()}, False) + new_pipeline.multiview_cond_3d.load_state_dict({k.replace(f"multiview_cond_3d.", ""): v for k, v in states.items()}, False) + + else: + new_pipeline.multiview_cond = ModulatedMultiViewCond( + 1024, + 3072, + num_heads=16, + mlp_ratio=4, + attn_mode='full', + use_checkpoint=False, + use_rope=False, + share_mod=False, + qk_rms_norm=True, + qk_rms_norm_cross=False, + ).to(new_pipeline.device) + new_pipeline.models['ss_encoder'] = models.from_pretrained("weights/TRELLIS-image-large/ckpts/ss_enc_conv3d_16l8_fp16") + new_pipeline.models['ss_encoder'].eval() + + new_pipeline.VGGT_dtype = torch.float32 + VGGT_model = VGGT() + VGGT_model_weight = torch.load("weights/VGGT_weight/model.pt") + VGGT_model.load_state_dict(VGGT_model_weight) + new_pipeline.VGGT_model = VGGT_model.to(new_pipeline.device) + del new_pipeline.VGGT_model.depth_head + del new_pipeline.VGGT_model.point_head + del new_pipeline.VGGT_model.track_head + del new_pipeline.VGGT_model.camera_head + new_pipeline.VGGT_model.eval() + + new_pipeline.sparse_structure_sampler = getattr(samplers, args['sparse_structure_sampler']['name'])(**args['sparse_structure_sampler']['args']) + new_pipeline.sparse_structure_sampler_params = args['sparse_structure_sampler']['params'] + + new_pipeline.slat_sampler = getattr(samplers, args['slat_sampler']['name'])(**args['slat_sampler']['args']) + new_pipeline.slat_sampler_params = args['slat_sampler']['params'] + + new_pipeline.slat_normalization = args['slat_normalization'] + + new_pipeline._init_image_cond_model(args['image_cond_model']) + + # new_pipeline.max_num_points = 6000 + + return new_pipeline + + def configure_optimizers(self): + trellis_lora_params = [p for p in self.slat_flow_model.parameters() if p.requires_grad] + params = list(self.multiview_cond_3d.parameters()) + trellis_lora_params + opt = torch.optim.AdamW(params, lr=1e-4, weight_decay=0.0) + return opt diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/trellis_image_to_ss.py b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/trellis_image_to_ss.py new file mode 100644 index 0000000000000000000000000000000000000000..a8db8ad9505675a5d9f447bb4ecd5f892d6ddb09 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/pipelines/trellis_image_to_ss.py @@ -0,0 +1,344 @@ +from typing import * +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from tqdm import tqdm +from easydict import EasyDict as edict +from torchvision import transforms +from PIL import Image +import trimesh +import os +from scipy.spatial import cKDTree +import pytorch_lightning as pl +import random +import open3d as o3d +import utils3d +from trellis.modules.sparse.attention import SparseMultiHeadAttention +from trellis.models.structured_latent_flow import SparseResBlock3d +import trellis.modules.sparse as sp +from .trellis_image_to_3d import * +from scipy.ndimage import binary_dilation +from .base import Pipeline +from . import samplers +from ..modules import sparse as sp +from trellis.models.sparse_structure_vae import * +from ..modules.spatial import patchify, unpatchify +from easydict import EasyDict as edict +import trellis.models as models +from trellis.modules.transformer import ModulatedPosedTransformerBlock + +# import sys +# sys.path.append("wheels/vggt") +# from wheels.vggt.vggt.models.vggt import VGGT +# from wheels.vggt.vggt.utils.pose_enc import pose_encoding_to_extri_intri, quat_to_mat, mat_to_quat +# from wheels.vggt.vggt.utils.geometry import depth_to_world_coords_points_tensor +# from trellis.modules.transformer import ModulatedMultiViewCond + +def get_opencv_from_blender(matrix_world, fov, image_size): + # convert matrix_world to opencv format extrinsics + opencv_world_to_cam = matrix_world.inverse() + opencv_world_to_cam[:, 1, :] *= -1 + opencv_world_to_cam[:, 2, :] *= -1 + R, T = opencv_world_to_cam[:, :3, :3], opencv_world_to_cam[:, :3, 3] + R, T = R, T + + # convert fov to opencv format intrinsics + opencv_cam_matrix = torch.diag(torch.tensor([1, 1, 1])).unsqueeze(0).float().repeat(fov.shape[0], 1, 1).to(fov.device) + focal = 1 / torch.tan(fov / 2) + opencv_cam_matrix[:, :2, :2] *= focal[:,None,None] + opencv_cam_matrix[:, :2, -1] += torch.tensor([image_size / 2, image_size / 2]).to(fov.device)[None] + opencv_cam_matrix[:, :2, :2] *= image_size / 2 + + return R, T, opencv_cam_matrix + +class TrellisImageToSSPipeline(TrellisImageTo3DPipeline): + """ + Pipeline for generating sparse structures from images using Trellis. + Inherits from TrellisImageTo3DPipeline but focuses only on sparse structure generation. + """ + + @staticmethod + def from_pretrained(path: str) -> "TrellisImageToSSPipeline": + """ + Load a pretrained model. + + Args: + path (str): The path to the model. Can be either local path or a Hugging Face repository. + """ + pipeline = super(TrellisImageToSSPipeline, TrellisImageToSSPipeline).from_pretrained(path) + new_pipeline = TrellisImageToSSPipeline() + new_pipeline.__dict__ = pipeline.__dict__ + args = pipeline._pretrained_args + + # Initialize the sparse structure sampler + new_pipeline.sparse_structure_sampler = getattr(samplers, args['sparse_structure_sampler']['name'])(**args['sparse_structure_sampler']['args']) + new_pipeline.sparse_structure_sampler_params = args['sparse_structure_sampler']['params'] + + # Remove unnecessary models and components since we only need sparse structure + for key in ['slat_flow_model', 'slat_encoder', 'slat_decoder_gs', 'slat_decoder_mesh', 'slat_decoder_rf']: + if key in new_pipeline.models: + del new_pipeline.models[key] + + if hasattr(new_pipeline, 'slat_flow_model'): + del new_pipeline.slat_flow_model + if hasattr(new_pipeline, 'slat_sampler'): + del new_pipeline.slat_sampler + if hasattr(new_pipeline, 'slat_sampler_params'): + del new_pipeline.slat_sampler_params + if hasattr(new_pipeline, 'slat_normalization'): + del new_pipeline.slat_normalization + + # Initialize image conditioning model + new_pipeline._init_image_cond_model(args['image_cond_model']) + + return new_pipeline + + def get_input(self, batch_data): + """ + Process input batch data for training. + + Args: + batch_data (dict): Batch data containing images and targets + + Returns: + tuple: Processed targets, conditioning, and noise + """ + images = batch_data['source_image'] + cond = self.encode_image(images) + + # Randomly zero out conditioning during training for robustness + if random.random() > 0.5: + cond = torch.zeros_like(cond) + + targets = batch_data['target_ss_latents'].to(self.device) + noise = torch.randn_like(targets).to(self.device) + + return targets, cond, noise + + def run( + self, + image: Image.Image, + num_samples: int = 1, + seed: int = 42, + sparse_structure_sampler_params: dict = {}, + preprocess_image: bool = True, + ) -> torch.Tensor: + """ + Generate sparse structure from an input image. + + Args: + image (Image.Image): Input image + num_samples (int): Number of samples to generate + seed (int): Random seed + sparse_structure_sampler_params (dict): Additional sampler parameters + preprocess_image (bool): Whether to preprocess the input image + + Returns: + torch.Tensor: Generated sparse structure coordinates + """ + if preprocess_image: + image = self.preprocess_image(image) + + # Get image conditioning + cond = self.get_cond([image]) + + # Sample sparse structure + flow_model = self.models['sparse_structure_flow_model'] + reso = flow_model.resolution + torch.manual_seed(seed) + noise = torch.randn(num_samples, flow_model.in_channels, reso, reso, reso).to(self.device) + + # Merge default and custom sampler parameters + sampler_params = {**self.sparse_structure_sampler_params, **sparse_structure_sampler_params} + + # Generate occupancy latent + z_s = self.sparse_structure_sampler.sample( + flow_model, + noise, + **cond, + **sampler_params, + verbose=True + ).samples + + # Decode occupancy latent to get coordinates + decoder = self.models['sparse_structure_decoder'] + coords = torch.argwhere(decoder(z_s) > 0)[:, [0, 2, 3, 4]].int() + + return coords + + def forward(self, x: torch.Tensor, t: torch.Tensor, cond: torch.Tensor) -> torch.Tensor: + """ + Forward pass for the sparse structure flow model. + + Args: + x (torch.Tensor): Input tensor + t (torch.Tensor): Time step + cond (torch.Tensor): Conditioning tensor + + Returns: + torch.Tensor: Model output + """ + return self.sparse_structure_flow_model(x, t, cond) + + def configure_optimizers(self): + """ + Configure the optimizer for training. + + Returns: + torch.optim.Optimizer: Configured optimizer + """ + params = list(self.sparse_structure_flow_model.parameters()) + # return torch.optim.AdamW(params, lr=1e-4, weight_decay=0.0) + return torch.optim.AdamW(params, lr=1e-5, weight_decay=0.0) + + def p_losses(self, x_0, cond, t, noise): + """ + Calculate training losses. + + Args: + x_0 (torch.Tensor): Ground truth tensor + cond (torch.Tensor): Conditioning tensor + t (float): Time step + noise (torch.Tensor): Noise tensor + + Returns: + tuple: Loss value and loss dictionary + """ + x_t, gt_v = self.sparse_structure_sampler._get_model_gt(x_0, t, noise) + + t = torch.tensor([1000 * t] * x_t.shape[0], device=x_t.device, dtype=torch.float32) + pred_v = self(x_t, t, cond) + + loss_dict = {} + prefix = 'train' if self.training else 'val' + loss_simple = F.mse_loss(pred_v, gt_v) + # Ignore NaN losses + valid_loss_simple = loss_simple[~torch.isnan(loss_simple)] + loss_dict.update({f'{prefix}/loss_simple': valid_loss_simple.mean()}) + loss = valid_loss_simple.mean() + + return loss, loss_dict + + def mse_loss(self, pred, target): + diff = pred - target + return diff ** 2 + +class TrellisVGGTLORAToSSPipeline(TrellisImageToSSPipeline): + + def get_input(self, batch_data): + + images = batch_data['ref_image'].to(self.VGGT_dtype) + b,n,c,h,w = images.shape + n = random.randint(1, n) + images = images[:,:n] + images = F.interpolate(images.reshape(b*n,c,h,w), 518, mode='bilinear') + coords = F.interpolate(batch_data['source_image'][:,:n].to(self.VGGT_dtype).reshape(b*n,3,h,w), 518, mode='nearest') + h, w = images.shape[-2:] + images = images.reshape(b,n,c,h,w) + coords = coords.reshape(b,n,3,h,w) + mask = ((coords.permute(0,1,3,4,2)[...,0] == 127/255) & (coords.permute(0,1,3,4,2)[...,1] == 127/255) & (coords.permute(0,1,3,4,2)[...,2] == 127/255)) + mask = ~mask + + aggregated_tokens_list, ps_idx = self.VGGT_model.aggregator(images) + + image_cond = self.encode_image(images.reshape(b*n,c,h,w)).reshape(b, n, -1, 1024)[:, :, 5:] + cond = self.multiview_cond(aggregated_tokens_list, image_cond) + if random.random() < 0.1: + cond = torch.zeros_like(cond) + + ss_encoder = self.models['ss_encoder'] + ss_encoder.eval() + target_coords = batch_data['target_coords'].to(self.device) + voxel_resolution = 64 + + with torch.no_grad(): + ss = torch.zeros(b, voxel_resolution, voxel_resolution, voxel_resolution, dtype=torch.long, device=self.device) + ss.index_put_((target_coords[:,0], target_coords[:,1], target_coords[:,2], target_coords[:,3]), torch.tensor(1, dtype=ss.dtype, device=ss.device)) + ss = ss.unsqueeze(1).float() + targets = ss_encoder(ss.to(ss_encoder.dtype), sample_posterior=False).to(self.VGGT_dtype) + + # targets = batch_data['target_ss_latents'].to(self.device) + noise = torch.randn_like(targets).to(self.VGGT_dtype).to(self.device) + + # return targets, cond, noise, pose_enc_gt, pose_enc + return targets, cond, noise + + @staticmethod + def from_pretrained(path: str, training=True, resume_path=None) -> "TrellisVGGTLORAToSSPipeline": + """ + Load a pretrained model. + + Args: + path (str): The path to the model. Can be either local path or a Hugging Face repository. + """ + pipeline = super(TrellisImageTo3DPipeline, TrellisImageTo3DPipeline).from_pretrained(path) + new_pipeline = TrellisVGGTLORAToSSPipeline() + new_pipeline.__dict__ = pipeline.__dict__ + args = pipeline._pretrained_args + + new_pipeline.multiview_cond = ModulatedMultiViewCond( + 1024, + 3072, + num_heads=16, + mlp_ratio=4, + attn_mode='full', + use_checkpoint=False, + use_rope=False, + share_mod=False, + qk_rms_norm=True, + qk_rms_norm_cross=False, + ).to(new_pipeline.device) + if training: + # Remove unnecessary models and components since we only need sparse structure + for key in ['slat_flow_model', 'slat_encoder', 'slat_decoder_gs', 'slat_decoder_mesh', 'slat_decoder_rf']: + if key in new_pipeline.models: + del new_pipeline.models[key] + + if hasattr(new_pipeline, 'slat_flow_model'): + del new_pipeline.slat_flow_model + if hasattr(new_pipeline, 'slat_sampler'): + del new_pipeline.slat_sampler + if hasattr(new_pipeline, 'slat_sampler_params'): + del new_pipeline.slat_sampler_params + if hasattr(new_pipeline, 'slat_normalization'): + del new_pipeline.slat_normalization + + if resume_path is not None: + states = torch.load(resume_path) + if 'state_dict' in states: + states = states['state_dict'] + new_pipeline.models['sparse_structure_flow_model'].load_state_dict({k.replace(f"sparse_structure_flow_model.", ""): v for k, v in states.items()}, False) + new_pipeline.multiview_cond.load_state_dict({k.replace(f"multiview_cond.", ""): v for k, v in states.items()}, False) + + new_pipeline.VGGT_dtype = torch.float32 + VGGT_model = VGGT() + VGGT_model_weight = torch.load("weights/VGGT_weight/model.pt") + VGGT_model.load_state_dict(VGGT_model_weight) + new_pipeline.VGGT_model = VGGT_model.to(new_pipeline.device) + del new_pipeline.VGGT_model.depth_head + del new_pipeline.VGGT_model.point_head + del new_pipeline.VGGT_model.track_head + del new_pipeline.VGGT_model.camera_head + new_pipeline.VGGT_model.eval() + + new_pipeline.models['ss_encoder'] = models.from_pretrained("weights/TRELLIS-image-large/ckpts/ss_enc_conv3d_16l8_fp16") + new_pipeline.models['ss_encoder'].eval() + new_pipeline.sparse_structure_sampler = getattr(samplers, args['sparse_structure_sampler']['name'])(**args['sparse_structure_sampler']['args']) + new_pipeline.sparse_structure_sampler_params = args['sparse_structure_sampler']['params'] + + new_pipeline.slat_sampler = getattr(samplers, args['slat_sampler']['name'])(**args['slat_sampler']['args']) + new_pipeline.slat_sampler_params = args['slat_sampler']['params'] + + new_pipeline.slat_normalization = args['slat_normalization'] + + new_pipeline._init_image_cond_model(args['image_cond_model']) + + return new_pipeline + + def configure_optimizers(self): + vggt_lora_params = [p for p in self.VGGT_model.aggregator.parameters() if p.requires_grad] + trellis_lora_params = [p for p in self.sparse_structure_flow_model.parameters() if p.requires_grad] + params = list(self.multiview_cond.parameters()) + trellis_lora_params + vggt_lora_params + opt = FusedAdam(params, 1e-4) + return opt \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/renderers/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/renderers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..72f1616ed82a2ba281eb518714d66555a13b8a0f --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/renderers/__init__.py @@ -0,0 +1,33 @@ +import importlib + +__attributes = { + 'GSplatRenderer': 'gsplat_renderer', + 'GaussianRenderer': 'gaussian_render', + 'MeshRenderer': 'mesh_renderer', + 'OctreeRenderer': 'octree_renderer' +} + +__submodules = [] + +__all__ = list(__attributes.keys()) + __submodules + +def __getattr__(name): + if name not in globals(): + if name in __attributes: + module_name = __attributes[name] + module = importlib.import_module(f".{module_name}", __name__) + globals()[name] = getattr(module, name) + elif name in __submodules: + module = importlib.import_module(f".{name}", __name__) + globals()[name] = module + else: + raise AttributeError(f"module {__name__} has no attribute {name}") + return globals()[name] + + +# For Pylance +if __name__ == '__main__': + from .mesh_renderer import MeshRenderer + from .gsplat_renderer import GSplatRenderer + from .gaussian_render import GaussianRenderer + from .octree_renderer import OctreeRenderer \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/renderers/gaussian_render.py b/OVOW/engine/oneposeviagen/trellis/trellis/renderers/gaussian_render.py new file mode 100644 index 0000000000000000000000000000000000000000..108c6af051bc4aeb159e7afdd59b163d3ff99667 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/renderers/gaussian_render.py @@ -0,0 +1,240 @@ +# +# Copyright (C) 2023, Inria +# GRAPHDECO research group, https://team.inria.fr/graphdeco +# All rights reserved. +# +# This software is free for non-commercial, research and evaluation use +# under the terms of the LICENSE.md file. +# +# For inquiries contact george.drettakis@inria.fr +# + +import torch +import math +from easydict import EasyDict as edict +import numpy as np +from ..representations.gaussian import Gaussian +import torch.nn.functional as F +from easydict import EasyDict as edict + + +def intrinsics_to_projection( + intrinsics: torch.Tensor, + near: float, + far: float, + ) -> torch.Tensor: + """ + OpenCV intrinsics to OpenGL perspective matrix + + Args: + intrinsics (torch.Tensor): [3, 3] OpenCV intrinsics matrix + near (float): near plane to clip + far (float): far plane to clip + Returns: + (torch.Tensor): [4, 4] OpenGL perspective matrix + """ + fx, fy = intrinsics[0, 0], intrinsics[1, 1] + cx, cy = intrinsics[0, 2], intrinsics[1, 2] + ret = torch.zeros((4, 4), dtype=intrinsics.dtype, device=intrinsics.device) + ret[0, 0] = 2 * fx + ret[1, 1] = 2 * fy + ret[0, 2] = 2 * cx - 1 + ret[1, 2] = - 2 * cy + 1 + ret[2, 2] = far / (far - near) + ret[2, 3] = near * far / (near - far) + ret[3, 2] = 1. + return ret + + +def render(viewpoint_camera, pc : Gaussian, pipe, bg_color : torch.Tensor, scaling_modifier = 1.0, override_color = None, need_depth = False): + """ + Render the scene. + + Background tensor (bg_color) must be on GPU! + """ + # lazy import + if 'GaussianRasterizer' not in globals(): + from diff_gaussian_rasterization import GaussianRasterizer, GaussianRasterizationSettings + + # Create zero tensor. We will use it to make pytorch return gradients of the 2D (screen-space) means + screenspace_points = torch.zeros_like(pc.get_xyz, dtype=pc.get_xyz.dtype, requires_grad=True, device="cuda") + 0 + try: + screenspace_points.retain_grad() + except: + pass + # Set up rasterization configuration + tanfovx = math.tan(viewpoint_camera.FoVx * 0.5) + tanfovy = math.tan(viewpoint_camera.FoVy * 0.5) + + kernel_size = pipe.kernel_size + subpixel_offset = torch.zeros((int(viewpoint_camera.image_height), int(viewpoint_camera.image_width), 2), dtype=torch.float32, device="cuda") + + raster_settings = GaussianRasterizationSettings( + image_height=int(viewpoint_camera.image_height), + image_width=int(viewpoint_camera.image_width), + tanfovx=tanfovx, + tanfovy=tanfovy, + kernel_size=kernel_size, + subpixel_offset=subpixel_offset, + bg=bg_color, + scale_modifier=scaling_modifier, + viewmatrix=viewpoint_camera.world_view_transform, + projmatrix=viewpoint_camera.full_proj_transform, + sh_degree=pc.active_sh_degree, + campos=viewpoint_camera.camera_center, + prefiltered=False, + debug=pipe.debug + ) + + rasterizer = GaussianRasterizer(raster_settings=raster_settings) + + means3D = pc.get_xyz + means2D = screenspace_points + opacity = pc.get_opacity + + # If precomputed 3d covariance is provided, use it. If not, then it will be computed from + # scaling / rotation by the rasterizer. + scales = None + rotations = None + cov3D_precomp = None + if pipe.compute_cov3D_python: + cov3D_precomp = pc.get_covariance(scaling_modifier) + else: + scales = pc.get_scaling + rotations = pc.get_rotation + + # If precomputed colors are provided, use them. Otherwise, if it is desired to precompute colors + # from SHs in Python, do it. If not, then SH -> RGB conversion will be done by rasterizer. + shs = pc.get_features + colors_precomp = None + + # Rasterize visible Gaussians to image, obtain their radii (on screen). + rendered_image, radii = rasterizer( + means3D = means3D, + means2D = means2D, + shs = shs, + colors_precomp = colors_precomp, + opacities = opacity, + scales = scales, + rotations = rotations, + cov3D_precomp = cov3D_precomp + ) + if need_depth: + p_hom = torch.cat([pc.get_xyz, torch.ones_like(pc.get_xyz[...,:1])], -1).unsqueeze(-1) + p_view = torch.matmul(viewpoint_camera.world_view_transform.transpose(0,1), p_hom) + p_view = p_view[...,:3,:] + depth = p_view.squeeze()[...,2:3] + depth = depth.repeat(1,3) + depth_map = rasterizer( + means3D = means3D, + means2D = means2D, + shs = None, + colors_precomp = depth, + opacities = opacity, + scales = scales, + rotations = rotations, + cov3D_precomp = cov3D_precomp)[0] + # Those Gaussians that were frustum culled or had a radius of 0 were not visible. + # They will be excluded from value updates used in the splitting criteria. + return edict({"render": rendered_image, + "depth": depth_map if need_depth else None, + "viewspace_points": screenspace_points, + "visibility_filter" : radii > 0, + "radii": radii}) + + +class GaussianRenderer: + """ + Renderer for the Voxel representation. + + Args: + rendering_options (dict): Rendering options. + """ + + def __init__(self, rendering_options={}) -> None: + self.pipe = edict({ + "kernel_size": 0.1, + "convert_SHs_python": False, + "compute_cov3D_python": False, + "scale_modifier": 1.0, + "debug": False + }) + self.rendering_options = edict({ + "resolution": None, + "near": None, + "far": None, + "ssaa": 1, + "bg_color": 'random', + }) + self.rendering_options.update(rendering_options) + self.bg_color = None + + def render( + self, + gausssian: Gaussian, + extrinsics: torch.Tensor, + intrinsics: torch.Tensor, + colors_overwrite: torch.Tensor = None, + need_depth: bool = False, + ) -> edict: + """ + Render the gausssian. + + Args: + gaussian : gaussianmodule + extrinsics (torch.Tensor): (4, 4) camera extrinsics + intrinsics (torch.Tensor): (3, 3) camera intrinsics + colors_overwrite (torch.Tensor): (N, 3) override color + + Returns: + edict containing: + color (torch.Tensor): (3, H, W) rendered color image + """ + resolution = self.rendering_options["resolution"] + near = self.rendering_options["near"] + far = self.rendering_options["far"] + ssaa = self.rendering_options["ssaa"] + + if self.rendering_options["bg_color"] == 'random': + self.bg_color = torch.zeros(3, dtype=torch.float32, device="cuda") + if np.random.rand() < 0.5: + self.bg_color += 1 + else: + self.bg_color = torch.tensor(self.rendering_options["bg_color"], dtype=torch.float32, device="cuda") + + view = extrinsics + perspective = intrinsics_to_projection(intrinsics, near, far) + camera = torch.inverse(view)[:3, 3] + focalx = intrinsics[0, 0] + focaly = intrinsics[1, 1] + fovx = 2 * torch.atan(0.5 / focalx) + fovy = 2 * torch.atan(0.5 / focaly) + + camera_dict = edict({ + "image_height": resolution * ssaa, + "image_width": resolution * ssaa, + "FoVx": fovx, + "FoVy": fovy, + "znear": near, + "zfar": far, + "world_view_transform": view.T.float().contiguous(), + "projection_matrix": perspective.T.float().contiguous(), + "full_proj_transform": (perspective @ view).T.float().contiguous(), + "camera_center": camera + }) + + # Render + render_ret = render(camera_dict, gausssian, self.pipe, self.bg_color, override_color=colors_overwrite, scaling_modifier=self.pipe.scale_modifier, need_depth=need_depth) + + if ssaa > 1: + render_ret.render = F.interpolate(render_ret.render[None], size=(resolution, resolution), mode='bilinear', align_corners=False, antialias=True).squeeze() + + if need_depth: + return edict({ + 'color': render_ret['render'], + 'depth': render_ret['depth'], + }) + else: + return edict({ + 'color': render_ret['render'], + }) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/renderers/gsplat_renderer.py b/OVOW/engine/oneposeviagen/trellis/trellis/renderers/gsplat_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..770089ec00fa5ddb998abb8f82cdd9f8c643dc40 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/renderers/gsplat_renderer.py @@ -0,0 +1,108 @@ +import gsplat as gs +import numpy as np +import torch +import torch.nn.functional as F +from easydict import EasyDict as edict + + +class GSplatRenderer: + def __init__(self, rendering_options={}) -> None: + self.pipe = edict({ + "kernel_size": 0.1, + "convert_SHs_python": False, + "compute_cov3D_python": False, + "scale_modifier": 1.0, + "debug": False, + "use_mip_gaussian": True + }) + self.rendering_options = edict({ + "resolution": None, + "near": None, + "far": None, + "ssaa": 1, + "bg_color": 'random', + }) + self.rendering_options.update(rendering_options) + self.bg_color = None + + def render( + self, + gaussian, + extrinsics: torch.Tensor, + intrinsics: torch.Tensor, + colors_overwrite: torch.Tensor = None + ) -> edict: + + resolution = self.rendering_options["resolution"] + ssaa = self.rendering_options["ssaa"] + + if self.rendering_options["bg_color"] == 'random': + self.bg_color = torch.zeros(3, dtype=torch.float32, device="cuda") + if np.random.rand() < 0.5: + self.bg_color += 1 + else: + self.bg_color = torch.tensor( + self.rendering_options["bg_color"], + dtype=torch.float32, + device="cuda" + ) + + height = resolution * ssaa + width = resolution * ssaa + + # Set up background color + if self.rendering_options["bg_color"] == 'random': + self.bg_color = torch.zeros(3, dtype=torch.float32, device="cuda") + if np.random.rand() < 0.5: + self.bg_color += 1 + else: + self.bg_color = torch.tensor( + self.rendering_options["bg_color"], + dtype=torch.float32, + device="cuda" + ) + + Ks_scaled = intrinsics.clone() + Ks_scaled[0, 0] *= width + Ks_scaled[1, 1] *= height + Ks_scaled[0, 2] *= width + Ks_scaled[1, 2] *= height + Ks_scaled = Ks_scaled.unsqueeze(0) + + near_plane = 0.01 + far_plane = 1000.0 + + # Rasterize with gsplat + render_colors, render_alphas, meta = gs.rasterization( + means=gaussian.get_xyz, + quats=F.normalize(gaussian.get_rotation, dim=-1), + scales=gaussian.get_scaling / intrinsics[0, 0], + opacities=gaussian.get_opacity.squeeze(-1), + colors=colors_overwrite.unsqueeze(0) if colors_overwrite is not None else torch.sigmoid( + gaussian.get_features.squeeze(1)).unsqueeze(0), + viewmats=extrinsics.unsqueeze(0), + Ks=Ks_scaled, + width=width, + height=height, + near_plane=near_plane, + far_plane=far_plane, + radius_clip=3.0, + eps2d=0.3, + render_mode="RGB", + backgrounds=self.bg_color.unsqueeze(0), + camera_model="pinhole" + ) + + rendered_image = render_colors[0, ..., 0:3].permute(2, 0, 1) + + # Apply supersampling if needed + if ssaa > 1: + rendered_image = F.interpolate( + rendered_image[None], + size=(resolution, resolution), + mode='bilinear', + align_corners=False, + antialias=True + ).squeeze() + + return edict({'color': rendered_image}) \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/renderers/mesh_renderer.py b/OVOW/engine/oneposeviagen/trellis/trellis/renderers/mesh_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..8a6ef3237c7f26c7b4c6a23aa7cf5c5edefa21e7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/renderers/mesh_renderer.py @@ -0,0 +1,153 @@ +import torch +try: + import nvdiffrast.torch as dr +except : + print("nvdiffrast are not installed. Please install them to use the mesh renderer.") +from easydict import EasyDict as edict +from ..representations.mesh import MeshExtractResult +import torch.nn.functional as F + + +def intrinsics_to_projection( + intrinsics: torch.Tensor, + near: float, + far: float, + ) -> torch.Tensor: + """ + OpenCV intrinsics to OpenGL perspective matrix + + Args: + intrinsics (torch.Tensor): [3, 3] OpenCV intrinsics matrix + near (float): near plane to clip + far (float): far plane to clip + Returns: + (torch.Tensor): [4, 4] OpenGL perspective matrix + """ + fx, fy = intrinsics[0, 0], intrinsics[1, 1] + cx, cy = intrinsics[0, 2], intrinsics[1, 2] + ret = torch.zeros((4, 4), dtype=intrinsics.dtype, device=intrinsics.device) + ret[0, 0] = 2 * fx + ret[1, 1] = 2 * fy + ret[0, 2] = 2 * cx - 1 + ret[1, 2] = - 2 * cy + 1 + ret[2, 2] = far / (far - near) + ret[2, 3] = near * far / (near - far) + ret[3, 2] = 1. + return ret + + +class MeshRenderer: + """ + Renderer for the Mesh representation. + + Args: + rendering_options (dict): Rendering options. + glctx (nvdiffrast.torch.RasterizeGLContext): RasterizeGLContext object for CUDA/OpenGL interop. + """ + def __init__(self, rendering_options={}, device='cuda'): + self.rendering_options = edict({ + "resolution": None, + "near": None, + "far": None, + "ssaa": 1 + }) + self.rendering_options.update(rendering_options) + self.glctx = dr.RasterizeCudaContext(device=device) + self.device = device + + def render( + self, + mesh : MeshExtractResult, + extrinsics: torch.Tensor, + intrinsics: torch.Tensor, + return_types = ["color", "normal", "nocs", "depth"] + ) -> edict: + """ + Render the mesh. + + Args: + mesh : meshmodel + extrinsics (torch.Tensor): (4, 4) camera extrinsics + intrinsics (torch.Tensor): (3, 3) camera intrinsics + return_types (list): list of return types, can be "mask", "depth", "normal", "color", "nocs" + + Returns: + edict based on return_types containing: + color (torch.Tensor): [3, H, W] rendered color image + depth (torch.Tensor): [H, W] rendered depth image + normal (torch.Tensor): [3, H, W] rendered normal image in camera space + mask (torch.Tensor): [H, W] rendered mask image + nocs (torch.Tensor): [3, H, W] rendered NOCS coordinates + """ + resolution = self.rendering_options["resolution"] + near = self.rendering_options["near"] + far = self.rendering_options["far"] + ssaa = self.rendering_options["ssaa"] + + if mesh.vertices.shape[0] == 0 or mesh.faces.shape[0] == 0: + default_img = torch.zeros((1, resolution, resolution, 3), dtype=torch.float32, device=self.device) + ret_dict = {k : default_img if k in ['normal', 'normal_map', 'color'] else default_img[..., :1] for k in return_types} + return ret_dict + + perspective = intrinsics_to_projection(intrinsics, near, far) + + RT = extrinsics.unsqueeze(0) + full_proj = (perspective @ extrinsics).unsqueeze(0) + + vertices = mesh.vertices.unsqueeze(0) + + vertices_homo = torch.cat([vertices, torch.ones_like(vertices[..., :1])], dim=-1) + vertices_camera = torch.bmm(vertices_homo, RT.transpose(-1, -2)) + vertices_clip = torch.bmm(vertices_homo, full_proj.transpose(-1, -2)) + faces_int = mesh.faces.int() + rast, _ = dr.rasterize( + self.glctx, vertices_clip, faces_int, (resolution * ssaa, resolution * ssaa)) + + out_dict = edict() + for type in return_types: + img = None + try: + if type == "mask": + img = dr.antialias((rast[..., -1:] > 0).float(), rast, vertices_clip, faces_int) + elif type == "depth": + img = dr.interpolate(vertices_camera[..., 2:3].contiguous(), rast, faces_int)[0] + elif type == "normal": + # Transform face normals to camera space + rotation = RT[..., :3, :3] # [1, 3, 3] + face_normals = mesh.face_normal.view(1, -1, 3) # [1, N, 3] + camera_space_normals = torch.matmul(face_normals, rotation.transpose(-1, -2)) + camera_space_normals = F.normalize(camera_space_normals, dim=-1) + + img = dr.interpolate( + camera_space_normals.reshape(1, -1, 3), rast, + torch.arange(mesh.faces.shape[0] * 3, device=self.device, dtype=torch.int).reshape(-1, 3) + )[0] + # normalize norm pictures to [0,1] range + img = (-img + 1) / 2 + elif type == "color": + img = dr.interpolate(mesh.vertex_attrs[:, :3].contiguous(), rast, faces_int)[0] + img = dr.antialias(img, rast, vertices_clip, faces_int) + elif type == "nocs": + img = dr.interpolate(vertices[..., :3].contiguous(), rast, faces_int)[0] + img = img + 0.5 + + if ssaa > 1: + if type == 'color': + img = F.interpolate(img.permute(0, 3, 1, 2), (resolution, resolution), mode='bilinear', align_corners=False, antialias=True) + img = img.squeeze() + else: + img = F.interpolate(img.permute(0, 3, 1, 2), (resolution, resolution), mode='nearest') + img = img.squeeze() + else: + img = img.permute(0, 3, 1, 2).squeeze() + except Exception as e: + print(f"Error rendering {type}: {str(e)}") + # Return a blank image of appropriate shape in case of error + if type in ['normal', 'color', 'nocs', 'depth']: + img = torch.zeros((3, resolution, resolution), dtype=torch.float32, device=self.device) + else: + img = torch.zeros((resolution, resolution), dtype=torch.float32, device=self.device) + + out_dict[type] = img + + return out_dict diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/renderers/octree_renderer.py b/OVOW/engine/oneposeviagen/trellis/trellis/renderers/octree_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..e933c9a55dbaa6177daa833c54fb70e08f81dc54 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/renderers/octree_renderer.py @@ -0,0 +1,301 @@ +import numpy as np +import torch +import torch.nn.functional as F +import math +import cv2 +from scipy.stats import qmc +from easydict import EasyDict as edict +from ..representations.octree import DfsOctree + + +def intrinsics_to_projection( + intrinsics: torch.Tensor, + near: float, + far: float, + ) -> torch.Tensor: + """ + OpenCV intrinsics to OpenGL perspective matrix + + Args: + intrinsics (torch.Tensor): [3, 3] OpenCV intrinsics matrix + near (float): near plane to clip + far (float): far plane to clip + Returns: + (torch.Tensor): [4, 4] OpenGL perspective matrix + """ + fx, fy = intrinsics[0, 0], intrinsics[1, 1] + cx, cy = intrinsics[0, 2], intrinsics[1, 2] + ret = torch.zeros((4, 4), dtype=intrinsics.dtype, device=intrinsics.device) + ret[0, 0] = 2 * fx + ret[1, 1] = 2 * fy + ret[0, 2] = 2 * cx - 1 + ret[1, 2] = - 2 * cy + 1 + ret[2, 2] = far / (far - near) + ret[2, 3] = near * far / (near - far) + ret[3, 2] = 1. + return ret + + +def render(viewpoint_camera, octree : DfsOctree, pipe, bg_color : torch.Tensor, scaling_modifier = 1.0, used_rank = None, colors_overwrite = None, aux=None, halton_sampler=None): + """ + Render the scene. + + Background tensor (bg_color) must be on GPU! + """ + # lazy import + if 'OctreeTrivecRasterizer' not in globals(): + from diffoctreerast import OctreeVoxelRasterizer, OctreeGaussianRasterizer, OctreeTrivecRasterizer, OctreeDecoupolyRasterizer + + # Set up rasterization configuration + tanfovx = math.tan(viewpoint_camera.FoVx * 0.5) + tanfovy = math.tan(viewpoint_camera.FoVy * 0.5) + + raster_settings = edict( + image_height=int(viewpoint_camera.image_height), + image_width=int(viewpoint_camera.image_width), + tanfovx=tanfovx, + tanfovy=tanfovy, + bg=bg_color, + scale_modifier=scaling_modifier, + viewmatrix=viewpoint_camera.world_view_transform, + projmatrix=viewpoint_camera.full_proj_transform, + sh_degree=octree.active_sh_degree, + campos=viewpoint_camera.camera_center, + with_distloss=pipe.with_distloss, + jitter=pipe.jitter, + debug=pipe.debug, + ) + + positions = octree.get_xyz + if octree.primitive == "voxel": + densities = octree.get_density + elif octree.primitive == "gaussian": + opacities = octree.get_opacity + elif octree.primitive == "trivec": + trivecs = octree.get_trivec + densities = octree.get_density + raster_settings.density_shift = octree.density_shift + elif octree.primitive == "decoupoly": + decoupolys_V, decoupolys_g = octree.get_decoupoly + densities = octree.get_density + raster_settings.density_shift = octree.density_shift + else: + raise ValueError(f"Unknown primitive {octree.primitive}") + depths = octree.get_depth + + # If precomputed colors are provided, use them. Otherwise, if it is desired to precompute colors + # from SHs in Python, do it. If not, then SH -> RGB conversion will be done by rasterizer. + colors_precomp = None + shs = octree.get_features + if octree.primitive in ["voxel", "gaussian"] and colors_overwrite is not None: + colors_precomp = colors_overwrite + shs = None + + ret = edict() + + if octree.primitive == "voxel": + renderer = OctreeVoxelRasterizer(raster_settings=raster_settings) + rgb, depth, alpha, distloss = renderer( + positions = positions, + densities = densities, + shs = shs, + colors_precomp = colors_precomp, + depths = depths, + aabb = octree.aabb, + aux = aux, + ) + ret['rgb'] = rgb + ret['depth'] = depth + ret['alpha'] = alpha + ret['distloss'] = distloss + elif octree.primitive == "gaussian": + renderer = OctreeGaussianRasterizer(raster_settings=raster_settings) + rgb, depth, alpha = renderer( + positions = positions, + opacities = opacities, + shs = shs, + colors_precomp = colors_precomp, + depths = depths, + aabb = octree.aabb, + aux = aux, + ) + ret['rgb'] = rgb + ret['depth'] = depth + ret['alpha'] = alpha + elif octree.primitive == "trivec": + raster_settings.used_rank = used_rank if used_rank is not None else trivecs.shape[1] + renderer = OctreeTrivecRasterizer(raster_settings=raster_settings) + rgb, depth, alpha, percent_depth = renderer( + positions = positions, + trivecs = trivecs, + densities = densities, + shs = shs, + colors_precomp = colors_precomp, + colors_overwrite = colors_overwrite, + depths = depths, + aabb = octree.aabb, + aux = aux, + halton_sampler = halton_sampler, + ) + ret['percent_depth'] = percent_depth + ret['rgb'] = rgb + ret['depth'] = depth + ret['alpha'] = alpha + elif octree.primitive == "decoupoly": + raster_settings.used_rank = used_rank if used_rank is not None else decoupolys_V.shape[1] + renderer = OctreeDecoupolyRasterizer(raster_settings=raster_settings) + rgb, depth, alpha = renderer( + positions = positions, + decoupolys_V = decoupolys_V, + decoupolys_g = decoupolys_g, + densities = densities, + shs = shs, + colors_precomp = colors_precomp, + depths = depths, + aabb = octree.aabb, + aux = aux, + ) + ret['rgb'] = rgb + ret['depth'] = depth + ret['alpha'] = alpha + + return ret + + +class OctreeRenderer: + """ + Renderer for the Voxel representation. + + Args: + rendering_options (dict): Rendering options. + """ + + def __init__(self, rendering_options={}) -> None: + try: + import diffoctreerast + except ImportError: + print("\033[93m[WARNING] diffoctreerast is not installed. The renderer will be disabled.\033[0m") + self.unsupported = True + else: + self.unsupported = False + + self.pipe = edict({ + "with_distloss": False, + "with_aux": False, + "scale_modifier": 1.0, + "used_rank": None, + "jitter": False, + "debug": False, + }) + self.rendering_options = edict({ + "resolution": None, + "near": None, + "far": None, + "ssaa": 1, + "bg_color": 'random', + }) + self.halton_sampler = qmc.Halton(2, scramble=False) + self.rendering_options.update(rendering_options) + self.bg_color = None + + def render( + self, + octree: DfsOctree, + extrinsics: torch.Tensor, + intrinsics: torch.Tensor, + colors_overwrite: torch.Tensor = None, + ) -> edict: + """ + Render the octree. + + Args: + octree (Octree): octree + extrinsics (torch.Tensor): (4, 4) camera extrinsics + intrinsics (torch.Tensor): (3, 3) camera intrinsics + colors_overwrite (torch.Tensor): (N, 3) override color + + Returns: + edict containing: + color (torch.Tensor): (3, H, W) rendered color + depth (torch.Tensor): (H, W) rendered depth + alpha (torch.Tensor): (H, W) rendered alpha + distloss (Optional[torch.Tensor]): (H, W) rendered distance loss + percent_depth (Optional[torch.Tensor]): (H, W) rendered percent depth + aux (Optional[edict]): auxiliary tensors + """ + resolution = self.rendering_options["resolution"] + near = self.rendering_options["near"] + far = self.rendering_options["far"] + ssaa = self.rendering_options["ssaa"] + + if self.unsupported: + image = np.zeros((512, 512, 3), dtype=np.uint8) + text_bbox = cv2.getTextSize("Unsupported", cv2.FONT_HERSHEY_SIMPLEX, 2, 3)[0] + origin = (512 - text_bbox[0]) // 2, (512 - text_bbox[1]) // 2 + image = cv2.putText(image, "Unsupported", origin, cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 3, cv2.LINE_AA) + return { + 'color': torch.tensor(image, dtype=torch.float32).permute(2, 0, 1) / 255, + } + + if self.rendering_options["bg_color"] == 'random': + self.bg_color = torch.zeros(3, dtype=torch.float32, device="cuda") + if np.random.rand() < 0.5: + self.bg_color += 1 + else: + self.bg_color = torch.tensor(self.rendering_options["bg_color"], dtype=torch.float32, device="cuda") + + if self.pipe["with_aux"]: + aux = { + 'grad_color2': torch.zeros((octree.num_leaf_nodes, 3), dtype=torch.float32, requires_grad=True, device="cuda") + 0, + 'contributions': torch.zeros((octree.num_leaf_nodes, 1), dtype=torch.float32, requires_grad=True, device="cuda") + 0, + } + for k in aux.keys(): + aux[k].requires_grad_() + aux[k].retain_grad() + else: + aux = None + + view = extrinsics + perspective = intrinsics_to_projection(intrinsics, near, far) + camera = torch.inverse(view)[:3, 3] + focalx = intrinsics[0, 0] + focaly = intrinsics[1, 1] + fovx = 2 * torch.atan(0.5 / focalx) + fovy = 2 * torch.atan(0.5 / focaly) + + print(f"Rendering with resolution {resolution}, near {near}, far {far}, ssaa {ssaa}, bg_color {self.bg_color}, fovx {fovx}, fovy {fovy}") + camera_dict = edict({ + "image_height": resolution * ssaa, + "image_width": resolution * ssaa, + "FoVx": fovx, + "FoVy": fovy, + "znear": near, + "zfar": far, + "world_view_transform": view.T.contiguous(), + "projection_matrix": perspective.T.contiguous(), + "full_proj_transform": (perspective @ view).T.contiguous(), + "camera_center": camera + }) + + # Render + render_ret = render(camera_dict, octree, self.pipe, self.bg_color, aux=aux, colors_overwrite=colors_overwrite, scaling_modifier=self.pipe.scale_modifier, used_rank=self.pipe.used_rank, halton_sampler=self.halton_sampler) + + if ssaa > 1: + render_ret.rgb = F.interpolate(render_ret.rgb[None], size=(resolution, resolution), mode='bilinear', align_corners=False, antialias=True).squeeze() + render_ret.depth = F.interpolate(render_ret.depth[None, None], size=(resolution, resolution), mode='bilinear', align_corners=False, antialias=True).squeeze() + render_ret.alpha = F.interpolate(render_ret.alpha[None, None], size=(resolution, resolution), mode='bilinear', align_corners=False, antialias=True).squeeze() + if hasattr(render_ret, 'percent_depth'): + render_ret.percent_depth = F.interpolate(render_ret.percent_depth[None, None], size=(resolution, resolution), mode='bilinear', align_corners=False, antialias=True).squeeze() + + ret = edict({ + 'color': render_ret.rgb, + 'depth': render_ret.depth, + 'alpha': render_ret.alpha, + }) + if self.pipe["with_distloss"] and 'distloss' in render_ret: + ret['distloss'] = render_ret.distloss + if self.pipe["with_aux"]: + ret['aux'] = aux + if hasattr(render_ret, 'percent_depth'): + ret['percent_depth'] = render_ret.percent_depth + return ret \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/representations/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/representations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c027ee0c4e866b8f536e982399caf70e45905cc7 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/representations/__init__.py @@ -0,0 +1,3 @@ +from .gaussian import Gaussian +from .mesh import MeshExtractResult +from .octree import DfsOctree as Octree \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/representations/gaussian/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/representations/gaussian/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3de6e180bd732836af876d748255595be2d4d74 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/representations/gaussian/__init__.py @@ -0,0 +1 @@ +from .gaussian_model import Gaussian \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/representations/gaussian/gaussian_model.py b/OVOW/engine/oneposeviagen/trellis/trellis/representations/gaussian/gaussian_model.py new file mode 100644 index 0000000000000000000000000000000000000000..1bfc51de0e79797a1a67c19dcae78dbe729f07a6 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/representations/gaussian/gaussian_model.py @@ -0,0 +1,215 @@ +import torch +import numpy as np +from plyfile import PlyData, PlyElement +from .general_utils import inverse_sigmoid, strip_symmetric, build_scaling_rotation + +SH_C0_0 = 0.28209479177387814 + +class Gaussian: + def __init__( + self, + aabb : list, + sh_degree : int = 0, + mininum_kernel_size : float = 0.0, + scaling_bias : float = 0.01, + opacity_bias : float = 0.1, + scaling_activation : str = "exp", + device='cuda' + ): + self.init_params = { + 'aabb': aabb, + 'sh_degree': sh_degree, + 'mininum_kernel_size': mininum_kernel_size, + 'scaling_bias': scaling_bias, + 'opacity_bias': opacity_bias, + 'scaling_activation': scaling_activation, + } + + self.sh_degree = sh_degree + self.active_sh_degree = sh_degree + self.mininum_kernel_size = mininum_kernel_size + self.scaling_bias = scaling_bias + self.opacity_bias = opacity_bias + self.scaling_activation_type = scaling_activation + self.device = device + self.aabb = torch.tensor(aabb, dtype=torch.float32, device=device) + + self.setup_functions() + + self._xyz = None + self._features_dc = None + self._features_rest = None + self._scaling = None + self._rotation = None + self._opacity = None + + def convert_to_fp32(self): + self.aabb = self.aabb.float() + if self._xyz is not None: + self._xyz = self._xyz.float() + if self._features_dc is not None: + self._features_dc = self._features_dc.float() + if self._features_rest is not None: + self._features_rest = self._features_rest.float() + if self._scaling is not None: + self._scaling = self._scaling.float() + if self._rotation is not None: + self._rotation = self._rotation.float() + if self._opacity is not None: + self._opacity = self._opacity.float() + + def setup_functions(self): + def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation): + L = build_scaling_rotation(scaling_modifier * scaling, rotation) + actual_covariance = L @ L.transpose(1, 2) + symm = strip_symmetric(actual_covariance) + return symm + + if self.scaling_activation_type == "exp": + self.scaling_activation = torch.exp + self.inverse_scaling_activation = torch.log + elif self.scaling_activation_type == "softplus": + self.scaling_activation = torch.nn.functional.softplus + self.inverse_scaling_activation = lambda x: x + torch.log(-torch.expm1(-x)) + + self.covariance_activation = build_covariance_from_scaling_rotation + + self.opacity_activation = torch.sigmoid + self.inverse_opacity_activation = inverse_sigmoid + + self.rotation_activation = torch.nn.functional.normalize + + self.scale_bias = self.inverse_scaling_activation(torch.tensor(self.scaling_bias)).cuda() + self.rots_bias = torch.zeros((4)).cuda() + self.rots_bias[0] = 1 + self.opacity_bias = self.inverse_opacity_activation(torch.tensor(self.opacity_bias)).cuda() + + @property + def get_scaling(self): + scales = self.scaling_activation(self._scaling + self.scale_bias) + scales = torch.square(scales) + self.mininum_kernel_size ** 2 + scales = torch.sqrt(scales) + return scales + + @property + def get_rotation(self): + return self.rotation_activation(self._rotation + self.rots_bias[None, :]) + + @property + def get_xyz(self): + return self._xyz * self.aabb[None, 3:] + self.aabb[None, :3] + + @property + def get_color(self): + return (SH_C0_0 * self._features_dc.squeeze(dim=1) + 0.5).clip(0, 1) + + @property + def get_features(self): + return torch.cat((self._features_dc, self._features_rest), dim=2) if self._features_rest is not None else self._features_dc + + @property + def get_opacity(self): + return self.opacity_activation(self._opacity + self.opacity_bias) + + def get_covariance(self, scaling_modifier = 1): + return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation + self.rots_bias[None, :]) + + def from_scaling(self, scales): + scales = torch.sqrt(torch.square(scales) - self.mininum_kernel_size ** 2) + self._scaling = self.inverse_scaling_activation(scales) - self.scale_bias + + def from_rotation(self, rots): + self._rotation = rots - self.rots_bias[None, :] + + def from_xyz(self, xyz): + self._xyz = (xyz - self.aabb[None, :3]) / self.aabb[None, 3:] + + def from_features(self, features): + self._features_dc = features + + def from_opacity(self, opacities): + self._opacity = self.inverse_opacity_activation(opacities) - self.opacity_bias + + def construct_list_of_attributes(self): + l = ['x', 'y', 'z', 'nx', 'ny', 'nz'] + # All channels except the 3 DC + for i in range(self._features_dc.shape[1]*self._features_dc.shape[2]): + l.append('f_dc_{}'.format(i)) + l.append('opacity') + for i in range(self._scaling.shape[1]): + l.append('scale_{}'.format(i)) + for i in range(self._rotation.shape[1]): + l.append('rot_{}'.format(i)) + return l + + def save_ply(self, path): + xyz = self.get_xyz.detach().cpu().numpy() + normals = np.zeros_like(xyz) + f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy() + opacities = inverse_sigmoid(self.get_opacity).detach().cpu().numpy() + scale = torch.log(self.get_scaling).detach().cpu().numpy() + rotation = (self._rotation + self.rots_bias[None, :]).detach().cpu().numpy() + + dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()] + + elements = np.empty(xyz.shape[0], dtype=dtype_full) + attributes = np.concatenate((xyz, normals, f_dc, opacities, scale, rotation), axis=1) + elements[:] = list(map(tuple, attributes)) + el = PlyElement.describe(elements, 'vertex') + PlyData([el]).write(path) + + def load_ply(self, path): + plydata = PlyData.read(path) + + xyz = np.stack((np.asarray(plydata.elements[0]["x"]), + np.asarray(plydata.elements[0]["y"]), + np.asarray(plydata.elements[0]["z"])), axis=1) + opacities = np.asarray(plydata.elements[0]["opacity"])[..., np.newaxis] + + features_dc = np.zeros((xyz.shape[0], 3, 1)) + features_dc[:, 0, 0] = np.asarray(plydata.elements[0]["f_dc_0"]) + features_dc[:, 1, 0] = np.asarray(plydata.elements[0]["f_dc_1"]) + features_dc[:, 2, 0] = np.asarray(plydata.elements[0]["f_dc_2"]) + + if self.sh_degree > 0: + extra_f_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("f_rest_")] + extra_f_names = sorted(extra_f_names, key = lambda x: int(x.split('_')[-1])) + assert len(extra_f_names)==3*(self.sh_degree + 1) ** 2 - 3 + features_extra = np.zeros((xyz.shape[0], len(extra_f_names))) + for idx, attr_name in enumerate(extra_f_names): + features_extra[:, idx] = np.asarray(plydata.elements[0][attr_name]) + # Reshape (P,F*SH_coeffs) to (P, F, SH_coeffs except DC) + features_extra = features_extra.reshape((features_extra.shape[0], 3, (self.max_sh_degree + 1) ** 2 - 1)) + + scale_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("scale_")] + scale_names = sorted(scale_names, key = lambda x: int(x.split('_')[-1])) + scales = np.zeros((xyz.shape[0], len(scale_names))) + for idx, attr_name in enumerate(scale_names): + scales[:, idx] = np.asarray(plydata.elements[0][attr_name]) + + rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("rot")] + rot_names = sorted(rot_names, key = lambda x: int(x.split('_')[-1])) + rots = np.zeros((xyz.shape[0], len(rot_names))) + for idx, attr_name in enumerate(rot_names): + rots[:, idx] = np.asarray(plydata.elements[0][attr_name]) + + # convert to actual gaussian attributes + xyz = torch.tensor(xyz, dtype=torch.float, device=self.device) + features_dc = torch.tensor(features_dc, dtype=torch.float, device=self.device).transpose(1, 2).contiguous() + if self.sh_degree > 0: + features_extra = torch.tensor(features_extra, dtype=torch.float, device=self.device).transpose(1, 2).contiguous() + opacities = torch.sigmoid(torch.tensor(opacities, dtype=torch.float, device=self.device)) + scales = torch.exp(torch.tensor(scales, dtype=torch.float, device=self.device)) + rots = torch.tensor(rots, dtype=torch.float, device=self.device) + + # convert to _hidden attributes + self._xyz = (xyz - self.aabb[None, :3]) / self.aabb[None, 3:] + self._features_dc = features_dc + if self.sh_degree > 0: + self._features_rest = features_extra + else: + self._features_rest = None + self._opacity = self.inverse_opacity_activation(opacities) - self.opacity_bias + self._scaling = self.inverse_scaling_activation(torch.sqrt(torch.square(scales) - self.mininum_kernel_size ** 2)) - self.scale_bias + self._rotation = rots - self.rots_bias[None, :] + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/representations/gaussian/general_utils.py b/OVOW/engine/oneposeviagen/trellis/trellis/representations/gaussian/general_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..541c0825229a2d86e84460b765879f86f724a59d --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/representations/gaussian/general_utils.py @@ -0,0 +1,133 @@ +# +# Copyright (C) 2023, Inria +# GRAPHDECO research group, https://team.inria.fr/graphdeco +# All rights reserved. +# +# This software is free for non-commercial, research and evaluation use +# under the terms of the LICENSE.md file. +# +# For inquiries contact george.drettakis@inria.fr +# + +import torch +import sys +from datetime import datetime +import numpy as np +import random + +def inverse_sigmoid(x): + return torch.log(x/(1-x)) + +def PILtoTorch(pil_image, resolution): + resized_image_PIL = pil_image.resize(resolution) + resized_image = torch.from_numpy(np.array(resized_image_PIL)) / 255.0 + if len(resized_image.shape) == 3: + return resized_image.permute(2, 0, 1) + else: + return resized_image.unsqueeze(dim=-1).permute(2, 0, 1) + +def get_expon_lr_func( + lr_init, lr_final, lr_delay_steps=0, lr_delay_mult=1.0, max_steps=1000000 +): + """ + Copied from Plenoxels + + Continuous learning rate decay function. Adapted from JaxNeRF + The returned rate is lr_init when step=0 and lr_final when step=max_steps, and + is log-linearly interpolated elsewhere (equivalent to exponential decay). + If lr_delay_steps>0 then the learning rate will be scaled by some smooth + function of lr_delay_mult, such that the initial learning rate is + lr_init*lr_delay_mult at the beginning of optimization but will be eased back + to the normal learning rate when steps>lr_delay_steps. + :param conf: config subtree 'lr' or similar + :param max_steps: int, the number of steps during optimization. + :return HoF which takes step as input + """ + + def helper(step): + if step < 0 or (lr_init == 0.0 and lr_final == 0.0): + # Disable this parameter + return 0.0 + if lr_delay_steps > 0: + # A kind of reverse cosine decay. + delay_rate = lr_delay_mult + (1 - lr_delay_mult) * np.sin( + 0.5 * np.pi * np.clip(step / lr_delay_steps, 0, 1) + ) + else: + delay_rate = 1.0 + t = np.clip(step / max_steps, 0, 1) + log_lerp = np.exp(np.log(lr_init) * (1 - t) + np.log(lr_final) * t) + return delay_rate * log_lerp + + return helper + +def strip_lowerdiag(L): + uncertainty = torch.zeros((L.shape[0], 6), dtype=torch.float, device="cuda") + + uncertainty[:, 0] = L[:, 0, 0] + uncertainty[:, 1] = L[:, 0, 1] + uncertainty[:, 2] = L[:, 0, 2] + uncertainty[:, 3] = L[:, 1, 1] + uncertainty[:, 4] = L[:, 1, 2] + uncertainty[:, 5] = L[:, 2, 2] + return uncertainty + +def strip_symmetric(sym): + return strip_lowerdiag(sym) + +def build_rotation(r): + norm = torch.sqrt(r[:,0]*r[:,0] + r[:,1]*r[:,1] + r[:,2]*r[:,2] + r[:,3]*r[:,3]) + + q = r / norm[:, None] + + R = torch.zeros((q.size(0), 3, 3), device='cuda') + + r = q[:, 0] + x = q[:, 1] + y = q[:, 2] + z = q[:, 3] + + R[:, 0, 0] = 1 - 2 * (y*y + z*z) + R[:, 0, 1] = 2 * (x*y - r*z) + R[:, 0, 2] = 2 * (x*z + r*y) + R[:, 1, 0] = 2 * (x*y + r*z) + R[:, 1, 1] = 1 - 2 * (x*x + z*z) + R[:, 1, 2] = 2 * (y*z - r*x) + R[:, 2, 0] = 2 * (x*z - r*y) + R[:, 2, 1] = 2 * (y*z + r*x) + R[:, 2, 2] = 1 - 2 * (x*x + y*y) + return R + +def build_scaling_rotation(s, r): + L = torch.zeros((s.shape[0], 3, 3), dtype=torch.float, device="cuda") + R = build_rotation(r) + + L[:,0,0] = s[:,0] + L[:,1,1] = s[:,1] + L[:,2,2] = s[:,2] + + L = R @ L + return L + +def safe_state(silent): + old_f = sys.stdout + class F: + def __init__(self, silent): + self.silent = silent + + def write(self, x): + if not self.silent: + if x.endswith("\n"): + old_f.write(x.replace("\n", " [{}]\n".format(str(datetime.now().strftime("%d/%m %H:%M:%S"))))) + else: + old_f.write(x) + + def flush(self): + old_f.flush() + + sys.stdout = F(silent) + + random.seed(0) + np.random.seed(0) + torch.manual_seed(0) + torch.cuda.set_device(torch.device("cuda:0")) diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bf6068e8bad549a7625d8de8b23ed1659814a655 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/__init__.py @@ -0,0 +1,5 @@ +from .cube2mesh import SparseFeatures2Mesh, MeshExtractResult +try: + from .mc2mesh import SparseFeatures2MCMesh +except ImportError: + pass \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/cube2mesh.py b/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/cube2mesh.py new file mode 100644 index 0000000000000000000000000000000000000000..c420ddccc9f87aef3932c66bf24a4e1c196b578b --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/cube2mesh.py @@ -0,0 +1,268 @@ +# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# NVIDIA CORPORATION & AFFILIATES and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION & AFFILIATES is strictly prohibited. +import torch +from ...modules.sparse import SparseTensor +from easydict import EasyDict as edict +from .utils_cube import * +from .flexicube import FlexiCubes + +import torch +import trimesh +import numpy as np + +# Dependency for mesh cleaning and hole fix +# from ...utils.random_utils import sphere_hammersley_sequence +# import utils3d +# import igraph +# from tqdm import tqdm +# from pymeshfix import _meshfix + +class MeshExtractResult: + def __init__(self, + vertices, + faces, + vertex_attrs=None, + res=64 + ): + self.vertices = vertices + self.faces = faces.long() + self.vertex_attrs = vertex_attrs + self.face_normal = self.comput_face_normals(vertices, faces) + self.vertex_normal = self.comput_v_normals(vertices, faces) + self.res = res + self.success = (vertices.shape[0] != 0 and faces.shape[0] != 0) + + # training only + self.tsdf_v = None + self.tsdf_s = None + self.reg_loss = None + + def comput_face_normals(self, verts, faces): + i0 = faces[..., 0].long() + i1 = faces[..., 1].long() + i2 = faces[..., 2].long() + + v0 = verts[i0, :] + v1 = verts[i1, :] + v2 = verts[i2, :] + face_normals = torch.cross(v1 - v0, v2 - v0, dim=-1) + face_normals = torch.nn.functional.normalize(face_normals, dim=1) + return face_normals[:, None, :].repeat(1, 3, 1) + + def comput_v_normals(self, verts, faces): + i0 = faces[..., 0].long() + i1 = faces[..., 1].long() + i2 = faces[..., 2].long() + + v0 = verts[i0, :] + v1 = verts[i1, :] + v2 = verts[i2, :] + face_normals = torch.cross(v1 - v0, v2 - v0, dim=-1) + v_normals = torch.zeros_like(verts) + v_normals.scatter_add_(0, i0[..., None].repeat(1, 3), face_normals) + v_normals.scatter_add_(0, i1[..., None].repeat(1, 3), face_normals) + v_normals.scatter_add_(0, i2[..., None].repeat(1, 3), face_normals) + + v_normals = torch.nn.functional.normalize(v_normals, dim=1) + return v_normals + + def to_trimesh(self, transform_pose=False): + """ + Convert the mesh to a trimesh.Trimesh object. + Args: + transform_pose (bool): If True, transform the vertices to change coordinate system + Returns: + trimesh.Trimesh: The converted mesh + """ + # Convert vertices and faces to numpy arrays + vertices = self.vertices.detach().cpu().numpy() + faces = self.faces.detach().cpu().numpy() + + # Apply coordinate transformation if requested + if transform_pose: + transform_matrix = np.array([ + [1, 0, 0], + [0, 0, -1], + [0, 1, 0] + ]) + vertices = vertices @ transform_matrix + + # Also transform the normals if they exist + vertex_normals = self.vertex_normal.detach().cpu().numpy() @ transform_matrix + else: + vertex_normals = self.vertex_normal.detach().cpu().numpy() + + # Prepare vertex colors if they exist + vertex_colors = None + if self.vertex_attrs is not None: + vertex_colors = self.vertex_attrs[:, :3].detach().cpu().numpy() + # Ensure colors are in [0, 255] range + if vertex_colors.max() <= 1.0: + vertex_colors = (vertex_colors * 255).astype(np.uint8) + + # Create the trimesh mesh + mesh = trimesh.Trimesh( + vertices=vertices, + faces=faces, + vertex_colors=vertex_colors + ) + + return mesh + + @staticmethod + def from_trimesh(mesh, device='cuda'): + # Convert scene to mesh if necessary + if hasattr(mesh, 'geometry'): + # If it's a scene, get the first mesh + # Assuming the scene has at least one mesh + mesh_name = list(mesh.geometry.keys())[0] + mesh = mesh.geometry[mesh_name] + + vertices = torch.tensor(mesh.vertices, dtype=torch.float32) + faces = torch.tensor(mesh.faces, dtype=torch.int64) + + vertex_attrs = None + if mesh.visual.vertex_colors is not None: + vertex_attrs = torch.tensor(mesh.visual.vertex_colors, dtype=torch.float32) / 255.0 + print(vertex_attrs) + vertex_attrs = vertex_attrs[:, :3] + else: + vertex_attrs = torch.zeros((vertices.shape[0], 3), dtype=torch.float32) + return MeshExtractResult(vertices, faces, vertex_attrs) + + def to(self, device): + self.vertices = self.vertices.to(device) + self.faces = self.faces.to(device) + if self.vertex_attrs is not None: + self.vertex_attrs = self.vertex_attrs.to(device) + self.face_normal = self.face_normal.to(device) + self.vertex_normal = self.vertex_normal.to(device) + return self + + def subdivide(self): + """ + Subdivide the mesh by splitting each triangle into four smaller triangles. + """ + new_vertices = [] + new_faces = [] + vertex_map = {} + + def get_midpoint(v1, v2): + edge = tuple(sorted((v1, v2))) + if edge not in vertex_map: + midpoint = (self.vertices[v1] + self.vertices[v2]) / 2 + vertex_map[edge] = len(new_vertices) + new_vertices.append(midpoint) + return vertex_map[edge] + + for face in self.faces: + v0, v1, v2 = face + a = get_midpoint(v0.item(), v1.item()) + b = get_midpoint(v1.item(), v2.item()) + c = get_midpoint(v2.item(), v0.item()) + + new_faces.append([v0.item(), a, c]) + new_faces.append([v1.item(), b, a]) + new_faces.append([v2.item(), c, b]) + new_faces.append([a, b, c]) + + new_vertices = torch.stack(new_vertices) + new_faces = torch.tensor(new_faces, dtype=torch.long) + + self.vertices = torch.cat([self.vertices, new_vertices], dim=0) + self.faces = new_faces + self.face_normal = self.comput_face_normals(self.vertices, self.faces) + self.vertex_normal = self.comput_v_normals(self.vertices, self.faces) + self.vertex_attrs = torch.zeros((self.vertices.shape[0], 3), dtype=torch.float32) + +class SparseFeatures2Mesh: + def __init__(self, device="cuda", res=64, use_color=True): + ''' + a model to generate a mesh from sparse features structures using flexicube + ''' + super().__init__() + self.device=device + self.res = res + self.mesh_extractor = FlexiCubes(device=device) + self.sdf_bias = -1.0 / res + verts, cube = construct_dense_grid(self.res, self.device) + self.reg_c = cube.to(self.device) + self.reg_v = verts.to(self.device) + self.use_color = use_color + self._calc_layout() + + def _calc_layout(self): + LAYOUTS = { + 'sdf': {'shape': (8, 1), 'size': 8}, + 'deform': {'shape': (8, 3), 'size': 8 * 3}, + 'weights': {'shape': (21,), 'size': 21} + } + if self.use_color: + ''' + 6 channel color including normal map + ''' + LAYOUTS['color'] = {'shape': (8, 6,), 'size': 8 * 6} + self.layouts = edict(LAYOUTS) + start = 0 + for k, v in self.layouts.items(): + v['range'] = (start, start + v['size']) + start += v['size'] + self.feats_channels = start + + def get_layout(self, feats : torch.Tensor, name : str): + if name not in self.layouts: + return None + return feats[:, self.layouts[name]['range'][0]:self.layouts[name]['range'][1]].reshape(-1, *self.layouts[name]['shape']) + + def __call__(self, cubefeats : SparseTensor, training=False): + """ + Generates a mesh based on the specified sparse voxel structures. + Args: + cube_attrs [Nx21] : Sparse Tensor attrs about cube weights + verts_attrs [Nx10] : [0:1] SDF [1:4] deform [4:7] color [7:10] normal + Returns: + return the success tag and ni you loss, + """ + # add sdf bias to verts_attrs + coords = cubefeats.coords[:, 1:] + feats = cubefeats.feats + + sdf, deform, color, weights = [self.get_layout(feats, name) for name in ['sdf', 'deform', 'color', 'weights']] + sdf += self.sdf_bias + v_attrs = [sdf, deform, color] if self.use_color else [sdf, deform] + v_pos, v_attrs, reg_loss = sparse_cube2verts(coords, torch.cat(v_attrs, dim=-1), training=training) + v_attrs_d = get_dense_attrs(v_pos, v_attrs, res=self.res+1, sdf_init=True) + weights_d = get_dense_attrs(coords, weights, res=self.res, sdf_init=False) + if self.use_color: + sdf_d, deform_d, colors_d = v_attrs_d[..., 0], v_attrs_d[..., 1:4], v_attrs_d[..., 4:] + else: + sdf_d, deform_d = v_attrs_d[..., 0], v_attrs_d[..., 1:4] + colors_d = None + + x_nx3 = get_defomed_verts(self.reg_v, deform_d, self.res) + + vertices, faces, L_dev, colors = self.mesh_extractor( + voxelgrid_vertices=x_nx3, + scalar_field=sdf_d, + cube_idx=self.reg_c, + resolution=self.res, + beta=weights_d[:, :12], + alpha=weights_d[:, 12:20], + gamma_f=weights_d[:, 20], + voxelgrid_colors=colors_d, + training=training) + + mesh = MeshExtractResult(vertices=vertices, faces=faces, vertex_attrs=colors, res=self.res) + if training: + if mesh.success: + reg_loss += L_dev.mean() * 0.5 + reg_loss += (weights[:,:20]).abs().mean() * 0.2 + mesh.reg_loss = reg_loss + mesh.tsdf_v = get_defomed_verts(v_pos, v_attrs[:, 1:4], self.res) + mesh.tsdf_s = v_attrs[:, 0] + return mesh diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/flexicube.py b/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/flexicube.py new file mode 100644 index 0000000000000000000000000000000000000000..c8b1177a7301e113a027826ded8cca01f64f22d8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/flexicube.py @@ -0,0 +1,362 @@ +# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# NVIDIA CORPORATION & AFFILIATES and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION & AFFILIATES is strictly prohibited. + +import torch +from .tables import * + +__all__ = [ + 'FlexiCubes' +] + + +class FlexiCubes: + def __init__(self, device="cuda"): + + self.device = device + self.dmc_table = torch.tensor(dmc_table, dtype=torch.long, device=device, requires_grad=False) + self.num_vd_table = torch.tensor(num_vd_table, + dtype=torch.long, device=device, requires_grad=False) + self.check_table = torch.tensor( + check_table, + dtype=torch.long, device=device, requires_grad=False) + + self.tet_table = torch.tensor(tet_table, dtype=torch.long, device=device, requires_grad=False) + self.quad_split_1 = torch.tensor([0, 1, 2, 0, 2, 3], dtype=torch.long, device=device, requires_grad=False) + self.quad_split_2 = torch.tensor([0, 1, 3, 3, 1, 2], dtype=torch.long, device=device, requires_grad=False) + self.quad_split_train = torch.tensor( + [0, 1, 1, 2, 2, 3, 3, 0], dtype=torch.long, device=device, requires_grad=False) + + self.cube_corners = torch.tensor([[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [ + 1, 0, 1], [0, 1, 1], [1, 1, 1]], dtype=torch.float, device=device) + self.cube_corners_idx = torch.pow(2, torch.arange(8, requires_grad=False)) + self.cube_edges = torch.tensor([0, 1, 1, 5, 4, 5, 0, 4, 2, 3, 3, 7, 6, 7, 2, 6, + 2, 0, 3, 1, 7, 5, 6, 4], dtype=torch.long, device=device, requires_grad=False) + + self.edge_dir_table = torch.tensor([0, 2, 0, 2, 0, 2, 0, 2, 1, 1, 1, 1], + dtype=torch.long, device=device) + self.dir_faces_table = torch.tensor([ + [[5, 4], [3, 2], [4, 5], [2, 3]], + [[5, 4], [1, 0], [4, 5], [0, 1]], + [[3, 2], [1, 0], [2, 3], [0, 1]] + ], dtype=torch.long, device=device) + self.adj_pairs = torch.tensor([0, 1, 1, 3, 3, 2, 2, 0], dtype=torch.long, device=device) + + def __call__(self, voxelgrid_vertices, scalar_field, cube_idx, resolution, qef_reg_scale=1e-3, + weight_scale=0.99, beta=None, alpha=None, gamma_f=None, voxelgrid_colors=None, training=False): + num_vertices = voxelgrid_vertices.shape[0] + num_cubes = cube_idx.shape[0] + + surf_cubes, occ_fx8 = self._identify_surf_cubes(scalar_field, cube_idx) + if surf_cubes.sum() == 0: + return ( + torch.zeros((0, 3), device=self.device), + torch.zeros((0, 3), dtype=torch.long, device=self.device), + torch.zeros((0), device=self.device), + torch.zeros((0, voxelgrid_colors.shape[-1]), device=self.device) if voxelgrid_colors is not None else None + ) + beta, alpha, gamma_f = self._normalize_weights( + beta, alpha, gamma_f, surf_cubes, weight_scale) + + if voxelgrid_colors is not None: + voxelgrid_colors = torch.sigmoid(voxelgrid_colors) + + case_ids = self._get_case_id(occ_fx8, surf_cubes, resolution) + + surf_edges, idx_map, edge_counts, surf_edges_mask = self._identify_surf_edges( + scalar_field, cube_idx, surf_cubes + ) + + vd, L_dev, vd_gamma, vd_idx_map, vd_color = self._compute_vd( + voxelgrid_vertices, cube_idx[surf_cubes], surf_edges, scalar_field, + case_ids, beta, alpha, gamma_f, idx_map, qef_reg_scale, voxelgrid_colors) + vertices, faces, s_edges, edge_indices, vertices_color = self._triangulate( + scalar_field, surf_edges, vd, vd_gamma, edge_counts, idx_map, + vd_idx_map, surf_edges_mask, training, vd_color) + return vertices, faces, L_dev, vertices_color + + def _compute_reg_loss(self, vd, ue, edge_group_to_vd, vd_num_edges): + """ + Regularizer L_dev as in Equation 8 + """ + dist = torch.norm(ue - torch.index_select(input=vd, index=edge_group_to_vd, dim=0), dim=-1) + mean_l2 = torch.zeros_like(vd[:, 0]) + mean_l2 = (mean_l2).index_add_(0, edge_group_to_vd, dist) / vd_num_edges.squeeze(1).float() + mad = (dist - torch.index_select(input=mean_l2, index=edge_group_to_vd, dim=0)).abs() + return mad + + def _normalize_weights(self, beta, alpha, gamma_f, surf_cubes, weight_scale): + """ + Normalizes the given weights to be non-negative. If input weights are None, it creates and returns a set of weights of ones. + """ + n_cubes = surf_cubes.shape[0] + + if beta is not None: + beta = (torch.tanh(beta) * weight_scale + 1) + else: + beta = torch.ones((n_cubes, 12), dtype=torch.float, device=self.device) + + if alpha is not None: + alpha = (torch.tanh(alpha) * weight_scale + 1) + else: + alpha = torch.ones((n_cubes, 8), dtype=torch.float, device=self.device) + + if gamma_f is not None: + gamma_f = torch.sigmoid(gamma_f) * weight_scale + (1 - weight_scale) / 2 + else: + gamma_f = torch.ones((n_cubes), dtype=torch.float, device=self.device) + + return beta[surf_cubes], alpha[surf_cubes], gamma_f[surf_cubes] + + @torch.no_grad() + def _get_case_id(self, occ_fx8, surf_cubes, res): + """ + Obtains the ID of topology cases based on cell corner occupancy. This function resolves the + ambiguity in the Dual Marching Cubes (DMC) configurations as described in Section 1.3 of the + supplementary material. It should be noted that this function assumes a regular grid. + """ + case_ids = (occ_fx8[surf_cubes] * self.cube_corners_idx.to(self.device).unsqueeze(0)).sum(-1) + + problem_config = self.check_table.to(self.device)[case_ids] + to_check = problem_config[..., 0] == 1 + problem_config = problem_config[to_check] + if not isinstance(res, (list, tuple)): + res = [res, res, res] + + # The 'problematic_configs' only contain configurations for surface cubes. Next, we construct a 3D array, + # 'problem_config_full', to store configurations for all cubes (with default config for non-surface cubes). + # This allows efficient checking on adjacent cubes. + problem_config_full = torch.zeros(list(res) + [5], device=self.device, dtype=torch.long) + vol_idx = torch.nonzero(problem_config_full[..., 0] == 0) # N, 3 + vol_idx_problem = vol_idx[surf_cubes][to_check] + problem_config_full[vol_idx_problem[..., 0], vol_idx_problem[..., 1], vol_idx_problem[..., 2]] = problem_config + vol_idx_problem_adj = vol_idx_problem + problem_config[..., 1:4] + + within_range = ( + vol_idx_problem_adj[..., 0] >= 0) & ( + vol_idx_problem_adj[..., 0] < res[0]) & ( + vol_idx_problem_adj[..., 1] >= 0) & ( + vol_idx_problem_adj[..., 1] < res[1]) & ( + vol_idx_problem_adj[..., 2] >= 0) & ( + vol_idx_problem_adj[..., 2] < res[2]) + + vol_idx_problem = vol_idx_problem[within_range] + vol_idx_problem_adj = vol_idx_problem_adj[within_range] + problem_config = problem_config[within_range] + problem_config_adj = problem_config_full[vol_idx_problem_adj[..., 0], + vol_idx_problem_adj[..., 1], vol_idx_problem_adj[..., 2]] + # If two cubes with cases C16 and C19 share an ambiguous face, both cases are inverted. + to_invert = (problem_config_adj[..., 0] == 1) + idx = torch.arange(case_ids.shape[0], device=self.device)[to_check][within_range][to_invert] + case_ids.index_put_((idx,), problem_config[to_invert][..., -1]) + return case_ids + + @torch.no_grad() + def _identify_surf_edges(self, scalar_field, cube_idx, surf_cubes): + """ + Identifies grid edges that intersect with the underlying surface by checking for opposite signs. As each edge + can be shared by multiple cubes, this function also assigns a unique index to each surface-intersecting edge + and marks the cube edges with this index. + """ + occ_n = scalar_field < 0 + all_edges = cube_idx[surf_cubes][:, self.cube_edges].reshape(-1, 2) + unique_edges, _idx_map, counts = torch.unique(all_edges, dim=0, return_inverse=True, return_counts=True) + + unique_edges = unique_edges.long() + mask_edges = occ_n[unique_edges.reshape(-1)].reshape(-1, 2).sum(-1) == 1 + + surf_edges_mask = mask_edges[_idx_map] + counts = counts[_idx_map] + + mapping = torch.ones((unique_edges.shape[0]), dtype=torch.long, device=cube_idx.device) * -1 + mapping[mask_edges] = torch.arange(mask_edges.sum(), device=cube_idx.device) + # Shaped as [number of cubes x 12 edges per cube]. This is later used to map a cube edge to the unique index + # for a surface-intersecting edge. Non-surface-intersecting edges are marked with -1. + idx_map = mapping[_idx_map] + surf_edges = unique_edges[mask_edges] + return surf_edges, idx_map, counts, surf_edges_mask + + @torch.no_grad() + def _identify_surf_cubes(self, scalar_field, cube_idx): + """ + Identifies grid cubes that intersect with the underlying surface by checking if the signs at + all corners are not identical. + """ + occ_n = scalar_field < 0 + occ_fx8 = occ_n[cube_idx.reshape(-1)].reshape(-1, 8) + _occ_sum = torch.sum(occ_fx8, -1) + surf_cubes = (_occ_sum > 0) & (_occ_sum < 8) + return surf_cubes, occ_fx8 + + def _linear_interp(self, edges_weight, edges_x): + """ + Computes the location of zero-crossings on 'edges_x' using linear interpolation with 'edges_weight'. + """ + edge_dim = edges_weight.dim() - 2 + assert edges_weight.shape[edge_dim] == 2 + edges_weight = torch.cat([torch.index_select(input=edges_weight, index=torch.tensor(1, device=self.device), dim=edge_dim), - + torch.index_select(input=edges_weight, index=torch.tensor(0, device=self.device), dim=edge_dim)] + , edge_dim) + denominator = edges_weight.sum(edge_dim) + ue = (edges_x * edges_weight).sum(edge_dim) / denominator + return ue + + def _solve_vd_QEF(self, p_bxnx3, norm_bxnx3, c_bx3, qef_reg_scale): + p_bxnx3 = p_bxnx3.reshape(-1, 7, 3) + norm_bxnx3 = norm_bxnx3.reshape(-1, 7, 3) + c_bx3 = c_bx3.reshape(-1, 3) + A = norm_bxnx3 + B = ((p_bxnx3) * norm_bxnx3).sum(-1, keepdims=True) + + A_reg = (torch.eye(3, device=p_bxnx3.device) * qef_reg_scale).unsqueeze(0).repeat(p_bxnx3.shape[0], 1, 1) + B_reg = (qef_reg_scale * c_bx3).unsqueeze(-1) + A = torch.cat([A, A_reg], 1) + B = torch.cat([B, B_reg], 1) + dual_verts = torch.linalg.lstsq(A, B).solution.squeeze(-1) + return dual_verts + + def _compute_vd(self, voxelgrid_vertices, surf_cubes_fx8, surf_edges, scalar_field, + case_ids, beta, alpha, gamma_f, idx_map, qef_reg_scale, voxelgrid_colors): + """ + Computes the location of dual vertices as described in Section 4.2 + """ + alpha_nx12x2 = torch.index_select(input=alpha, index=self.cube_edges, dim=1).reshape(-1, 12, 2) + surf_edges_x = torch.index_select(input=voxelgrid_vertices, index=surf_edges.reshape(-1), dim=0).reshape(-1, 2, 3) + surf_edges_s = torch.index_select(input=scalar_field, index=surf_edges.reshape(-1), dim=0).reshape(-1, 2, 1) + zero_crossing = self._linear_interp(surf_edges_s, surf_edges_x) + + if voxelgrid_colors is not None: + C = voxelgrid_colors.shape[-1] + surf_edges_c = torch.index_select(input=voxelgrid_colors, index=surf_edges.reshape(-1), dim=0).reshape(-1, 2, C) + + idx_map = idx_map.reshape(-1, 12) + num_vd = torch.index_select(input=self.num_vd_table, index=case_ids, dim=0) + edge_group, edge_group_to_vd, edge_group_to_cube, vd_num_edges, vd_gamma = [], [], [], [], [] + + # if color is not None: + # vd_color = [] + + total_num_vd = 0 + vd_idx_map = torch.zeros((case_ids.shape[0], 12), dtype=torch.long, device=self.device, requires_grad=False) + + for num in torch.unique(num_vd): + cur_cubes = (num_vd == num) # consider cubes with the same numbers of vd emitted (for batching) + curr_num_vd = cur_cubes.sum() * num + curr_edge_group = self.dmc_table[case_ids[cur_cubes], :num].reshape(-1, num * 7) + curr_edge_group_to_vd = torch.arange( + curr_num_vd, device=self.device).unsqueeze(-1).repeat(1, 7) + total_num_vd + total_num_vd += curr_num_vd + curr_edge_group_to_cube = torch.arange(idx_map.shape[0], device=self.device)[ + cur_cubes].unsqueeze(-1).repeat(1, num * 7).reshape_as(curr_edge_group) + + curr_mask = (curr_edge_group != -1) + edge_group.append(torch.masked_select(curr_edge_group, curr_mask)) + edge_group_to_vd.append(torch.masked_select(curr_edge_group_to_vd.reshape_as(curr_edge_group), curr_mask)) + edge_group_to_cube.append(torch.masked_select(curr_edge_group_to_cube, curr_mask)) + vd_num_edges.append(curr_mask.reshape(-1, 7).sum(-1, keepdims=True)) + vd_gamma.append(torch.masked_select(gamma_f, cur_cubes).unsqueeze(-1).repeat(1, num).reshape(-1)) + # if color is not None: + # vd_color.append(color[cur_cubes].unsqueeze(1).repeat(1, num, 1).reshape(-1, 3)) + + edge_group = torch.cat(edge_group) + edge_group_to_vd = torch.cat(edge_group_to_vd) + edge_group_to_cube = torch.cat(edge_group_to_cube) + vd_num_edges = torch.cat(vd_num_edges) + vd_gamma = torch.cat(vd_gamma) + # if color is not None: + # vd_color = torch.cat(vd_color) + # else: + # vd_color = None + + vd = torch.zeros((total_num_vd, 3), device=self.device) + beta_sum = torch.zeros((total_num_vd, 1), device=self.device) + + idx_group = torch.gather(input=idx_map.reshape(-1), dim=0, index=edge_group_to_cube * 12 + edge_group) + + x_group = torch.index_select(input=surf_edges_x, index=idx_group.reshape(-1), dim=0).reshape(-1, 2, 3) + s_group = torch.index_select(input=surf_edges_s, index=idx_group.reshape(-1), dim=0).reshape(-1, 2, 1) + + + zero_crossing_group = torch.index_select( + input=zero_crossing, index=idx_group.reshape(-1), dim=0).reshape(-1, 3) + + alpha_group = torch.index_select(input=alpha_nx12x2.reshape(-1, 2), dim=0, + index=edge_group_to_cube * 12 + edge_group).reshape(-1, 2, 1) + ue_group = self._linear_interp(s_group * alpha_group, x_group) + + beta_group = torch.gather(input=beta.reshape(-1), dim=0, + index=edge_group_to_cube * 12 + edge_group).reshape(-1, 1) + beta_sum = beta_sum.index_add_(0, index=edge_group_to_vd, source=beta_group) + vd = vd.index_add_(0, index=edge_group_to_vd, source=ue_group * beta_group) / beta_sum + + ''' + interpolate colors use the same method as dual vertices + ''' + if voxelgrid_colors is not None: + vd_color = torch.zeros((total_num_vd, C), device=self.device) + c_group = torch.index_select(input=surf_edges_c, index=idx_group.reshape(-1), dim=0).reshape(-1, 2, C) + uc_group = self._linear_interp(s_group * alpha_group, c_group) + vd_color = vd_color.index_add_(0, index=edge_group_to_vd, source=uc_group * beta_group) / beta_sum + else: + vd_color = None + + L_dev = self._compute_reg_loss(vd, zero_crossing_group, edge_group_to_vd, vd_num_edges) + + v_idx = torch.arange(vd.shape[0], device=self.device) # + total_num_vd + + vd_idx_map = (vd_idx_map.reshape(-1)).scatter(dim=0, index=edge_group_to_cube * + 12 + edge_group, src=v_idx[edge_group_to_vd]) + + return vd, L_dev, vd_gamma, vd_idx_map, vd_color + + def _triangulate(self, scalar_field, surf_edges, vd, vd_gamma, edge_counts, idx_map, vd_idx_map, surf_edges_mask, training, vd_color): + """ + Connects four neighboring dual vertices to form a quadrilateral. The quadrilaterals are then split into + triangles based on the gamma parameter, as described in Section 4.3. + """ + with torch.no_grad(): + group_mask = (edge_counts == 4) & surf_edges_mask # surface edges shared by 4 cubes. + group = idx_map.reshape(-1)[group_mask] + vd_idx = vd_idx_map[group_mask] + edge_indices, indices = torch.sort(group, stable=True) + quad_vd_idx = vd_idx[indices].reshape(-1, 4) + + # Ensure all face directions point towards the positive SDF to maintain consistent winding. + s_edges = scalar_field[surf_edges[edge_indices.reshape(-1, 4)[:, 0]].reshape(-1)].reshape(-1, 2) + flip_mask = s_edges[:, 0] > 0 + quad_vd_idx = torch.cat((quad_vd_idx[flip_mask][:, [0, 1, 3, 2]], + quad_vd_idx[~flip_mask][:, [2, 3, 1, 0]])) + + quad_gamma = torch.index_select(input=vd_gamma, index=quad_vd_idx.reshape(-1), dim=0).reshape(-1, 4) + gamma_02 = quad_gamma[:, 0] * quad_gamma[:, 2] + gamma_13 = quad_gamma[:, 1] * quad_gamma[:, 3] + if not training: + mask = (gamma_02 > gamma_13) + faces = torch.zeros((quad_gamma.shape[0], 6), dtype=torch.long, device=quad_vd_idx.device) + faces[mask] = quad_vd_idx[mask][:, self.quad_split_1] + faces[~mask] = quad_vd_idx[~mask][:, self.quad_split_2] + faces = faces.reshape(-1, 3) + else: + vd_quad = torch.index_select(input=vd, index=quad_vd_idx.reshape(-1), dim=0).reshape(-1, 4, 3) + vd_02 = (vd_quad[:, 0] + vd_quad[:, 2]) / 2 + vd_13 = (vd_quad[:, 1] + vd_quad[:, 3]) / 2 + weight_sum = (gamma_02 + gamma_13) + 1e-8 + vd_center = (vd_02 * gamma_02.unsqueeze(-1) + vd_13 * gamma_13.unsqueeze(-1)) / weight_sum.unsqueeze(-1) + + if vd_color is not None: + color_quad = torch.index_select(input=vd_color, index=quad_vd_idx.reshape(-1), dim=0).reshape(-1, 4, vd_color.shape[-1]) + color_02 = (color_quad[:, 0] + color_quad[:, 2]) / 2 + color_13 = (color_quad[:, 1] + color_quad[:, 3]) / 2 + color_center = (color_02 * gamma_02.unsqueeze(-1) + color_13 * gamma_13.unsqueeze(-1)) / weight_sum.unsqueeze(-1) + vd_color = torch.cat([vd_color, color_center]) + + + vd_center_idx = torch.arange(vd_center.shape[0], device=self.device) + vd.shape[0] + vd = torch.cat([vd, vd_center]) + faces = quad_vd_idx[:, self.quad_split_train].reshape(-1, 4, 2) + faces = torch.cat([faces, vd_center_idx.reshape(-1, 1, 1).repeat(1, 4, 1)], -1).reshape(-1, 3) + return vd, faces, s_edges, edge_indices, vd_color diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/mc2mesh.py b/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/mc2mesh.py new file mode 100644 index 0000000000000000000000000000000000000000..7f88be01f938f664eb35d9d62c1bd32846fca2e8 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/mc2mesh.py @@ -0,0 +1,216 @@ +import torch +from easydict import EasyDict as edict +from typing import Tuple, Optional +from diso import DiffDMC +from .cube2mesh import MeshExtractResult +from .utils_cube import * +from ...modules.sparse import SparseTensor + +class EnhancedMarchingCubes: + def __init__(self, device="cuda"): + self.device = device + self.diffdmc = DiffDMC(dtype=torch.float32) + + def __call__(self, + voxelgrid_vertices: torch.Tensor, + scalar_field: torch.Tensor, + voxelgrid_colors: Optional[torch.Tensor] = None, + training: bool = False + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: + """ + Enhanced Marching Cubes implementation using DiffDMC that handles deformations and colors + """ + if scalar_field.dim() == 1: + grid_size = int(round(scalar_field.shape[0] ** (1 / 3))) + scalar_field = scalar_field.reshape(grid_size, grid_size, grid_size) + elif scalar_field.dim() > 3: + scalar_field = scalar_field.squeeze() + + if scalar_field.dim() != 3: + raise ValueError(f"Expected 3D array, got shape {scalar_field.shape}") + + # Normalize coordinates for DiffDMC + scalar_field = scalar_field.to(self.device) + + # Get deformation field if provided + deform_field = None + if voxelgrid_vertices is not None: + if voxelgrid_vertices.dim() == 2: + grid_size = int(round(voxelgrid_vertices.shape[0] ** (1 / 3))) + voxelgrid_vertices = voxelgrid_vertices.reshape(grid_size, grid_size, grid_size, 3) + deform_field = voxelgrid_vertices.to(self.device) + + # Run DiffDMC + vertices, faces = self.diffdmc( + scalar_field, + deform_field, + isovalue=0.0 + ) + + # Handle colors if provided + colors = None + if voxelgrid_colors is not None: + voxelgrid_colors = torch.sigmoid(voxelgrid_colors) + if voxelgrid_colors.dim() == 2: + grid_size = int(round(voxelgrid_colors.shape[0] ** (1/3))) + voxelgrid_colors = voxelgrid_colors.reshape(grid_size, grid_size, grid_size, -1) + + grid_positions = vertices.clone() * grid_size + grid_coords = grid_positions.long() + local_coords = grid_positions - grid_coords.float() + + # Clamp coordinates to grid bounds + grid_coords = torch.clamp(grid_coords, 0, voxelgrid_colors.shape[0] - 1) + + # Trilinear interpolation for colors + colors = self._interpolate_color(grid_coords, local_coords, voxelgrid_colors) + + vertices = vertices * 2 - 1 # Normalize vertices to [-1, 1] + vertices /= 2.0 # Normalize vertices to [-0.5, 0.5] + + # Compute deviation loss for training + deviation_loss = torch.tensor(0.0, device=self.device) + if training and deform_field is not None: + # Compute deviation between original and deformed vertices + deviation_loss = self._compute_deviation_loss(vertices, deform_field) + + # faces = faces.flip(dims=[1]) # Maintain consistent face orientation + + return vertices, faces, deviation_loss, colors + + def _interpolate_color(self, grid_coords: torch.Tensor, + local_coords: torch.Tensor, + color_field: torch.Tensor) -> torch.Tensor: + """ + Interpolate colors using trilinear interpolation + Args: + grid_coords: (N, 3) integer grid coordinates + local_coords: (N, 3) fractional positions within grid cells + color_field: (res, res, res, C) color values + """ + x, y, z = local_coords[:, 0], local_coords[:, 1], local_coords[:, 2] + + # Get corner values for each vertex + c000 = color_field[grid_coords[:, 0], grid_coords[:, 1], grid_coords[:, 2]] + c001 = color_field[grid_coords[:, 0], grid_coords[:, 1], + torch.clamp(grid_coords[:, 2] + 1, 0, color_field.shape[2] - 1)] + c010 = color_field[grid_coords[:, 0], + torch.clamp(grid_coords[:, 1] + 1, 0, color_field.shape[1] - 1), + grid_coords[:, 2]] + c011 = color_field[grid_coords[:, 0], + torch.clamp(grid_coords[:, 1] + 1, 0, color_field.shape[1] - 1), + torch.clamp(grid_coords[:, 2] + 1, 0, color_field.shape[2] - 1)] + c100 = color_field[torch.clamp(grid_coords[:, 0] + 1, 0, color_field.shape[0] - 1), + grid_coords[:, 1], grid_coords[:, 2]] + c101 = color_field[torch.clamp(grid_coords[:, 0] + 1, 0, color_field.shape[0] - 1), + grid_coords[:, 1], + torch.clamp(grid_coords[:, 2] + 1, 0, color_field.shape[2] - 1)] + c110 = color_field[torch.clamp(grid_coords[:, 0] + 1, 0, color_field.shape[0] - 1), + torch.clamp(grid_coords[:, 1] + 1, 0, color_field.shape[1] - 1), + grid_coords[:, 2]] + c111 = color_field[torch.clamp(grid_coords[:, 0] + 1, 0, color_field.shape[0] - 1), + torch.clamp(grid_coords[:, 1] + 1, 0, color_field.shape[1] - 1), + torch.clamp(grid_coords[:, 2] + 1, 0, color_field.shape[2] - 1)] + + # Interpolate along x axis + c00 = c000 * (1 - x)[:, None] + c100 * x[:, None] + c01 = c001 * (1 - x)[:, None] + c101 * x[:, None] + c10 = c010 * (1 - x)[:, None] + c110 * x[:, None] + c11 = c011 * (1 - x)[:, None] + c111 * x[:, None] + + # Interpolate along y axis + c0 = c00 * (1 - y)[:, None] + c10 * y[:, None] + c1 = c01 * (1 - y)[:, None] + c11 * y[:, None] + + # Interpolate along z axis + colors = c0 * (1 - z)[:, None] + c1 * z[:, None] + + return colors + + def _compute_deviation_loss(self, vertices: torch.Tensor, + deform_field: torch.Tensor) -> torch.Tensor: + """Compute deviation loss for training""" + # Since DiffDMC already handles the deformation, we compute the loss + # based on the magnitude of the deformation field + return torch.mean(deform_field ** 2) + +class SparseFeatures2MCMesh: + def __init__(self, device="cuda", res=128, use_color=True): + super().__init__() + self.device = device + + self.res = res + + self.mesh_extractor = EnhancedMarchingCubes(device=device) + self.sdf_bias = -1.0 / res + verts, cube = construct_dense_grid(self.res, self.device) + self.reg_c = cube.to(self.device) + self.reg_v = verts.to(self.device) + self.use_color = use_color + self._calc_layout() + + def _calc_layout(self): + LAYOUTS = { + 'sdf': {'shape': (8, 1), 'size': 8}, + 'deform': {'shape': (8, 3), 'size': 8 * 3}, + 'weights': {'shape': (21,), 'size': 21} + } + if self.use_color: + ''' + 6 channel color including normal map + ''' + LAYOUTS['color'] = {'shape': (8, 6,), 'size': 8 * 6} + self.layouts = edict(LAYOUTS) + start = 0 + for k, v in self.layouts.items(): + v['range'] = (start, start + v['size']) + start += v['size'] + self.feats_channels = start + + def get_layout(self, feats: torch.Tensor, name: str): + if name not in self.layouts: + return None + return feats[:, self.layouts[name]['range'][0]:self.layouts[name]['range'][1]].reshape(-1, *self.layouts[name][ + 'shape']) + + def __call__(self, cubefeats: SparseTensor, training=False): + coords = cubefeats.coords[:, 1:] + feats = cubefeats.feats + + sdf, deform, color, weights = [self.get_layout(feats, name) + for name in ['sdf', 'deform', 'color', 'weights']] + sdf += self.sdf_bias + v_attrs = [sdf, deform, color] if self.use_color else [sdf, deform] + v_pos, v_attrs, reg_loss = sparse_cube2verts(coords, torch.cat(v_attrs, dim=-1), + training=training) + + v_attrs_d = get_dense_attrs(v_pos, v_attrs, res=self.res + 1, sdf_init=True) + + if self.use_color: + sdf_d, deform_d, colors_d = (v_attrs_d[..., 0], v_attrs_d[..., 1:4], + v_attrs_d[..., 4:]) + else: + sdf_d, deform_d = v_attrs_d[..., 0], v_attrs_d[..., 1:4] + colors_d = None + + x_nx3 = get_defomed_verts(self.reg_v, deform_d, self.res) + + vertices, faces, L_dev, colors = self.mesh_extractor( + voxelgrid_vertices=x_nx3, + scalar_field=sdf_d, + voxelgrid_colors=colors_d, + training=training + ) + + mesh = MeshExtractResult(vertices=vertices, faces=faces, + vertex_attrs=colors, res=self.res) + + if training: + if mesh.success: + reg_loss += L_dev.mean() * 0.5 + reg_loss += (weights[:, :20]).abs().mean() * 0.2 + mesh.reg_loss = reg_loss + mesh.tsdf_v = get_defomed_verts(v_pos, v_attrs[:, 1:4], self.res) + mesh.tsdf_s = v_attrs[:, 0] + + return mesh \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/tables.py b/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/tables.py new file mode 100644 index 0000000000000000000000000000000000000000..7c02dd7f4133aef487f623c02b11e3075cab0916 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/tables.py @@ -0,0 +1,791 @@ +# Copyright (c) 2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# NVIDIA CORPORATION & AFFILIATES and its licensors retain all intellectual property +# and proprietary rights in and to this software, related documentation +# and any modifications thereto. Any use, reproduction, disclosure or +# distribution of this software and related documentation without an express +# license agreement from NVIDIA CORPORATION & AFFILIATES is strictly prohibited. +dmc_table = [ +[[-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 8, 9, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 7, 8, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 4, 7, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [4, 7, 8, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 4, 7, 9, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 5, 9, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [4, 5, 9, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 4, 5, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 4, 5, 8, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[5, 7, 8, 9, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 5, 7, 9, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 5, 7, 8, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 5, 7, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 8, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [2, 3, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 8, 9, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 7, 8, -1, -1, -1, -1], [2, 3, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 4, 7, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [4, 7, 8, -1, -1, -1, -1], [2, 3, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 4, 7, 9, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 5, 9, -1, -1, -1, -1], [2, 3, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 8, 11, -1, -1, -1], [4, 5, 9, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 4, 5, -1, -1, -1], [2, 3, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 4, 5, 8, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[5, 7, 8, 9, -1, -1, -1], [2, 3, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 5, 7, 9, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 5, 7, 8, -1, -1], [2, 3, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 5, 7, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [1, 2, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 9, 10, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 8, 9, 10, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 7, 8, -1, -1, -1, -1], [1, 2, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 4, 7, -1, -1, -1], [1, 2, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 9, 10, -1, -1, -1], [4, 7, 8, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 4, 7, 9, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 5, 9, -1, -1, -1, -1], [1, 2, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [4, 5, 9, -1, -1, -1, -1], [1, 2, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 4, 5, 10, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 4, 5, 8, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[5, 7, 8, 9, -1, -1, -1], [1, 2, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 5, 7, 9, -1, -1], [1, 2, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 5, 7, 8, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 5, 7, 10, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 10, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 8, 10, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 9, 10, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[8, 9, 10, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 7, 8, -1, -1, -1, -1], [1, 3, 10, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 4, 7, 10, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 9, 10, 11, -1, -1], [4, 7, 8, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 7, 9, 10, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 5, 9, -1, -1, -1, -1], [1, 3, 10, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 8, 10, 11, -1, -1], [4, 5, 9, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 4, 5, 10, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 5, 8, 10, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[5, 7, 8, 9, -1, -1, -1], [1, 3, 10, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 5, 7, 9, 10, 11], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 5, 7, 8, 10, 11], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[5, 7, 10, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 8, 9, -1, -1, -1], [6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 6, 8, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 4, 6, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [4, 6, 8, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 4, 6, 9, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 5, 9, -1, -1, -1, -1], [6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [4, 5, 9, -1, -1, -1, -1], [6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 4, 5, -1, -1, -1], [6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 4, 5, 8, -1, -1], [6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[5, 6, 8, 9, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 5, 6, 9, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 5, 6, 8, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 5, 6, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 6, 7, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 6, 7, 8, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [2, 3, 6, 7, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 6, 7, 8, 9, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 4, 6, 8, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 4, 6, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [2, 3, 4, 6, 8, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 4, 6, 9, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 5, 9, -1, -1, -1, -1], [2, 3, 6, 7, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 6, 7, 8, -1, -1], [4, 5, 9, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 4, 5, -1, -1, -1], [2, 3, 6, 7, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 4, 5, 6, 7, 8], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 5, 6, 8, 9, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 5, 6, 9, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 2, 3, 5, 6, 8], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 5, 6, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 10, -1, -1, -1, -1], [6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [1, 2, 10, -1, -1, -1, -1], [6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 9, 10, -1, -1, -1], [6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 8, 9, 10, -1, -1], [6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 6, 8, 11, -1, -1, -1], [1, 2, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 4, 6, 11, -1, -1], [1, 2, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 9, 10, -1, -1, -1], [4, 6, 8, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 4, 6, 9, 10, 11], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 5, 9, -1, -1, -1, -1], [1, 2, 10, -1, -1, -1, -1], [6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [4, 5, 9, -1, -1, -1, -1], [1, 2, 10, -1, -1, -1, -1], [6, 7, 11, -1, -1, -1, -1]], +[[0, 2, 4, 5, 10, -1, -1], [6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 4, 5, 8, 10, -1], [6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[5, 6, 8, 9, 11, -1, -1], [1, 2, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 5, 6, 9, 11, -1], [1, 2, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 5, 6, 8, 10, 11], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 5, 6, 10, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 6, 7, 10, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 6, 7, 8, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 6, 7, 9, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[6, 7, 8, 9, 10, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 4, 6, 8, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 4, 6, 10, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 4, 6, 8, 9, 10], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 6, 9, 10, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 5, 9, -1, -1, -1, -1], [1, 3, 6, 7, 10, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 6, 7, 8, 10, -1], [4, 5, 9, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 4, 5, 6, 7, 10], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 5, 6, 7, 8, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 5, 6, 8, 9, 10], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 5, 6, 9, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 8, 9, -1, -1, -1], [5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 7, 8, -1, -1, -1, -1], [5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 4, 7, -1, -1, -1], [5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [4, 7, 8, -1, -1, -1, -1], [5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 4, 7, 9, -1, -1], [5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 6, 9, 10, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [4, 6, 9, 10, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 4, 6, 10, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 4, 6, 8, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[6, 7, 8, 9, 10, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 6, 7, 9, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 6, 7, 8, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 6, 7, 10, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 11, -1, -1, -1, -1], [5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 8, 11, -1, -1, -1], [5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [2, 3, 11, -1, -1, -1, -1], [5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 8, 9, 11, -1, -1], [5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 7, 8, -1, -1, -1, -1], [2, 3, 11, -1, -1, -1, -1], [5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 4, 7, 11, -1, -1], [5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [4, 7, 8, -1, -1, -1, -1], [2, 3, 11, -1, -1, -1, -1], [5, 6, 10, -1, -1, -1, -1]], +[[1, 2, 4, 7, 9, 11, -1], [5, 6, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 6, 9, 10, -1, -1, -1], [2, 3, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 8, 11, -1, -1, -1], [4, 6, 9, 10, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 4, 6, 10, -1, -1], [2, 3, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 4, 6, 8, 10, 11], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[6, 7, 8, 9, 10, -1, -1], [2, 3, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 6, 7, 9, 10, 11], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 6, 7, 8, 10, -1], [2, 3, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 6, 7, 10, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 5, 6, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [1, 2, 5, 6, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 5, 6, 9, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 5, 6, 8, 9, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 7, 8, -1, -1, -1, -1], [1, 2, 5, 6, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 4, 7, -1, -1, -1], [1, 2, 5, 6, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 5, 6, 9, -1, -1], [4, 7, 8, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 4, 5, 6, 7, 9], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 4, 6, 9, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [1, 2, 4, 6, 9, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 4, 6, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 4, 6, 8, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 6, 7, 8, 9, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 2, 3, 6, 7, 9], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 6, 7, 8, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 6, 7, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 5, 6, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 5, 6, 8, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 5, 6, 9, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[5, 6, 8, 9, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 7, 8, -1, -1, -1, -1], [1, 3, 5, 6, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 4, 5, 6, 7, 11], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 5, 6, 9, 11, -1], [4, 7, 8, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 5, 6, 7, 9, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 4, 6, 9, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 4, 6, 8, 9, 11], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 4, 6, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 6, 8, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 6, 7, 8, 9, 11], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 6, 7, 8, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[6, 7, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[5, 7, 10, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [5, 7, 10, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [5, 7, 10, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 8, 9, -1, -1, -1], [5, 7, 10, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 5, 8, 10, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 4, 5, 10, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [4, 5, 8, 10, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 4, 5, 9, 10, 11], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 7, 9, 10, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [4, 7, 9, 10, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 4, 7, 10, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 4, 7, 8, 10, 11], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[8, 9, 10, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 9, 10, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 8, 10, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 10, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 5, 7, 10, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 5, 7, 8, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [2, 3, 5, 7, 10, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 5, 7, 8, 9, 10], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 4, 5, 8, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 4, 5, 10, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [2, 3, 4, 5, 8, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 4, 5, 9, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 4, 7, 9, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 4, 7, 8, 9, 10], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 2, 3, 4, 7, 10], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 7, 8, -1, -1, -1, -1], [1, 2, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 8, 9, 10, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 9, 10, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 2, 3, 8, 10, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 10, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 5, 7, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [1, 2, 5, 7, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 5, 7, 9, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 5, 7, 8, 9, 11], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 4, 5, 8, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 2, 3, 4, 5, 11], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 4, 5, 8, 9, 11], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 5, 9, -1, -1, -1, -1], [2, 3, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 4, 7, 9, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [1, 2, 4, 7, 9, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 4, 7, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 4, 7, 8, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 2, 8, 9, 11, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 2, 3, 9, 11, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 2, 8, 11, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[2, 3, 11, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 5, 7, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 5, 7, 8, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 5, 7, 9, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[5, 7, 8, 9, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 4, 5, 8, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 4, 5, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 4, 5, 8, 9, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 5, 9, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 4, 7, 9, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 4, 7, 8, 9, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 4, 7, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[4, 7, 8, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[1, 3, 8, 9, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 1, 9, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[0, 3, 8, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]], +[[-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1]] +] +num_vd_table = [0, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 2, 2, +2, 1, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 2, 1, 2, 3, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 2, +1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 1, 1, 2, 2, 2, 1, 1, 2, 1, 2, 3, 2, 2, 1, 1, 1, 1, +1, 1, 2, 1, 1, 1, 2, 1, 2, 2, 2, 1, 1, 1, 1, 1, 2, 3, 2, 2, 2, 2, 2, 1, 3, 4, 2, +2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 2, 1, 1, 2, 2, 2, 2, 2, +3, 2, 1, 2, 1, 1, 1, 1, 1, 1, 2, 2, 3, 2, 3, 2, 4, 2, 2, 2, 2, 1, 2, 1, 2, 1, 1, +2, 1, 1, 2, 2, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, +1, 2, 1, 1, 1, 2, 2, 2, 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, +1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, +1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0] +check_table = [ +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 1, 0, 0, 194], +[1, -1, 0, 0, 193], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 0, 1, 0, 164], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 0, -1, 0, 161], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 0, 0, 1, 152], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 0, 0, 1, 145], +[1, 0, 0, 1, 144], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 0, 0, -1, 137], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 0, 1, 0, 133], +[1, 0, 1, 0, 132], +[1, 1, 0, 0, 131], +[1, 1, 0, 0, 130], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 0, 0, 1, 100], +[0, 0, 0, 0, 0], +[1, 0, 0, 1, 98], +[0, 0, 0, 0, 0], +[1, 0, 0, 1, 96], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 0, 1, 0, 88], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 0, -1, 0, 82], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 0, 1, 0, 74], +[0, 0, 0, 0, 0], +[1, 0, 1, 0, 72], +[0, 0, 0, 0, 0], +[1, 0, 0, -1, 70], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, -1, 0, 0, 67], +[0, 0, 0, 0, 0], +[1, -1, 0, 0, 65], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 1, 0, 0, 56], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, -1, 0, 0, 52], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 1, 0, 0, 44], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 1, 0, 0, 40], +[0, 0, 0, 0, 0], +[1, 0, 0, -1, 38], +[1, 0, -1, 0, 37], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 0, -1, 0, 33], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, -1, 0, 0, 28], +[0, 0, 0, 0, 0], +[1, 0, -1, 0, 26], +[1, 0, 0, -1, 25], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, -1, 0, 0, 20], +[0, 0, 0, 0, 0], +[1, 0, -1, 0, 18], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 0, 0, -1, 9], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[1, 0, 0, -1, 6], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0], +[0, 0, 0, 0, 0] +] +tet_table = [ +[-1, -1, -1, -1, -1, -1], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[1, 1, 1, 1, 1, 1], +[4, 4, 4, 4, 4, 4], +[0, 0, 0, 0, 0, 0], +[4, 0, 0, 4, 4, -1], +[1, 1, 1, 1, 1, 1], +[4, 4, 4, 4, 4, 4], +[0, 4, 0, 4, 4, -1], +[0, 0, 0, 0, 0, 0], +[1, 1, 1, 1, 1, 1], +[5, 5, 5, 5, 5, 5], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[1, 1, 1, 1, 1, 1], +[2, 2, 2, 2, 2, 2], +[0, 0, 0, 0, 0, 0], +[2, 0, 2, -1, 0, 2], +[1, 1, 1, 1, 1, 1], +[2, -1, 2, 4, 4, 2], +[0, 0, 0, 0, 0, 0], +[2, 0, 2, 4, 4, 2], +[1, 1, 1, 1, 1, 1], +[2, 4, 2, 4, 4, 2], +[0, 4, 0, 4, 4, 0], +[2, 0, 2, 0, 0, 2], +[1, 1, 1, 1, 1, 1], +[2, 5, 2, 5, 5, 2], +[0, 0, 0, 0, 0, 0], +[2, 0, 2, 0, 0, 2], +[1, 1, 1, 1, 1, 1], +[1, 1, 1, 1, 1, 1], +[0, 1, 1, -1, 0, 1], +[0, 0, 0, 0, 0, 0], +[2, 2, 2, 2, 2, 2], +[4, 1, 1, 4, 4, 1], +[0, 1, 1, 0, 0, 1], +[4, 0, 0, 4, 4, 0], +[2, 2, 2, 2, 2, 2], +[-1, 1, 1, 4, 4, 1], +[0, 1, 1, 4, 4, 1], +[0, 0, 0, 0, 0, 0], +[2, 2, 2, 2, 2, 2], +[5, 1, 1, 5, 5, 1], +[0, 1, 1, 0, 0, 1], +[0, 0, 0, 0, 0, 0], +[2, 2, 2, 2, 2, 2], +[1, 1, 1, 1, 1, 1], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[8, 8, 8, 8, 8, 8], +[1, 1, 1, 4, 4, 1], +[0, 0, 0, 0, 0, 0], +[4, 0, 0, 4, 4, 0], +[4, 4, 4, 4, 4, 4], +[1, 1, 1, 4, 4, 1], +[0, 4, 0, 4, 4, 0], +[0, 0, 0, 0, 0, 0], +[4, 4, 4, 4, 4, 4], +[1, 1, 1, 5, 5, 1], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[5, 5, 5, 5, 5, 5], +[6, 6, 6, 6, 6, 6], +[6, -1, 0, 6, 0, 6], +[6, 0, 0, 6, 0, 6], +[6, 1, 1, 6, 1, 6], +[4, 4, 4, 4, 4, 4], +[0, 0, 0, 0, 0, 0], +[4, 0, 0, 4, 4, 4], +[1, 1, 1, 1, 1, 1], +[6, 4, -1, 6, 4, 6], +[6, 4, 0, 6, 4, 6], +[6, 0, 0, 6, 0, 6], +[6, 1, 1, 6, 1, 6], +[5, 5, 5, 5, 5, 5], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[1, 1, 1, 1, 1, 1], +[2, 2, 2, 2, 2, 2], +[0, 0, 0, 0, 0, 0], +[2, 0, 2, 2, 0, 2], +[1, 1, 1, 1, 1, 1], +[2, 2, 2, 2, 2, 2], +[0, 0, 0, 0, 0, 0], +[2, 0, 2, 2, 2, 2], +[1, 1, 1, 1, 1, 1], +[2, 4, 2, 2, 4, 2], +[0, 4, 0, 4, 4, 0], +[2, 0, 2, 2, 0, 2], +[1, 1, 1, 1, 1, 1], +[2, 2, 2, 2, 2, 2], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[1, 1, 1, 1, 1, 1], +[6, 1, 1, 6, -1, 6], +[6, 1, 1, 6, 0, 6], +[6, 0, 0, 6, 0, 6], +[6, 2, 2, 6, 2, 6], +[4, 1, 1, 4, 4, 1], +[0, 1, 1, 0, 0, 1], +[4, 0, 0, 4, 4, 4], +[2, 2, 2, 2, 2, 2], +[6, 1, 1, 6, 4, 6], +[6, 1, 1, 6, 4, 6], +[6, 0, 0, 6, 0, 6], +[6, 2, 2, 6, 2, 6], +[5, 1, 1, 5, 5, 1], +[0, 1, 1, 0, 0, 1], +[0, 0, 0, 0, 0, 0], +[2, 2, 2, 2, 2, 2], +[1, 1, 1, 1, 1, 1], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[6, 6, 6, 6, 6, 6], +[1, 1, 1, 1, 1, 1], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[4, 4, 4, 4, 4, 4], +[1, 1, 1, 1, 4, 1], +[0, 4, 0, 4, 4, 0], +[0, 0, 0, 0, 0, 0], +[4, 4, 4, 4, 4, 4], +[1, 1, 1, 1, 1, 1], +[0, 0, 0, 0, 0, 0], +[0, 5, 0, 5, 0, 5], +[5, 5, 5, 5, 5, 5], +[5, 5, 5, 5, 5, 5], +[0, 5, 0, 5, 0, 5], +[-1, 5, 0, 5, 0, 5], +[1, 5, 1, 5, 1, 5], +[4, 5, -1, 5, 4, 5], +[0, 5, 0, 5, 0, 5], +[4, 5, 0, 5, 4, 5], +[1, 5, 1, 5, 1, 5], +[4, 4, 4, 4, 4, 4], +[0, 4, 0, 4, 4, 4], +[0, 0, 0, 0, 0, 0], +[1, 1, 1, 1, 1, 1], +[6, 6, 6, 6, 6, 6], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[1, 1, 1, 1, 1, 1], +[2, 5, 2, 5, -1, 5], +[0, 5, 0, 5, 0, 5], +[2, 5, 2, 5, 0, 5], +[1, 5, 1, 5, 1, 5], +[2, 5, 2, 5, 4, 5], +[0, 5, 0, 5, 0, 5], +[2, 5, 2, 5, 4, 5], +[1, 5, 1, 5, 1, 5], +[2, 4, 2, 4, 4, 2], +[0, 4, 0, 4, 4, 4], +[2, 0, 2, 0, 0, 2], +[1, 1, 1, 1, 1, 1], +[2, 6, 2, 6, 6, 2], +[0, 0, 0, 0, 0, 0], +[2, 0, 2, 0, 0, 2], +[1, 1, 1, 1, 1, 1], +[1, 1, 1, 1, 1, 1], +[0, 1, 1, 1, 0, 1], +[0, 0, 0, 0, 0, 0], +[2, 2, 2, 2, 2, 2], +[4, 1, 1, 1, 4, 1], +[0, 1, 1, 1, 0, 1], +[4, 0, 0, 4, 4, 0], +[2, 2, 2, 2, 2, 2], +[1, 1, 1, 1, 1, 1], +[0, 1, 1, 1, 1, 1], +[0, 0, 0, 0, 0, 0], +[2, 2, 2, 2, 2, 2], +[1, 1, 1, 1, 1, 1], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[2, 2, 2, 2, 2, 2], +[1, 1, 1, 1, 1, 1], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[5, 5, 5, 5, 5, 5], +[1, 1, 1, 1, 4, 1], +[0, 0, 0, 0, 0, 0], +[4, 0, 0, 4, 4, 0], +[4, 4, 4, 4, 4, 4], +[1, 1, 1, 1, 1, 1], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[4, 4, 4, 4, 4, 4], +[1, 1, 1, 1, 1, 1], +[6, 0, 0, 6, 0, 6], +[0, 0, 0, 0, 0, 0], +[6, 6, 6, 6, 6, 6], +[5, 5, 5, 5, 5, 5], +[5, 5, 0, 5, 0, 5], +[5, 5, 0, 5, 0, 5], +[5, 5, 1, 5, 1, 5], +[4, 4, 4, 4, 4, 4], +[0, 0, 0, 0, 0, 0], +[4, 4, 0, 4, 4, 4], +[1, 1, 1, 1, 1, 1], +[4, 4, 4, 4, 4, 4], +[4, 4, 0, 4, 4, 4], +[0, 0, 0, 0, 0, 0], +[1, 1, 1, 1, 1, 1], +[8, 8, 8, 8, 8, 8], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[1, 1, 1, 1, 1, 1], +[2, 2, 2, 2, 2, 2], +[0, 0, 0, 0, 0, 0], +[2, 2, 2, 2, 0, 2], +[1, 1, 1, 1, 1, 1], +[2, 2, 2, 2, 2, 2], +[0, 0, 0, 0, 0, 0], +[2, 2, 2, 2, 2, 2], +[1, 1, 1, 1, 1, 1], +[2, 2, 2, 2, 2, 2], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[4, 1, 1, 4, 4, 1], +[2, 2, 2, 2, 2, 2], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[1, 1, 1, 1, 1, 1], +[1, 1, 1, 1, 1, 1], +[1, 1, 1, 1, 0, 1], +[0, 0, 0, 0, 0, 0], +[2, 2, 2, 2, 2, 2], +[1, 1, 1, 1, 1, 1], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[2, 4, 2, 4, 4, 2], +[1, 1, 1, 1, 1, 1], +[1, 1, 1, 1, 1, 1], +[0, 0, 0, 0, 0, 0], +[2, 2, 2, 2, 2, 2], +[1, 1, 1, 1, 1, 1], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[2, 2, 2, 2, 2, 2], +[1, 1, 1, 1, 1, 1], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[5, 5, 5, 5, 5, 5], +[1, 1, 1, 1, 1, 1], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[4, 4, 4, 4, 4, 4], +[1, 1, 1, 1, 1, 1], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[4, 4, 4, 4, 4, 4], +[1, 1, 1, 1, 1, 1], +[0, 0, 0, 0, 0, 0], +[0, 0, 0, 0, 0, 0], +[12, 12, 12, 12, 12, 12] +] \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/utils_cube.py b/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/utils_cube.py new file mode 100644 index 0000000000000000000000000000000000000000..23913c97bb2d57dfa0384667c69f9860ea0a4155 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/representations/mesh/utils_cube.py @@ -0,0 +1,61 @@ +import torch +cube_corners = torch.tensor([[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [ + 1, 0, 1], [0, 1, 1], [1, 1, 1]], dtype=torch.int) +cube_neighbor = torch.tensor([[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]]) +cube_edges = torch.tensor([0, 1, 1, 5, 4, 5, 0, 4, 2, 3, 3, 7, 6, 7, 2, 6, + 2, 0, 3, 1, 7, 5, 6, 4], dtype=torch.long, requires_grad=False) + +def construct_dense_grid(res, device='cuda'): + '''construct a dense grid based on resolution''' + res_v = res + 1 + vertsid = torch.arange(res_v ** 3, device=device) + coordsid = vertsid.reshape(res_v, res_v, res_v)[:res, :res, :res].flatten() + cube_corners_bias = (cube_corners[:, 0] * res_v + cube_corners[:, 1]) * res_v + cube_corners[:, 2] + cube_fx8 = (coordsid.unsqueeze(1) + cube_corners_bias.unsqueeze(0).to(device)) + verts = torch.stack([vertsid // (res_v ** 2), (vertsid // res_v) % res_v, vertsid % res_v], dim=1) + return verts, cube_fx8 + + +def construct_voxel_grid(coords): + verts = (cube_corners.unsqueeze(0).to(coords) + coords.unsqueeze(1)).reshape(-1, 3) + verts_unique, inverse_indices = torch.unique(verts, dim=0, return_inverse=True) + cubes = inverse_indices.reshape(-1, 8) + return verts_unique, cubes + + +def cubes_to_verts(num_verts, cubes, value, reduce='mean'): + """ + Args: + cubes [Vx8] verts index for each cube + value [Vx8xM] value to be scattered + Operation: + reduced[cubes[i][j]][k] += value[i][k] + """ + M = value.shape[2] # number of channels + reduced = torch.zeros(num_verts, M, device=cubes.device) + return torch.scatter_reduce(reduced, 0, + cubes.unsqueeze(-1).expand(-1, -1, M).flatten(0, 1), + value.flatten(0, 1), reduce=reduce, include_self=False) + +def sparse_cube2verts(coords, feats, training=True): + new_coords, cubes = construct_voxel_grid(coords) + new_feats = cubes_to_verts(new_coords.shape[0], cubes, feats) + if training: + con_loss = torch.mean((feats - new_feats[cubes]) ** 2) + else: + con_loss = 0.0 + return new_coords, new_feats, con_loss + + +def get_dense_attrs(coords : torch.Tensor, feats : torch.Tensor, res : int, sdf_init=True): + F = feats.shape[-1] + dense_attrs = torch.zeros([res] * 3 + [F], device=feats.device) + if sdf_init: + dense_attrs[..., 0] = 1 # initial outside sdf value + dense_attrs[coords[:, 0], coords[:, 1], coords[:, 2], :] = feats + return dense_attrs.reshape(-1, F) + + +def get_defomed_verts(v_pos : torch.Tensor, deform : torch.Tensor, res): + return v_pos / res - 0.5 + (1 - 1e-8) / (res * 2) * torch.tanh(deform) + \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/representations/octree/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/representations/octree/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f66a39a5a7498e2e99fe9d94d663796b3bc157b5 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/representations/octree/__init__.py @@ -0,0 +1 @@ +from .octree_dfs import DfsOctree \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/representations/octree/octree_dfs.py b/OVOW/engine/oneposeviagen/trellis/trellis/representations/octree/octree_dfs.py new file mode 100644 index 0000000000000000000000000000000000000000..648f90299a7121b8fc65fd8e282ff90ff8191765 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/representations/octree/octree_dfs.py @@ -0,0 +1,362 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F + + +DEFAULT_TRIVEC_CONFIG = { + 'dim': 8, + 'rank': 8, +} + +DEFAULT_VOXEL_CONFIG = { + 'solid': False, +} + +DEFAULT_DECOPOLY_CONFIG = { + 'degree': 8, + 'rank': 16, +} + + +class DfsOctree: + """ + Sparse Voxel Octree (SVO) implementation for PyTorch. + Using Depth-First Search (DFS) order to store the octree. + DFS order suits rendering and ray tracing. + + The structure and data are separatedly stored. + Structure is stored as a continuous array, each element is a 3*32 bits descriptor. + |-----------------------------------------| + | 0:3 bits | 4:31 bits | + | leaf num | unused | + |-----------------------------------------| + | 0:31 bits | + | child ptr | + |-----------------------------------------| + | 0:31 bits | + | data ptr | + |-----------------------------------------| + Each element represents a non-leaf node in the octree. + The valid mask is used to indicate whether the children are valid. + The leaf mask is used to indicate whether the children are leaf nodes. + The child ptr is used to point to the first non-leaf child. Non-leaf children descriptors are stored continuously from the child ptr. + The data ptr is used to point to the data of leaf children. Leaf children data are stored continuously from the data ptr. + + There are also auxiliary arrays to store the additional structural information to facilitate parallel processing. + - Position: the position of the octree nodes. + - Depth: the depth of the octree nodes. + + Args: + depth (int): the depth of the octree. + """ + + def __init__( + self, + depth, + aabb=[0,0,0,1,1,1], + sh_degree=2, + primitive='voxel', + primitive_config={}, + device='cuda', + ): + self.max_depth = depth + self.aabb = torch.tensor(aabb, dtype=torch.float32, device=device) + self.device = device + self.sh_degree = sh_degree + self.active_sh_degree = sh_degree + self.primitive = primitive + self.primitive_config = primitive_config + + self.structure = torch.tensor([[8, 1, 0]], dtype=torch.int32, device=self.device) + self.position = torch.zeros((8, 3), dtype=torch.float32, device=self.device) + self.depth = torch.zeros((8, 1), dtype=torch.uint8, device=self.device) + self.position[:, 0] = torch.tensor([0.25, 0.75, 0.25, 0.75, 0.25, 0.75, 0.25, 0.75], device=self.device) + self.position[:, 1] = torch.tensor([0.25, 0.25, 0.75, 0.75, 0.25, 0.25, 0.75, 0.75], device=self.device) + self.position[:, 2] = torch.tensor([0.25, 0.25, 0.25, 0.25, 0.75, 0.75, 0.75, 0.75], device=self.device) + self.depth[:, 0] = 1 + + self.data = ['position', 'depth'] + self.param_names = [] + + if primitive == 'voxel': + self.features_dc = torch.zeros((8, 1, 3), dtype=torch.float32, device=self.device) + self.features_ac = torch.zeros((8, (sh_degree+1)**2-1, 3), dtype=torch.float32, device=self.device) + self.data += ['features_dc', 'features_ac'] + self.param_names += ['features_dc', 'features_ac'] + if not primitive_config.get('solid', False): + self.density = torch.zeros((8, 1), dtype=torch.float32, device=self.device) + self.data.append('density') + self.param_names.append('density') + elif primitive == 'gaussian': + self.features_dc = torch.zeros((8, 1, 3), dtype=torch.float32, device=self.device) + self.features_ac = torch.zeros((8, (sh_degree+1)**2-1, 3), dtype=torch.float32, device=self.device) + self.opacity = torch.zeros((8, 1), dtype=torch.float32, device=self.device) + self.data += ['features_dc', 'features_ac', 'opacity'] + self.param_names += ['features_dc', 'features_ac', 'opacity'] + elif primitive == 'trivec': + self.trivec = torch.zeros((8, primitive_config['rank'], 3, primitive_config['dim']), dtype=torch.float32, device=self.device) + self.density = torch.zeros((8, primitive_config['rank']), dtype=torch.float32, device=self.device) + self.features_dc = torch.zeros((8, primitive_config['rank'], 1, 3), dtype=torch.float32, device=self.device) + self.features_ac = torch.zeros((8, primitive_config['rank'], (sh_degree+1)**2-1, 3), dtype=torch.float32, device=self.device) + self.density_shift = 0 + self.data += ['trivec', 'density', 'features_dc', 'features_ac'] + self.param_names += ['trivec', 'density', 'features_dc', 'features_ac'] + elif primitive == 'decoupoly': + self.decoupoly_V = torch.zeros((8, primitive_config['rank'], 3), dtype=torch.float32, device=self.device) + self.decoupoly_g = torch.zeros((8, primitive_config['rank'], primitive_config['degree']), dtype=torch.float32, device=self.device) + self.density = torch.zeros((8, primitive_config['rank']), dtype=torch.float32, device=self.device) + self.features_dc = torch.zeros((8, primitive_config['rank'], 1, 3), dtype=torch.float32, device=self.device) + self.features_ac = torch.zeros((8, primitive_config['rank'], (sh_degree+1)**2-1, 3), dtype=torch.float32, device=self.device) + self.density_shift = 0 + self.data += ['decoupoly_V', 'decoupoly_g', 'density', 'features_dc', 'features_ac'] + self.param_names += ['decoupoly_V', 'decoupoly_g', 'density', 'features_dc', 'features_ac'] + + self.setup_functions() + + def setup_functions(self): + self.density_activation = (lambda x: torch.exp(x - 2)) if self.primitive != 'trivec' else (lambda x: x) + self.opacity_activation = lambda x: torch.sigmoid(x - 6) + self.inverse_opacity_activation = lambda x: torch.log(x / (1 - x)) + 6 + self.color_activation = lambda x: torch.sigmoid(x) + + @property + def num_non_leaf_nodes(self): + return self.structure.shape[0] + + @property + def num_leaf_nodes(self): + return self.depth.shape[0] + + @property + def cur_depth(self): + return self.depth.max().item() + + @property + def occupancy(self): + return self.num_leaf_nodes / 8 ** self.cur_depth + + @property + def get_xyz(self): + return self.position + + @property + def get_depth(self): + return self.depth + + @property + def get_density(self): + if self.primitive == 'voxel' and self.primitive_config['solid']: + return torch.full((self.position.shape[0], 1), 1000, dtype=torch.float32, device=self.device) + return self.density_activation(self.density) + + @property + def get_opacity(self): + return self.opacity_activation(self.density) + + @property + def get_trivec(self): + return self.trivec + + @property + def get_decoupoly(self): + return F.normalize(self.decoupoly_V, dim=-1), self.decoupoly_g + + @property + def get_color(self): + return self.color_activation(self.colors) + + @property + def get_features(self): + if self.sh_degree == 0: + return self.features_dc + return torch.cat([self.features_dc, self.features_ac], dim=-2) + + def state_dict(self): + ret = {'structure': self.structure, 'position': self.position, 'depth': self.depth, 'sh_degree': self.sh_degree, 'active_sh_degree': self.active_sh_degree, 'trivec_config': self.trivec_config, 'voxel_config': self.voxel_config, 'primitive': self.primitive} + if hasattr(self, 'density_shift'): + ret['density_shift'] = self.density_shift + for data in set(self.data + self.param_names): + if not isinstance(getattr(self, data), nn.Module): + ret[data] = getattr(self, data) + else: + ret[data] = getattr(self, data).state_dict() + return ret + + def load_state_dict(self, state_dict): + keys = list(set(self.data + self.param_names + list(state_dict.keys()) + ['structure', 'position', 'depth'])) + for key in keys: + if key not in state_dict: + print(f"Warning: key {key} not found in the state_dict.") + continue + try: + if not isinstance(getattr(self, key), nn.Module): + setattr(self, key, state_dict[key]) + else: + getattr(self, key).load_state_dict(state_dict[key]) + except Exception as e: + print(e) + raise ValueError(f"Error loading key {key}.") + + def gather_from_leaf_children(self, data): + """ + Gather the data from the leaf children. + + Args: + data (torch.Tensor): the data to gather. The first dimension should be the number of leaf nodes. + """ + leaf_cnt = self.structure[:, 0] + leaf_cnt_masks = [leaf_cnt == i for i in range(1, 9)] + ret = torch.zeros((self.num_non_leaf_nodes,), dtype=data.dtype, device=self.device) + for i in range(8): + if leaf_cnt_masks[i].sum() == 0: + continue + start = self.structure[leaf_cnt_masks[i], 2] + for j in range(i+1): + ret[leaf_cnt_masks[i]] += data[start + j] + return ret + + def gather_from_non_leaf_children(self, data): + """ + Gather the data from the non-leaf children. + + Args: + data (torch.Tensor): the data to gather. The first dimension should be the number of leaf nodes. + """ + non_leaf_cnt = 8 - self.structure[:, 0] + non_leaf_cnt_masks = [non_leaf_cnt == i for i in range(1, 9)] + ret = torch.zeros_like(data, device=self.device) + for i in range(8): + if non_leaf_cnt_masks[i].sum() == 0: + continue + start = self.structure[non_leaf_cnt_masks[i], 1] + for j in range(i+1): + ret[non_leaf_cnt_masks[i]] += data[start + j] + return ret + + def structure_control(self, mask): + """ + Control the structure of the octree. + + Args: + mask (torch.Tensor): the mask to control the structure. 1 for subdivide, -1 for merge, 0 for keep. + """ + # Dont subdivide when the depth is the maximum. + mask[self.depth.squeeze() == self.max_depth] = torch.clamp_max(mask[self.depth.squeeze() == self.max_depth], 0) + # Dont merge when the depth is the minimum. + mask[self.depth.squeeze() == 1] = torch.clamp_min(mask[self.depth.squeeze() == 1], 0) + + # Gather control mask + structre_ctrl = self.gather_from_leaf_children(mask) + structre_ctrl[structre_ctrl==-8] = -1 + + new_leaf_num = self.structure[:, 0].clone() + # Modify the leaf num. + structre_valid = structre_ctrl >= 0 + new_leaf_num[structre_valid] -= structre_ctrl[structre_valid] # Add the new nodes. + structre_delete = structre_ctrl < 0 + merged_nodes = self.gather_from_non_leaf_children(structre_delete.int()) + new_leaf_num += merged_nodes # Delete the merged nodes. + + # Update the structure array to allocate new nodes. + mem_offset = torch.zeros((self.num_non_leaf_nodes + 1,), dtype=torch.int32, device=self.device) + mem_offset.index_add_(0, self.structure[structre_valid, 1], structre_ctrl[structre_valid]) # Add the new nodes. + mem_offset[:-1] -= structre_delete.int() # Delete the merged nodes. + new_structre_idx = torch.arange(0, self.num_non_leaf_nodes + 1, dtype=torch.int32, device=self.device) + mem_offset.cumsum(0) + new_structure_length = new_structre_idx[-1].item() + new_structre_idx = new_structre_idx[:-1] + new_structure = torch.empty((new_structure_length, 3), dtype=torch.int32, device=self.device) + new_structure[new_structre_idx[structre_valid], 0] = new_leaf_num[structre_valid] + + # Initialize the new nodes. + new_node_mask = torch.ones((new_structure_length,), dtype=torch.bool, device=self.device) + new_node_mask[new_structre_idx[structre_valid]] = False + new_structure[new_node_mask, 0] = 8 # Initialize to all leaf nodes. + new_node_num = new_node_mask.sum().item() + + # Rebuild child ptr. + non_leaf_cnt = 8 - new_structure[:, 0] + new_child_ptr = torch.cat([torch.zeros((1,), dtype=torch.int32, device=self.device), non_leaf_cnt.cumsum(0)[:-1]]) + new_structure[:, 1] = new_child_ptr + 1 + + # Rebuild data ptr with old data. + leaf_cnt = torch.zeros((new_structure_length,), dtype=torch.int32, device=self.device) + leaf_cnt.index_add_(0, new_structre_idx, self.structure[:, 0]) + old_data_ptr = torch.cat([torch.zeros((1,), dtype=torch.int32, device=self.device), leaf_cnt.cumsum(0)[:-1]]) + + # Update the data array + subdivide_mask = mask == 1 + merge_mask = mask == -1 + data_valid = ~(subdivide_mask | merge_mask) + mem_offset = torch.zeros((self.num_leaf_nodes + 1,), dtype=torch.int32, device=self.device) + mem_offset.index_add_(0, old_data_ptr[new_node_mask], torch.full((new_node_num,), 8, dtype=torch.int32, device=self.device)) # Add data array for new nodes + mem_offset[:-1] -= subdivide_mask.int() # Delete data elements for subdivide nodes + mem_offset[:-1] -= merge_mask.int() # Delete data elements for merge nodes + mem_offset.index_add_(0, self.structure[structre_valid, 2], merged_nodes[structre_valid]) # Add data elements for merge nodes + new_data_idx = torch.arange(0, self.num_leaf_nodes + 1, dtype=torch.int32, device=self.device) + mem_offset.cumsum(0) + new_data_length = new_data_idx[-1].item() + new_data_idx = new_data_idx[:-1] + new_data = {data: torch.empty((new_data_length,) + getattr(self, data).shape[1:], dtype=getattr(self, data).dtype, device=self.device) for data in self.data} + for data in self.data: + new_data[data][new_data_idx[data_valid]] = getattr(self, data)[data_valid] + + # Rebuild data ptr + leaf_cnt = new_structure[:, 0] + new_data_ptr = torch.cat([torch.zeros((1,), dtype=torch.int32, device=self.device), leaf_cnt.cumsum(0)[:-1]]) + new_structure[:, 2] = new_data_ptr + + # Initialize the new data array + ## For subdivide nodes + if subdivide_mask.sum() > 0: + subdivide_data_ptr = new_structure[new_node_mask, 2] + for data in self.data: + for i in range(8): + if data == 'position': + offset = torch.tensor([i // 4, (i // 2) % 2, i % 2], dtype=torch.float32, device=self.device) - 0.5 + scale = 2 ** (-1.0 - self.depth[subdivide_mask]) + new_data['position'][subdivide_data_ptr + i] = self.position[subdivide_mask] + offset * scale + elif data == 'depth': + new_data['depth'][subdivide_data_ptr + i] = self.depth[subdivide_mask] + 1 + elif data == 'opacity': + new_data['opacity'][subdivide_data_ptr + i] = self.inverse_opacity_activation(torch.sqrt(self.opacity_activation(self.opacity[subdivide_mask]))) + elif data == 'trivec': + offset = torch.tensor([i // 4, (i // 2) % 2, i % 2], dtype=torch.float32, device=self.device) * 0.5 + coord = (torch.linspace(0, 0.5, self.trivec.shape[-1], dtype=torch.float32, device=self.device)[None] + offset[:, None]).reshape(1, 3, self.trivec.shape[-1], 1) + axis = torch.linspace(0, 1, 3, dtype=torch.float32, device=self.device).reshape(1, 3, 1, 1).repeat(1, 1, self.trivec.shape[-1], 1) + coord = torch.stack([coord, axis], dim=3).reshape(1, 3, self.trivec.shape[-1], 2).expand(self.trivec[subdivide_mask].shape[0], -1, -1, -1) * 2 - 1 + new_data['trivec'][subdivide_data_ptr + i] = F.grid_sample(self.trivec[subdivide_mask], coord, align_corners=True) + else: + new_data[data][subdivide_data_ptr + i] = getattr(self, data)[subdivide_mask] + ## For merge nodes + if merge_mask.sum() > 0: + merge_data_ptr = torch.empty((merged_nodes.sum().item(),), dtype=torch.int32, device=self.device) + merge_nodes_cumsum = torch.cat([torch.zeros((1,), dtype=torch.int32, device=self.device), merged_nodes.cumsum(0)[:-1]]) + for i in range(8): + merge_data_ptr[merge_nodes_cumsum[merged_nodes > i] + i] = new_structure[new_structre_idx[merged_nodes > i], 2] + i + old_merge_data_ptr = self.structure[structre_delete, 2] + for data in self.data: + if data == 'position': + scale = 2 ** (1.0 - self.depth[old_merge_data_ptr]) + new_data['position'][merge_data_ptr] = ((self.position[old_merge_data_ptr] + 0.5) / scale).floor() * scale + 0.5 * scale - 0.5 + elif data == 'depth': + new_data['depth'][merge_data_ptr] = self.depth[old_merge_data_ptr] - 1 + elif data == 'opacity': + new_data['opacity'][subdivide_data_ptr + i] = self.inverse_opacity_activation(self.opacity_activation(self.opacity[subdivide_mask])**2) + elif data == 'trivec': + new_data['trivec'][merge_data_ptr] = self.trivec[old_merge_data_ptr] + else: + new_data[data][merge_data_ptr] = getattr(self, data)[old_merge_data_ptr] + + # Update the structure and data array + self.structure = new_structure + for data in self.data: + setattr(self, data, new_data[data]) + + # Save data array control temp variables + self.data_rearrange_buffer = { + 'subdivide_mask': subdivide_mask, + 'merge_mask': merge_mask, + 'data_valid': data_valid, + 'new_data_idx': new_data_idx, + 'new_data_length': new_data_length, + 'new_data': new_data + } diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/utils/__init__.py b/OVOW/engine/oneposeviagen/trellis/trellis/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/utils/general_utils.py b/OVOW/engine/oneposeviagen/trellis/trellis/utils/general_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3b454d9c75521e33466055fe37c3fc1e37180a79 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/utils/general_utils.py @@ -0,0 +1,187 @@ +import numpy as np +import cv2 +import torch + + +# Dictionary utils +def _dict_merge(dicta, dictb, prefix=''): + """ + Merge two dictionaries. + """ + assert isinstance(dicta, dict), 'input must be a dictionary' + assert isinstance(dictb, dict), 'input must be a dictionary' + dict_ = {} + all_keys = set(dicta.keys()).union(set(dictb.keys())) + for key in all_keys: + if key in dicta.keys() and key in dictb.keys(): + if isinstance(dicta[key], dict) and isinstance(dictb[key], dict): + dict_[key] = _dict_merge(dicta[key], dictb[key], prefix=f'{prefix}.{key}') + else: + raise ValueError(f'Duplicate key {prefix}.{key} found in both dictionaries. Types: {type(dicta[key])}, {type(dictb[key])}') + elif key in dicta.keys(): + dict_[key] = dicta[key] + else: + dict_[key] = dictb[key] + return dict_ + + +def dict_merge(dicta, dictb): + """ + Merge two dictionaries. + """ + return _dict_merge(dicta, dictb, prefix='') + + +def dict_foreach(dic, func, special_func={}): + """ + Recursively apply a function to all non-dictionary leaf values in a dictionary. + """ + assert isinstance(dic, dict), 'input must be a dictionary' + for key in dic.keys(): + if isinstance(dic[key], dict): + dic[key] = dict_foreach(dic[key], func) + else: + if key in special_func.keys(): + dic[key] = special_func[key](dic[key]) + else: + dic[key] = func(dic[key]) + return dic + + +def dict_reduce(dicts, func, special_func={}): + """ + Reduce a list of dictionaries. Leaf values must be scalars. + """ + assert isinstance(dicts, list), 'input must be a list of dictionaries' + assert all([isinstance(d, dict) for d in dicts]), 'input must be a list of dictionaries' + assert len(dicts) > 0, 'input must be a non-empty list of dictionaries' + all_keys = set([key for dict_ in dicts for key in dict_.keys()]) + reduced_dict = {} + for key in all_keys: + vlist = [dict_[key] for dict_ in dicts if key in dict_.keys()] + if isinstance(vlist[0], dict): + reduced_dict[key] = dict_reduce(vlist, func, special_func) + else: + if key in special_func.keys(): + reduced_dict[key] = special_func[key](vlist) + else: + reduced_dict[key] = func(vlist) + return reduced_dict + + +def dict_any(dic, func): + """ + Recursively apply a function to all non-dictionary leaf values in a dictionary. + """ + assert isinstance(dic, dict), 'input must be a dictionary' + for key in dic.keys(): + if isinstance(dic[key], dict): + if dict_any(dic[key], func): + return True + else: + if func(dic[key]): + return True + return False + + +def dict_all(dic, func): + """ + Recursively apply a function to all non-dictionary leaf values in a dictionary. + """ + assert isinstance(dic, dict), 'input must be a dictionary' + for key in dic.keys(): + if isinstance(dic[key], dict): + if not dict_all(dic[key], func): + return False + else: + if not func(dic[key]): + return False + return True + + +def dict_flatten(dic, sep='.'): + """ + Flatten a nested dictionary into a dictionary with no nested dictionaries. + """ + assert isinstance(dic, dict), 'input must be a dictionary' + flat_dict = {} + for key in dic.keys(): + if isinstance(dic[key], dict): + sub_dict = dict_flatten(dic[key], sep=sep) + for sub_key in sub_dict.keys(): + flat_dict[str(key) + sep + str(sub_key)] = sub_dict[sub_key] + else: + flat_dict[key] = dic[key] + return flat_dict + + +def make_grid(images, nrow=None, ncol=None, aspect_ratio=None): + num_images = len(images) + if nrow is None and ncol is None: + if aspect_ratio is not None: + nrow = int(np.round(np.sqrt(num_images / aspect_ratio))) + else: + nrow = int(np.sqrt(num_images)) + ncol = (num_images + nrow - 1) // nrow + elif nrow is None and ncol is not None: + nrow = (num_images + ncol - 1) // ncol + elif nrow is not None and ncol is None: + ncol = (num_images + nrow - 1) // nrow + else: + assert nrow * ncol >= num_images, 'nrow * ncol must be greater than or equal to the number of images' + + grid = np.zeros((nrow * images[0].shape[0], ncol * images[0].shape[1], images[0].shape[2]), dtype=images[0].dtype) + for i, img in enumerate(images): + row = i // ncol + col = i % ncol + grid[row * img.shape[0]:(row + 1) * img.shape[0], col * img.shape[1]:(col + 1) * img.shape[1]] = img + return grid + + +def notes_on_image(img, notes=None): + img = np.pad(img, ((0, 32), (0, 0), (0, 0)), 'constant', constant_values=0) + img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) + if notes is not None: + img = cv2.putText(img, notes, (0, img.shape[0] - 4), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 1) + img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + return img + + +def save_image_with_notes(img, path, notes=None): + """ + Save an image with notes. + """ + if isinstance(img, torch.Tensor): + img = img.cpu().numpy().transpose(1, 2, 0) + if img.dtype == np.float32 or img.dtype == np.float64: + img = np.clip(img * 255, 0, 255).astype(np.uint8) + img = notes_on_image(img, notes) + cv2.imwrite(path, cv2.cvtColor(img, cv2.COLOR_RGB2BGR)) + + +# debug utils + +def atol(x, y): + """ + Absolute tolerance. + """ + return torch.abs(x - y) + + +def rtol(x, y): + """ + Relative tolerance. + """ + return torch.abs(x - y) / torch.clamp_min(torch.maximum(torch.abs(x), torch.abs(y)), 1e-12) + + +# print utils +def indent(s, n=4): + """ + Indent a string. + """ + lines = s.split('\n') + for i in range(1, len(lines)): + lines[i] = ' ' * n + lines[i] + return '\n'.join(lines) + diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/utils/postprocessing_utils.py b/OVOW/engine/oneposeviagen/trellis/trellis/utils/postprocessing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7551df28fa74f9316a2c0bc991683d302ec85029 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/utils/postprocessing_utils.py @@ -0,0 +1,954 @@ +from typing import * +import numpy as np +import trimesh +import trimesh.visual +import xatlas +from PIL import Image +import cv2 +import os +import igraph +import pyvista as pv + +from pymeshfix import _meshfix + +from .render_utils import render_condition_images, render_multiview +from ..renderers import GaussianRenderer +from ..representations import MeshExtractResult, Gaussian + +from .random_utils import sphere_hammersley_sequence + +import torch +import utils3d +from tqdm import tqdm +import nvdiffrast.torch as dr +import torchvision +from ..representations import MeshExtractResult + +import torch +import torch.nn.functional as F +from torch.autograd import Variable +import numpy as np +from math import exp + +@torch.no_grad() +def _fill_holes( + verts, + faces, + max_hole_size=0.04, + max_hole_nbe=32, + resolution=128, + num_views=500, + debug=False, + verbose=False +): + """ + Rasterize a mesh from multiple views and remove invisible faces. + Also includes postprocessing to: + 1. Remove connected components that are have low visibility. + 2. Mincut to remove faces at the inner side of the mesh connected to the outer side with a small hole. + + Args: + verts (torch.Tensor): Vertices of the mesh. Shape (V, 3). + faces (torch.Tensor): Faces of the mesh. Shape (F, 3). + max_hole_size (float): Maximum area of a hole to fill. + resolution (int): Resolution of the rasterization. + num_views (int): Number of views to rasterize the mesh. + verbose (bool): Whether to print progress. + """ + # Construct cameras + yaws = [] + pitchs = [] + for i in range(num_views): + y, p = sphere_hammersley_sequence(i, num_views) + yaws.append(y) + pitchs.append(p) + yaws = torch.tensor(yaws).cuda() + pitchs = torch.tensor(pitchs).cuda() + radius = 2.0 + fov = torch.deg2rad(torch.tensor(40)).cuda() + projection = utils3d.torch.perspective_from_fov_xy(fov, fov, 1, 3) + views = [] + for (yaw, pitch) in zip(yaws, pitchs): + orig = torch.tensor([ + torch.sin(yaw) * torch.cos(pitch), + torch.cos(yaw) * torch.cos(pitch), + torch.sin(pitch), + ]).cuda().float() * radius + view = utils3d.torch.view_look_at(orig, torch.tensor([0, 0, 0]).float().cuda(), torch.tensor([0, 0, 1]).float().cuda()) + views.append(view) + views = torch.stack(views, dim=0) + + # Rasterize + visblity = torch.zeros(faces.shape[0], dtype=torch.int32, device=verts.device) + rastctx = utils3d.torch.RastContext(backend='cuda')#gengzheng : segmentation fault happened + for i in tqdm(range(views.shape[0]), total=views.shape[0], disable=not verbose, desc='Rasterizing'): + view = views[i] + buffers = utils3d.torch.rasterize_triangle_faces( + rastctx, verts[None], faces, resolution, resolution, view=view, projection=projection + ) + face_id = buffers['face_id'][0][buffers['mask'][0] > 0.95] - 1 + face_id = torch.unique(face_id).long() + visblity[face_id] += 1 + visblity = visblity.float() / num_views + + # Mincut + ## construct outer faces + edges, face2edge, edge_degrees = utils3d.torch.compute_edges(faces) + boundary_edge_indices = torch.nonzero(edge_degrees == 1).reshape(-1) + connected_components = utils3d.torch.compute_connected_components(faces, edges, face2edge) + outer_face_indices = torch.zeros(faces.shape[0], dtype=torch.bool, device=faces.device) + for i in range(len(connected_components)): + outer_face_indices[connected_components[i]] = visblity[connected_components[i]] > min(max(visblity[connected_components[i]].quantile(0.75).item(), 0.25), 0.5) + outer_face_indices = outer_face_indices.nonzero().reshape(-1) + + ## construct inner faces + inner_face_indices = torch.nonzero(visblity == 0).reshape(-1) + if verbose: + tqdm.write(f'Found {inner_face_indices.shape[0]} invisible faces') + if inner_face_indices.shape[0] == 0: + return verts, faces + + ## Construct dual graph (faces as nodes, edges as edges) + dual_edges, dual_edge2edge = utils3d.torch.compute_dual_graph(face2edge) + dual_edge2edge = edges[dual_edge2edge] + dual_edges_weights = torch.norm(verts[dual_edge2edge[:, 0]] - verts[dual_edge2edge[:, 1]], dim=1) + if verbose: + tqdm.write(f'Dual graph: {dual_edges.shape[0]} edges') + + ## solve mincut problem + ### construct main graph + g = igraph.Graph() + g.add_vertices(faces.shape[0]) + g.add_edges(dual_edges.cpu().numpy()) + g.es['weight'] = dual_edges_weights.cpu().numpy() + + ### source and target + g.add_vertex('s') + g.add_vertex('t') + + ### connect invisible faces to source + g.add_edges([(f, 's') for f in inner_face_indices], attributes={'weight': torch.ones(inner_face_indices.shape[0], dtype=torch.float32).cpu().numpy()}) + + ### connect outer faces to target + g.add_edges([(f, 't') for f in outer_face_indices], attributes={'weight': torch.ones(outer_face_indices.shape[0], dtype=torch.float32).cpu().numpy()}) + + ### solve mincut + cut = g.mincut('s', 't', (np.array(g.es['weight']) * 1000).tolist()) + remove_face_indices = torch.tensor([v for v in cut.partition[0] if v < faces.shape[0]], dtype=torch.long, device=faces.device) + if verbose: + tqdm.write(f'Mincut solved, start checking the cut') + + ### check if the cut is valid with each connected component + to_remove_cc = utils3d.torch.compute_connected_components(faces[remove_face_indices]) + if debug: + tqdm.write(f'Number of connected components of the cut: {len(to_remove_cc)}') + valid_remove_cc = [] + cutting_edges = [] + for cc in to_remove_cc: + #### check if the connected component has low visibility + visblity_median = visblity[remove_face_indices[cc]].median() + if debug: + tqdm.write(f'visblity_median: {visblity_median}') + if visblity_median > 0.25: + continue + + #### check if the cuting loop is small enough + cc_edge_indices, cc_edges_degree = torch.unique(face2edge[remove_face_indices[cc]], return_counts=True) + cc_boundary_edge_indices = cc_edge_indices[cc_edges_degree == 1] + cc_new_boundary_edge_indices = cc_boundary_edge_indices[~torch.isin(cc_boundary_edge_indices, boundary_edge_indices)] + if len(cc_new_boundary_edge_indices) > 0: + cc_new_boundary_edge_cc = utils3d.torch.compute_edge_connected_components(edges[cc_new_boundary_edge_indices]) + cc_new_boundary_edges_cc_center = [verts[edges[cc_new_boundary_edge_indices[edge_cc]]].mean(dim=1).mean(dim=0) for edge_cc in cc_new_boundary_edge_cc] + cc_new_boundary_edges_cc_area = [] + for i, edge_cc in enumerate(cc_new_boundary_edge_cc): + _e1 = verts[edges[cc_new_boundary_edge_indices[edge_cc]][:, 0]] - cc_new_boundary_edges_cc_center[i] + _e2 = verts[edges[cc_new_boundary_edge_indices[edge_cc]][:, 1]] - cc_new_boundary_edges_cc_center[i] + cc_new_boundary_edges_cc_area.append(torch.norm(torch.cross(_e1, _e2, dim=-1), dim=1).sum() * 0.5) + if debug: + cutting_edges.append(cc_new_boundary_edge_indices) + tqdm.write(f'Area of the cutting loop: {cc_new_boundary_edges_cc_area}') + if any([l > max_hole_size for l in cc_new_boundary_edges_cc_area]): + continue + + valid_remove_cc.append(cc) + + if debug: + face_v = verts[faces].mean(dim=1).cpu().numpy() + vis_dual_edges = dual_edges.cpu().numpy() + vis_colors = np.zeros((faces.shape[0], 3), dtype=np.uint8) + vis_colors[inner_face_indices.cpu().numpy()] = [0, 0, 255] + vis_colors[outer_face_indices.cpu().numpy()] = [0, 255, 0] + vis_colors[remove_face_indices.cpu().numpy()] = [255, 0, 255] + if len(valid_remove_cc) > 0: + vis_colors[remove_face_indices[torch.cat(valid_remove_cc)].cpu().numpy()] = [255, 0, 0] + utils3d.io.write_ply('dbg_dual.ply', face_v, edges=vis_dual_edges, vertex_colors=vis_colors) + + vis_verts = verts.cpu().numpy() + vis_edges = edges[torch.cat(cutting_edges)].cpu().numpy() + utils3d.io.write_ply('dbg_cut.ply', vis_verts, edges=vis_edges) + + + if len(valid_remove_cc) > 0: + remove_face_indices = remove_face_indices[torch.cat(valid_remove_cc)] + mask = torch.ones(faces.shape[0], dtype=torch.bool, device=faces.device) + mask[remove_face_indices] = 0 + faces = faces[mask] + faces, verts = utils3d.torch.remove_unreferenced_vertices(faces, verts) + if verbose: + tqdm.write(f'Removed {(~mask).sum()} faces by mincut') + else: + if verbose: + tqdm.write(f'Removed 0 faces by mincut') + + mesh = _meshfix.PyTMesh() + mesh.load_array(verts.cpu().numpy(), faces.cpu().numpy()) + mesh.fill_small_boundaries(nbe=max_hole_nbe, refine=True) + verts, faces = mesh.return_arrays() + verts, faces = torch.tensor(verts, device='cuda', dtype=torch.float32), torch.tensor(faces, device='cuda', dtype=torch.int32) + + return verts, faces + +SR_cache = None + + +def gaussian(window_size, sigma): + gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)]) + return gauss/gauss.sum() + +def create_window(window_size, channel): + _1D_window = gaussian(window_size, 1.5).unsqueeze(1) + _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0) + window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous()) + return window + +def _ssim(img1, img2, window, window_size, channel, size_average = True): + mu1 = F.conv2d(img1, window, padding = window_size//2, groups = channel) + mu2 = F.conv2d(img2, window, padding = window_size//2, groups = channel) + + mu1_sq = mu1.pow(2) + mu2_sq = mu2.pow(2) + mu1_mu2 = mu1*mu2 + + sigma1_sq = F.conv2d(img1*img1, window, padding = window_size//2, groups = channel) - mu1_sq + sigma2_sq = F.conv2d(img2*img2, window, padding = window_size//2, groups = channel) - mu2_sq + sigma12 = F.conv2d(img1*img2, window, padding = window_size//2, groups = channel) - mu1_mu2 + + C1 = 0.01**2 + C2 = 0.03**2 + + ssim_map = ((2*mu1_mu2 + C1)*(2*sigma12 + C2))/((mu1_sq + mu2_sq + C1)*(sigma1_sq + sigma2_sq + C2)) + + if size_average: + return ssim_map.mean() + else: + return ssim_map.mean(1).mean(1).mean(1) + +class SSIM(torch.nn.Module): + def __init__(self, window_size = 11, size_average = True): + super(SSIM, self).__init__() + self.window_size = window_size + self.size_average = size_average + self.channel = 1 + self.window = create_window(window_size, self.channel) + + def forward(self, img1, img2): + (_, channel, _, _) = img1.size() + + if channel == self.channel and self.window.data.type() == img1.data.type(): + window = self.window + else: + window = create_window(self.window_size, channel) + + if img1.is_cuda: + window = window.cuda(img1.get_device()) + window = window.type_as(img1) + + self.window = window + self.channel = channel + + + return _ssim(img1, img2, window, self.window_size, channel, self.size_average) + +def ssim(img1, img2, window_size = 11, size_average = True): + (_, channel, _, _) = img1.size() + window = create_window(window_size, channel) + + if img1.is_cuda: + window = window.cuda(img1.get_device()) + window = window.type_as(img1) + + return _ssim(img1, img2, window, window_size, channel, size_average) + + +def run_sr_fast(source_pils, scale=4): + from PIL import Image + import numpy as np + global SR_cache + from aura_sr import AuraSR + + target_size = (512, 512) + + if SR_cache is not None: + upsampler = SR_cache + else: + upsampler = AuraSR.from_pretrained("fal/AuraSR-v2") + + ret_pils = [] + for idx, img_pils in enumerate(tqdm(source_pils, desc='Image Upsampling')): + np_in = isinstance(img_pils, np.ndarray) + assert isinstance(img_pils, (Image.Image, np.ndarray)) + + if np_in: + img_pil = Image.fromarray(img_pils) + else: + img_pil = img_pils + + img_resized = img_pil.resize(target_size, Image.Resampling.LANCZOS) + output = upsampler.upscale_4x_overlapped(img_resized) + + ret_pils.append(np.array(output) if np_in else output) + + if SR_cache is None: + SR_cache = upsampler + + return ret_pils + +def normalize_trimesh(mesh): + # Calculate the mesh centroid and bounding box extents + centroid = mesh.centroid + # Determine the scale based on the largest extent to fit into unit cube + # Normalizing: Center and scale the vertices + mesh.vertices -= centroid + + extents = mesh.extents + scale = max(extents) + mesh.vertices /= scale + + return mesh + +def bake_texture( + vertices: np.array, + faces: np.array, + uvs: np.array, + observations: List[np.array], + masks: List[np.array], + extrinsics: List[np.array], + intrinsics: List[np.array], + texture_size: int = 2048, + near: float = 0.1, + far: float = 10.0, + mode: Literal['fast', 'opt'] = 'opt', + lambda_tv: float = 1e-2, + verbose: bool = False, +): + """ + Bake texture to a mesh from multiple observations. + + Args: + vertices (np.array): Vertices of the mesh. Shape (V, 3). + faces (np.array): Faces of the mesh. Shape (F, 3). + uvs (np.array): UV coordinates of the mesh. Shape (V, 2). + observations (List[np.array]): List of observations. Each observation is a 2D image. Shape (H, W, 3). + masks (List[np.array]): List of masks. Each mask is a 2D image. Shape (H, W). + extrinsics (List[np.array]): List of extrinsics. Shape (4, 4). + intrinsics (List[np.array]): List of intrinsics. Shape (3, 3). + texture_size (int): Size of the texture. + near (float): Near plane of the camera. + far (float): Far plane of the camera. + mode (Literal['fast', 'opt']): Mode of texture baking. + lambda_tv (float): Weight of total variation loss in optimization. + verbose (bool): Whether to print progress. + """ + vertices = torch.tensor(vertices).cuda() + faces = torch.tensor(faces.astype(np.int32)).cuda() + uvs = torch.tensor(uvs).cuda() + observations = [torch.tensor(obs / 255.0).float().cuda() for obs in observations] + masks = [torch.tensor(m>0).bool().cuda() for m in masks] + views = [utils3d.torch.extrinsics_to_view(torch.tensor(extr).cuda()) for extr in extrinsics] + projections = [utils3d.torch.intrinsics_to_perspective(torch.tensor(intr).cuda(), near, far) for intr in intrinsics] + + if mode == 'fast': + texture = torch.zeros((texture_size * texture_size, 3), dtype=torch.float32).cuda() + texture_weights = torch.zeros((texture_size * texture_size), dtype=torch.float32).cuda() + rastctx = utils3d.torch.RastContext(backend='cuda') + for observation, view, projection in tqdm(zip(observations, views, projections), total=len(observations), disable=not verbose, desc='Texture baking (fast)'): + with torch.no_grad(): + rast = utils3d.torch.rasterize_triangle_faces( + rastctx, vertices[None], faces, observation.shape[1], observation.shape[0], uv=uvs[None], view=view, projection=projection + ) + uv_map = rast['uv'][0].detach().flip(0) + mask = rast['mask'][0].detach().bool() & masks[0] + + # nearest neighbor interpolation + uv_map = (uv_map * texture_size).floor().long() + obs = observation[mask] + uv_map = uv_map[mask] + idx = uv_map[:, 0] + (texture_size - uv_map[:, 1] - 1) * texture_size + texture = texture.scatter_add(0, idx.view(-1, 1).expand(-1, 3), obs) + texture_weights = texture_weights.scatter_add(0, idx, torch.ones((obs.shape[0]), dtype=torch.float32, device=texture.device)) + + mask = texture_weights > 0 + texture[mask] /= texture_weights[mask][:, None] + texture = np.clip(texture.reshape(texture_size, texture_size, 3).cpu().numpy() * 255, 0, 255).astype(np.uint8) + + # inpaint + mask = (texture_weights == 0).cpu().numpy().astype(np.uint8).reshape(texture_size, texture_size) + texture = cv2.inpaint(texture, mask, 3, cv2.INPAINT_TELEA) + + elif mode == 'opt': + rastctx = utils3d.torch.RastContext(backend='cuda') + observations = [observations.flip(0) for observations in observations] + masks = [m.flip(0) for m in masks] + _uv = [] + _uv_dr = [] + for observation, view, projection in tqdm(zip(observations, views, projections), total=len(views), disable=not verbose, desc='Texture baking (opt): UV'): + with torch.no_grad(): + rast = utils3d.torch.rasterize_triangle_faces( + rastctx, vertices[None], faces, observation.shape[1], observation.shape[0], uv=uvs[None], view=view, projection=projection + ) + _uv.append(rast['uv'].detach()) + _uv_dr.append(rast['uv_dr'].detach()) + + texture = torch.nn.Parameter(torch.zeros((1, texture_size, texture_size, 3), dtype=torch.float32).cuda()) + optimizer = torch.optim.Adam([texture], betas=(0.5, 0.9), lr=1e-2) + + def exp_anealing(optimizer, step, total_steps, start_lr, end_lr): + return start_lr * (end_lr / start_lr) ** (step / total_steps) + + def cosine_anealing(optimizer, step, total_steps, start_lr, end_lr): + return end_lr + 0.5 * (start_lr - end_lr) * (1 + np.cos(np.pi * step / total_steps)) + + def tv_loss(texture): + return torch.nn.functional.l1_loss(texture[:, :-1, :, :], texture[:, 1:, :, :]) + \ + torch.nn.functional.l1_loss(texture[:, :, :-1, :], texture[:, :, 1:, :]) + + total_steps = 2500 + with tqdm(total=total_steps, disable=not verbose, desc='Texture baking (opt): optimizing') as pbar: + for step in range(total_steps): + optimizer.zero_grad() + selected = np.random.randint(0, len(views)) + uv, uv_dr, observation, mask = _uv[selected], _uv_dr[selected], observations[selected], masks[selected] + render = dr.texture(texture, uv, uv_dr)[0] + loss = torch.nn.functional.l1_loss(render[mask], observation[mask]) + if lambda_tv > 0: + loss += lambda_tv * tv_loss(texture) + loss.backward() + optimizer.step() + # annealing + optimizer.param_groups[0]['lr'] = cosine_anealing(optimizer, step, total_steps, 1e-2, 1e-5) + pbar.set_postfix({'loss': loss.item()}) + pbar.update() + texture = np.clip(texture[0].flip(0).detach().cpu().numpy() * 255, 0, 255).astype(np.uint8) + mask = 1 - utils3d.torch.rasterize_triangle_faces( + rastctx, (uvs * 2 - 1)[None], faces, texture_size, texture_size + )['mask'][0].detach().cpu().numpy().astype(np.uint8) + texture = cv2.inpaint(texture, mask, 3, cv2.INPAINT_TELEA) + else: + raise ValueError(f'Unknown mode: {mode}') + + return texture + +def postprocess_mesh( + vertices: np.array, + faces: np.array, + simplify: bool = True, + simplify_ratio: float = 0.9, + fill_holes: bool = True, + fill_holes_max_hole_size: float = 0.04, + fill_holes_max_hole_nbe: int = 32, + fill_holes_resolution: int = 1024, + fill_holes_num_views: int = 1000, + debug: bool = False, + verbose: bool = False, +): + """ + Postprocess a mesh by simplifying, removing invisible faces, and removing isolated pieces. + + Args: + vertices (np.array): Vertices of the mesh. Shape (V, 3). + faces (np.array): Faces of the mesh. Shape (F, 3). + simplify (bool): Whether to simplify the mesh, using quadric edge collapse. + simplify_ratio (float): Ratio of faces to keep after simplification. + fill_holes (bool): Whether to fill holes in the mesh. + fill_holes_max_hole_size (float): Maximum area of a hole to fill. + fill_holes_max_hole_nbe (int): Maximum number of boundary edges of a hole to fill. + fill_holes_resolution (int): Resolution of the rasterization. + fill_holes_num_views (int): Number of views to rasterize the mesh. + verbose (bool): Whether to print progress. + """ + + if verbose: + tqdm.write(f'Before postprocess: {vertices.shape[0]} vertices, {faces.shape[0]} faces') + + # Optional global skip (avoids GPU rasterization / nvdiffrast) + if os.environ.get("OPG_SKIP_FILL_HOLES", "").strip().lower() in {"1", "true", "yes"}: + fill_holes = False + + # Simplify + if simplify and simplify_ratio > 0: + mesh = pv.PolyData(vertices, np.concatenate([np.full((faces.shape[0], 1), 3), faces], axis=1)) + mesh = mesh.decimate(simplify_ratio, progress_bar=verbose) + vertices, faces = mesh.points, mesh.faces.reshape(-1, 4)[:, 1:] + if verbose: + tqdm.write(f'After decimate: {vertices.shape[0]} vertices, {faces.shape[0]} faces') + + # Remove invisible faces + if fill_holes: + vertices, faces = torch.tensor(vertices).cuda(), torch.tensor(faces.astype(np.int32)).cuda() + vertices, faces = _fill_holes( + vertices, faces, + max_hole_size=fill_holes_max_hole_size, + max_hole_nbe=fill_holes_max_hole_nbe, + resolution=fill_holes_resolution, + num_views=fill_holes_num_views, + debug=debug, + verbose=verbose, + ) + vertices, faces = vertices.cpu().numpy(), faces.cpu().numpy() + if verbose: + tqdm.write(f'After remove invisible faces: {vertices.shape[0]} vertices, {faces.shape[0]} faces') + + return vertices, faces + +def to_trimesh(app_rep: Gaussian, mesh: MeshExtractResult, simplify: float = 0.95, debug: bool = False, + fill_holes: bool = True, fill_holes_max_size: float = 0.04, texture_size: int = 1024, verbose: bool = True) -> trimesh.Trimesh: + vertices = mesh.vertices.cpu().numpy() + faces = mesh.faces.cpu().numpy() + + # mesh postprocess + vertices, faces = postprocess_mesh( + vertices, faces, + simplify=simplify > 0, + simplify_ratio=simplify, + fill_holes=fill_holes, + fill_holes_max_hole_size=fill_holes_max_size, + fill_holes_max_hole_nbe=int(250 * np.sqrt(1-simplify)), + fill_holes_resolution=1024, + fill_holes_num_views=1000, + debug=debug, + verbose=verbose, + ) + + if os.environ.get("OPG_SKIP_TEXTURE", "").strip().lower() in {"1", "true", "yes"}: + # rotate mesh (from z-up to y-up) + vertices = vertices @ np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]]) + return trimesh.Trimesh(vertices, faces, process=False) + + vertices, faces, uvs = parametrize_mesh(vertices, faces) + # bake texture + observations, extrinsics, intrinsics = render_multiview(app_rep, resolution=1024, nviews=100) + masks = [np.any(observation > 0, axis=-1) for observation in observations] + extrinsics = [extrinsics[i].cpu().numpy() for i in range(len(extrinsics))] + intrinsics = [intrinsics[i].cpu().numpy() for i in range(len(intrinsics))] + texture = bake_texture( + vertices, faces, uvs, + observations, masks, extrinsics, intrinsics, + texture_size=texture_size, mode='opt', + lambda_tv=0.01, + verbose=verbose + ) + texture = Image.fromarray(texture) + + # rotate mesh (from z-up to y-up) + vertices = vertices @ np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]]) + material = trimesh.visual.material.PBRMaterial( + roughnessFactor=1.0, + baseColorTexture=texture, + baseColorFactor=np.array([255, 255, 255, 255], dtype=np.uint8) + ) + mesh = trimesh.Trimesh(vertices, faces, visual=trimesh.visual.TextureVisuals(uv=uvs, material=material)) + + return mesh + +SR_cache = None + +def parametrize_mesh(vertices: np.array, faces: np.array): + """ + Parametrize a mesh to a texture space, using xatlas. + + Args: + vertices (np.array): Vertices of the mesh. Shape (V, 3). + faces (np.array): Faces of the mesh. Shape (F, 3). + """ + + vmapping, indices, uvs = xatlas.parametrize(vertices, faces) + + vertices = vertices[vmapping] + faces = indices + + return vertices, faces, uvs + +def bake_vertex_colors( + vertices: np.array, + faces: np.array, + init_colors: np.array, + observations: List[np.array], + masks: List[np.array], + extrinsics: List[np.array], + intrinsics: List[np.array], + projections: List[np.array] = None, + near: float = 0.1, + far: float = 10.0, + mode: Literal['fast', 'opt'] = 'opt', + lambda_smooth: float = 0, + verbose: bool = False, + iterations: int = 1000 +): + """ + Bake colors to mesh vertices from multiple observations using differential rasterization. + + Args: + vertices (np.array): Vertices of the mesh. Shape (V, 3). + faces (np.array): Faces of the mesh. Shape (F, 3). + init_colors (np.array): Initial vertex colors. Shape (V, 3). + observations (List[np.array]): List of observations. Each observation is a 2D image. Shape (H, W, 3). + masks (List[np.array]): List of masks. Each mask is a 2D image. Shape (H, W). + extrinsics (List[np.array]): List of extrinsics. Shape (4, 4). + intrinsics (List[np.array]): List of intrinsics. Shape (3, 3). + near (float): Near plane of the camera. + far (float): Far plane of the camera. + mode (Literal['fast', 'opt']): Mode of color baking. + lambda_smooth (float): Weight of smoothness loss in optimization. + verbose (bool): Whether to print progress. + + Returns: + np.array: Vertex colors. Shape (V, 3). + """ + vertices = torch.tensor(vertices).cuda() + faces = torch.tensor(faces.astype(np.int32)).cuda() + init_colors = torch.tensor(init_colors / 255.0).float().cuda() # Convert to float [0,1] + observations = [torch.tensor(obs / 255.0).float().cuda() for obs in observations] + masks = [torch.tensor(m > 0).bool().cuda() for m in masks] + views = [utils3d.torch.extrinsics_to_view(torch.tensor(extr).cuda()) for extr in extrinsics] + if projections is None: + projections = [utils3d.torch.intrinsics_to_perspective(torch.tensor(intr).cuda(), near, far) for intr in intrinsics] + + if mode == 'fast': + vertex_colors = init_colors.clone() # Start from initial colors + vertex_weights = torch.zeros(vertices.shape[0], dtype=torch.float32).cuda() + glctx = dr.RasterizeCudaContext() + + for observation, mask, view, projection in tqdm(zip(observations, masks, views, projections), + total=len(observations), disable=not verbose, + desc='Color baking (fast)'): + with torch.no_grad(): + # Transform vertices to clip space with homogeneous coordinates + view_proj_matrix = projection @ view + vertices_homogeneous = torch.cat([vertices, torch.ones_like(vertices[:, :1])], dim=1) + vertices_clip = vertices_homogeneous @ view_proj_matrix.T + + # Rasterize using differential renderer + # Add batch dimension and ranges for nvdiffrast (ranges must be on CPU) + vertices_clip = vertices_clip.unsqueeze(0) # [1, V, 4] + ranges = torch.tensor([[0, vertices_clip.shape[1]]], dtype=torch.int32) # Keep ranges on CPU + rast, _ = dr.rasterize(glctx, vertices_clip, faces, + (observation.shape[1], observation.shape[0]), + ranges=ranges) + + # Interpolate colors + rendered = dr.interpolate(vertex_colors[None], rast, faces)[0] + rendered = dr.antialias(rendered, rast, vertices_clip, faces) + + # Update colors using valid mask + valid_mask = mask & (rast[..., 3] > 0) # Combine visibility and input mask + + # Accumulate colors and weights + vertex_contributions = dr.interpolate(rendered[None], rast, faces, grad_db=True)[1][0] + vertex_colors.scatter_add_(0, faces.view(-1)[:, None].expand(-1, 3), + vertex_contributions.reshape(-1, 3)) + vertex_weights.scatter_add_(0, faces.view(-1), + vertex_contributions.sum(-1).reshape(-1)) + + valid_vertices = vertex_weights > 0 + vertex_colors[valid_vertices] /= vertex_weights[valid_vertices].view(-1, 1) + + # For invisible vertices, keep their initial colors + vertex_colors[~valid_vertices] = init_colors[~valid_vertices] + + elif mode == 'opt': + vertex_colors = torch.nn.Parameter(init_colors.clone()) # Initialize from existing colors + optimizer = torch.optim.Adam([vertex_colors], betas=(0.5, 0.9), lr=1e-4) + glctx = dr.RasterizeCudaContext() + observations = [observations.flip(0) for observations in observations] + masks = [m.flip(0) for m in masks] + + edge_indices, _, _ = utils3d.torch.compute_edges(faces) + + def smoothness_loss(colors): + return torch.mean(torch.norm( + colors[edge_indices[:, 0]] - colors[edge_indices[:, 1]], + dim=1 + )) + + def cosine_annealing(step, total_steps, start_lr, end_lr): + return end_lr + 0.5 * (start_lr - end_lr) * (1 + np.cos(np.pi * step / total_steps)) + + total_steps = iterations + with tqdm(total=total_steps, disable=not verbose, desc='Color baking (opt)') as pbar: + for step in range(total_steps): + optimizer.zero_grad() + + idx = np.random.randint(0, len(observations)) + observation = observations[idx] + mask = masks[idx] + view = views[idx] + projection = projections[idx] + + # Transform vertices to clip space with homogeneous coordinates + view_proj_matrix = projection @ view + vertices_homogeneous = torch.cat([vertices, torch.ones_like(vertices[:, :1])], dim=1) + vertices_clip = vertices_homogeneous @ view_proj_matrix.T + + # Rasterize and render + vertices_clip = vertices_clip.unsqueeze(0) # [1, V, 4] + ranges = torch.tensor([[0, vertices_clip.shape[1]]], dtype=torch.int32) # Keep ranges on CPU + rast, _ = dr.rasterize(glctx, vertices_clip, faces, + (observation.shape[1], observation.shape[0]), + ranges=ranges) + rendered = dr.interpolate(vertex_colors[None], rast, faces)[0] + rendered = dr.antialias(rendered, rast, vertices_clip, faces) + + # Compute loss on valid pixels + valid_mask = mask & (rast[..., 3] > 0) + + color_loss = torch.nn.functional.mse_loss( + rendered[valid_mask], + observation[valid_mask.squeeze(0)] + ) + smooth_loss = smoothness_loss(vertex_colors) if lambda_smooth > 0 else 0 + loss = color_loss + lambda_smooth * smooth_loss + + loss.backward() + optimizer.step() + + lr = cosine_annealing(step, total_steps, 1e-2, 1e-5) + for param_group in optimizer.param_groups: + param_group['lr'] = lr + + pbar.set_postfix({'loss': loss.item()}) + pbar.update() + + vertex_colors = vertex_colors.detach() + + else: + raise ValueError(f'Unknown mode: {mode}') + + vertex_colors = vertex_colors.clamp(0, 1).cpu().numpy() + # vertex_colors = linear_to_srgb(vertex_colors.clamp(0, 1).cpu().numpy()) + # vertex_colors = srgb_to_linear(vertex_colors.clamp(0, 1).cpu().numpy()) + return (vertex_colors * 255).astype(np.uint8) + +def srgb_to_linear(srgb): + # Clip values to valid range + srgb = np.clip(srgb, 0, 1) + + # Apply inverse sRGB transform + linear = np.where( + srgb <= 0.04045, + srgb / 12.92, + np.power((srgb + 0.055) / 1.055, 2.4) + ) + return linear + +def linear_to_srgb(linear): + # Clip values to valid range + linear = np.clip(linear, 0, 1) + + # Apply sRGB transform + srgb = np.where( + linear <= 0.0031308, + linear * 12.92, + 1.055 * np.power(linear, 1/2.4) - 0.055 + ) + return srgb + +def bake_gs_to_mesh( + app_rep: Union[Gaussian], + mesh: MeshExtractResult, + verbose: bool +) -> trimesh.Trimesh: + # mesh = mesh.subdivide() + vertices = mesh.vertices.cpu().numpy() + faces = mesh.faces.cpu().numpy() + init_colors = mesh.vertex_attrs[:, :3].cpu().numpy() + + # Convert initial colors to uint8 if they're in float format + if init_colors.dtype != np.uint8: + init_colors = (init_colors.clip(0, 1) * 255).astype(np.uint8) + + # Render multiview images for color baking + observations, extrinsics, intrinsics = render_multiview(app_rep, resolution=2048, nviews=20) + observations = observations['color'] + # observations = run_sr_fast(observations['color']) + masks = [np.any(observation > 0, axis=-1) for observation in observations] + extrinsics = [extrinsics[i].detach().cpu().numpy() for i in range(len(extrinsics))] + intrinsics = [intrinsics[i].detach().cpu().numpy() for i in range(len(intrinsics))] + + # Bake vertex colors using initial colors + vertex_colors = bake_vertex_colors( + vertices, faces, init_colors, + observations, masks, extrinsics, intrinsics, + mode='opt', + lambda_smooth=0.05, + verbose=verbose + ) + + mesh.vertex_attrs[:, :3] = torch.tensor(vertex_colors / 255.0).float().cuda() + + return mesh + + +def bake_observations_to_mesh( + observations, + masks, + extrinsics, + intrinsics, + projections, + mesh: MeshExtractResult, + verbose: bool +) -> trimesh.Trimesh: + vertices = mesh.vertices.cpu().numpy() + faces = mesh.faces.cpu().numpy() + init_colors = mesh.vertex_attrs[:, :3].cpu().numpy() + + # Convert initial colors to uint8 if they're in float format + if init_colors.dtype != np.uint8: + init_colors = (init_colors.clip(0, 1) * 255).astype(np.uint8) + + # Bake vertex colors using initial colors + vertex_colors = bake_vertex_colors( + vertices, faces, init_colors, + observations, masks, extrinsics, intrinsics, projections, + mode='opt', + lambda_smooth=0., + verbose=verbose + ) + + mesh.vertex_attrs[:, :3] = torch.tensor(vertex_colors / 255.0).float().cuda() + + return mesh + +def simplify_gs( + gs: Gaussian, + simplify: float = 0.95, + verbose: bool = True, +): + """ + Simplify 3D Gaussians + NOTE: this function is not used in the current implementation for the unsatisfactory performance. + + Args: + gs (Gaussian): 3D Gaussian. + simplify (float): Ratio of Gaussians to remove in simplification. + """ + if simplify <= 0: + return gs + + # simplify + observations, extrinsics, intrinsics = render_multiview(gs, resolution=2048, nviews=20) + # observations = observations['color'] + observations = run_sr_fast(observations['color']) + observations = [torch.tensor(obs / 255.0).float().cuda().permute(2, 0, 1) for obs in observations] + + # Following https://arxiv.org/pdf/2411.06019 + renderer = GaussianRenderer({ + "resolution": 2048, + "near": 0.8, + "far": 1.6, + "ssaa": 1, + "bg_color": (0,0,0), + }) + new_gs = Gaussian(**gs.init_params) + new_gs._features_dc = gs._features_dc.clone() + new_gs._features_rest = gs._features_rest.clone() if gs._features_rest is not None else None + new_gs._opacity = torch.nn.Parameter(gs._opacity.clone()) + new_gs._rotation = torch.nn.Parameter(gs._rotation.clone()) + new_gs._scaling = torch.nn.Parameter(gs._scaling.clone()) + new_gs._xyz = torch.nn.Parameter(gs._xyz.clone()) + + # start_lr = [1e-4, 1e-3, 5e-3, 0.025, 1e-2] + start_lr = [1e-4, 1e-3, 5e-3, 0.025, 1e-2] + end_lr = [1e-6, 1e-5, 5e-5, 0.00025, 1e-4] + optimizer = torch.optim.Adam([ + {"params": new_gs._xyz, "lr": start_lr[0]}, + {"params": new_gs._rotation, "lr": start_lr[1]}, + {"params": new_gs._scaling, "lr": start_lr[2]}, + {"params": new_gs._features_dc, "lr": start_lr[4]}, + ], lr=start_lr[0]) + + def exp_anealing(optimizer, step, total_steps, start_lr, end_lr): + return start_lr * (end_lr / start_lr) ** (step / total_steps) + + def cosine_anealing(optimizer, step, total_steps, start_lr, end_lr): + return end_lr + 0.5 * (start_lr - end_lr) * (1 + np.cos(np.pi * step / total_steps)) + + _zeta = new_gs.get_opacity.clone().detach().squeeze() + _lambda = torch.zeros_like(_zeta) + _delta = 1e-7 + _interval = 10 + num_target = int((1 - simplify) * _zeta.shape[0]) + + with tqdm(total=2500, disable=not verbose, desc='Simplifying Gaussian') as pbar: + for i in range(2500): + # prune + # if i % 100 == 0: + # mask = new_gs.get_opacity.squeeze() > 0.05 + # mask = torch.nonzero(mask).squeeze() + # new_gs._xyz = torch.nn.Parameter(new_gs._xyz[mask]) + # new_gs._rotation = torch.nn.Parameter(new_gs._rotation[mask]) + # new_gs._scaling = torch.nn.Parameter(new_gs._scaling[mask]) + # new_gs._opacity = torch.nn.Parameter(new_gs._opacity[mask]) + # new_gs._features_dc = new_gs._features_dc[mask] + # new_gs._features_rest = new_gs._features_rest[mask] if new_gs._features_rest is not None else None + # _zeta = _zeta[mask] + # _lambda = _lambda[mask] + # # update optimizer state + # for param_group, new_param in zip(optimizer.param_groups, [new_gs._xyz, new_gs._rotation, new_gs._scaling, new_gs._opacity]): + # stored_state = optimizer.state[param_group['params'][0]] + # if 'exp_avg' in stored_state: + # stored_state['exp_avg'] = stored_state['exp_avg'][mask] + # stored_state['exp_avg_sq'] = stored_state['exp_avg_sq'][mask] + # del optimizer.state[param_group['params'][0]] + # param_group['params'][0] = new_param + # optimizer.state[param_group['params'][0]] = stored_state + + opacity = new_gs.get_opacity.squeeze() + + # sparisfy + # if i % _interval == 0: + # _zeta = _lambda + opacity.detach() + # if opacity.shape[0] > num_target: + # index = _zeta.topk(num_target)[1] + # _m = torch.ones_like(_zeta, dtype=torch.bool) + # _m[index] = 0 + # _zeta[_m] = 0 + # _lambda = _lambda + opacity.detach() - _zeta + + # sample a random view + view_idx = np.random.randint(len(observations)) + observation = observations[view_idx] + extrinsic = extrinsics[view_idx] + intrinsic = intrinsics[view_idx] + + color = renderer.render(new_gs, extrinsic, intrinsic)['color'] + rgb_loss = torch.nn.functional.l1_loss(color, observation) + # loss = rgb_loss + ssimloss = 1.0 - ssim(color.unsqueeze(0), observation.unsqueeze(0)) + loss = rgb_loss * 0.8 + ssimloss * 0.2 + optimizer.zero_grad() + loss.backward() + optimizer.step() + + # update lr + for j in range(len(optimizer.param_groups)): + optimizer.param_groups[j]['lr'] = cosine_anealing(optimizer, i, 100, start_lr[j], end_lr[j]) + + pbar.set_postfix({'loss': loss.item(), 'num': opacity.shape[0], 'lambda': _lambda.mean().item()}) + pbar.update() + + new_gs._xyz = new_gs._xyz.data + new_gs._rotation = new_gs._rotation.data + new_gs._scaling = new_gs._scaling.data + new_gs._opacity = new_gs._opacity.data + + return new_gs diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/utils/random_utils.py b/OVOW/engine/oneposeviagen/trellis/trellis/utils/random_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5b668c277b51f4930991912a80573adc79364028 --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/utils/random_utils.py @@ -0,0 +1,30 @@ +import numpy as np + +PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53] + +def radical_inverse(base, n): + val = 0 + inv_base = 1.0 / base + inv_base_n = inv_base + while n > 0: + digit = n % base + val += digit * inv_base_n + n //= base + inv_base_n *= inv_base + return val + +def halton_sequence(dim, n): + return [radical_inverse(PRIMES[dim], n) for dim in range(dim)] + +def hammersley_sequence(dim, n, num_samples): + return [n / num_samples] + halton_sequence(dim - 1, n) + +def sphere_hammersley_sequence(n, num_samples, offset=(0, 0), remap=False): + u, v = hammersley_sequence(2, n, num_samples) + u += offset[0] / num_samples + v += offset[1] + if remap: + u = 2 * u if u < 0.25 else 2 / 3 * u + 1 / 3 + theta = np.arccos(1 - 2 * u) - np.pi / 2 + phi = v * 2 * np.pi + return [phi, theta] \ No newline at end of file diff --git a/OVOW/engine/oneposeviagen/trellis/trellis/utils/render_utils.py b/OVOW/engine/oneposeviagen/trellis/trellis/utils/render_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..47d8e625976296bfa94215df872d41ffa6051e3a --- /dev/null +++ b/OVOW/engine/oneposeviagen/trellis/trellis/utils/render_utils.py @@ -0,0 +1,254 @@ +import torch +import numpy as np +from tqdm import tqdm +import utils3d +from PIL import Image + +from trellis.renderers import MeshRenderer +from trellis.representations import Octree, Gaussian, MeshExtractResult +from trellis.utils.random_utils import sphere_hammersley_sequence + + +def yaw_pitch_r_fov_to_extrinsics_intrinsics(yaws, pitchs, rs, fovs, device='cuda'): + is_list = isinstance(yaws, list) + if not is_list: + yaws = [yaws] + pitchs = [pitchs] + if not isinstance(rs, list): + rs = [rs] * len(yaws) + if not isinstance(fovs, list): + fovs = [fovs] * len(yaws) + extrinsics = [] + intrinsics = [] + for yaw, pitch, r, fov in zip(yaws, pitchs, rs, fovs): + fov = torch.deg2rad(torch.tensor(float(fov))).to(device) + yaw = torch.tensor(float(yaw)).to(device) + pitch = torch.tensor(float(pitch)).to(device) + orig = torch.tensor([ + torch.sin(yaw) * torch.cos(pitch), + torch.cos(yaw) * torch.cos(pitch), + torch.sin(pitch), + ]).to(device) * r + extr = utils3d.torch.extrinsics_look_at(orig, torch.tensor([0, 0, 0]).float().to(device), torch.tensor([0, 0, 1]).float().to(device)) + intr = utils3d.torch.intrinsics_from_fov_xy(fov, fov) + extrinsics.append(extr) + intrinsics.append(intr) + if not is_list: + extrinsics = extrinsics[0] + intrinsics = intrinsics[0] + return extrinsics, intrinsics + + +def render_frames(sample, extrinsics, intrinsics, options={}, colors_overwrite=None, verbose=True, need_depth=False, **kwargs): + if isinstance(sample, MeshExtractResult): + renderer = MeshRenderer() + renderer.rendering_options.resolution = options.get('resolution', 1024) + renderer.rendering_options.near = options.get('near', 1) + renderer.rendering_options.far = options.get('far', 100) + renderer.rendering_options.ssaa = options.get('ssaa', 4) + elif isinstance(sample, Gaussian): + # from ..renderers import GSplatRenderer, GaussianRenderer + # renderer = GSplatRenderer() + from ..renderers import GaussianRenderer + renderer = GaussianRenderer() + renderer.rendering_options.resolution = options.get('resolution', 1024) + renderer.rendering_options.near = options.get('near', 0.8) + renderer.rendering_options.far = options.get('far', 1.6) + renderer.rendering_options.bg_color = options.get('bg_color', (0, 0, 0)) + renderer.rendering_options.ssaa = options.get('ssaa', 1) + renderer.pipe.kernel_size = kwargs.get('kernel_size', 0.1) + renderer.pipe.use_mip_gaussian = True + elif isinstance(sample, Octree): + from ..renderers import OctreeRenderer + renderer = OctreeRenderer() + renderer.rendering_options.resolution = options.get('resolution', 512) + renderer.rendering_options.near = options.get('near', 0.8) + renderer.rendering_options.far = options.get('far', 1.6) + renderer.rendering_options.bg_color = options.get('bg_color', (0, 0, 0)) + renderer.rendering_options.ssaa = options.get('ssaa', 4) + renderer.pipe.primitive = sample.primitive + else: + raise ValueError(f'Unsupported sample type: {type(sample)}') + + rets = {} + for j, (extr, intr) in tqdm(enumerate(zip(extrinsics, intrinsics)), desc='Rendering', disable=not verbose): + if not isinstance(sample, MeshExtractResult): + res = renderer.render(sample, extr, intr, colors_overwrite=colors_overwrite, need_depth=need_depth) + if 'color' not in rets: rets['color'] = [] + if 'depth' not in rets: rets['depth'] = [] + rets['color'].append(np.clip(res['color'].detach().cpu().numpy().transpose(1, 2, 0) * 255, 0, 255).astype(np.uint8)) + if 'percent_depth' in res: + rets['depth'].append(res['percent_depth'].detach().cpu().numpy()) + elif 'depth' in res: + rets['depth'].append(res['depth'].detach().cpu().numpy()) + else: + rets['depth'].append(None) + else: + res = renderer.render(sample, extr, intr, return_types = ["color", "normal", "nocs", "depth"]) + if 'normal' not in rets: rets['normal'] = [] + if 'color' not in rets: rets['color'] = [] + if 'nocs' not in rets: rets['nocs'] = [] + if 'depth' not in rets: rets['depth'] = [] + rets['color'].append(np.clip(res['color'].detach().cpu().numpy().transpose(1, 2, 0) * 255, 0, 255).astype(np.uint8)) + rets['normal'].append(np.clip(res['normal'].detach().cpu().numpy().transpose(1, 2, 0) * 255, 0, 255).astype(np.uint8)) + rets['nocs'].append(np.clip(res['nocs'].detach().cpu().numpy().transpose(1, 2, 0) * 255, 0, 255).astype(np.uint8)) + rets['depth'].append(res['depth'].detach().cpu().numpy()) + return rets + +def render_orth_frames(sample, extrinsics, projections, options={}, colors_overwrite=None, verbose=True, **kwargs): + # Select renderer according to sample type + if isinstance(sample, MeshExtractResult): + renderer = MeshRenderer() + renderer.rendering_options.resolution = options.get('resolution', 1024) + renderer.rendering_options.ssaa = options.get('ssaa', 4) + else: + raise ValueError(f'Unsupported sample type: {type(sample)}') + + rets = {} + for j, extr in tqdm(enumerate(extrinsics), desc='Rendering Orthographic', disable=not verbose): + res = renderer.render(sample, extr, None, perspective=projections[j], return_types=["normal", "nocs", "depth"]) + if 'normal' not in rets: + rets['normal'] = [] + if 'color' not in rets: + rets['color'] = [] + if 'nocs' not in rets: + rets['nocs'] = [] + if 'depth' not in rets: + rets['depth'] = [] + rets['normal'].append(np.clip( + res['normal'].detach().cpu().numpy().transpose(1, 2, 0) * 255, 0, 255 + ).astype(np.uint8)) + rets['nocs'].append(np.clip( + res['nocs'].detach().cpu().numpy().transpose(1, 2, 0) * 255, 0, 255 + ).astype(np.uint8)) + rets['depth'].append(res['depth'].detach().cpu().numpy()) + return rets + +def get_ortho_projection_matrix(left, right, bottom, top, near, far): + """ + 使用 torch 创建正交投影矩阵, 使用标准的正交投影矩阵公式: + [ 2/(r-l) 0 0 -(r+l)/(r-l) ] + [ 0 2/(t-b) 0 -(t+b)/(t-b) ] + [ 0 0 -2/(f-n) -(f+n)/(f-n) ] + [ 0 0 0 1 ] + """ + projection_matrix = torch.zeros((4, 4), dtype=torch.float32) + + projection_matrix[0, 0] = 2.0 / (right - left) + projection_matrix[1, 1] = 2.0 / (top - bottom) + projection_matrix[2, 2] = -2.0 / (far - near) + projection_matrix[3, 3] = 1.0 + + projection_matrix[0, 3] = -(right + left) / (right - left) + projection_matrix[1, 3] = -(top + bottom) / (top - bottom) + projection_matrix[2, 3] = (far + near) / (far - near) + + return projection_matrix + + +def intrinsics_to_projection( + intrinsics: torch.Tensor, + near: float, + far: float, + ) -> torch.Tensor: + """ + OpenCV intrinsics to OpenGL perspective matrix + + Args: + intrinsics (torch.Tensor): [3, 3] OpenCV intrinsics matrix + near (float): near plane to clip + far (float): far plane to clip + Returns: + (torch.Tensor): [4, 4] OpenGL perspective matrix + """ + fx, fy = intrinsics[0, 0], intrinsics[1, 1] + cx, cy = intrinsics[0, 2], intrinsics[1, 2] + ret = torch.zeros((4, 4), dtype=intrinsics.dtype, device=intrinsics.device) + ret[0, 0] = 2 * fx + ret[1, 1] = 2 * fy + ret[0, 2] = 2 * cx - 1 + ret[1, 2] = - 2 * cy + 1 + ret[2, 2] = far / (far - near) + ret[2, 3] = near * far / (near - far) + ret[3, 2] = 1. + return ret + +def render_ortho_video(sample, resolution=512, ssaa=4, bg_color=(0, 0, 0), num_frames=300, r=2, inverse_direction=False, pitch=-1, **kwargs): + if inverse_direction: + yaws = torch.linspace(3.1415, -3.1415, num_frames) + else: + yaws = torch.linspace(0, 2 * 3.1415, num_frames) + if pitch != -1: + pitch = pitch * torch.ones(num_frames) + else: + pitch = 0.25 + 0.5 * torch.sin(torch.linspace(0, 2 * 3.1415, num_frames)) + yaws = yaws.tolist() + pitchs = pitch.tolist() + + ortho_scale = 0.6 + extrinsics, intrinsics = yaw_pitch_r_fov_to_extrinsics_intrinsics(yaws, pitchs, r, 40) + + projection = get_ortho_projection_matrix(-ortho_scale, ortho_scale, -ortho_scale, ortho_scale, 1e-6, 100).to(extrinsics[0].device) + projections = [projection] * num_frames + render_results = render_orth_frames(sample, extrinsics, projections, {'resolution': resolution, 'bg_color': bg_color, 'ssaa': ssaa}, **kwargs) + render_results.update({'extrinsics': extrinsics, 'intrinsics': None, 'projections': projections}) + return render_results + + +def render_multiview(sample, resolution=518, ssaa=4, bg_color=(0, 0, 0), num_frames=30, r = 2, fov = 40, random_offset=False, **kwargs): + if random_offset: + yaws = [] + pitchs = [] + offset = (np.random.rand(), np.random.rand()) + for i in range(num_frames): + y, p = sphere_hammersley_sequence(i, num_frames, offset) + yaws.append(y) + pitchs.append(p) + else: + cams = [sphere_hammersley_sequence(i, num_frames) for i in range(num_frames)] + yaws = [cam[0] for cam in cams] + pitchs = [cam[1] for cam in cams] + extrinsics, intrinsics = yaw_pitch_r_fov_to_extrinsics_intrinsics(yaws, pitchs, r, fov) + res = render_frames(sample, extrinsics, intrinsics, {'resolution': resolution, 'bg_color': bg_color, 'ssaa': ssaa}, **kwargs) + return res['color'], extrinsics, intrinsics + +def render_video(sample, resolution=512, ssaa=4, bg_color=(0, 0, 0), num_frames=300, r=2, fov=40, + inverse_direction=False, pitch=-1, **kwargs): + if inverse_direction: + yaws = torch.linspace(3.1415, -3.1415, num_frames) + # pitch = 0.25 + 0.5 * torch.sin(torch.linspace(2 * 3.1415, 0, num_frames)) + else: + yaws = torch.linspace(0, 2 * 3.1415, num_frames) + if pitch != -1: + pitch = pitch * torch.ones(num_frames) + else: + pitch = 0.25 + 0.5 * torch.sin(torch.linspace(0, 2 * 3.1415, num_frames)) + yaws = yaws.tolist() + pitch = pitch.tolist() + extrinsics, intrinsics = yaw_pitch_r_fov_to_extrinsics_intrinsics(yaws, pitch, r, fov) + + res = render_frames(sample, extrinsics, intrinsics, {'resolution': resolution, 'bg_color': bg_color, 'ssaa': ssaa}, **kwargs) + res.update({'extrinsics': extrinsics, 'intrinsics': intrinsics}) + return res + +def render_condition_images(sample, resolution=512, ssaa=4, bg_color=(0, 0, 0), num_frames=300, r=2, fov=40, **kwargs): + yaws = [] + pitchs = [] + offset = (np.random.rand(), np.random.rand()) + for i in range(num_frames): + y, p = sphere_hammersley_sequence(i, num_frames, offset) + yaws.append(y) + pitchs.append(p) + + fov_min, fov_max = 10, 70 + radius_min = np.sqrt(3) / 2 / np.sin(fov_max / 360 * np.pi) + radius_max = np.sqrt(3) / 2 / np.sin(fov_min / 360 * np.pi) + k_min = 1 / radius_max**2 + k_max = 1 / radius_min**2 + ks = np.random.uniform(k_min, k_max, (1000000,)) + radius = [1 / np.sqrt(k) for k in ks] + fov = [2 * np.arcsin(np.sqrt(3) / 2 / r) for r in radius] + fov = [value_in_radians * 180 / np.pi for value_in_radians in fov] + + extrinsics, intrinsics = yaw_pitch_r_fov_to_extrinsics_intrinsics(yaws, pitchs, radius, fov) + return render_frames(sample, extrinsics, intrinsics, {'resolution': resolution, 'bg_color': bg_color, 'ssaa': ssaa}, **kwargs), extrinsics, intrinsics diff --git a/OVOW/engine/pipe.sh b/OVOW/engine/pipe.sh new file mode 100644 index 0000000000000000000000000000000000000000..a2ec01996d6cd65ba32ff65da8109389180e408b --- /dev/null +++ b/OVOW/engine/pipe.sh @@ -0,0 +1,467 @@ +#!/usr/bin/env bash +set -euo pipefail + + +VIDEO="${1:?Usage: $0 /path/to/video.mp4}" +NAME="${NAME:-$(basename "$VIDEO")}" +NAME="${NAME%.*}" +OUTPUT_ROOT="${OUTPUT_ROOT:-/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs}" +CUDA_VISIBLE_DEVICES="${CUDA_VISIBLE_DEVICES:-0}" +LOCK_STATIC="${LOCK_STATIC:-1}" +RENDER_BG="${RENDER_BG:-black}" +FPS="${FPS:-10}" +EXPORT_BLENDER_GLB="${EXPORT_BLENDER_GLB:-1}" +EXPORT_PHYSICS_GLB="${EXPORT_PHYSICS_GLB:-1}" +RUN_MOTION324="${RUN_MOTION324:-1}" +MOTION324_BACKEND="${MOTION324_BACKEND:-hunyuan}" +MOTION324_INPUT_ROOT="${MOTION324_INPUT_ROOT:-/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs/motion324_inputs}" +MOTION324_OUTPUT_ROOT="${MOTION324_OUTPUT_ROOT:-/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs/motion324_outputs}" +MOTION324_ROOT="${MOTION324_ROOT:-/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/third_party/Motion324}" +MOTION324_PY="${MOTION324_PY:-/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-motion/bin/python}" +BLENDER_BIN="${BLENDER_BIN:-/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/opt/blender-4.2.3-linux-x64/blender}" +BLENDER_LIB="${BLENDER_LIB:-}" +DEFORM_POSE_MODE="${DEFORM_POSE_MODE:-single_track}" +DEFORM_FRAME_STEP="${DEFORM_FRAME_STEP:-1}" +DEFORM_RENDER_VIDEO="${DEFORM_RENDER_VIDEO:-1}" +EXPORT_SCENE_MESH_FRAMES="${EXPORT_SCENE_MESH_FRAMES:-1}" +PLANE_NUM="${PLANE_NUM:-5}" +PLANE_BOTTOM="${PLANE_BOTTOM:-0.03}" +PHYSICS_BOTTOM="${PHYSICS_BOTTOM:-0.10}" +PHYSICS_ITERS="${PHYSICS_ITERS:-2}" +PHYSICS_MAX_DROP="${PHYSICS_MAX_DROP:-1.0}" +PHYSICS_ALLOW_DOWN="${PHYSICS_ALLOW_DOWN:-1}" +PHYSICS_CONTACT="${PHYSICS_CONTACT:-1}" + +QWEN_PY="${QWEN_PY:-/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python}" +SAM3_PY="${SAM3_PY:-/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-sam3/bin/python}" +OPG_PY="${OPG_PY:-/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python}" + +QWEN_SCRIPT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/masking/qwen_sam3_video_masks.py" +QWEN_MODEL="${QWEN_MODEL:-/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/public_ckpts/model/Qwen3-VL-32B-Instruct}" +SAM3_CKPT="${SAM3_CKPT:-/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/third_party/sam3/checkpoints/sam3/sam3.pt}" +BATCH_CONFIG="${BATCH_CONFIG:-/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/config/batch_config_example_legacy.json}" + +REPO="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine" +CONFIG_JSON="$OUTPUT_ROOT/recon_ready/$NAME/pipeline_config.json" +ALIGN_JSON="" + +echo "[1/4] Qwen labels" +if [[ -n "${LABELS:-}" ]]; then + "$QWEN_PY" "$QWEN_SCRIPT" \ + --video-path "$VIDEO" \ + --mode labels \ + --output-root "$OUTPUT_ROOT" \ + --labels "$LABELS" \ + --batch-config "$BATCH_CONFIG" +else + "$QWEN_PY" "$QWEN_SCRIPT" \ + --video-path "$VIDEO" \ + --mode labels \ + --output-root "$OUTPUT_ROOT" \ + --qwen-model "$QWEN_MODEL" \ + --keyframe-count 5 \ + --dynamic-source motion \ + --default-dynamic-category rigid \ + --batch-config "$BATCH_CONFIG" +fi + +echo "[2/4] SAM3 masks" +"$SAM3_PY" "$QWEN_SCRIPT" \ + --video-path "$VIDEO" \ + --mode masks \ + --labels-json "$OUTPUT_ROOT/metadata/${NAME}_labels.json" \ + --output-root "$OUTPUT_ROOT" \ + --sam3-ckpt "$SAM3_CKPT" \ + --batch-config "$BATCH_CONFIG" + +echo "[2.5/4] Motion324 deform (if any)" +DEFORM_MANIFEST=$( + PATH="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin:$PATH" \ + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/build_deform_videos.py \ + --summary "$OUTPUT_ROOT/metadata/${NAME}_mask_summary.json" \ + --output-root "$MOTION324_INPUT_ROOT" \ + --video-path "$VIDEO" +) +export DEFORM_MANIFEST +DEFORM_COUNT=$( + "$OPG_PY" - <<'PY' +import json, os, sys +path = os.environ.get("DEFORM_MANIFEST", "") +if not path: + print(0) + sys.exit(0) +data = json.loads(open(path, "r").read()) +objs = data.get("objects", []) +print(len(objs)) +PY +) + +if [[ "$DEFORM_COUNT" -gt 0 ]]; then + if [[ "$RUN_MOTION324" == "1" ]]; then + echo "[2.6/4] Run Motion324 for deform objects" + OBJ_LIST=$( + "$OPG_PY" - <<'PY' +import json, os +data = json.loads(open(os.environ["DEFORM_MANIFEST"], "r").read()) +for obj in data.get("objects", []): + print(obj["name"] + "|" + obj["video"]) +PY + ) + while IFS="|" read -r OBJ_NAME OBJ_VIDEO; do + if [[ -z "$OBJ_NAME" ]]; then + continue + fi + echo " - Motion324: $OBJ_NAME" + PATH="$(dirname "$MOTION324_PY"):$PATH" \ + bash "$MOTION324_ROOT/scripts/4D_from_video.sh" "$OBJ_VIDEO" --backend "$MOTION324_BACKEND" + done <<< "$OBJ_LIST" + fi + + echo "[2.7/4] Scan Motion324 outputs" + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/scan_motion324_outputs.py \ + --input-root "$MOTION324_INPUT_ROOT" \ + --output-root "$MOTION324_OUTPUT_ROOT" \ + --video-name "$NAME" >/dev/null +fi + +echo "[3/4] Reconstruction" +LOG="$OUTPUT_ROOT/${NAME}_recon.log" +cd "$REPO" +PATH="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin:$PATH" \ +CUDA_VISIBLE_DEVICES="$CUDA_VISIBLE_DEVICES" \ +OPG_SKIP_PREVIEW=1 \ +CONFIG_JSON_RIGID="$OUTPUT_ROOT/recon_ready/$NAME/pipeline_config_rigid.json" +CONFIG_JSON_USE="$CONFIG_JSON" +if [[ "$DEFORM_COUNT" -gt 0 ]]; then + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/filter_pipeline_config.py \ + --input "$CONFIG_JSON" \ + --output "$CONFIG_JSON_RIGID" \ + --exclude-category deform + CONFIG_JSON_USE="$CONFIG_JSON_RIGID" +fi + +"$OPG_PY" pipeline.py --config "$CONFIG_JSON_USE" | tee "$LOG" + +RUN_ROOT="$(grep -m 1 'Done. Output:' "$LOG" | sed 's/.*Done. Output: //')" +if [[ -z "$RUN_ROOT" ]]; then + RUN_ROOT="$(ls -1dt "$OUTPUT_ROOT"/video_pipeline_* | head -n 1)" +fi +RUN_DIR="$RUN_ROOT/$NAME" + +if [[ ! -d "$RUN_DIR" ]]; then + echo "ERROR: run dir not found: $RUN_DIR" >&2 + exit 1 +fi + +if [[ "$LOCK_STATIC" == "1" ]]; then + echo "[3.5/4] Lock static poses" + export RUN_DIR CONFIG_JSON + PATH="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin:$PATH" \ + "$OPG_PY" - <<'PY' +import json +from pathlib import Path +import cv2 +import os + +run_dir = Path(os.environ["RUN_DIR"]) +config_path = Path(os.environ["CONFIG_JSON"]) + +with config_path.open("r", encoding="utf-8") as f: + cfg = json.load(f) + +static_names = {o["name"] for o in cfg.get("objects", []) if str(o.get("category", "")).lower() == "static"} +objects_root = run_dir / "objects" + +for obj_dir in objects_root.iterdir(): + if not obj_dir.is_dir() or obj_dir.name not in static_names: + continue + pose_path = obj_dir / "pose_result" / "poses.json" + if not pose_path.exists(): + continue + poses = json.loads(pose_path.read_text()) + frame_ids = sorted(int(k) for k in poses.keys() if k.isdigit()) + if not frame_ids: + continue + mask_dir = obj_dir / "masks" + best_frame = None + best_area = -1 + if mask_dir.exists(): + for fid in frame_ids: + mp = mask_dir / f"{fid:06d}.png" + if not mp.exists(): + continue + m = cv2.imread(str(mp), cv2.IMREAD_GRAYSCALE) + if m is None: + continue + area = int((m > 0).sum()) + if area > best_area: + best_area, best_frame = area, fid + if best_frame is None: + best_frame = frame_ids[0] + locked = {str(fid): poses[str(best_frame)] for fid in frame_ids} + (pose_path.parent / "poses_locked.json").write_text(json.dumps(locked, indent=2)) +PY +fi + +if [[ "$EXPORT_BLENDER_GLB" == "1" || "$EXPORT_PHYSICS_GLB" == "1" ]]; then + echo "[3.8/4] Fit plane alignment" + ALIGN_JSON="$RUN_DIR/alignment_plane.json" + PATH="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin:$PATH" \ + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/fit_plane_align.py \ + --run-dir "$RUN_DIR" \ + --config "$CONFIG_JSON" \ + --pcd "$RUN_DIR/scene_point_cloud_frame_all.ply" \ + --static-only \ + --num-planes "$PLANE_NUM" \ + --bottom-percent "$PLANE_BOTTOM" \ + --out "$ALIGN_JSON" +fi + +if [[ "$EXPORT_BLENDER_GLB" == "1" ]]; then + echo "[3.9/4] Export aligned Blender GLB (with plane)" + PATH="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin:$PATH" \ + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/export_scene_glb_anim.py \ + --run-dir "$RUN_DIR" \ + --config "$CONFIG_JSON" \ + --output "$RUN_DIR/scene_anim_blender_aligned_plane_v3.glb" \ + --use-locked-static \ + --coord blender_noflip \ + --alignment "$ALIGN_JSON" \ + --add-plane \ + --plane-z static_minz +fi + +if [[ "$EXPORT_PHYSICS_GLB" == "1" ]]; then + echo "[3.10/4] Physics Z-projection (keep animation)" + PHYS_LOCK_FLAG="" + if [[ "$LOCK_STATIC" == "1" ]]; then + PHYS_LOCK_FLAG="--use-locked-static" + fi + PHYS_ALLOW_FLAG="" + if [[ "$PHYSICS_ALLOW_DOWN" == "1" ]]; then + PHYS_ALLOW_FLAG="--allow-down" + fi + PHYS_CONTACT_FLAG="" + if [[ "$PHYSICS_CONTACT" == "1" ]]; then + PHYS_CONTACT_FLAG="--contact-objects" + fi + + PATH="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin:$PATH" \ + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/physics_project_z.py \ + --run-dir "$RUN_DIR" \ + --config "$CONFIG_JSON" \ + --alignment "$ALIGN_JSON" \ + --plane-z zero \ + --bottom-percent "$PHYSICS_BOTTOM" \ + --iters "$PHYSICS_ITERS" \ + --max-drop "$PHYSICS_MAX_DROP" \ + $PHYS_LOCK_FLAG \ + $PHYS_ALLOW_FLAG \ + $PHYS_CONTACT_FLAG + + echo "[3.11/4] Export physics GLB (Y-up, XY plane in Blender)" + PATH="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin:$PATH" \ + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/export_scene_glb_anim.py \ + --run-dir "$RUN_DIR" \ + --config "$CONFIG_JSON" \ + --output "$RUN_DIR/scene_anim_blender_physics_projected_contact_v3_yup.glb" \ + --use-locked-static \ + --pose-name poses_physics.json \ + --coord blender_noflip \ + --alignment "$ALIGN_JSON" \ + --add-plane \ + --plane-z zero +fi + +if [[ "$DEFORM_COUNT" -gt 0 ]]; then + MOTION324_MANIFEST="$MOTION324_OUTPUT_ROOT/$NAME/manifest.json" + export MOTION324_MANIFEST + if [[ -f "$MOTION324_MANIFEST" ]]; then + OBJ_LINES=$( + "$OPG_PY" - <<'PY' +import json, os +data = json.loads(open(os.environ["MOTION324_MANIFEST"], "r").read()) +for obj in data.get("objects", []): + print(obj["name"]) +PY + ) + + DEFORM_MASK_STRIDE_RESOLVED="${DEFORM_MASK_STRIDE:-}" + if [[ -z "$DEFORM_MASK_STRIDE_RESOLVED" ]]; then + DEFORM_MASK_STRIDE_RESOLVED="$( + "$OPG_PY" - "$BATCH_CONFIG" <<'PY' +import json +import pathlib +import sys +path = pathlib.Path(sys.argv[1]) +try: + cfg = json.loads(path.read_text(encoding="utf-8")) + stride = int(cfg.get("tracker", {}).get("sample_stride", 1) or 1) +except Exception: + stride = 1 +print(max(1, stride)) +PY + )" + fi + if [[ -z "$DEFORM_MASK_STRIDE_RESOLVED" ]]; then + DEFORM_MASK_STRIDE_RESOLVED="1" + fi + echo "[3.12/4] Deform mask stride: $DEFORM_MASK_STRIDE_RESOLVED" + DEFORM_RENDER_FLAG="" + if [[ "$DEFORM_RENDER_VIDEO" == "1" ]]; then + DEFORM_RENDER_FLAG="--render-video" + fi + + if [[ "$DEFORM_POSE_MODE" != "ref" && ! -x "$BLENDER_BIN" ]]; then + echo "ERROR: $DEFORM_POSE_MODE pose mode requires Blender binary: $BLENDER_BIN" >&2 + exit 1 + fi + + echo "[3.13/4] Deform scale + full-frame pose estimation" + while IFS= read -r OBJ_NAME; do + if [[ -z "$OBJ_NAME" ]]; then + continue + fi + PYTHONPATH="$REPO/oneposeviagen/fpose:$PYTHONPATH" \ + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/deform_pose_pipeline.py \ + --run-dir "$RUN_DIR" \ + --mask-summary "$OUTPUT_ROOT/metadata/${NAME}_mask_summary.json" \ + --object-name "$OBJ_NAME" \ + --motion-output-root "$MOTION324_OUTPUT_ROOT" \ + --manifest "$MOTION324_MANIFEST" \ + --pose-mode "$DEFORM_POSE_MODE" \ + --frame-step "$DEFORM_FRAME_STEP" \ + --mask-stride "$DEFORM_MASK_STRIDE_RESOLVED" \ + $DEFORM_RENDER_FLAG \ + --blender-bin "$BLENDER_BIN" \ + --blender-lib "$BLENDER_LIB" + done <<< "$OBJ_LINES" + + echo "[3.14/4] Build deform world mesh sequences" + while IFS= read -r OBJ_NAME; do + if [[ -z "$OBJ_NAME" ]]; then + continue + fi + OBJ_ROOT="$MOTION324_OUTPUT_ROOT/$NAME/$OBJ_NAME" + MESH_FRAMES="$OBJ_ROOT/mesh_frames" + POSE_WORLD="$MOTION324_OUTPUT_ROOT/$NAME/$OBJ_NAME/poses_fp_world.json" + SCALE_JSON="$MOTION324_OUTPUT_ROOT/$NAME/$OBJ_NAME/scale.json" + WORLD_FRAMES="$OBJ_ROOT/world_mesh_frames" + if [[ ! -d "$MESH_FRAMES" ]]; then + echo " [Skip] mesh frames not found: $MESH_FRAMES" + continue + fi + if [[ ! -f "$POSE_WORLD" || ! -f "$SCALE_JSON" ]]; then + echo " [Skip] missing pose/scale for $OBJ_NAME" + continue + fi + + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/deform_apply_world_pose.py \ + --mesh-frames "$MESH_FRAMES" \ + --poses-world "$POSE_WORLD" \ + --scale 1.0 \ + --scale-json "$SCALE_JSON" \ + --output-dir "$WORLD_FRAMES" + done <<< "$OBJ_LINES" + + DEFORM_WORLD_FRAMES_DIR="world_mesh_frames" + if [[ "$EXPORT_PHYSICS_GLB" == "1" ]]; then + if [[ ! -f "$ALIGN_JSON" ]]; then + echo " [Warn] alignment not found, skip deform physics projection: $ALIGN_JSON" + else + echo "[3.14/4] Physics Z-projection for deform mesh sequences" + PHYS_LOCK_FLAG="" + if [[ "$LOCK_STATIC" == "1" ]]; then + PHYS_LOCK_FLAG="--use-locked-static" + fi + PHYS_ALLOW_FLAG="" + if [[ "$PHYSICS_ALLOW_DOWN" == "1" ]]; then + PHYS_ALLOW_FLAG="--allow-down" + fi + PHYS_CONTACT_FLAG="" + if [[ "$PHYSICS_CONTACT" == "1" ]]; then + PHYS_CONTACT_FLAG="--contact-objects" + fi + + PATH="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin:$PATH" \ + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/physics_project_z_deform_seq.py \ + --run-dir "$RUN_DIR" \ + --config "$CONFIG_JSON" \ + --alignment "$ALIGN_JSON" \ + --motion-output-root "$MOTION324_OUTPUT_ROOT" \ + --video-name "$NAME" \ + --manifest "$MOTION324_MANIFEST" \ + --deform-frames-dir world_mesh_frames \ + --deform-output-frames-dir world_mesh_frames_physics \ + --rigid-pose-name poses_physics.json \ + --plane-z zero \ + --bottom-percent "$PHYSICS_BOTTOM" \ + --iters "$PHYSICS_ITERS" \ + --max-drop "$PHYSICS_MAX_DROP" \ + $PHYS_LOCK_FLAG \ + $PHYS_ALLOW_FLAG \ + $PHYS_CONTACT_FLAG + + DEFORM_WORLD_FRAMES_DIR="world_mesh_frames_physics" + fi + fi + + if [[ "$EXPORT_SCENE_MESH_FRAMES" == "1" ]]; then + echo "[3.15/4] Export unified scene mesh frames (static+rigid+deform)" + SCENE_POSE_NAME="" + if [[ "$EXPORT_PHYSICS_GLB" == "1" ]]; then + SCENE_POSE_NAME="poses_physics.json" + fi + EXPORT_CMD=( + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/export_scene_mesh_frames.py + --run-dir "$RUN_DIR" + --config "$CONFIG_JSON" + --output-dir "$RUN_DIR/scene_mesh_frames_all_world" + --deform-root "$MOTION324_OUTPUT_ROOT" + --deform-manifest "$MOTION324_MANIFEST" + --deform-frames-dir "$DEFORM_WORLD_FRAMES_DIR" + ) + if [[ -n "$SCENE_POSE_NAME" ]]; then + EXPORT_CMD+=(--pose-name "$SCENE_POSE_NAME") + fi + if [[ "$LOCK_STATIC" == "1" ]]; then + EXPORT_CMD+=(--use-locked-static) + fi + if [[ -f "$ALIGN_JSON" ]]; then + EXPORT_CMD+=(--alignment "$ALIGN_JSON") + fi + PATH="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin:$PATH" "${EXPORT_CMD[@]}" + fi + fi +fi + +echo "[4/4] Render mesh video" +POSE_NAME="poses.json" +LOCK_TAG="unlocked" +if [[ "$LOCK_STATIC" == "1" ]]; then + POSE_NAME="poses_locked.json" + LOCK_TAG="locked" +fi + +OUT_DIR="$RUN_DIR/render_mesh_${RENDER_BG}_${LOCK_TAG}" +PATH="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin:$PATH" \ +CUDA_VISIBLE_DEVICES="$CUDA_VISIBLE_DEVICES" \ +"$OPG_PY" oneposeviagen/scripts/render_multi_objects.py \ + --objects_root "$RUN_DIR/objects" \ + --intrinsics "$RUN_DIR/intrinsics.json" \ + --rgb_dir "$RUN_DIR/rgb" \ + --out_dir "$OUT_DIR" \ + --background "$RENDER_BG" \ + --light \ + --pose_name "$POSE_NAME" + +cd "$OUT_DIR" +PATH="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin:$PATH" \ +ffmpeg -y -framerate "$FPS" -i %06d.png -c:v libx264 -pix_fmt yuv420p "$RUN_DIR/render_mesh_${RENDER_BG}_${LOCK_TAG}.mp4" + +echo "Done." +echo "Run dir: $RUN_DIR" +echo "Video: $RUN_DIR/render_mesh_${RENDER_BG}_${LOCK_TAG}.mp4" +if [[ "$DEFORM_COUNT" -gt 0 && "$EXPORT_SCENE_MESH_FRAMES" == "1" ]]; then + echo "Scene: $RUN_DIR/scene_mesh_frames_all_world" +fi diff --git a/OVOW/engine/pipe_deform_fbx.sh b/OVOW/engine/pipe_deform_fbx.sh new file mode 100644 index 0000000000000000000000000000000000000000..1bf00afa0026f21e9cc7f643470d860dde288ae9 --- /dev/null +++ b/OVOW/engine/pipe_deform_fbx.sh @@ -0,0 +1,430 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +NAME="" +OBJECT="" +OUT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs" +RUN_DIR="" +MOTION_ROOT="" +MANIFEST="" +POSE_JSON="poses_fp_world.json" +ALIGNMENT="" +COORD="blender_noflip" +FPS="10" +FRAME_OFFSET="" +EXPORT_GLB="1" +EXPORT_BLEND="0" +OUTPUT_ROOT="" +SUMMARY_OUT="" +BLENDER_BIN="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/opt/blender-4.2.3-linux-x64/blender" +BLENDER_LIB="" +OPG_PY="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python" + +usage() { + cat </motion324_outputs) + --manifest PATH Motion324 manifest (default: //manifest.json) + --pose-json NAME|PATH Pose json (default: ${POSE_JSON}) + --alignment PATH alignment_plane.json (default: /alignment_plane.json if exists) + --coord MODE raw|opengl|blender|blender_noflip|blender_zup|gltf (default: ${COORD}) + --fps NUM Timeline FPS for exported assets (default: ${FPS}) + --frame-offset INT Force pose frame offset; default auto align to imported action start + --output-root DIR Output root for exports (default: per-object under motion324_outputs) + --summary-out PATH Output summary json + --export-glb 0|1 Also export GLB beside FBX (default: ${EXPORT_GLB}) + --export-blend 0|1 Also save a .blend beside FBX (default: ${EXPORT_BLEND}) + --blender-bin PATH Blender binary (default: ${BLENDER_BIN}) + --blender-lib PATH Blender lib for LD_LIBRARY_PATH (default: ${BLENDER_LIB}) + --opg-py PATH Python used for manifest parsing (default: ${OPG_PY}) + --help Show this help + +Example: + bash pipe_deform_fbx.sh --name V0 --object rhinoceros_01 --pose-json poses_fp_world.json +USAGE +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --name) + NAME="$2" + shift 2 + ;; + --object) + OBJECT="$2" + shift 2 + ;; + --out) + OUT="$2" + shift 2 + ;; + --run-dir) + RUN_DIR="$2" + shift 2 + ;; + --motion-root) + MOTION_ROOT="$2" + shift 2 + ;; + --manifest) + MANIFEST="$2" + shift 2 + ;; + --pose-json) + POSE_JSON="$2" + shift 2 + ;; + --alignment) + ALIGNMENT="$2" + shift 2 + ;; + --coord) + COORD="$2" + shift 2 + ;; + --fps) + FPS="$2" + shift 2 + ;; + --frame-offset) + FRAME_OFFSET="$2" + shift 2 + ;; + --output-root) + OUTPUT_ROOT="$2" + shift 2 + ;; + --summary-out) + SUMMARY_OUT="$2" + shift 2 + ;; + --export-glb) + EXPORT_GLB="$2" + shift 2 + ;; + --export-blend) + EXPORT_BLEND="$2" + shift 2 + ;; + --blender-bin) + BLENDER_BIN="$2" + shift 2 + ;; + --blender-lib) + BLENDER_LIB="$2" + shift 2 + ;; + --opg-py) + OPG_PY="$2" + shift 2 + ;; + --help|-h) + usage + exit 0 + ;; + *) + echo "Unknown argument: $1" >&2 + usage + exit 1 + ;; + esac +done + +if [[ -z "${NAME}" ]]; then + echo "ERROR: --name is required." >&2 + usage + exit 1 +fi + +if [[ ! -x "${OPG_PY}" ]]; then + echo "ERROR: python not executable: ${OPG_PY}" >&2 + exit 1 +fi +if [[ ! -x "${BLENDER_BIN}" ]]; then + echo "ERROR: Blender not executable: ${BLENDER_BIN}" >&2 + exit 1 +fi + +if [[ -z "${MOTION_ROOT}" ]]; then + MOTION_ROOT="${OUT}/motion324_outputs" +fi +if [[ -z "${MANIFEST}" ]]; then + MANIFEST="${MOTION_ROOT}/${NAME}/manifest.json" +fi +if [[ ! -f "${MANIFEST}" ]]; then + echo "ERROR: manifest missing: ${MANIFEST}" >&2 + exit 1 +fi + +if [[ -z "${RUN_DIR}" ]]; then + state_json="${OUT}/metadata/${NAME}_step_state.json" + if [[ -f "${state_json}" ]]; then + RUN_DIR="$("${OPG_PY}" - "${state_json}" <<'PY' +import json, sys +from pathlib import Path +p = Path(sys.argv[1]) +try: + d = json.loads(p.read_text()) +except Exception: + print("") + raise SystemExit +v = d.get("run_dir", "") +print(v if isinstance(v, str) else "") +PY +)" + fi +fi +if [[ -z "${RUN_DIR}" ]]; then + latest="$(ls -dt "${OUT}"/video_pipeline_*/"${NAME}" 2>/dev/null | head -n 1 || true)" + if [[ -n "${latest}" ]]; then + RUN_DIR="${latest}" + fi +fi + +if [[ "${ALIGNMENT,,}" == "none" ]]; then + ALIGNMENT="" +fi +if [[ -z "${ALIGNMENT}" && -n "${RUN_DIR}" && -f "${RUN_DIR}/alignment_plane.json" ]]; then + ALIGNMENT="${RUN_DIR}/alignment_plane.json" +fi +if [[ -n "${ALIGNMENT}" && ! -f "${ALIGNMENT}" ]]; then + echo "ERROR: alignment file not found: ${ALIGNMENT}" >&2 + exit 1 +fi + +if [[ -z "${SUMMARY_OUT}" ]]; then + SUMMARY_OUT="${MOTION_ROOT}/${NAME}/deform_fbx_world_manifest.json" +fi + +if [[ -n "${OBJECT}" ]]; then + object_names="${OBJECT}" +else + object_names="$("${OPG_PY}" - "${MANIFEST}" <<'PY' +import json, sys +from pathlib import Path +m = Path(sys.argv[1]) +d = json.loads(m.read_text()) +for obj in d.get("objects", []): + name = str(obj.get("name", "")).strip() + if name: + print(name) +PY +)" +fi + +if [[ -z "${object_names}" ]]; then + echo "[pipe_deform_fbx] No deform objects found in manifest." + exit 0 +fi + +tmp_tsv="$(mktemp "/tmp/deform_fbx_${NAME}_XXXXXX.tsv")" +cleanup() { + rm -f "${tmp_tsv}" +} +trap cleanup EXIT + +while IFS= read -r obj_name; do + [[ -z "${obj_name}" ]] && continue + obj_root="${MOTION_ROOT}/${NAME}/${obj_name}" + if [[ ! -d "${obj_root}" ]]; then + echo "[Warn] skip ${obj_name}: missing object output dir: ${obj_root}" + continue + fi + + anim_fbx="$("${OPG_PY}" - "${MANIFEST}" "${obj_name}" <<'PY' +import json, sys +from pathlib import Path + +manifest = Path(sys.argv[1]).resolve() +obj_name = sys.argv[2] +d = json.loads(manifest.read_text()) + +def _resolve(p): + q = Path(p) + if not q.is_absolute(): + q = (manifest.parent / q).resolve() + return q + +candidates = [] +for obj in d.get("objects", []): + if str(obj.get("name", "")) != obj_name: + continue + anim = obj.get("animation") + if isinstance(anim, str) and anim.strip(): + candidates.append(_resolve(anim.strip())) + proc = obj.get("processed_dir") + if isinstance(proc, str) and proc.strip(): + proc_p = _resolve(proc.strip()) + candidates.append(proc_p / "animation" / "output_animation.fbx") + candidates.append(proc_p / "animation" / "output_animation.glb") + break + +for p in candidates: + if p.suffix.lower() == ".fbx" and p.exists(): + print(str(p.resolve())) + raise SystemExit(0) +print("") +PY +)" + if [[ -z "${anim_fbx}" ]]; then + echo "[Warn] skip ${obj_name}: cannot find animation FBX from ${MANIFEST}" + continue + fi + + pose_path="$("${OPG_PY}" - "${obj_root}" "${POSE_JSON}" <<'PY' +import sys +from pathlib import Path + +obj_root = Path(sys.argv[1]).resolve() +spec = sys.argv[2] + +candidates = [] +spec_path = Path(spec) +if spec_path.is_absolute(): + candidates.append(spec_path) +else: + candidates.append(obj_root / spec_path) + if spec_path.parent == Path("."): + candidates.append(obj_root / "pose_result" / spec_path) + +candidates.extend([ + obj_root / "poses_fp_world.json", + obj_root / "poses_physics_world.json", + obj_root / "pose_result" / "poses_world.json", +]) + +seen = set() +for p in candidates: + rp = p.resolve() + key = str(rp) + if key in seen: + continue + seen.add(key) + if rp.exists(): + print(key) + raise SystemExit(0) +print("") +PY +)" + if [[ -z "${pose_path}" ]]; then + echo "[Warn] skip ${obj_name}: cannot find pose json (requested: ${POSE_JSON})" + continue + fi + + pose_tag="$(basename "${pose_path}")" + pose_tag="${pose_tag%.json}" + + if [[ -n "${OUTPUT_ROOT}" ]]; then + obj_out_dir="${OUTPUT_ROOT}/${obj_name}" + else + obj_out_dir="${obj_root}/fbx_world_pose_${pose_tag}" + fi + mkdir -p "${obj_out_dir}" + + out_fbx="${obj_out_dir}/${obj_name}_world_parent.fbx" + out_glb="" + out_blend="" + if [[ "${EXPORT_GLB}" == "1" ]]; then + out_glb="${obj_out_dir}/${obj_name}_world_parent.glb" + fi + if [[ "${EXPORT_BLEND}" == "1" ]]; then + out_blend="${obj_out_dir}/${obj_name}_world_parent.blend" + fi + + cmd=( + "${BLENDER_BIN}" -b + -P "${REPO}/tools/blender_apply_world_pose_to_fbx_parent.py" + -- + --input-fbx "${anim_fbx}" + --poses-world "${pose_path}" + --output-fbx "${out_fbx}" + --object-name "${obj_name}" + --coord "${COORD}" + --fps "${FPS}" + ) + if [[ -n "${ALIGNMENT}" ]]; then + cmd+=(--alignment "${ALIGNMENT}") + fi + if [[ -n "${FRAME_OFFSET}" ]]; then + cmd+=(--frame-offset "${FRAME_OFFSET}") + fi + if [[ -n "${out_glb}" ]]; then + cmd+=(--output-glb "${out_glb}") + fi + if [[ -n "${out_blend}" ]]; then + cmd+=(--output-blend "${out_blend}") + fi + + echo "[pipe_deform_fbx] object=${obj_name}" + echo " anim_fbx=${anim_fbx}" + echo " pose_json=${pose_path}" + echo " output_fbx=${out_fbx}" + if [[ -n "${out_glb}" ]]; then + echo " output_glb=${out_glb}" + fi + + LD_LIBRARY_PATH="${BLENDER_LIB}:${LD_LIBRARY_PATH:-}" "${cmd[@]}" + printf "%s\t%s\t%s\t%s\t%s\t%s\n" \ + "${obj_name}" "${anim_fbx}" "${pose_path}" "${out_fbx}" "${out_glb}" "${out_blend}" >> "${tmp_tsv}" +done <<< "${object_names}" + +"${OPG_PY}" - "${tmp_tsv}" "${SUMMARY_OUT}" "${NAME}" "${RUN_DIR}" "${ALIGNMENT}" "${COORD}" "${FPS}" "${POSE_JSON}" <<'PY' +import json +import sys +from pathlib import Path + +tsv_path = Path(sys.argv[1]) +summary_out = Path(sys.argv[2]) +scene_name = sys.argv[3] +run_dir = sys.argv[4] +alignment = sys.argv[5] +coord = sys.argv[6] +fps = float(sys.argv[7]) +pose_json = sys.argv[8] + +items = [] +if tsv_path.exists(): + for line in tsv_path.read_text().splitlines(): + toks = line.split("\t") + if len(toks) < 6: + continue + items.append( + { + "name": toks[0], + "input_fbx": toks[1], + "poses_world": toks[2], + "output_fbx": toks[3], + "output_glb": toks[4] or None, + "output_blend": toks[5] or None, + } + ) + +payload = { + "scene_name": scene_name, + "run_dir": run_dir or None, + "alignment": alignment or None, + "coord": coord, + "fps": fps, + "pose_json": pose_json, + "objects": items, +} +summary_out.parent.mkdir(parents=True, exist_ok=True) +summary_out.write_text(json.dumps(payload, indent=2)) +print(f"[OK] Summary: {summary_out}") +print(f"[OK] Exported objects: {len(items)}") +PY + diff --git a/OVOW/engine/pipe_deform_post.sh b/OVOW/engine/pipe_deform_post.sh new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/OVOW/engine/pipeline.py b/OVOW/engine/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..851b93f43332ca301fbf01c87eba1b4f212c9b40 --- /dev/null +++ b/OVOW/engine/pipeline.py @@ -0,0 +1,543 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import shutil +import subprocess +import traceback +from dataclasses import dataclass, field, replace +from datetime import datetime +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence + +import cv2 +import numpy as np + +import batch_scene_pipeline as bsp + + +@dataclass +class Motion324Config: + enabled: bool = False + script_path: Path = Path("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/third_party/Motion324/scripts/4D_from_video.sh") + backend: str = "hunyuan" + split_only: bool = False + + +@dataclass +class PipelineObject: + name: str + masks_dir: Path + category: str = "static" + is_occluded: bool = False + seed: Optional[int] = None + anchor_frame: Optional[int] = None + dynamic_backend: str = "motion324" + run_dynamic: bool = False + + +@dataclass +class PipelineConfig: + batch_config: Path + video_path: Path + objects: List[PipelineObject] + output_root: Path = Path("temp_local") + mask_glob: str = "frame_*.png" + tracker_mask_mode: str = "none" + motion324: Motion324Config = field(default_factory=Motion324Config) + + +def _resolve_path(base: Path, value: str) -> Path: + p = Path(value) + return p if p.is_absolute() else (base / p).resolve() + + +def load_pipeline_config(path: Path) -> PipelineConfig: + with path.open("r", encoding="utf-8") as f: + data = json.load(f) + base = path.parent.resolve() + batch_config = _resolve_path(base, data["batch_config"]) + video_path = _resolve_path(base, data["video_path"]) + output_root = _resolve_path(base, data.get("output_root", "temp_local")) + mask_glob = str(data.get("mask_glob", "frame_*.png")) + tracker_mask_mode = str(data.get("tracker_mask_mode", "none")).strip().lower() + motion_cfg = Motion324Config(**data.get("motion324", {})) + + objects: List[PipelineObject] = [] + for entry in data.get("objects", []): + name = entry.get("name") or entry.get("id") + masks_dir = entry.get("masks_dir") or entry.get("masks") + if not name or not masks_dir: + raise ValueError("Each object needs name and masks_dir.") + objects.append( + PipelineObject( + name=str(name), + masks_dir=_resolve_path(base, str(masks_dir)), + category=str(entry.get("category", "static")).strip().lower(), + is_occluded=bool(entry.get("is_occluded", False)), + seed=entry.get("seed"), + anchor_frame=entry.get("anchor_frame"), + dynamic_backend=str(entry.get("dynamic_backend", "motion324")).strip().lower(), + run_dynamic=bool(entry.get("run_dynamic", False)), + ) + ) + + if tracker_mask_mode not in {"none", "static", "all"}: + raise ValueError(f"tracker_mask_mode must be none/static/all, got {tracker_mask_mode}") + if not objects: + raise ValueError("Config must include objects.") + + return PipelineConfig( + batch_config=batch_config, + video_path=video_path, + objects=objects, + output_root=output_root, + mask_glob=mask_glob, + tracker_mask_mode=tracker_mask_mode, + motion324=motion_cfg, + ) + + +def _parse_mask_frame_id(path: Path) -> Optional[int]: + stem = path.stem + if stem.startswith("frame_"): + stem = stem[len("frame_") :] + try: + return int(stem) + except Exception: + return None + + +def _pick_nearest_frame(target: int, frames: Sequence[int]) -> int: + import bisect + + pos = bisect.bisect_left(frames, target) + cand: List[int] = [] + if pos < len(frames): + cand.append(frames[pos]) + if pos > 0: + cand.append(frames[pos - 1]) + return min(cand, key=lambda x: abs(x - target)) + + +def _mask_shape_from_mapping(mapping: Dict[int, Path]) -> tuple[int, int]: + for path in mapping.values(): + mask = cv2.imread(str(path), cv2.IMREAD_GRAYSCALE) + if mask is not None: + return mask.shape[:2] + raise FileNotFoundError("No readable mask image found.") + + +def _blank_mask_for_frame(masks_dir: Path, shape: tuple[int, int], frame_id: int) -> Path: + blank_dir = masks_dir / "_generated_blank_masks" + blank_dir.mkdir(parents=True, exist_ok=True) + out_path = blank_dir / f"frame_{frame_id:06d}.png" + if not out_path.exists(): + h, w = shape + cv2.imwrite(str(out_path), np.zeros((h, w), dtype=np.uint8)) + return out_path + + +def _looks_like_sparse_manual_masks(frame_ids: Sequence[int], num_frames: int) -> bool: + return len(frame_ids) < max(3, num_frames // 2) + + +def build_object_mask_sequence( + masks_dir: Path, mask_glob: str, num_frames: int, sample_stride: int +) -> List[Path]: + files = sorted(masks_dir.glob(mask_glob)) + mapping: Dict[int, Path] = {} + for p in files: + fid = _parse_mask_frame_id(p) + if fid is None: + continue + mapping[int(fid)] = p + if not mapping: + raise FileNotFoundError(f"No masks found in {masks_dir} (glob={mask_glob})") + frame_ids = sorted(mapping.keys()) + sparse_manual = _looks_like_sparse_manual_masks(frame_ids, num_frames) + blank_shape = _mask_shape_from_mapping(mapping) if sparse_manual else None + seq: List[Path] = [] + for i in range(num_frames): + target = int(i * sample_stride) + if sparse_manual: + mask_path = mapping.get(target) + if mask_path is None: + if blank_shape is None: + raise FileNotFoundError("No readable mask image found.") + mask_path = _blank_mask_for_frame(masks_dir, blank_shape, target) + else: + nearest = _pick_nearest_frame(target, frame_ids) + mask_path = mapping[nearest] + seq.append(mask_path.resolve()) + return seq + + +def maybe_write_tracker_union_mask( + session_dir: Path, + video_name: str, + objects: Sequence[PipelineObject], + object_mask_sequences: Dict[str, List[Path]], + mode: str, +) -> Optional[Path]: + if mode == "none": + return None + + rgb0 = session_dir / "rgb" / "000000.jpg" + frame = cv2.imread(str(rgb0)) + if frame is None: + raise FileNotFoundError(f"Missing {rgb0}") + h, w = frame.shape[:2] + + include_names: List[str] = [] + for obj in objects: + if mode == "all": + include_names.append(obj.name) + elif mode == "static" and obj.category == "static": + include_names.append(obj.name) + + if not include_names: + return None + + union_mask = np.zeros((h, w), dtype=np.uint8) + for name in include_names: + seq = object_mask_sequences.get(name, []) + for p in seq: + mask = cv2.imread(str(p), cv2.IMREAD_GRAYSCALE) + if mask is None: + continue + if mask.shape != (h, w): + mask = cv2.resize(mask, (w, h), interpolation=cv2.INTER_NEAREST) + union_mask = np.maximum(union_mask, (mask > 0).astype(np.uint8) * 255) + + out_path = session_dir / f"{video_name}.png" + cv2.imwrite(str(out_path), union_mask) + return out_path + + +def _video_fps(video_path: Path) -> float: + cap = cv2.VideoCapture(str(video_path)) + if not cap.isOpened(): + return 1.0 + try: + fps = float(cap.get(cv2.CAP_PROP_FPS)) + finally: + cap.release() + return fps if fps > 0 else 1.0 + + +def _safe_name(name: str) -> str: + return "".join(c if c.isalnum() or c in ("-", "_") else "_" for c in name) + + +def write_masked_video( + rgb_paths: Sequence[Path], + mask_paths: Sequence[Path], + out_path: Path, + fps: float, +) -> None: + if not rgb_paths: + raise ValueError("rgb_paths is empty") + first = cv2.imread(str(rgb_paths[0])) + if first is None: + raise FileNotFoundError(f"Missing {rgb_paths[0]}") + h, w = first.shape[:2] + out_path.parent.mkdir(parents=True, exist_ok=True) + writer = cv2.VideoWriter( + str(out_path), + cv2.VideoWriter_fourcc(*"mp4v"), + float(fps), + (w, h), + ) + for rgb_path, mask_path in zip(rgb_paths, mask_paths): + rgb = cv2.imread(str(rgb_path)) + if rgb is None: + continue + mask = cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE) + if mask is None: + continue + if mask.shape != (h, w): + mask = cv2.resize(mask, (w, h), interpolation=cv2.INTER_NEAREST) + masked = cv2.bitwise_and(rgb, rgb, mask=(mask > 0).astype(np.uint8) * 255) + writer.write(masked) + writer.release() + + +def run_motion324(masked_video: Path, cfg: Motion324Config) -> Optional[Path]: + if not cfg.script_path.exists(): + raise FileNotFoundError(f"Motion324 script not found: {cfg.script_path}") + cmd = ["bash", str(cfg.script_path), str(masked_video), "--backend", cfg.backend] + if cfg.split_only: + cmd.append("--split_only") + subprocess.run(cmd, check=True) + return masked_video.parent / f"{masked_video.stem}_processed" / "animation" + + +def run_pipeline( + cfg: PipelineConfig, + *, + continue_on_object_error: bool = True, + object_error_report: Optional[Path] = None, +) -> Path: + base_cfg = bsp.load_batch_config(cfg.batch_config) + + state = bsp.prepare_session_from_video(str(cfg.video_path), base_cfg.tracker.sample_stride) + + run_root = cfg.output_root / f"video_pipeline_{datetime.now().strftime('%Y%m%d_%H%M%S')}" + run_root.mkdir(parents=True, exist_ok=True) + session_dir = Path(state.temp_dir).resolve() + final_session_dir = (run_root / _safe_name(cfg.video_path.stem)).resolve() + if final_session_dir.exists(): + shutil.rmtree(final_session_dir) + final_session_dir.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(session_dir), str(final_session_dir)) + session_dir = final_session_dir + state.temp_dir = str(session_dir) + + rgb_paths = bsp.list_ordered_frames(session_dir / "rgb", "jpg") + num_frames = len(rgb_paths) + object_mask_sequences: Dict[str, List[Path]] = {} + failed_objects: List[Dict[str, Any]] = [] + object_status: Dict[str, Dict[str, str]] = {} + + def _archive_failed_object_dir(obj_name: str) -> str: + src = session_dir / "objects" / obj_name + if not src.exists(): + return "" + dst_root = session_dir / "objects_failed" + dst_root.mkdir(parents=True, exist_ok=True) + dst = dst_root / obj_name + if dst.exists(): + shutil.rmtree(dst) + shutil.move(str(src), str(dst)) + return str(dst.resolve()) + + def _record_object_failure(obj: PipelineObject, stage: str, exc: Exception) -> None: + err_msg = str(exc) + tb = traceback.format_exc() + archived_dir = _archive_failed_object_dir(obj.name) + failed_objects.append( + { + "name": obj.name, + "category": obj.category, + "stage": stage, + "error": err_msg, + "traceback": tb, + "time": datetime.utcnow().isoformat() + "Z", + "archived_dir": archived_dir or None, + } + ) + object_status[obj.name] = { + "name": obj.name, + "category": obj.category, + "status": "failed", + "stage": stage, + "error": err_msg, + } + print(f"[Warn] Skip object {obj.name}: {err_msg}") + + for obj in cfg.objects: + try: + object_mask_sequences[obj.name] = build_object_mask_sequence( + obj.masks_dir, cfg.mask_glob, num_frames, base_cfg.tracker.sample_stride + ) + except Exception as exc: # noqa: BLE001 + if not continue_on_object_error: + raise + _record_object_failure(obj, "build_mask_sequence", exc) + + maybe_write_tracker_union_mask( + session_dir, + state.video_name, + cfg.objects, + object_mask_sequences, + cfg.tracker_mask_mode, + ) + + bsp.run_tracker_if_needed(state, base_cfg) + rgb_paths, depth_paths, intrinsics = bsp.load_session_sequences(session_dir) + + static_results: List[bsp.ObjectResult] = [] + dynamic_results: List[Dict[str, Optional[str]]] = [] + succeeded_names: List[str] = [] + + for obj in cfg.objects: + if object_status.get(obj.name, {}).get("status") == "failed": + continue + masks = object_mask_sequences.get(obj.name, []) + if not masks: + if continue_on_object_error: + _record_object_failure(obj, "build_mask_sequence", FileNotFoundError("Mask sequence is empty.")) + continue + raise FileNotFoundError(f"Mask sequence is empty for {obj.name}") + + try: + if obj.category in {"static", "rigid"}: + obj_anchor = obj.anchor_frame + scale_cfg = base_cfg.scale + if obj_anchor is not None: + scale_cfg = replace( + base_cfg.scale, + anchor_frame=int(np.clip(int(obj_anchor), 0, max(0, len(rgb_paths) - 1))), + anchor_frame_mode="fixed", + ) + mask_idx = int(np.clip(int(obj_anchor), 0, max(0, len(masks) - 1))) + else: + mask_idx = 0 + scene_obj = bsp.SceneObject( + name=obj.name, + mask_path=masks[mask_idx], + is_occluded=obj.is_occluded, + seed=obj.seed, + ) + result = bsp.process_object( + scene_obj, + masks, + session_dir, + session_dir, + rgb_paths, + depth_paths, + intrinsics, + base_cfg.generation, + scale_cfg, + ) + static_results.append(result) + elif obj.category == "deform": + obj_dir = session_dir / "dynamic" / _safe_name(obj.name) + obj_dir.mkdir(parents=True, exist_ok=True) + fps = _video_fps(cfg.video_path) + out_fps = max(1.0, fps / max(1, base_cfg.tracker.sample_stride)) + masked_video = obj_dir / f"{_safe_name(obj.name)}_masked.mp4" + write_masked_video(rgb_paths, masks, masked_video, out_fps) + motion_dir = None + if obj.run_dynamic or cfg.motion324.enabled: + motion_cfg = cfg.motion324 + if obj.run_dynamic and not motion_cfg.enabled: + motion_cfg = Motion324Config( + enabled=True, + script_path=motion_cfg.script_path, + backend=motion_cfg.backend, + split_only=motion_cfg.split_only, + ) + motion_dir = run_motion324(masked_video, motion_cfg) + dynamic_results.append( + { + "name": obj.name, + "category": obj.category, + "masked_video": str(masked_video), + "motion324_dir": str(motion_dir) if motion_dir else None, + } + ) + else: + raise ValueError(f"Unknown category: {obj.category}") + object_status[obj.name] = { + "name": obj.name, + "category": obj.category, + "status": "succeeded", + "stage": "done", + "error": "", + } + succeeded_names.append(obj.name) + except Exception as exc: # noqa: BLE001 + if not continue_on_object_error: + raise + _record_object_failure(obj, "process_object", exc) + + point_cloud = bsp.export_scene_point_cloud(session_dir, base_cfg.generation) + combined_cloud = bsp.export_scene_objects_combined( + session_dir, point_cloud, static_results, base_cfg.generation + ) + + report_path = object_error_report.resolve() if object_error_report is not None else session_dir / "object_errors_step6.json" + report_path.parent.mkdir(parents=True, exist_ok=True) + failed_payload = { + "video": str(cfg.video_path), + "run_dir": str(session_dir), + "generated_at": datetime.utcnow().isoformat() + "Z", + "failed_objects": failed_objects, + "failed_names": sorted({item["name"] for item in failed_objects}), + } + report_path.write_text(json.dumps(failed_payload, indent=2), encoding="utf-8") + + status_path = session_dir / "object_status_step6.json" + ordered_status: List[Dict[str, str]] = [] + for obj in cfg.objects: + if obj.name not in object_status: + object_status[obj.name] = { + "name": obj.name, + "category": obj.category, + "status": "skipped", + "stage": "unknown", + "error": "", + } + ordered_status.append(object_status[obj.name]) + status_payload = { + "video": str(cfg.video_path), + "run_dir": str(session_dir), + "generated_at": datetime.utcnow().isoformat() + "Z", + "objects": ordered_status, + "succeeded_names": sorted(set(succeeded_names)), + "failed_names": sorted({item["name"] for item in failed_objects}), + } + status_path.write_text(json.dumps(status_payload, indent=2), encoding="utf-8") + + summary = { + "video": str(cfg.video_path), + "session_dir": str(session_dir), + "scene_point_cloud": str(point_cloud) if point_cloud else None, + "combined_cloud": str(combined_cloud) if combined_cloud else None, + "object_error_report": str(report_path), + "object_status_report": str(status_path), + "failed_objects": failed_objects, + "static_objects": [ + { + "name": obj.name, + "object_dir": str(obj.object_dir), + "scaled_mesh": str(obj.scaled_mesh), + "pose_json": str(obj.pose_json), + "pose_video": str(obj.pose_video), + } + for obj in static_results + ], + "dynamic_objects": dynamic_results, + } + summary_path = run_root / "summary.json" + with summary_path.open("w", encoding="utf-8") as f: + json.dump(summary, f, indent=2) + + return run_root + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Video pipeline for static + dynamic meshes.") + parser.add_argument("--config", type=Path, required=True, help="Pipeline config JSON") + parser.add_argument( + "--continue-on-object-error", + type=int, + choices=[0, 1], + default=1, + help="Continue processing remaining objects when one object fails (default: 1)", + ) + parser.add_argument( + "--object-error-report", + type=Path, + default=None, + help="Optional output path for object-level error report JSON", + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + cfg = load_pipeline_config(args.config) + run_root = run_pipeline( + cfg, + continue_on_object_error=bool(args.continue_on_object_error), + object_error_report=args.object_error_report, + ) + print(f"Done. Output: {run_root}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/pipeline_core.py b/OVOW/engine/pipeline_core.py new file mode 100644 index 0000000000000000000000000000000000000000..1b2d26bd0356b1a617a933608b906ca4f76d1721 --- /dev/null +++ b/OVOW/engine/pipeline_core.py @@ -0,0 +1,1363 @@ +#!/usr/bin/env python3 +"""Headless pipeline utilities shared by batch scripts.""" + +import base64 +import glob +import json +import os +os.environ['OPENCV_IO_ENABLE_OPENEXR'] = '1' +os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True" +import shutil +import subprocess +import sys +import time +import uuid +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +import cv2 +import imageio +import numpy as np +import torch +import trimesh +from PIL import Image +import o_voxel + +current_dir = os.path.dirname(os.path.abspath(__file__)) +cache_root = os.path.abspath(os.path.join(current_dir, "..", ".cache")) +torch_cache = os.path.join(cache_root, "torch") +hf_cache = os.path.join(cache_root, "huggingface") + +if os.path.isdir(torch_cache): + os.environ.setdefault("TORCH_HOME", torch_cache) +if os.path.isdir(hf_cache): + os.environ.setdefault("HF_HOME", hf_cache) + os.environ.setdefault("HUGGINGFACE_HUB_CACHE", os.path.join(hf_cache, "hub")) +submodule_paths = [ + os.path.join(current_dir, "oneposeviagen", "SpaTrackerV2"), + os.path.join(current_dir, "oneposeviagen", "SAM2-in-video"), + os.path.join(current_dir, "oneposeviagen", "fpose"), + os.path.join(current_dir, "oneposeviagen", "Amodal3R"), + os.path.join(current_dir, "oneposeviagen", "trellis"), + os.path.join(current_dir, "oneposeviagen", "TRELLIS.2"), +] +for lib_path in submodule_paths: + if os.path.exists(lib_path) and lib_path not in sys.path: + sys.path.insert(0, lib_path) + + +os.environ.setdefault( + "GRADIO_FRPC_BINARY", + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/.cache/huggingface/gradio/frpc/frpc_linux_amd64_v0.3", +) +if torch.cuda.is_available(): + os.environ.setdefault( + "TORCH_CUDA_ARCH_LIST", + ".".join(map(str, torch.cuda.get_device_capability())), + ) +os.environ.setdefault("ATTN_BACKEND", "xformers") +os.environ.setdefault("HF_ENDPOINT", "https://hf-mirror.com") +os.environ.setdefault("OPENCV_IO_ENABLE_OPENEXR", "1") + +from models.SpaTrackV2.models.vggt4track.models.vggt_moe import VGGT4Track +from models.SpaTrackV2.models.vggt4track.utils.load_fn import preprocess_image +from models.SpaTrackV2.models.predictor import Predictor + +from app_3rd.spatrack_utils.infer_track import get_tracker_predictor, get_points_on_a_grid +from fpose.recover_scale import recover_scale +from amodal3r.pipelines import Amodal3RImageTo3DPipeline +from amodal3r.utils import render_utils, postprocessing_utils +from trellis.pipelines import TrellisImageTo3DPipeline +from trellis.utils import render_utils as render_utils_hi3dgen +from trellis.utils import postprocessing_utils as postprocessing_utils_hi3dgen + + +def _get_env_target_size(default: Optional[int] = None) -> Optional[int]: + value = os.getenv("OPG_TARGET_SIZE") + if value is None or value == "": + return default + try: + parsed = int(value) + except ValueError: + return default + return parsed if parsed > 0 else default + +MAX_SEED = np.iinfo(np.int32).max +VIDEO_FPS = 10 +MAX_FRAMES_OFFLINE = 50 + +print("🚀 Initializing core models for batch pipeline (lazy tracker loading enabled)...") +vggt4track_model = None +tracker_model_offline = None +tracker_model_online = None + + +def _get_vggt4track_model(): + global vggt4track_model + if vggt4track_model is None: + print("🚀 Loading VGGT4Track model...") + vggt4track_model = VGGT4Track.from_pretrained( + "checkpoints/OnePoseViaGen/SpatialTrackerV2/vggt_front" + ) + vggt4track_model.eval() + vggt4track_model = vggt4track_model.to("cuda") + return vggt4track_model + + +def _get_spatracker_model(mode: str): + global tracker_model_offline, tracker_model_online + if mode == "offline": + if tracker_model_offline is None: + print("🚀 Loading SpatialTrackerV2 offline model...") + tracker_model_offline = Predictor.from_pretrained( + "checkpoints/OnePoseViaGen/SpatialTrackerV2/tracker_offline" + ) + tracker_model_offline.eval() + return tracker_model_offline + if tracker_model_online is None: + print("🚀 Loading SpatialTrackerV2 online model...") + tracker_model_online = Predictor.from_pretrained( + "checkpoints/OnePoseViaGen/SpatialTrackerV2/tracker_online" + ) + tracker_model_online.eval() + return tracker_model_online + +_amodal3r_pipeline: Optional[Amodal3RImageTo3DPipeline] = None +_hi3dgen_pipeline: Optional[TrellisImageTo3DPipeline] = None +_trellis2_pipelines: Dict[str, object] = {} +_trellis2_envmaps: Dict[str, object] = {} + + + + +def get_amodal3r_pipeline( + checkpoint_path: str = "checkpoints/OnePoseViaGen/Amodal3R", +) -> Amodal3RImageTo3DPipeline: + global _amodal3r_pipeline + if _amodal3r_pipeline is None: + print(f"🚀 Loading Amodal3R pipeline from {checkpoint_path} ...") + _amodal3r_pipeline = Amodal3RImageTo3DPipeline.from_pretrained(checkpoint_path) + _amodal3r_pipeline.cuda() + return _amodal3r_pipeline + + +def get_hi3dgen_pipeline( + checkpoint_path: str = "checkpoints/OnePoseViaGen/Hi3DGen_Color", +) -> TrellisImageTo3DPipeline: + global _hi3dgen_pipeline + if _hi3dgen_pipeline is None: + print(f"🚀 Loading Hi3DGen pipeline from {checkpoint_path} ...") + _hi3dgen_pipeline = TrellisImageTo3DPipeline.from_pretrained(checkpoint_path) + _hi3dgen_pipeline.cuda() + return _hi3dgen_pipeline + + +def get_trellis2_pipeline( + checkpoint_path: str = "checkpoints/OnePoseViaGen/TRELLIS.2-4B", +): + """Lazy-load TRELLIS.2 pipeline to CUDA.""" + if not checkpoint_path: + raise ValueError("TRELLIS.2 checkpoint_path 不能为空") + + expanded = os.path.expandvars(os.path.expanduser(checkpoint_path)) + resolved = expanded if os.path.exists(expanded) else checkpoint_path + cached = _trellis2_pipelines.get(resolved) + if cached is None: + from trellis2.pipelines import Trellis2ImageTo3DPipeline + + print(f"🚀 Loading TRELLIS.2 pipeline from {resolved} ...") + cached = Trellis2ImageTo3DPipeline.from_pretrained(resolved) + cached.cuda() + _trellis2_pipelines[resolved] = cached + return cached + + +def get_trellis2_envmap(envmap_path: str = ""): + """Load (and cache) TRELLIS.2 EnvMap on CUDA for PBR preview rendering.""" + if not envmap_path: + envmap_path = os.path.join( + current_dir, "oneposeviagen", "TRELLIS.2", "assets", "hdri", "forest.exr" + ) + + expanded = os.path.expandvars(os.path.expanduser(envmap_path)) + resolved = expanded if os.path.exists(expanded) else envmap_path + cached = _trellis2_envmaps.get(resolved) + if cached is None: + from trellis2.renderers import EnvMap + + hdr = cv2.imread(resolved, cv2.IMREAD_UNCHANGED) + if hdr is None: + raise FileNotFoundError(f"无法读取 TRELLIS.2 envmap: {resolved}") + hdr_rgb = cv2.cvtColor(hdr, cv2.COLOR_BGR2RGB) + cached = EnvMap(torch.tensor(hdr_rgb, dtype=torch.float32, device="cuda")) + _trellis2_envmaps[resolved] = cached + return cached + + +@dataclass +class SessionState: + temp_dir: str + video_name: str + video_path: str + fps: int + + + + +def create_user_temp_dir() -> str: + session_id = str(uuid.uuid4())[:8] + temp_dir = os.path.join("temp_local", f"session_{session_id}") + os.makedirs(temp_dir, exist_ok=True) + return temp_dir + + +def get_video_name(video_path: str) -> str: + return os.path.splitext(os.path.basename(video_path))[0] + + +def extract_first_frame(video_path: str) -> Optional[np.ndarray]: + cap = cv2.VideoCapture(video_path) + if not cap.isOpened(): + return None + ret, frame = cap.read() + cap.release() + if not ret: + return None + return cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + + +def numpy_to_base64(arr: np.ndarray) -> str: + _, buffer = cv2.imencode(".png", cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)) + return base64.b64encode(buffer).decode("utf-8") + + +def load_video_with_opencv(video_path: str) -> torch.Tensor: + cap = cv2.VideoCapture(video_path) + if not cap.isOpened(): + raise ValueError(f"无法打开视频文件: {video_path}") + frames = [] + while True: + ret, frame = cap.read() + if not ret: + break + frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + frames.append(frame) + cap.release() + if not frames: + raise ValueError("视频中没有有效帧") + video_array = np.stack(frames) + video_tensor = torch.from_numpy(video_array).permute(0, 3, 1, 2).float() + return video_tensor + + +def process_tensor(video_path: str, fps: int) -> torch.Tensor: + import torchvision.transforms as T + + video_tensor = load_video_with_opencv(video_path) + h, w = video_tensor.shape[2:] + target_size = _get_env_target_size(None) + if target_size: + scale = target_size / min(h, w) + if scale != 1: + new_h = int(h * scale) // 2 * 2 + new_w = int(w * scale) // 2 * 2 + if new_h > 0 and new_w > 0: + video_tensor = T.Resize((new_h, new_w))(video_tensor) + video_tensor = video_tensor[::fps].float()[:MAX_FRAMES_OFFLINE] + video_tensor = video_tensor.cuda() + if target_size is None: + target_size = int(video_tensor.shape[3]) + video_tensor = preprocess_image(video_tensor, target_size=target_size, keep_ratio=True)[None] + return video_tensor + + +def process_and_save_rgb(video_path: str, user_temp_dir: str, fps: int) -> None: + from torchvision.utils import save_image + + video_tensor = process_tensor(video_path, fps) + result = video_tensor[0] + output_dir = os.path.join(user_temp_dir, "rgb") + os.makedirs(output_dir, exist_ok=True) + for i in range(result.shape[0]): + img_tensor = result[i] + if img_tensor.max() <= 1.0: + img_tensor = img_tensor.clamp(0, 1) + else: + img_tensor = (img_tensor - img_tensor.min()) / ( + img_tensor.max() - img_tensor.min() + ) + save_image(img_tensor, os.path.join(output_dir, f"{i:06d}.jpg")) + + + + +def prepare_session_from_video(video_path: str, fps: int) -> SessionState: + temp_dir = create_user_temp_dir() + video_name = get_video_name(video_path) + dst_video = os.path.join(temp_dir, f"{video_name}.mp4") + shutil.copy(video_path, dst_video) + + frame = extract_first_frame(dst_video) + if frame is None: + raise RuntimeError("无法从视频中提取首帧") + h, w = frame.shape[:2] + target_size = _get_env_target_size(512) + scale = target_size / min(h, w) + new_h = int(h * scale) // 2 * 2 + new_w = int(w * scale) // 2 * 2 + frame = cv2.resize(frame, (new_w, new_h), interpolation=cv2.INTER_LINEAR) + + frame_data = { + "data": numpy_to_base64(frame), + "shape": frame.shape, + "dtype": str(frame.dtype), + "temp_dir": temp_dir, + "video_name": video_name, + "video_path": dst_video, + } + with open(os.path.join(temp_dir, "frame_meta.json"), "w") as f: + json.dump(frame_data, f) + + process_and_save_rgb(dst_video, temp_dir, fps) + return SessionState(temp_dir=temp_dir, video_name=video_name, video_path=dst_video, fps=fps) + + + + +def gpu_run_tracker( + temp_dir: str, video_name: str, grid_size: int, vo_points: int, fps: int, mode: str +) -> List[str]: + import torchvision.transforms as T + + out_dir = os.path.join(temp_dir, "results") + os.makedirs(out_dir, exist_ok=True) + base_tracker_model = _get_spatracker_model(mode) + tracker_model_arg, tracker_viser_arg = get_tracker_predictor( + out_dir, vo_points=vo_points, tracker_model=base_tracker_model.cuda() + ) + + video_path = os.path.join(temp_dir, f"{video_name}.mp4") + mask_path = os.path.join(temp_dir, f"{video_name}.png") + video_tensor = process_tensor(video_path, fps) + + with torch.no_grad(): + with torch.cuda.amp.autocast(dtype=torch.bfloat16): + predictions = _get_vggt4track_model()(video_tensor.cuda() / 255) + extrinsic, intrinsic = predictions["poses_pred"], predictions["intrs"] + depth_map, depth_conf = predictions["points_map"][..., 2], predictions["unc_metric"] + + depth_tensor = depth_map.squeeze().cpu().numpy() + extrs = extrinsic.squeeze().cpu().numpy() + intrs = intrinsic.squeeze().cpu().numpy() + video_tensor = video_tensor.squeeze() + unc_metric = depth_conf.squeeze().cpu().numpy() > 0.5 + + if os.path.exists(mask_path): + mask = cv2.imread(mask_path) + mask = cv2.resize(mask, (video_tensor.shape[3], video_tensor.shape[2])) + mask = mask.sum(axis=-1) > 0 + else: + mask = np.ones_like(video_tensor[0, 0].cpu().numpy()) > 0 + grid_size = 10 + + frame_H, frame_W = video_tensor.shape[2:] + grid_pts = get_points_on_a_grid(grid_size, (frame_H, frame_W), device="cuda") + if os.path.exists(mask_path): + grid_pts_int = grid_pts[0].long() + mask_values = mask[ + grid_pts_int.cpu()[..., 1], grid_pts_int.cpu()[..., 0] + ] + grid_pts = grid_pts[:, mask_values] + + query_xyt = torch.cat( + [torch.zeros_like(grid_pts[:, :, :1]), grid_pts], dim=2 + )[0].cpu().numpy() + + with torch.amp.autocast(device_type="cuda", dtype=torch.bfloat16): + ( + c2w_traj, + intrs, + point_map, + conf_depth, + track3d_pred, + track2d_pred, + vis_pred, + conf_pred, + video, + ) = tracker_model_arg.forward( + video_tensor, + depth=depth_tensor, + intrs=intrs, + extrs=extrs, + queries=query_xyt, + fps=1, + full_point=False, + iters_track=4, + query_no_BA=True, + fixed_cam=False, + stage=1, + unc_metric=unc_metric, + support_frame=len(video_tensor) - 1, + replace_ratio=0.2, + ) + + + data_npz = { + "coords": ( + torch.einsum("tij,tnj->tni", c2w_traj[:, :3, :3].cpu(), track3d_pred[:, :, :3].cpu()) + + c2w_traj[:, :3, 3][:, None, :].cpu() + ).numpy(), + "extrinsics": torch.inverse(c2w_traj).cpu().numpy(), + "intrinsics": intrs.cpu().numpy(), + "depths": point_map[:, 2, ...].cpu().numpy(), + "video": video.cpu().numpy() / 255, + "visibs": vis_pred.cpu().numpy(), + "confs": conf_pred.cpu().numpy(), + "confs_depth": conf_depth.cpu().numpy(), + } + + result_dir = os.path.join(temp_dir, "results") + os.makedirs(result_dir, exist_ok=True) + np.savez(os.path.join(result_dir, "result.npz"), **data_npz) + + depth_dir = os.path.join(temp_dir, "depth") + os.makedirs(depth_dir, exist_ok=True) + depth_paths = [] + for idx in range(data_npz["depths"].shape[0]): + depth_img = data_npz["depths"][idx] + depth_uint16 = (depth_img * 1000).astype(np.uint16) + depth_path = os.path.join(depth_dir, f"{idx:06d}.png") + cv2.imwrite(depth_path, depth_uint16) + depth_paths.append(depth_path) + + intrinsic_file_path = os.path.join(temp_dir, "intrinsics.json") + intrinsics_dict = { + str(frame_id): data_npz["intrinsics"][frame_id].tolist() + for frame_id in range(len(data_npz["intrinsics"])) + } + with open(intrinsic_file_path, "w", encoding="utf-8") as f: + json.dump(intrinsics_dict, f, indent=2) + return depth_paths + + +def gpu_run_tracker_da3_init( + temp_dir: str, + video_name: str, + grid_size: int, + vo_points: int, + fps: int, + mode: str, + model_path: str, + process_res: int, + use_ray_pose: bool, + debug_depth: bool = False, + single_frame: bool = False, + export_raw_cloud: bool = False, +) -> List[str]: + """Use DA3 outputs as initial depth/intr/extr, then run SpaTracker tracker forward for refinement.""" + import torchvision.transforms as T + + out_dir = os.path.join(temp_dir, "results") + os.makedirs(out_dir, exist_ok=True) + base_tracker_model = _get_spatracker_model(mode) + tracker_model_arg, tracker_viser_arg = get_tracker_predictor( + out_dir, vo_points=vo_points, tracker_model=base_tracker_model.cuda() + ) + + video_path = os.path.join(temp_dir, f"{video_name}.mp4") + mask_path = os.path.join(temp_dir, f"{video_name}.png") + video_tensor = process_tensor(video_path, fps) + video_tensor = video_tensor.squeeze() + if single_frame: + video_tensor = video_tensor[:1] + T_len, _, H_v, W_v = video_tensor.shape + + rgb0_path = os.path.join(temp_dir, "rgb", "000000.jpg") + if not os.path.exists(rgb0_path): + raise FileNotFoundError(f"缺少首帧 RGB:{rgb0_path}") + model = _get_da3_model(model_path) + prediction = model.inference( + image=[rgb0_path], + process_res=process_res, + use_ray_pose=use_ray_pose, + export_dir=None, + align_to_input_ext_scale=True, + export_format="mini_npz", + ) + depth0 = prediction.depth[0] + Hd, Wd = depth0.shape + + if prediction.extrinsics is not None: + ext0 = np.asarray(prediction.extrinsics[0], dtype=np.float32) + if ext0.shape == (3, 4): + ext0 = np.vstack([ext0, np.array([[0, 0, 0, 1]], dtype=np.float32)]) + elif ext0.shape != (4, 4): + ext0 = np.eye(4, dtype=np.float32) + else: + ext0 = np.eye(4, dtype=np.float32) + + if prediction.intrinsics is not None: + intr0 = np.asarray(prediction.intrinsics[0], dtype=np.float32) + else: + fx = fy = max(Wd, Hd) + cx, cy = Wd / 2.0, Hd / 2.0 + intr0 = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]], dtype=np.float32) + + depth_resized = cv2.resize(depth0, (W_v, H_v), interpolation=cv2.INTER_LINEAR) + scale_x = W_v / Wd + scale_y = H_v / Hd + intr_resized = intr0.copy() + intr_resized[0, 0] *= scale_x + intr_resized[1, 1] *= scale_y + intr_resized[0, 2] *= scale_x + intr_resized[1, 2] *= scale_y + + depth_tensor = np.repeat(depth_resized[None, ...], T_len, axis=0) + intrs = np.repeat(intr_resized[None, ...], T_len, axis=0) + extrs = np.repeat(ext0[None, ...], T_len, axis=0) + unc_metric = np.ones_like(depth_tensor, dtype=bool) + + if debug_depth: + dbg_dir = os.path.join(temp_dir, "debug_da3") + os.makedirs(dbg_dir, exist_ok=True) + with open(os.path.join(dbg_dir, "da3_init_stats.txt"), "w", encoding="utf-8") as f: + def _stats(arr): + return np.min(arr), np.median(arr), np.max(arr) + f.write( + f"DA3 depth (orig HxW={Hd}x{Wd}) min/med/max: " + f"{_stats(depth0)}\n" + f"DA3 depth resized ({H_v}x{W_v}) min/med/max: " + f"{_stats(depth_resized)}\n" + ) + + if os.path.exists(mask_path): + mask = cv2.imread(mask_path) + mask = cv2.resize(mask, (W_v, H_v)) + mask = mask.sum(axis=-1) > 0 + else: + mask = np.ones((H_v, W_v), dtype=bool) + grid_size = 10 + + frame_H, frame_W = H_v, W_v + grid_pts = get_points_on_a_grid(grid_size, (frame_H, frame_W), device="cuda") + if os.path.exists(mask_path): + grid_pts_int = grid_pts[0].long() + mask_values = mask[ + grid_pts_int.cpu()[..., 1], grid_pts_int.cpu()[..., 0] + ] + grid_pts = grid_pts[:, mask_values] + + query_xyt = torch.cat( + [torch.zeros_like(grid_pts[:, :, :1]), grid_pts], dim=2 + )[0].cpu().numpy() + + with torch.amp.autocast(device_type="cuda", dtype=torch.bfloat16): + ( + c2w_traj, + intrs_out, + point_map, + conf_depth, + track3d_pred, + track2d_pred, + vis_pred, + conf_pred, + video_out, + ) = tracker_model_arg.forward( + video_tensor, + depth=depth_tensor, + intrs=intrs, + extrs=extrs, + queries=query_xyt, + fps=1, + full_point=False, + iters_track=4, + query_no_BA=True, + fixed_cam=False, + stage=1, + unc_metric=unc_metric, + support_frame=len(video_tensor) - 1, + replace_ratio=0.2, + ) + + + if debug_depth: + dbg_dir = os.path.join(temp_dir, "debug_da3") + os.makedirs(dbg_dir, exist_ok=True) + def _stats_t(tensor): + arr = tensor.cpu().numpy() + return arr.min(), np.median(arr), arr.max() + with open(os.path.join(dbg_dir, "tracker_depth_stats.txt"), "w", encoding="utf-8") as f: + f.write( + f"Tracker depth min/med/max: {_stats_t(point_map[:,2,...])}\n" + f"Tracker intrinsics shape: {intrs_out.shape}\n" + ) + + data_npz = { + "coords": ( + torch.einsum("tij,tnj->tni", c2w_traj[:, :3, :3].cpu(), track3d_pred[:, :, :3].cpu()) + + c2w_traj[:, :3, 3][:, None, :].cpu() + ).numpy(), + "extrinsics": torch.inverse(c2w_traj).cpu().numpy(), + "intrinsics": intrs_out.cpu().numpy(), + "depths": point_map[:, 2, ...].cpu().numpy(), + "video": video_out.cpu().numpy() / 255, + "visibs": vis_pred.cpu().numpy(), + "confs": conf_pred.cpu().numpy(), + "confs_depth": conf_depth.cpu().numpy(), + } + + result_dir = os.path.join(temp_dir, "results") + os.makedirs(result_dir, exist_ok=True) + np.savez(os.path.join(result_dir, "result.npz"), **data_npz) + + depth_dir = os.path.join(temp_dir, "depth") + os.makedirs(depth_dir, exist_ok=True) + depth_paths = [] + for idx in range(data_npz["depths"].shape[0]): + depth_img = data_npz["depths"][idx] + depth_uint16 = (depth_img * 1000).astype(np.uint16) + depth_path = os.path.join(depth_dir, f"{idx:06d}.png") + cv2.imwrite(depth_path, depth_uint16) + depth_paths.append(depth_path) + + intrinsic_file_path = os.path.join(temp_dir, "intrinsics.json") + intrinsics_dict = { + str(frame_id): data_npz["intrinsics"][frame_id].tolist() + for frame_id in range(len(data_npz["intrinsics"])) + } + with open(intrinsic_file_path, "w", encoding="utf-8") as f: + json.dump(intrinsics_dict, f, indent=2) + return depth_paths + + +def convert_depth_images_to_video(file_paths: List[str], output_video_path: str, fps: int = 30): + if not file_paths: + raise ValueError("没有深度图可以合成视频") + frame = cv2.imread(file_paths[0], cv2.IMREAD_UNCHANGED) + h, w = frame.shape + fourcc = cv2.VideoWriter_fourcc(*"mp4v") + out = cv2.VideoWriter(output_video_path, fourcc, fps, (w, h), isColor=False) + for path in file_paths: + frame = cv2.imread(path, cv2.IMREAD_UNCHANGED) + out.write(frame) + out.release() + + +def _resolve_ffmpeg_bin() -> Optional[str]: + ffmpeg_bin = shutil.which("ffmpeg") + if ffmpeg_bin: + return ffmpeg_bin + try: + import imageio_ffmpeg # type: ignore + except Exception: + return None + try: + return imageio_ffmpeg.get_ffmpeg_exe() + except Exception: + return None + + +def convert_video_to_mp4(input_path: str, output_path: str): + ffmpeg_bin = _resolve_ffmpeg_bin() + if ffmpeg_bin is None: + raise FileNotFoundError( + "ffmpeg not found in PATH and imageio-ffmpeg is unavailable; install ffmpeg or imageio-ffmpeg." + ) + command = [ + ffmpeg_bin, + "-i", + input_path, + "-c:v", + "libx264", + "-preset", + "fast", + "-crf", + "23", + "-c:a", + "aac", + "-b:a", + "128k", + "-movflags", + "+faststart", + "-y", + output_path, + ] + subprocess.run(command, check=True) + + +def _get_preview_settings() -> Tuple[bool, int, int, int]: + """Preview rendering knobs (legacy/Hi3DGen).""" + skip = os.environ.get("OPG_SKIP_PREVIEW", "").strip().lower() in {"1", "true", "yes"} + res = int(os.environ.get("OPG_PREVIEW_RES", "512")) + frames = int(os.environ.get("OPG_PREVIEW_FRAMES", "60")) + ssaa = int(os.environ.get("OPG_PREVIEW_SSAA", "1")) + return skip, res, frames, ssaa + + +_da3_model = None + + +def _get_da3_model(model_path: str): + """Lazy-load DepthAnything3 model to CUDA, using HF mirror env already set.""" + global _da3_model + if _da3_model is None: + try: + from depth_anything_3.api import DepthAnything3 + except ImportError as exc: # noqa: BLE001 + raise ImportError( + "depth-anything-3 未安装,请先在当前环境安装 DA3。" + ) from exc + print(f"🚀 Loading DA3 model: {model_path}") + _da3_model = DepthAnything3.from_pretrained(model_path).to("cuda") + return _da3_model + + +def _write_depth_and_intrinsics( + temp_dir: str, + depths: np.ndarray, + intrs: np.ndarray, + extrs: np.ndarray, + rgb_paths: List[str], + raw_cloud_tag: Optional[str] = None, +) -> List[str]: + """Write depth pngs, intrinsics.json, result.npz to temp_dir.""" + depth_dir = os.path.join(temp_dir, "depth") + os.makedirs(depth_dir, exist_ok=True) + depth_paths: List[str] = [] + for idx in range(depths.shape[0]): + depth_img = depths[idx] + depth_uint16 = (depth_img * 1000).astype(np.uint16) + depth_path = os.path.join(depth_dir, f"{idx:06d}.png") + cv2.imwrite(depth_path, depth_uint16) + depth_paths.append(depth_path) + + intrinsic_file_path = os.path.join(temp_dir, "intrinsics.json") + intrinsics_dict = {str(i): intrs[i].tolist() for i in range(len(intrs))} + with open(intrinsic_file_path, "w", encoding="utf-8") as f: + json.dump(intrinsics_dict, f, indent=2) + + video_list = [] + for idx, rgb_path in enumerate(rgb_paths): + rgb = cv2.imread(rgb_path) + if rgb is None: + continue + rgb = cv2.cvtColor(rgb, cv2.COLOR_BGR2RGB) + if (rgb.shape[0], rgb.shape[1]) != depths.shape[1:]: + rgb = cv2.resize(rgb, (depths.shape[2], depths.shape[1]), interpolation=cv2.INTER_LINEAR) + video_list.append(rgb.transpose(2, 0, 1) / 255.0) + if not video_list: + video = np.zeros((depths.shape[0], 3, depths.shape[1], depths.shape[2]), dtype=np.float32) + else: + while len(video_list) < depths.shape[0]: + video_list.append(video_list[-1]) + video = np.stack(video_list[: depths.shape[0]], axis=0).astype(np.float32) + + result_dir = os.path.join(temp_dir, "results") + os.makedirs(result_dir, exist_ok=True) + np.savez( + os.path.join(result_dir, "result.npz"), + coords=np.zeros_like(depths)[..., None].repeat(3, axis=-1), + extrinsics=extrs, + intrinsics=intrs, + depths=depths, + video=video, + visibs=np.zeros((depths.shape[0], 1)), + confs=np.zeros((depths.shape[0], 1)), + confs_depth=np.zeros_like(depths), + ) + + if raw_cloud_tag is not None: + try: + depth = depths[0] + intr = intrs[0] + extr = extrs[0] + H, W = depth.shape + ys, xs = np.meshgrid(np.arange(H), np.arange(W), indexing="ij") + z = depth.astype(np.float32) + valid = z > 1e-6 + xs = xs[valid].astype(np.float32) + ys = ys[valid].astype(np.float32) + z = z[valid] + fx, fy = intr[0, 0], intr[1, 1] + cx, cy = intr[0, 2], intr[1, 2] + x_cam = (xs - cx) / fx * z + y_cam = (ys - cy) / fy * z + pts_cam = np.stack([x_cam, y_cam, z, np.ones_like(z)], axis=1) + pts_world = pts_cam @ np.linalg.inv(extr).T + pts_world = pts_world[:, :3] + rgb = None + if rgb_paths: + img = cv2.imread(str(rgb_paths[0])) + if img is not None: + img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) + rgb = img.reshape(-1, 3)[np.flatnonzero(valid)] + cloud = trimesh.points.PointCloud(pts_world, colors=rgb) + out_path = os.path.join(temp_dir, f"raw_scene_cloud_{raw_cloud_tag}.ply") + cloud.export(out_path) + print(f"📁 原始场景点云导出: {out_path}") + except Exception as exc: # noqa: BLE001 + print(f"⚠️ 原始点云导出失败:{exc}") + return depth_paths + + +def _estimate_depth_with_da3( + state: SessionState, + model_path: str, + process_res: int, + use_ray_pose: bool, + export_raw_cloud: bool = False, +) -> List[str]: + """Run DA3 on the first RGB frame, replicate to all frames, and return depth paths.""" + rgb_dir = os.path.join(state.temp_dir, "rgb") + rgb_paths = sorted(glob.glob(os.path.join(rgb_dir, "*.jpg"))) + if not rgb_paths: + raise FileNotFoundError(f"未找到 RGB 帧: {rgb_dir}") + + first_rgb = rgb_paths[0] + + model = _get_da3_model(model_path) + + prediction = model.inference( + image=[first_rgb], + process_res=process_res, + use_ray_pose=use_ray_pose, + export_dir=None, + align_to_input_ext_scale=True, + export_format="mini_npz", + ) + + depth0 = prediction.depth[0] + H, W = depth0.shape + + if prediction.extrinsics is not None: + ext0 = np.asarray(prediction.extrinsics[0], dtype=np.float32) + if ext0.shape == (3, 4): + ext0 = np.vstack([ext0, np.array([[0, 0, 0, 1]], dtype=np.float32)]) + elif ext0.shape != (4, 4): + ext0 = np.eye(4, dtype=np.float32) + else: + ext0 = np.eye(4, dtype=np.float32) + + if prediction.intrinsics is not None: + intr0 = prediction.intrinsics[0] + else: + fx = fy = max(H, W) + cx = W / 2.0 + cy = H / 2.0 + intr0 = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]], dtype=np.float32) + + frame_count = len(rgb_paths) + depths = np.repeat(depth0[None, ...], frame_count, axis=0).astype(np.float32) + intrs = np.repeat(intr0[None, ...], frame_count, axis=0).astype(np.float32) + extrs = np.repeat(ext0[None, ...], frame_count, axis=0).astype(np.float32) + + depth_paths = _write_depth_and_intrinsics( + state.temp_dir, + depths, + intrs, + extrs, + rgb_paths, + raw_cloud_tag="da3_init_raw" if export_raw_cloud else None, + ) + return depth_paths + + +def estimate_depth_intrinsic( + state: SessionState, + grid_size: int, + vo_points: int, + fps: int, + processing_mode: str, + tracker_cfg: Optional[Dict] = None, +) -> Optional[str]: + if processing_mode == "da3": + tracker_cfg = tracker_cfg or {} + model_path = tracker_cfg.get("da3_model_path", "depth-anything/DA3NESTED-GIANT-LARGE") + process_res = int(tracker_cfg.get("da3_process_res", 518)) + use_ray_pose = bool(tracker_cfg.get("da3_use_ray_pose", False)) + depth_names = _estimate_depth_with_da3(state, model_path, process_res, use_ray_pose) + elif processing_mode == "da3_direct": + tracker_cfg = tracker_cfg or {} + model_path = tracker_cfg.get("da3_model_path", "depth-anything/DA3NESTED-GIANT-LARGE") + process_res = int(tracker_cfg.get("da3_process_res", 518)) + use_ray_pose = bool(tracker_cfg.get("da3_use_ray_pose", False)) + depth_names = _estimate_depth_with_da3(state, model_path, process_res, use_ray_pose) + elif processing_mode == "da3_init": + tracker_cfg = tracker_cfg or {} + model_path = tracker_cfg.get("da3_model_path", "depth-anything/DA3NESTED-GIANT-LARGE") + process_res = int(tracker_cfg.get("da3_process_res", 518)) + use_ray_pose = bool(tracker_cfg.get("da3_use_ray_pose", False)) + debug_depth = bool(tracker_cfg.get("da3_debug_depth", False)) + single_frame = bool(tracker_cfg.get("single_frame_mode", False)) + depth_names = gpu_run_tracker_da3_init( + state.temp_dir, + state.video_name, + grid_size, + vo_points, + fps, + "offline", + model_path, + process_res, + use_ray_pose, + debug_depth, + single_frame, + ) + else: + depth_names = gpu_run_tracker( + state.temp_dir, state.video_name, grid_size, vo_points, fps, processing_mode + ) + depth_dir = os.path.join(state.temp_dir, "depth") + depth_video_path = os.path.join(depth_dir, "depth.mp4") + depth_video_converted = os.path.join(depth_dir, "depth_new.mp4") + convert_depth_images_to_video(depth_names, depth_video_path, fps=VIDEO_FPS) + convert_video_to_mp4(depth_video_path, depth_video_converted) + os.remove(depth_video_path) + return depth_video_converted + + + + +def get_seed(randomize_seed: bool, seed: int) -> int: + return np.random.randint(0, MAX_SEED) if randomize_seed else seed + + +def generate_final_mask(seg_path, depth_path, out_path, area_threshold=100, max_iter=50): + seg = cv2.imread(seg_path, cv2.IMREAD_GRAYSCALE) + depth = cv2.imread(depth_path, cv2.IMREAD_UNCHANGED) + object_mask = seg > 128 + object_depths = depth[object_mask] + min_depth = np.percentile(object_depths, 90) + occluder_mask = (depth < min_depth) & (~object_mask) + kernel = np.ones((3, 3), np.uint8) + occluder_mask = cv2.erode(occluder_mask.astype(np.uint8), kernel, iterations=1) + x, y, w, h = cv2.boundingRect(object_mask.astype(np.uint8)) + occluder_mask_bbox = np.zeros_like(occluder_mask) + occluder_mask_bbox[y : y + h, x : x + w] = occluder_mask[y : y + h, x : x + w] + num_labels, labels, stats, _ = cv2.connectedComponentsWithStats( + occluder_mask_bbox, connectivity=8 + ) + filtered_mask = np.zeros_like(occluder_mask_bbox) + for i in range(1, num_labels): + if stats[i, cv2.CC_STAT_AREA] >= area_threshold: + filtered_mask[labels == i] = 1 + dilated_occluder = filtered_mask.copy() + for _ in range(max_iter): + overlap = (dilated_occluder > 0) & (object_mask > 0) + if np.any(overlap): + break + dilated_occluder = cv2.dilate(dilated_occluder, kernel, iterations=1) + gap_mask = (dilated_occluder > 0) & (~filtered_mask.astype(bool)) & (~object_mask) + filtered_mask[gap_mask] = 1 + final_mask = np.ones_like(seg, dtype=np.uint8) * 255 + final_mask[object_mask] = 188 + final_mask[filtered_mask > 0] = 0 + return Image.fromarray(final_mask) + + +def mask_image(rgb_path, mask_path) -> Image.Image: + input_img = Image.open(rgb_path) + input_np = np.array(input_img) + has_alpha = input_img.mode == "RGBA" and not np.all(input_np[:, :, 3] == 255) + if has_alpha: + output = input_img + mask_binary = input_np[:, :, 3] + else: + mask_img = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE) + _, mask_binary = cv2.threshold(mask_img, 1, 255, cv2.THRESH_BINARY) + rgb_img = cv2.cvtColor(np.array(input_img.convert("RGB")), cv2.COLOR_RGB2BGR) + result_img = cv2.bitwise_and(rgb_img, rgb_img, mask=mask_binary) + output = Image.fromarray(cv2.cvtColor(result_img, cv2.COLOR_BGR2RGB)) + output_np = np.array(output) + if output.mode == "RGBA": + alpha = output_np[:, :, 3] + else: + alpha = mask_binary + bbox = np.argwhere(alpha > 0.8 * 255) + if len(bbox) == 0: + return output + y0, x0 = bbox.min(axis=0) + y1, x1 = bbox.max(axis=0) + center = ((x0 + x1) / 2, (y0 + y1) / 2) + size = int(max(x1 - x0, y1 - y0) * 1.2) + bbox = ( + int(center[0] - size // 2), + int(center[1] - size // 2), + int(center[0] + size // 2), + int(center[1] + size // 2), + ) + output = output.crop(bbox) + target_size = _get_env_target_size(518) + output = output.resize((target_size, target_size), Image.LANCZOS) + output_np = np.array(output).astype(np.float32) / 255 + if output_np.shape[2] == 4: + output_np = output_np[:, :, :3] * output_np[:, :, 3:4] + return Image.fromarray((output_np * 255).astype(np.uint8)) + + + + + +def _prepare_trellis2_masked_image(image: Image.Image, mask: Optional[Image.Image]) -> Image.Image: + """将 final_mask 转成 RGBA,避免 TRELLIS.2 依赖 rembg。""" + image = image.convert("RGB") + if mask is None: + return image + mask = mask.convert("L") + if mask.size != image.size: + mask = mask.resize(image.size, Image.NEAREST) + mask_np = np.array(mask) + object_mask = mask_np == 188 + if not np.any(object_mask): + object_mask = mask_np < 255 + alpha = (object_mask.astype(np.uint8)) * 255 + rgb_np = np.array(image) + rgba = np.dstack([rgb_np, alpha]) + return Image.fromarray(rgba) + + + + + + + +def generate_3d_viaT2( + image: Image.Image, + mask: Optional[Image.Image], + temp_dir: str, + export_format: str, + seed: int = -1, + *, + checkpoint_path: str = "checkpoints/OnePoseViaGen/TRELLIS.2-4B", + pipeline_type: str = "1024", + preview_resolution: int = 1024, + preview_frames: int = 120, + preview_mode: str = "shaded", + envmap_path: str = "", + simplify_target: int = 1000000, + preprocess_image: bool = True, + max_num_tokens: int = 49152, +): + """TRELLIS.2 image-to-3D (统一路径,不区分 occlusion).""" + if seed == -1: + seed = np.random.randint(0, MAX_SEED) + + pipeline = get_trellis2_pipeline(checkpoint_path) + masked_input = _prepare_trellis2_masked_image(image, mask) + masked_input.save(os.path.join(temp_dir, "masked_input.png")) + outputs = pipeline.run( + masked_input, + num_samples=1, + seed=int(seed), + preprocess_image=bool(preprocess_image), + pipeline_type=str(pipeline_type), + max_num_tokens=int(max_num_tokens), + ) + raw_mesh = outputs[0] + raw_mesh.simplify(1000000) + + model_dir = os.path.join(temp_dir, "model") + model_middle_dir = os.path.join(model_dir, "middle_file") + + os.makedirs(model_middle_dir, exist_ok=True) + output_id = str(uuid.uuid4()) + video_path = f"{model_middle_dir}/{output_id}_preview.mp4" + mesh_path = f"{model_dir}/model.{export_format}" + high_mesh_path = f"{model_middle_dir}/{output_id}_high_mesh.obj" + + + if preview_mode.lower() != "off": + from trellis2.utils import render_utils as render_utils_t2 + envmap = get_trellis2_envmap(envmap_path) + + render_out = render_utils_t2.render_video( + raw_mesh, + envmap=envmap, + resolution=int(preview_resolution), + num_frames=int(preview_frames), + ) + if preview_mode.lower() == "pbr_grid": + frames = render_utils_t2.make_pbr_vis_frames( + render_out, resolution=int(preview_resolution) + ) + else: + frames = render_out.get("shaded", next(iter(render_out.values()))) + imageio.mimsave(video_path, frames, fps=15) + else: + video_path = "" + + + glb_obj = o_voxel.postprocess.to_glb( + vertices = raw_mesh.vertices, + faces = raw_mesh.faces, + attr_volume = raw_mesh.attrs, + coords = raw_mesh.coords, + attr_layout = raw_mesh.layout, + voxel_size = raw_mesh.voxel_size, + aabb = [[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]], + decimation_target = simplify_target, + texture_size = 1024, + remesh = True, + remesh_band = 1, + remesh_project = 0, + verbose = False + ) + + + + temp_glb_path = f"{model_middle_dir}/sample.glb" + glb_obj.export(temp_glb_path, extension_webp=True) + + + mesh= trimesh.load(glb_obj) + + + + + + if str(export_format).lower() == "obj": + _export_obj_local_assets(mesh, mesh_path) + else: + mesh.export(mesh_path, file_type=export_format) + _export_obj_local_assets(mesh, high_mesh_path) + + return video_path, mesh_path, high_mesh_path + + +def _load_trimesh_from_asset(path: str) -> trimesh.Trimesh: + loaded = trimesh.load(path, process=False) + if isinstance(loaded, trimesh.Scene): + meshes = [g for g in loaded.geometry.values() if isinstance(g, trimesh.Trimesh)] + if not meshes: + raise RuntimeError(f"No mesh geometry found in {path}") + mesh = trimesh.util.concatenate(meshes) + elif isinstance(loaded, trimesh.Trimesh): + mesh = loaded + else: + raise RuntimeError(f"Unsupported mesh asset type from {path}: {type(loaded)!r}") + if mesh.is_empty: + raise RuntimeError(f"Empty mesh from {path}") + return mesh + + + + + + +def generate_3d( + image: Image.Image, + mask, + temp_dir: str, + export_format: str, + seed: int = -1, + ss_guidance_strength: float = 7.5, + ss_sampling_steps: int = 12, + slat_guidance_strength: float = 15, + slat_sampling_steps: int = 25, + is_occluded: bool = False, +): + if seed == -1: + seed = np.random.randint(0, MAX_SEED) + if is_occluded: + pipeline = get_amodal3r_pipeline() + outputs = pipeline.run_multi_image( + [image], + [mask], + seed=seed, + formats=["mesh", "gaussian"], + sparse_structure_sampler_params={ + "steps": ss_sampling_steps, + "cfg_strength": ss_guidance_strength, + }, + slat_sampler_params={ + "steps": slat_sampling_steps, + "cfg_strength": slat_guidance_strength, + }, + ) + generated_mesh = outputs["mesh"][0] + generated_gs = outputs["gaussian"][0] + model_dir = os.path.join(temp_dir, "model") + model_middle_dir = os.path.join(model_dir, "middle_file") + os.makedirs(model_middle_dir, exist_ok=True) + output_id = str(uuid.uuid4()) + video_path = f"{model_middle_dir}/{output_id}_preview.mp4" + mesh_path = f"{model_dir}/model.{export_format}" + skip_preview, preview_res, preview_frames, preview_ssaa = _get_preview_settings() + if not skip_preview: + try: + video_geo = render_utils.render_video( + generated_gs, + resolution=preview_res, + num_frames=preview_frames, + ssaa=preview_ssaa, + )["color"] + imageio.mimsave(video_path, video_geo, fps=15) + except RuntimeError as exc: + if "out of memory" in str(exc).lower(): + print("⚠️ 预览渲染 OOM,跳过 preview video。") + video_path = "" + torch.cuda.empty_cache() + else: + raise + trimesh_mesh = postprocessing_utils.to_glb( + generated_gs, generated_mesh, verbose=False + ) + else: + pipeline = get_hi3dgen_pipeline() + outputs = pipeline.run( + image, + seed=seed, + formats=["mesh", "gaussian"], + preprocess_image=False, + sparse_structure_sampler_params={ + "steps": ss_sampling_steps, + "cfg_strength": ss_guidance_strength, + }, + slat_sampler_params={ + "steps": slat_sampling_steps, + "cfg_strength": slat_guidance_strength, + }, + ) + generated_mesh = outputs["mesh"][0] + generated_gs = outputs["gaussian"][0] + model_dir = os.path.join(temp_dir, "model") + model_middle_dir = os.path.join(model_dir, "middle_file") + os.makedirs(model_middle_dir, exist_ok=True) + output_id = str(uuid.uuid4()) + video_path = f"{model_middle_dir}/{output_id}_preview.mp4" + mesh_path = f"{model_dir}/model.{export_format}" + skip_preview, preview_res, preview_frames, preview_ssaa = _get_preview_settings() + if not skip_preview: + try: + video_geo = render_utils_hi3dgen.render_video( + generated_mesh, + resolution=preview_res, + num_frames=preview_frames, + ssaa=preview_ssaa, + )["color"] + imageio.mimsave(video_path, video_geo, fps=15) + except RuntimeError as exc: + if "out of memory" in str(exc).lower(): + print("⚠️ 预览渲染 OOM,跳过 preview video。") + video_path = "" + torch.cuda.empty_cache() + else: + raise + trimesh_mesh = postprocessing_utils_hi3dgen.to_trimesh( + generated_gs, generated_mesh, verbose=False + ) + R = trimesh.transformations.rotation_matrix(np.pi / 2, [1, 0, 0]) + trimesh_mesh.apply_transform(R) + _export_obj_local_assets(trimesh_mesh, mesh_path) + high_mesh_path = f"{model_middle_dir}/{output_id}_high_mesh.obj" + save_mesh(generated_mesh, high_mesh_path) + return video_path, mesh_path, high_mesh_path + + + + +def _export_obj_local_assets(mesh: trimesh.Trimesh, filename: str) -> None: + filename = Path(filename) + filename.parent.mkdir(parents=True, exist_ok=True) + obj_stem = filename.stem + mtl_name = f"{obj_stem}.mtl" + obj_text, assets = trimesh.exchange.obj.export_obj( + mesh, + include_texture=True, + return_texture=True, + write_texture=False, + mtl_name=mtl_name, + ) + + rewritten_assets = {} + for asset_name, asset_data in assets.items(): + safe_name = Path(asset_name).name + if safe_name != mtl_name: + safe_name = f"{obj_stem}_{safe_name}" + rewritten_assets[safe_name] = asset_data + if safe_name != Path(asset_name).name: + obj_text = obj_text.replace(Path(asset_name).name, safe_name) + + if mtl_name in rewritten_assets: + mtl_text = rewritten_assets[mtl_name].decode("utf-8") + for asset_name in assets: + source_name = Path(asset_name).name + target_name = f"{obj_stem}_{source_name}" + if source_name != mtl_name and target_name in rewritten_assets: + mtl_text = mtl_text.replace(source_name, target_name) + rewritten_assets[mtl_name] = mtl_text.encode("utf-8") + + filename.write_text(obj_text, encoding="utf-8") + for asset_name, asset_data in rewritten_assets.items(): + asset_path = filename.parent / asset_name + asset_path.write_bytes(asset_data) + + +def save_mesh(mesh_result, filename): + vertices = ( + mesh_result.vertices.cpu().numpy() + if hasattr(mesh_result.vertices, "cpu") + else mesh_result.vertices + ) + faces = ( + mesh_result.faces.cpu().numpy() + if hasattr(mesh_result.faces, "cpu") + else mesh_result.faces + ) + mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False) + if mesh_result.vertex_attrs is not None: + attrs = ( + mesh_result.vertex_attrs.cpu().numpy() + if hasattr(mesh_result.vertex_attrs, "cpu") + else mesh_result.vertex_attrs + ) + mesh.visual.vertex_colors = attrs + if str(filename).lower().endswith(".obj"): + _export_obj_local_assets(mesh, filename) + else: + mesh.export(filename) + + +def recover_true_scale( + normal_model_path: str, + anchor_depth_name: str, + anchor_intrinsic: List[List[float]], + anchor_image_name: str, + anchor_mask_name: str, + output_dir: str, +): + intrinsic_path = os.path.join(output_dir, "anchor_file") + os.makedirs(intrinsic_path, exist_ok=True) + intrinsic_file = os.path.join(intrinsic_path, "intrinsic.txt") + np.savetxt(intrinsic_file, anchor_intrinsic, fmt="%.6f") + mid_dir = os.path.join(output_dir, "mid_files") + os.makedirs(mid_dir, exist_ok=True) + scaled_mesh_path = os.path.join(mid_dir, "scaled_mesh.obj") + scaled_mesh, pose, final_scale = recover_scale( + normal_model_path, + anchor_depth_name, + anchor_image_name, + anchor_mask_name, + intrinsic_file, + "test", + mid_dir, + ) + _export_obj_local_assets(scaled_mesh, scaled_mesh_path) + return scaled_mesh_path, final_scale, pose + + +__all__ = [ + "SessionState", + "VIDEO_FPS", + "MAX_SEED", + "prepare_session_from_video", + "estimate_depth_intrinsic", + "generate_final_mask", + "mask_image", + "generate_3d_viaT2", + "generate_3d", + "recover_true_scale", + "get_seed", + "convert_video_to_mp4", + "get_trellis2_pipeline", +] diff --git a/OVOW/engine/pipeline_core_single_image.py b/OVOW/engine/pipeline_core_single_image.py new file mode 100644 index 0000000000000000000000000000000000000000..67274cd82dea554ee3dc30f42d198f695cc72db9 --- /dev/null +++ b/OVOW/engine/pipeline_core_single_image.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import json +import os +import shutil +from pathlib import Path +from typing import Dict, List, Optional + +import cv2 +import numpy as np +import torch +from PIL import Image +from torchvision.utils import save_image + +from pipeline_core import ( # type: ignore + SessionState, + _estimate_depth_with_da3, + _get_vggt4track_model, + _get_env_target_size, + _write_depth_and_intrinsics, + create_user_temp_dir, + numpy_to_base64, + preprocess_image, +) + + +def _load_image_tensor(image_path: str) -> torch.Tensor: + img = Image.open(image_path) + if img.mode == "RGBA": + bg = Image.new("RGBA", img.size, (255, 255, 255, 255)) + img = Image.alpha_composite(bg, img) + img = img.convert("RGB") + arr = np.array(img, dtype=np.uint8) + tensor = torch.from_numpy(arr).permute(2, 0, 1).float().unsqueeze(0) + + h, w = tensor.shape[2:] + target_size = _get_env_target_size(None) + if target_size: + scale = target_size / float(min(h, w)) + if scale != 1.0: + new_h = max(2, int(h * scale) // 2 * 2) + new_w = max(2, int(w * scale) // 2 * 2) + tensor = torch.nn.functional.interpolate( + tensor, + size=(new_h, new_w), + mode="bilinear", + align_corners=False, + ) + if target_size is None: + target_size = int(tensor.shape[3]) + tensor = preprocess_image(tensor, target_size=target_size, keep_ratio=True) + return tensor.unsqueeze(0) + + +def prepare_session_from_image(image_path: str, scene_name: Optional[str] = None) -> SessionState: + src = Path(image_path).expanduser().resolve() + if not src.is_file(): + raise FileNotFoundError(src) + + temp_dir = Path(create_user_temp_dir()).resolve() + image_name = str(scene_name or src.stem) + input_copy = temp_dir / f"input_image{src.suffix.lower() or '.png'}" + shutil.copy2(src, input_copy) + + video_tensor = _load_image_tensor(str(src)) + rgb_dir = temp_dir / "rgb" + rgb_dir.mkdir(parents=True, exist_ok=True) + rgb_path = rgb_dir / "000000.jpg" + img_tensor = video_tensor[0, 0] + if img_tensor.max() > 1.0: + img_tensor = (img_tensor / 255.0).clamp(0.0, 1.0) + save_image(img_tensor, str(rgb_path)) + + rgb_preview = cv2.imread(str(rgb_path)) + if rgb_preview is None: + raise RuntimeError(f"Failed to read preprocessed image: {rgb_path}") + rgb_preview = cv2.cvtColor(rgb_preview, cv2.COLOR_BGR2RGB) + frame_data = { + "data": numpy_to_base64(rgb_preview), + "shape": list(rgb_preview.shape), + "dtype": str(rgb_preview.dtype), + "temp_dir": str(temp_dir), + "video_name": image_name, + "video_path": str(src), + "image_path": str(src), + "input_image_copy": str(input_copy), + "input_type": "image", + } + with (temp_dir / "frame_meta.json").open("w", encoding="utf-8") as f: + json.dump(frame_data, f, indent=2) + + return SessionState(temp_dir=str(temp_dir), video_name=image_name, video_path=str(src), fps=1) + + +@torch.inference_mode() +def _estimate_depth_with_vggt_single_frame(state: SessionState) -> List[str]: + rgb_dir = Path(state.temp_dir) / "rgb" + rgb_paths = sorted(str(p) for p in rgb_dir.glob("*.jpg")) + if not rgb_paths: + raise FileNotFoundError(f"No RGB frames found under {rgb_dir}") + + video_tensor = _load_image_tensor(rgb_paths[0]).cuda() + with torch.cuda.amp.autocast(dtype=torch.bfloat16): + predictions = _get_vggt4track_model()(video_tensor / 255.0) + + depths = predictions["points_map"][0, ..., 2].detach().float().cpu().numpy() + intrs = predictions["intrs"][0].detach().float().cpu().numpy() + extrs = predictions["poses_pred"][0].detach().float().cpu().numpy() + + if depths.ndim == 2: + depths = depths[None, ...] + if intrs.ndim == 2: + intrs = intrs[None, ...] + if extrs.ndim == 2: + extrs = extrs[None, ...] + + return _write_depth_and_intrinsics( + state.temp_dir, + depths.astype(np.float32), + intrs.astype(np.float32), + extrs.astype(np.float32), + rgb_paths, + raw_cloud_tag="vggt_single_raw", + ) + + +def estimate_depth_intrinsic_from_image( + state: SessionState, + grid_size: int, + vo_points: int, + processing_mode: str, + tracker_cfg: Optional[Dict] = None, +) -> List[str]: + del grid_size, vo_points + tracker_cfg = tracker_cfg or {} + mode = str(processing_mode or "offline").strip().lower() + if mode in {"da3", "da3_direct", "da3_init"}: + model_path = tracker_cfg.get("da3_model_path", "depth-anything/DA3NESTED-GIANT-LARGE") + process_res = int(tracker_cfg.get("da3_process_res", 518)) + use_ray_pose = bool(tracker_cfg.get("da3_use_ray_pose", False)) + export_raw_cloud = bool(tracker_cfg.get("da3_debug_depth", False)) + return _estimate_depth_with_da3( + state, + model_path=model_path, + process_res=process_res, + use_ray_pose=use_ray_pose, + export_raw_cloud=export_raw_cloud, + ) + return _estimate_depth_with_vggt_single_frame(state) diff --git a/OVOW/engine/pipeline_single_image.py b/OVOW/engine/pipeline_single_image.py new file mode 100644 index 0000000000000000000000000000000000000000..f403c63f4292d7e7a1870eac23bcf380c82d5ea5 --- /dev/null +++ b/OVOW/engine/pipeline_single_image.py @@ -0,0 +1,340 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import shutil +import traceback +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from typing import Any, Dict, List, Optional + +import batch_scene_pipeline as bsp +from pipeline import _safe_name, build_object_mask_sequence, maybe_write_tracker_union_mask # type: ignore +from pipeline_core_single_image import estimate_depth_intrinsic_from_image, prepare_session_from_image + + +@dataclass +class PipelineObject: + name: str + masks_dir: Path + category: str = "static" + is_occluded: bool = False + seed: Optional[int] = None + + +@dataclass +class PipelineConfig: + batch_config: Path + image_path: Path + objects: List[PipelineObject] + output_root: Path = Path("temp_local") + run_name: str = "" + mask_glob: str = "frame_*.png" + tracker_mask_mode: str = "static" + + +def _resolve_path(base: Path, value: str) -> Path: + p = Path(value) + return p if p.is_absolute() else (base / p).resolve() + + +def load_pipeline_config(path: Path) -> PipelineConfig: + with path.open("r", encoding="utf-8") as f: + data = json.load(f) + base = path.parent.resolve() + batch_config = _resolve_path(base, data["batch_config"]) + image_raw = data.get("image_path") or data.get("video_path") + if not image_raw: + raise ValueError("Config must include image_path.") + image_path = _resolve_path(base, image_raw) + output_root = _resolve_path(base, data.get("output_root", "temp_local")) + mask_glob = str(data.get("mask_glob", "frame_*.png")) + tracker_mask_mode = str(data.get("tracker_mask_mode", "static")).strip().lower() + run_name = str(data.get("run_name") or data.get("scene_name") or image_path.stem).strip() + + if tracker_mask_mode not in {"none", "static", "all"}: + raise ValueError(f"tracker_mask_mode must be none/static/all, got {tracker_mask_mode}") + + objects: List[PipelineObject] = [] + for entry in data.get("objects", []): + if not isinstance(entry, dict): + continue + name = entry.get("name") or entry.get("id") + masks_dir = entry.get("masks_dir") or entry.get("masks") + if not name or not masks_dir: + raise ValueError("Each object needs name and masks_dir.") + objects.append( + PipelineObject( + name=str(name), + masks_dir=_resolve_path(base, str(masks_dir)), + category=str(entry.get("category", "static")).strip().lower(), + is_occluded=bool(entry.get("is_occluded", False)), + seed=entry.get("seed"), + ) + ) + if not objects: + raise ValueError("Config must include objects.") + + return PipelineConfig( + batch_config=batch_config, + image_path=image_path, + objects=objects, + output_root=output_root, + run_name=run_name, + mask_glob=mask_glob, + tracker_mask_mode=tracker_mask_mode, + ) + + +def run_pipeline( + cfg: PipelineConfig, + *, + run_dir: Optional[Path] = None, + continue_on_object_error: bool = True, + object_error_report: Optional[Path] = None, +) -> Path: + base_cfg = bsp.load_batch_config(cfg.batch_config) + + state = prepare_session_from_image(str(cfg.image_path), scene_name=cfg.run_name or cfg.image_path.stem) + estimate_depth_intrinsic_from_image( + state, + base_cfg.tracker.grid_size, + base_cfg.tracker.vo_points, + base_cfg.tracker.processing_mode, + tracker_cfg=base_cfg.tracker.__dict__, + ) + + source_session_dir = Path(state.temp_dir).resolve() + if run_dir is not None: + final_session_dir = run_dir.expanduser().resolve() + if final_session_dir.exists(): + shutil.rmtree(final_session_dir) + final_session_dir.parent.mkdir(parents=True, exist_ok=True) + else: + run_root = cfg.output_root / f"image_pipeline_{datetime.now().strftime('%Y%m%d_%H%M%S')}" + run_root.mkdir(parents=True, exist_ok=True) + final_session_dir = (run_root / _safe_name(cfg.run_name or cfg.image_path.stem)).resolve() + if final_session_dir.exists(): + shutil.rmtree(final_session_dir) + final_session_dir.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(source_session_dir), str(final_session_dir)) + state.temp_dir = str(final_session_dir) + + rgb_paths = bsp.list_ordered_frames(final_session_dir / "rgb", "jpg") + num_frames = len(rgb_paths) + object_mask_sequences: Dict[str, List[Path]] = {} + failed_objects: List[Dict[str, Any]] = [] + object_status: Dict[str, Dict[str, str]] = {} + + def _archive_failed_object_dir(obj_name: str) -> str: + src = final_session_dir / "objects" / obj_name + if not src.exists(): + return "" + dst_root = final_session_dir / "objects_failed" + dst_root.mkdir(parents=True, exist_ok=True) + dst = dst_root / obj_name + if dst.exists(): + shutil.rmtree(dst) + shutil.move(str(src), str(dst)) + return str(dst.resolve()) + + def _record_object_failure(obj: PipelineObject, stage: str, exc: Exception) -> None: + err_msg = str(exc) + archived_dir = _archive_failed_object_dir(obj.name) + failed_objects.append( + { + "name": obj.name, + "category": obj.category, + "stage": stage, + "error": err_msg, + "traceback": traceback.format_exc(), + "time": datetime.utcnow().isoformat() + "Z", + "archived_dir": archived_dir or None, + } + ) + object_status[obj.name] = { + "name": obj.name, + "category": obj.category, + "status": "failed", + "stage": stage, + "error": err_msg, + } + print(f"[Warn] Skip object {obj.name}: {err_msg}") + + for obj in cfg.objects: + try: + object_mask_sequences[obj.name] = build_object_mask_sequence( + obj.masks_dir, + cfg.mask_glob, + num_frames, + max(1, int(base_cfg.tracker.sample_stride)), + ) + except Exception as exc: # noqa: BLE001 + if not continue_on_object_error: + raise + _record_object_failure(obj, "build_mask_sequence", exc) + + maybe_write_tracker_union_mask( + final_session_dir, + state.video_name, + cfg.objects, + object_mask_sequences, + cfg.tracker_mask_mode, + ) + + rgb_paths, depth_paths, intrinsics = bsp.load_session_sequences(final_session_dir) + static_results: List[bsp.ObjectResult] = [] + succeeded_names: List[str] = [] + + for obj in cfg.objects: + if object_status.get(obj.name, {}).get("status") == "failed": + continue + if obj.category not in {"static", "rigid"}: + object_status[obj.name] = { + "name": obj.name, + "category": obj.category, + "status": "skipped", + "stage": "unsupported_category", + "error": "single-image pipeline only supports static/rigid objects", + } + continue + masks = object_mask_sequences.get(obj.name, []) + if not masks: + if continue_on_object_error: + _record_object_failure(obj, "build_mask_sequence", FileNotFoundError("Mask sequence is empty.")) + continue + raise FileNotFoundError(f"Mask sequence is empty for {obj.name}") + try: + scene_obj = bsp.SceneObject( + name=obj.name, + mask_path=masks[0], + is_occluded=obj.is_occluded, + seed=obj.seed, + ) + result = bsp.process_object( + scene_obj, + masks, + final_session_dir, + final_session_dir, + rgb_paths, + depth_paths, + intrinsics, + base_cfg.generation, + base_cfg.scale, + ) + static_results.append(result) + object_status[obj.name] = { + "name": obj.name, + "category": obj.category, + "status": "succeeded", + "stage": "done", + "error": "", + } + succeeded_names.append(obj.name) + except Exception as exc: # noqa: BLE001 + if not continue_on_object_error: + raise + _record_object_failure(obj, "process_object", exc) + + point_cloud = bsp.export_scene_point_cloud(final_session_dir, base_cfg.generation) + combined_cloud = bsp.export_scene_objects_combined( + final_session_dir, + point_cloud, + static_results, + base_cfg.generation, + ) + + report_path = object_error_report.resolve() if object_error_report is not None else (final_session_dir / "object_errors_step6.json") + report_path.parent.mkdir(parents=True, exist_ok=True) + failed_payload = { + "image": str(cfg.image_path), + "run_dir": str(final_session_dir), + "generated_at": datetime.utcnow().isoformat() + "Z", + "failed_objects": failed_objects, + "failed_names": sorted({item["name"] for item in failed_objects}), + } + report_path.write_text(json.dumps(failed_payload, indent=2), encoding="utf-8") + + status_path = final_session_dir / "object_status_step6.json" + ordered_status: List[Dict[str, str]] = [] + for obj in cfg.objects: + if obj.name not in object_status: + object_status[obj.name] = { + "name": obj.name, + "category": obj.category, + "status": "skipped", + "stage": "unknown", + "error": "", + } + ordered_status.append(object_status[obj.name]) + status_payload = { + "image": str(cfg.image_path), + "run_dir": str(final_session_dir), + "generated_at": datetime.utcnow().isoformat() + "Z", + "objects": ordered_status, + "succeeded_names": sorted(set(succeeded_names)), + "failed_names": sorted({item["name"] for item in failed_objects}), + } + status_path.write_text(json.dumps(status_payload, indent=2), encoding="utf-8") + + summary_path = final_session_dir / "summary.json" + summary_payload = { + "image": str(cfg.image_path), + "run_dir": str(final_session_dir), + "generated_at": datetime.utcnow().isoformat() + "Z", + "scene_point_cloud": str(point_cloud) if point_cloud else None, + "combined_cloud": str(combined_cloud) if combined_cloud else None, + "object_error_report": str(report_path), + "object_status_report": str(status_path), + "failed_objects": failed_objects, + "static_objects": [ + { + "name": obj.name, + "object_dir": str(obj.object_dir), + "scaled_mesh": str(obj.scaled_mesh), + "pose_json": str(obj.pose_json), + "pose_video": str(obj.pose_video), + } + for obj in static_results + ], + } + summary_path.write_text(json.dumps(summary_payload, indent=2), encoding="utf-8") + return final_session_dir + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Single-image pipeline for static + rigid meshes.") + parser.add_argument("--config", type=Path, required=True, help="Pipeline config JSON") + parser.add_argument("--run-dir", type=Path, default=None, help="Optional explicit run dir") + parser.add_argument( + "--continue-on-object-error", + type=int, + choices=[0, 1], + default=1, + help="Continue processing remaining objects when one object fails (default: 1)", + ) + parser.add_argument( + "--object-error-report", + type=Path, + default=None, + help="Optional output path for object-level error report JSON", + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + cfg = load_pipeline_config(args.config) + run_dir = run_pipeline( + cfg, + run_dir=args.run_dir, + continue_on_object_error=bool(args.continue_on_object_error), + object_error_report=args.object_error_report, + ) + print(f"Done. Output: {run_dir}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/requirements.txt b/OVOW/engine/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..5bb47bbbb03b894a6841a5522df5b4b6c75155d8 --- /dev/null +++ b/OVOW/engine/requirements.txt @@ -0,0 +1,60 @@ +#spatial tracker v2 +numpy==1.26.4 +gradio==5.31.0 +pydantic==2.10.6 +opencv-python-headless==4.10.0.84 +einops +einx +plotly +prettytable +decord +easydict +flow_vis +moviepy==1.0.0 +safetensors +scikit-learn +hydra-core +omegaconf +albumentations +matplotlib +mediapy +scikit-image +pycolmap==3.11.1 +git+https://github.com/facebookresearch/segment-anything.git +git+https://github.com/EasternJournalist/utils3d.git#egg=utils3d +huggingface_hub +pyceres +kornia==0.8.1 +xformers==0.0.28 +timm +PyJWT +gdown +rich +decord +ray[default] +jaxtyping +transformers + +#trellis +spaces +trimesh==4.5.3 +pytorch_lightning +open3d +deepspeed +git+https://github.com/NVlabs/nvdiffrast +xatlas +igraph +pyvista +pymeshfix +peft +spconv-cu121==2.3.7 + +#foundationpose +h5py==3.10.0 +transformations==2024.6.1 +ruamel.yaml==0.18.6 +warp-lang==1.0.2 + +#amodal3r +rembg +onnxruntime diff --git a/OVOW/engine/run_all_videos.sh b/OVOW/engine/run_all_videos.sh new file mode 100644 index 0000000000000000000000000000000000000000..3a80a83e52dfdc0bb3e901e9eb0e879bceae713a --- /dev/null +++ b/OVOW/engine/run_all_videos.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +set -uo pipefail + +REPO="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine" +VIDEO_ROOT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/examples/videos" +APIKEY_FILE="" +PIPELINE="$REPO/run_steps_scene_pipeline.sh" + +VIDEOS_ARG="" +GPUS_ARG="" +STEPS="1 2 3 4 5 6 7 8 10 17 18" +RECON_BACKBONE="uplegacy" +DRY_RUN="0" +FREE_MEM_MB="20000" + +usage() { sed -n '2,30p' "$0"; exit 0; } + +while [[ $# -gt 0 ]]; do + case "$1" in + --videos) VIDEOS_ARG="$2"; shift 2 ;; + --gpus) GPUS_ARG="$2"; shift 2 ;; + --steps) STEPS="$2"; shift 2 ;; + --recon-backbone) RECON_BACKBONE="$2"; shift 2 ;; + --dry-run) DRY_RUN="1"; shift ;; + -h|--help) usage ;; + *) echo "未知参数: $1" >&2; exit 1 ;; + esac +done + +declare -a VIDEOS=() +if [[ -n "$VIDEOS_ARG" ]]; then + IFS=',' read -r -a raw <<< "$VIDEOS_ARG" + for v in "${raw[@]}"; do + v="${v##*/}"; v="${v%.mp4}" + VIDEOS+=("$v") + done +else + for f in "$VIDEO_ROOT"/*.mp4; do + [[ -e "$f" ]] || continue + b="${f##*/}"; VIDEOS+=("${b%.mp4}") + done +fi +[[ "${#VIDEOS[@]}" -gt 0 ]] || { echo "ERROR: 没有可跑的视频" >&2; exit 1; } + +declare -a GPUS=() +if [[ -n "$GPUS_ARG" ]]; then + IFS=',' read -r -a GPUS <<< "$GPUS_ARG" +else + while IFS=',' read -r idx used; do + idx="${idx// /}"; used="${used// /}" + if [[ "$used" =~ ^[0-9]+$ ]] && (( used < FREE_MEM_MB )); then + GPUS+=("$idx") + fi + done < <(nvidia-smi --query-gpu=index,memory.used --format=csv,noheader,nounits 2>/dev/null) +fi +[[ "${#GPUS[@]}" -gt 0 ]] || { echo "ERROR: 没有空闲 GPU(可用 --gpus 强制指定)" >&2; exit 1; } + +KEY="" +[[ -f "$APIKEY_FILE" ]] && KEY="$(grep -oE 'sk-[A-Za-z0-9]+' "$APIKEY_FILE" | head -1)" + +TS="$(date +%Y%m%d_%H%M%S)" +BATCH_LOG_DIR="$VIDEO_ROOT/_batch_logs/$TS" +mkdir -p "$BATCH_LOG_DIR" +SUMMARY="$BATCH_LOG_DIR/summary.tsv" +: > "$SUMMARY" + +echo "==================================================================" +echo "批量视频调度 ($TS)" +echo " 视频 (${#VIDEOS[@]}): ${VIDEOS[*]}" +echo " GPU (${#GPUS[@]}): ${GPUS[*]}" +echo " 步骤: $STEPS backbone: $RECON_BACKBONE" +echo " env : OPG_MATCHER=romav2 OPG_SCALE_REFINE_ITERS=0 OPG_ROMAV2_INPROC=1 OPG_FP_RESIDENT=1" +echo " 日志: $BATCH_LOG_DIR" +echo "==================================================================" +if [[ "$DRY_RUN" == "1" ]]; then echo "[dry-run] 不执行。"; exit 0; fi +BATCH_T0=$(date +%s) + +launch_one() { + local video="$1" gpu="$2" + local vpath="$VIDEO_ROOT/$video.mp4" + local log="$BATCH_LOG_DIR/${video}.log" + if [[ ! -f "$vpath" ]]; then + echo " [skip] $video: 找不到 $vpath" | tee -a "$SUMMARY" + return 1 + fi + echo " [launch] $video -> GPU $gpu (log: $log) @ $(date '+%H:%M:%S')" + local t0; t0=$(date +%s) + ( + export CUDA_VISIBLE_DEVICES="$gpu" + export OPG_MATCHER="romav2" + export OPG_SCALE_REFINE_ITERS="0" + export OPG_ROMAV2_INPROC="1" + export OPG_FP_RESIDENT="1" + [[ -n "$KEY" ]] && export DASHSCOPE_API_KEY="$KEY" + bash "$PIPELINE" --name "$video" --video "$vpath" \ + --recon-backbone "$RECON_BACKBONE" \ + --deform-force-scale 1 --deform-force-poses 1 \ + $STEPS + ) > "$log" 2>&1 + local rc=$? + local dur=$(( $(date +%s) - t0 )) + printf "%s\t%s\tGPU%s\t%dm%02ds\t%s\n" "$video" "$([[ $rc -eq 0 ]] && echo OK || echo FAIL\($rc\))" "$gpu" "$((dur/60))" "$((dur%60))" "$log" >> "$SUMMARY" + echo " [done] $video rc=$rc 耗时 $((dur/60))m$((dur%60))s" + return $rc +} + +declare -A SLOT_PID=() +qi=0 +NV="${#VIDEOS[@]}" +while (( qi < NV )) || (( ${#SLOT_PID[@]} > 0 )); do + for g in "${GPUS[@]}"; do + (( qi < NV )) || break + if [[ -z "${SLOT_PID[$g]:-}" ]]; then + v="${VIDEOS[$qi]}"; qi=$((qi+1)) + launch_one "$v" "$g" & + SLOT_PID[$g]=$! + fi + done + sleep 5 + for g in "${!SLOT_PID[@]}"; do + pid="${SLOT_PID[$g]}" + if ! kill -0 "$pid" 2>/dev/null; then + wait "$pid" 2>/dev/null + unset 'SLOT_PID[$g]' + fi + done +done + +echo "==================================================================" +BATCH_DUR=$(( $(date +%s) - BATCH_T0 )) +echo "全部完成。总墙钟: $((BATCH_DUR/60))m$((BATCH_DUR%60))s (${#VIDEOS[@]} 视频 / ${#GPUS[@]} GPU 并行)" +echo "汇总(视频 状态 GPU 耗时 日志):" +column -t -s $'\t' "$SUMMARY" 2>/dev/null || cat "$SUMMARY" +echo "汇总文件: $SUMMARY" diff --git a/OVOW/engine/run_batch_scenes.sh b/OVOW/engine/run_batch_scenes.sh new file mode 100644 index 0000000000000000000000000000000000000000..21a8c3dc197b57073c32a4c37d2e360da0f30640 --- /dev/null +++ b/OVOW/engine/run_batch_scenes.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +CONFIG_PATH="${1:-${SCRIPT_DIR}/config/batch_config_example.json}" +SCENE_SPEC="${2:-1}" + +if [[ ! -f "${CONFIG_PATH}" ]]; then + echo "配置文件不存在:${CONFIG_PATH}" >&2 + exit 1 +fi + +cd "${SCRIPT_DIR}" +python batch_scene_pipeline.py --config "${CONFIG_PATH}" --scenes "${SCENE_SPEC}" \ No newline at end of file diff --git a/OVOW/engine/run_batch_scenes_rap.sh b/OVOW/engine/run_batch_scenes_rap.sh new file mode 100644 index 0000000000000000000000000000000000000000..e7bd446b5b4d1b74ce8b70cf0739a0d4cc5f2f8b --- /dev/null +++ b/OVOW/engine/run_batch_scenes_rap.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +SCENES="${1:-${SCENES:-1}}" +CONFIG="${2:-${CONFIG:-"$SCRIPT_DIR/config/batch_config_example_legacy_rap.json"}}" +shift $(( $# > 0 ? 1 : 0 )) +shift $(( $# > 0 ? 1 : 0 )) + +if [[ ! -f "$CONFIG" ]]; then + echo "[ERR] Config not found: $CONFIG" >&2 + exit 1 +fi + +python "$SCRIPT_DIR/batch_scene_pipeline_rap.py" \ + --config "$CONFIG" \ + --scenes "$SCENES" \ + "$@" diff --git a/OVOW/engine/run_batch_scenes_unilat3d.sh b/OVOW/engine/run_batch_scenes_unilat3d.sh new file mode 100644 index 0000000000000000000000000000000000000000..de4a8aa357b4861fce575cf99edec6e9ed8475d8 --- /dev/null +++ b/OVOW/engine/run_batch_scenes_unilat3d.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +CONFIG_PATH="${1:-${SCRIPT_DIR}/config/batch_config_unilat_example.json}" +SCENE_SPEC="${2:-1}" + +if [[ ! -f "${CONFIG_PATH}" ]]; then + echo "配置文件不存在:${CONFIG_PATH}" >&2 + exit 1 +fi + +cd "${SCRIPT_DIR}" +python batch_scene_pipeline_unilat3d.py --config "${CONFIG_PATH}" --scenes "${SCENE_SPEC}" diff --git a/OVOW/engine/run_batch_scenes_vedio.sh b/OVOW/engine/run_batch_scenes_vedio.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc2c4320898dc64125fafd1cca72e715e96b02d --- /dev/null +++ b/OVOW/engine/run_batch_scenes_vedio.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +CONFIG_PATH="${1:-${SCRIPT_DIR}/config/batch_video_config_example.json}" +SCENE_SPEC="${2:-1}" + +if [[ ! -f "${CONFIG_PATH}" ]]; then + echo "配置文件不存在:${CONFIG_PATH}" >&2 + exit 1 +fi + +cd "${SCRIPT_DIR}" +python batch_scene_pipeline_vedio.py --config "${CONFIG_PATH}" --scenes "${SCENE_SPEC}" + diff --git a/OVOW/engine/run_steps_scene_image_pipeline.sh b/OVOW/engine/run_steps_scene_image_pipeline.sh new file mode 100644 index 0000000000000000000000000000000000000000..8bb781502c38a2342c6ba2a4af9efec0743373d8 --- /dev/null +++ b/OVOW/engine/run_steps_scene_image_pipeline.sh @@ -0,0 +1,1803 @@ +#!/usr/bin/env bash +set -euo pipefail + +ORIG_ARGS=("$@") + +SCENE_DIR="" +NAME="" +RUN_DIR="" +OUT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs" +OUT_EXPLICIT="0" +REPO="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine" +QWEN_PY="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python" +SAM3_PY="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-sam3/bin/python" +OPG_PY="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python" +BLENDER_BIN="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/opt/blender-4.2.3-linux-x64/blender" +BLENDER_BIN="$(command -v "$BLENDER_BIN" 2>/dev/null || echo "$BLENDER_BIN")" +BLENDER_LIB="" +HDR_PY="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-hdr/bin/python" +INTRHDR_REPO="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/IntrinsicHDR" +INTRHDR_RUNNER="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/run_intrhdr_media.sh" + +STEP12_SCRIPT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/masking/qwen_sam3_single_image_masks.py" +PIPELINE_SINGLE_IMAGE="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/pipeline_single_image.py" +BATCH_CONFIG="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/config/batch_config_example_legacy.json" +RECON_BACKBONE="config" +COMPOSE_IMAGE_SCRIPT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/compose_side_by_side_image.py" + +QWEN_MODEL="Qwen/Qwen3-VL-8B-Instruct" +QWEN_BACKEND="api" +QWEN_API_MODEL="qwen3.5-plus-2026-02-15" +QWEN_API_MODEL_LIST="qwen3.5-flash-2026-02-23,qwen3.5-plus-2026-02-15,qwen3.5-flash,qwen3.5-122b-a10b,qwen3.5-35b-a3b" +QWEN_API_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1" +QWEN_API_KEY_ENV="DASHSCOPE_API_KEY" +QWEN_API_KEY="" +MASK_BACKEND="sam3" +FORCE_STEP1="0" +FORCE_STEP2="0" +SAM_MIN_OBJ_AREA="200" +SAM3_CONF_THRESH="0.35" + +PLANE_NUM="10" +PLANE_BOTTOM="0.03" +GRAVITY_SIGN_MODE="camera_up" +GRAVITY_SIGN_SAMPLES="5" + +PHYSICS_ENABLE="0" +PHYSICS_BOTTOM="0.10" +PHYSICS_ITERS="2" +PHYSICS_MAX_DROP="1.0" +PHYSICS_ALLOW_DOWN="1" +PHYSICS_CONTACT="1" + +LOCK_STATIC="1" +LOCK_STATIC_MODE="full" +STEP18_UNLIT_TEXTURE="1" +STEP18_HDR="" +STEP14_EXPORT_CAMERA="0" +STEP14_KEEP_WORLD_COORD="0" + +RERUN_OBJECTS="" +RERUN_ONLY_FAILED="1" +RERUN_ANCHOR_FRAME="-1" +RERUN_REF_MAP="" +RERUN_REF_IMAGE="" +RERUN_USE_FLUX_REF="0" + +FLUX_PY="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-flux/bin/python" +FLUX2_REPO="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/flux2" +FLUX_STEP19_SCRIPT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/flux2_single_ref_edit.py" +FLUX_MODE="amodal" +FLUX_OBJ_NAME="" +FLUX_SEED="1234" +FLUX_OUT_WIDTH="518" +FLUX_OUT_HEIGHT="518" +FLUX_MATCH_IMAGE_SIZE="none" +FLUX_USE_RGB_CROP_REF="0" +FLUX_GPU="" +FLUX_PROMPT_AMODAL="" +FLUX_PROMPT_VIEW="" +FLUX_KLEIN_9B_MODEL_PATH="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/flux2/flux-2-klein-9b.safetensors" +FLUX_AE_MODEL_PATH="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/flux2/ae.safetensors" +FLUX_QWEN3_8B_MODEL_PATH="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/flux2/text_encoder" +FLUX_QWEN3_8B_TOKENIZER_PATH="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/flux2/tokenizer" + +STEPS=() +STATE_JSON="" +SUMMARY_JSON="" +CFG_MAIN="" +CFG_RIGID="" +CFG_EFFECTIVE="" +SCENE_JSON="" +LABELS_JSON="" + +usage() { + cat < [step ...] + +Main options: + --scene-dir DIR + --name NAME + --run-dir DIR + --out DIR + --qwen-backend api|local + --qwen-model PATH + --qwen-api-model NAME + --qwen-api-model-list LIST + --qwen-api-base-url URL + --qwen-api-key-env ENV + --mask-backend sam3 + --force-step1 0|1 + --force-step2 0|1 + --sam-min-obj-area N + --plane-num N + --plane-bottom X + --gravity-sign-mode camera_up|object_region|auto|none + --gravity-sign-samples N + --physics-enable 0|1 + --physics-bottom X + --physics-iters N + --physics-max-drop X + --physics-allow-down 0|1 + --physics-contact 0|1 + --sam3-conf-thresh X + --batch-config PATH + --recon-backbone config|legacy|trellis2 + --lock-static 0|1 + --lock-static-mode full|rot_only|off + --step14-export-camera 0|1 + --step14-keep-world-coord 0|1 + --step18-unlit-texture 0|1 + + Step 16 options: + --rerun-objects OBJ1,OBJ2 + --rerun-only-failed 0|1 + --rerun-anchor-frame N + --rerun-ref-map PATH + --ref-image PATH + --flux + + Step 18 options: + --hdr PATH|auto + +Step 19 options: + --flux-obj-name OBJS + --flux-mode amodal|view + --flux-seed N + --flux-width N + --flux-height N + --flux-match-image-size V + --flux-use-rgb-crop-ref 0|1 + --flux-gpu ID + --flux-prompt-amodal T + --flux-prompt-view T + + Steps: 1 2 6 7 13 14 15 16 17 18 19 + +Note: + If --scene-dir directly contains image files, the script will auto-create one + subfolder per image and run the selected steps inside each image folder. +USAGE +} + +trim_spaces() { + local s="$1" + s="${s#"${s%%[![:space:]]*}"}" + s="${s%"${s##*[![:space:]]}"}" + echo "$s" +} + +parse_csv_items() { + local raw="$1" + IFS="," read -r -a items <<<"$raw" + local out=() + local item + for item in "${items[@]}"; do + item="$(trim_spaces "$item")" + [[ -n "$item" ]] && out+=("$item") + done + if [[ "${#out[@]}" -le 0 ]]; then + echo "ERROR: requires at least one object, got: '$raw'" >&2 + exit 1 + fi + printf "%s\n" "${out[@]}" +} + +extract_single_csv_item() { + local raw="$1" + local out=() + local item + while IFS= read -r item; do + [[ -n "$item" ]] && out+=("$item") + done < <(parse_csv_items "$raw") + if [[ "${#out[@]}" -ne 1 ]]; then + echo "ERROR: requires exactly one object, got: '$raw'" >&2 + exit 1 + fi + echo "${out[0]}" +} + +normalize_bool() { + local raw="${1:-}" + local v + v="$(echo "$raw" | tr "[:upper:]" "[:lower:]")" + case "$v" in + 1|true|yes|on) echo "1" ;; + 0|false|no|off) echo "0" ;; + *) echo "ERROR: invalid boolean '$raw' (use true/false or 1/0)" >&2; exit 1 ;; + esac +} + +normalize_int() { + local raw="${1:-}" + if [[ "$raw" =~ ^-?[0-9]+$ ]]; then + echo "$raw" + else + echo "ERROR: invalid integer '$raw'" >&2 + exit 1 + fi +} + +normalize_float() { + local raw="${1:-}" + python3 - "$raw" <<'PY' +import sys +raw = sys.argv[1] +try: + val = float(raw) +except Exception: + print(f"ERROR: invalid float '{raw}'", file=sys.stderr) + raise SystemExit(1) +if val in (float("inf"), float("-inf")) or val != val: + print(f"ERROR: invalid float '{raw}'", file=sys.stderr) + raise SystemExit(1) +print(raw) +PY +} + +normalize_lock_static_mode() { + local raw="${1:-}" + local mode + mode="$(echo "$raw" | tr "[:upper:]" "[:lower:]")" + case "$mode" in + full|all|1|true|yes|on) echo "full" ;; + rot_only|rot|rotation|rotation_only) echo "rot_only" ;; + off|none|0|false|no|disable|disabled) echo "off" ;; + *) echo "ERROR: invalid lock-static mode '$raw' (use full|rot_only|off)" >&2; exit 1 ;; + esac +} + +normalize_recon_backbone() { + local raw="${1:-}" + local mode + mode="$(echo "$raw" | tr "[:upper:]" "[:lower:]")" + case "$mode" in + ""|config|default|batch|batch_config) echo "config" ;; + legacy|hi3dgen|amodal3r) echo "legacy" ;; + trellis2|trellis.2|t2|viat2) echo "trellis2" ;; + *) echo "ERROR: invalid --recon-backbone '$raw' (use config|legacy|trellis2)" >&2; exit 1 ;; + esac +} + +normalize_flux_mode() { + local raw="${1:-}" + local mode + mode="$(echo "$raw" | tr "[:upper:]" "[:lower:]")" + case "$mode" in + amodal|complete|completion) echo "amodal" ;; + view|novel|novel_view|novel-view) echo "view" ;; + *) echo "ERROR: invalid flux mode '$raw' (use amodal|view)" >&2; exit 1 ;; + esac +} + +normalize_flux_match_image_size() { + local raw="${1:-}" + local mode + mode="$(echo "$raw" | tr "[:upper:]" "[:lower:]")" + if [[ "$mode" == "none" || -z "$mode" ]]; then + echo "none" + return + fi + if [[ "$mode" =~ ^[0-9]+$ ]]; then + echo "$mode" + return + fi + echo "ERROR: invalid --flux-match-image-size '$raw'" >&2 + exit 1 +} + +materialize_scene_dirs_if_needed() { + local raw_dir="$1" + python3 - "$raw_dir" <<'PY' +from pathlib import Path +import re +import shutil +import sys + +root = Path(sys.argv[1]).expanduser().resolve() +exts = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG", ".webp", ".WEBP"} + +if not root.is_dir(): + raise SystemExit(f"ERROR: scene dir not found: {root}") + +scene_markers = ( + (root / "scene.json").exists() + or (root / "masks").exists() + or (root / "mask_summary.json").exists() +) +image_files = sorted(p for p in root.iterdir() if p.is_file() and p.suffix in exts) + +if scene_markers: + print("passthrough") + print(str(root)) + raise SystemExit(0) + +if len(image_files) == 1: + print("passthrough") + print(str(root)) + raise SystemExit(0) + +if not image_files: + child_scene_dirs = [] + for child in sorted(p for p in root.iterdir() if p.is_dir()): + child_markers = ( + (child / "scene.json").exists() + or (child / "masks").exists() + or (child / "mask_summary.json").exists() + ) + child_images = [p for p in child.iterdir() if p.is_file() and p.suffix in exts] + if child_markers or len(child_images) == 1: + child_scene_dirs.append(str(child.resolve())) + if child_scene_dirs: + print("children") + for scene_dir in child_scene_dirs: + print(scene_dir) + raise SystemExit(0) + print("passthrough") + print(str(root)) + raise SystemExit(0) + +def sanitize(name: str) -> str: + s = name.strip().lower() + s = re.sub(r"\s+", "_", s) + s = re.sub(r"[^a-z0-9_\-]+", "_", s) + s = re.sub(r"_+", "_", s).strip("_") + return s or "image" + +used = set() +scene_dirs = [] +for image_path in image_files: + base = sanitize(image_path.stem) + if base in used: + base = sanitize(f"{image_path.stem}_{image_path.suffix.lstrip('.').lower()}") + idx = 2 + candidate = base + while candidate in used: + candidate = f"{base}_{idx}" + idx += 1 + used.add(candidate) + + scene_dir = root / candidate + scene_dir.mkdir(parents=True, exist_ok=True) + target_image = scene_dir / image_path.name + if not target_image.exists(): + try: + target_image.hardlink_to(image_path) + except Exception: + shutil.copy2(str(image_path), str(target_image)) + scene_dirs.append(scene_dir) + +print("materialized") +for scene_dir in scene_dirs: + print(str(scene_dir)) +PY +} + +default_scene_name_for_scene() { + local scene_dir="$1" + python3 - "$scene_dir" <<'PY' +from pathlib import Path +import json +import sys + +scene_dir = Path(sys.argv[1]).expanduser().resolve() +scene_json = scene_dir / "scene.json" +image_path = None + +if scene_json.exists(): + try: + payload = json.loads(scene_json.read_text(encoding="utf-8")) + except Exception: + payload = {} + image_name = str(payload.get("image") or "").strip() + if image_name: + cand = (scene_dir / image_name).resolve() + if cand.is_file(): + image_path = cand + +if image_path is None: + exts = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG", ".webp", ".WEBP"} + images = sorted(p for p in scene_dir.iterdir() if p.is_file() and p.suffix in exts) + if len(images) == 1: + image_path = images[0].resolve() + elif images: + image_path = images[0].resolve() + +print(image_path.stem if image_path is not None else scene_dir.name) +PY +} + +default_output_root_for_scene() { + local scene_dir="$1" + python3 - "$scene_dir" <<'PY' +from pathlib import Path +import json +import sys + +scene_dir = Path(sys.argv[1]).expanduser().resolve() +scene_json = scene_dir / "scene.json" +image_path = None + +if scene_json.exists(): + try: + payload = json.loads(scene_json.read_text(encoding="utf-8")) + except Exception: + payload = {} + image_name = str(payload.get("image") or "").strip() + if image_name: + cand = (scene_dir / image_name).resolve() + if cand.is_file(): + image_path = cand + +if image_path is None: + exts = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG", ".webp", ".WEBP"} + images = sorted(p for p in scene_dir.iterdir() if p.is_file() and p.suffix in exts) + if len(images) == 1: + image_path = images[0].resolve() + elif images: + image_path = images[0].resolve() + +print(str(scene_dir.resolve())) +PY +} + +forward_args_without_scene_dir() { + local out=() + local skip_next="0" + local arg + for arg in "${ORIG_ARGS[@]}"; do + if [[ "$skip_next" == "1" ]]; then + skip_next="0" + continue + fi + case "$arg" in + --scene-dir) + skip_next="1" + continue + ;; + --scene-dir=*) + continue + ;; + *) + out+=("$arg") + ;; + esac + done + if [[ "${#out[@]}" -gt 0 ]]; then + printf '%s\n' "${out[@]}" + fi +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --scene-dir) SCENE_DIR="$2"; shift 2 ;; + --name) NAME="$2"; shift 2 ;; + --run-dir) RUN_DIR="$2"; shift 2 ;; + --out) OUT="$2"; OUT_EXPLICIT="1"; shift 2 ;; + --qwen-backend) QWEN_BACKEND="$2"; shift 2 ;; + --qwen-model) QWEN_MODEL="$2"; shift 2 ;; + --qwen-api-model) QWEN_API_MODEL="$2"; shift 2 ;; + --qwen-api-model-list) QWEN_API_MODEL_LIST="$2"; shift 2 ;; + --qwen-api-base-url) QWEN_API_BASE_URL="$2"; shift 2 ;; + --qwen-api-key-env) QWEN_API_KEY_ENV="$2"; shift 2 ;; + --mask-backend) MASK_BACKEND="$2"; shift 2 ;; + --force-step1) FORCE_STEP1="$2"; shift 2 ;; + --force-step2) FORCE_STEP2="$2"; shift 2 ;; + --sam-min-obj-area) SAM_MIN_OBJ_AREA="$2"; shift 2 ;; + --plane-num) PLANE_NUM="$2"; shift 2 ;; + --plane-bottom) PLANE_BOTTOM="$2"; shift 2 ;; + --gravity-sign-mode) GRAVITY_SIGN_MODE="$2"; shift 2 ;; + --gravity-sign-samples) GRAVITY_SIGN_SAMPLES="$2"; shift 2 ;; + --physics-enable) PHYSICS_ENABLE="$2"; shift 2 ;; + --physics-bottom) PHYSICS_BOTTOM="$2"; shift 2 ;; + --physics-iters) PHYSICS_ITERS="$2"; shift 2 ;; + --physics-max-drop) PHYSICS_MAX_DROP="$2"; shift 2 ;; + --physics-allow-down) PHYSICS_ALLOW_DOWN="$2"; shift 2 ;; + --physics-contact) PHYSICS_CONTACT="$2"; shift 2 ;; + --sam3-conf-thresh) SAM3_CONF_THRESH="$2"; shift 2 ;; + --batch-config) BATCH_CONFIG="$2"; shift 2 ;; + --recon-backbone) RECON_BACKBONE="$2"; shift 2 ;; + --lock-static) LOCK_STATIC="$2"; shift 2 ;; + --lock-static-mode) LOCK_STATIC_MODE="$2"; shift 2 ;; + --step14-export-camera) STEP14_EXPORT_CAMERA="$2"; shift 2 ;; + --step14-keep-world-coord) STEP14_KEEP_WORLD_COORD="$2"; shift 2 ;; + --step18-unlit-texture) STEP18_UNLIT_TEXTURE="$2"; shift 2 ;; + --hdr) STEP18_HDR="$2"; shift 2 ;; + --rerun-objects) RERUN_OBJECTS="$2"; shift 2 ;; + --rerun-only-failed) RERUN_ONLY_FAILED="$2"; shift 2 ;; + --rerun-anchor-frame) RERUN_ANCHOR_FRAME="$2"; shift 2 ;; + --rerun-ref-map) RERUN_REF_MAP="$2"; shift 2 ;; + --ref-image) RERUN_REF_IMAGE="$2"; shift 2 ;; + --flux) RERUN_USE_FLUX_REF="1"; shift ;; + --flux-obj-name) FLUX_OBJ_NAME="$2"; shift 2 ;; + --flux-mode) FLUX_MODE="$2"; shift 2 ;; + --flux-seed) FLUX_SEED="$2"; shift 2 ;; + --flux-width) FLUX_OUT_WIDTH="$2"; shift 2 ;; + --flux-height) FLUX_OUT_HEIGHT="$2"; shift 2 ;; + --flux-match-image-size) FLUX_MATCH_IMAGE_SIZE="$2"; shift 2 ;; + --flux-use-rgb-crop-ref) FLUX_USE_RGB_CROP_REF="$2"; shift 2 ;; + --flux-gpu) FLUX_GPU="$2"; shift 2 ;; + --flux-prompt-amodal) FLUX_PROMPT_AMODAL="$2"; shift 2 ;; + --flux-prompt-view) FLUX_PROMPT_VIEW="$2"; shift 2 ;; + --help|-h) usage; exit 0 ;; + --*) echo "ERROR: unknown option $1" >&2; usage; exit 1 ;; + *) STEPS+=("$1"); shift ;; + esac +done + +[[ -n "$SCENE_DIR" ]] || { echo "ERROR: --scene-dir is required" >&2; usage; exit 1; } +[[ "${#STEPS[@]}" -gt 0 ]] || { echo "ERROR: at least one step is required" >&2; usage; exit 1; } + +if [[ "${OPG_SINGLE_IMAGE_SCENE_PREPARED:-0}" != "1" ]]; then + mapfile -t _scene_dir_mode_lines < <(materialize_scene_dirs_if_needed "$SCENE_DIR") + if [[ "${#_scene_dir_mode_lines[@]}" -ge 2 && ( "${_scene_dir_mode_lines[0]}" == "materialized" || "${_scene_dir_mode_lines[0]}" == "children" ) ]]; then + mapfile -t _forward_args < <(forward_args_without_scene_dir) + mapfile -t _scene_dir_list < <(printf '%s\n' "${_scene_dir_mode_lines[@]:1}") + if [[ -n "$NAME" && "${#_scene_dir_list[@]}" -gt 1 ]]; then + echo "ERROR: --name cannot be used when --scene-dir expands to multiple image scenes." >&2 + exit 1 + fi + if [[ "${#_scene_dir_list[@]}" -eq 1 ]]; then + echo "[Info] Use image scene dir: ${_scene_dir_list[0]}" + SCENE_DIR="${_scene_dir_list[0]}" + else + echo "[Info] Found ${#_scene_dir_list[@]} image scenes under: $SCENE_DIR" + local_scene_dir="" + for local_scene_dir in "${_scene_dir_list[@]}"; do + echo "[Batch] Run image scene: $local_scene_dir" + OPG_SINGLE_IMAGE_SCENE_PREPARED=1 bash "$0" --scene-dir "$local_scene_dir" "${_forward_args[@]}" + done + exit 0 + fi + fi +fi + +SCENE_DIR="$(python3 - "$SCENE_DIR" <<'PY' +from pathlib import Path +import sys +print(Path(sys.argv[1]).expanduser().resolve()) +PY +)" +[[ -d "$SCENE_DIR" ]] || { echo "ERROR: scene dir not found: $SCENE_DIR" >&2; exit 1; } +NAME="${NAME:-$(default_scene_name_for_scene "$SCENE_DIR")}" +if [[ "$OUT_EXPLICIT" != "1" ]]; then + OUT="$(default_output_root_for_scene "$SCENE_DIR")" +fi +mkdir -p "$OUT/metadata" "$OUT/recon_ready/$NAME" + +STATE_JSON="$OUT/metadata/${NAME}_image_step_state.json" +SUMMARY_JSON="$OUT/metadata/${NAME}_mask_summary.json" +CFG_MAIN="$OUT/recon_ready/$NAME/pipeline_config.json" +CFG_RIGID="$OUT/recon_ready/$NAME/pipeline_config_rigid.json" +CFG_EFFECTIVE="$OUT/recon_ready/$NAME/pipeline_config_effective.json" +SCENE_JSON="$SCENE_DIR/scene.json" +LABELS_JSON="$OUT/metadata/${NAME}_labels.json" + +MASK_BACKEND="$(echo "$MASK_BACKEND" | tr "[:upper:]" "[:lower:]")" +QWEN_BACKEND="$(echo "$QWEN_BACKEND" | tr "[:upper:]" "[:lower:]")" +[[ "$QWEN_BACKEND" == "api" || "$QWEN_BACKEND" == "local" ]] || { echo "ERROR: --qwen-backend must be api or local" >&2; exit 1; } +[[ "$MASK_BACKEND" == "sam3" ]] || { echo "ERROR: single-image pipeline only supports --mask-backend sam3" >&2; exit 1; } +if [[ "$QWEN_BACKEND" == "api" ]]; then + if [[ -n "$QWEN_API_KEY" ]]; then + export "$QWEN_API_KEY_ENV=$QWEN_API_KEY" + fi + if [[ -z "${!QWEN_API_KEY_ENV:-}" ]]; then + echo "ERROR: API key env '$QWEN_API_KEY_ENV' is empty." >&2 + exit 1 + fi +fi +FORCE_STEP1_BOOL="$(normalize_bool "$FORCE_STEP1")" +FORCE_STEP2_BOOL="$(normalize_bool "$FORCE_STEP2")" +LOCK_STATIC_BOOL="$(normalize_bool "$LOCK_STATIC")" +STEP14_EXPORT_CAMERA_BOOL="$(normalize_bool "$STEP14_EXPORT_CAMERA")" +STEP14_KEEP_WORLD_COORD_BOOL="$(normalize_bool "$STEP14_KEEP_WORLD_COORD")" +STEP18_UNLIT_TEXTURE_BOOL="$(normalize_bool "$STEP18_UNLIT_TEXTURE")" +RERUN_ONLY_FAILED_BOOL="$(normalize_bool "$RERUN_ONLY_FAILED")" +PHYSICS_ENABLE_BOOL="$(normalize_bool "$PHYSICS_ENABLE")" +PHYSICS_ALLOW_DOWN_BOOL="$(normalize_bool "$PHYSICS_ALLOW_DOWN")" +PHYSICS_CONTACT_BOOL="$(normalize_bool "$PHYSICS_CONTACT")" +LOCK_STATIC_MODE_CANONICAL="$(normalize_lock_static_mode "$LOCK_STATIC_MODE")" +RECON_BACKBONE_CANONICAL="$(normalize_recon_backbone "$RECON_BACKBONE")" +FLUX_USE_RGB_CROP_REF_BOOL="$(normalize_bool "$FLUX_USE_RGB_CROP_REF")" +RERUN_ANCHOR_FRAME_INT="$(normalize_int "$RERUN_ANCHOR_FRAME")" +SAM_MIN_OBJ_AREA_INT="$(normalize_int "$SAM_MIN_OBJ_AREA")" +PLANE_NUM_INT="$(normalize_int "$PLANE_NUM")" +GRAVITY_SIGN_SAMPLES_INT="$(normalize_int "$GRAVITY_SIGN_SAMPLES")" +PHYSICS_ITERS_INT="$(normalize_int "$PHYSICS_ITERS")" +PLANE_BOTTOM_FLOAT="$(normalize_float "$PLANE_BOTTOM")" +PHYSICS_BOTTOM_FLOAT="$(normalize_float "$PHYSICS_BOTTOM")" +PHYSICS_MAX_DROP_FLOAT="$(normalize_float "$PHYSICS_MAX_DROP")" +FLUX_OUT_WIDTH_INT="$(normalize_int "$FLUX_OUT_WIDTH")" +FLUX_OUT_HEIGHT_INT="$(normalize_int "$FLUX_OUT_HEIGHT")" +FLUX_MODE_CANONICAL="$(normalize_flux_mode "$FLUX_MODE")" +FLUX_MATCH_IMAGE_SIZE_CANONICAL="$(normalize_flux_match_image_size "$FLUX_MATCH_IMAGE_SIZE")" + +if [[ "$PLANE_NUM_INT" -le 0 ]]; then + echo "ERROR: --plane-num must be > 0 (got: $PLANE_NUM_INT)" >&2 + exit 1 +fi +if [[ "$GRAVITY_SIGN_SAMPLES_INT" -le 0 ]]; then + echo "ERROR: --gravity-sign-samples must be > 0 (got: $GRAVITY_SIGN_SAMPLES_INT)" >&2 + exit 1 +fi +if [[ "$PHYSICS_ITERS_INT" -le 0 ]]; then + echo "ERROR: --physics-iters must be > 0 (got: $PHYSICS_ITERS_INT)" >&2 + exit 1 +fi + +if [[ -n "$RERUN_REF_MAP" && ! -f "$RERUN_REF_MAP" ]]; then + echo "ERROR: --rerun-ref-map file not found: $RERUN_REF_MAP" >&2 + exit 1 +fi +if [[ -n "$RERUN_REF_IMAGE" && ! -f "$RERUN_REF_IMAGE" ]]; then + echo "ERROR: --ref-image file not found: $RERUN_REF_IMAGE" >&2 + exit 1 +fi +if [[ "$RERUN_USE_FLUX_REF" == "1" && -n "$RERUN_REF_MAP" ]]; then + echo "ERROR: --flux and --rerun-ref-map cannot be used together." >&2 + exit 1 +fi +if [[ "$RERUN_USE_FLUX_REF" == "1" && -n "$RERUN_REF_IMAGE" ]]; then + echo "ERROR: --flux and --ref-image cannot be used together." >&2 + exit 1 +fi +if [[ "$RERUN_USE_FLUX_REF" == "1" && -z "$RERUN_OBJECTS" ]]; then + echo "ERROR: --flux requires --rerun-objects." >&2 + exit 1 +fi +if [[ -n "$RERUN_REF_IMAGE" && -n "$RERUN_REF_MAP" ]]; then + echo "ERROR: --ref-image and --rerun-ref-map cannot be used together." >&2 + exit 1 +fi +if [[ -n "$RERUN_REF_IMAGE" && -n "$RERUN_OBJECTS" ]]; then + obj_count="$(parse_csv_items "$RERUN_OBJECTS" | wc -l | tr -d " ")" + if [[ "$obj_count" -ne 1 ]]; then + echo "ERROR: --ref-image requires exactly one --rerun-objects object." >&2 + exit 1 + fi +fi + +state_get() { + local key="$1" + python3 - "$STATE_JSON" "$key" <<'PY' +import json +import pathlib +import sys +p = pathlib.Path(sys.argv[1]) +k = sys.argv[2] +if not p.exists(): + print("") + raise SystemExit +try: + d = json.loads(p.read_text(encoding="utf-8")) +except Exception: + print("") + raise SystemExit +v = d.get(k, "") +print(v if isinstance(v, str) else "") +PY +} + +state_set() { + local key="$1" + local val="$2" + python3 - "$STATE_JSON" "$key" "$val" <<'PY' +import json +import pathlib +import sys +p = pathlib.Path(sys.argv[1]) +k = sys.argv[2] +v = sys.argv[3] +d = {} +if p.exists(): + try: + d = json.loads(p.read_text(encoding="utf-8")) + except Exception: + d = {} +d[k] = v +p.parent.mkdir(parents=True, exist_ok=True) +p.write_text(json.dumps(d, indent=2), encoding="utf-8") +print(f"[state] {k}={v}") +PY +} + +timestamp_now() { + date "+%Y-%m-%dT%H:%M:%S%z" +} + +steps_csv() { + local IFS="," + echo "${STEPS[*]}" +} + +step_name_for_id() { + case "${1:-}" in + 1) echo "Qwen labels" ;; + 2) echo "Build masks" ;; + 6) echo "Rigid reconstruction" ;; + 7) echo "Plane + rigid/static physics" ;; + 13) echo "Export pre-physics GLB" ;; + 14) echo "Export physics GLB" ;; + 15) echo "Generate intrinsic HDR EXR" ;; + 16) echo "Rerun failed step-6 objects" ;; + 17) echo "Render white split image" ;; + 18) echo "Render textured split image" ;; + 19) echo "FLUX.2 single-reference edit" ;; + *) echo "Unknown" ;; + esac +} + +CURRENT_STEP_ID="" +CURRENT_STEP_NAME="" +PIPELINE_FINAL_STATUS="" + +init_pipeline_state() { + state_set scene_dir "$SCENE_DIR" + state_set scene_name "$NAME" + state_set out_root "$OUT" + state_set requested_steps "$(steps_csv)" + state_set total_steps "${#STEPS[@]}" + state_set pipeline_status "ready" + state_set current_step "" + state_set current_step_name "" + state_set current_step_status "" + state_set failed_step "" + state_set failed_step_name "" + state_set interrupt_signal "" + state_set started_at "$(timestamp_now)" + state_set finished_at "" +} + +mark_step_started() { + local step="$1" + CURRENT_STEP_ID="$step" + CURRENT_STEP_NAME="$(step_name_for_id "$step")" + state_set pipeline_status "running" + state_set current_step "$CURRENT_STEP_ID" + state_set current_step_name "$CURRENT_STEP_NAME" + state_set current_step_status "running" + state_set current_step_started_at "$(timestamp_now)" +} + +mark_step_finished() { + local step="$1" + local step_name="${CURRENT_STEP_NAME:-$(step_name_for_id "$step")}" + state_set last_completed_step "$step" + state_set last_completed_step_name "$step_name" + state_set last_completed_at "$(timestamp_now)" + state_set current_step "" + state_set current_step_name "" + state_set current_step_status "completed" + state_set current_step_started_at "" + CURRENT_STEP_ID="" + CURRENT_STEP_NAME="" +} + +mark_step_failed() { + local status="$1" + if [[ -n "$CURRENT_STEP_ID" ]]; then + state_set current_step "$CURRENT_STEP_ID" + state_set current_step_name "$CURRENT_STEP_NAME" + state_set current_step_status "$status" + state_set failed_step "$CURRENT_STEP_ID" + state_set failed_step_name "$CURRENT_STEP_NAME" + fi +} + +on_pipeline_signal() { + local sig="$1" + PIPELINE_FINAL_STATUS="interrupted" + mark_step_failed "interrupted" + state_set interrupt_signal "$sig" + exit 130 +} + +on_pipeline_exit() { + local rc=$? + if [[ "$PIPELINE_FINAL_STATUS" == "interrupted" ]]; then + state_set pipeline_status "interrupted" + state_set finished_at "$(timestamp_now)" + return + fi + if [[ "$rc" -eq 0 ]]; then + state_set pipeline_status "completed" + state_set finished_at "$(timestamp_now)" + return + fi + state_set pipeline_status "failed" + mark_step_failed "failed" + state_set finished_at "$(timestamp_now)" +} + +mark_inputs_dirty() { state_set inputs_dirty "1"; } +mark_inputs_clean() { state_set inputs_dirty "0"; } + +ensure_inputs_clean() { + local dirty + dirty="$(state_get inputs_dirty)" + if [[ "$dirty" == "1" ]]; then + echo "ERROR: step 1/2 changed scene inputs. Please rerun step 6 before later steps." >&2 + exit 1 + fi +} + +resolve_run_dir() { + if [[ -n "$RUN_DIR" ]]; then + return + fi + RUN_DIR="$(state_get run_dir)" + if [[ -z "$RUN_DIR" ]]; then + echo "ERROR: RUN_DIR not set. Please run step 6 first or pass --run-dir." >&2 + exit 1 + fi +} + +get_effective_config() { + local cfg_state + cfg_state="$(state_get effective_config)" + if [[ -n "$cfg_state" && -f "$cfg_state" ]]; then + echo "$cfg_state" + return + fi + if [[ -f "$CFG_EFFECTIVE" ]]; then + echo "$CFG_EFFECTIVE" + return + fi + echo "$CFG_MAIN" +} + +prepare_step6_batch_config() { + local backbone="$1" + local cfg_out="$OUT/recon_ready/$NAME/batch_config_step6_${backbone}.json" + if [[ "$backbone" == "config" ]]; then + echo "$BATCH_CONFIG" + return + fi + + "$OPG_PY" - "$BATCH_CONFIG" "$cfg_out" "$backbone" <<'PY' +import json +import sys +from pathlib import Path + +src = Path(sys.argv[1]) +dst = Path(sys.argv[2]) +backbone = sys.argv[3] + +cfg = json.loads(src.read_text(encoding="utf-8")) +generation = cfg.setdefault("generation", {}) +generation["model_type"] = backbone + +dst.parent.mkdir(parents=True, exist_ok=True) +dst.write_text(json.dumps(cfg, indent=2, ensure_ascii=False), encoding="utf-8") +print(dst) +PY +} + +choose_plane_pcd() { + local pcd_main="$RUN_DIR/scene_point_cloud_frame_all.ply" + local pcd_alt="$RUN_DIR/combined_scene_objects.ply" + if [[ -f "$pcd_main" ]]; then + echo "$pcd_main" + return + fi + if [[ -f "$pcd_alt" ]]; then + echo "$pcd_alt" + return + fi + echo "$pcd_main" +} + +scene_input_image_path() { + python3 - "$SCENE_DIR" "$LABELS_JSON" <<'PY' +from pathlib import Path +import json +import sys + +scene_dir = Path(sys.argv[1]).expanduser().resolve() +labels_json = Path(sys.argv[2]).expanduser().resolve() +scene_json = scene_dir / "scene.json" +image_path = None + +if scene_json.exists(): + try: + payload = json.loads(scene_json.read_text(encoding="utf-8")) + except Exception: + payload = {} + image_name = str(payload.get("image") or "").strip() + if image_name: + cand = (scene_dir / image_name).resolve() + if cand.is_file(): + image_path = cand + +if image_path is None: + exts = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG", ".webp", ".WEBP"} + images = sorted(p for p in scene_dir.iterdir() if p.is_file() and p.suffix in exts) + if images: + image_path = images[0].resolve() + +if image_path is None and labels_json.is_file(): + try: + payload = json.loads(labels_json.read_text(encoding="utf-8")) + except Exception: + payload = {} + for key in ("image", "video"): + raw = str(payload.get(key) or "").strip() + if not raw: + continue + cand = Path(raw).expanduser() + if not cand.is_absolute(): + cand = (scene_dir / cand).resolve() + if cand.is_file(): + image_path = cand + break + +if image_path is None: + raise SystemExit(f"ERROR: no input image found under {scene_dir}") + +print(str(image_path)) +PY +} + +default_step15_hdr_path() { + echo "$SCENE_DIR/lighting/scene_intrinsic_hdr.exr" +} + +resolve_step18_hdr_path() { + local hdr_path="${STEP18_HDR:-}" + if [[ -z "$hdr_path" ]]; then + echo "" + return + fi + if [[ "$hdr_path" == "auto" ]]; then + hdr_path="$(state_get step15_hdr_exr)" + if [[ -z "$hdr_path" || ! -f "$hdr_path" ]]; then + hdr_path="$SCENE_DIR/lighting/scene_intrinsic_hdr.exr" + fi + if [[ ! -f "$hdr_path" && -n "$RUN_DIR" ]]; then + hdr_path="$RUN_DIR/lighting/scene_intrinsic_hdr.exr" + fi + fi + if [[ ! -f "$hdr_path" ]]; then + echo "ERROR: HDR EXR not found: $hdr_path" >&2 + exit 1 + fi + echo "$hdr_path" +} + +write_effective_config_from_step6() { + local run_dir="$1" + if [[ ! -f "$CFG_MAIN" ]]; then + return + fi + "$OPG_PY" - "$CFG_MAIN" "$CFG_EFFECTIVE" "$run_dir/object_errors_step6.json" "$run_dir" <<'PY' +import json +import sys +from pathlib import Path + +cfg_in = Path(sys.argv[1]) +cfg_out = Path(sys.argv[2]) +err_json = Path(sys.argv[3]) +run_dir = Path(sys.argv[4]) + +cfg = json.loads(cfg_in.read_text(encoding="utf-8")) +failed_names = set() +if err_json.exists(): + try: + payload = json.loads(err_json.read_text(encoding="utf-8")) + except Exception: + payload = {} + for item in payload.get("failed_objects", []): + name = str(item.get("name", "")).strip() + if name: + failed_names.add(name) + for name in payload.get("failed_names", []): + n = str(name).strip() + if n: + failed_names.add(n) + +kept = [] +for obj in cfg.get("objects", []): + name = str(obj.get("name") or obj.get("id") or "").strip() + category = str(obj.get("category", "")).strip().lower() + if name and name in failed_names: + continue + if name and category in {"static", "rigid"}: + pose_dir = run_dir / "objects" / name / "pose_result" + has_pose = (pose_dir / "poses.json").exists() or (pose_dir / "poses_locked.json").exists() + if not has_pose: + continue + kept.append(obj) + +cfg["objects"] = kept +cfg_out.parent.mkdir(parents=True, exist_ok=True) +cfg_out.write_text(json.dumps(cfg, indent=2, ensure_ascii=False), encoding="utf-8") +PY + state_set effective_config "$CFG_EFFECTIVE" +} + +lock_static_poses() { + local run_dir="$1" + local cfg + cfg="$(get_effective_config)" + if [[ "$LOCK_STATIC_BOOL" != "1" || "$LOCK_STATIC_MODE_CANONICAL" == "off" ]]; then + return + fi + if [[ ! -d "$run_dir" || ! -f "$cfg" ]]; then + return + fi + "$OPG_PY" - "$run_dir" "$cfg" "$LOCK_STATIC_MODE_CANONICAL" <<'PY' +import json +import sys +from pathlib import Path +import cv2 +import numpy as np + +run_dir = Path(sys.argv[1]) +cfg_path = Path(sys.argv[2]) +lock_mode = str(sys.argv[3]).strip().lower() +cfg = json.loads(cfg_path.read_text(encoding="utf-8")) +static_names = { + str(o.get("name")) + for o in cfg.get("objects", []) + if str(o.get("category", "")).lower() == "static" +} +objects_root = run_dir / "objects" +if not objects_root.exists(): + raise SystemExit(0) + +for obj_dir in objects_root.iterdir(): + if not obj_dir.is_dir() or obj_dir.name not in static_names: + continue + pose_path = obj_dir / "pose_result" / "poses.json" + if not pose_path.exists(): + continue + poses = json.loads(pose_path.read_text(encoding="utf-8")) + frame_ids = sorted(int(k) for k in poses.keys() if str(k).isdigit()) + if not frame_ids: + continue + mask_dir = obj_dir / "masks" + best_frame = None + best_area = -1 + if mask_dir.exists(): + for fid in frame_ids: + mp = mask_dir / f"{fid:06d}.png" + if not mp.exists(): + continue + m = cv2.imread(str(mp), cv2.IMREAD_GRAYSCALE) + if m is None: + continue + area = int((m > 0).sum()) + if area > best_area: + best_area, best_frame = area, fid + if best_frame is None: + best_frame = frame_ids[0] + anchor = np.asarray(poses[str(best_frame)], dtype=np.float64) + if anchor.shape != (4, 4): + continue + if lock_mode == "full": + locked = {str(fid): poses[str(best_frame)] for fid in frame_ids} + elif lock_mode == "rot_only": + locked = {} + anchor_R = anchor[:3, :3] + for fid in frame_ids: + src = np.asarray(poses[str(fid)], dtype=np.float64) + if src.shape != (4, 4): + continue + out_pose = src.copy() + out_pose[:3, :3] = anchor_R + out_pose[3, :] = np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64) + locked[str(fid)] = out_pose.tolist() + if not locked: + continue + else: + continue + out = pose_path.parent / "poses_locked.json" + out.write_text(json.dumps(locked, indent=2), encoding="utf-8") +PY +} + +ensure_alignment() { + local cfg_effective plane_pcd align + cfg_effective="$(get_effective_config)" + plane_pcd="$(choose_plane_pcd)" + align="$RUN_DIR/alignment_plane.json" + if [[ -f "$align" ]]; then + local keep="0" + keep="$(python3 - "$align" "$GRAVITY_SIGN_MODE" <<'PY' +import json +import sys +path = sys.argv[1] +expected_mode = sys.argv[2].strip().lower() +try: + data = json.load(open(path, "r", encoding="utf-8")) +except Exception: + print("0") + raise SystemExit +stats = data.get("stats", {}) +mode = str(stats.get("gravity_sign_mode", "camera_up")).strip().lower() +camera_ok = int(stats.get("camera_up_prior", 0)) == 1 +print("1" if mode == expected_mode and camera_ok else "0") +PY +)" + if [[ "$keep" == "1" ]]; then + return + fi + echo "[Info] Re-fitting alignment with gravity sign mode: $GRAVITY_SIGN_MODE" + fi + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/fit_plane_align.py \ + --run-dir "$RUN_DIR" \ + --config "$cfg_effective" \ + --pcd "$plane_pcd" \ + --static-only \ + --num-planes "$PLANE_NUM_INT" \ + --bottom-percent "$PLANE_BOTTOM_FLOAT" \ + --gravity-sign-mode "$GRAVITY_SIGN_MODE" \ + --gravity-sign-samples "$GRAVITY_SIGN_SAMPLES_INT" \ + --camera-up-prior 1 \ + --camera-up-samples 5 \ + --out "$align" +} + +scene_masks_ready() { + python3 - "$SCENE_JSON" <<'PY' +import json +import sys +from pathlib import Path +path = Path(sys.argv[1]) +if not path.exists(): + print("0") + raise SystemExit +try: + data = json.loads(path.read_text(encoding="utf-8")) +except Exception: + print("0") + raise SystemExit +objs = data.get("objects", []) +if not isinstance(objs, list) or not objs: + print("0") + raise SystemExit +scene_dir = path.parent +for obj in objs: + mask_rel = str(obj.get("mask") or "").strip() + if not mask_rel: + print("0") + raise SystemExit + mask_path = (scene_dir / mask_rel).resolve() + if not mask_path.is_file() or mask_path.stat().st_size <= 0: + print("0") + raise SystemExit +print("1") +PY +} + +find_first_png() { + local dir="$1" + python3 - "$dir" <<'PY' +from pathlib import Path +import sys +p = Path(sys.argv[1]) +files = sorted(p.glob("*.png")) +print(files[0] if files else "") +PY +} + +find_flux_ref_image() { + local run_dir="$1" + local obj_name="$2" + local mode="$3" + "$OPG_PY" - "$run_dir" "$obj_name" "$mode" <<'PY' +import sys +from pathlib import Path +run_dir = Path(sys.argv[1]) +obj_name = sys.argv[2] +mode = sys.argv[3] +root = run_dir / "objects" / "fluxoutput" / obj_name +if not root.exists(): + raise SystemExit(f"ERROR: flux output dir not found: {root}") +mode_dir = root / mode +if not mode_dir.exists(): + mode_dirs = sorted(p for p in root.iterdir() if p.is_dir()) + if not mode_dirs: + raise SystemExit(f"ERROR: no mode directories in flux output: {root}") + mode_dir = mode_dirs[-1] +run_dirs = sorted([p for p in mode_dir.iterdir() if p.is_dir()]) +if not run_dirs: + raise SystemExit(f"ERROR: no run directories in flux output: {mode_dir}") +for run_path in sorted(run_dirs, reverse=True): + candidates = [] + candidates.extend(sorted(run_path.glob("*.png"))) + candidates.extend(sorted((run_path / "outputs").glob("*.png"))) + candidates.extend(sorted((run_path / "output").glob("*.png"))) + for cand in reversed(candidates): + if cand.is_file(): + print(str(cand.resolve())) + raise SystemExit(0) +raise SystemExit(f"ERROR: no flux reference image found for object {obj_name} under {root}") +PY +} + +init_pipeline_state +trap 'on_pipeline_signal INT' INT +trap 'on_pipeline_signal TERM' TERM +trap 'on_pipeline_exit' EXIT + +step1_labels() { + echo "[Step 1] Qwen labels" + if [[ -f "$LABELS_JSON" && "$FORCE_STEP1_BOOL" != "1" ]]; then + echo "[Step 1] Reuse existing $LABELS_JSON" + state_set labels_json "$LABELS_JSON" + return + fi + "$QWEN_PY" "$STEP12_SCRIPT" \ + --scene-dir "$SCENE_DIR" \ + --scene-name "$NAME" \ + --mode labels \ + --output-root "$OUT" \ + --qwen-backend "$QWEN_BACKEND" \ + --qwen-model "$QWEN_MODEL" \ + --qwen-api-model "$QWEN_API_MODEL" \ + --qwen-api-model-list "$QWEN_API_MODEL_LIST" \ + --qwen-api-base-url "$QWEN_API_BASE_URL" \ + --qwen-api-key-env "$QWEN_API_KEY_ENV" + test -f "$LABELS_JSON" + state_set labels_json "$LABELS_JSON" + mark_inputs_dirty +} + +step2_masks() { + echo "[Step 2] Build single-image masks (${MASK_BACKEND})" + local ready + local labels_newer="0" + ready="$(scene_masks_ready)" + if [[ -f "$LABELS_JSON" && -f "$SUMMARY_JSON" && "$LABELS_JSON" -nt "$SUMMARY_JSON" ]]; then + labels_newer="1" + fi + if [[ "$FORCE_STEP2_BOOL" != "1" && "$labels_newer" != "1" && "$ready" == "1" && -f "$SUMMARY_JSON" && -f "$CFG_MAIN" ]]; then + echo "[Step 2] Reuse existing masks/config" + state_set mask_summary "$SUMMARY_JSON" + return + fi + [[ -f "$LABELS_JSON" ]] || { echo "ERROR: missing $LABELS_JSON. Run step 1 first." >&2; exit 1; } + "$SAM3_PY" "$STEP12_SCRIPT" \ + --scene-dir "$SCENE_DIR" \ + --scene-name "$NAME" \ + --mode masks \ + --labels-json "$LABELS_JSON" \ + --backend sam3 \ + --output-root "$OUT" \ + --batch-config "$BATCH_CONFIG" \ + --default-category static \ + --min-obj-area "$SAM_MIN_OBJ_AREA_INT" \ + --sam3-ckpt "${SAM3_CKPT:-/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/third_party/sam3/checkpoints/sam3/sam3.pt}" \ + --sam3-confidence-threshold "$SAM3_CONF_THRESH" + test -f "$SUMMARY_JSON" + test -f "$CFG_MAIN" + state_set mask_summary "$SUMMARY_JSON" + if [[ -f "$SCENE_JSON" ]]; then + state_set scene_json "$SCENE_JSON" + fi + mark_inputs_dirty +} + +step6_reconstruct_rigid() { + echo "[Step 6] Run single-image static+rigid pipeline (recon_backbone=${RECON_BACKBONE_CANONICAL})" + if [[ ! -f "$CFG_MAIN" ]]; then + echo "ERROR: missing $CFG_MAIN. Run step 2 first." >&2 + exit 1 + fi + local step6_batch_config + step6_batch_config="$(prepare_step6_batch_config "$RECON_BACKBONE_CANONICAL")" + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/filter_pipeline_config.py \ + --input "$CFG_MAIN" \ + --output "$CFG_RIGID" \ + --exclude-category deform \ + --drop-missing-masks + + local rigid_count + rigid_count="$($OPG_PY - "$CFG_RIGID" <<'PY' +import json +import sys +cfg = json.load(open(sys.argv[1], "r", encoding="utf-8")) +objs = cfg.get("objects", []) +print(len(objs) if isinstance(objs, list) else 0) +PY +)" + if [[ "$rigid_count" -le 0 ]]; then + echo "ERROR: no valid static/rigid objects remain after filtering masks." >&2 + exit 1 + fi + "$OPG_PY" - "$CFG_RIGID" "$step6_batch_config" <<'PY' +import json +import sys +from pathlib import Path + +cfg_path = Path(sys.argv[1]) +batch_path = Path(sys.argv[2]).resolve() +cfg = json.loads(cfg_path.read_text(encoding="utf-8")) +cfg["batch_config"] = str(batch_path) +cfg_path.write_text(json.dumps(cfg, indent=2, ensure_ascii=False), encoding="utf-8") +print(f"[Step 6] batch_config={batch_path}") +PY + if [[ -z "$RUN_DIR" ]]; then + RUN_DIR="$OUT/image_pipeline_$(date +%Y%m%d_%H%M%S)/$NAME" + fi + "$OPG_PY" "$PIPELINE_SINGLE_IMAGE" \ + --config "$CFG_RIGID" \ + --run-dir "$RUN_DIR" \ + --continue-on-object-error 1 + test -d "$RUN_DIR" + state_set step6_recon_backbone "$RECON_BACKBONE_CANONICAL" + state_set step6_batch_config "$step6_batch_config" + state_set run_dir "$RUN_DIR" + write_effective_config_from_step6 "$RUN_DIR" + lock_static_poses "$RUN_DIR" + mark_inputs_clean +} + +step7_plane_and_rigid_physics() { + echo "[Step 7] Plane + rigid/static physics" + ensure_inputs_clean + resolve_run_dir + local cfg_effective plane_pcd + cfg_effective="$(get_effective_config)" + plane_pcd="$(choose_plane_pcd)" + lock_static_poses "$RUN_DIR" + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/fit_plane_align.py \ + --run-dir "$RUN_DIR" \ + --config "$cfg_effective" \ + --pcd "$plane_pcd" \ + --static-only \ + --num-planes "$PLANE_NUM_INT" \ + --bottom-percent "$PLANE_BOTTOM_FLOAT" \ + --gravity-sign-mode "$GRAVITY_SIGN_MODE" \ + --gravity-sign-samples "$GRAVITY_SIGN_SAMPLES_INT" \ + --camera-up-prior 1 \ + --camera-up-samples 5 \ + --out "$RUN_DIR/alignment_plane.json" + if [[ "$PHYSICS_ENABLE_BOOL" != "1" ]]; then + echo "[Step 7] Physics disabled; fitted plane only." + return + fi + local phys_flags=() + if [[ "$LOCK_STATIC_BOOL" == "1" ]]; then phys_flags+=(--use-locked-static); fi + if [[ "$PHYSICS_ALLOW_DOWN_BOOL" == "1" ]]; then phys_flags+=(--allow-down); fi + if [[ "$PHYSICS_CONTACT_BOOL" == "1" ]]; then phys_flags+=(--contact-objects); fi + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/physics_project_z.py \ + --run-dir "$RUN_DIR" \ + --config "$cfg_effective" \ + --alignment "$RUN_DIR/alignment_plane.json" \ + --plane-z zero \ + --bottom-percent "$PHYSICS_BOTTOM_FLOAT" \ + --iters "$PHYSICS_ITERS_INT" \ + --max-drop "$PHYSICS_MAX_DROP_FLOAT" \ + "${phys_flags[@]}" +} + +step13_export_prephysics_glb() { + echo "[Step 13] Export full-scene GLB pre-physics (video-compatible)" + ensure_inputs_clean + resolve_run_dir + local cfg_effective + cfg_effective="$(get_effective_config)" + lock_static_poses "$RUN_DIR" + ensure_alignment + + local glb_args=( + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/export_scene_glb_with_deform.py + --run-dir "$RUN_DIR" + --config "$cfg_effective" + --motion-output-root "$OUT/motion324_outputs" + --motion-manifest "$OUT/motion324_outputs/$NAME/manifest.json" + --output "$RUN_DIR/scene_anim_blender_aligned_plane_with_deform_prephysics.glb" + --no-plane + --coord blender_zup + --alignment "$RUN_DIR/alignment_plane.json" + --blender-bin "$BLENDER_BIN" + --blender-lib "$BLENDER_LIB" + ) + if [[ "$LOCK_STATIC_BOOL" != "1" ]]; then glb_args+=(--no-locked-static); fi + "$OPG_PY" "${glb_args[@]}" +} + +step14_export_physics_glb() { + echo "[Step 14] Export full-scene GLB physics (video-compatible)" + ensure_inputs_clean + resolve_run_dir + local cfg_effective + cfg_effective="$(get_effective_config)" + lock_static_poses "$RUN_DIR" + ensure_alignment + local step14_coord step14_camera_axis step14_world_conv step14_alignment + local step14_plane_args=() + step14_coord="blender_zup" + step14_camera_axis="standard" + step14_world_conv="identity" + step14_alignment="$RUN_DIR/alignment_plane.json" + step14_plane_args=(--plane-z zero) + if [[ "$STEP14_KEEP_WORLD_COORD_BOOL" == "1" ]]; then + echo "[Step 14] Keep original world coordinates for export; physics result is preserved via poses_physics.json." + step14_coord="raw" + step14_alignment="" + step14_plane_args=(--no-plane) + fi + local glb_args=( + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/export_scene_glb_with_deform.py + --run-dir "$RUN_DIR" + --config "$cfg_effective" + --motion-output-root "$OUT/motion324_outputs" + --motion-manifest "$OUT/motion324_outputs/$NAME/manifest.json" + --output "$RUN_DIR/scene_anim_blender_physics_with_deform.glb" + --coord "$step14_coord" + --blender-bin "$BLENDER_BIN" + --blender-lib "$BLENDER_LIB" + ) + if [[ -n "$step14_alignment" ]]; then + glb_args+=(--alignment "$step14_alignment") + fi + glb_args+=("${step14_plane_args[@]}") + if [[ "$PHYSICS_ENABLE_BOOL" == "1" ]]; then + glb_args+=(--pose-name poses_physics.json) + fi + if [[ "$LOCK_STATIC_BOOL" != "1" ]]; then glb_args+=(--no-locked-static); fi + "$OPG_PY" "${glb_args[@]}" + cp -f "$RUN_DIR/scene_anim_blender_physics_with_deform.glb" "$RUN_DIR/scene_anim_blender_physics_projected_contact_v3_yup.glb" + + if [[ "$STEP14_EXPORT_CAMERA_BOOL" == "1" ]]; then + local result_npz camera_json camera_npz + result_npz="$RUN_DIR/results/result.npz" + camera_json="$RUN_DIR/camera_step18_bundle.json" + camera_npz="$RUN_DIR/camera_step18_bundle.npz" + [[ -f "$result_npz" ]] || { echo "ERROR: result.npz not found: $result_npz" >&2; exit 1; } + echo "[Step 14] Export camera bundle matching current GLB coordinates" + local camera_args=( + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/export_step18_camera_bundle.py + --run-dir "$RUN_DIR" + --result-npz "$result_npz" + --coord "$step14_coord" + --camera-axis "$step14_camera_axis" + --world-conv "$step14_world_conv" + --fps 10 + --output-json "$camera_json" + --output-npz "$camera_npz" + ) + if [[ -n "$step14_alignment" ]]; then + camera_args+=(--alignment "$step14_alignment") + fi + "$OPG_PY" "${camera_args[@]}" + fi +} + +step15_generate_intrinsic_hdr_exr() { + echo "[Step 15] Generate intrinsic HDR EXR from input image" + + local input_image out_exr + input_image="$(scene_input_image_path)" + [[ -f "$input_image" ]] || { echo "ERROR: input image not found: $input_image" >&2; exit 1; } + [[ -f "$INTRHDR_RUNNER" ]] || { echo "ERROR: HDR runner not found: $INTRHDR_RUNNER" >&2; exit 1; } + [[ -f "$INTRHDR_REPO/inference.py" ]] || { echo "ERROR: IntrinsicHDR repo missing inference.py: $INTRHDR_REPO" >&2; exit 1; } + [[ -x "$HDR_PY" ]] || { echo "ERROR: HDR python not found: $HDR_PY" >&2; exit 1; } + + out_exr="$(default_step15_hdr_path)" + mkdir -p "$(dirname "$out_exr")" + bash "$INTRHDR_RUNNER" \ + --image "$input_image" \ + --output "$out_exr" \ + --project-dir "$INTRHDR_REPO" \ + --python "$HDR_PY" + state_set step15_hdr_exr "$out_exr" +} + +step16_rerun_failed_step6_objects() { + echo "[Step 16] Rerun failed step-6 objects" + ensure_inputs_clean + resolve_run_dir + local rerun_ref_map_effective="$RERUN_REF_MAP" + local rerun_ref_image_effective="$RERUN_REF_IMAGE" + + if [[ "$RERUN_USE_FLUX_REF" == "1" ]]; then + local flux_ref_pairs=() + local obj_name obj_ref_image + while IFS= read -r obj_name; do + [[ -z "$obj_name" ]] && continue + obj_ref_image="$(find_flux_ref_image "$RUN_DIR" "$obj_name" "$FLUX_MODE_CANONICAL")" + flux_ref_pairs+=("$obj_name" "$obj_ref_image") + done < <(parse_csv_items "$RERUN_OBJECTS") + local ref_map_json="$RUN_DIR/.step16_ref_map_flux.json" + "$OPG_PY" - "$ref_map_json" "${flux_ref_pairs[@]}" <<'PY' +import json +import sys +from pathlib import Path +out = Path(sys.argv[1]) +args = sys.argv[2:] +if len(args) % 2 != 0: + raise SystemExit("ERROR: invalid flux ref pairs") +payload = {} +for i in range(0, len(args), 2): + payload[args[i]] = {"ref_image": args[i + 1]} +out.write_text(json.dumps(payload, indent=2), encoding="utf-8") +PY + rerun_ref_map_effective="$ref_map_json" + rerun_ref_image_effective="" + fi + + if [[ -n "$rerun_ref_image_effective" ]]; then + local obj_name + obj_name="$(extract_single_csv_item "$RERUN_OBJECTS")" + local ref_map_json="$RUN_DIR/.step16_ref_map_${obj_name}.json" + "$OPG_PY" - "$ref_map_json" "$obj_name" "$rerun_ref_image_effective" <<'PY' +import json +import sys +from pathlib import Path +out = Path(sys.argv[1]) +out.write_text(json.dumps({sys.argv[2]: {"ref_image": sys.argv[3]}}, indent=2), encoding="utf-8") +PY + rerun_ref_map_effective="$ref_map_json" + fi + + local rerun_args=( + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/rerun_step6_objects.py + --run-dir "$RUN_DIR" + --config "$CFG_MAIN" + --output-effective-config "$CFG_EFFECTIVE" + ) + if [[ "$RERUN_ANCHOR_FRAME_INT" -ge 0 ]]; then rerun_args+=(--anchor-frame "$RERUN_ANCHOR_FRAME_INT"); fi + if [[ -n "$rerun_ref_map_effective" ]]; then rerun_args+=(--ref-map "$rerun_ref_map_effective"); fi + if [[ -n "$RERUN_OBJECTS" ]]; then + rerun_args+=(--objects "$RERUN_OBJECTS" --only-failed 0) + else + rerun_args+=(--only-failed "$RERUN_ONLY_FAILED_BOOL") + fi + "$OPG_PY" "${rerun_args[@]}" + if [[ -f "$CFG_EFFECTIVE" ]]; then state_set effective_config "$CFG_EFFECTIVE"; fi + lock_static_poses "$RUN_DIR" +} + +step17_render_white_split_image() { + echo "[Step 17] Render white-model split image" + ensure_inputs_clean + resolve_run_dir + lock_static_poses "$RUN_DIR" + local cfg_effective result_npz mesh_dir rgba_dir camview_png split_png alias_png first_png + cfg_effective="$(get_effective_config)" + result_npz="$RUN_DIR/results/result.npz" + if [[ ! -f "$result_npz" ]]; then + echo "ERROR: missing $result_npz" >&2 + local saved_run_dir + saved_run_dir="$(state_get run_dir)" + if [[ -n "$saved_run_dir" && "$saved_run_dir" != "$RUN_DIR" ]]; then + echo "Hint: state file run_dir is $saved_run_dir ; the current --run-dir may be wrong." >&2 + fi + exit 1 + fi + [[ -x "$BLENDER_BIN" ]] || { echo "ERROR: Blender not found: $BLENDER_BIN" >&2; exit 1; } + ensure_alignment + mesh_dir="$RUN_DIR/scene_mesh_frames_all_world_deform_noalign" + rgba_dir="$RUN_DIR/fullscene_deform_objseq_white_clay_camview_rgba" + camview_png="$RUN_DIR/fullscene_deform_objseq_white_clay_camview.png" + split_png="$RUN_DIR/fullscene_deform_objseq_white_left_rgb_right_split10_h264.png" + alias_png="$RUN_DIR/fullscene_deform_objseq_white_clay_split10_h264.png" + + local mesh_export_args=( + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/export_scene_mesh_frames.py + --run-dir "$RUN_DIR" + --config "$cfg_effective" + --output-dir "$mesh_dir" + --max-frames 1 + ) + if [[ "$LOCK_STATIC_BOOL" == "1" ]]; then mesh_export_args+=(--use-locked-static); fi + "$OPG_PY" "${mesh_export_args[@]}" + + rm -rf "$rgba_dir" + LD_LIBRARY_PATH="$BLENDER_LIB:${LD_LIBRARY_PATH:-}" "$BLENDER_BIN" -b \ + -P /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/blender_render_obj_sequence_with_video_camera.py -- \ + --mesh-dir "$mesh_dir" \ + --result-npz "$result_npz" \ + --output-video "$RUN_DIR/.unused_step17.mp4" \ + --output-rgba-dir "$rgba_dir" \ + --alignment "$RUN_DIR/alignment_plane.json" \ + --coord blender_zup \ + --camera-axis standard \ + --world-conv identity \ + --white-clay \ + --bg-gray 0.35 \ + --world-strength 1.0 \ + --sun-energy 2.5 \ + --camera-headlight \ + --camera-headlight-type sun \ + --camera-headlight-energy 8 \ + --fps 10 \ + --max-frames 1 + first_png="$(find_first_png "$rgba_dir")" + [[ -n "$first_png" && -f "$first_png" ]] || { echo "ERROR: no rendered PNG found in $rgba_dir" >&2; exit 1; } + "$OPG_PY" "$COMPOSE_IMAGE_SCRIPT" --left "$first_png" --right "$RUN_DIR/rgb/000000.jpg" --left-output "$camview_png" --output "$split_png" + cp -f "$split_png" "$alias_png" +} + +step18_render_textured_split_image() { + echo "[Step 18] Render textured split image" + ensure_inputs_clean + resolve_run_dir + lock_static_poses "$RUN_DIR" + local cfg_effective result_npz rgba_dir camview_png split_png alias_png compat_camview_png compat_split_png compat_alias_png first_png hdr_path + cfg_effective="$(get_effective_config)" + result_npz="$RUN_DIR/results/result.npz" + if [[ ! -f "$result_npz" ]]; then + echo "ERROR: missing $result_npz" >&2 + local saved_run_dir + saved_run_dir="$(state_get run_dir)" + if [[ -n "$saved_run_dir" && "$saved_run_dir" != "$RUN_DIR" ]]; then + echo "Hint: state file run_dir is $saved_run_dir ; the current --run-dir may be wrong." >&2 + fi + exit 1 + fi + [[ -x "$BLENDER_BIN" ]] || { echo "ERROR: Blender not found: $BLENDER_BIN" >&2; exit 1; } + ensure_alignment + hdr_path="$(resolve_step18_hdr_path)" + rgba_dir="$RUN_DIR/fullscene_deform_objseq_textured_camview_rgba" + camview_png="$RUN_DIR/fullscene_deform_objseq_textured_camview.png" + split_png="$RUN_DIR/fullscene_deform_objseq_textured_left_rgb_right_split10_h264.png" + alias_png="$RUN_DIR/fullscene_deform_objseq_textured_split10_h264.png" + compat_camview_png="$RUN_DIR/fullscene_deform_textured_camview.png" + compat_split_png="$RUN_DIR/fullscene_deform_textured_left_rgb_right_split10_h264.png" + compat_alias_png="$RUN_DIR/fullscene_deform_textured_split10_h264.png" + + rm -rf "$rgba_dir" + local render_args=( + --run-dir "$RUN_DIR" + --config "$cfg_effective" + --result-npz "$result_npz" + --output-video "$RUN_DIR/.unused_step18.mp4" + --output-rgba-dir "$rgba_dir" + --alignment "$RUN_DIR/alignment_plane.json" + --coord blender_zup + --camera-axis standard + --world-conv identity + --bg-gray 1.0 + --world-strength 1.0 + --sun-energy 2.5 + --camera-headlight + --camera-headlight-type sun + --camera-headlight-energy 8 + --dark-texture-fallback-ref + --dark-texture-thresh 40 + --dark-texture-target-p99 110 + --dark-texture-max-gain 8 + --fps 10 + --max-frames 1 + ) + if [[ "$PHYSICS_ENABLE_BOOL" == "1" ]]; then + render_args+=(--pose-name poses_physics.json --add-plane --plane-scale 1.35 --plane-gray 0.72) + fi + if [[ "$LOCK_STATIC_BOOL" == "1" ]]; then render_args+=(--use-locked-static); fi + if [[ -n "$hdr_path" ]]; then render_args+=(--hdr "$hdr_path"); fi + if [[ "$STEP18_UNLIT_TEXTURE_BOOL" == "1" ]]; then render_args+=(--unlit-texture --unlit-emission-strength 1.0); fi + LD_LIBRARY_PATH="$BLENDER_LIB:${LD_LIBRARY_PATH:-}" "$BLENDER_BIN" -b \ + -P /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/blender_render_scene_textured_with_video_camera.py -- \ + "${render_args[@]}" + first_png="$(find_first_png "$rgba_dir")" + [[ -n "$first_png" && -f "$first_png" ]] || { echo "ERROR: no rendered PNG found in $rgba_dir" >&2; exit 1; } + "$OPG_PY" "$COMPOSE_IMAGE_SCRIPT" --left "$first_png" --right "$RUN_DIR/rgb/000000.jpg" --left-output "$camview_png" --output "$split_png" + cp -f "$split_png" "$alias_png" + cp -f "$camview_png" "$compat_camview_png" + cp -f "$split_png" "$compat_split_png" + cp -f "$split_png" "$compat_alias_png" +} + +step19_flux2_single_ref_edit() { + echo "[Step 19] FLUX.2 single-reference edit" + ensure_inputs_clean + resolve_run_dir + [[ -n "$FLUX_OBJ_NAME" ]] || { echo "ERROR: --flux-obj-name is required for step 19." >&2; exit 1; } + [[ -x "$FLUX_PY" ]] || { echo "ERROR: flux python not found: $FLUX_PY" >&2; exit 1; } + [[ -f "$FLUX_STEP19_SCRIPT" ]] || { echo "ERROR: missing step-19 helper script: $FLUX_STEP19_SCRIPT" >&2; exit 1; } + [[ -d "$FLUX2_REPO" ]] || { echo "ERROR: flux2 repo not found: $FLUX2_REPO" >&2; exit 1; } + local model_path="${KLEIN_9B_MODEL_PATH:-$FLUX_KLEIN_9B_MODEL_PATH}" + local ae_path="${AE_MODEL_PATH:-$FLUX_AE_MODEL_PATH}" + local qwen_model_path="${QWEN3_8B_MODEL_PATH:-$FLUX_QWEN3_8B_MODEL_PATH}" + local qwen_tokenizer_path="${QWEN3_8B_TOKENIZER_PATH:-$FLUX_QWEN3_8B_TOKENIZER_PATH}" + local py_path="$FLUX2_REPO/src" + + [[ -f "$model_path" ]] || { echo "ERROR: missing FLUX model file: $model_path" >&2; exit 1; } + [[ -f "$ae_path" ]] || { echo "ERROR: missing AE model file: $ae_path" >&2; exit 1; } + [[ -d "$qwen_model_path" ]] || { echo "ERROR: missing Qwen text encoder dir: $qwen_model_path" >&2; exit 1; } + [[ -d "$qwen_tokenizer_path" ]] || { echo "ERROR: missing Qwen tokenizer dir: $qwen_tokenizer_path" >&2; exit 1; } + + local succeeded=() + local failed=() + local out_roots=() + local obj_name + while IFS= read -r obj_name; do + [[ -z "$obj_name" ]] && continue + local cmd=( + "$OPG_PY" "$FLUX_STEP19_SCRIPT" + --run-dir "$RUN_DIR" + --obj-name "$obj_name" + --mode "$FLUX_MODE_CANONICAL" + --flux-python "$FLUX_PY" + --flux-repo "$FLUX2_REPO" + --model-name flux.2-klein-9b + --seed "$FLUX_SEED" + --out-width "$FLUX_OUT_WIDTH_INT" + --out-height "$FLUX_OUT_HEIGHT_INT" + --match-image-size "$FLUX_MATCH_IMAGE_SIZE_CANONICAL" + --use-rgb-crop-ref "$FLUX_USE_RGB_CROP_REF_BOOL" + --overwrite-mode-output 1 + ) + if [[ -n "$FLUX_PROMPT_AMODAL" ]]; then cmd+=(--prompt-amodal "$FLUX_PROMPT_AMODAL"); fi + if [[ -n "$FLUX_PROMPT_VIEW" ]]; then cmd+=(--prompt-view "$FLUX_PROMPT_VIEW"); fi + + echo "[Step 19] object: $obj_name" + if [[ -n "$FLUX_GPU" ]]; then + if ! CUDA_VISIBLE_DEVICES="$FLUX_GPU" \ + PYTHONPATH="$py_path:${PYTHONPATH:-}" \ + KLEIN_9B_MODEL_PATH="$model_path" \ + AE_MODEL_PATH="$ae_path" \ + QWEN3_8B_MODEL_PATH="$qwen_model_path" \ + QWEN3_8B_TOKENIZER_PATH="$qwen_tokenizer_path" \ + FLUX2_ENABLE_AUX_MODEL=0 \ + "${cmd[@]}"; then + failed+=("$obj_name") + continue + fi + else + if ! PYTHONPATH="$py_path:${PYTHONPATH:-}" \ + KLEIN_9B_MODEL_PATH="$model_path" \ + AE_MODEL_PATH="$ae_path" \ + QWEN3_8B_MODEL_PATH="$qwen_model_path" \ + QWEN3_8B_TOKENIZER_PATH="$qwen_tokenizer_path" \ + FLUX2_ENABLE_AUX_MODEL=0 \ + "${cmd[@]}"; then + failed+=("$obj_name") + continue + fi + fi + + succeeded+=("$obj_name") + local out_root="$RUN_DIR/objects/fluxoutput/$obj_name/$FLUX_MODE_CANONICAL" + out_roots+=("$out_root") + echo "[OK] Step 19 output root [$obj_name]: $out_root" + done < <(parse_csv_items "$FLUX_OBJ_NAME") + + if [[ "${#failed[@]}" -gt 0 ]]; then + echo "ERROR: step 19 failed objects: $(IFS=,; echo "${failed[*]}")" >&2 + exit 1 + fi + + local step19_out_root="$RUN_DIR/objects/fluxoutput" + if [[ "${#out_roots[@]}" -eq 1 ]]; then + step19_out_root="${out_roots[0]}" + fi + state_set step19_flux_obj "$FLUX_OBJ_NAME" + state_set step19_flux_mode "$FLUX_MODE_CANONICAL" + state_set step19_flux_output_root "$step19_out_root" + if [[ "${#out_roots[@]}" -gt 0 ]]; then + state_set step19_flux_output_roots "$(IFS=,; echo "${out_roots[*]}")" + fi + echo "[OK] Step 19 completed objects: $(IFS=,; echo "${succeeded[*]}")" + echo "[OK] Step 19 output root: $step19_out_root" +} + +run_requested_step() { + local step="$1" + mark_step_started "$step" + case "$step" in + 1) step1_labels ;; + 2) step2_masks ;; + 6) step6_reconstruct_rigid ;; + 7) step7_plane_and_rigid_physics ;; + 13) step13_export_prephysics_glb ;; + 14) step14_export_physics_glb ;; + 15) step15_generate_intrinsic_hdr_exr ;; + 16) step16_rerun_failed_step6_objects ;; + 17) step17_render_white_split_image ;; + 18) step18_render_textured_split_image ;; + 19) step19_flux2_single_ref_edit ;; + *) echo "ERROR: unsupported step in single-image pipeline: $step" >&2; exit 1 ;; + esac + mark_step_finished "$step" +} + +for step in "${STEPS[@]}"; do + run_requested_step "$step" +done diff --git a/OVOW/engine/run_steps_scene_image_pipeline_batch.sh b/OVOW/engine/run_steps_scene_image_pipeline_batch.sh new file mode 100644 index 0000000000000000000000000000000000000000..5ed2b9ce107d68ce0437c598e62035a2b58295c0 --- /dev/null +++ b/OVOW/engine/run_steps_scene_image_pipeline_batch.sh @@ -0,0 +1,907 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +PIPELINE_SCRIPT="${SCRIPT_DIR}/run_steps_scene_image_pipeline.sh" +SCENE_ROOT="" +OUT_ROOT="" +RUN_DIR_ROOT="" +STEPS_RAW="" + +BATCH_STOP_ON_FAIL=0 +DRY_RUN=0 + +GPU_MODE="inherit" +GPU_VALUE="" + +GPU_LIST_RAW="" +MAX_PER_GPU=1 + +PIPELINE_EXTRA_ARGS=() +STEPS=() +CMD=() + +usage() { + cat <<'USAGE' +Usage: + bash run_steps_scene_image_pipeline_batch.sh [batch-options] [step ...] [-- pipeline-options...] + +Required: + --scene-dir DIR Root directory that contains images or per-image scene dirs + +Batch options: + --steps "LIST" Steps to run, e.g. "1 2 6 7 14 17 18" or "17,18" + --out DIR Pass --out DIR/ to each per-image pipeline run + --run-dir-root DIR Pass --run-dir DIR/ to each pipeline run + --batch-stop-on-fail 0|1 Stop launching new images after first failed image (default: 0) + --dry-run Print planned commands without executing + -h, --help Show this help + +GPU options (choose one mode): + --gpu ID|none Legacy single-gpu mode for all images + --gpus LIST Multi-gpu mode, e.g. "0,1,2,3,4,5,6" + --max-per-gpu N Max concurrent images per GPU in multi-gpu mode (default: 1) + +Pipeline options: + Put extra options after '--'. They are forwarded to run_steps_scene_image_pipeline.sh. + Example: + bash run_steps_scene_image_pipeline_batch.sh \ + --scene-dir /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/data_demo_img \ + --gpus "0,1,2,3,4,5,6" \ + --steps "17 18" \ + -- --lock-static-mode off + +Notes: + - If --scene-dir directly contains image files, this batch script creates one child + scene dir per image, matching the single-image pipeline's built-in behavior. + - In multi-gpu mode, the default --max-per-gpu 1 means "one image per GPU". +USAGE +} + +is_int() { + [[ "${1:-}" =~ ^-?[0-9]+$ ]] +} + +is_bool01() { + [[ "${1:-}" == "0" || "${1:-}" == "1" ]] +} + +parse_steps() { + local raw="$1" + raw="${raw//,/ }" + read -r -a STEPS <<<"$raw" + if [[ "${#STEPS[@]}" -eq 0 ]]; then + echo "ERROR: no valid steps were provided." >&2 + exit 1 + fi +} + +parse_gpu_list() { + local raw="$1" + local cleaned + cleaned="${raw//,/ }" + read -r -a GPU_IDS <<<"$cleaned" + if [[ "${#GPU_IDS[@]}" -eq 0 ]]; then + echo "ERROR: --gpus is empty." >&2 + exit 1 + fi + + declare -A seen=() + local g + for g in "${GPU_IDS[@]}"; do + if ! is_int "$g" || [[ "$g" -lt 0 ]]; then + echo "ERROR: invalid gpu id in --gpus: '$g'." >&2 + exit 1 + fi + if [[ -n "${seen[$g]:-}" ]]; then + echo "ERROR: duplicate gpu id in --gpus: '$g'." >&2 + exit 1 + fi + seen[$g]=1 + done +} + +discover_image_scenes() { + local raw_dir="$1" + python3 - "$raw_dir" <<'PY' +from pathlib import Path +import json +import re +import shutil +import sys + +root = Path(sys.argv[1]).expanduser().resolve() +exts = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG", ".webp", ".WEBP"} + +if not root.is_dir(): + raise SystemExit(f"ERROR: scene dir not found: {root}") + +def has_scene_markers(path: Path) -> bool: + return ( + (path / "scene.json").exists() + or (path / "masks").exists() + or (path / "mask_summary.json").exists() + ) + +def child_images(path: Path): + return sorted(p for p in path.iterdir() if p.is_file() and p.suffix in exts) + +def sanitize(name: str) -> str: + s = name.strip().lower() + s = re.sub(r"\s+", "_", s) + s = re.sub(r"[^a-z0-9_\-]+", "_", s) + s = re.sub(r"_+", "_", s).strip("_") + return s or "image" + +image_files = child_images(root) + +if has_scene_markers(root): + print("passthrough") + print(str(root)) + raise SystemExit(0) + +if len(image_files) == 1: + print("passthrough") + print(str(root)) + raise SystemExit(0) + +if not image_files: + child_scene_dirs = [] + for child in sorted(p for p in root.iterdir() if p.is_dir()): + if has_scene_markers(child) or len(child_images(child)) == 1: + child_scene_dirs.append(str(child.resolve())) + if child_scene_dirs: + print("children") + for scene_dir in child_scene_dirs: + print(scene_dir) + raise SystemExit(0) + raise SystemExit(f"ERROR: no image scenes found under: {root}") + +used = set() +scene_dirs = [] +for image_path in image_files: + base = sanitize(image_path.stem) + if base in used: + base = sanitize(f"{image_path.stem}_{image_path.suffix.lstrip('.').lower()}") + idx = 2 + candidate = base + while candidate in used: + candidate = f"{base}_{idx}" + idx += 1 + used.add(candidate) + + scene_dir = root / candidate + scene_dir.mkdir(parents=True, exist_ok=True) + target_image = scene_dir / image_path.name + if not target_image.exists(): + try: + target_image.hardlink_to(image_path) + except Exception: + shutil.copy2(str(image_path), str(target_image)) + scene_dirs.append(scene_dir) + +print("materialized") +for scene_dir in scene_dirs: + print(str(scene_dir.resolve())) +PY +} + +scene_name_for_dir() { + local scene_dir="$1" + python3 - "$scene_dir" <<'PY' +from pathlib import Path +import json +import sys + +scene_dir = Path(sys.argv[1]).expanduser().resolve() +scene_json = scene_dir / "scene.json" +image_path = None + +if scene_json.exists(): + try: + payload = json.loads(scene_json.read_text(encoding="utf-8")) + except Exception: + payload = {} + image_name = str(payload.get("image") or "").strip() + if image_name: + cand = (scene_dir / image_name).resolve() + if cand.is_file(): + image_path = cand + +if image_path is None: + exts = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG", ".webp", ".WEBP"} + images = sorted(p for p in scene_dir.iterdir() if p.is_file() and p.suffix in exts) + if images: + image_path = images[0].resolve() + +print(image_path.stem if image_path is not None else scene_dir.name) +PY +} + +slugify_token() { + printf '%s' "$1" | tr '[:space:]' '_' | tr -cs '[:alnum:]_.-' '_' +} + +build_scene_cmd() { + local scene_dir="$1" + local scene_name="$2" + CMD=( + bash "$PIPELINE_SCRIPT" + --scene-dir "$scene_dir" + --name "$scene_name" + ) + if [[ -n "$OUT_ROOT" ]]; then + CMD+=(--out "${OUT_ROOT}/${scene_name}") + fi + if [[ -n "$RUN_DIR_ROOT" ]]; then + CMD+=(--run-dir "${RUN_DIR_ROOT}/${scene_name}") + fi + if [[ "${#PIPELINE_EXTRA_ARGS[@]}" -gt 0 ]]; then + CMD+=("${PIPELINE_EXTRA_ARGS[@]}") + fi + CMD+=("${STEPS[@]}") +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --scene-dir) + SCENE_ROOT="$2" + shift 2 + ;; + --steps) + STEPS_RAW="$2" + shift 2 + ;; + --out) + OUT_ROOT="$2" + shift 2 + ;; + --run-dir-root) + RUN_DIR_ROOT="$2" + shift 2 + ;; + --batch-stop-on-fail) + BATCH_STOP_ON_FAIL="$2" + shift 2 + ;; + --gpu) + if [[ "$2" == "none" ]]; then + GPU_MODE="none" + GPU_VALUE="" + else + GPU_MODE="set" + GPU_VALUE="$2" + fi + shift 2 + ;; + --gpus|--gpu-list) + GPU_LIST_RAW="$2" + shift 2 + ;; + --max-per-gpu) + MAX_PER_GPU="$2" + shift 2 + ;; + --dry-run) + DRY_RUN=1 + shift + ;; + -h|--help) + usage + exit 0 + ;; + --) + shift + PIPELINE_EXTRA_ARGS=("$@") + break + ;; + --*) + echo "ERROR: unknown option '$1'" >&2 + usage + exit 1 + ;; + *) + STEPS+=("$1") + shift + ;; + esac +done + +if [[ ! -f "$PIPELINE_SCRIPT" ]]; then + echo "ERROR: pipeline script not found: $PIPELINE_SCRIPT" >&2 + exit 1 +fi + +if [[ -z "$SCENE_ROOT" ]]; then + echo "ERROR: --scene-dir is required." >&2 + usage + exit 1 +fi + +if [[ "${#STEPS[@]}" -eq 0 ]]; then + parse_steps "$STEPS_RAW" +fi + +if ! is_bool01 "$BATCH_STOP_ON_FAIL"; then + echo "ERROR: --batch-stop-on-fail must be 0 or 1." >&2 + exit 1 +fi + +MULTI_GPU_MODE=0 +GPU_IDS=() +if [[ -n "$GPU_LIST_RAW" ]]; then + parse_gpu_list "$GPU_LIST_RAW" + MULTI_GPU_MODE=1 +fi + +if ! is_int "$MAX_PER_GPU" || [[ "$MAX_PER_GPU" -le 0 ]]; then + echo "ERROR: --max-per-gpu must be an integer > 0." >&2 + exit 1 +fi + +if [[ "$GPU_MODE" == "set" && ( ! "$GPU_VALUE" =~ ^[0-9]+$ ) ]]; then + echo "ERROR: --gpu must be a non-negative integer or 'none'." >&2 + exit 1 +fi + +if [[ "$MULTI_GPU_MODE" == "1" && "$GPU_MODE" != "inherit" ]]; then + echo "[Warn] Both --gpus and --gpu were set. Ignoring --gpu and using --gpus scheduler." +fi + +mapfile -t DISCOVERY_LINES < <(discover_image_scenes "$SCENE_ROOT") +if [[ "${#DISCOVERY_LINES[@]}" -lt 2 ]]; then + echo "ERROR: failed to discover any image scenes under: $SCENE_ROOT" >&2 + exit 1 +fi + +DISCOVERY_MODE="${DISCOVERY_LINES[0]}" +SCENE_DIRS=("${DISCOVERY_LINES[@]:1}") + +SCENE_NAMES=() +SCENE_TAGS=() +declare -A NAME_COUNTS=() +for idx in "${!SCENE_DIRS[@]}"; do + scene_dir="${SCENE_DIRS[$idx]}" + base_name="$(scene_name_for_dir "$scene_dir")" + count=$(( ${NAME_COUNTS[$base_name]:-0} + 1 )) + NAME_COUNTS[$base_name]=$count + if (( count > 1 )); then + scene_name="${base_name}_${count}" + else + scene_name="$base_name" + fi + SCENE_NAMES+=("$scene_name") + SCENE_TAGS+=("img$(printf '%03d' $((idx + 1)))") +done + +TIMESTAMP="$(date +%Y%m%d_%H%M%S)" +LOG_DIR="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs/batch_logs_image_${TIMESTAMP}" +mkdir -p "$LOG_DIR" + +declare -a OK_SCENES=() +declare -a FAILED_SCENES=() +declare -a SKIPPED_SCENES=() +declare -a RUNNING_PIDS=() +declare -A GPU_RUNNING=() +declare -A GPU_LAUNCHED=() +declare -A PID_TO_GPU=() +declare -A PID_TO_TAG=() +declare -A PID_TO_NAME=() +declare -A PID_TO_LOG=() +PROGRESS_INTERVAL=15 +LAST_PROGRESS_TS=0 +STOP_LAUNCH=0 + +echo "[Batch] scene root: ${SCENE_ROOT}" +echo "[Batch] discovered images: ${#SCENE_DIRS[@]}" +echo "[Batch] discovery mode: ${DISCOVERY_MODE}" +echo "[Batch] steps: ${STEPS[*]}" +echo "[Batch] log dir: ${LOG_DIR}" +if [[ -n "$OUT_ROOT" ]]; then + echo "[Batch] out root: ${OUT_ROOT}" +fi +if [[ -n "$RUN_DIR_ROOT" ]]; then + echo "[Batch] run-dir root: ${RUN_DIR_ROOT}" +fi +if [[ "$MULTI_GPU_MODE" == "1" ]]; then + echo "[Batch] mode: multi-gpu scheduler" + echo "[Batch] gpus: ${GPU_IDS[*]}" + echo "[Batch] max-per-gpu: ${MAX_PER_GPU}" +else + echo "[Batch] mode: single-gpu/sequential" + if [[ "$GPU_MODE" == "set" ]]; then + echo "[Batch] CUDA_VISIBLE_DEVICES=${GPU_VALUE}" + elif [[ "$GPU_MODE" == "none" ]]; then + echo "[Batch] CUDA_VISIBLE_DEVICES will be unset" + fi +fi +if [[ "${#PIPELINE_EXTRA_ARGS[@]}" -gt 0 ]]; then + echo "[Batch] forwarded pipeline args: ${PIPELINE_EXTRA_ARGS[*]}" +fi + +scene_output_root() { + local scene_dir="$1" + local scene_name="$2" + if [[ -n "$OUT_ROOT" ]]; then + printf '%s\n' "${OUT_ROOT}/${scene_name}" + else + printf '%s\n' "$scene_dir" + fi +} + +scene_state_json_path() { + local scene_dir="$1" + local scene_name="$2" + local out_dir + out_dir="$(scene_output_root "$scene_dir" "$scene_name")" + printf '%s\n' "${out_dir}/metadata/${scene_name}_image_step_state.json" +} + +progress_line_for_scene() { + local scene_tag="$1" + local scene_name="$2" + local scene_dir="$3" + local gpu="$4" + local pid="$5" + local log_file="$6" + local state_json + state_json="$(scene_state_json_path "$scene_dir" "$scene_name")" + python3 - "$state_json" "$log_file" "$scene_tag" "$scene_name" "$gpu" "$pid" <<'PY' +from pathlib import Path +import json +import re +import sys + +state_path = Path(sys.argv[1]) +log_path = Path(sys.argv[2]) +scene_tag, scene_name, gpu, pid = sys.argv[3:7] + +status = "starting" +step = "" +step_status = "" +run_dir = "" + +if state_path.exists(): + try: + data = json.loads(state_path.read_text(encoding="utf-8")) + except Exception: + data = {} + status = str(data.get("pipeline_status") or status) + cur = str(data.get("current_step") or "").strip() + cur_name = str(data.get("current_step_name") or "").strip() + step_status = str(data.get("current_step_status") or "").strip() + if cur or cur_name: + step = " ".join(x for x in (cur, cur_name) if x).strip() + else: + last = str(data.get("last_completed_step") or "").strip() + last_name = str(data.get("last_completed_step_name") or "").strip() + if last or last_name: + step = "done " + " ".join(x for x in (last, last_name) if x).strip() + run_dir = str(data.get("run_dir") or "").strip() + +if not step and log_path.exists(): + try: + lines = log_path.read_text(encoding="utf-8", errors="ignore").splitlines() + except Exception: + lines = [] + for line in reversed(lines[-200:]): + m = re.match(r"^\[Step\s+([0-9]+)\]\s*(.*)$", line.strip()) + if m: + extra = m.group(2).strip() + step = m.group(1) + (f" {extra}" if extra else "") + break + +parts = [ + f"[{scene_tag}]", + f"pid={pid}", + f"gpu={gpu or '-'}", + f"name={scene_name}", + f"status={status}", +] +if step: + parts.append(f"step={step}") +if step_status: + parts.append(f"step_status={step_status}") +if run_dir: + parts.append(f"run_dir={run_dir}") +print(" ".join(parts)) +PY +} + +build_progress_bar() { + local filled="$1" + local total="$2" + local width="${3:-28}" + local n_fill=0 + local n_empty + local i + if (( total > 0 )); then + n_fill=$(( filled * width / total )) + fi + if (( n_fill < 0 )); then n_fill=0; fi + if (( n_fill > width )); then n_fill=$width; fi + n_empty=$((width - n_fill)) + printf '[' + for ((i=0; i"$snapshot_file" +} + +print_progress_line() { + local total="${#SCENE_DIRS[@]}" + local ok_count="${#OK_SCENES[@]}" + local failed_count="${#FAILED_SCENES[@]}" + local skipped_count="${#SKIPPED_SCENES[@]}" + local running_count="${#RUNNING_PIDS[@]}" + local accounted queued percent + accounted=$((ok_count + failed_count + skipped_count + running_count)) + queued=$((total - accounted)) + if (( queued < 0 )); then + queued=0 + fi + if (( total > 0 )); then + percent=$((accounted * 100 / total)) + else + percent=100 + fi + echo "[Batch] $(build_progress_bar "$accounted" "$total") ${percent}% accounted=${accounted}/${total} ok=${ok_count} fail=${failed_count} running=${running_count} queued=${queued} skipped=${skipped_count}" +} + +show_progress_update() { + write_progress_snapshot + print_progress_line + LAST_PROGRESS_TS="$(date +%s)" +} + +maybe_write_progress_snapshot() { + local now + now="$(date +%s)" + if (( LAST_PROGRESS_TS == 0 || now - LAST_PROGRESS_TS >= PROGRESS_INTERVAL )); then + show_progress_update + LAST_PROGRESS_TS="$now" + fi +} + +kill_pid_group() { + local signal="$1" + local pid="$2" + local pgid + pgid="$(ps -o pgid= -p "$pid" 2>/dev/null | tr -d '[:space:]')" + if [[ -n "$pgid" ]]; then + kill "-${signal}" "-${pgid}" 2>/dev/null || true + fi + kill "-${signal}" "$pid" 2>/dev/null || true +} + +cleanup_running_jobs() { + local signal="$1" + local pid + for pid in "${RUNNING_PIDS[@]}"; do + kill_pid_group "$signal" "$pid" + done +} + +on_batch_signal() { + local sig="$1" + STOP_LAUNCH=1 + echo + echo "[Batch] Caught ${sig}; stopping running image jobs..." + show_progress_update + cleanup_running_jobs TERM + sleep 2 + cleanup_running_jobs KILL + exit 130 +} + +trap 'on_batch_signal INT' INT +trap 'on_batch_signal TERM' TERM + +run_scene_sync() { + local scene_tag="$1" + local scene_name="$2" + local scene_dir="$3" + local log_file="$4" + local gpu="$5" + + build_scene_cmd "$scene_dir" "$scene_name" + { + if [[ -n "$gpu" ]]; then + printf '[%s] name=%s gpu=%s scene_dir=%s command:' "$scene_tag" "$scene_name" "$gpu" "$scene_dir" + else + printf '[%s] name=%s scene_dir=%s command:' "$scene_tag" "$scene_name" "$scene_dir" + fi + printf ' %q' "${CMD[@]}" + printf '\n' + } | tee "$log_file" + + if [[ "$DRY_RUN" == "1" ]]; then + echo "[${scene_tag}] dry-run only" | tee -a "$log_file" + OK_SCENES+=("$scene_tag:$scene_name") + show_progress_update + return 0 + fi + + local rc + set +e + if [[ -n "$gpu" ]]; then + CUDA_VISIBLE_DEVICES="$gpu" "${CMD[@]}" >>"$log_file" 2>&1 + rc=$? + elif [[ "$GPU_MODE" == "set" ]]; then + CUDA_VISIBLE_DEVICES="$GPU_VALUE" "${CMD[@]}" >>"$log_file" 2>&1 + rc=$? + elif [[ "$GPU_MODE" == "none" ]]; then + env -u CUDA_VISIBLE_DEVICES "${CMD[@]}" >>"$log_file" 2>&1 + rc=$? + else + "${CMD[@]}" >>"$log_file" 2>&1 + rc=$? + fi + set -e + + if [[ "$rc" -eq 0 ]]; then + if [[ -n "$gpu" ]]; then + echo "[${scene_tag}] OK (name=${scene_name}, gpu=${gpu})" + else + echo "[${scene_tag}] OK (name=${scene_name})" + fi + OK_SCENES+=("$scene_tag:$scene_name") + show_progress_update + return 0 + fi + + if [[ -n "$gpu" ]]; then + echo "[${scene_tag}] FAIL rc=${rc} (name=${scene_name}, gpu=${gpu}, log: ${log_file})" + else + echo "[${scene_tag}] FAIL rc=${rc} (name=${scene_name}, log: ${log_file})" + fi + FAILED_SCENES+=("$scene_tag:$scene_name") + show_progress_update + return 1 +} + +if [[ "$MULTI_GPU_MODE" == "0" ]]; then + for i in "${!SCENE_DIRS[@]}"; do + scene_tag="${SCENE_TAGS[$i]}" + scene_name="${SCENE_NAMES[$i]}" + scene_dir="${SCENE_DIRS[$i]}" + log_file="${LOG_DIR}/${scene_tag}_$(slugify_token "$scene_name").log" + + echo + echo "==== [${scene_tag}] start ====" + echo "[${scene_tag}] scene dir: ${scene_dir}" + echo "[${scene_tag}] name: ${scene_name}" + + if ! run_scene_sync "$scene_tag" "$scene_name" "$scene_dir" "$log_file" ""; then + if [[ "$BATCH_STOP_ON_FAIL" == "1" ]]; then + for ((j=i+1; j<${#SCENE_DIRS[@]}; j++)); do + SKIPPED_SCENES+=("${SCENE_TAGS[$j]}:${SCENE_NAMES[$j]}") + done + echo "[Batch] stop on first failure." + break + fi + fi + done +else + for g in "${GPU_IDS[@]}"; do + GPU_RUNNING[$g]=0 + GPU_LAUNCHED[$g]=0 + done + + GPU_RR_INDEX=0 + NEXT_SCENE_INDEX=0 + + pick_next_gpu() { + local n="${#GPU_IDS[@]}" + local best_gpu="" + local best_idx=-1 + local best_launch=0 + local k idx g run launched + for ((k=0; k= MAX_PER_GPU )); then + continue + fi + launched="${GPU_LAUNCHED[$g]}" + if [[ -z "$best_gpu" ]] || (( launched < best_launch )); then + best_gpu="$g" + best_idx="$idx" + best_launch="$launched" + fi + done + if [[ -z "$best_gpu" ]]; then + return 1 + fi + GPU_RR_INDEX=$(( (best_idx + 1) % n )) + printf '%s\n' "$best_gpu" + return 0 + } + + launch_scene_async() { + local scene_index="$1" + local gpu="$2" + local scene_tag="${SCENE_TAGS[$scene_index]}" + local scene_name="${SCENE_NAMES[$scene_index]}" + local scene_dir="${SCENE_DIRS[$scene_index]}" + local log_file="${LOG_DIR}/${scene_tag}_$(slugify_token "$scene_name").log" + + build_scene_cmd "$scene_dir" "$scene_name" + { + printf '[%s] name=%s gpu=%s scene_dir=%s command:' "$scene_tag" "$scene_name" "$gpu" "$scene_dir" + printf ' %q' "${CMD[@]}" + printf '\n' + } | tee "$log_file" + + CUDA_VISIBLE_DEVICES="$gpu" "${CMD[@]}" >>"$log_file" 2>&1 & + local pid=$! + RUNNING_PIDS+=("$pid") + PID_TO_GPU[$pid]="$gpu" + PID_TO_TAG[$pid]="$scene_tag" + PID_TO_NAME[$pid]="$scene_name" + PID_TO_LOG[$pid]="$log_file" + GPU_RUNNING[$gpu]=$((GPU_RUNNING[$gpu] + 1)) + GPU_LAUNCHED[$gpu]=$((GPU_LAUNCHED[$gpu] + 1)) + echo "[${scene_tag}] launched on gpu=${gpu} (name=${scene_name}, pid=${pid})" + show_progress_update + } + + collect_finished_jobs_once() { + local had_completion=0 + local -a next_running=() + local pid rc gpu scene_tag scene_name log_file + + for pid in "${RUNNING_PIDS[@]}"; do + if kill -0 "$pid" 2>/dev/null; then + next_running+=("$pid") + continue + fi + + set +e + wait "$pid" + rc=$? + set -e + + had_completion=1 + gpu="${PID_TO_GPU[$pid]}" + scene_tag="${PID_TO_TAG[$pid]}" + scene_name="${PID_TO_NAME[$pid]}" + log_file="${PID_TO_LOG[$pid]}" + unset 'PID_TO_GPU[$pid]' + unset 'PID_TO_TAG[$pid]' + unset 'PID_TO_NAME[$pid]' + unset 'PID_TO_LOG[$pid]' + GPU_RUNNING[$gpu]=$((GPU_RUNNING[$gpu] - 1)) + + if [[ "$rc" -eq 0 ]]; then + echo "[${scene_tag}] OK (name=${scene_name}, gpu=${gpu})" + OK_SCENES+=("$scene_tag:$scene_name") + else + echo "[${scene_tag}] FAIL rc=${rc} (name=${scene_name}, gpu=${gpu}, log: ${log_file})" + FAILED_SCENES+=("$scene_tag:$scene_name") + if [[ "$BATCH_STOP_ON_FAIL" == "1" ]]; then + STOP_LAUNCH=1 + fi + fi + done + + RUNNING_PIDS=("${next_running[@]}") + if [[ "$had_completion" == "1" ]]; then + show_progress_update + fi + if [[ "$had_completion" == "1" ]]; then + return 0 + fi + return 1 + } + + if [[ "$DRY_RUN" == "1" ]]; then + declare -A GPU_PLANNED=() + for g in "${GPU_IDS[@]}"; do + GPU_PLANNED[$g]=0 + done + rr_idx=0 + for i in "${!SCENE_DIRS[@]}"; do + best_gpu="" + best_idx=-1 + best_count=0 + for ((k=0; k<${#GPU_IDS[@]}; k++)); do + idx=$(( (rr_idx + k) % ${#GPU_IDS[@]} )) + g="${GPU_IDS[$idx]}" + c="${GPU_PLANNED[$g]}" + if [[ -z "$best_gpu" ]] || (( c < best_count )); then + best_gpu="$g" + best_idx="$idx" + best_count="$c" + fi + done + rr_idx=$(( (best_idx + 1) % ${#GPU_IDS[@]} )) + GPU_PLANNED[$best_gpu]=$((GPU_PLANNED[$best_gpu] + 1)) + log_file="${LOG_DIR}/${SCENE_TAGS[$i]}_$(slugify_token "${SCENE_NAMES[$i]}").log" + echo + echo "==== [${SCENE_TAGS[$i]}] plan ====" + echo "[${SCENE_TAGS[$i]}] scene dir: ${SCENE_DIRS[$i]}" + echo "[${SCENE_TAGS[$i]}] name: ${SCENE_NAMES[$i]}" + run_scene_sync "${SCENE_TAGS[$i]}" "${SCENE_NAMES[$i]}" "${SCENE_DIRS[$i]}" "$log_file" "$best_gpu" + done + else + while (( NEXT_SCENE_INDEX < ${#SCENE_DIRS[@]} || ${#RUNNING_PIDS[@]} > 0 )); do + if [[ "$STOP_LAUNCH" == "0" ]]; then + while (( NEXT_SCENE_INDEX < ${#SCENE_DIRS[@]} )); do + if ! gpu="$(pick_next_gpu)"; then + break + fi + echo + echo "==== [${SCENE_TAGS[$NEXT_SCENE_INDEX]}] start ====" + echo "[${SCENE_TAGS[$NEXT_SCENE_INDEX]}] scene dir: ${SCENE_DIRS[$NEXT_SCENE_INDEX]}" + echo "[${SCENE_TAGS[$NEXT_SCENE_INDEX]}] name: ${SCENE_NAMES[$NEXT_SCENE_INDEX]}" + launch_scene_async "$NEXT_SCENE_INDEX" "$gpu" + NEXT_SCENE_INDEX=$((NEXT_SCENE_INDEX + 1)) + done + fi + + if (( ${#RUNNING_PIDS[@]} == 0 )); then + break + fi + + until collect_finished_jobs_once; do + maybe_write_progress_snapshot + sleep 1 + done + done + + if [[ "$STOP_LAUNCH" == "1" && "$NEXT_SCENE_INDEX" -lt "${#SCENE_DIRS[@]}" ]]; then + for ((j=NEXT_SCENE_INDEX; j<${#SCENE_DIRS[@]}; j++)); do + SKIPPED_SCENES+=("${SCENE_TAGS[$j]}:${SCENE_NAMES[$j]}") + done + echo "[Batch] stop-on-fail enabled; skipped images: ${SKIPPED_SCENES[*]}" + show_progress_update + fi + fi +fi + +echo +echo "==== Batch summary ====" +echo "log dir: ${LOG_DIR}" +echo "ok (${#OK_SCENES[@]}): ${OK_SCENES[*]:-}" +echo "failed (${#FAILED_SCENES[@]}): ${FAILED_SCENES[*]:-}" +echo "skipped (${#SKIPPED_SCENES[@]}): ${SKIPPED_SCENES[*]:-}" + +printf "%s\n" "${OK_SCENES[@]}" >"${LOG_DIR}/ok.txt" +printf "%s\n" "${FAILED_SCENES[@]}" >"${LOG_DIR}/failed.txt" +printf "%s\n" "${SKIPPED_SCENES[@]}" >"${LOG_DIR}/skipped.txt" + +if [[ "${#FAILED_SCENES[@]}" -gt 0 ]]; then + exit 1 +fi diff --git a/OVOW/engine/run_steps_scene_pipeline.sh b/OVOW/engine/run_steps_scene_pipeline.sh new file mode 100644 index 0000000000000000000000000000000000000000..5500abd574c58dd59e29264cd4c3ea7373300e43 --- /dev/null +++ b/OVOW/engine/run_steps_scene_pipeline.sh @@ -0,0 +1,3510 @@ +#!/bin/sh +if [ -z "${BASH_VERSION:-}" ]; then + exec /usr/bin/env bash "$0" "$@" +fi +set -euo pipefail + + +VIDEO="" +NAME="" +RUN_DIR="" +OUT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs" +OUT_BASE="" +WORKSPACE_ROOT="" +WORKSPACE_NEW="0" +WORKSPACE_NEW_EXPLICIT="0" +WORKSPACE_KEY="" +WORKSPACE_POINTER_FILE="" +REPO="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine" +VIDEO_ROOT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/examples/videos" +DEFAULT_VIDEO="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/examples/videos/default/default.mp4" +VIDEO_EXPLICIT="0" + +QWEN_PY="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python" +SAM3_PY="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-sam3/bin/python" +OPG_PY="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python" +MOTION_PY="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-motion/bin/python" + +QWEN_SCRIPT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/masking/qwen_sam3_video_masks.py" +BATCH_CONFIG="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/config/batch_config_example_legacy.json" +RECON_BACKBONE="legacy" +QWEN_BACKEND="api" +QWEN_BACKEND_EXPLICIT="0" +QWEN_API_MODEL="qwen3.5-plus" +QWEN_API_MODEL_LIST="qwen3.5-flash-2026-02-23,qwen3.5-plus-2026-02-15,qwen3.5-flash,qwen3.5-122b-a10b,qwen3.5-35b-a3b" +QWEN_API_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1" +QWEN_MODEL="" +QWEN_API_KEY_ENV="DASHSCOPE_API_KEY" +QWEN_API_KEY="" + +QWEN_LABEL_CATEGORY_ENABLE="1" +QWEN_LABEL_CATEGORY_MODE="single" +QWEN_LABEL_CATEGORY_STRICT="1" +QWEN_LABEL_CATEGORY_MODEL="" +QWEN_CATEGORY_PASS="0" +QWEN_CATEGORY_PASS_STRICT="1" +QWEN_CATEGORY_API_MODEL="" +QWEN_MAX_NEW_TOKENS="2048" +QWEN_CATEGORY_MAX_NEW_TOKENS="2048" +SAM_MIN_OBJ_AREA="200" +PRUNE_LABELS="" +ADD_LABELS="" +ADD_LABEL_CATEGORY="static" +ADD_LABEL_OVERWRITE_CATEGORY="0" +MERGE_MASK_LABELS="" +MERGE_MASK_CATEGORY="" +MERGE_MASK_OUTPUT_LABEL="" + +MOTION324_ROOT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/third_party/Motion324" +MOTION324_CKPT_ROOT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts" +HY3DGEN_MODELS_DEFAULT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/hy3dgen" +BLENDER_BIN="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/opt/blender-4.2.3-linux-x64/blender" +BLENDER_BIN="$(command -v "$BLENDER_BIN" 2>/dev/null || echo "$BLENDER_BIN")" +BLENDER_LIB="" +HDR_PY="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-hdr/bin/python" +INTRHDR_REPO="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/IntrinsicHDR" +INTRHDR_RUNNER="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/run_intrhdr_media.sh" +MOTION324_BACKEND="hunyuan" +PLANE_NUM="5" +PLANE_BOTTOM="0.03" +GRAVITY_SIGN_MODE="object_region" +GRAVITY_SIGN_SAMPLES="5" +PHYSICS_ENABLE="0" +PHYSICS_BOTTOM="0.10" +PHYSICS_ITERS="2" +PHYSICS_MAX_DROP="1.0" +PHYSICS_ALLOW_DOWN="1" +PHYSICS_CONTACT="1" +LOCK_STATIC="1" +LOCK_STATIC_MODE="full" +LOCK_STATIC_EXPLICIT="0" +LOCK_STATIC_MODE_EXPLICIT="0" + +DEFORM_FORCE_POSES="0" +DEFORM_FORCE_SCALE="0" +DEFORM_RENDER_VIDEO="1" +DEFORM_EXPORT_VIDEO_FRAMES="0" +DEFORM_LOCK_POSE="0" +DEFORM_LOCK_FRAME="-1" +DEFORM_LOCK_MESH="0" + +DEFORM_BACKEND="${DEFORM_BACKEND:-motion324}" + +MOTION_NORMALIZE_ZOOM="1" +MOTION_NORMALIZE_TARGET_RATIO="0.65" +MOTION_NORMALIZE_SMOOTH="7" +MOTION_NORMALIZE_OUT_SIZE="512" +STEP18_UNLIT_TEXTURE="1" +STEP18_DEFORM_FRAMES_DIR="world_mesh_frames_physics" +STEP18_DEFORM_FRAMES_DIR_EXPLICIT="0" +STEP18_HDR="" +RERUN_OBJECTS="" +RERUN_ONLY_FAILED="1" +RERUN_ANCHOR_FRAME="-1" +RERUN_REF_MAP="" +RERUN_REF_IMAGE="" +RERUN_SINGLE_OBJECT="" +RERUN_USE_FLUX_REF="0" + +FLUX_PY="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-flux/bin/python" +FLUX2_REPO="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/flux2" +FLUX_STEP19_SCRIPT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/flux2_single_ref_edit.py" +FLUX_MODE="amodal" +FLUX_OBJ_NAME="" +FLUX_SEED="1234" +FLUX_OUT_WIDTH="518" +FLUX_OUT_HEIGHT="518" +FLUX_MATCH_IMAGE_SIZE="none" +FLUX_USE_RGB_CROP_REF="0" +FLUX_GPU="" +FLUX_PROMPT_AMODAL="" +FLUX_PROMPT_VIEW="" + +STEPS=() +CONTINUE_ON_ERROR="1" + +usage() { + cat < [step ...] + +Options: + --video PATH Input video path (overrides auto path from --name) + --video-root DIR Video root for auto path from --name (default: ${VIDEO_ROOT}) + --name NAME Scene name, e.g. v9 -> scene9/v9.mp4 under --video-root + --out DIR Output root (default: ${OUT}) + --workspace-root DIR Force workspace root (overrides auto workspace under --out) + --new-workspace 0|1 Force create new workspace for this name/video (auto: step-1=>new, otherwise reuse latest) + --run-dir DIR Override run dir for steps >= 7 + --backend NAME Motion324 backend (default: ${MOTION324_BACKEND}) + --deform-backend NAME Deform backend: motion324 (default: ${DEFORM_BACKEND}) + --recon-backbone NAME Static/rigid 3D backend for step 6: config|legacy|trellis2 (default: ${RECON_BACKBONE}) + --batch-config PATH Batch config JSON for step 6/tracker settings (default: ${BATCH_CONFIG}) + --qwen-backend NAME Qwen labels backend: api|local (default: ${QWEN_BACKEND}) + --qwen-api-model M Qwen API model for step 1 (default: ${QWEN_API_MODEL}) + --qwen-api-model-list L Qwen API fallback model list for step 1 (default: ${QWEN_API_MODEL_LIST}) + --qwen-api-base-url U Qwen API base URL (default: ${QWEN_API_BASE_URL}) + --qwen-api-key-env V Env var name for Qwen API key (default: ${QWEN_API_KEY_ENV}) + --qwen-label-category-enable 0|1 Master switch for Qwen label category mode (default: ${QWEN_LABEL_CATEGORY_ENABLE}) + --qwen-label-category-mode MODE Category mode: legacy|single|dual (default: ${QWEN_LABEL_CATEGORY_MODE}) + --qwen-label-category-strict 0|1 Strict category validation for selected mode (default: ${QWEN_LABEL_CATEGORY_STRICT}) + --qwen-label-category-model M API model for selected category mode (default: --qwen-api-model) + --qwen-max-new-tokens N Max tokens for Qwen step-1 label/category call (default: ${QWEN_MAX_NEW_TOKENS}) + --qwen-category-pass 0|1 [Deprecated] old dual-pass switch (default: ${QWEN_CATEGORY_PASS}) + --qwen-category-pass-strict 0|1 [Deprecated] strict for old dual-pass switch (default: ${QWEN_CATEGORY_PASS_STRICT}) + --qwen-category-api-model M [Deprecated] old dual-pass model override (default: --qwen-api-model) + --qwen-category-max-new-tokens N [Deprecated] max tokens for old dual-pass call (default: ${QWEN_CATEGORY_MAX_NEW_TOKENS}) + --sam-min-obj-area N Minimum SAM3 mask area to keep instance (default: ${SAM_MIN_OBJ_AREA}) + --add-labels L Step 1.4 labels to append to *_labels.json before SAM3 masks (comma-separated) + --add-label-category C Category for --add-labels: static|rigid|deform (default: ${ADD_LABEL_CATEGORY}) + --add-label-overwrite-category 0|1 Overwrite category for existing labels in step 1.4 (default: ${ADD_LABEL_OVERWRITE_CATEGORY}) + --prune-labels L Step 1.5 labels to remove from *_labels.json (comma-separated) + --merge-mask-labels A,B Step 2.5 merge all masks from exactly two labels into one object + --merge-mask-category C Step 2.5 merged object category: static|rigid|deform + --merge-mask-output-label L Step 2.5 merged label name (default: " with ") + --plane-num N Number of candidate planes for alignment fitting (default: ${PLANE_NUM}) + --plane-bottom X Bottom-percent used to score plane candidates against object meshes (default: ${PLANE_BOTTOM}) + --gravity-sign-mode MODE Plane-normal sign mode: camera_up|object_region|auto|none (default: ${GRAVITY_SIGN_MODE}) + --gravity-sign-samples N Frames sampled for object-region gravity sign voting (default: ${GRAVITY_SIGN_SAMPLES}) + --physics-enable 0|1 Master switch for rigid/deform physics and physics-aware step 18 render (default: ${PHYSICS_ENABLE}) + --physics-bottom X Bottom vertex fraction used by physics contact projection (default: ${PHYSICS_BOTTOM}) + --physics-iters N Contact projection iterations per frame (default: ${PHYSICS_ITERS}) + --physics-max-drop X Max downward settle distance in physics projection (default: ${PHYSICS_MAX_DROP}) + --physics-allow-down 0|1 Allow objects to move downward during physics settle (default: ${PHYSICS_ALLOW_DOWN}) + --physics-contact 0|1 Enable object-object contact during physics settle (default: ${PHYSICS_CONTACT}) + --continue-on-error 0|1 Continue running remaining steps after a step fails (default: ${CONTINUE_ON_ERROR}) + --rerun-objects OBJ1,OBJ2 Object names to rerun in step 16 (default: empty=auto) + --rerun-only-failed 0|1 In step 16 rerun failed objects from report when --rerun-objects is empty (default: ${RERUN_ONLY_FAILED}) + --rerun-anchor-frame N In step 16 override anchor frame for re-generation/scale (default: ${RERUN_ANCHOR_FRAME}; -1=use batch config) + --rerun-ref-map PATH In step 16 provide external ref images for object mesh generation + --ref-image PATH Step 16 shortcut for single object external image (requires --rerun-objects OBJ) + --flux Step 16: use latest image from RUN_DIR/objects/fluxoutput//... as ref image (supports one or more --rerun-objects) + --qwen-model PATH Local Qwen model path/HF ID (auto-switches step 1 to local unless --qwen-backend is set) + --lock-static 0|1 [Compat] static lock switch: 1->full, 0->off (default: ${LOCK_STATIC}) + --lock-static-mode MODE Static lock mode: full|rot_only|off (default: ${LOCK_STATIC_MODE}) + --deform-force-poses 0|1 Recompute deform poses in step 8 (default: ${DEFORM_FORCE_POSES}) + --deform-force-scale 0|1 Recompute deform scale in step 8 (default: ${DEFORM_FORCE_SCALE}) + --deform-render-video 0|1 Render deform pose video in step 8 (default: ${DEFORM_RENDER_VIDEO}) + --deform-export-video-frames 0|1 Export deform pose preview frames to pose_result/normal_video_frames in step 8 (default: ${DEFORM_EXPORT_VIDEO_FRAMES}) + --deform-lock 0|1 Lock deform object world/camera poses after step 8 pose solve (default: ${DEFORM_LOCK_POSE}) + --deform-lock-frame N Lock deform to frame N in step 8 (default: ${DEFORM_LOCK_FRAME}; -1=auto max-mask frame) + --deform-lock-mesh 0|1 Freeze deform world mesh sequence to lock frame in step 8 (default: ${DEFORM_LOCK_MESH}) + --motion-normalize-zoom true|false|1|0 Enable zoom-normalized masked videos in step 3 (default: ${MOTION_NORMALIZE_ZOOM}) + --motion-normalize-target-ratio R Target object ratio in step 3 normalize mode (default: ${MOTION_NORMALIZE_TARGET_RATIO}) + --motion-normalize-smooth N Temporal smoothing window in step 3 normalize mode (default: ${MOTION_NORMALIZE_SMOOTH}) + --motion-normalize-out-size N Output side size in step 3 normalize mode (default: ${MOTION_NORMALIZE_OUT_SIZE}) + --step18-unlit-texture 0|1 Render step 18 with unlit emission material (disable PBR shading, default: ${STEP18_UNLIT_TEXTURE}) + --step18-deform-frames-dir DIR Step 18 deform frame source dir (world_mesh_frames|world_mesh_frames_physics, default: ${STEP18_DEFORM_FRAMES_DIR}) + --hdr PATH|auto Step 18 HDR EXR/HDR world lighting (use auto for RUN_DIR/lighting/scene_intrinsic_hdr.exr) + --flux-obj-name OBJS Object name(s) under RUN_DIR/objects for step 19 (single or comma-separated) + --flux-mode MODE Step 19 mode: amodal|view (default: ${FLUX_MODE}) + --flux-seed N Step 19 seed for FLUX generation (default: ${FLUX_SEED}) + --flux-width N Step 19 output width (default: ${FLUX_OUT_WIDTH}) + --flux-height N Step 19 output height (default: ${FLUX_OUT_HEIGHT}) + --flux-match-image-size V Step 19 match image size index (e.g. 0) or none (default: ${FLUX_MATCH_IMAGE_SIZE}) + --flux-use-rgb-crop-ref 0|1 Step 19 pass both masked crop and original RGB crop as references (default: ${FLUX_USE_RGB_CROP_REF}) + --flux-gpu ID Optional CUDA_VISIBLE_DEVICES override for step 19 + --flux-prompt-amodal T Optional custom prompt for step 19 amodal mode + --flux-prompt-view T Optional custom prompt for step 19 view mode + --help Show this help + +Steps: + 1 Qwen labels + 1.4 Add labels JSON before SAM3 masks + 1.5 Prune labels JSON before SAM3 masks + 2 SAM3 masks + 2.5 Merge two label masks into one object label + 3 Build Motion324 deform inputs + 4 Run Motion324 for deform objects + 5 Scan Motion324 outputs + 6 Run pipeline for static+rigid (exclude deform) + 7 Fit plane + rigid/static physics + 8 Deform scale+pose + build deform world mesh sequence + 9 Deform physics sync (frame mesh) + 10 Export unified scene mesh frames (static+rigid+deform) + 11 Export static+rigid GLB (respects static lock mode) + 12 Export static+rigid physics GLB + 13 Export full-scene GLB pre-physics (rigid/static + deform animation, no-plane, UV-seam-safe) + 14 Export full-scene GLB physics (rigid/static + deform animation, UV-seam-safe) + 15 Generate intrinsic HDR EXR from the input video first frame + 16 Rerun failed step-6 objects and refresh scene point clouds + 17 Render full-scene + deform white-model video (left white model / right RGB) + 18 Render full-scene + deform textured video (left textured / right RGB) + 19 FLUX.2 single-reference edit for one object (amodal or view) + 20 Render mixed video (left white model / right textured) + 21 Split a video into frame images (PNG) + +Example: + bash run_steps_scene_pipeline.sh --video /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/examples/videos/scene3/v3.mp4 1 2 3 + bash run_steps_scene_pipeline.sh --name demo1 --add-labels book --add-label-category rigid 1.4 2 + bash run_steps_scene_pipeline.sh --name demo1 --prune-labels sandbox 1.5 2 + bash run_steps_scene_pipeline.sh --name demo1 --merge-mask-labels robot,watering_can --merge-mask-category deform --merge-mask-output-label "robot with watering_can" 2.5 3 4 + bash run_steps_scene_pipeline.sh --name v9 1 2 3 + CUDA_VISIBLE_DEVICES=1 bash /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/run_steps_scene_pipeline.sh --name v15 --run-dir /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs/video_pipeline_20260222_185124/v15 16 + bash run_steps_scene_pipeline.sh --video /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs/video_pipeline_20260227_211917/indoor2/indoor2.mp4 --run-dir /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs/video_pipeline_20260227_211917/indoor2 --rerun-objects nightstand_01 --flux 16 + CUDA_VISIBLE_DEVICES=2 bash /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/run_steps_scene_pipeline.sh --video /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/examples/videos/scene25/indoor2.mp4 --run-dir /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs/video_pipeline_20260227_211917/indoor2 --flux-obj-name pillow_01 --flux-mode amodal 19 + bash run_steps_scene_pipeline.sh --video /path/to/any_video.mp4 21 +USAGE +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --video) + VIDEO="$2" + VIDEO_EXPLICIT="1" + shift 2 + ;; + --video-root) + VIDEO_ROOT="$2" + shift 2 + ;; + --name) + NAME="$2" + shift 2 + ;; + --out) + OUT="$2" + shift 2 + ;; + --workspace-root) + WORKSPACE_ROOT="$2" + shift 2 + ;; + --new-workspace) + WORKSPACE_NEW="$2" + WORKSPACE_NEW_EXPLICIT="1" + shift 2 + ;; + --run-dir) + RUN_DIR="$2" + shift 2 + ;; + --backend) + MOTION324_BACKEND="$2" + shift 2 + ;; + --deform-backend) + DEFORM_BACKEND="$2" + shift 2 + ;; + --recon-backbone) + RECON_BACKBONE="$2" + shift 2 + ;; + --batch-config) + BATCH_CONFIG="$2" + shift 2 + ;; + --qwen-backend) + QWEN_BACKEND="$2" + QWEN_BACKEND_EXPLICIT="1" + shift 2 + ;; + --qwen-api-model) + QWEN_API_MODEL="$2" + shift 2 + ;; + --qwen-api-model-list) + QWEN_API_MODEL_LIST="$2" + shift 2 + ;; + --qwen-api-base-url) + QWEN_API_BASE_URL="$2" + shift 2 + ;; + --qwen-api-key-env) + QWEN_API_KEY_ENV="$2" + shift 2 + ;; + --qwen-label-category-enable) + QWEN_LABEL_CATEGORY_ENABLE="$2" + shift 2 + ;; + --qwen-label-category-mode) + QWEN_LABEL_CATEGORY_MODE="$2" + shift 2 + ;; + --qwen-label-category-strict) + QWEN_LABEL_CATEGORY_STRICT="$2" + shift 2 + ;; + --qwen-label-category-model) + QWEN_LABEL_CATEGORY_MODEL="$2" + shift 2 + ;; + --qwen-max-new-tokens) + QWEN_MAX_NEW_TOKENS="$2" + shift 2 + ;; + --qwen-category-pass) + QWEN_CATEGORY_PASS="$2" + shift 2 + ;; + --qwen-category-pass-strict) + QWEN_CATEGORY_PASS_STRICT="$2" + shift 2 + ;; + --qwen-category-api-model) + QWEN_CATEGORY_API_MODEL="$2" + shift 2 + ;; + --qwen-category-max-new-tokens) + QWEN_CATEGORY_MAX_NEW_TOKENS="$2" + shift 2 + ;; + --sam-min-obj-area) + SAM_MIN_OBJ_AREA="$2" + shift 2 + ;; + --add-labels) + ADD_LABELS="$2" + shift 2 + ;; + --add-label-category) + ADD_LABEL_CATEGORY="$2" + shift 2 + ;; + --add-label-overwrite-category) + ADD_LABEL_OVERWRITE_CATEGORY="$2" + shift 2 + ;; + --prune-labels) + PRUNE_LABELS="$2" + shift 2 + ;; + --merge-mask-labels) + MERGE_MASK_LABELS="$2" + shift 2 + ;; + --merge-mask-category) + MERGE_MASK_CATEGORY="$2" + shift 2 + ;; + --merge-mask-output-label) + MERGE_MASK_OUTPUT_LABEL="$2" + shift 2 + ;; + --plane-num) + PLANE_NUM="$2" + shift 2 + ;; + --plane-bottom) + PLANE_BOTTOM="$2" + shift 2 + ;; + --gravity-sign-mode) + GRAVITY_SIGN_MODE="$2" + shift 2 + ;; + --gravity-sign-samples) + GRAVITY_SIGN_SAMPLES="$2" + shift 2 + ;; + --physics-enable) + PHYSICS_ENABLE="$2" + shift 2 + ;; + --physics-bottom) + PHYSICS_BOTTOM="$2" + shift 2 + ;; + --physics-iters) + PHYSICS_ITERS="$2" + shift 2 + ;; + --physics-max-drop) + PHYSICS_MAX_DROP="$2" + shift 2 + ;; + --physics-allow-down) + PHYSICS_ALLOW_DOWN="$2" + shift 2 + ;; + --physics-contact) + PHYSICS_CONTACT="$2" + shift 2 + ;; + --continue-on-error) + CONTINUE_ON_ERROR="$2" + shift 2 + ;; + --rerun-objects) + RERUN_OBJECTS="$2" + shift 2 + ;; + --rerun-only-failed) + RERUN_ONLY_FAILED="$2" + shift 2 + ;; + --rerun-anchor-frame) + RERUN_ANCHOR_FRAME="$2" + shift 2 + ;; + --rerun-ref-map) + RERUN_REF_MAP="$2" + shift 2 + ;; + --ref-image|--ref_image) + RERUN_REF_IMAGE="$2" + shift 2 + ;; + --flux) + RERUN_USE_FLUX_REF="1" + shift + ;; + --qwen-model) + QWEN_MODEL="$2" + shift 2 + ;; + --lock-static) + LOCK_STATIC="$2" + LOCK_STATIC_EXPLICIT="1" + shift 2 + ;; + --lock-static-mode) + LOCK_STATIC_MODE="$2" + LOCK_STATIC_MODE_EXPLICIT="1" + shift 2 + ;; + --deform-force-poses) + DEFORM_FORCE_POSES="$2" + shift 2 + ;; + --deform-force-scale) + DEFORM_FORCE_SCALE="$2" + shift 2 + ;; + --deform-render-video) + DEFORM_RENDER_VIDEO="$2" + shift 2 + ;; + --deform-export-video-frames) + DEFORM_EXPORT_VIDEO_FRAMES="$2" + shift 2 + ;; + --deform-lock) + DEFORM_LOCK_POSE="$2" + shift 2 + ;; + --deform-lock-frame) + DEFORM_LOCK_FRAME="$2" + shift 2 + ;; + --deform-lock-mesh) + DEFORM_LOCK_MESH="$2" + shift 2 + ;; + --motion-normalize-zoom) + MOTION_NORMALIZE_ZOOM="$2" + shift 2 + ;; + --motion-normalize-target-ratio) + MOTION_NORMALIZE_TARGET_RATIO="$2" + shift 2 + ;; + --motion-normalize-smooth) + MOTION_NORMALIZE_SMOOTH="$2" + shift 2 + ;; + --motion-normalize-out-size) + MOTION_NORMALIZE_OUT_SIZE="$2" + shift 2 + ;; + --step18-unlit-texture) + STEP18_UNLIT_TEXTURE="$2" + shift 2 + ;; + --step18-deform-frames-dir) + STEP18_DEFORM_FRAMES_DIR="$2" + STEP18_DEFORM_FRAMES_DIR_EXPLICIT="1" + shift 2 + ;; + --hdr) + STEP18_HDR="$2" + shift 2 + ;; + --flux-obj-name) + FLUX_OBJ_NAME="$2" + shift 2 + ;; + --flux-mode) + FLUX_MODE="$2" + shift 2 + ;; + --flux-seed) + FLUX_SEED="$2" + shift 2 + ;; + --flux-width) + FLUX_OUT_WIDTH="$2" + shift 2 + ;; + --flux-height) + FLUX_OUT_HEIGHT="$2" + shift 2 + ;; + --flux-match-image-size) + FLUX_MATCH_IMAGE_SIZE="$2" + shift 2 + ;; + --flux-use-rgb-crop-ref) + FLUX_USE_RGB_CROP_REF="$2" + shift 2 + ;; + --flux-gpu) + FLUX_GPU="$2" + shift 2 + ;; + --flux-prompt-amodal) + FLUX_PROMPT_AMODAL="$2" + shift 2 + ;; + --flux-prompt-view) + FLUX_PROMPT_VIEW="$2" + shift 2 + ;; + --help|-h) + usage + exit 0 + ;; + *) + STEPS+=("$1") + shift + ;; + esac +done + +if [[ "$QWEN_BACKEND_EXPLICIT" != "1" && -n "$QWEN_MODEL" ]]; then + QWEN_BACKEND="local" +fi + +if [[ "$QWEN_BACKEND" != "api" && "$QWEN_BACKEND" != "local" ]]; then + echo "ERROR: --qwen-backend must be api or local (got: $QWEN_BACKEND)" >&2 + exit 1 +fi + +if [[ "$QWEN_BACKEND" == "api" ]]; then + if [[ -n "$QWEN_API_KEY" ]]; then + export "$QWEN_API_KEY_ENV=$QWEN_API_KEY" + fi + if [[ -z "${!QWEN_API_KEY_ENV:-}" ]]; then + echo "ERROR: API key env '$QWEN_API_KEY_ENV' is empty." >&2 + exit 1 + fi +else + if [[ -n "$QWEN_MODEL" && ! -e "$QWEN_MODEL" ]]; then + echo "ERROR: local Qwen model not found: $QWEN_MODEL" >&2 + echo "Hint: bundle/restore weights_qwen_local_optional to /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/public_ckpts/model/Qwen3-VL-32B-Instruct, or run with --qwen-backend api and set $QWEN_API_KEY_ENV." >&2 + exit 1 + fi +fi + +export MOTION324_CKPT_ROOT="${MOTION324_CKPT_ROOT:-$MOTION324_CKPT_ROOT}" +export HY3DGEN_MODELS="${HY3DGEN_MODELS:-$HY3DGEN_MODELS_DEFAULT}" +export BLENDER_BIN="${BLENDER_BIN:-$BLENDER_BIN}" + +if [[ ${#STEPS[@]} -eq 0 ]]; then + usage + exit 1 +fi + +if [[ -z "${NAME}" && -z "${VIDEO}" ]]; then + if [[ -f "$DEFAULT_VIDEO" ]]; then + VIDEO="$DEFAULT_VIDEO" + echo "[Auto] No --video/--name provided; using DEFAULT_VIDEO=$VIDEO" + else + auto_video="$(find "$VIDEO_ROOT" -type f \( -iname '*.mp4' -o -iname '*.mov' -o -iname '*.mkv' \) 2>/dev/null | sort | head -n1 || true)" + if [[ -n "$auto_video" ]]; then + VIDEO="$auto_video" + echo "[Auto] No --video/--name provided; using first video under VIDEO_ROOT=$VIDEO" + else + echo "ERROR: please pass --name or --video, or bundle a default video at: $DEFAULT_VIDEO" >&2 + usage + exit 1 + fi + fi +fi + +if [[ -z "${VIDEO}" ]]; then + if [[ "${NAME}" =~ ^v([0-9]+)$ ]]; then + scene_id="${BASH_REMATCH[1]}" + VIDEO="${VIDEO_ROOT}/scene${scene_id}/${NAME}.mp4" + else + VIDEO="${VIDEO_ROOT}/${NAME}.mp4" + fi +fi + +if [[ -z "${NAME}" ]]; then + NAME="$(basename "$VIDEO")" + NAME="${NAME%.*}" +fi + +VIDEO_BASENAME="$(basename "$VIDEO")" +VIDEO_BASENAME="${VIDEO_BASENAME%.*}" +if [[ "${VIDEO_BASENAME}" != "${NAME}" ]]; then + echo "ERROR: --name (${NAME}) and --video basename (${VIDEO_BASENAME}) mismatch." >&2 + exit 1 +fi + +if [[ ! -f "${VIDEO}" ]]; then + echo "ERROR: video not found: ${VIDEO}" >&2 + if [[ "$VIDEO_EXPLICIT" == "0" ]]; then + echo "Hint: pass --video explicitly, or check --video-root/--name." >&2 + fi + exit 1 +fi + +OUT_BASE="$OUT" + +if [[ "$WORKSPACE_NEW_EXPLICIT" == "1" ]]; then + case "$WORKSPACE_NEW" in + 0|false|False|FALSE|no|No|NO|off|Off|OFF) + WORKSPACE_NEW="0" + ;; + 1|true|True|TRUE|yes|Yes|YES|on|On|ON) + WORKSPACE_NEW="1" + ;; + *) + echo "ERROR: --new-workspace must be 0|1 (got: $WORKSPACE_NEW)" >&2 + exit 1 + ;; + esac +fi + +WORKSPACE_KEY="$(printf '%s|%s' "$VIDEO" "$NAME" | sha1sum | awk '{print $1}' | cut -c1-12)" +local_workspace_idx="${OUT_BASE}/_ws_idx" +WORKSPACE_POINTER_FILE="${local_workspace_idx}/${NAME}_${WORKSPACE_KEY}.txt" + +if [[ -n "$WORKSPACE_ROOT" ]]; then + OUT="$WORKSPACE_ROOT" +else + workspace_from_run="" + if [[ -n "$RUN_DIR" ]]; then + marker_file="${RUN_DIR}/.onepose_workspace_root" + if [[ -f "$marker_file" ]]; then + workspace_from_run="$(head -n1 "$marker_file" | tr -d '\r')" + fi + if [[ -z "$workspace_from_run" ]]; then + if [[ -f "${OUT_BASE}/recon_ready/${NAME}/pipeline_config.json" || -f "${OUT_BASE}/metadata/${NAME}_mask_summary.json" ]]; then + workspace_from_run="$OUT_BASE" + fi + fi + fi + + latest_workspace="" + if [[ -n "$workspace_from_run" ]]; then + latest_workspace="$workspace_from_run" + elif [[ -f "$WORKSPACE_POINTER_FILE" ]]; then + latest_workspace="$(head -n1 "$WORKSPACE_POINTER_FILE" | tr -d '\r')" + fi + + auto_new_workspace="0" + if [[ -z "$RUN_DIR" ]]; then + for s in "${STEPS[@]}"; do + if [[ "$s" == "1" ]]; then + auto_new_workspace="1" + break + fi + done + fi + + create_new_workspace="$auto_new_workspace" + if [[ "$WORKSPACE_NEW_EXPLICIT" == "1" ]]; then + create_new_workspace="$WORKSPACE_NEW" + fi + + if [[ "$create_new_workspace" == "1" || -z "$latest_workspace" ]]; then + ws_ts="$(date '+%Y%m%d_%H%M%S')" + OUT="${OUT_BASE}/ws/${NAME}_${ws_ts}_${WORKSPACE_KEY}" + else + OUT="$latest_workspace" + fi + +fi + +mkdir -p "$local_workspace_idx" +printf '%s\n' "$OUT" >"$WORKSPACE_POINTER_FILE" + +STATE_JSON="${OUT}/metadata/${NAME}_step_state.json" +ERROR_LOG="${OUT}/metadata/${NAME}_step_errors.log" +STEP_LOG_DIR="${OUT}/logs/${NAME}" + +mkdir -p "${OUT}/metadata" +mkdir -p "${STEP_LOG_DIR}" + +state_get() { + local key="$1" + python3 - "$STATE_JSON" "$key" <>"$ERROR_LOG" +} + +normalize_bool() { + local raw="${1:-}" + local v + v="$(echo "$raw" | tr '[:upper:]' '[:lower:]')" + case "$v" in + 1|true|yes|on) + echo "1" + ;; + 0|false|no|off) + echo "0" + ;; + *) + echo "ERROR: invalid boolean '$raw' (use true/false or 1/0)" >&2 + exit 1 + ;; + esac +} + +normalize_int() { + local raw="${1:-}" + if [[ "$raw" =~ ^-?[0-9]+$ ]]; then + echo "$raw" + else + echo "ERROR: invalid integer '$raw'" >&2 + exit 1 + fi +} + +normalize_float() { + local raw="${1:-}" + python3 - "$raw" <<'PY' +import math +import sys +raw = sys.argv[1] +try: + value = float(raw) +except Exception: + print(f"ERROR: invalid float '{raw}'", file=sys.stderr) + raise SystemExit(1) +if not math.isfinite(value): + print(f"ERROR: invalid float '{raw}'", file=sys.stderr) + raise SystemExit(1) +print(repr(value)) +PY +} + +trim_spaces() { + local s="$1" + s="${s#"${s%%[![:space:]]*}"}" + s="${s%"${s##*[![:space:]]}"}" + echo "$s" +} + +extract_single_csv_item() { + local raw="$1" + local out=() + local item + while IFS= read -r item; do + [[ -n "$item" ]] && out+=("$item") + done < <(parse_csv_items "$raw") + if [[ "${#out[@]}" -ne 1 ]]; then + echo "ERROR: requires exactly one object, got: '$raw'" >&2 + exit 1 + fi + echo "${out[0]}" +} + +parse_csv_items() { + local raw="$1" + IFS=',' read -r -a items <<<"$raw" + local out=() + local item + for item in "${items[@]}"; do + item="$(trim_spaces "$item")" + if [[ -n "$item" ]]; then + out+=("$item") + fi + done + if [[ "${#out[@]}" -le 0 ]]; then + echo "ERROR: requires at least one object, got: '$raw'" >&2 + exit 1 + fi + printf '%s\n' "${out[@]}" +} + +normalize_lock_static_mode() { + local raw="${1:-}" + local mode + mode="$(echo "$raw" | tr '[:upper:]' '[:lower:]')" + case "$mode" in + full|all|1|true|yes|on) + echo "full" + ;; + rot_only|rot|r|rotation|rotation_only) + echo "rot_only" + ;; + off|none|0|false|no|disable|disabled) + echo "off" + ;; + *) + echo "ERROR: invalid lock-static mode '$raw' (use full|rot_only|off)" >&2 + exit 1 + ;; + esac +} + +normalize_label_category_mode() { + local raw="${1:-}" + local mode + mode="$(echo "$raw" | tr '[:upper:]' '[:lower:]')" + case "$mode" in + legacy) + echo "legacy" + ;; + single|single_pass|single-pass) + echo "single_pass" + ;; + dual|dual_pass|dual-pass) + echo "dual_pass" + ;; + *) + echo "ERROR: invalid qwen label category mode '$raw' (use legacy|single|dual)" >&2 + exit 1 + ;; + esac +} + +normalize_flux_mode() { + local raw="${1:-}" + local mode + mode="$(echo "$raw" | tr '[:upper:]' '[:lower:]')" + case "$mode" in + amodal|complete|completion) + echo "amodal" + ;; + view|novel|novel_view|novel-view) + echo "view" + ;; + *) + echo "ERROR: invalid flux mode '$raw' (use amodal|view)" >&2 + exit 1 + ;; + esac +} + +normalize_flux_match_image_size() { + local raw="${1:-}" + local v + v="$(echo "$raw" | tr '[:upper:]' '[:lower:]')" + case "$v" in + ""|none|null|-1) + echo "none" + ;; + *) + if [[ "$v" =~ ^[0-9]+$ ]]; then + echo "$v" + else + echo "ERROR: invalid --flux-match-image-size '$raw' (use none or non-negative integer index)" >&2 + exit 1 + fi + ;; + esac +} + +normalize_recon_backbone() { + local raw="${1:-}" + local v + v="$(echo "$raw" | tr '[:upper:]' '[:lower:]')" + case "$v" in + ""|config|default|batch|batch_config) + echo "config" + ;; + legacy|hi3dgen|amodal3r|uplegacy) + echo "legacy" + ;; + trellis2|trellis.2|t2|viat2) + echo "trellis2" + ;; + *) + echo "ERROR: invalid --recon-backbone '$raw' (use config|legacy|trellis2)" >&2 + exit 1 + ;; + esac +} + +MOTION_NORMALIZE_ZOOM_BOOL="$(normalize_bool "$MOTION_NORMALIZE_ZOOM")" +STEP18_UNLIT_TEXTURE_BOOL="$(normalize_bool "$STEP18_UNLIT_TEXTURE")" +DEFORM_LOCK_POSE_BOOL="$(normalize_bool "$DEFORM_LOCK_POSE")" +DEFORM_LOCK_MESH_BOOL="$(normalize_bool "$DEFORM_LOCK_MESH")" +DEFORM_EXPORT_VIDEO_FRAMES_BOOL="$(normalize_bool "$DEFORM_EXPORT_VIDEO_FRAMES")" +DEFORM_LOCK_FRAME_INT="$(normalize_int "$DEFORM_LOCK_FRAME")" +LOCK_STATIC_BOOL="$(normalize_bool "$LOCK_STATIC")" +PHYSICS_ENABLE_BOOL="$(normalize_bool "$PHYSICS_ENABLE")" +PHYSICS_ALLOW_DOWN_BOOL="$(normalize_bool "$PHYSICS_ALLOW_DOWN")" +PHYSICS_CONTACT_BOOL="$(normalize_bool "$PHYSICS_CONTACT")" +LOCK_STATIC_MODE_CANONICAL="$(normalize_lock_static_mode "$LOCK_STATIC_MODE")" +QWEN_LABEL_CATEGORY_ENABLE_BOOL="$(normalize_bool "$QWEN_LABEL_CATEGORY_ENABLE")" +QWEN_CATEGORY_PASS_BOOL="$(normalize_bool "$QWEN_CATEGORY_PASS")" +QWEN_CATEGORY_PASS_STRICT_BOOL="$(normalize_bool "$QWEN_CATEGORY_PASS_STRICT")" +QWEN_LABEL_CATEGORY_STRICT_BOOL="$(normalize_bool "$QWEN_LABEL_CATEGORY_STRICT")" +ADD_LABEL_OVERWRITE_CATEGORY_BOOL="$(normalize_bool "$ADD_LABEL_OVERWRITE_CATEGORY")" +QWEN_MAX_NEW_TOKENS_INT="$(normalize_int "$QWEN_MAX_NEW_TOKENS")" +QWEN_CATEGORY_MAX_NEW_TOKENS_INT="$(normalize_int "$QWEN_CATEGORY_MAX_NEW_TOKENS")" +SAM_MIN_OBJ_AREA_INT="$(normalize_int "$SAM_MIN_OBJ_AREA")" +RECON_BACKBONE_CANONICAL="$(normalize_recon_backbone "$RECON_BACKBONE")" +if [[ "$(echo "$RECON_BACKBONE" | tr '[:upper:]' '[:lower:]')" == "uplegacy" \ + || "$(basename "$BATCH_CONFIG" | tr '[:upper:]' '[:lower:]')" == *uplegacy* ]]; then + export OPG_MATCHER="${OPG_MATCHER:-romav2}" + export OPG_SCALE_REFINE_ITERS="${OPG_SCALE_REFINE_ITERS:-0}" + echo "[uplegacy] scale chain: OPG_MATCHER=$OPG_MATCHER OPG_SCALE_REFINE_ITERS=$OPG_SCALE_REFINE_ITERS (static+deform)" +fi +PLANE_NUM_INT="$(normalize_int "$PLANE_NUM")" +GRAVITY_SIGN_SAMPLES_INT="$(normalize_int "$GRAVITY_SIGN_SAMPLES")" +PHYSICS_ITERS_INT="$(normalize_int "$PHYSICS_ITERS")" +PLANE_BOTTOM_FLOAT="$(normalize_float "$PLANE_BOTTOM")" +PHYSICS_BOTTOM_FLOAT="$(normalize_float "$PHYSICS_BOTTOM")" +PHYSICS_MAX_DROP_FLOAT="$(normalize_float "$PHYSICS_MAX_DROP")" +CONTINUE_ON_ERROR_BOOL="$(normalize_bool "$CONTINUE_ON_ERROR")" +RERUN_ONLY_FAILED_BOOL="$(normalize_bool "$RERUN_ONLY_FAILED")" +RERUN_USE_FLUX_REF_BOOL="$(normalize_bool "$RERUN_USE_FLUX_REF")" +RERUN_ANCHOR_FRAME_INT="$(normalize_int "$RERUN_ANCHOR_FRAME")" +FLUX_MODE_CANONICAL="$(normalize_flux_mode "$FLUX_MODE")" +FLUX_SEED_INT="$(normalize_int "$FLUX_SEED")" +FLUX_OUT_WIDTH_INT="$(normalize_int "$FLUX_OUT_WIDTH")" +FLUX_OUT_HEIGHT_INT="$(normalize_int "$FLUX_OUT_HEIGHT")" +FLUX_MATCH_IMAGE_SIZE_CANONICAL="$(normalize_flux_match_image_size "$FLUX_MATCH_IMAGE_SIZE")" +FLUX_USE_RGB_CROP_REF_BOOL="$(normalize_bool "$FLUX_USE_RGB_CROP_REF")" +if [[ "$QWEN_MAX_NEW_TOKENS_INT" -le 0 ]]; then + echo "ERROR: --qwen-max-new-tokens must be > 0 (got: $QWEN_MAX_NEW_TOKENS_INT)" >&2 + exit 1 +fi +if [[ "$QWEN_CATEGORY_MAX_NEW_TOKENS_INT" -le 0 ]]; then + echo "ERROR: --qwen-category-max-new-tokens must be > 0 (got: $QWEN_CATEGORY_MAX_NEW_TOKENS_INT)" >&2 + exit 1 +fi +if [[ "$SAM_MIN_OBJ_AREA_INT" -le 0 ]]; then + echo "ERROR: --sam-min-obj-area must be > 0 (got: $SAM_MIN_OBJ_AREA_INT)" >&2 + exit 1 +fi +if [[ "$PLANE_NUM_INT" -le 0 ]]; then + echo "ERROR: --plane-num must be > 0 (got: $PLANE_NUM_INT)" >&2 + exit 1 +fi +if [[ "$GRAVITY_SIGN_SAMPLES_INT" -le 0 ]]; then + echo "ERROR: --gravity-sign-samples must be > 0 (got: $GRAVITY_SIGN_SAMPLES_INT)" >&2 + exit 1 +fi +if [[ "$PHYSICS_ITERS_INT" -le 0 ]]; then + echo "ERROR: --physics-iters must be > 0 (got: $PHYSICS_ITERS_INT)" >&2 + exit 1 +fi +if [[ "$RERUN_ANCHOR_FRAME_INT" -lt -1 ]]; then + echo "ERROR: --rerun-anchor-frame must be >= -1 (-1 means use batch config; got: $RERUN_ANCHOR_FRAME_INT)" >&2 + exit 1 +fi +if [[ "$STEP18_DEFORM_FRAMES_DIR" != "world_mesh_frames" && "$STEP18_DEFORM_FRAMES_DIR" != "world_mesh_frames_physics" ]]; then + echo "ERROR: --step18-deform-frames-dir must be world_mesh_frames or world_mesh_frames_physics (got: $STEP18_DEFORM_FRAMES_DIR)" >&2 + exit 1 +fi +if [[ "$DEFORM_BACKEND" != "motion324" ]]; then + echo "ERROR: --deform-backend must be motion324 (got: $DEFORM_BACKEND). ActionMesh 后端已从 OVOW 发布中移除。" >&2 + exit 1 +fi +if [[ "$FLUX_OUT_WIDTH_INT" -le 0 || "$FLUX_OUT_HEIGHT_INT" -le 0 ]]; then + echo "ERROR: --flux-width/--flux-height must be > 0 (got: ${FLUX_OUT_WIDTH_INT}x${FLUX_OUT_HEIGHT_INT})" >&2 + exit 1 +fi +if [[ -n "$RERUN_REF_MAP" && ! -f "$RERUN_REF_MAP" ]]; then + echo "ERROR: --rerun-ref-map file not found: $RERUN_REF_MAP" >&2 + exit 1 +fi +if [[ "$RERUN_USE_FLUX_REF_BOOL" == "1" ]]; then + if [[ -n "$RERUN_REF_MAP" ]]; then + echo "ERROR: --flux and --rerun-ref-map cannot be used together." >&2 + exit 1 + fi + if [[ -n "$RERUN_REF_IMAGE" ]]; then + echo "ERROR: --flux and --ref-image cannot be used together." >&2 + exit 1 + fi + if [[ -z "$RERUN_OBJECTS" ]]; then + echo "ERROR: --flux requires --rerun-objects with one or more objects." >&2 + exit 1 + fi + parse_csv_items "$RERUN_OBJECTS" >/dev/null +fi +if [[ -n "$RERUN_REF_IMAGE" ]]; then + if [[ -n "$RERUN_REF_MAP" ]]; then + echo "ERROR: --ref-image and --rerun-ref-map cannot be used together." >&2 + exit 1 + fi + if [[ ! -f "$RERUN_REF_IMAGE" ]]; then + echo "ERROR: --ref-image file not found: $RERUN_REF_IMAGE" >&2 + exit 1 + fi + if [[ -z "$RERUN_OBJECTS" ]]; then + echo "ERROR: --ref-image requires --rerun-objects with exactly one object." >&2 + exit 1 + fi + RERUN_SINGLE_OBJECT="$(extract_single_csv_item "$RERUN_OBJECTS")" +fi + +if [[ "$LOCK_STATIC_MODE_EXPLICIT" != "1" ]]; then + if [[ "$LOCK_STATIC_BOOL" == "1" ]]; then + LOCK_STATIC_MODE_CANONICAL="full" + else + LOCK_STATIC_MODE_CANONICAL="off" + fi +elif [[ "$LOCK_STATIC_EXPLICIT" == "1" ]]; then + echo "[WARN] Both --lock-static and --lock-static-mode were set; using --lock-static-mode=${LOCK_STATIC_MODE_CANONICAL}." +fi + +if [[ "$LOCK_STATIC_MODE_CANONICAL" == "off" ]]; then + LOCK_STATIC_ENABLED_BOOL="0" +else + LOCK_STATIC_ENABLED_BOOL="1" +fi + +QWEN_LABEL_CATEGORY_MODE_CANONICAL="$(normalize_label_category_mode "$QWEN_LABEL_CATEGORY_MODE")" +QWEN_LABEL_CATEGORY_MODE_EFFECTIVE="$QWEN_LABEL_CATEGORY_MODE_CANONICAL" +if [[ "$QWEN_LABEL_CATEGORY_ENABLE_BOOL" == "0" ]]; then + QWEN_LABEL_CATEGORY_MODE_EFFECTIVE="legacy" +fi + +if [[ "$QWEN_LABEL_CATEGORY_MODE_EFFECTIVE" == "dual_pass" ]]; then + QWEN_CATEGORY_PASS_EFFECTIVE="1" +else + QWEN_CATEGORY_PASS_EFFECTIVE="0" +fi +QWEN_CATEGORY_PASS_STRICT_EFFECTIVE="$QWEN_LABEL_CATEGORY_STRICT_BOOL" + +if [[ "$QWEN_CATEGORY_PASS_BOOL" == "1" && "$QWEN_LABEL_CATEGORY_MODE_EFFECTIVE" != "dual_pass" ]]; then + echo "[WARN] --qwen-category-pass is deprecated and ignored. Use --qwen-label-category-mode dual." +fi +if [[ "$QWEN_CATEGORY_PASS_STRICT_BOOL" != "$QWEN_LABEL_CATEGORY_STRICT_BOOL" ]]; then + echo "[WARN] --qwen-category-pass-strict is deprecated and ignored. Use --qwen-label-category-strict." +fi + +write_run_workspace_marker() { + local run_dir="$1" + if [[ -z "$run_dir" || ! -d "$run_dir" ]]; then + return + fi + printf '%s\n' "$OUT" >"${run_dir}/.onepose_workspace_root" || true +} + +resolve_run_dir() { + if [[ -n "${RUN_DIR}" ]]; then + write_run_workspace_marker "$RUN_DIR" + return + fi + RUN_DIR="$(state_get run_dir)" + if [[ -z "${RUN_DIR}" ]]; then + echo "ERROR: RUN_DIR not set. Please run step 6 first or pass --run-dir." >&2 + exit 1 + fi + write_run_workspace_marker "$RUN_DIR" +} + +get_effective_config() { + local cfg_state cfg_effective cfg_main + cfg_main="$OUT/recon_ready/$NAME/pipeline_config.json" + cfg_state="$(state_get effective_config)" + if [[ -n "$cfg_state" && -f "$cfg_state" ]]; then + echo "$cfg_state" + return + fi + cfg_effective="$OUT/recon_ready/$NAME/pipeline_config_effective.json" + if [[ -f "$cfg_effective" ]]; then + echo "$cfg_effective" + return + fi + echo "$cfg_main" +} + +prepare_step6_batch_config() { + local backbone="$1" + local cfg_out="$OUT/recon_ready/$NAME/batch_config_step6_${backbone}.json" + if [[ "$backbone" == "config" ]]; then + echo "$BATCH_CONFIG" + return + fi + + "$OPG_PY" - "$BATCH_CONFIG" "$cfg_out" "$backbone" <<'PY' +import json +import sys +from pathlib import Path + +src = Path(sys.argv[1]) +dst = Path(sys.argv[2]) +backbone = sys.argv[3] + +cfg = json.loads(src.read_text(encoding="utf-8")) +generation = cfg.setdefault("generation", {}) +generation["model_type"] = backbone + +dst.parent.mkdir(parents=True, exist_ok=True) +dst.write_text(json.dumps(cfg, indent=2, ensure_ascii=False), encoding="utf-8") +print(dst) +PY +} + +choose_plane_pcd() { + local pcd_main="$RUN_DIR/scene_point_cloud_frame_all.ply" + local pcd_alt="$RUN_DIR/combined_scene_objects.ply" + if [[ -f "$pcd_main" ]]; then + echo "$pcd_main" + return + fi + if [[ -f "$pcd_alt" ]]; then + echo "[Warn] scene_point_cloud_frame_all.ply missing; fallback to combined_scene_objects.ply" >&2 + echo "$pcd_alt" + return + fi + echo "$pcd_main" +} + +default_step15_hdr_path() { + echo "$RUN_DIR/lighting/scene_intrinsic_hdr.exr" +} + +resolve_step18_hdr_path() { + local hdr_path="${STEP18_HDR:-}" + if [[ -z "$hdr_path" ]]; then + echo "" + return + fi + if [[ "$hdr_path" == "auto" ]]; then + hdr_path="$(default_step15_hdr_path)" + fi + if [[ ! -f "$hdr_path" ]]; then + echo "ERROR: HDR EXR not found: $hdr_path" >&2 + exit 1 + fi + echo "$hdr_path" +} + +compute_rgb_select_expr() { + local video_path="$1" + local target_frames="$2" + local sample_stride="${3:-0}" + "$OPG_PY" - "$video_path" "$target_frames" "$sample_stride" <<'PY' +import cv2 +import numpy as np +import sys + +video_path = sys.argv[1] +target = max(1, int(sys.argv[2])) +try: + stride = int(sys.argv[3]) +except Exception: + stride = 0 + +cap = cv2.VideoCapture(video_path) +src_frames = int(round(float(cap.get(cv2.CAP_PROP_FRAME_COUNT)))) +cap.release() +if src_frames <= 0: + src_frames = target + +if stride > 0: + idx = [i * stride for i in range(target) if (i * stride) < src_frames] +elif src_frames >= target: + idx = np.rint(np.linspace(0, src_frames - 1, target)).astype(int) + idx = np.clip(idx, 0, src_frames - 1) + # select() cannot duplicate frames; keep unique increasing indices. + uniq = [] + seen = set() + for v in idx.tolist(): + if v not in seen: + uniq.append(v) + seen.add(v) + if len(uniq) < target: + remain = [i for i in range(src_frames) if i not in seen] + if remain: + need = target - len(uniq) + fill = np.rint(np.linspace(0, len(remain) - 1, need)).astype(int) + for p in fill.tolist(): + uniq.append(remain[p]) + idx = sorted(uniq)[:target] +else: + idx = list(range(src_frames)) + +parts = [f"eq(n,{i})" for i in idx] +expr = "+".join(parts) if parts else "not(mod(n,1))" +print(expr) +print(len(idx)) +print(src_frames) +print(idx[0] if idx else -1) +print(idx[-1] if idx else -1) +PY +} + +write_effective_config_from_step6() { + local run_dir="$1" + local cfg_in="$OUT/recon_ready/$NAME/pipeline_config.json" + local cfg_out="$OUT/recon_ready/$NAME/pipeline_config_effective.json" + local err_json="$run_dir/object_errors_step6.json" + local step6_batch_config + step6_batch_config="$(state_get step6_batch_config)" + if [[ ! -f "$cfg_in" ]]; then + return + fi + + "$OPG_PY" - "$cfg_in" "$cfg_out" "$err_json" "$run_dir" "$step6_batch_config" <<'PY' +import json +import sys +from pathlib import Path + +cfg_in = Path(sys.argv[1]) +cfg_out = Path(sys.argv[2]) +err_json = Path(sys.argv[3]) +run_dir = Path(sys.argv[4]) +step6_batch_config = sys.argv[5].strip() if len(sys.argv) > 5 else "" + +cfg = json.loads(cfg_in.read_text(encoding="utf-8")) +if step6_batch_config: + cfg["batch_config"] = str(Path(step6_batch_config).resolve()) +failed_names = set() +if err_json.exists(): + try: + payload = json.loads(err_json.read_text(encoding="utf-8")) + except Exception: + payload = {} + for item in payload.get("failed_objects", []): + name = str(item.get("name", "")).strip() + if name: + failed_names.add(name) + for name in payload.get("failed_names", []): + n = str(name).strip() + if n: + failed_names.add(n) + +objects = cfg.get("objects", []) +if not isinstance(objects, list): + objects = [] + +kept = [] +dropped = [] +for obj in objects: + name = str(obj.get("name") or obj.get("id") or "").strip() + category = str(obj.get("category", "")).strip().lower() + if name and name in failed_names: + dropped.append((name, "failed_in_step6")) + continue + # Drop broken rigid/static objects so later steps don't crash. + if name and category in {"static", "rigid"}: + pose_dir = run_dir / "objects" / name / "pose_result" + has_pose = (pose_dir / "poses.json").exists() or (pose_dir / "poses_locked.json").exists() + if not has_pose: + dropped.append((name, "missing_pose_result")) + continue + kept.append(obj) + +cfg["objects"] = kept +cfg_out.parent.mkdir(parents=True, exist_ok=True) +cfg_out.write_text(json.dumps(cfg, indent=2, ensure_ascii=False), encoding="utf-8") +print(f"[effective-config] wrote {cfg_out} (kept={len(kept)}, dropped={len(dropped)})") +for name, reason in dropped: + print(f"[effective-config] drop {name}: {reason}") +PY + + if [[ -f "$cfg_out" ]]; then + state_set effective_config "$cfg_out" + fi + if [[ -f "$err_json" ]]; then + state_set step6_error_report "$err_json" + fi +} + +sync_pipeline_categories() { + local summary="$OUT/metadata/${NAME}_mask_summary.json" + local cfg_main="$OUT/recon_ready/$NAME/pipeline_config.json" + local cfg_eff="$OUT/recon_ready/$NAME/pipeline_config_effective.json" + if [[ ! -f "$summary" || ! -f "$cfg_main" ]]; then + return + fi + local cfg_list=("$cfg_main") + if [[ -f "$cfg_eff" ]]; then + cfg_list+=("$cfg_eff") + fi + python3 - "$summary" "${cfg_list[@]}" <<'PY' +import json +import sys +from pathlib import Path + +summary_path = Path(sys.argv[1]) +cfg_paths = [Path(x) for x in sys.argv[2:]] +summary = json.loads(summary_path.read_text(encoding="utf-8")) + +cat_by_name = {} +for o in summary.get("objects", []): + n = o.get("name") + c = o.get("category") + if isinstance(n, str) and n and isinstance(c, str) and c: + cat_by_name[n] = c + +for cfg_path in cfg_paths: + if not cfg_path.exists(): + continue + cfg = json.loads(cfg_path.read_text(encoding="utf-8")) + changed = [] + for o in cfg.get("objects", []): + n = o.get("name") + if n in cat_by_name and o.get("category") != cat_by_name[n]: + changed.append((n, o.get("category"), cat_by_name[n])) + o["category"] = cat_by_name[n] + if changed: + cfg_path.write_text(json.dumps(cfg, indent=2, ensure_ascii=False), encoding="utf-8") + print("[sync] Updated categories in", cfg_path) + for n, old, new in changed: + print(f"[sync] {n}: {old} -> {new}") +PY +} + +get_tracker_sample_stride() { + local cfg="$OUT/recon_ready/$NAME/pipeline_config.json" + local fallback="$BATCH_CONFIG" + if [[ ! -f "$cfg" ]]; then + echo "1" + return + fi + + python3 - "$cfg" "$fallback" <<'PY' +import json +import pathlib +import sys + +cfg_path = pathlib.Path(sys.argv[1]) +fallback = pathlib.Path(sys.argv[2]) +stride = 1 + +try: + cfg = json.loads(cfg_path.read_text(encoding="utf-8")) +except Exception: + print("1") + raise SystemExit + +batch_cfg = cfg.get("batch_config") +batch_path = None +if isinstance(batch_cfg, str) and batch_cfg.strip(): + batch_path = pathlib.Path(batch_cfg.strip()) + if not batch_path.is_absolute(): + batch_path = (cfg_path.parent / batch_path).resolve() +elif fallback.exists(): + batch_path = fallback + +if batch_path is not None and batch_path.exists(): + try: + payload = json.loads(batch_path.read_text(encoding="utf-8")) + stride = int(payload.get("tracker", {}).get("sample_stride", 1) or 1) + except Exception: + stride = 1 + +print(str(max(1, stride))) +PY +} + +lock_static_poses() { + local run_dir="$1" + local cfg + cfg="$(get_effective_config)" + if [[ "$LOCK_STATIC_ENABLED_BOOL" != "1" ]]; then + return + fi + if [[ ! -d "$run_dir" || ! -f "$cfg" ]]; then + return + fi + + "$OPG_PY" - "$run_dir" "$cfg" "$LOCK_STATIC_MODE_CANONICAL" <<'PY' +import json, sys +from pathlib import Path +import cv2 +import numpy as np + +run_dir = Path(sys.argv[1]) +cfg_path = Path(sys.argv[2]) +lock_mode = str(sys.argv[3]).strip().lower() +cfg = json.loads(cfg_path.read_text(encoding="utf-8")) + +static_names = { + str(o.get("name")) + for o in cfg.get("objects", []) + if str(o.get("category", "")).lower() == "static" +} +objects_root = run_dir / "objects" +if not objects_root.exists(): + raise SystemExit(0) + +for obj_dir in objects_root.iterdir(): + if not obj_dir.is_dir() or obj_dir.name not in static_names: + continue + pose_path = obj_dir / "pose_result" / "poses.json" + if not pose_path.exists(): + continue + poses = json.loads(pose_path.read_text(encoding="utf-8")) + frame_ids = sorted(int(k) for k in poses.keys() if str(k).isdigit()) + if not frame_ids: + continue + + mask_dir = obj_dir / "masks" + best_frame = None + best_area = -1 + if mask_dir.exists(): + for fid in frame_ids: + mp = mask_dir / f"{fid:06d}.png" + if not mp.exists(): + continue + m = cv2.imread(str(mp), cv2.IMREAD_GRAYSCALE) + if m is None: + continue + area = int((m > 0).sum()) + if area > best_area: + best_area, best_frame = area, fid + if best_frame is None: + best_frame = frame_ids[0] + anchor = np.asarray(poses[str(best_frame)], dtype=np.float64) + if anchor.shape != (4, 4): + print(f"[lock-static] skip {obj_dir.name}: invalid anchor pose shape {anchor.shape}") + continue + + if lock_mode == "full": + locked = {str(fid): poses[str(best_frame)] for fid in frame_ids} + elif lock_mode == "rot_only": + locked = {} + anchor_R = anchor[:3, :3] + for fid in frame_ids: + src = np.asarray(poses[str(fid)], dtype=np.float64) + if src.shape != (4, 4): + continue + out_pose = src.copy() + out_pose[:3, :3] = anchor_R + out_pose[3, :] = np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64) + locked[str(fid)] = out_pose.tolist() + if not locked: + print(f"[lock-static] skip {obj_dir.name}: no valid poses for rot_only lock") + continue + else: + print(f"[lock-static] skip {obj_dir.name}: unsupported mode {lock_mode}") + continue + + out = pose_path.parent / "poses_locked.json" + out.write_text(json.dumps(locked, indent=2), encoding="utf-8") + print(f"[lock-static] {obj_dir.name}: mode={lock_mode}, frame {best_frame} -> {out}") +PY +} + +lock_deform_pose() { + local obj_name="$1" + local lock_frame="$2" + local obj_root="$OUT/motion324_outputs/$NAME/$obj_name" + local world_json="$obj_root/poses_fp_world.json" + local cam_json="$obj_root/poses_fp_cam.json" + local mask_dir="$OUT/masks/$NAME/$obj_name" + + if [[ ! -f "$world_json" ]]; then + echo "[lock-deform] skip $obj_name: missing $world_json" + return + fi + + "$OPG_PY" - "$world_json" "$cam_json" "$mask_dir" "$obj_root" "$obj_name" "$lock_frame" <<'PY' +import json +import sys +from pathlib import Path + +import cv2 + +world_path = Path(sys.argv[1]) +cam_path = Path(sys.argv[2]) +mask_dir = Path(sys.argv[3]) +obj_root = Path(sys.argv[4]) +obj_name = sys.argv[5] +lock_frame = int(sys.argv[6]) + + +def load_pose(path: Path): + if not path.exists(): + return None + try: + data = json.loads(path.read_text(encoding="utf-8")) + except Exception: + return None + return data if isinstance(data, dict) else None + + +world_current = load_pose(world_path) +if not world_current: + print(f"[lock-deform] skip {obj_name}: invalid world poses") + raise SystemExit(0) + +world_backup_path = world_path.with_suffix(world_path.suffix + ".before_lock.json") +world_backup = load_pose(world_backup_path) +world_source = world_backup if world_backup else world_current +world_source_tag = "before_lock" if world_backup else "current" + +keys = [k for k in world_source.keys() if str(k).lstrip("-").isdigit()] +if keys: + keys = sorted(keys, key=lambda x: int(x)) +else: + keys = sorted(world_source.keys()) +if not keys: + print(f"[lock-deform] skip {obj_name}: empty pose keys") + raise SystemExit(0) + +anchor = keys[0] +best_area = -1 +anchor_source = "auto_max_mask" + +if lock_frame >= 0: + if str(lock_frame) in world_source: + anchor = str(lock_frame) + else: + candidates = [] + for k in keys: + try: + candidates.append((abs(int(k) - lock_frame), k)) + except Exception: + pass + if candidates: + candidates.sort(key=lambda x: x[0]) + anchor = candidates[0][1] + anchor_source = f"manual:{lock_frame}" +else: + if mask_dir.exists(): + for k in keys: + try: + fid = int(k) + except Exception: + continue + mp = mask_dir / f"frame_{fid:06d}.png" + if not mp.exists(): + continue + mask = cv2.imread(str(mp), cv2.IMREAD_GRAYSCALE) + if mask is None: + continue + area = int((mask > 0).sum()) + if area > best_area: + best_area = area + anchor = k + +# Report chosen anchor mask area when available. +if mask_dir.exists(): + try: + fid = int(anchor) + mp = mask_dir / f"frame_{fid:06d}.png" + if mp.exists(): + mask = cv2.imread(str(mp), cv2.IMREAD_GRAYSCALE) + if mask is not None: + best_area = int((mask > 0).sum()) + except Exception: + pass + + +def lock_pose(path: Path, data): + if not data: + return + anchor_pose = data.get(anchor) + if anchor_pose is None: + anchor_pose = data[next(iter(data.keys()))] + backup = path.with_suffix(path.suffix + ".before_lock.json") + if not backup.exists(): + backup.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8") + locked = {k: anchor_pose for k in data.keys()} + path.write_text(json.dumps(locked, indent=2, ensure_ascii=False), encoding="utf-8") + + +lock_pose(world_path, world_source) +cam_current = load_pose(cam_path) +cam_backup = load_pose(cam_path.with_suffix(cam_path.suffix + ".before_lock.json")) +cam_source = cam_backup if cam_backup else cam_current +lock_pose(cam_path, cam_source) + +pose_dir = obj_root / "pose_result" +pose_dir.mkdir(parents=True, exist_ok=True) +if world_path.exists(): + txt = world_path.read_text(encoding="utf-8") + (pose_dir / "poses_fp_world.json").write_text(txt, encoding="utf-8") + (pose_dir / "poses_world.json").write_text(txt, encoding="utf-8") +if cam_path.exists(): + txt = cam_path.read_text(encoding="utf-8") + (pose_dir / "poses_fp_cam.json").write_text(txt, encoding="utf-8") + (pose_dir / "poses.json").write_text(txt, encoding="utf-8") + +area_info = str(best_area) if best_area >= 0 else "n/a" +print( + f"[lock-deform] {obj_name}: anchor={anchor} ({anchor_source}), " + f"mask_area={area_info}, world_source={world_source_tag}" +) +PY +} + +get_video_fps_from_summary() { + local summary="$OUT/metadata/${NAME}_mask_summary.json" + if [[ ! -f "$summary" ]]; then + echo "10.0" + return + fi + python3 - "$summary" <<'PY' +import json +import sys +try: + data = json.load(open(sys.argv[1], "r", encoding="utf-8")) + fps = float(data.get("fps", 10.0) or 10.0) +except Exception: + fps = 10.0 +print(f"{fps:.6f}") +PY +} + +transcode_video_h264_inplace() { + local in_video="$1" + if [[ ! -f "$in_video" ]]; then + return 0 + fi + "$OPG_PY" - "$in_video" <<'PY' +import shutil +import subprocess +import sys +from pathlib import Path + +in_path = Path(sys.argv[1]) +ffmpeg_bin = shutil.which("ffmpeg") +if not ffmpeg_bin: + try: + import imageio_ffmpeg # type: ignore + ffmpeg_bin = imageio_ffmpeg.get_ffmpeg_exe() + except Exception: + ffmpeg_bin = None + +if not ffmpeg_bin: + print(f"[Warn] Skip h264 transcode (ffmpeg unavailable): {in_path}") + raise SystemExit(0) + +tmp = in_path.with_name(in_path.stem + "_h264_tmp.mp4") +cmd = [ + ffmpeg_bin, "-y", + "-i", str(in_path), + "-c:v", "libx264", + "-pix_fmt", "yuv420p", + "-movflags", "+faststart", + "-an", + str(tmp), +] +try: + subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + tmp.replace(in_path) +except Exception as ex: + print(f"[Warn] h264 transcode failed: {in_path} ({ex})") + if tmp.exists(): + tmp.unlink() +PY +} + +render_locked_deform_video() { + local obj_name="$1" + local out_video="$OUT/motion324_outputs/$NAME/$obj_name/pose_result/normal_video_locked.mp4" + local fps + fps="$(get_video_fps_from_summary)" + + if ! PYTHONPATH="$REPO:${PYTHONPATH:-}" "$OPG_PY" \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/render_deform_scale_video.py \ + --run-dir "$RUN_DIR" \ + --object-name "$obj_name" \ + --motion-output-root "$OUT/motion324_outputs" \ + --output "$out_video" \ + --fps "$fps"; then + echo "[Warn] Failed to render locked deform video for $obj_name" + return 0 + fi + + transcode_video_h264_inplace "$out_video" + echo "[OK] Locked pose preview: $out_video" +} + +lock_deform_world_mesh_frames() { + local obj_name="$1" + local lock_frame="$2" + local world_dir="$OUT/motion324_outputs/$NAME/$obj_name/world_mesh_frames" + if [[ ! -d "$world_dir" ]]; then + echo "[lock-deform-mesh] skip $obj_name: missing $world_dir" + return 0 + fi + + "$OPG_PY" - "$world_dir" "$obj_name" "$lock_frame" <<'PY' +import shutil +import sys +from pathlib import Path + +world_dir = Path(sys.argv[1]) +obj_name = sys.argv[2] +lock_frame = int(sys.argv[3]) + +frames = sorted(world_dir.glob("frame_*.obj")) +frame_ids = [] +for p in frames: + stem = p.stem + part = stem.split("_")[-1] + if part.isdigit(): + frame_ids.append((int(part), p)) +if not frame_ids: + print(f"[lock-deform-mesh] skip {obj_name}: no frame_*.obj in {world_dir}") + raise SystemExit(0) + +frame_ids.sort(key=lambda x: x[0]) +anchor_id, anchor_path = frame_ids[0] +anchor_src = "first" +if lock_frame >= 0: + best = min(frame_ids, key=lambda x: abs(x[0] - lock_frame)) + anchor_id, anchor_path = best + anchor_src = f"manual:{lock_frame}" + +copied = 0 +for fid, out_path in frame_ids: + if out_path.resolve() == anchor_path.resolve(): + continue + shutil.copy2(anchor_path, out_path) + copied += 1 + +print( + f"[lock-deform-mesh] {obj_name}: anchor={anchor_id} ({anchor_src}), " + f"frozen_frames={len(frame_ids)}, copied={copied}" +) +PY +} + +step1_labels() { + echo "[Step 1] Qwen labels" + local qwen_args=( + --video-path "$VIDEO" + --mode labels + --output-root "$OUT" + --qwen-backend "$QWEN_BACKEND" + --qwen-api-model "$QWEN_API_MODEL" + --qwen-api-model-list "$QWEN_API_MODEL_LIST" + --qwen-api-base-url "$QWEN_API_BASE_URL" + --qwen-api-key-env "$QWEN_API_KEY_ENV" + --max-new-tokens "$QWEN_MAX_NEW_TOKENS_INT" + --qwen-label-category-mode "$QWEN_LABEL_CATEGORY_MODE_EFFECTIVE" + --qwen-label-category-strict "$QWEN_LABEL_CATEGORY_STRICT_BOOL" + --qwen-category-pass "$QWEN_CATEGORY_PASS_EFFECTIVE" + --qwen-category-pass-strict "$QWEN_CATEGORY_PASS_STRICT_EFFECTIVE" + --qwen-category-max-new-tokens "$QWEN_CATEGORY_MAX_NEW_TOKENS_INT" + --keyframe-count 3 + --dynamic-source motion + --default-dynamic-category rigid + --batch-config "$BATCH_CONFIG" + ) + if [[ -n "$QWEN_CATEGORY_API_MODEL" ]]; then + qwen_args+=(--qwen-category-api-model "$QWEN_CATEGORY_API_MODEL") + fi + if [[ -n "$QWEN_LABEL_CATEGORY_MODEL" ]]; then + qwen_args+=(--qwen-label-category-model "$QWEN_LABEL_CATEGORY_MODEL") + fi + if [[ -n "$QWEN_MODEL" ]]; then + qwen_args+=(--qwen-model "$QWEN_MODEL") + fi + "$QWEN_PY" "$QWEN_SCRIPT" "${qwen_args[@]}" + + test -f "$OUT/metadata/${NAME}_labels.json" + state_set labels_json "$OUT/metadata/${NAME}_labels.json" +} + +step1_4_add_labels() { + echo "[Step 1.4] Add labels json" + local labels_json + labels_json="$(state_get labels_json)" + if [[ -z "$labels_json" ]]; then + labels_json="$OUT/metadata/${NAME}_labels.json" + fi + if [[ ! -f "$labels_json" ]]; then + echo "ERROR: labels json not found: $labels_json" >&2 + echo "Run step 1 first, or provide a workspace that already has labels." >&2 + exit 1 + fi + + local add_labels="$ADD_LABELS" + if [[ -z "${add_labels// }" && -t 0 ]]; then + read -r -p "Labels to add (comma-separated): " add_labels + fi + if [[ -z "${add_labels// }" ]]; then + echo "ERROR: no labels provided. Pass --add-labels or type labels interactively." >&2 + exit 1 + fi + + local add_args=( + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/add_video_labels.py + --labels-json "$labels_json" + --add-labels "$add_labels" + --default-category "$ADD_LABEL_CATEGORY" + --print-json + ) + if [[ "$ADD_LABEL_OVERWRITE_CATEGORY_BOOL" == "1" ]]; then + add_args+=(--overwrite-category) + fi + "$OPG_PY" "${add_args[@]}" + + state_set labels_json "$labels_json" +} + +step1_5_prune_labels() { + echo "[Step 1.5] Prune labels json" + local labels_json + labels_json="$(state_get labels_json)" + if [[ -z "$labels_json" ]]; then + labels_json="$OUT/metadata/${NAME}_labels.json" + fi + if [[ ! -f "$labels_json" ]]; then + echo "ERROR: labels json not found: $labels_json" >&2 + echo "Run step 1 first, or provide a workspace that already has labels." >&2 + exit 1 + fi + + local drop_labels="$PRUNE_LABELS" + if [[ -z "${drop_labels// }" && -t 0 ]]; then + read -r -p "Labels to remove (comma-separated): " drop_labels + fi + if [[ -z "${drop_labels// }" ]]; then + echo "ERROR: no labels provided. Pass --prune-labels or type labels interactively." >&2 + exit 1 + fi + + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/prune_video_labels.py \ + --labels-json "$labels_json" \ + --drop-labels "$drop_labels" \ + --print-json + + state_set labels_json "$labels_json" +} + +step2_masks() { + echo "[Step 2] SAM3 masks" + local sam_args=( + --video-path "$VIDEO" + --mode masks + --labels-json "$OUT/metadata/${NAME}_labels.json" + --output-root "$OUT" + --qwen-label-category-mode "$QWEN_LABEL_CATEGORY_MODE_EFFECTIVE" + --qwen-label-category-strict "$QWEN_LABEL_CATEGORY_STRICT_BOOL" + --qwen-category-pass "$QWEN_CATEGORY_PASS_EFFECTIVE" + --qwen-category-pass-strict "$QWEN_CATEGORY_PASS_STRICT_EFFECTIVE" + --min-obj-area "$SAM_MIN_OBJ_AREA_INT" + --sam3-ckpt "${SAM3_CKPT:-/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/third_party/sam3/checkpoints/sam3/sam3.pt}" + --batch-config "$BATCH_CONFIG" + ) + if [[ -n "${SAM3_SERVER_QUEUE:-}" ]]; then + echo "[Step 2] 走常驻 sam3-server (queue=$SAM3_SERVER_QUEUE)" + local argv_json + argv_json="$(printf '%s\n' "${sam_args[@]}" | "$OPG_PY" -c 'import json,sys; print(json.dumps([l.rstrip("\n") for l in sys.stdin]))')" + "$OPG_PY" "$REPO/tools/model_server/client.py" --queue "$SAM3_SERVER_QUEUE" --op masks \ + --args "{\"argv\": $argv_json, \"video_name\": \"$NAME\"}" + else + "$SAM3_PY" "$QWEN_SCRIPT" "${sam_args[@]}" + fi + + test -f "$OUT/metadata/${NAME}_mask_summary.json" + state_set mask_summary "$OUT/metadata/${NAME}_mask_summary.json" + + local obj_count + obj_count="$("$OPG_PY" - "$OUT/metadata/${NAME}_mask_summary.json" <<'PY' +import json +import sys +from pathlib import Path + +summary_path = Path(sys.argv[1]) +try: + summary = json.loads(summary_path.read_text(encoding="utf-8")) +except Exception: + print("-1") + raise SystemExit +objs = summary.get("objects", []) +if not isinstance(objs, list): + print("-1") + raise SystemExit +print(len(objs)) +PY +)" + if [[ "$obj_count" == "-1" ]]; then + echo "ERROR: invalid mask summary format: $OUT/metadata/${NAME}_mask_summary.json" >&2 + exit 1 + fi + if [[ "$obj_count" -eq 0 ]]; then + echo "ERROR: Step 2 produced 0 objects. Pipeline would fail at step 6." >&2 + echo "Hint: adjust labels/prompts (step 1) or lower --min-obj-area in qwen_sam3_video_masks.py run." >&2 + exit 1 + fi +} + +step2_5_merge_mask_labels() { + echo "[Step 2.5] Merge two label masks" + local merge_labels="$MERGE_MASK_LABELS" + local merge_category="$MERGE_MASK_CATEGORY" + local merge_output_label="$MERGE_MASK_OUTPUT_LABEL" + + if [[ -z "${merge_labels// }" && -t 0 ]]; then + read -r -p "Source labels to merge (exactly two, comma-separated): " merge_labels + fi + if [[ -z "${merge_labels// }" ]]; then + echo "ERROR: no source labels provided. Pass --merge-mask-labels A,B." >&2 + exit 1 + fi + + if [[ -z "${merge_category// }" && -t 0 ]]; then + read -r -p "Merged object category (static|rigid|deform): " merge_category + fi + if [[ -z "${merge_category// }" ]]; then + echo "ERROR: no category provided. Pass --merge-mask-category static|rigid|deform." >&2 + exit 1 + fi + + local merge_args=( + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/merge_video_label_masks.py + --workspace-root "$OUT" + --scene-name "$NAME" + --source-labels "$merge_labels" + --category "$merge_category" + ) + if [[ -n "${merge_output_label// }" ]]; then + merge_args+=(--merged-label "$merge_output_label") + fi + "$OPG_PY" "${merge_args[@]}" + + state_set labels_json "$OUT/metadata/${NAME}_labels.json" + state_set mask_summary "$OUT/metadata/${NAME}_mask_summary.json" +} + +step3_build_motion_inputs() { + echo "[Step 3] Build Motion324 deform inputs" + local build_args=( + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/build_deform_videos.py + --summary "$OUT/metadata/${NAME}_mask_summary.json" + --output-root "$OUT/motion324_inputs" + --video-path "$VIDEO" + ) + if [[ "$MOTION_NORMALIZE_ZOOM_BOOL" == "1" ]]; then + build_args+=( + --normalize-zoom 1 + --normalize-target-ratio "$MOTION_NORMALIZE_TARGET_RATIO" + --normalize-smooth "$MOTION_NORMALIZE_SMOOTH" + --normalize-out-size "$MOTION_NORMALIZE_OUT_SIZE" + ) + fi + local manifest + manifest="$($OPG_PY "${build_args[@]}")" + + echo "deform manifest: $manifest" + test -f "$manifest" + state_set deform_manifest "$manifest" +} + +step4_run_motion324() { + echo "[Step 4] Run Motion324" + local deform_manifest + deform_manifest="$(state_get deform_manifest)" + if [[ -z "$deform_manifest" ]]; then + deform_manifest="$OUT/motion324_inputs/$NAME/deform_manifest.json" + fi + if [[ ! -f "$deform_manifest" ]]; then + echo "ERROR: deform manifest missing: $deform_manifest" >&2 + exit 1 + fi + + local obj_list=() + mapfile -t obj_list < <("$OPG_PY" - "$deform_manifest" </dev/null + + test -f "$OUT/motion324_outputs/$NAME/manifest.json" + state_set motion_manifest "$OUT/motion324_outputs/$NAME/manifest.json" +} + +step6_reconstruct_rigid() { + echo "[Step 6] Run static+rigid pipeline (recon_backbone=${RECON_BACKBONE_CANONICAL})" + sync_pipeline_categories + local cfg_rigid="$OUT/recon_ready/$NAME/pipeline_config_rigid.json" + local step6_batch_config + step6_batch_config="$(prepare_step6_batch_config "$RECON_BACKBONE_CANONICAL")" + + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/filter_pipeline_config.py \ + --input "$OUT/recon_ready/$NAME/pipeline_config.json" \ + --output "$cfg_rigid" \ + --exclude-category deform \ + --drop-missing-masks + + local rigid_count + rigid_count="$("$OPG_PY" - "$cfg_rigid" <<'PY' +import json +import sys + +cfg = json.load(open(sys.argv[1], "r", encoding="utf-8")) +objs = cfg.get("objects", []) +print(len(objs) if isinstance(objs, list) else 0) +PY +)" + if [[ "$rigid_count" -le 0 ]]; then + echo "ERROR: no valid static/rigid objects remain after filtering masks." >&2 + echo "Hint: run step 2 to regenerate masks, or restore at least one masks//frame_*.png." >&2 + exit 1 + fi + + "$OPG_PY" - "$cfg_rigid" "$step6_batch_config" <<'PY' +import json +import sys +from pathlib import Path + +cfg_path = Path(sys.argv[1]) +batch_path = Path(sys.argv[2]).resolve() +cfg = json.loads(cfg_path.read_text(encoding="utf-8")) +cfg["batch_config"] = str(batch_path) +cfg_path.write_text(json.dumps(cfg, indent=2, ensure_ascii=False), encoding="utf-8") +print(f"[Step 6] batch_config={batch_path}") +PY + state_set step6_recon_backbone "$RECON_BACKBONE_CANONICAL" + state_set step6_batch_config "$step6_batch_config" + + local log="$OUT/${NAME}_recon.log" + ( + cd "$REPO" + if [[ -n "${OPG_SERVER_QUEUE:-}" ]]; then + echo "[Step 6] 走常驻 opg-server (queue=$OPG_SERVER_QUEUE)" + "$OPG_PY" tools/model_server/client.py --queue "$OPG_SERVER_QUEUE" --op step6 \ + --args "{\"config\": \"$cfg_rigid\"}" | tee "$log" + else + "$OPG_PY" pipeline.py --config "$cfg_rigid" --continue-on-object-error 1 | tee "$log" + fi + ) + + local run_root + run_root="$(grep -m1 'Done. Output:' "$log" | sed 's/.*Done. Output: //')" + if [[ -z "$run_root" ]]; then + run_root="$(ls -1dt "$OUT"/video_pipeline_* | head -n1)" + fi + RUN_DIR="$run_root/$NAME" + test -d "$RUN_DIR" + write_run_workspace_marker "$RUN_DIR" + write_effective_config_from_step6 "$RUN_DIR" + state_set run_dir "$RUN_DIR" + lock_static_poses "$RUN_DIR" +} + +step7_plane_and_rigid_physics() { + echo "[Step 7] Plane + rigid/static physics" + sync_pipeline_categories + resolve_run_dir + local cfg_effective + cfg_effective="$(get_effective_config)" + local plane_pcd + plane_pcd="$(choose_plane_pcd)" + lock_static_poses "$RUN_DIR" + + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/fit_plane_align.py \ + --run-dir "$RUN_DIR" \ + --config "$cfg_effective" \ + --pcd "$plane_pcd" \ + --static-only \ + --num-planes "$PLANE_NUM_INT" \ + --bottom-percent "$PLANE_BOTTOM_FLOAT" \ + --gravity-sign-mode "$GRAVITY_SIGN_MODE" \ + --gravity-sign-samples "$GRAVITY_SIGN_SAMPLES_INT" \ + --camera-up-prior 1 \ + --camera-up-samples 5 \ + --out "$RUN_DIR/alignment_plane.json" + + if [[ "$PHYSICS_ENABLE_BOOL" != "1" ]]; then + echo "[Step 7] Physics disabled; fitted plane only." + return + fi + + local phys_flags=() + if [[ "$LOCK_STATIC_ENABLED_BOOL" == "1" ]]; then + phys_flags+=(--use-locked-static) + fi + if [[ "$PHYSICS_ALLOW_DOWN_BOOL" == "1" ]]; then + phys_flags+=(--allow-down) + fi + if [[ "$PHYSICS_CONTACT_BOOL" == "1" ]]; then + phys_flags+=(--contact-objects) + fi + + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/physics_project_z.py \ + --run-dir "$RUN_DIR" \ + --config "$cfg_effective" \ + --alignment "$RUN_DIR/alignment_plane.json" \ + --plane-z zero \ + --bottom-percent "$PHYSICS_BOTTOM_FLOAT" \ + --iters "$PHYSICS_ITERS_INT" \ + --max-drop "$PHYSICS_MAX_DROP_FLOAT" \ + "${phys_flags[@]}" +} + +step8_deform_world_mesh() { + echo "[Step 8] Deform pose + world mesh" + sync_pipeline_categories + resolve_run_dir + + local motion_manifest + motion_manifest="$(state_get motion_manifest)" + if [[ -z "$motion_manifest" ]]; then + motion_manifest="$OUT/motion324_outputs/$NAME/manifest.json" + fi + if [[ ! -f "$motion_manifest" ]]; then + echo "ERROR: motion manifest missing: $motion_manifest" >&2 + exit 1 + fi + + local obj_names=() + mapfile -t obj_names < <("$OPG_PY" - "$motion_manifest" <<'PY' +import json, sys +d = json.load(open(sys.argv[1])) +for o in d.get("objects", []): + print(o["name"]) +PY +) + + if [[ "${#obj_names[@]}" -eq 0 ]]; then + echo "[Step 8] No deform objects found." + return + fi + + if [[ ! -x "$BLENDER_BIN" ]]; then + echo "ERROR: Blender not found: $BLENDER_BIN" >&2 + exit 1 + fi + + local mask_stride + mask_stride="$(get_tracker_sample_stride)" + echo "[Step 8] mask stride from tracker: $mask_stride" + local deform_pose_flags=() + if [[ "$DEFORM_FORCE_POSES" == "1" ]]; then + deform_pose_flags+=(--force-poses) + fi + if [[ "$DEFORM_FORCE_SCALE" == "1" ]]; then + deform_pose_flags+=(--force-scale) + fi + if [[ "$DEFORM_RENDER_VIDEO" == "1" ]]; then + deform_pose_flags+=(--render-video) + fi + if [[ "$DEFORM_EXPORT_VIDEO_FRAMES_BOOL" == "1" ]]; then + deform_pose_flags+=(--export-video-frames) + fi + + local obj_name="" + for obj_name in "${obj_names[@]}"; do + [[ -z "$obj_name" ]] && continue + + local dargs=( + --run-dir "$RUN_DIR" + --mask-summary "$OUT/metadata/${NAME}_mask_summary.json" + --object-name "$obj_name" + --motion-output-root "$OUT/motion324_outputs" + --manifest "$motion_manifest" + --pose-mode "${DEFORM_POSE_MODE:-frame_track}" + --frame-step 1 + --mask-stride "$mask_stride" + "${deform_pose_flags[@]}" + --blender-bin "$BLENDER_BIN" + --blender-lib "$BLENDER_LIB" + ) + if [[ -n "${OPG_SERVER_QUEUE:-}" ]]; then + echo "[Step 8] deform 走常驻 opg-server (queue=$OPG_SERVER_QUEUE)" + local argv_json + argv_json="$(printf '%s\n' "${dargs[@]}" | "$OPG_PY" -c 'import json,sys; print(json.dumps([l.rstrip("\n") for l in sys.stdin]))')" + "$OPG_PY" "$REPO/tools/model_server/client.py" --queue "$OPG_SERVER_QUEUE" --op deform \ + --args "{\"argv\": $argv_json}" + else + PYTHONPATH="$REPO/oneposeviagen/fpose:${PYTHONPATH:-}" \ + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/deform_pose_pipeline.py \ + "${dargs[@]}" + fi + + if [[ "$DEFORM_LOCK_POSE_BOOL" == "1" ]]; then + lock_deform_pose "$obj_name" "$DEFORM_LOCK_FRAME_INT" + if [[ "$DEFORM_RENDER_VIDEO" == "1" ]]; then + render_locked_deform_video "$obj_name" + fi + fi + + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/deform_apply_world_pose.py \ + --mesh-frames "$OUT/motion324_outputs/$NAME/$obj_name/mesh_frames" \ + --poses-world "$OUT/motion324_outputs/$NAME/$obj_name/poses_fp_world.json" \ + --scale 1.0 \ + --scale-json "$OUT/motion324_outputs/$NAME/$obj_name/scale.json" \ + --output-dir "$OUT/motion324_outputs/$NAME/$obj_name/world_mesh_frames" + + if [[ "$DEFORM_LOCK_POSE_BOOL" == "1" && "$DEFORM_LOCK_MESH_BOOL" == "1" ]]; then + lock_deform_world_mesh_frames "$obj_name" "$DEFORM_LOCK_FRAME_INT" + fi + done +} + +step9_deform_physics_sync() { + echo "[Step 9] Deform physics sync" + sync_pipeline_categories + resolve_run_dir + local cfg_effective + cfg_effective="$(get_effective_config)" + ensure_alignment + + if [[ "$PHYSICS_ENABLE_BOOL" != "1" ]]; then + echo "[Step 9] Physics disabled; skip deform physics sync." + return + fi + + local phys_flags=() + if [[ "$PHYSICS_ALLOW_DOWN_BOOL" == "1" ]]; then + phys_flags+=(--allow-down) + fi + if [[ "$PHYSICS_CONTACT_BOOL" == "1" ]]; then + phys_flags+=(--contact-objects) + fi + + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/physics_project_z_deform_seq.py \ + --run-dir "$RUN_DIR" \ + --config "$cfg_effective" \ + --alignment "$RUN_DIR/alignment_plane.json" \ + --motion-output-root "$OUT/motion324_outputs" \ + --video-name "$NAME" \ + --manifest "$OUT/motion324_outputs/$NAME/manifest.json" \ + --deform-frames-dir world_mesh_frames \ + --deform-output-frames-dir world_mesh_frames_physics \ + --rigid-pose-name poses_physics.json \ + --plane-z zero \ + --bottom-percent "$PHYSICS_BOTTOM_FLOAT" \ + --iters "$PHYSICS_ITERS_INT" \ + --max-drop "$PHYSICS_MAX_DROP_FLOAT" \ + "${phys_flags[@]}" +} + +step10_export_scene_mesh() { + echo "[Step 10] Export unified scene mesh frames" + sync_pipeline_categories + resolve_run_dir + local cfg_effective + cfg_effective="$(get_effective_config)" + local mesh_args=( + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/export_scene_mesh_frames.py + --run-dir "$RUN_DIR" + --config "$cfg_effective" + --output-dir "$RUN_DIR/scene_mesh_frames_all_world" + --deform-root "$OUT/motion324_outputs" + --deform-manifest "$OUT/motion324_outputs/$NAME/manifest.json" + --alignment "$RUN_DIR/alignment_plane.json" + ) + if [[ "$PHYSICS_ENABLE_BOOL" == "1" ]]; then + mesh_args+=(--deform-frames-dir world_mesh_frames_physics --pose-name poses_physics.json) + else + mesh_args+=(--deform-frames-dir world_mesh_frames) + fi + "$OPG_PY" "${mesh_args[@]}" +} + +ensure_alignment() { + local cfg_effective + cfg_effective="$(get_effective_config)" + local plane_pcd + plane_pcd="$(choose_plane_pcd)" + local align="$RUN_DIR/alignment_plane.json" + if [[ -f "$align" ]]; then + local keep="0" + keep="$(python3 - "$align" "$GRAVITY_SIGN_MODE" <<'PY' +import json, sys +path = sys.argv[1] +expected_mode = sys.argv[2].strip().lower() +try: + data = json.load(open(path, "r", encoding="utf-8")) +except Exception: + print("0") + raise SystemExit +stats = data.get("stats", {}) +mode = str(stats.get("gravity_sign_mode", "camera_up")).strip().lower() +camera_ok = int(stats.get("camera_up_prior", 0)) == 1 +print("1" if mode == expected_mode and camera_ok else "0") +PY +)" + if [[ "$keep" == "1" ]]; then + return + fi + echo "[Info] Re-fitting alignment with camera-up prior: $align" + fi + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/fit_plane_align.py \ + --run-dir "$RUN_DIR" \ + --config "$cfg_effective" \ + --pcd "$plane_pcd" \ + --static-only \ + --num-planes "$PLANE_NUM_INT" \ + --bottom-percent "$PLANE_BOTTOM_FLOAT" \ + --gravity-sign-mode "$GRAVITY_SIGN_MODE" \ + --gravity-sign-samples "$GRAVITY_SIGN_SAMPLES_INT" \ + --camera-up-prior 1 \ + --camera-up-samples 5 \ + --out "$align" +} + +step11_export_rigid_glb() { + echo "[Step 11] Export static+rigid GLB" + sync_pipeline_categories + resolve_run_dir + local cfg_effective + cfg_effective="$(get_effective_config)" + lock_static_poses "$RUN_DIR" + ensure_alignment + + local glb_args=( + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/export_scene_glb_anim.py + --run-dir "$RUN_DIR" + --config "$cfg_effective" + --output "$RUN_DIR/scene_anim_blender_aligned_plane_v3.glb" + --coord blender_zup + --alignment "$RUN_DIR/alignment_plane.json" + --add-plane + --plane-z static_minz + ) + if [[ "$LOCK_STATIC_ENABLED_BOOL" == "1" ]]; then + glb_args+=(--use-locked-static) + fi + "$OPG_PY" "${glb_args[@]}" +} + +step12_export_rigid_physics_glb() { + echo "[Step 12] Export static+rigid physics GLB" + sync_pipeline_categories + resolve_run_dir + local cfg_effective + cfg_effective="$(get_effective_config)" + lock_static_poses "$RUN_DIR" + ensure_alignment + + if [[ "$PHYSICS_ENABLE_BOOL" == "1" ]] && ! compgen -G "$RUN_DIR/objects/*/pose_result/poses_physics.json" >/dev/null; then + echo "[Warn] poses_physics.json not found for some objects. Run step 7 first." + fi + + local glb_args=( + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/export_scene_glb_anim.py + --run-dir "$RUN_DIR" + --config "$cfg_effective" + --output "$RUN_DIR/scene_anim_blender_physics_projected_contact_v3_yup.glb" + --coord blender_zup + --alignment "$RUN_DIR/alignment_plane.json" + --add-plane + --plane-z zero + ) + if [[ "$PHYSICS_ENABLE_BOOL" == "1" ]]; then + glb_args+=(--pose-name poses_physics.json) + fi + if [[ "$LOCK_STATIC_ENABLED_BOOL" == "1" ]]; then + glb_args+=(--use-locked-static) + fi + "$OPG_PY" "${glb_args[@]}" +} + +step13_export_full_glb_prephysics() { + echo "[Step 13] Export full-scene GLB pre-physics (with deform animation, no-plane, UV-seam-safe)" + sync_pipeline_categories + resolve_run_dir + local cfg_effective + cfg_effective="$(get_effective_config)" + lock_static_poses "$RUN_DIR" + ensure_alignment + + "$OPG_PY" /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/export_scene_glb_with_deform.py \ + --run-dir "$RUN_DIR" \ + --config "$cfg_effective" \ + --motion-output-root "$OUT/motion324_outputs" \ + --motion-manifest "$OUT/motion324_outputs/$NAME/manifest.json" \ + --deform-frames-dir world_mesh_frames \ + --output "$RUN_DIR/scene_anim_blender_aligned_plane_with_deform_prephysics.glb" \ + --no-plane \ + --coord blender_zup \ + --alignment "$RUN_DIR/alignment_plane.json" \ + --blender-bin "$BLENDER_BIN" \ + --blender-lib "$BLENDER_LIB" +} + +step14_export_full_glb_physics() { + echo "[Step 14] Export full-scene GLB physics (with deform animation, UV-seam-safe)" + sync_pipeline_categories + resolve_run_dir + local cfg_effective + cfg_effective="$(get_effective_config)" + lock_static_poses "$RUN_DIR" + ensure_alignment + + local export_args=( + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/export_scene_glb_with_deform.py + --run-dir "$RUN_DIR" + --config "$cfg_effective" + --motion-output-root "$OUT/motion324_outputs" + --motion-manifest "$OUT/motion324_outputs/$NAME/manifest.json" + --output "$RUN_DIR/scene_anim_blender_physics_with_deform.glb" + --coord blender_zup + --alignment "$RUN_DIR/alignment_plane.json" + --plane-z zero + --blender-bin "$BLENDER_BIN" + --blender-lib "$BLENDER_LIB" + ) + if [[ "$PHYSICS_ENABLE_BOOL" == "1" ]]; then + export_args+=(--deform-frames-dir world_mesh_frames_physics --pose-name poses_physics.json) + else + export_args+=(--deform-frames-dir world_mesh_frames) + fi + "$OPG_PY" "${export_args[@]}" +} + +step15_generate_intrinsic_hdr_exr() { + echo "[Step 15] Generate intrinsic HDR EXR from input video first frame" + resolve_run_dir + + local video_input out_exr + video_input="$RUN_DIR/${NAME}.mp4" + if [[ ! -f "$video_input" ]]; then + video_input="$VIDEO" + fi + [[ -f "$video_input" ]] || { echo "ERROR: input video not found for step 15: $video_input" >&2; exit 1; } + [[ -f "$INTRHDR_RUNNER" ]] || { echo "ERROR: HDR runner not found: $INTRHDR_RUNNER" >&2; exit 1; } + [[ -f "$INTRHDR_REPO/inference.py" ]] || { echo "ERROR: IntrinsicHDR repo missing inference.py: $INTRHDR_REPO" >&2; exit 1; } + [[ -x "$HDR_PY" ]] || { echo "ERROR: HDR python not found: $HDR_PY" >&2; exit 1; } + + out_exr="$(default_step15_hdr_path)" + mkdir -p "$(dirname "$out_exr")" + bash "$INTRHDR_RUNNER" \ + --video "$video_input" \ + --output "$out_exr" \ + --project-dir "$INTRHDR_REPO" \ + --python "$HDR_PY" +} + +find_flux_ref_image() { + local run_dir="$1" + local obj_name="$2" + local preferred_mode="$3" + "$OPG_PY" - "$run_dir" "$obj_name" "$preferred_mode" <<'PY' +import json +import pathlib +import sys + +run_dir = pathlib.Path(sys.argv[1]).resolve() +obj_name = sys.argv[2].strip() +preferred_mode = sys.argv[3].strip().lower() + +root = run_dir / "objects" / "fluxoutput" / obj_name +if not root.is_dir(): + raise SystemExit(f"ERROR: flux output dir not found: {root}") + +mode_dirs = [p for p in root.iterdir() if p.is_dir()] +if not mode_dirs: + raise SystemExit(f"ERROR: no mode directories in flux output: {root}") + +ordered = [] +if preferred_mode: + pref = root / preferred_mode + if pref.is_dir(): + ordered.append(pref) +for p in sorted(mode_dirs): + if p not in ordered: + ordered.append(p) + +candidates = [] + +def add_candidate(path: pathlib.Path): + if path.is_file(): + candidates.append((path.stat().st_mtime, path)) + +for mode_dir in ordered: + latest_json = mode_dir / "latest.json" + if latest_json.is_file(): + try: + payload = json.loads(latest_json.read_text(encoding="utf-8")) + except Exception: + payload = {} + final_output = str(payload.get("final_output", "")).strip() + if final_output: + add_candidate(pathlib.Path(final_output)) + +if not candidates: + for mode_dir in ordered: + for run_info in mode_dir.glob("*/run_info.json"): + try: + payload = json.loads(run_info.read_text(encoding="utf-8")) + except Exception: + continue + final_output = str(payload.get("final_output", "")).strip() + if final_output: + add_candidate(pathlib.Path(final_output)) + +if not candidates: + for mode_dir in ordered: + for png in mode_dir.glob("*/*_seed*.png"): + add_candidate(png) + +if not candidates: + raise SystemExit( + f"ERROR: no flux reference image found for object '{obj_name}' under {root}" + ) + +candidates.sort(key=lambda t: t[0]) +print(str(candidates[-1][1].resolve())) +PY +} + +step16_rerun_failed_step6_objects() { + echo "[Step 16] Rerun failed step-6 objects + refresh point clouds" + sync_pipeline_categories + resolve_run_dir + + local cfg_main="$OUT/recon_ready/$NAME/pipeline_config.json" + local cfg_effective="$OUT/recon_ready/$NAME/pipeline_config_effective.json" + local err_json="$RUN_DIR/object_errors_step6.json" + local rerun_ref_map_effective="$RERUN_REF_MAP" + local rerun_ref_image_effective="$RERUN_REF_IMAGE" + if [[ "$RERUN_USE_FLUX_REF_BOOL" == "1" ]]; then + local flux_ref_pairs=() + local obj_name="" + local obj_ref_image="" + while IFS= read -r obj_name; do + [[ -z "$obj_name" ]] && continue + obj_ref_image="$(find_flux_ref_image "$RUN_DIR" "$obj_name" "$FLUX_MODE_CANONICAL")" + if [[ -z "$obj_ref_image" || ! -f "$obj_ref_image" ]]; then + echo "ERROR: failed to resolve flux ref image for '$obj_name'." >&2 + exit 1 + fi + echo "[Step 16] use flux ref image [$obj_name]: $obj_ref_image" + flux_ref_pairs+=("$obj_name" "$obj_ref_image") + done < <(parse_csv_items "$RERUN_OBJECTS") + if [[ "${#flux_ref_pairs[@]}" -le 0 ]]; then + echo "ERROR: --flux found no valid objects in --rerun-objects." >&2 + exit 1 + fi + + local ref_map_json="$RUN_DIR/.step16_ref_map_flux.json" + "$OPG_PY" - "$ref_map_json" "${flux_ref_pairs[@]}" <<'PY' +import json +import pathlib +import sys + +out = pathlib.Path(sys.argv[1]).resolve() +args = sys.argv[2:] +if not args or len(args) % 2 != 0: + raise SystemExit("ERROR: internal error building flux ref-map (invalid arg pairs)") + +payload = {} +for i in range(0, len(args), 2): + obj = args[i].strip() + img = pathlib.Path(args[i + 1]).resolve() + payload[obj] = {"ref_image": str(img)} + +out.write_text(json.dumps(payload, indent=2), encoding="utf-8") +print(f"[Step 16] generated ref-map: {out}") +PY + rerun_ref_map_effective="$ref_map_json" + rerun_ref_image_effective="" + fi + + if [[ -n "$rerun_ref_image_effective" ]]; then + local obj_name="$RERUN_SINGLE_OBJECT" + if [[ -z "$obj_name" ]]; then + obj_name="$(extract_single_csv_item "$RERUN_OBJECTS")" + fi + local ref_map_json="$RUN_DIR/.step16_ref_map_${obj_name}.json" + "$OPG_PY" - "$ref_map_json" "$obj_name" "$rerun_ref_image_effective" <<'PY' +import json +import pathlib +import sys + +out = pathlib.Path(sys.argv[1]).resolve() +obj = sys.argv[2] +img = str(pathlib.Path(sys.argv[3]).resolve()) +payload = {obj: {"ref_image": img}} +out.write_text(json.dumps(payload, indent=2), encoding="utf-8") +print(f"[Step 16] generated ref-map: {out}") +PY + rerun_ref_map_effective="$ref_map_json" + fi + + local rerun_args=( + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/rerun_step6_objects.py + --run-dir "$RUN_DIR" + --config "$cfg_main" + --error-report "$err_json" + --output-effective-config "$cfg_effective" + ) + if [[ "$RERUN_ANCHOR_FRAME_INT" -ge 0 ]]; then + rerun_args+=(--anchor-frame "$RERUN_ANCHOR_FRAME_INT") + fi + if [[ -n "$rerun_ref_map_effective" ]]; then + rerun_args+=(--ref-map "$rerun_ref_map_effective") + fi + if [[ -n "$RERUN_OBJECTS" ]]; then + rerun_args+=(--objects "$RERUN_OBJECTS" --only-failed 0) + else + rerun_args+=(--only-failed "$RERUN_ONLY_FAILED_BOOL") + fi + + "$OPG_PY" "${rerun_args[@]}" + if [[ -f "$cfg_effective" ]]; then + state_set effective_config "$cfg_effective" + fi + if [[ -f "$err_json" ]]; then + state_set step6_error_report "$err_json" + fi +} + +step17_render_fullscene_deform_white_split_video() { + echo "[Step 17] Render full-scene + deform white-model split video" + sync_pipeline_categories + resolve_run_dir + lock_static_poses "$RUN_DIR" + ensure_alignment + + local cfg_effective + cfg_effective="$(get_effective_config)" + local result_npz="$RUN_DIR/results/result.npz" + if [[ ! -f "$result_npz" ]]; then + echo "ERROR: missing $result_npz" >&2 + exit 1 + fi + if [[ ! -x "$BLENDER_BIN" ]]; then + echo "ERROR: Blender not found: $BLENDER_BIN" >&2 + exit 1 + fi + + local motion_manifest="$OUT/motion324_outputs/$NAME/manifest.json" + + local mesh_dir="$RUN_DIR/scene_mesh_frames_all_world_deform_noalign" + local render_video="$RUN_DIR/fullscene_deform_objseq_white_clay_camview.mp4" + local split_video="$RUN_DIR/fullscene_deform_objseq_white_left_rgb_right_split10_h264.mp4" + local split_alias="$RUN_DIR/fullscene_deform_objseq_white_clay_split10_h264.mp4" + local rgb_video="$RUN_DIR/${NAME}.mp4" + if [[ ! -f "$rgb_video" ]]; then + rgb_video="$VIDEO" + fi + if [[ ! -f "$rgb_video" ]]; then + echo "ERROR: RGB video not found in RUN_DIR or --video path." >&2 + exit 1 + fi + + local num_frames + num_frames="$("$OPG_PY" - "$result_npz" <<'PY' +import numpy as np +import sys +d = np.load(sys.argv[1]) +print(int(d["extrinsics"].shape[0])) +PY +)" + if [[ -z "$num_frames" || "$num_frames" -le 0 ]]; then + echo "ERROR: invalid frame count from $result_npz" >&2 + exit 1 + fi + + local tracker_stride + tracker_stride="$(get_tracker_sample_stride)" + if [[ -z "$tracker_stride" || "$tracker_stride" -le 0 ]]; then + tracker_stride=1 + fi + local rgb_select_info rgb_select_expr rgb_selected_frames rgb_src_frames rgb_first_idx rgb_last_idx + rgb_select_info="$(compute_rgb_select_expr "$rgb_video" "$num_frames" "$tracker_stride")" + rgb_select_expr="$(printf '%s\n' "$rgb_select_info" | sed -n '1p')" + rgb_selected_frames="$(printf '%s\n' "$rgb_select_info" | sed -n '2p')" + rgb_src_frames="$(printf '%s\n' "$rgb_select_info" | sed -n '3p')" + rgb_first_idx="$(printf '%s\n' "$rgb_select_info" | sed -n '4p')" + rgb_last_idx="$(printf '%s\n' "$rgb_select_info" | sed -n '5p')" + if [[ -z "$rgb_select_expr" ]]; then + rgb_select_expr="not(mod(n,1))" + fi + if [[ -z "$rgb_selected_frames" ]]; then + rgb_selected_frames=0 + fi + if [[ -z "$rgb_src_frames" ]]; then + rgb_src_frames=0 + fi + echo "[Step 17] RGB frame mapping for split compose: stride=${tracker_stride}, src=${rgb_src_frames}, target=${num_frames}, picked=${rgb_selected_frames}, first_idx=${rgb_first_idx:-0}, last_idx=${rgb_last_idx:-0}" + + local mesh_export_args=( + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/export_scene_mesh_frames.py + --run-dir "$RUN_DIR" + --config "$cfg_effective" + --output-dir "$mesh_dir" + --max-frames "$num_frames" + ) + if [[ "$LOCK_STATIC_ENABLED_BOOL" == "1" ]]; then + mesh_export_args+=(--use-locked-static) + fi + if [[ -f "$motion_manifest" ]]; then + mesh_export_args+=( + --deform-root "$OUT/motion324_outputs" + --deform-manifest "$motion_manifest" + --deform-frames-dir world_mesh_frames + ) + else + echo "[Warn] motion manifest missing, render rigid/static scene only: $motion_manifest" + fi + "$OPG_PY" "${mesh_export_args[@]}" + local mesh_frame_count + mesh_frame_count="$(find "$mesh_dir" -maxdepth 1 -type f -name 'frame_*.obj' | wc -l | tr -d ' ')" + if [[ -z "$mesh_frame_count" || "$mesh_frame_count" -eq 0 ]]; then + echo "[Step 17] No frame_*.obj mesh frames exported; skip white-model render." + return + fi + + LD_LIBRARY_PATH="$BLENDER_LIB:${LD_LIBRARY_PATH:-}" "$BLENDER_BIN" -b \ + -P /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/blender_render_obj_sequence_with_video_camera.py -- \ + --mesh-dir "$mesh_dir" \ + --result-npz "$result_npz" \ + --output-video "$render_video" \ + --alignment "$RUN_DIR/alignment_plane.json" \ + --coord blender_zup \ + --camera-axis standard \ + --world-conv identity \ + --white-clay \ + --bg-gray 0.35 \ + --world-strength 1.0 \ + --sun-energy 2.5 \ + --camera-headlight \ + --camera-headlight-type sun \ + --camera-headlight-energy 8 \ + --fps 10 + + local ffmpeg_bin + ffmpeg_bin="$("$OPG_PY" - <<'PY' +import shutil +try: + import imageio_ffmpeg # type: ignore +except Exception: + imageio_ffmpeg = None +ff = shutil.which("ffmpeg") +if not ff and imageio_ffmpeg is not None: + try: + ff = imageio_ffmpeg.get_ffmpeg_exe() + except Exception: + ff = None +print(ff or "") +PY +)" + if [[ -z "$ffmpeg_bin" || ! -x "$ffmpeg_bin" ]]; then + echo "ERROR: ffmpeg not found. Install ffmpeg or imageio-ffmpeg in opg env." >&2 + exit 1 + fi + + "$ffmpeg_bin" -y \ + -i "$render_video" \ + -i "$rgb_video" \ + -filter_complex \ + "[0:v]fps=10,scale=1008:560[wm];[1:v]select='${rgb_select_expr}',setpts=N/(10*TB),scale=1008:560[rgb];[wm]crop=504:560:0:0[wm_l];[rgb]crop=504:560:504:0[rgb_r];[wm_l][rgb_r]hstack=inputs=2[mix];[mix]drawbox=x=503:y=0:w=2:h=560:color=white@1:t=fill[out]" \ + -map "[out]" \ + -an \ + -r 10 \ + -c:v libx264 \ + -pix_fmt yuv420p \ + -crf 18 \ + -preset fast \ + -frames:v "$num_frames" \ + "$split_video" + + cp -f "$split_video" "$split_alias" + state_set step17_white_camview_video "$render_video" + state_set step17_white_split_video "$split_video" + echo "[OK] White camview video: $render_video" + echo "[OK] Left-white/right-rgb split video: $split_video" +} + +step18_render_fullscene_deform_textured_split_video() { + echo "[Step 18] Render full-scene + deform textured split video" + sync_pipeline_categories + resolve_run_dir + lock_static_poses "$RUN_DIR" + ensure_alignment + + local cfg_effective hdr_path + cfg_effective="$(get_effective_config)" + local result_npz="$RUN_DIR/results/result.npz" + if [[ ! -f "$result_npz" ]]; then + echo "ERROR: missing $result_npz" >&2 + exit 1 + fi + if [[ ! -x "$BLENDER_BIN" ]]; then + echo "ERROR: Blender not found: $BLENDER_BIN" >&2 + exit 1 + fi + + local motion_manifest="$OUT/motion324_outputs/$NAME/manifest.json" + hdr_path="$(resolve_step18_hdr_path)" + + local render_video_tex="$RUN_DIR/fullscene_deform_objseq_textured_camview.mp4" + local split_video_tex="$RUN_DIR/fullscene_deform_objseq_textured_left_rgb_right_split10_h264.mp4" + local split_alias_tex="$RUN_DIR/fullscene_deform_objseq_textured_split10_h264.mp4" + local render_video_tex_compat="$RUN_DIR/fullscene_deform_textured_camview.mp4" + local split_video_tex_compat="$RUN_DIR/fullscene_deform_textured_left_rgb_right_split10_h264.mp4" + local split_alias_tex_compat="$RUN_DIR/fullscene_deform_textured_split10_h264.mp4" + local rgb_video="$RUN_DIR/${NAME}.mp4" + if [[ ! -f "$rgb_video" ]]; then + rgb_video="$VIDEO" + fi + if [[ ! -f "$rgb_video" ]]; then + echo "ERROR: RGB video not found in RUN_DIR or --video path." >&2 + exit 1 + fi + + local num_frames + num_frames="$("$OPG_PY" - "$result_npz" <<'PY' +import numpy as np +import sys +d = np.load(sys.argv[1]) +print(int(d["extrinsics"].shape[0])) +PY +)" + if [[ -z "$num_frames" || "$num_frames" -le 0 ]]; then + echo "ERROR: invalid frame count from $result_npz" >&2 + exit 1 + fi + + local tracker_stride + tracker_stride="$(get_tracker_sample_stride)" + if [[ -z "$tracker_stride" || "$tracker_stride" -le 0 ]]; then + tracker_stride=1 + fi + local rgb_select_info rgb_select_expr rgb_selected_frames rgb_src_frames rgb_first_idx rgb_last_idx + rgb_select_info="$(compute_rgb_select_expr "$rgb_video" "$num_frames" "$tracker_stride")" + rgb_select_expr="$(printf '%s\n' "$rgb_select_info" | sed -n '1p')" + rgb_selected_frames="$(printf '%s\n' "$rgb_select_info" | sed -n '2p')" + rgb_src_frames="$(printf '%s\n' "$rgb_select_info" | sed -n '3p')" + rgb_first_idx="$(printf '%s\n' "$rgb_select_info" | sed -n '4p')" + rgb_last_idx="$(printf '%s\n' "$rgb_select_info" | sed -n '5p')" + if [[ -z "$rgb_select_expr" ]]; then + rgb_select_expr="not(mod(n,1))" + fi + if [[ -z "$rgb_selected_frames" ]]; then + rgb_selected_frames=0 + fi + if [[ -z "$rgb_src_frames" ]]; then + rgb_src_frames=0 + fi + echo "[Step 18] RGB frame mapping for split compose: stride=${tracker_stride}, src=${rgb_src_frames}, target=${num_frames}, picked=${rgb_selected_frames}, first_idx=${rgb_first_idx:-0}, last_idx=${rgb_last_idx:-0}" + + local step18_deform_frames_dir="$STEP18_DEFORM_FRAMES_DIR" + if [[ "$PHYSICS_ENABLE_BOOL" != "1" ]]; then + step18_deform_frames_dir="world_mesh_frames" + echo "[Step 18] Physics disabled; render original rigid poses and deform meshes." + elif [[ "$DEFORM_LOCK_POSE_BOOL" == "1" && "$STEP18_DEFORM_FRAMES_DIR_EXPLICIT" != "1" ]]; then + step18_deform_frames_dir="world_mesh_frames" + echo "[Step 18] DEFORM_LOCK_POSE=1 detected; defaulting deform frames to ${step18_deform_frames_dir} to preserve lock." + fi + + local step18_render_args=( + --run-dir "$RUN_DIR" + --config "$cfg_effective" + --result-npz "$result_npz" + --output-video "$render_video_tex" + --alignment "$RUN_DIR/alignment_plane.json" + --coord blender_zup + --camera-axis standard + --world-conv identity + --deform-root "$OUT/motion324_outputs" + --deform-manifest "$motion_manifest" + --deform-frames-dir "$step18_deform_frames_dir" + --bg-gray 1.0 + --world-strength 1.0 + --sun-energy 2.5 + --camera-headlight + --camera-headlight-type sun + --camera-headlight-energy 8 + --dark-texture-fallback-ref + --dark-texture-thresh 40 + --dark-texture-target-p99 110 + --dark-texture-max-gain 8 + --fps 10 + --max-frames "$num_frames" + ) + if [[ "$PHYSICS_ENABLE_BOOL" == "1" ]]; then + step18_render_args+=(--pose-name poses_physics.json --add-plane --plane-scale 1.35 --plane-gray 0.72) + fi + if [[ "$LOCK_STATIC_ENABLED_BOOL" == "1" ]]; then + step18_render_args+=(--use-locked-static) + fi + if [[ -n "$hdr_path" ]]; then + step18_render_args+=(--hdr "$hdr_path") + fi + if [[ "$STEP18_UNLIT_TEXTURE_BOOL" == "1" ]]; then + step18_render_args+=(--unlit-texture --unlit-emission-strength 1.0) + fi + LD_LIBRARY_PATH="$BLENDER_LIB:${LD_LIBRARY_PATH:-}" "$BLENDER_BIN" -b \ + -P /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/blender_render_scene_textured_with_video_camera.py -- \ + "${step18_render_args[@]}" + + local ffmpeg_bin + ffmpeg_bin="$("$OPG_PY" - <<'PY' +import shutil +try: + import imageio_ffmpeg # type: ignore +except Exception: + imageio_ffmpeg = None +ff = shutil.which("ffmpeg") +if not ff and imageio_ffmpeg is not None: + try: + ff = imageio_ffmpeg.get_ffmpeg_exe() + except Exception: + ff = None +print(ff or "") +PY +)" + if [[ -z "$ffmpeg_bin" || ! -x "$ffmpeg_bin" ]]; then + echo "ERROR: ffmpeg not found. Install ffmpeg or imageio-ffmpeg in opg env." >&2 + exit 1 + fi + + "$ffmpeg_bin" -y \ + -i "$render_video_tex" \ + -i "$rgb_video" \ + -filter_complex \ + "[0:v]fps=10,scale=1008:560[tex];[1:v]select='${rgb_select_expr}',setpts=N/(10*TB),scale=1008:560[rgb];[tex]crop=504:560:0:0[tex_l];[rgb]crop=504:560:504:0[rgb_r];[tex_l][rgb_r]hstack=inputs=2[mix];[mix]drawbox=x=503:y=0:w=2:h=560:color=white@1:t=fill[out]" \ + -map "[out]" \ + -an \ + -r 10 \ + -c:v libx264 \ + -pix_fmt yuv420p \ + -crf 18 \ + -preset fast \ + -frames:v "$num_frames" \ + "$split_video_tex" + + cp -f "$split_video_tex" "$split_alias_tex" + cp -f "$render_video_tex" "$render_video_tex_compat" + cp -f "$split_video_tex" "$split_video_tex_compat" + cp -f "$split_video_tex" "$split_alias_tex_compat" + state_set step18_textured_camview_video "$render_video_tex" + state_set step18_textured_split_video "$split_video_tex" + echo "[OK] Textured camview video: $render_video_tex" + echo "[OK] Left-textured/right-rgb split video: $split_video_tex" +} + +step19_flux2_single_ref_edit() { + echo "[Step 19] FLUX.2 single-reference object edit" + resolve_run_dir + + if [[ -z "$FLUX_OBJ_NAME" ]]; then + echo "ERROR: --flux-obj-name is required for step 19." >&2 + exit 1 + fi + if [[ ! -x "$FLUX_PY" ]]; then + echo "ERROR: flux python not found/executable: $FLUX_PY" >&2 + exit 1 + fi + if [[ ! -f "$FLUX_STEP19_SCRIPT" ]]; then + echo "ERROR: step-19 helper script not found: $FLUX_STEP19_SCRIPT" >&2 + exit 1 + fi + if [[ ! -d "$FLUX2_REPO" ]]; then + echo "ERROR: flux2 repo not found: $FLUX2_REPO" >&2 + exit 1 + fi + + local model_path="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/flux2/flux-2-klein-9b.safetensors" + local ae_path="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/flux2/ae.safetensors" + local qwen_model_path="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/flux2/text_encoder" + local qwen_tokenizer_path="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/flux2/tokenizer" + + if [[ ! -f "$model_path" ]]; then + echo "ERROR: missing FLUX model file: $model_path" >&2 + exit 1 + fi + if [[ ! -f "$ae_path" ]]; then + echo "ERROR: missing AE model file: $ae_path" >&2 + exit 1 + fi + if [[ ! -d "$qwen_model_path" ]]; then + echo "ERROR: missing Qwen text encoder dir: $qwen_model_path" >&2 + exit 1 + fi + if [[ ! -d "$qwen_tokenizer_path" ]]; then + echo "ERROR: missing Qwen tokenizer dir: $qwen_tokenizer_path" >&2 + exit 1 + fi + + local py_path="$FLUX2_REPO/src" + local flux_objects=() + local obj_name="" + while IFS= read -r obj_name; do + [[ -n "$obj_name" ]] && flux_objects+=("$obj_name") + done < <(parse_csv_items "$FLUX_OBJ_NAME") + + local succeeded=() + local failed=() + local out_roots=() + + for obj_name in "${flux_objects[@]}"; do + local cmd=( + "$FLUX_PY" + "$FLUX_STEP19_SCRIPT" + --run-dir "$RUN_DIR" + --obj-name "$obj_name" + --mode "$FLUX_MODE_CANONICAL" + --seed "$FLUX_SEED_INT" + --out-width "$FLUX_OUT_WIDTH_INT" + --out-height "$FLUX_OUT_HEIGHT_INT" + --match-image-size "$FLUX_MATCH_IMAGE_SIZE_CANONICAL" + --use-rgb-crop-ref "$FLUX_USE_RGB_CROP_REF_BOOL" + --flux-python "$FLUX_PY" + --flux-repo "$FLUX2_REPO" + --model-name flux.2-klein-9b + ) + if [[ -n "$FLUX_PROMPT_AMODAL" ]]; then + cmd+=(--prompt-amodal "$FLUX_PROMPT_AMODAL") + fi + if [[ -n "$FLUX_PROMPT_VIEW" ]]; then + cmd+=(--prompt-view "$FLUX_PROMPT_VIEW") + fi + + echo "[Step 19] object: $obj_name" + if [[ -n "$FLUX_GPU" ]]; then + if ! CUDA_VISIBLE_DEVICES="$FLUX_GPU" \ + PYTHONPATH="$py_path:${PYTHONPATH:-}" \ + KLEIN_9B_MODEL_PATH="$model_path" \ + AE_MODEL_PATH="$ae_path" \ + QWEN3_8B_MODEL_PATH="$qwen_model_path" \ + QWEN3_8B_TOKENIZER_PATH="$qwen_tokenizer_path" \ + FLUX2_ENABLE_AUX_MODEL=0 \ + "${cmd[@]}"; then + failed+=("$obj_name") + continue + fi + else + if ! PYTHONPATH="$py_path:${PYTHONPATH:-}" \ + KLEIN_9B_MODEL_PATH="$model_path" \ + AE_MODEL_PATH="$ae_path" \ + QWEN3_8B_MODEL_PATH="$qwen_model_path" \ + QWEN3_8B_TOKENIZER_PATH="$qwen_tokenizer_path" \ + FLUX2_ENABLE_AUX_MODEL=0 \ + "${cmd[@]}"; then + failed+=("$obj_name") + continue + fi + fi + + succeeded+=("$obj_name") + local out_root="$RUN_DIR/objects/fluxoutput/$obj_name/$FLUX_MODE_CANONICAL" + out_roots+=("$out_root") + echo "[OK] Step 19 output root [$obj_name]: $out_root" + done + + if [[ "${#failed[@]}" -gt 0 ]]; then + echo "ERROR: step 19 failed objects: $(IFS=,; echo "${failed[*]}")" >&2 + exit 1 + fi + + local step19_out_root="$RUN_DIR/objects/fluxoutput" + if [[ "${#out_roots[@]}" -eq 1 ]]; then + step19_out_root="${out_roots[0]}" + fi + state_set step19_flux_obj "$FLUX_OBJ_NAME" + state_set step19_flux_mode "$FLUX_MODE_CANONICAL" + state_set step19_flux_output_root "$step19_out_root" + if [[ "${#out_roots[@]}" -gt 0 ]]; then + state_set step19_flux_output_roots "$(IFS=,; echo "${out_roots[*]}")" + fi + echo "[OK] Step 19 completed objects: $(IFS=,; echo "${succeeded[*]}")" + echo "[OK] Step 19 output root: $step19_out_root" +} + +step20_render_fullscene_white_textured_split_video() { + echo "[Step 20] Render mixed split video (left white / right textured)" + sync_pipeline_categories + resolve_run_dir + ensure_alignment + + local result_npz="$RUN_DIR/results/result.npz" + if [[ ! -f "$result_npz" ]]; then + echo "ERROR: missing $result_npz" >&2 + exit 1 + fi + + local white_camview="$RUN_DIR/fullscene_deform_objseq_white_clay_camview.mp4" + local textured_camview="$RUN_DIR/fullscene_deform_objseq_textured_camview.mp4" + if [[ ! -f "$white_camview" ]]; then + echo "ERROR: missing step-17 white camview video: $white_camview (run step 17 first)." >&2 + exit 1 + fi + if [[ ! -f "$textured_camview" ]]; then + echo "ERROR: missing step-18 textured camview video: $textured_camview (run step 18 first)." >&2 + exit 1 + fi + + local split_video="$RUN_DIR/splitteaser.mp4" + local split_alias="$RUN_DIR/fullscene_deform_objseq_white_textured_split10_h264.mp4" + + local num_frames + num_frames="$("$OPG_PY" - "$result_npz" <<'PY' +import numpy as np +import sys +d = np.load(sys.argv[1]) +print(int(d["extrinsics"].shape[0])) +PY +)" + if [[ -z "$num_frames" || "$num_frames" -le 0 ]]; then + echo "ERROR: invalid frame count from $result_npz" >&2 + exit 1 + fi + + local ffmpeg_bin + ffmpeg_bin="$("$OPG_PY" - <<'PY' +import shutil +try: + import imageio_ffmpeg # type: ignore +except Exception: + imageio_ffmpeg = None +ff = shutil.which("ffmpeg") +if not ff and imageio_ffmpeg is not None: + try: + ff = imageio_ffmpeg.get_ffmpeg_exe() + except Exception: + ff = None +print(ff or "") +PY +)" + if [[ -z "$ffmpeg_bin" || ! -x "$ffmpeg_bin" ]]; then + echo "ERROR: ffmpeg not found. Install ffmpeg or imageio-ffmpeg in opg env." >&2 + exit 1 + fi + + "$ffmpeg_bin" -y \ + -i "$white_camview" \ + -i "$textured_camview" \ + -filter_complex \ + "[0:v]fps=10,scale=1008:560[white];[1:v]fps=10,scale=1008:560[tex];[white]crop=504:560:0:0[white_l];[tex]crop=504:560:504:0[tex_r];[white_l][tex_r]hstack=inputs=2[mix];[mix]drawbox=x=503:y=0:w=2:h=560:color=white@1:t=fill[out]" \ + -map "[out]" \ + -an \ + -r 10 \ + -c:v libx264 \ + -pix_fmt yuv420p \ + -crf 18 \ + -preset fast \ + -frames:v "$num_frames" \ + "$split_video" + + cp -f "$split_video" "$split_alias" + state_set step20_white_textured_split_video "$split_video" + echo "[OK] Step 20 mixed split video: $split_video" +} + +step21_split_video_to_frames() { + echo "[Step 21] Split video into frames" + local input_video="$VIDEO" + if [[ ! -f "$input_video" ]]; then + echo "ERROR: step 21 input video not found: $input_video" >&2 + exit 1 + fi + + local video_name video_stem video_dir frames_dir + video_name="$(basename "$input_video")" + video_stem="${video_name%.*}" + video_dir="$(dirname "$input_video")" + frames_dir="${video_dir}/${video_stem}_frames" + mkdir -p "$frames_dir" + + local frame_info + frame_info="$("$OPG_PY" - "$input_video" "$frames_dir" <<'PY' +import sys +from pathlib import Path + +try: + import cv2 # type: ignore +except Exception as exc: + raise RuntimeError("OpenCV (cv2) is required in OPG_PY env for step 21.") from exc + +video_path = Path(sys.argv[1]) +out_dir = Path(sys.argv[2]) +out_dir.mkdir(parents=True, exist_ok=True) + +# Avoid stale files when re-running on the same output dir. +for p in out_dir.glob("[0-9][0-9][0-9][0-9][0-9][0-9].png"): + p.unlink() + +cap = cv2.VideoCapture(str(video_path)) +if not cap.isOpened(): + raise RuntimeError(f"Cannot open video: {video_path}") + +fps = float(cap.get(cv2.CAP_PROP_FPS) or 0.0) +width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0) +height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0) + +count = 0 +while True: + ok, frame = cap.read() + if not ok: + break + out_path = out_dir / f"{count:06d}.png" + if not cv2.imwrite(str(out_path), frame): + raise RuntimeError(f"Failed to write frame: {out_path}") + count += 1 +cap.release() + +print(f"FRAME_COUNT={count}") +print(f"FPS={fps}") +print(f"WIDTH={width}") +print(f"HEIGHT={height}") +PY +)" + + local frame_count="" fps="" width="" height="" + while IFS='=' read -r key value; do + case "$key" in + FRAME_COUNT) frame_count="$value" ;; + FPS) fps="$value" ;; + WIDTH) width="$value" ;; + HEIGHT) height="$value" ;; + esac + done <<<"$frame_info" + + state_set step21_input_video "$input_video" + state_set step21_frames_dir "$frames_dir" + state_set step21_frame_count "${frame_count:-0}" + if [[ -n "$fps" ]]; then + state_set step21_video_fps "$fps" + fi + if [[ -n "$width" && -n "$height" ]]; then + state_set step21_video_size "${width}x${height}" + fi + + echo "[OK] Step 21 input video: $input_video" + echo "[OK] Step 21 frames dir: $frames_dir" + echo "[OK] Step 21 frame count: ${frame_count:-0}" + if [[ -n "$fps" ]]; then + echo "[OK] Step 21 source FPS: $fps" + fi + if [[ -n "$width" && -n "$height" ]]; then + echo "[OK] Step 21 source size: ${width}x${height}" + fi +} + +run_step() { + case "$1" in + 1) step1_labels ;; + 1.4) step1_4_add_labels ;; + 1.5) step1_5_prune_labels ;; + 2) step2_masks ;; + 2.5) step2_5_merge_mask_labels ;; + 3) step3_build_motion_inputs ;; + 4) step4_run_motion324 ;; + 5) step5_scan_motion_outputs ;; + 6) step6_reconstruct_rigid ;; + 7) step7_plane_and_rigid_physics ;; + 8) step8_deform_world_mesh ;; + 9) step9_deform_physics_sync ;; + 10) step10_export_scene_mesh ;; + 11) step11_export_rigid_glb ;; + 12) step12_export_rigid_physics_glb ;; + 13) step13_export_full_glb_prephysics ;; + 14) step14_export_full_glb_physics ;; + 15) step15_generate_intrinsic_hdr_exr ;; + 16) step16_rerun_failed_step6_objects ;; + 17) step17_render_fullscene_deform_white_split_video ;; + 18) step18_render_fullscene_deform_textured_split_video ;; + 19) step19_flux2_single_ref_edit ;; + 20) step20_render_fullscene_white_textured_split_video ;; + 21) step21_split_video_to_frames ;; + *) + echo "ERROR: unknown step '$1'" >&2 + exit 1 + ;; + esac +} + +echo "[Config] VIDEO=$VIDEO" +echo "[Config] NAME=$NAME" +echo "[Config] OUT_BASE=$OUT_BASE" +echo "[Config] OUT=$OUT" +echo "[Config] WORKSPACE_KEY=$WORKSPACE_KEY" +if [[ -n "$WORKSPACE_POINTER_FILE" ]]; then + echo "[Config] WORKSPACE_POINTER=$WORKSPACE_POINTER_FILE" +fi +echo "[Config] LOCK_STATIC_MODE=$LOCK_STATIC_MODE_CANONICAL" +echo "[Config] DEFORM_LOCK_POSE=$DEFORM_LOCK_POSE_BOOL" +echo "[Config] DEFORM_LOCK_FRAME=$DEFORM_LOCK_FRAME_INT" +echo "[Config] DEFORM_LOCK_MESH=$DEFORM_LOCK_MESH_BOOL" +echo "[Config] DEFORM_EXPORT_VIDEO_FRAMES=$DEFORM_EXPORT_VIDEO_FRAMES_BOOL" +echo "[Config] PHYSICS_ENABLE=$PHYSICS_ENABLE_BOOL" +echo "[Config] PLANE_NUM=$PLANE_NUM_INT" +echo "[Config] PLANE_BOTTOM=$PLANE_BOTTOM_FLOAT" +echo "[Config] PHYSICS_BOTTOM=$PHYSICS_BOTTOM_FLOAT" +echo "[Config] PHYSICS_ITERS=$PHYSICS_ITERS_INT" +echo "[Config] PHYSICS_MAX_DROP=$PHYSICS_MAX_DROP_FLOAT" +echo "[Config] PHYSICS_ALLOW_DOWN=$PHYSICS_ALLOW_DOWN_BOOL" +echo "[Config] PHYSICS_CONTACT=$PHYSICS_CONTACT_BOOL" +echo "[Config] STEP18_DEFORM_FRAMES_DIR=$STEP18_DEFORM_FRAMES_DIR" +echo "[Config] MOTION_NORMALIZE_ZOOM=$MOTION_NORMALIZE_ZOOM_BOOL" +echo "[Config] STEP18_UNLIT_TEXTURE=$STEP18_UNLIT_TEXTURE_BOOL" +if [[ "$MOTION_NORMALIZE_ZOOM_BOOL" == "1" ]]; then + echo "[Config] MOTION_NORMALIZE_TARGET_RATIO=$MOTION_NORMALIZE_TARGET_RATIO" + echo "[Config] MOTION_NORMALIZE_SMOOTH=$MOTION_NORMALIZE_SMOOTH" + echo "[Config] MOTION_NORMALIZE_OUT_SIZE=$MOTION_NORMALIZE_OUT_SIZE" +fi +echo "[Config] QWEN_BACKEND=$QWEN_BACKEND" +echo "[Config] CONTINUE_ON_ERROR=$CONTINUE_ON_ERROR_BOOL" +echo "[Config] RERUN_ONLY_FAILED=$RERUN_ONLY_FAILED_BOOL" +echo "[Config] RERUN_ANCHOR_FRAME=$RERUN_ANCHOR_FRAME_INT" +echo "[Config] RERUN_USE_FLUX_REF=$RERUN_USE_FLUX_REF_BOOL" +if [[ -n "$RERUN_OBJECTS" ]]; then + echo "[Config] RERUN_OBJECTS=$RERUN_OBJECTS" +fi +if [[ -n "$RERUN_REF_MAP" ]]; then + echo "[Config] RERUN_REF_MAP=$RERUN_REF_MAP" +fi +if [[ -n "$RERUN_REF_IMAGE" ]]; then + echo "[Config] RERUN_REF_IMAGE=$RERUN_REF_IMAGE" + if [[ -n "$RERUN_SINGLE_OBJECT" ]]; then + echo "[Config] RERUN_SINGLE_OBJECT=$RERUN_SINGLE_OBJECT" + fi +fi +echo "[Config] FLUX_MODE=$FLUX_MODE_CANONICAL" +echo "[Config] FLUX_SEED=$FLUX_SEED_INT" +echo "[Config] FLUX_SIZE=${FLUX_OUT_WIDTH_INT}x${FLUX_OUT_HEIGHT_INT}" +echo "[Config] FLUX_MATCH_IMAGE_SIZE=$FLUX_MATCH_IMAGE_SIZE_CANONICAL" +echo "[Config] FLUX_USE_RGB_CROP_REF=$FLUX_USE_RGB_CROP_REF_BOOL" +if [[ -n "$FLUX_OBJ_NAME" ]]; then + echo "[Config] FLUX_OBJ_NAME=$FLUX_OBJ_NAME" +fi +if [[ -n "$FLUX_GPU" ]]; then + echo "[Config] FLUX_GPU=$FLUX_GPU" +fi +if [[ -n "$FLUX_PROMPT_AMODAL" ]]; then + echo "[Config] FLUX_PROMPT_AMODAL=" +fi +if [[ -n "$FLUX_PROMPT_VIEW" ]]; then + echo "[Config] FLUX_PROMPT_VIEW=" +fi +echo "[Config] QWEN_LABEL_CATEGORY_ENABLE=$QWEN_LABEL_CATEGORY_ENABLE_BOOL" +echo "[Config] QWEN_LABEL_CATEGORY_MODE_INPUT=$QWEN_LABEL_CATEGORY_MODE" +echo "[Config] QWEN_LABEL_CATEGORY_MODE=$QWEN_LABEL_CATEGORY_MODE_EFFECTIVE" +echo "[Config] QWEN_LABEL_CATEGORY_STRICT=$QWEN_LABEL_CATEGORY_STRICT_BOOL" +if [[ -n "$QWEN_LABEL_CATEGORY_MODEL" ]]; then + echo "[Config] QWEN_LABEL_CATEGORY_MODEL=$QWEN_LABEL_CATEGORY_MODEL" +fi +echo "[Config] QWEN_CATEGORY_PASS=$QWEN_CATEGORY_PASS_EFFECTIVE" +echo "[Config] QWEN_CATEGORY_PASS_STRICT=$QWEN_CATEGORY_PASS_STRICT_EFFECTIVE" +echo "[Config] SAM_MIN_OBJ_AREA=$SAM_MIN_OBJ_AREA_INT" +if [[ -n "$ADD_LABELS" ]]; then + echo "[Config] ADD_LABELS=$ADD_LABELS" + echo "[Config] ADD_LABEL_CATEGORY=$ADD_LABEL_CATEGORY" + echo "[Config] ADD_LABEL_OVERWRITE_CATEGORY=$ADD_LABEL_OVERWRITE_CATEGORY_BOOL" +fi +if [[ -n "$PRUNE_LABELS" ]]; then + echo "[Config] PRUNE_LABELS=$PRUNE_LABELS" +fi +if [[ -n "$MERGE_MASK_LABELS" ]]; then + echo "[Config] MERGE_MASK_LABELS=$MERGE_MASK_LABELS" + if [[ -n "$MERGE_MASK_OUTPUT_LABEL" ]]; then + echo "[Config] MERGE_MASK_OUTPUT_LABEL=$MERGE_MASK_OUTPUT_LABEL" + fi + if [[ -n "$MERGE_MASK_CATEGORY" ]]; then + echo "[Config] MERGE_MASK_CATEGORY=$MERGE_MASK_CATEGORY" + fi +fi +if [[ "$QWEN_BACKEND" == "api" ]]; then + echo "[Config] QWEN_API_MODEL=$QWEN_API_MODEL" + echo "[Config] QWEN_API_MODEL_LIST=$QWEN_API_MODEL_LIST" + echo "[Config] QWEN_MAX_NEW_TOKENS=$QWEN_MAX_NEW_TOKENS_INT" + if [[ -n "$QWEN_CATEGORY_API_MODEL" ]]; then + echo "[Config] QWEN_CATEGORY_API_MODEL=$QWEN_CATEGORY_API_MODEL" + else + echo "[Config] QWEN_CATEGORY_API_MODEL=" + fi + echo "[Config] QWEN_CATEGORY_MAX_NEW_TOKENS=$QWEN_CATEGORY_MAX_NEW_TOKENS_INT" + echo "[Config] QWEN_API_KEY_ENV=$QWEN_API_KEY_ENV" +else + echo "[Config] QWEN_MODEL=${QWEN_MODEL:-}" +fi + +FAILED_STEPS=() +if [[ "$CONTINUE_ON_ERROR_BOOL" == "1" ]]; then + : >"$ERROR_LOG" +fi + +for s in "${STEPS[@]}"; do + if [[ "$CONTINUE_ON_ERROR_BOOL" == "1" ]]; then + step_log="${STEP_LOG_DIR}/step_${s}.log" + : >"$step_log" + set +e + ( set -e; run_step "$s" ) > >(tee -a "$step_log") 2> >(tee -a "$step_log" >&2) + rc=$? + set -e + if [[ "$rc" -ne 0 ]]; then + echo "[Warn] Step $s failed (rc=$rc). Continue to next step." + echo "[Warn] Step log: $step_log" + record_step_error "$s" "$rc" "$step_log" + FAILED_STEPS+=("$s") + continue + fi + else + run_step "$s" + fi +done + +if [[ "${#FAILED_STEPS[@]}" -gt 0 ]]; then + echo "[Warn] Completed with failed steps: ${FAILED_STEPS[*]}" + echo "[Warn] Error report: $ERROR_LOG" +fi + +echo "[Done] Requested steps completed." diff --git a/OVOW/engine/run_steps_scene_pipeline_batch.sh b/OVOW/engine/run_steps_scene_pipeline_batch.sh new file mode 100644 index 0000000000000000000000000000000000000000..a7ef56074921b75be330a4073521f1e0ce01152a --- /dev/null +++ b/OVOW/engine/run_steps_scene_pipeline_batch.sh @@ -0,0 +1,627 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +PIPELINE_SCRIPT="${SCRIPT_DIR}/run_steps_scene_pipeline.sh" +VIDEO_ROOT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/examples/videos" +OUT_ROOT="" +RUN_DIR_ROOT="" + +SCENE_START=31 +SCENE_END=40 +STEPS_RAW="1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 17 18" + +SCENE_CONTINUE_ON_ERROR=0 +BATCH_STOP_ON_FAIL=0 +DRY_RUN=0 + +GPU_MODE="inherit" +GPU_VALUE="" + +GPU_LIST_RAW="" +MAX_PER_GPU=1 + +PIPELINE_EXTRA_ARGS=() +STEPS=() +CMD=() +VIDEO_LOOKUP_NOTES=() + +usage() { + cat <<'USAGE' +Usage: + bash run_steps_scene_pipeline_batch.sh [batch-options] [-- pipeline-options...] + +Batch options: + --scene-start N First scene id (default: 31) + --scene-end N Last scene id (default: 40) + --steps "LIST" Steps to run, e.g. "1 2 3" or "17,18" + --video-root DIR Video root (default: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/examples/videos) + --out DIR Pass --out DIR to per-scene pipeline + --run-dir-root DIR Pass --run-dir DIR/v{scene_id} to per-scene pipeline + --scene-continue 0|1 Per-scene --continue-on-error value (default: 0) + --batch-stop-on-fail 0|1 Stop launching new scenes after first failed scene (default: 0) + --dry-run Print planned commands without executing + -h, --help Show this help + +GPU options (choose one mode): + --gpu ID|none Legacy single-gpu mode for all scenes + --gpus LIST Multi-gpu mode, e.g. "0,1,2,3" or "0 1 2 3" + --max-per-gpu N Max concurrent scenes per GPU in multi-gpu mode (default: 1) + +Pipeline options: + Put extra options after '--'. They are forwarded to run_steps_scene_pipeline.sh. + Example: + bash run_steps_scene_pipeline_batch.sh --gpus "0,1,2,3" --max-per-gpu 2 -- --lock-static-mode off + +Examples: + bash run_steps_scene_pipeline_batch.sh + bash run_steps_scene_pipeline_batch.sh --steps "17 18" --gpu 1 + bash run_steps_scene_pipeline_batch.sh --gpus "0,1,2,3,4,5,6,7" --max-per-gpu 2 +USAGE +} + +is_int() { + [[ "${1:-}" =~ ^-?[0-9]+$ ]] +} + +is_bool01() { + [[ "${1:-}" == "0" || "${1:-}" == "1" ]] +} + +parse_steps() { + local raw="$1" + raw="${raw//,/ }" + read -r -a STEPS <<<"$raw" + if [[ "${#STEPS[@]}" -eq 0 ]]; then + echo "ERROR: no valid steps were provided." >&2 + exit 1 + fi +} + +parse_gpu_list() { + local raw="$1" + local cleaned + cleaned="${raw//,/ }" + read -r -a GPU_IDS <<<"$cleaned" + if [[ "${#GPU_IDS[@]}" -eq 0 ]]; then + echo "ERROR: --gpus is empty." >&2 + exit 1 + fi + + declare -A seen=() + local g + for g in "${GPU_IDS[@]}"; do + if ! is_int "$g" || [[ "$g" -lt 0 ]]; then + echo "ERROR: invalid gpu id in --gpus: '$g'." >&2 + exit 1 + fi + if [[ -n "${seen[$g]:-}" ]]; then + echo "ERROR: duplicate gpu id in --gpus: '$g'." >&2 + exit 1 + fi + seen[$g]=1 + done +} + +resolve_scene_video() { + local scene_id="$1" + local scene_tag="v${scene_id}" + local scene_dir="${VIDEO_ROOT}/scene${scene_id}" + local preferred="${scene_dir}/${scene_tag}.mp4" + local -a candidates=() + local video="" + + if [[ ! -d "$scene_dir" ]]; then + printf '%s\n' "" + return 0 + fi + + if [[ -f "$preferred" ]]; then + printf '%s\n' "$preferred" + return 0 + fi + + mapfile -t candidates < <( + find "$scene_dir" -maxdepth 1 -type f \ + \( -iname '*.mp4' -o -iname '*.mov' -o -iname '*.mkv' -o -iname '*.avi' \) \ + | sort + ) + if [[ "${#candidates[@]}" -eq 0 ]]; then + printf '%s\n' "" + return 0 + fi + + video="${candidates[0]}" + if [[ "${#candidates[@]}" -gt 1 ]]; then + VIDEO_LOOKUP_NOTES+=( + "scene${scene_id}: found ${#candidates[@]} videos, using first: $(basename "$video")" + ) + fi + printf '%s\n' "$video" +} + +build_scene_cmd() { + local name="$1" + local video="$2" + CMD=( + bash "$PIPELINE_SCRIPT" + --name "$name" + --video "$video" + --continue-on-error "$SCENE_CONTINUE_ON_ERROR" + ) + if [[ -n "$OUT_ROOT" ]]; then + CMD+=(--out "$OUT_ROOT") + fi + if [[ -n "$RUN_DIR_ROOT" ]]; then + CMD+=(--run-dir "${RUN_DIR_ROOT}/${name}") + fi + if [[ "${#PIPELINE_EXTRA_ARGS[@]}" -gt 0 ]]; then + CMD+=("${PIPELINE_EXTRA_ARGS[@]}") + fi + CMD+=("${STEPS[@]}") +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --scene-start) + SCENE_START="$2" + shift 2 + ;; + --scene-end) + SCENE_END="$2" + shift 2 + ;; + --steps) + STEPS_RAW="$2" + shift 2 + ;; + --video-root) + VIDEO_ROOT="$2" + shift 2 + ;; + --out) + OUT_ROOT="$2" + shift 2 + ;; + --run-dir-root) + RUN_DIR_ROOT="$2" + shift 2 + ;; + --scene-continue) + SCENE_CONTINUE_ON_ERROR="$2" + shift 2 + ;; + --batch-stop-on-fail) + BATCH_STOP_ON_FAIL="$2" + shift 2 + ;; + --gpu) + if [[ "$2" == "none" ]]; then + GPU_MODE="none" + GPU_VALUE="" + else + GPU_MODE="set" + GPU_VALUE="$2" + fi + shift 2 + ;; + --gpus|--gpu-list) + GPU_LIST_RAW="$2" + shift 2 + ;; + --max-per-gpu) + MAX_PER_GPU="$2" + shift 2 + ;; + --dry-run) + DRY_RUN=1 + shift + ;; + -h|--help) + usage + exit 0 + ;; + --) + shift + PIPELINE_EXTRA_ARGS=("$@") + break + ;; + *) + echo "ERROR: unknown option '$1'" >&2 + usage + exit 1 + ;; + esac +done + +if [[ ! -f "$PIPELINE_SCRIPT" ]]; then + echo "ERROR: pipeline script not found: $PIPELINE_SCRIPT" >&2 + exit 1 +fi + +if ! is_int "$SCENE_START" || ! is_int "$SCENE_END"; then + echo "ERROR: --scene-start/--scene-end must be integers." >&2 + exit 1 +fi +if [[ "$SCENE_START" -le 0 || "$SCENE_END" -le 0 || "$SCENE_START" -gt "$SCENE_END" ]]; then + echo "ERROR: invalid scene range: ${SCENE_START}..${SCENE_END}" >&2 + exit 1 +fi + +if ! is_bool01 "$SCENE_CONTINUE_ON_ERROR"; then + echo "ERROR: --scene-continue must be 0 or 1." >&2 + exit 1 +fi +if ! is_bool01 "$BATCH_STOP_ON_FAIL"; then + echo "ERROR: --batch-stop-on-fail must be 0 or 1." >&2 + exit 1 +fi + +parse_steps "$STEPS_RAW" + +MULTI_GPU_MODE=0 +GPU_IDS=() +if [[ -n "$GPU_LIST_RAW" ]]; then + parse_gpu_list "$GPU_LIST_RAW" + MULTI_GPU_MODE=1 +fi + +if ! is_int "$MAX_PER_GPU" || [[ "$MAX_PER_GPU" -le 0 ]]; then + echo "ERROR: --max-per-gpu must be an integer > 0." >&2 + exit 1 +fi + +if [[ "$MULTI_GPU_MODE" == "1" && "$GPU_MODE" != "inherit" ]]; then + echo "[Warn] Both --gpus and --gpu were set. Ignoring --gpu and using --gpus scheduler." +fi + +TIMESTAMP="$(date +%Y%m%d_%H%M%S)" +LOG_DIR="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs/batch_logs_scene_${SCENE_START}_${SCENE_END}_${TIMESTAMP}" +mkdir -p "$LOG_DIR" + +declare -a OK_SCENES=() +declare -a FAILED_SCENES=() +declare -a MISSING_SCENES=() +declare -a SKIPPED_SCENES=() + +declare -a PENDING_TAGS=() +declare -a PENDING_NAMES=() +declare -a PENDING_VIDEOS=() + +for sid in $(seq "$SCENE_START" "$SCENE_END"); do + scene_tag="v${sid}" + video="$(resolve_scene_video "$sid")" + if [[ ! -f "$video" ]]; then + MISSING_SCENES+=("$scene_tag") + continue + fi + scene_name="$(basename "$video")" + scene_name="${scene_name%.*}" + PENDING_TAGS+=("$scene_tag") + PENDING_NAMES+=("$scene_name") + PENDING_VIDEOS+=("$video") +done + +echo "[Batch] scene range: ${SCENE_START}-${SCENE_END}" +echo "[Batch] steps: ${STEPS[*]}" +echo "[Batch] video root: ${VIDEO_ROOT}" +echo "[Batch] log dir: ${LOG_DIR}" +echo "[Batch] scene continue-on-error: ${SCENE_CONTINUE_ON_ERROR}" +if [[ -n "$OUT_ROOT" ]]; then + echo "[Batch] out root: ${OUT_ROOT}" +fi +if [[ -n "$RUN_DIR_ROOT" ]]; then + echo "[Batch] run-dir root: ${RUN_DIR_ROOT}" +fi +if [[ "$MULTI_GPU_MODE" == "1" ]]; then + echo "[Batch] mode: multi-gpu scheduler" + echo "[Batch] gpus: ${GPU_IDS[*]}" + echo "[Batch] max-per-gpu: ${MAX_PER_GPU}" +else + echo "[Batch] mode: single-gpu/sequential" + if [[ "$GPU_MODE" == "set" ]]; then + echo "[Batch] CUDA_VISIBLE_DEVICES=${GPU_VALUE}" + elif [[ "$GPU_MODE" == "none" ]]; then + echo "[Batch] CUDA_VISIBLE_DEVICES will be unset" + fi +fi +if [[ "${#PIPELINE_EXTRA_ARGS[@]}" -gt 0 ]]; then + echo "[Batch] forwarded pipeline args: ${PIPELINE_EXTRA_ARGS[*]}" +fi +if [[ "${#MISSING_SCENES[@]}" -gt 0 ]]; then + echo "[Batch] missing scenes: ${MISSING_SCENES[*]}" +fi +if [[ "${#VIDEO_LOOKUP_NOTES[@]}" -gt 0 ]]; then + echo "[Batch] lookup notes:" + for note in "${VIDEO_LOOKUP_NOTES[@]}"; do + echo " - $note" + done +fi + +run_scene_sync() { + local scene_tag="$1" + local scene_name="$2" + local video="$3" + local log_file="$4" + local gpu="$5" + + build_scene_cmd "$scene_name" "$video" + { + if [[ -n "$gpu" ]]; then + printf '[%s] name=%s gpu=%s command:' "$scene_tag" "$scene_name" "$gpu" + else + printf '[%s] name=%s command:' "$scene_tag" "$scene_name" + fi + printf ' %q' "${CMD[@]}" + printf '\n' + } | tee "$log_file" + + if [[ "$DRY_RUN" == "1" ]]; then + echo "[${scene_tag}] dry-run only" | tee -a "$log_file" + OK_SCENES+=("$scene_tag") + return 0 + fi + + local rc + set +e + if [[ -n "$gpu" ]]; then + CUDA_VISIBLE_DEVICES="$gpu" "${CMD[@]}" >>"$log_file" 2>&1 + rc=$? + elif [[ "$GPU_MODE" == "set" ]]; then + CUDA_VISIBLE_DEVICES="$GPU_VALUE" "${CMD[@]}" >>"$log_file" 2>&1 + rc=$? + elif [[ "$GPU_MODE" == "none" ]]; then + env -u CUDA_VISIBLE_DEVICES "${CMD[@]}" >>"$log_file" 2>&1 + rc=$? + else + "${CMD[@]}" >>"$log_file" 2>&1 + rc=$? + fi + set -e + + if [[ "$rc" -eq 0 ]]; then + if [[ -n "$gpu" ]]; then + echo "[${scene_tag}] OK (name=${scene_name}, gpu=${gpu})" + else + echo "[${scene_tag}] OK (name=${scene_name})" + fi + OK_SCENES+=("$scene_tag") + return 0 + fi + + if [[ -n "$gpu" ]]; then + echo "[${scene_tag}] FAIL rc=${rc} (name=${scene_name}, gpu=${gpu}, log: ${log_file})" + else + echo "[${scene_tag}] FAIL rc=${rc} (name=${scene_name}, log: ${log_file})" + fi + FAILED_SCENES+=("$scene_tag") + return 1 +} + +if [[ "$MULTI_GPU_MODE" == "0" ]]; then + STOP_LAUNCH=0 + for i in "${!PENDING_TAGS[@]}"; do + scene_tag="${PENDING_TAGS[$i]}" + scene_name="${PENDING_NAMES[$i]}" + video="${PENDING_VIDEOS[$i]}" + log_file="${LOG_DIR}/${scene_tag}.log" + echo + echo "==== [${scene_tag}] start ====" + echo "[${scene_tag}] video: ${video}" + echo "[${scene_tag}] name: ${scene_name}" + + if ! run_scene_sync "$scene_tag" "$scene_name" "$video" "$log_file" ""; then + if [[ "$BATCH_STOP_ON_FAIL" == "1" ]]; then + STOP_LAUNCH=1 + for ((j=i+1; j<${#PENDING_TAGS[@]}; j++)); do + SKIPPED_SCENES+=("${PENDING_TAGS[$j]}") + done + echo "[Batch] stop on first failure." + break + fi + fi + done +else + if [[ "${#PENDING_TAGS[@]}" -eq 0 ]]; then + : + elif [[ "$DRY_RUN" == "1" ]]; then + declare -A gpu_launch_count=() + for g in "${GPU_IDS[@]}"; do + gpu_launch_count[$g]=0 + done + rr_idx=0 + for i in "${!PENDING_TAGS[@]}"; do + scene_tag="${PENDING_TAGS[$i]}" + scene_name="${PENDING_NAMES[$i]}" + video="${PENDING_VIDEOS[$i]}" + best_gpu="" + best_idx=-1 + best_count=0 + for ((k=0; k<${#GPU_IDS[@]}; k++)); do + idx=$(( (rr_idx + k) % ${#GPU_IDS[@]} )) + g="${GPU_IDS[$idx]}" + c="${gpu_launch_count[$g]}" + if [[ -z "$best_gpu" ]] || (( c < best_count )); then + best_gpu="$g" + best_idx="$idx" + best_count="$c" + fi + done + rr_idx=$(( (best_idx + 1) % ${#GPU_IDS[@]} )) + gpu_launch_count[$best_gpu]=$((gpu_launch_count[$best_gpu] + 1)) + log_file="${LOG_DIR}/${scene_tag}.log" + echo + echo "==== [${scene_tag}] plan ====" + echo "[${scene_tag}] video: ${video}" + echo "[${scene_tag}] name: ${scene_name}" + run_scene_sync "$scene_tag" "$scene_name" "$video" "$log_file" "$best_gpu" + done + else + declare -A GPU_RUNNING=() + declare -A GPU_LAUNCHED=() + declare -A PID_TO_GPU=() + declare -A PID_TO_TAG=() + declare -A PID_TO_NAME=() + declare -A PID_TO_LOG=() + declare -a RUNNING_PIDS=() + + for g in "${GPU_IDS[@]}"; do + GPU_RUNNING[$g]=0 + GPU_LAUNCHED[$g]=0 + done + + GPU_RR_INDEX=0 + NEXT_SCENE_INDEX=0 + STOP_LAUNCH=0 + + pick_next_gpu() { + local n="${#GPU_IDS[@]}" + local best_gpu="" + local best_idx=-1 + local best_launch=0 + local k idx g run launched + for ((k=0; k= MAX_PER_GPU )); then + continue + fi + launched="${GPU_LAUNCHED[$g]}" + if [[ -z "$best_gpu" ]] || (( launched < best_launch )); then + best_gpu="$g" + best_idx="$idx" + best_launch="$launched" + fi + done + if [[ -z "$best_gpu" ]]; then + return 1 + fi + GPU_RR_INDEX=$(( (best_idx + 1) % n )) + printf '%s\n' "$best_gpu" + return 0 + } + + launch_scene_async() { + local scene_index="$1" + local gpu="$2" + local scene_tag="${PENDING_TAGS[$scene_index]}" + local scene_name="${PENDING_NAMES[$scene_index]}" + local video="${PENDING_VIDEOS[$scene_index]}" + local log_file="${LOG_DIR}/${scene_tag}.log" + + build_scene_cmd "$scene_name" "$video" + { + printf '[%s] name=%s gpu=%s command:' "$scene_tag" "$scene_name" "$gpu" + printf ' %q' "${CMD[@]}" + printf '\n' + } | tee "$log_file" + + CUDA_VISIBLE_DEVICES="$gpu" "${CMD[@]}" >>"$log_file" 2>&1 & + local pid=$! + RUNNING_PIDS+=("$pid") + PID_TO_GPU[$pid]="$gpu" + PID_TO_TAG[$pid]="$scene_tag" + PID_TO_NAME[$pid]="$scene_name" + PID_TO_LOG[$pid]="$log_file" + GPU_RUNNING[$gpu]=$((GPU_RUNNING[$gpu] + 1)) + GPU_LAUNCHED[$gpu]=$((GPU_LAUNCHED[$gpu] + 1)) + echo "[${scene_tag}] launched on gpu=${gpu} (name=${scene_name}, pid=${pid})" + } + + collect_finished_jobs_once() { + local had_completion=0 + local -a next_running=() + local pid rc gpu scene_tag scene_name log_file + + for pid in "${RUNNING_PIDS[@]}"; do + if kill -0 "$pid" 2>/dev/null; then + next_running+=("$pid") + continue + fi + + set +e + wait "$pid" + rc=$? + set -e + + had_completion=1 + gpu="${PID_TO_GPU[$pid]}" + scene_tag="${PID_TO_TAG[$pid]}" + scene_name="${PID_TO_NAME[$pid]}" + log_file="${PID_TO_LOG[$pid]}" + unset 'PID_TO_GPU[$pid]' + unset 'PID_TO_TAG[$pid]' + unset 'PID_TO_NAME[$pid]' + unset 'PID_TO_LOG[$pid]' + GPU_RUNNING[$gpu]=$((GPU_RUNNING[$gpu] - 1)) + + if [[ "$rc" -eq 0 ]]; then + echo "[${scene_tag}] OK (name=${scene_name}, gpu=${gpu})" + OK_SCENES+=("$scene_tag") + else + echo "[${scene_tag}] FAIL rc=${rc} (name=${scene_name}, gpu=${gpu}, log: ${log_file})" + FAILED_SCENES+=("$scene_tag") + if [[ "$BATCH_STOP_ON_FAIL" == "1" ]]; then + STOP_LAUNCH=1 + fi + fi + done + + RUNNING_PIDS=("${next_running[@]}") + if [[ "$had_completion" == "1" ]]; then + return 0 + fi + return 1 + } + + while (( NEXT_SCENE_INDEX < ${#PENDING_TAGS[@]} || ${#RUNNING_PIDS[@]} > 0 )); do + if [[ "$STOP_LAUNCH" == "0" ]]; then + while (( NEXT_SCENE_INDEX < ${#PENDING_TAGS[@]} )); do + if ! gpu="$(pick_next_gpu)"; then + break + fi + echo + echo "==== [${PENDING_TAGS[$NEXT_SCENE_INDEX]}] start ====" + echo "[${PENDING_TAGS[$NEXT_SCENE_INDEX]}] video: ${PENDING_VIDEOS[$NEXT_SCENE_INDEX]}" + echo "[${PENDING_TAGS[$NEXT_SCENE_INDEX]}] name: ${PENDING_NAMES[$NEXT_SCENE_INDEX]}" + launch_scene_async "$NEXT_SCENE_INDEX" "$gpu" + NEXT_SCENE_INDEX=$((NEXT_SCENE_INDEX + 1)) + done + fi + + if (( ${#RUNNING_PIDS[@]} == 0 )); then + break + fi + + until collect_finished_jobs_once; do + sleep 1 + done + done + + if [[ "$STOP_LAUNCH" == "1" && "$NEXT_SCENE_INDEX" -lt "${#PENDING_TAGS[@]}" ]]; then + for ((j=NEXT_SCENE_INDEX; j<${#PENDING_TAGS[@]}; j++)); do + SKIPPED_SCENES+=("${PENDING_TAGS[$j]}") + done + echo "[Batch] stop-on-fail enabled; skipped scenes: ${SKIPPED_SCENES[*]}" + fi + fi +fi + +echo +echo "==== Batch summary ====" +echo "log dir: ${LOG_DIR}" +echo "ok (${#OK_SCENES[@]}): ${OK_SCENES[*]:-}" +echo "failed (${#FAILED_SCENES[@]}): ${FAILED_SCENES[*]:-}" +echo "missing (${#MISSING_SCENES[@]}): ${MISSING_SCENES[*]:-}" +echo "skipped (${#SKIPPED_SCENES[@]}): ${SKIPPED_SCENES[*]:-}" + +printf "%s\n" "${OK_SCENES[@]}" >"${LOG_DIR}/ok.txt" +printf "%s\n" "${FAILED_SCENES[@]}" >"${LOG_DIR}/failed.txt" +printf "%s\n" "${MISSING_SCENES[@]}" >"${LOG_DIR}/missing.txt" +printf "%s\n" "${SKIPPED_SCENES[@]}" >"${LOG_DIR}/skipped.txt" + +if [[ "${#FAILED_SCENES[@]}" -gt 0 ]]; then + exit 1 +fi diff --git a/OVOW/engine/setup.sh b/OVOW/engine/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..96ca5ec0ef2469cf49473e2d9ce17090ca5a062e --- /dev/null +++ b/OVOW/engine/setup.sh @@ -0,0 +1,79 @@ +#!/bin/bash + +set -e + +echo "🚀 Starting setup for OnePoseviaGen..." + +PYTHON_VERSION=$(python --version 2>&1 | awk '{print $2}') +if [[ "$PYTHON_VERSION" != 3.11* ]]; then + echo "⚠️ Warning: This project is tested with Python 3.11, but current version is $PYTHON_VERSION" + read -p "Continue anyway? (y/n): " -n 1 -r + echo + if [[ ! $REPLY =~ ^[Yy]$ ]]; then + echo "❌ Setup canceled." + exit 1 + fi +fi + +echo "📦 Installing PyTorch with CUDA support..." +python -m pip install torch==2.4.1 torchvision==0.19.1 torchaudio==2.4.1 --index-url https://download.pytorch.org/whl/cu121 + +echo "📦 Installing requirements from requirements.txt..." +pip install -r requirements.txt + +echo "📦 Installing Boost and Eigen via Conda..." +conda install -c conda-forge eigen=3.4.0 -y + +echo "📦 Cloning and installing external extensions..." +mkdir -p tmp/extensions + +echo "🛠️ Installing diffoctreerast..." +git clone --recurse-submodules https://github.com/JeffreyXiang/diffoctreerast.git tmp/extensions/diffoctreerast +pip install tmp/extensions/diffoctreerast + +echo "🛠️ Installing mip-splatting and diff-gaussian-rasterization..." +git clone https://github.com/autonomousvision/mip-splatting.git tmp/extensions/mip-splatting +pip install tmp/extensions/mip-splatting/submodules/diff-gaussian-rasterization/ + +echo "🛠️ Installing PyTorch3D..." +python -m pip install --no-build-isolation git+https://github.com/facebookresearch/pytorch3d.git + + +echo "🛠️ Building F-Pose..." +cd oneposeviagen/fpose/fpose +CMAKE_PREFIX_PATH=$CONDA_PREFIX/lib/python3.11/site-packages/pybind11/share/cmake/pybind11 bash build_all_conda.sh +cd ../../.. + +echo "🛠️ Installing local packages in editable mode..." + +cd oneposeviagen + +echo "📦 Installing fpose..." +cd fpose +pip install -e . +cd .. + +echo "📦 Installing SAM2-in-video..." +cd SAM2-in-video +pip install -e . +cd .. + +echo "📦 Installing Trellis..." +cd trellis +pip install -e . +cd .. + +echo "📦 Installing Trellis..." +cd Amodal3R +pip install -e . +cd .. + +echo "📦 Installing SpaTrackerV2..." +cd SpaTrackerV2 +pip install -e . +cd .. + +echo "📦 Downloading pretrained weights..." +python oneposeviagen/scripts/download_weights.py + +echo "🎉 Setup completed successfully!" \ No newline at end of file diff --git a/OVOW/engine/tools/actionmesh_shim/usercustomize.py b/OVOW/engine/tools/actionmesh_shim/usercustomize.py new file mode 100644 index 0000000000000000000000000000000000000000..2f3f134cf06488fcfab6c4829ac94530533911b2 --- /dev/null +++ b/OVOW/engine/tools/actionmesh_shim/usercustomize.py @@ -0,0 +1,7 @@ +try: + import flash_attn.flash_attn_interface as _fi + if not hasattr(_fi, "_wrapped_flash_attn_backward"): + _fi._wrapped_flash_attn_backward = _fi._flash_attn_backward + _fi._wrapped_flash_attn_forward = _fi._flash_attn_forward +except Exception: + pass diff --git a/OVOW/engine/tools/add_video_labels.py b/OVOW/engine/tools/add_video_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..503674c6c6d54a622393dd520c7672a071a00ab1 --- /dev/null +++ b/OVOW/engine/tools/add_video_labels.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import shutil +from datetime import datetime, timezone +from json import JSONDecodeError +from pathlib import Path +from typing import Any, Dict, List, Sequence + + +def _parse_label_csv(raw: str) -> List[str]: + labels: List[str] = [] + seen = set() + for part in str(raw or "").split(","): + label = _normalize_label(part) + if not label or label in seen: + continue + seen.add(label) + labels.append(label) + return labels + + +def _normalize_label(raw: Any) -> str: + text = str(raw or "").strip().lower() + text = text.replace("-", " ").replace("_", " ") + text = "".join(ch if (ch.isalnum() or ch.isspace()) else " " for ch in text) + return " ".join(text.split()).strip() + + +def _ordered_union(*sequences: Sequence[str]) -> List[str]: + out: List[str] = [] + seen = set() + for seq in sequences: + for item in seq: + label = _normalize_label(item) + if not label or label in seen: + continue + seen.add(label) + out.append(label) + return out + + +def _strip_trailing_commas(text: str) -> str: + out: List[str] = [] + in_string = False + escaped = False + idx = 0 + while idx < len(text): + ch = text[idx] + if in_string: + out.append(ch) + if escaped: + escaped = False + elif ch == "\\": + escaped = True + elif ch == '"': + in_string = False + idx += 1 + continue + if ch == '"': + in_string = True + out.append(ch) + idx += 1 + continue + if ch == ",": + look_ahead = idx + 1 + while look_ahead < len(text) and text[look_ahead] in " \t\r\n": + look_ahead += 1 + if look_ahead < len(text) and text[look_ahead] in "]}": + idx += 1 + continue + out.append(ch) + idx += 1 + return "".join(out) + + +def _load_json(path: Path) -> Dict[str, Any]: + text = path.read_text(encoding="utf-8") + try: + payload = json.loads(text) + except JSONDecodeError: + repaired = _strip_trailing_commas(text) + if repaired == text: + raise + payload = json.loads(repaired) + print(f"[warn] repaired malformed JSON while reading: {path}") + if not isinstance(payload, dict): + raise RuntimeError(f"Expected JSON object: {path}") + return payload + + +def _write_json(path: Path, payload: Dict[str, Any]) -> None: + path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + + +def _backup_file(path: Path) -> Path: + ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + backup_path = path.with_name(f"{path.name}.bak.{ts}") + shutil.copy2(path, backup_path) + return backup_path + + +def _ensure_mapping(payload: Dict[str, Any], key: str) -> Dict[str, Any]: + value = payload.get(key) + if isinstance(value, dict): + return value + value = {} + payload[key] = value + return value + + +def _update_labels_payload( + payload: Dict[str, Any], + add_labels: Sequence[str], + default_category: str, + overwrite_category: bool, +) -> Dict[str, Any]: + labels = payload.get("labels") + payload["labels"] = _ordered_union(labels if isinstance(labels, list) else [], add_labels) + + keyframes = payload.get("keyframes") + if not isinstance(keyframes, list): + keyframes = [] + labels_per_keyframe = payload.get("labels_per_keyframe") + updated_lpk: Dict[str, List[str]] = {} + if isinstance(labels_per_keyframe, dict): + for raw_key, value in labels_per_keyframe.items(): + updated_lpk[str(raw_key)] = _ordered_union(value if isinstance(value, list) else [], add_labels) + for frame_id in keyframes: + key = str(int(frame_id)) + updated_lpk.setdefault(key, list(payload["labels"])) + payload["labels_per_keyframe"] = updated_lpk + + categories = _ensure_mapping(payload, "label_categories") + reasons = _ensure_mapping(payload, "label_category_reasons") + visuals = _ensure_mapping(payload, "label_visual_descriptions") + for label in add_labels: + if overwrite_category or label not in categories: + categories[label] = default_category + if overwrite_category or label not in reasons: + reasons[label] = "manual_label_add" + visuals.setdefault(label, "") + return payload + + +def _update_meta_payload( + payload: Dict[str, Any], + add_labels: Sequence[str], + default_category: str, + overwrite_category: bool, +) -> Dict[str, Any]: + labels = payload.get("labels") + payload["labels"] = _ordered_union(labels if isinstance(labels, list) else [], add_labels) + + categories = _ensure_mapping(payload, "label_categories") + reasons = _ensure_mapping(payload, "label_category_reasons") + visuals = _ensure_mapping(payload, "label_visual_descriptions") + parsed_payload = payload.get("parsed_payload") + if not isinstance(parsed_payload, dict): + parsed_payload = {} + payload["parsed_payload"] = parsed_payload + objects = parsed_payload.get("objects") + if not isinstance(objects, list): + objects = [] + parsed_payload["objects"] = objects + + existing_names = {_normalize_label(item.get("name")) for item in objects if isinstance(item, dict)} + for label in add_labels: + if overwrite_category or label not in categories: + categories[label] = default_category + if overwrite_category or label not in reasons: + reasons[label] = "manual_label_add" + visuals.setdefault(label, "") + if overwrite_category: + for item in objects: + if not isinstance(item, dict): + continue + if _normalize_label(item.get("name")) != label: + continue + item["category"] = default_category + item["reason"] = "manual_label_add" + if label not in existing_names: + objects.append( + { + "name": label, + "num": 1, + "visual_description": "", + "category": default_category, + "reason": "manual_label_add", + "is_occluded": False, + "occluded_by": [], + } + ) + payload["updated_at"] = datetime.now(timezone.utc).isoformat() + return payload + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Append labels into a video labels JSON before SAM3 masks run.") + parser.add_argument("--labels-json", type=Path, required=True, help="Path to *_labels.json") + parser.add_argument("--add-labels", type=str, required=True, help="Comma-separated labels to append") + parser.add_argument( + "--default-category", + type=str, + default="static", + choices=["static", "rigid", "deform"], + help="Category assigned to newly added labels", + ) + parser.add_argument( + "--overwrite-category", + action="store_true", + help="Also overwrite category for labels that already exist", + ) + parser.add_argument("--print-json", action="store_true", help="Print updated JSON after overwriting it") + args = parser.parse_args(argv) + + labels_json = args.labels_json.expanduser().resolve() + if not labels_json.is_file(): + raise FileNotFoundError(f"labels json not found: {labels_json}") + + add_labels = _parse_label_csv(args.add_labels) + if not add_labels: + raise RuntimeError("No valid labels were provided in --add-labels.") + + payload = _load_json(labels_json) + before_labels = payload.get("labels", []) + before_labels = before_labels if isinstance(before_labels, list) else [] + payload = _update_labels_payload( + payload, + add_labels, + args.default_category, + overwrite_category=bool(args.overwrite_category), + ) + + labels_backup = _backup_file(labels_json) + _write_json(labels_json, payload) + + meta_backup = None + meta_path_raw = str(payload.get("label_category_meta", "")).strip() + if meta_path_raw: + meta_path = Path(meta_path_raw).expanduser() + if not meta_path.is_absolute(): + meta_path = (labels_json.parent / meta_path).resolve() + else: + meta_path = meta_path.resolve() + if meta_path.is_file(): + meta_payload = _load_json(meta_path) + meta_payload = _update_meta_payload( + meta_payload, + add_labels, + args.default_category, + overwrite_category=bool(args.overwrite_category), + ) + meta_backup = _backup_file(meta_path) + _write_json(meta_path, meta_payload) + + after_labels = payload.get("labels", []) + added_now = [label for label in add_labels if label in after_labels and label not in before_labels] + already_present = [label for label in add_labels if label in before_labels] + + print(f"[ok] labels json updated: {labels_json}") + print(f"[ok] backup: {labels_backup}") + print(f"[ok] labels before: {before_labels}") + print(f"[ok] labels after: {after_labels}") + print(f"[ok] added labels: {added_now}") + if already_present: + print(f"[warn] labels already present: {already_present}") + if meta_backup is not None: + print(f"[ok] synced label_category_meta backup: {meta_backup}") + + if args.print_json: + print(json.dumps(payload, indent=2, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/OVOW/engine/tools/amodal_minimal_step.py b/OVOW/engine/tools/amodal_minimal_step.py new file mode 100644 index 0000000000000000000000000000000000000000..456f84d9c3f893e66f2aa1cef96a8059bb4bfd8a --- /dev/null +++ b/OVOW/engine/tools/amodal_minimal_step.py @@ -0,0 +1,497 @@ +#!/usr/bin/env python3 +""" +Minimal "amodal completion" step extracted from OnePoseviaGen-style inputs. + +Goal: + Given a OnePoseviaGen batch/session folder (e.g. temp_local/.../scene_19), + use (rgb + depth + visible mask) to: + 1) estimate an occluder region (depth+mask heuristic), + 2) inpaint that occluder region (OpenCV Telea) to produce a "completed" image. + +This is a *minimal runnable sample* (no diffusion, no external services). +Later you can swap the inpainting backend with your /amodal pipeline. + +Example (scene_19): + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python \\ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/amodal_minimal_step.py \\ + --scene-session-dir /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/temp_local/batch_run_20251211_060644/scene_19 \\ + --object "black fountain pen" \\ + --out-root /tmp/amodal_step_scene_19 +""" + +from __future__ import annotations + +import argparse +import json +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Optional, Tuple + +import cv2 +import numpy as np +from PIL import Image + + +@dataclass(frozen=True) +class OccluderParams: + depth_percentile: float = 90.0 + area_threshold: int = 100 + band_dilate_iters: int = 8 + + +@dataclass(frozen=True) +class CropParams: + out_size: int = 518 + padding_scale: float = 1.2 + + +@dataclass(frozen=True) +class InpaintParams: + radius: float = 3.0 + method: str = "telea" + + +@dataclass(frozen=True) +class Sd2InpaintParams: + model: str = "stabilityai/stable-diffusion-2-inpainting" + device: str = "cuda" + dtype: str = "fp16" + steps: int = 25 + guidance_scale: float = 7.5 + strength: Optional[float] = None + seed: Optional[int] = 0 + negative_prompt: str = "" + + +def _read_bgr(path: Path) -> np.ndarray: + img = cv2.imread(str(path), cv2.IMREAD_COLOR) + if img is None: + raise FileNotFoundError(f"Failed to read image: {path}") + return img + + +def _read_u16_depth(path: Path) -> np.ndarray: + dep = cv2.imread(str(path), cv2.IMREAD_UNCHANGED) + if dep is None: + raise FileNotFoundError(f"Failed to read depth: {path}") + if dep.dtype != np.uint16: + raise ValueError(f"Expected uint16 depth png, got {dep.dtype} from {path}") + return dep + + +def _read_mask(path: Path) -> np.ndarray: + m = cv2.imread(str(path), cv2.IMREAD_GRAYSCALE) + if m is None: + raise FileNotFoundError(f"Failed to read mask: {path}") + return m + + +def _compute_square_crop_bbox(mask: np.ndarray, padding_scale: float) -> Tuple[int, int, int, int]: + """ + Compute a square crop bbox around mask foreground, with a padding factor. + Returns (left, top, right, bottom) in pixel coords. Can be outside image bounds. + """ + ys, xs = np.nonzero(mask) + if len(xs) == 0 or len(ys) == 0: + h, w = mask.shape[:2] + return (0, 0, w, h) + + x0, x1 = int(xs.min()), int(xs.max()) + y0, y1 = int(ys.min()), int(ys.max()) + cx = (x0 + x1) / 2.0 + cy = (y0 + y1) / 2.0 + size = max(x1 - x0, y1 - y0) * float(padding_scale) + size = max(1.0, size) + half = size / 2.0 + left = int(np.floor(cx - half)) + top = int(np.floor(cy - half)) + right = int(np.ceil(cx + half)) + bottom = int(np.ceil(cy + half)) + return (left, top, right, bottom) + + +def _crop_resize_rgb_and_masks( + rgb_bgr: np.ndarray, + bbox: Tuple[int, int, int, int], + out_size: int, + *, + visible_mask: np.ndarray, + occluder_mask: np.ndarray, +) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + rgb = cv2.cvtColor(rgb_bgr, cv2.COLOR_BGR2RGB) + rgb_pil = Image.fromarray(rgb) + + vis_pil = Image.fromarray(visible_mask.astype(np.uint8)) + occ_pil = Image.fromarray(occluder_mask.astype(np.uint8)) + + rgb_crop = rgb_pil.crop(bbox).resize((out_size, out_size), Image.Resampling.LANCZOS) + vis_crop = vis_pil.crop(bbox).resize((out_size, out_size), Image.Resampling.NEAREST) + occ_crop = occ_pil.crop(bbox).resize((out_size, out_size), Image.Resampling.NEAREST) + + rgb_np = np.array(rgb_crop, dtype=np.uint8) + vis_np = np.array(vis_crop, dtype=np.uint8) + occ_np = np.array(occ_crop, dtype=np.uint8) + return rgb_np, vis_np, occ_np + + +def _filter_connected_components(mask_u8: np.ndarray, area_threshold: int) -> np.ndarray: + if mask_u8.dtype != np.uint8: + mask_u8 = mask_u8.astype(np.uint8) + num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(mask_u8, connectivity=8) + out = np.zeros_like(mask_u8, dtype=np.uint8) + for i in range(1, num_labels): + if stats[i, cv2.CC_STAT_AREA] >= int(area_threshold): + out[labels == i] = 255 + return out + + +def compute_occluder_mask_from_depth( + depth_u16: np.ndarray, + visible_mask_u8: np.ndarray, + params: OccluderParams, +) -> np.ndarray: + """ + Depth+mask heuristic (compatible with OnePoseviaGen's generate_final_mask spirit). + Returns an occluder mask uint8 {0,255} in the same resolution as depth/rgb. + """ + if depth_u16.shape[:2] != visible_mask_u8.shape[:2]: + visible_mask_u8 = cv2.resize( + visible_mask_u8, (depth_u16.shape[1], depth_u16.shape[0]), interpolation=cv2.INTER_NEAREST + ) + + object_mask = visible_mask_u8 > 128 + if int(object_mask.sum()) < 10: + return np.zeros(depth_u16.shape[:2], dtype=np.uint8) + + object_depths = depth_u16[object_mask] + thresh = float(np.percentile(object_depths, float(params.depth_percentile))) + + candidate = (depth_u16 > 0) & (depth_u16 < thresh) & (~object_mask) + + x, y, w, h = cv2.boundingRect(object_mask.astype(np.uint8)) + candidate_bbox = np.zeros_like(candidate, dtype=np.uint8) + candidate_bbox[y : y + h, x : x + w] = (candidate[y : y + h, x : x + w]).astype(np.uint8) * 255 + + if int(params.band_dilate_iters) > 0: + kernel = np.ones((3, 3), np.uint8) + dil = cv2.dilate(object_mask.astype(np.uint8) * 255, kernel, iterations=int(params.band_dilate_iters)) + band = (dil > 0) & (~object_mask) + candidate_bbox = np.where(band, candidate_bbox, 0).astype(np.uint8) + + return _filter_connected_components(candidate_bbox, params.area_threshold) + + +def inpaint_occluder( + rgb_u8: np.ndarray, + occluder_mask_u8: np.ndarray, + params: InpaintParams, +) -> np.ndarray: + """ + Inpaint occluder region on RGB image (uint8 RGB), return uint8 RGB. + """ + if rgb_u8.dtype != np.uint8: + raise ValueError("rgb_u8 must be uint8") + if occluder_mask_u8.dtype != np.uint8: + occluder_mask_u8 = occluder_mask_u8.astype(np.uint8) + + method = params.method.lower().strip() + if method == "telea": + flag = cv2.INPAINT_TELEA + elif method in ("ns", "navier", "navier-stokes"): + flag = cv2.INPAINT_NS + else: + raise ValueError(f"Unknown inpaint method: {params.method}") + + bgr = cv2.cvtColor(rgb_u8, cv2.COLOR_RGB2BGR) + out_bgr = cv2.inpaint(bgr, occluder_mask_u8, float(params.radius), flag) + return cv2.cvtColor(out_bgr, cv2.COLOR_BGR2RGB) + + +def _call_with_supported_kwargs(fn, **kwargs): + """Call `fn` with only the kwargs it supports (robust across diffusers versions).""" + import inspect + + sig = inspect.signature(fn) + supported = {k: v for k, v in kwargs.items() if k in sig.parameters and v is not None} + return fn(**supported) + + +def inpaint_occluder_sd2( + rgb_u8: np.ndarray, + occluder_mask_u8: np.ndarray, + prompt: str, + params: Sd2InpaintParams, +) -> np.ndarray: + """ + Stable Diffusion 2 inpainting (diffusers) backend. + Expects RGB uint8 image and uint8 mask {0,255}, returns RGB uint8. + """ + try: + import torch + from diffusers import StableDiffusionInpaintPipeline + except Exception as exc: # noqa: BLE001 + raise RuntimeError( + "diffusers backend requested but dependencies are missing. " + "Install `diffusers`, `accelerate`, `safetensors`, and ensure torch is available." + ) from exc + + if params.device.startswith("cuda") and not torch.cuda.is_available(): + raise RuntimeError(f"Requested device={params.device} but CUDA is not available.") + + dtype = torch.float16 if params.dtype == "fp16" else torch.float32 + pipe = StableDiffusionInpaintPipeline.from_pretrained( + params.model, + torch_dtype=dtype, + ) + pipe = pipe.to(params.device) + + if hasattr(pipe, "enable_attention_slicing"): + pipe.enable_attention_slicing() + if hasattr(pipe, "enable_xformers_memory_efficient_attention"): + try: + pipe.enable_xformers_memory_efficient_attention() + except Exception: + pass + + image_pil = Image.fromarray(rgb_u8) + mask_pil = Image.fromarray(occluder_mask_u8).convert("L") + + generator = None + if params.seed is not None: + generator = torch.Generator(device=params.device).manual_seed(int(params.seed)) + + out = _call_with_supported_kwargs( + pipe, + prompt=prompt, + negative_prompt=params.negative_prompt or None, + image=image_pil, + mask_image=mask_pil, + num_inference_steps=int(params.steps), + guidance_scale=float(params.guidance_scale), + strength=float(params.strength) if params.strength is not None else None, + generator=generator, + ) + images = getattr(out, "images", None) + if not images: + raise RuntimeError("diffusers pipeline returned no images.") + return np.array(images[0].convert("RGB"), dtype=np.uint8) + + +def _whiten_background(rgb_u8: np.ndarray, keep_mask_u8: np.ndarray) -> np.ndarray: + out = rgb_u8.copy() + bg = keep_mask_u8 <= 0 + out[bg] = 255 + return out + + +def _resolve_frame_paths(scene_session_dir: Path, frame: int) -> Tuple[Path, Path]: + rgb_path = scene_session_dir / "rgb" / f"{frame:06d}.jpg" + depth_path = scene_session_dir / "depth" / f"{frame:06d}.png" + if not rgb_path.exists(): + raise FileNotFoundError(f"Missing rgb frame: {rgb_path}") + if not depth_path.exists(): + raise FileNotFoundError(f"Missing depth frame: {depth_path}") + return rgb_path, depth_path + + +def _resolve_object_visible_mask(object_dir: Path, frame: int) -> Path: + mask_path = object_dir / "masks" / f"{frame:06d}.png" + if mask_path.exists(): + return mask_path + final_mask_path = object_dir / "final_mask.png" + if final_mask_path.exists(): + return final_mask_path + raise FileNotFoundError(f"Missing mask for object: {object_dir}") + + +def _load_visible_mask_u8(mask_path: Path) -> np.ndarray: + m = _read_mask(mask_path) + unique = np.unique(m) + if len(unique) <= 4 and 188 in unique: + out = np.zeros_like(m, dtype=np.uint8) + out[m == 188] = 255 + return out + return (m > 0).astype(np.uint8) * 255 + + +def process_one_object( + scene_session_dir: Path, + object_name: str, + frame: int, + out_root: Path, + *, + occ_params: OccluderParams, + crop_params: CropParams, + inpaint_params: InpaintParams, + sd2_params: Optional[Sd2InpaintParams], + backend: str, + save_debug: bool, +) -> Path: + rgb_path, depth_path = _resolve_frame_paths(scene_session_dir, frame) + object_dir = scene_session_dir / "objects" / object_name + if not object_dir.exists(): + raise FileNotFoundError(f"Object dir not found: {object_dir}") + + visible_mask_path = _resolve_object_visible_mask(object_dir, frame) + + rgb_bgr = _read_bgr(rgb_path) + depth_u16 = _read_u16_depth(depth_path) + visible_mask_u8 = _load_visible_mask_u8(visible_mask_path) + if visible_mask_u8.shape[:2] != rgb_bgr.shape[:2]: + visible_mask_u8 = cv2.resize( + visible_mask_u8, (rgb_bgr.shape[1], rgb_bgr.shape[0]), interpolation=cv2.INTER_NEAREST + ) + if depth_u16.shape[:2] != rgb_bgr.shape[:2]: + depth_u16 = cv2.resize(depth_u16, (rgb_bgr.shape[1], rgb_bgr.shape[0]), interpolation=cv2.INTER_NEAREST) + + occluder_mask_u8 = compute_occluder_mask_from_depth(depth_u16, visible_mask_u8, occ_params) + union_mask_u8 = np.maximum(visible_mask_u8, occluder_mask_u8) + + bbox = _compute_square_crop_bbox(union_mask_u8 > 0, crop_params.padding_scale) + rgb_crop, vis_crop, occ_crop = _crop_resize_rgb_and_masks( + rgb_bgr, + bbox, + crop_params.out_size, + visible_mask=visible_mask_u8, + occluder_mask=occluder_mask_u8, + ) + union_crop = np.maximum(vis_crop, occ_crop) + + input_img = _whiten_background(rgb_crop, union_crop) + if backend == "opencv": + completed_rgb = inpaint_occluder(input_img, occ_crop, inpaint_params) + elif backend == "sd2": + if sd2_params is None: + raise ValueError("sd2 backend requires sd2_params") + completed_rgb = inpaint_occluder_sd2(input_img, occ_crop, object_name, sd2_params) + else: + raise ValueError(f"Unknown backend: {backend}") + output_img = _whiten_background(completed_rgb, union_crop) + + out_dir = out_root / object_name + out_dir.mkdir(parents=True, exist_ok=True) + + input_path = out_dir / "input_occluded.png" + output_path = out_dir / "output_completed.png" + Image.fromarray(input_img).save(input_path) + Image.fromarray(output_img).save(output_path) + rgba = np.dstack([output_img, (union_crop > 0).astype(np.uint8) * 255]) + Image.fromarray(rgba).convert("RGBA").save(out_dir / "output_completed_rgba.png") + + if save_debug: + Image.fromarray(vis_crop).save(out_dir / "visible_mask.png") + Image.fromarray(occ_crop).save(out_dir / "occluder_mask.png") + Image.fromarray(union_crop).save(out_dir / "union_mask.png") + + meta = { + "scene_session_dir": str(scene_session_dir), + "object": object_name, + "frame": frame, + "rgb_path": str(rgb_path), + "depth_path": str(depth_path), + "visible_mask_path": str(visible_mask_path), + "occluder_params": asdict(occ_params), + "crop_params": asdict(crop_params), + "inpaint_params": asdict(inpaint_params), + "sd2_params": asdict(sd2_params) if sd2_params is not None else None, + "backend": backend, + "stats": { + "visible_px": int((visible_mask_u8 > 0).sum()), + "occluder_px": int((occluder_mask_u8 > 0).sum()), + "union_px": int((union_mask_u8 > 0).sum()), + "crop_bbox_xyxy": list(map(int, bbox)), + }, + } + (out_dir / "meta.json").write_text(json.dumps(meta, indent=2), encoding="utf-8") + + return output_path + + +def parse_args() -> argparse.Namespace: + p = argparse.ArgumentParser(description="Minimal amodal completion step (depth+mask -> inpaint).") + p.add_argument("--scene-session-dir", type=Path, required=True, help="OnePoseviaGen session dir (e.g. .../scene_19)") + p.add_argument("--object", type=str, default="", help="Object name (subfolder under objects/). If empty, process all.") + p.add_argument("--frame", type=int, default=0, help="Frame index (default: 0)") + p.add_argument("--out-root", type=Path, default=None, help="Output root dir (default: /amodal_step_minimal)") + p.add_argument("--backend", type=str, default="opencv", choices=["opencv", "sd2"], help="Inpainting backend.") + p.add_argument("--no-debug", action="store_true", help="Do not save debug masks/meta.json") + + p.add_argument("--depth-percentile", type=float, default=90.0) + p.add_argument("--area-threshold", type=int, default=100) + p.add_argument("--band-dilate-iters", type=int, default=8) + + p.add_argument("--out-size", type=int, default=518) + p.add_argument("--padding-scale", type=float, default=1.2) + + p.add_argument("--inpaint-radius", type=float, default=3.0) + p.add_argument("--inpaint-method", type=str, default="telea", choices=["telea", "ns"]) + + p.add_argument("--sd2-model", type=str, default="stabilityai/stable-diffusion-2-inpainting") + p.add_argument("--sd2-device", type=str, default="cuda") + p.add_argument("--sd2-dtype", type=str, default="fp16", choices=["fp16", "fp32"]) + p.add_argument("--sd2-steps", type=int, default=25) + p.add_argument("--sd2-guidance", type=float, default=7.5) + p.add_argument("--sd2-strength", type=float, default=None) + p.add_argument("--sd2-seed", type=int, default=0) + p.add_argument("--sd2-negative-prompt", type=str, default="") + return p.parse_args() + + +def main() -> None: + args = parse_args() + scene_session_dir: Path = args.scene_session_dir.resolve() + out_root = (args.out_root or (scene_session_dir / "amodal_step_minimal")).resolve() + out_root.mkdir(parents=True, exist_ok=True) + + occ_params = OccluderParams( + depth_percentile=float(args.depth_percentile), + area_threshold=int(args.area_threshold), + band_dilate_iters=int(args.band_dilate_iters), + ) + crop_params = CropParams(out_size=int(args.out_size), padding_scale=float(args.padding_scale)) + inpaint_params = InpaintParams(radius=float(args.inpaint_radius), method=str(args.inpaint_method)) + sd2_params: Optional[Sd2InpaintParams] = None + if args.backend == "sd2": + sd2_params = Sd2InpaintParams( + model=str(args.sd2_model), + device=str(args.sd2_device), + dtype=str(args.sd2_dtype), + steps=int(args.sd2_steps), + guidance_scale=float(args.sd2_guidance), + strength=float(args.sd2_strength) if args.sd2_strength is not None else None, + seed=int(args.sd2_seed) if args.sd2_seed is not None else None, + negative_prompt=str(args.sd2_negative_prompt), + ) + save_debug = not bool(args.no_debug) + + objects_dir = scene_session_dir / "objects" + if not objects_dir.exists(): + raise FileNotFoundError(f"Missing objects dir: {objects_dir}") + + if args.object: + obj_names = [args.object] + else: + obj_names = sorted([p.name for p in objects_dir.iterdir() if p.is_dir()]) + + outputs = [] + for obj_name in obj_names: + out_path = process_one_object( + scene_session_dir, + obj_name, + int(args.frame), + out_root, + occ_params=occ_params, + crop_params=crop_params, + inpaint_params=inpaint_params, + sd2_params=sd2_params, + backend=str(args.backend), + save_debug=save_debug, + ) + outputs.append(str(out_path)) + + (out_root / "outputs.txt").write_text("\n".join(outputs) + "\n", encoding="utf-8") + print(f"[OK] Wrote {len(outputs)} completed image(s) under: {out_root}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/apply_pose_anim_glb.py b/OVOW/engine/tools/apply_pose_anim_glb.py new file mode 100644 index 0000000000000000000000000000000000000000..d26796fcf84586bcbb7dc51e5bade08b828f8ace --- /dev/null +++ b/OVOW/engine/tools/apply_pose_anim_glb.py @@ -0,0 +1,689 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import math +from copy import deepcopy +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +import numpy as np +import trimesh +from pygltflib import ( + Accessor, + Animation, + AnimationChannel, + AnimationChannelTarget, + AnimationSampler, + Buffer, + BufferView, + GLTF2, + Node, +) + +def sanitize_float_array(arr: np.ndarray) -> np.ndarray: + """ + 将数组中的 NaN, Inf, -Inf 全部替换为 0.0。 + 这是防止 Blender 导入失败的第一道防线。 + """ + if not np.all(np.isfinite(arr)): + print(f"[Warning] Found NaN/Inf in animation data. Cleaning...") + arr = np.nan_to_num(arr, nan=0.0, posinf=0.0, neginf=0.0) + return arr + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Apply pose animation to a GLB.") + parser.add_argument("--input-glb", type=Path, required=True) + parser.add_argument("--poses-world", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--fps", type=float, default=10.0) + parser.add_argument("--summary", type=Path, default=None) + parser.add_argument("--alignment", type=Path, default=None) + parser.add_argument( + "--coord", + type=str, + default="blender_noflip", + choices=("gltf", "opengl", "blender", "blender_noflip", "blender_zup", "raw"), + help="坐标系转换:gltf/opengl/blender(带flip_x)/blender_noflip(不翻转)/blender_zup/raw", + ) + parser.add_argument( + "--merge-animations", + action="store_true", + help="将已有动画(形变)与位姿动画合并为一个动画,避免只播放其中一个", + ) + parser.add_argument( + "--mesh-align", + type=str, + default="none", + choices=("none", "procrustes", "procrustes_reflect"), + help="对动画网格做局部坐标对齐(anim->ref),用于修正形变物体侧躺问题", + ) + parser.add_argument( + "--mesh-align-ref", + type=Path, + default=None, + help="对齐参考网格(scaled_ref_mesh.obj),与 Motion324 动画的基准帧对齐", + ) + parser.add_argument( + "--mesh-align-target", + type=Path, + default=None, + help="对齐目标网格(如 mesh_frames/frame_000040.obj),优先于 input-glb", + ) + parser.add_argument( + "--mesh-align-samples", + type=int, + default=4000, + help="对齐时采样点数", + ) + parser.add_argument("--mesh-rot-x", type=float, default=0.0, help="额外网格旋转(度,绕X)") + parser.add_argument("--mesh-rot-y", type=float, default=0.0, help="额外网格旋转(度,绕Y)") + parser.add_argument("--mesh-rot-z", type=float, default=0.0, help="额外网格旋转(度,绕Z)") + parser.add_argument( + "--strip-anim-trs", + action="store_true", + help="移除输入动画中的平移/旋转/缩放通道,仅保留形变权重", + ) + parser.add_argument( + "--strip-anim-tr", + action="store_true", + help="移除输入动画中的平移/旋转通道,保留缩放与形变权重", + ) + parser.add_argument( + "--mesh-offset-ref", + type=Path, + default=None, + help="用参考网格修正动画网格局部平移(仅沿 Z 方向对齐底部)", + ) + parser.add_argument( + "--mesh-offset-eps", + type=float, + default=0.0, + help="局部平移时额外抬升量(>0 会略微悬空)", + ) + parser.add_argument( + "--project-plane", + action="store_true", + help="逐帧将形变物体投影到对齐平面(z=0),用于让物体落在桌面上", + ) + parser.add_argument( + "--project-plane-eps", + type=float, + default=0.0, + help="投影到平面时的抬升量(>0 会略微悬空)", + ) + parser.add_argument( + "--project-bottom-percent", + type=float, + default=0.03, + help="投影时使用底部百分位(避免异常点抬高物体)", + ) + parser.add_argument( + "--project-use-ref", + action="store_true", + help="使用参考网格(scaled_ref_mesh)来估计接触高度,作为形变物体的代理", + ) + parser.add_argument( + "--project-samples", + type=int, + default=5000, + help="投影时用于估计底部的最大采样点数", + ) + return parser.parse_args() + +def _matrix_to_quat(m: np.ndarray) -> np.ndarray: + """将旋转矩阵转换为四元数,增加鲁棒性保护""" + r = m[:3, :3] + trace = np.trace(r) + + if trace > 0.0: + s = math.sqrt(max(0.0, trace + 1.0)) * 2.0 + w = 0.25 * s + x = (r[2, 1] - r[1, 2]) / s + y = (r[0, 2] - r[2, 0]) / s + z = (r[1, 0] - r[0, 1]) / s + else: + if r[0, 0] > r[1, 1] and r[0, 0] > r[2, 2]: + s = math.sqrt(max(0.0, 1.0 + r[0, 0] - r[1, 1] - r[2, 2])) * 2.0 + w = (r[2, 1] - r[1, 2]) / s + x = 0.25 * s + y = (r[0, 1] + r[1, 0]) / s + z = (r[0, 2] + r[2, 0]) / s + elif r[1, 1] > r[2, 2]: + s = math.sqrt(max(0.0, 1.0 + r[1, 1] - r[0, 0] - r[2, 2])) * 2.0 + w = (r[0, 2] - r[2, 0]) / s + x = (r[0, 1] + r[1, 0]) / s + y = 0.25 * s + z = (r[1, 2] + r[2, 1]) / s + else: + s = math.sqrt(max(0.0, 1.0 + r[2, 2] - r[0, 0] - r[1, 1])) * 2.0 + w = (r[1, 0] - r[0, 1]) / s + x = (r[0, 2] + r[2, 0]) / s + y = (r[1, 2] + r[2, 1]) / s + z = 0.25 * s + + quat = np.array([x, y, z, w], dtype=np.float32) + norm = np.linalg.norm(quat) + if norm < 1e-6: + return np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float32) + return quat / norm + +def _load_alignment(path: Optional[Path]) -> Optional[np.ndarray]: + if path is None: return None + if not path.exists(): raise FileNotFoundError(path) + data = json.loads(path.read_text()) + return np.asarray(data.get("T"), dtype=np.float32) + +def _load_poses(path: Path) -> Dict[int, np.ndarray]: + data = json.loads(path.read_text()) + poses = {} + for k, v in data.items(): + try: poses[int(k)] = np.asarray(v, dtype=np.float32) + except: continue + return poses + +def _mesh_from_path(path: Path) -> trimesh.Trimesh: + mesh = trimesh.load(str(path), force="scene") + if isinstance(mesh, trimesh.Scene): + try: + mesh = mesh.dump(concatenate=True) + except Exception: + geos = [g for g in mesh.geometry.values() if isinstance(g, trimesh.Trimesh)] + mesh = trimesh.util.concatenate(geos) + if not isinstance(mesh, trimesh.Trimesh): + raise RuntimeError(f"Invalid mesh: {path}") + if mesh.vertex_normals is None or len(mesh.vertex_normals) == 0: + mesh.rezero() + mesh.compute_vertex_normals() + return mesh + + +def _dtype_from_component(comp: int): + if comp == 5126: + return np.float32 + if comp == 5123: + return np.uint16 + if comp == 5121: + return np.uint8 + raise ValueError(f"Unsupported componentType: {comp}") + + +def _components_for_type(t: str) -> int: + return {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT4": 16}[t] + + +def _read_accessor(gltf: GLTF2, acc_idx: int) -> np.ndarray: + acc = gltf.accessors[acc_idx] + bv = gltf.bufferViews[acc.bufferView] + blob = gltf.binary_blob() + dtype = _dtype_from_component(acc.componentType) + comps = _components_for_type(acc.type) + count = acc.count + offset = (bv.byteOffset or 0) + (acc.byteOffset or 0) + stride = bv.byteStride or (np.dtype(dtype).itemsize * comps) + data = np.zeros((count, comps), dtype=dtype) + for i in range(count): + start = offset + i * stride + data[i] = np.frombuffer(blob, dtype=dtype, count=comps, offset=start) + return data + + +def _first_primitive_with_positions(gltf: GLTF2): + for mesh in gltf.meshes or []: + for prim in mesh.primitives or []: + if prim.attributes and prim.attributes.POSITION is not None: + return prim + return None + + +def _compute_mesh_offset_z( + anim_glb: Path, + ref_mesh: Path, + mesh_local_T: np.ndarray, + max_samples: int, +) -> float: + """Compute local Z offset so anim bottom matches ref bottom after mesh_local_T.""" + gltf = GLTF2().load(anim_glb) + prim = _first_primitive_with_positions(gltf) + if prim is None: + raise RuntimeError("No mesh primitive found for mesh-offset") + base = _read_accessor(gltf, prim.attributes.POSITION).astype(np.float32) + if base.ndim != 2 or base.shape[1] != 3: + raise RuntimeError("Invalid POSITION accessor shape") + if base.shape[0] > max_samples: + rng = np.random.default_rng(0) + idx = rng.choice(base.shape[0], size=max_samples, replace=False) + base = base[idx] + + ref = _mesh_from_path(ref_mesh) + ref_pts = np.asarray(ref.vertices, dtype=np.float32) + if ref_pts.shape[0] > max_samples: + rng = np.random.default_rng(1) + idx = rng.choice(ref_pts.shape[0], size=max_samples, replace=False) + ref_pts = ref_pts[idx] + + Rm = mesh_local_T[:3, :3] + tm = mesh_local_T[:3, 3] + base_aligned = (Rm @ base.T).T + tm + ref_aligned = (Rm @ ref_pts.T).T + tm + + anim_min_z = float(np.min(base_aligned[:, 2])) + ref_min_z = float(np.min(ref_aligned[:, 2])) + return (ref_min_z - anim_min_z) + + +def _load_weight_animation(gltf: GLTF2, num_targets: int) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]: + """Return (times, weights[K, M]) if weights animation exists.""" + for anim in gltf.animations or []: + if not anim.channels or not anim.samplers: + continue + for ch in anim.channels: + if ch.target and ch.target.path == "weights": + sampler = anim.samplers[ch.sampler] + t = _read_accessor(gltf, sampler.input).reshape(-1) + w = _read_accessor(gltf, sampler.output).reshape(-1) + if num_targets <= 0 or w.size < num_targets: + continue + k = w.size // num_targets + w = w[: k * num_targets].reshape(k, num_targets) + return t.astype(np.float32), w.astype(np.float32) + return None, None + + +def _sample_weights(times_key: np.ndarray, weights_key: np.ndarray, times_query: np.ndarray) -> np.ndarray: + """Linear interpolation of weights per target.""" + if times_key.size == 1: + return np.repeat(weights_key[:1], repeats=len(times_query), axis=0) + out = np.zeros((len(times_query), weights_key.shape[1]), dtype=np.float32) + for j in range(weights_key.shape[1]): + out[:, j] = np.interp(times_query, times_key, weights_key[:, j]).astype(np.float32) + return out + + +def _compute_mesh_align(anim_mesh: Path, ref_mesh: Path, samples: int, reflection: bool = False) -> np.ndarray: + """Compute rigid transform anim->ref using Procrustes (no scale).""" + anim_mesh = _mesh_from_path(anim_mesh) + ref = _mesh_from_path(ref_mesh) + n = int(max(1000, min(samples, 20000))) + anim_pts = anim_mesh.sample(n) + ref_pts = ref.sample(n) + T, _, cost = trimesh.registration.procrustes(anim_pts, ref_pts, reflection=reflection, scale=False) + det = np.linalg.det(T[:3, :3]) + mode = "reflect" if reflection else "rigid" + print(f"[MeshAlign] Procrustes ({mode}) cost={cost:.6f}, det={det:.6f}") + return T.astype(np.float32) + + +def _rot_xyz(rx: float, ry: float, rz: float) -> np.ndarray: + """Build rotation matrix from degrees (XYZ order).""" + rx, ry, rz = np.deg2rad([rx, ry, rz]) + cx, sx = np.cos(rx), np.sin(rx) + cy, sy = np.cos(ry), np.sin(ry) + cz, sz = np.cos(rz), np.sin(rz) + Rx = np.array([[1, 0, 0, 0], [0, cx, -sx, 0], [0, sx, cx, 0], [0, 0, 0, 1]], dtype=np.float32) + Ry = np.array([[cy, 0, sy, 0], [0, 1, 0, 0], [-sy, 0, cy, 0], [0, 0, 0, 1]], dtype=np.float32) + Rz = np.array([[cz, -sz, 0, 0], [sz, cz, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=np.float32) + return (Rz @ Ry @ Rx).astype(np.float32) + + +def _strip_trs_animations(gltf: GLTF2, keep_scale: bool) -> None: + """Remove translation/rotation (and optionally scale), keep weights.""" + if not gltf.animations: + return + new_anims: List[Animation] = [] + for anim in gltf.animations: + if not anim.channels or not anim.samplers: + continue + keep_channels = [] + keep_sampler_indices = [] + for ch in anim.channels: + if ch.target and ch.target.path in ("weights", "scale"): + if ch.target.path == "scale" and not keep_scale: + continue + keep_channels.append(deepcopy(ch)) + keep_sampler_indices.append(ch.sampler) + if not keep_channels: + continue + unique = [] + for idx in keep_sampler_indices: + if idx not in unique: + unique.append(idx) + new_samplers = [anim.samplers[i] for i in unique] + remap = {old: new for new, old in enumerate(unique)} + for ch in keep_channels: + ch.sampler = remap[ch.sampler] + new_anims.append(Animation(samplers=new_samplers, channels=keep_channels)) + gltf.animations = new_anims + +class BufferAppender: + def __init__(self, gltf: GLTF2) -> None: + self.gltf = gltf + if not gltf.buffers: + gltf.buffers = [Buffer(byteLength=0)] + + current_blob = gltf.binary_blob() + self.buffer = bytearray(current_blob if current_blob is not None else b"") + + if gltf.bufferViews is None: gltf.bufferViews = [] + if gltf.accessors is None: gltf.accessors = [] + + def _align(self, alignment: int = 4) -> None: + padding = (-len(self.buffer)) % alignment + if padding: + self.buffer.extend(b"\x00" * padding) + + def add_array(self, arr: np.ndarray, accessor_type: str, component_type: int, normalized: bool = False) -> int: + arr = sanitize_float_array(np.asarray(arr)) + + self._align(4) + byte_offset = len(self.buffer) + data = arr.tobytes() + self.buffer.extend(data) + + bv = BufferView( + buffer=0, + byteOffset=byte_offset, + byteLength=len(data), + ) + bv_index = len(self.gltf.bufferViews) + self.gltf.bufferViews.append(bv) + + min_val = None + max_val = None + + acc = Accessor( + bufferView=bv_index, + byteOffset=0, + componentType=component_type, + count=len(arr), + type=accessor_type, + min=min_val, + max=max_val, + normalized=normalized, + ) + acc_index = len(self.gltf.accessors) + self.gltf.accessors.append(acc) + return acc_index + + def finalize(self) -> None: + self._align(4) + self.gltf.buffers[0].byteLength = len(self.buffer) + self.gltf.set_binary_blob(bytes(self.buffer)) + + +def main() -> None: + args = parse_args() + if not args.input_glb.exists(): + print(f"Error: Input file {args.input_glb} does not exist.") + return + + gltf = GLTF2().load(args.input_glb) + + if args.strip_anim_tr or args.strip_anim_trs: + _strip_trs_animations(gltf, keep_scale=bool(args.strip_anim_tr and not args.strip_anim_trs)) + + if args.summary and args.summary.exists(): + summary = json.loads(args.summary.read_text()) + args.fps = float(summary.get("fps", args.fps)) + + align_T = _load_alignment(args.alignment) + + if args.coord == "raw": + cv_to_gltf = np.eye(4, dtype=np.float32) + elif args.coord == "opengl": + cv_to_gltf = np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float32) + elif args.coord == "blender": + rot_x_neg_90 = np.array([[1,0,0,0],[0,0,1,0],[0,-1,0,0],[0,0,0,1]], dtype=np.float32) + flip_x = np.diag([-1, 1, 1, 1]).astype(np.float32) + cv_to_gltf = flip_x @ (rot_x_neg_90 @ np.diag([1, -1, 1, 1]).astype(np.float32)) + elif args.coord == "blender_noflip": + rot_x_neg_90 = np.array([[1,0,0,0],[0,0,1,0],[0,-1,0,0],[0,0,0,1]], dtype=np.float32) + cv_to_gltf = rot_x_neg_90 @ np.diag([1, -1, 1, 1]).astype(np.float32) + elif args.coord == "blender_zup": + cv_to_gltf = np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + else: + cv_to_gltf = np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + + poses = _load_poses(args.poses_world) + if not poses: + raise RuntimeError("No poses found") + + num_frames = max(poses.keys()) + 1 + times = np.arange(num_frames, dtype=np.float32) / max(1e-6, args.fps) + + mesh_align_T: Optional[np.ndarray] = None + if args.mesh_align != "none": + if args.mesh_align_ref is None: + raise RuntimeError("--mesh-align-ref is required when --mesh-align != none") + if not args.mesh_align_ref.exists(): + raise FileNotFoundError(args.mesh_align_ref) + align_src = args.mesh_align_target if args.mesh_align_target is not None else args.input_glb + if not align_src.exists(): + raise FileNotFoundError(align_src) + reflect = args.mesh_align == "procrustes_reflect" + mesh_align_T = _compute_mesh_align(align_src, args.mesh_align_ref, args.mesh_align_samples, reflection=reflect) + mesh_rot_T = None + if abs(args.mesh_rot_x) > 1e-6 or abs(args.mesh_rot_y) > 1e-6 or abs(args.mesh_rot_z) > 1e-6: + mesh_rot_T = _rot_xyz(args.mesh_rot_x, args.mesh_rot_y, args.mesh_rot_z) + + mesh_local_T = np.eye(4, dtype=np.float32) + if mesh_rot_T is not None: + mesh_local_T = mesh_rot_T @ mesh_local_T + if mesh_align_T is not None: + mesh_local_T = mesh_align_T @ mesh_local_T + + mesh_offset_T = None + if args.mesh_offset_ref is not None: + if not args.mesh_offset_ref.exists(): + raise FileNotFoundError(args.mesh_offset_ref) + dz = _compute_mesh_offset_z(args.input_glb, args.mesh_offset_ref, mesh_local_T, max_samples=5000) + dz = float(dz + args.mesh_offset_eps) + mesh_offset_T = np.eye(4, dtype=np.float32) + mesh_offset_T[2, 3] = dz + mesh_local_T = mesh_offset_T @ mesh_local_T + + proj_base = None + proj_deltas = None + proj_weights = None + if args.project_plane: + if align_T is None: + raise RuntimeError("--project-plane requires --alignment") + prim = _first_primitive_with_positions(gltf) + if prim is None: + raise RuntimeError("No mesh primitive found for projection") + base_full = _read_accessor(gltf, prim.attributes.POSITION).astype(np.float32) + if base_full.ndim != 2 or base_full.shape[1] != 3: + raise RuntimeError("Invalid POSITION accessor shape") + max_samples = max(100, int(args.project_samples)) + if base_full.shape[0] > max_samples: + rng = np.random.default_rng(0) + idx = rng.choice(base_full.shape[0], size=max_samples, replace=False) + proj_base = base_full[idx] + else: + idx = None + proj_base = base_full + if prim.targets: + deltas = [] + for target in prim.targets: + if "POSITION" in target: + dpos = _read_accessor(gltf, target["POSITION"]).astype(np.float32) + if idx is not None: + dpos = dpos[idx] + deltas.append(dpos) + if deltas: + proj_deltas = np.stack(deltas, axis=0) + t_key, w_key = _load_weight_animation(gltf, proj_deltas.shape[0]) + if t_key is not None and w_key is not None: + proj_weights = _sample_weights(t_key, w_key, times) + else: + proj_weights = np.zeros((len(times), proj_deltas.shape[0]), dtype=np.float32) + + translations = [] + rotations = [] + w_T_o0 = None + + for f in range(num_frames): + pose = poses.get(f) + if pose is None: + if len(poses) > 0: + pose = poses[max(poses.keys())] + else: + pose = np.eye(4) + + w_T_o = sanitize_float_array(pose.astype(np.float32)) + + if align_T is not None: + w_T_o = align_T @ w_T_o + if f == 0: + w_T_o0 = w_T_o.copy() + + t = w_T_o[:3, 3] + q = _matrix_to_quat(w_T_o) + + if args.project_plane and proj_base is not None: + if args.project_use_ref and args.mesh_offset_ref is not None and args.mesh_offset_ref.exists(): + ref_mesh = _mesh_from_path(args.mesh_offset_ref) + v_local = np.asarray(ref_mesh.vertices, dtype=np.float32) + if v_local.shape[0] > args.project_samples: + rng = np.random.default_rng(0) + idx = rng.choice(v_local.shape[0], size=args.project_samples, replace=False) + v_local = v_local[idx] + else: + if proj_deltas is not None and proj_weights is not None: + w = proj_weights[min(f, proj_weights.shape[0] - 1)] + v_local = proj_base + np.tensordot(w, proj_deltas, axes=(0, 0)) + else: + v_local = proj_base + Rm = mesh_local_T[:3, :3] + tm = mesh_local_T[:3, 3] + v_local = (Rm @ v_local.T).T + tm + Rw = w_T_o[:3, :3] + tw = w_T_o[:3, 3] + v_world = (Rw @ v_local.T).T + tw + z_vals = v_world[:, 2] + if z_vals.size == 0: + min_z = 0.0 + else: + k = max(1, int(len(z_vals) * max(1e-6, min(args.project_bottom_percent, 0.5)))) + min_z = float(np.partition(z_vals, k - 1)[k - 1]) + delta = -(min_z - float(args.project_plane_eps)) + min_after = float(np.min(z_vals)) + delta + if min_after > 0.0: + delta -= min_after + t = t + np.array([0.0, 0.0, delta], dtype=np.float32) + + translations.append(t.tolist()) + rotations.append(q.tolist()) + + if args.project_plane and proj_base is not None and w_T_o0 is not None: + if proj_deltas is not None and proj_weights is not None: + w0 = proj_weights[0] + v_local = proj_base + np.tensordot(w0, proj_deltas, axes=(0, 0)) + else: + v_local = proj_base + Rm = mesh_local_T[:3, :3] + tm = mesh_local_T[:3, 3] + v_local = (Rm @ v_local.T).T + tm + v_world = (w_T_o0[:3, :3] @ v_local.T).T + w_T_o0[:3, 3] + v_gltf = (cv_to_gltf[:3, :3] @ v_world.T).T + cv_to_gltf[:3, 3] + min_y = float(np.min(v_gltf[:, 1])) if v_gltf.size > 0 else 0.0 + if min_y > 0.0: + inv_cv = np.linalg.inv(cv_to_gltf) + delta_vec = inv_cv @ np.array([0.0, -min_y, 0.0, 0.0], dtype=np.float32) + delta_xyz = delta_vec[:3] + translations = [(np.asarray(t) + delta_xyz).tolist() for t in translations] + + if gltf.nodes is None: gltf.nodes = [] + + old_scene_nodes = [] + if gltf.scene is not None and gltf.scenes: + if gltf.scenes[gltf.scene].nodes: + old_scene_nodes = list(gltf.scenes[gltf.scene].nodes) + + root_cv = Node(name="root_cv2gl", matrix=cv_to_gltf.T.flatten().tolist()) + root_cv_index = len(gltf.nodes) + gltf.nodes.append(root_cv) + + pose_root = Node(name="pose_root") + pose_root_index = len(gltf.nodes) + gltf.nodes.append(pose_root) + + gltf.nodes[root_cv_index].children = [pose_root_index] + if mesh_align_T is not None or mesh_rot_T is not None or mesh_offset_T is not None: + parent_idx = pose_root_index + if mesh_align_T is not None: + mesh_align = Node(name="mesh_align", matrix=mesh_align_T.T.flatten().tolist()) + mesh_align_index = len(gltf.nodes) + gltf.nodes.append(mesh_align) + gltf.nodes[parent_idx].children = [mesh_align_index] + parent_idx = mesh_align_index + if mesh_rot_T is not None: + mesh_rot = Node(name="mesh_rot", matrix=mesh_rot_T.T.flatten().tolist()) + mesh_rot_index = len(gltf.nodes) + gltf.nodes.append(mesh_rot) + gltf.nodes[parent_idx].children = [mesh_rot_index] + parent_idx = mesh_rot_index + if mesh_offset_T is not None: + mesh_offset = Node(name="mesh_offset", matrix=mesh_offset_T.T.flatten().tolist()) + mesh_offset_index = len(gltf.nodes) + gltf.nodes.append(mesh_offset) + gltf.nodes[parent_idx].children = [mesh_offset_index] + parent_idx = mesh_offset_index + gltf.nodes[parent_idx].children = old_scene_nodes + else: + gltf.nodes[pose_root_index].children = old_scene_nodes + + if gltf.scene is not None and gltf.scenes: + gltf.scenes[gltf.scene].nodes = [root_cv_index] + + builder = BufferAppender(gltf) + + time_acc = builder.add_array(times, "SCALAR", 5126) + trans_acc = builder.add_array(np.asarray(translations, dtype=np.float32), "VEC3", 5126) + rot_acc = builder.add_array(np.asarray(rotations, dtype=np.float32), "VEC4", 5126) + + sampler_t = AnimationSampler(input=time_acc, output=trans_acc, interpolation="LINEAR") + sampler_r = AnimationSampler(input=time_acc, output=rot_acc, interpolation="LINEAR") + + channel_t = AnimationChannel(sampler=0, target=AnimationChannelTarget(node=pose_root_index, path="translation")) + channel_r = AnimationChannel(sampler=1, target=AnimationChannelTarget(node=pose_root_index, path="rotation")) + + anim = Animation(samplers=[sampler_t, sampler_r], channels=[channel_t, channel_r]) + + if gltf.animations is None: + gltf.animations = [] + + if args.merge_animations and len(gltf.animations) > 0: + merged_samplers = [] + merged_channels = [] + for a in gltf.animations: + base = len(merged_samplers) + if a.samplers: + merged_samplers.extend(a.samplers) + if a.channels: + for ch in a.channels: + ch_new = deepcopy(ch) + ch_new.sampler = ch_new.sampler + base + merged_channels.append(ch_new) + + base = len(merged_samplers) + merged_samplers.append(sampler_t) + merged_samplers.append(sampler_r) + channel_t.sampler = base + 0 + channel_r.sampler = base + 1 + merged_channels.append(channel_t) + merged_channels.append(channel_r) + + gltf.animations = [Animation(samplers=merged_samplers, channels=merged_channels)] + else: + gltf.animations.append(anim) + + builder.finalize() + + args.output.parent.mkdir(parents=True, exist_ok=True) + gltf.save(args.output) + print(f"[OK] Wrote: {args.output}") + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/augment_single_image_masks.py b/OVOW/engine/tools/augment_single_image_masks.py new file mode 100644 index 0000000000000000000000000000000000000000..1b6d1761fb071aae89ffebb19d495a296d345c69 --- /dev/null +++ b/OVOW/engine/tools/augment_single_image_masks.py @@ -0,0 +1,593 @@ +#!/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-sam3/bin/python +from __future__ import annotations + +import argparse +import importlib.util +import json +import re +import shutil +import subprocess +import sys +from collections import OrderedDict +from datetime import datetime +from pathlib import Path +from typing import Any, Dict, List, Sequence + +import numpy as np +from PIL import Image + +THIS_DIR = Path(__file__).resolve().parent +ONEPOSE_ROOT = THIS_DIR.parent +PROJECT_ROOT = ONEPOSE_ROOT.parent +SINGLE_IMAGE_MASKS_SCRIPT = PROJECT_ROOT / "Grounded_SAM2" / "qwen" / "qwen_sam3_single_image_masks.py" +RERUN_STEP6_SCRIPT = ONEPOSE_ROOT / "tools" / "rerun_step6_objects.py" +DEFAULT_BATCH_CONFIG = ONEPOSE_ROOT / "config" / "batch_config_example_legacy.json" +DEFAULT_SAM3_CKPT = PROJECT_ROOT / "sam3" / "checkpoints" / "sam3" / "sam3.pt" +DEFAULT_OPG_PY = Path("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python") + + +def load_single_image_masks_module(): + spec = importlib.util.spec_from_file_location("qwen_sam3_single_image_masks", SINGLE_IMAGE_MASKS_SCRIPT) + if spec is None or spec.loader is None: + raise RuntimeError(f"Failed to load module: {SINGLE_IMAGE_MASKS_SCRIPT}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +M = load_single_image_masks_module() + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Incrementally add single-image SAM3 masks for new labels and sync scene/config metadata." + ) + parser.add_argument("--run-dir", type=Path, required=True, help="Existing image-pipeline run dir") + parser.add_argument("--labels", type=str, required=True, help="Comma-separated labels to add or retry") + parser.add_argument( + "--default-category", + type=str, + choices=("static", "rigid"), + default="static", + help="Category assigned to newly added labels", + ) + parser.add_argument("--min-obj-area", type=int, default=200, help="Minimum accepted mask area") + parser.add_argument( + "--max-instances-per-label", + type=int, + default=20, + help="Maximum kept instances for each new label", + ) + parser.add_argument( + "--sam3-confidence-threshold", + type=float, + default=0.35, + help="SAM3 confidence threshold", + ) + parser.add_argument( + "--sam3-ckpt", + type=Path, + default=DEFAULT_SAM3_CKPT, + help="SAM3 checkpoint path", + ) + parser.add_argument( + "--batch-config", + type=Path, + default=None, + help="Optional batch config override; defaults to existing pipeline_config.json value", + ) + parser.add_argument( + "--rerun-step6", + type=int, + choices=[0, 1], + default=0, + help="1: immediately rerun newly added objects; if none were added, rerun existing objects matching the requested labels", + ) + parser.add_argument( + "--anchor-frame", + type=int, + default=-1, + help="Optional anchor-frame override when --rerun-step6=1", + ) + parser.add_argument( + "--opg-python", + type=Path, + default=DEFAULT_OPG_PY, + help="Python executable used for rerun_step6_objects.py", + ) + parser.add_argument( + "--backup", + type=int, + choices=[0, 1], + default=1, + help="1: create timestamped backups for modified JSON files before writing", + ) + parser.add_argument("--dry-run", action="store_true", help="Analyze and print actions without writing files") + return parser.parse_args() + + +def normalize_labels(raw: str) -> List[str]: + labels = [] + seen = set() + for piece in str(raw or "").split(","): + name = M._simple_normalize(piece) + if not name or name in seen: + continue + seen.add(name) + labels.append(name) + return labels + + +def ordered_union(*sequences: Sequence[str]) -> List[str]: + out = [] + seen = set() + for seq in sequences: + for item in seq: + name = M._simple_normalize(item) + if not name or name in seen: + continue + seen.add(name) + out.append(name) + return out + + +def load_json(path: Path) -> Dict[str, Any]: + return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} + + +def resolve_image_path(scene_dir: Path, labels_json_path: Path) -> Path: + try: + return M._find_single_image(scene_dir) + except RuntimeError: + pass + + labels_payload = load_json(labels_json_path) if labels_json_path.exists() else {} + for key in ("image", "video"): + raw = str(labels_payload.get(key, "")).strip() + if not raw: + continue + candidate = Path(raw).expanduser() + if not candidate.is_absolute(): + candidate = (scene_dir / candidate).resolve() + if candidate.is_file(): + return candidate + + raise RuntimeError( + f"Cannot resolve scene image from {scene_dir}. " + f"Tried scene.json / in-dir image discovery / labels json: {labels_json_path}" + ) + + +def save_json(path: Path, payload: Dict[str, Any], dry_run: bool) -> None: + if dry_run: + return + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8") + + +def backup_file(path: Path, dry_run: bool) -> None: + if dry_run or not path.exists(): + return + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + backup = path.with_name(f"{path.name}.bak_{ts}") + shutil.copy2(path, backup) + + +def resolve_context(run_dir: Path) -> Dict[str, Path | str]: + run_dir = run_dir.expanduser().resolve() + if not run_dir.is_dir(): + raise FileNotFoundError(f"run dir not found: {run_dir}") + + scene_name = run_dir.name + scene_dir = run_dir.parent.parent + if not scene_dir.is_dir(): + raise FileNotFoundError(f"scene dir not found from run dir: {scene_dir}") + + out_root = scene_dir + labels_json = out_root / "metadata" / f"{scene_name}_labels.json" + summary_json = out_root / "metadata" / f"{scene_name}_mask_summary.json" + state_json = out_root / "metadata" / f"{scene_name}_image_step_state.json" + cfg_main = out_root / "recon_ready" / scene_name / "pipeline_config.json" + cfg_effective = out_root / "recon_ready" / scene_name / "pipeline_config_effective.json" + scene_json = scene_dir / "scene.json" + + return { + "run_dir": run_dir, + "scene_dir": scene_dir, + "scene_name": scene_name, + "out_root": out_root, + "labels_json": labels_json, + "summary_json": summary_json, + "state_json": state_json, + "cfg_main": cfg_main, + "cfg_effective": cfg_effective, + "scene_json": scene_json, + } + + +def infer_batch_config(cfg_main_path: Path, override: Path | None) -> Path: + if override is not None: + return override.expanduser().resolve() + if cfg_main_path.exists(): + payload = load_json(cfg_main_path) + raw = str(payload.get("batch_config", "")).strip() + if raw: + return Path(raw).expanduser().resolve() + return DEFAULT_BATCH_CONFIG.resolve() + + +def load_existing_masks(scene_dir: Path, summary_objects: Sequence[Dict[str, Any]]) -> List[np.ndarray]: + masks: List[np.ndarray] = [] + for obj in summary_objects: + raw = str(obj.get("mask", "")).strip() + if not raw: + continue + mask_path = (scene_dir / raw).resolve() + if not mask_path.exists(): + continue + mask = np.asarray(Image.open(mask_path).convert("L")) > 0 + if mask.any(): + masks.append(mask) + return masks + + +def next_instance_index(label: str, existing_names: Sequence[str]) -> int: + label_id = M._safe_id(label) + pattern = re.compile(rf"^{re.escape(label_id)}_(\d+)$") + max_idx = 0 + for name in existing_names: + match = pattern.match(str(name)) + if match: + max_idx = max(max_idx, int(match.group(1))) + return max_idx + 1 + + +def merge_dropped_objects(existing: Sequence[Dict[str, Any]], updates: Dict[str, Dict[str, Any]]) -> List[Dict[str, Any]]: + merged: "OrderedDict[str, Dict[str, Any]]" = OrderedDict() + for item in existing: + label = M._simple_normalize(item.get("label", "")) + if not label: + continue + merged[label] = dict(item) + for label, item in updates.items(): + if item is None: + merged.pop(label, None) + else: + merged[label] = dict(item) + return list(merged.values()) + + +def update_state_file(state_path: Path, updates: Dict[str, Any], dry_run: bool) -> None: + payload = load_json(state_path) if state_path.exists() else {} + for key, value in updates.items(): + payload[key] = value + save_json(state_path, payload, dry_run=dry_run) + + +def collect_object_names_for_labels(objects: Sequence[Dict[str, Any]], labels: Sequence[str]) -> List[str]: + wanted = {M._simple_normalize(label) for label in labels if M._simple_normalize(label)} + names: List[str] = [] + seen = set() + for obj in objects: + label = M._simple_normalize(obj.get("label", "")) + name = str(obj.get("name", "")).strip() + if not name or label not in wanted or name in seen: + continue + seen.add(name) + names.append(name) + return names + + +def main() -> None: + args = parse_args() + labels = normalize_labels(args.labels) + if not labels: + raise SystemExit("ERROR: at least one valid label is required.") + if int(args.min_obj_area) <= 0: + raise SystemExit(f"ERROR: --min-obj-area must be > 0 (got {args.min_obj_area})") + if int(args.max_instances_per_label) <= 0: + raise SystemExit(f"ERROR: --max-instances-per-label must be > 0 (got {args.max_instances_per_label})") + if int(args.anchor_frame) < -1: + raise SystemExit(f"ERROR: --anchor-frame must be >= -1 (got {args.anchor_frame})") + + ctx = resolve_context(args.run_dir) + run_dir = ctx["run_dir"] + scene_dir = ctx["scene_dir"] + scene_name = str(ctx["scene_name"]) + out_root = ctx["out_root"] + labels_json_path = ctx["labels_json"] + summary_json_path = ctx["summary_json"] + state_json_path = ctx["state_json"] + cfg_main_path = ctx["cfg_main"] + cfg_effective_path = ctx["cfg_effective"] + scene_json_path = ctx["scene_json"] + + batch_config = infer_batch_config(cfg_main_path, args.batch_config) + if not batch_config.exists(): + raise FileNotFoundError(f"batch config not found: {batch_config}") + sam3_ckpt = args.sam3_ckpt.expanduser().resolve() + if not sam3_ckpt.exists(): + raise FileNotFoundError(f"SAM3 checkpoint not found: {sam3_ckpt}") + + image_path = resolve_image_path(scene_dir, labels_json_path) + width, height = M._image_info(image_path) + + labels_payload = load_json(labels_json_path) if labels_json_path.exists() else {} + existing_labels = [M._simple_normalize(x) for x in labels_payload.get("labels", []) if M._simple_normalize(x)] + + summary_payload = load_json(summary_json_path) if summary_json_path.exists() else {} + existing_summary_objects = list(summary_payload.get("objects", [])) if isinstance(summary_payload.get("objects", []), list) else [] + existing_dropped = list(summary_payload.get("dropped_objects", [])) if isinstance(summary_payload.get("dropped_objects", []), list) else [] + + scene_payload = load_json(scene_json_path) if scene_json_path.exists() else {} + existing_scene_objects = list(scene_payload.get("objects", [])) if isinstance(scene_payload.get("objects", []), list) else [] + + cfg_main_payload = load_json(cfg_main_path) if cfg_main_path.exists() else {} + existing_cfg_objects = list(cfg_main_payload.get("objects", [])) if isinstance(cfg_main_payload.get("objects", []), list) else [] + + all_labels = ordered_union(existing_labels, labels) + label_to_candidates, mask_width, mask_height = M._collect_sam3_candidates( + image_path=image_path, + labels=labels, + ckpt_path=str(sam3_ckpt), + confidence_threshold=float(args.sam3_confidence_threshold), + ) + + existing_names = [str(obj.get("name", "")).strip() for obj in existing_summary_objects if str(obj.get("name", "")).strip()] + existing_mask_arrays = load_existing_masks(scene_dir, existing_summary_objects) + merged_masks = list(existing_mask_arrays) + new_scene_objects: List[Dict[str, Any]] = [] + new_summary_objects: List[Dict[str, Any]] = [] + new_cfg_objects: List[Dict[str, Any]] = [] + dropped_updates: Dict[str, Dict[str, Any] | None] = {} + created_names: List[str] = [] + + for label in labels: + selected = M._select_instances_for_label( + candidates=label_to_candidates.get(label, []), + min_obj_area=int(args.min_obj_area), + max_instances_per_label=int(args.max_instances_per_label), + ) + accepted = [] + for candidate in selected: + mask = np.asarray(candidate["mask"]).astype(bool) + if M._is_duplicate_mask(mask, merged_masks): + continue + merged_masks.append(mask) + accepted.append(candidate) + + if not accepted: + dropped_updates[label] = {"label": label, "reason": "no_valid_mask"} + continue + + dropped_updates[label] = None + next_idx = next_instance_index(label, existing_names + created_names) + for candidate in accepted: + obj_name = f"{M._safe_id(label)}_{next_idx:02d}" + next_idx += 1 + created_names.append(obj_name) + + mask_rel = Path("masks") / obj_name / "frame_000000.png" + mask_path = (scene_dir / mask_rel).resolve() + area = int(candidate.get("area", 0)) + if not args.dry_run: + area = M._save_mask(np.asarray(candidate["mask"]).astype(bool), mask_path) + + new_scene_objects.append( + { + "id": obj_name, + "name": obj_name, + "label": label, + "prompt": label, + "mask": str(mask_rel.as_posix()), + "is_occluded": False, + "category": args.default_category, + } + ) + new_summary_objects.append( + { + "name": obj_name, + "label": label, + "frames_with_mask": 1, + "max_area": int(area), + "median_area": float(area), + "valid_frames": 1, + "occluded_frames": 0, + "median_iou": 1.0, + "median_motion_px": 0.0, + "is_static": args.default_category == "static", + "category": args.default_category, + "category_source": "manual_label_add", + "backend": "sam3", + "score": float(candidate.get("score", 0.0)), + "proposal_index": int(candidate.get("proposal_index", -1)), + "masks_dir": str(mask_path.parent.resolve()), + "mask": str(mask_rel.as_posix()), + } + ) + new_cfg_objects.append( + { + "name": obj_name, + "masks_dir": str(mask_path.parent.resolve()), + "category": args.default_category, + "is_occluded": False, + } + ) + + labels_payload = dict(labels_payload) + labels_payload.update( + { + "video": str(image_path), + "video_name": scene_name, + "image": str(image_path), + "image_name": image_path.name, + "num_frames": 1, + "fps": 1.0, + "width": int(width), + "height": int(height), + "keyframes": [0], + "labels": all_labels, + "labels_per_keyframe": {"0": list(all_labels)}, + } + ) + + merged_scene_objects = existing_scene_objects + new_scene_objects + scene_payload = { + "image": image_path.name, + "objects": merged_scene_objects, + } + + merged_dropped = merge_dropped_objects(existing_dropped, dropped_updates) + merged_summary_objects = existing_summary_objects + new_summary_objects + summary_payload = { + "scene_dir": str(scene_dir), + "scene_name": scene_name, + "video": str(image_path), + "video_name": scene_name, + "image": str(image_path), + "image_name": image_path.name, + "num_frames": 1, + "fps": 1.0, + "width": int(mask_width), + "height": int(mask_height), + "keyframes": [0], + "labels": all_labels, + "labels_per_keyframe": {"0": list(all_labels)}, + "objects": merged_summary_objects, + "dropped_objects": merged_dropped, + "mask_root": str((scene_dir / "masks").resolve()), + "labels_json": str(labels_json_path.resolve()), + "backend": "sam3", + } + + cfg_main_payload = dict(cfg_main_payload) + cfg_main_payload.update( + { + "batch_config": str(batch_config.resolve()), + "scene_dir": str(scene_dir), + "scene_name": scene_name, + "image_path": str(image_path), + "output_root": str(out_root), + "mask_glob": "frame_*.png", + "tracker_mask_mode": "static", + "objects": existing_cfg_objects + new_cfg_objects, + } + ) + + print(f"[info] scene_dir: {scene_dir}") + print(f"[info] run_dir: {run_dir}") + print(f"[info] requested labels: {labels}") + print(f"[info] created objects: {created_names if created_names else 'none'}") + if merged_dropped: + dropped_labels = [str(item.get('label', '')) for item in merged_dropped] + print(f"[info] dropped labels: {dropped_labels}") + + existing_matching_names = collect_object_names_for_labels(existing_summary_objects, labels) + rerun_targets: List[str] = [] + rerun_mode = "" + if int(args.rerun_step6) == 1: + if created_names: + rerun_targets = list(created_names) + rerun_mode = "new_objects" + elif existing_matching_names: + rerun_targets = list(existing_matching_names) + rerun_mode = "existing_label_matches" + if rerun_mode == "existing_label_matches": + print(f"[info] rerun existing objects: {rerun_targets}") + + if not args.dry_run: + for path in [labels_json_path, summary_json_path, scene_json_path, cfg_main_path]: + if int(args.backup) == 1: + backup_file(path, dry_run=False) + + save_json(labels_json_path, labels_payload, dry_run=False) + save_json(summary_json_path, summary_payload, dry_run=False) + save_json(scene_json_path, scene_payload, dry_run=False) + save_json(cfg_main_path, cfg_main_payload, dry_run=False) + + rerun_ok = False + rerun_attempted = False + rerun_return_code = 0 + if rerun_targets: + rerun_cmd = [ + str(args.opg_python.expanduser().resolve()), + str(RERUN_STEP6_SCRIPT.resolve()), + "--run-dir", + str(run_dir), + "--config", + str(cfg_main_path), + "--output-effective-config", + str(cfg_effective_path), + "--objects", + ",".join(rerun_targets), + "--only-failed", + "0", + ] + if int(args.anchor_frame) >= 0: + rerun_cmd.extend(["--anchor-frame", str(int(args.anchor_frame))]) + print("[rerun] command:") + print(" " + " ".join(rerun_cmd)) + if not args.dry_run: + rerun_attempted = True + completed = subprocess.run(rerun_cmd, check=False) + rerun_return_code = int(completed.returncode) + rerun_ok = rerun_return_code == 0 + if not rerun_ok: + print( + f"[warn] rerun step6 exited with code {rerun_return_code}; " + "marking inputs clean so later step 16 can continue." + ) + + effective_config_value = load_json(state_json_path).get("effective_config", "") + if rerun_targets and cfg_effective_path.exists(): + effective_config_value = str(cfg_effective_path.resolve()) + + dirty_flag = "0" if (rerun_ok or rerun_attempted) else "1" + update_state_file( + state_json_path, + { + "labels_json": str(labels_json_path.resolve()), + "mask_summary": str(summary_json_path.resolve()), + "scene_json": str(scene_json_path.resolve()), + "run_dir": str(run_dir), + "effective_config": effective_config_value, + "inputs_dirty": dirty_flag, + }, + dry_run=args.dry_run, + ) + + print(f"[ok] labels json: {labels_json_path}") + print(f"[ok] summary json: {summary_json_path}") + print(f"[ok] scene json: {scene_json_path}") + print(f"[ok] pipeline config: {cfg_main_path}") + if rerun_ok: + print(f"[ok] rerun step6 succeeded for: {', '.join(rerun_targets)}") + elif rerun_attempted: + print(f"[ok] rerun step6 attempted for: {', '.join(rerun_targets)}") + print("[ok] inputs marked clean; you can continue with step 16.") + elif created_names: + print("[next] Added masks/config only. Rerun step 6 before later steps, for example:") + print( + " " + + " ".join( + [ + "bash", + str((ONEPOSE_ROOT / "run_steps_scene_image_pipeline.sh").resolve()), + "--scene-dir", + str(scene_dir), + "--name", + scene_name, + "--run-dir", + str(run_dir), + "6", + ] + ) + ) + elif int(args.rerun_step6) == 1 and existing_matching_names: + print("[next] Matching objects were found but rerun did not execute. Re-run without --dry-run to clean inputs.") + else: + print("[next] No new objects were created; inspect dropped labels or lower the SAM3 threshold.") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/augment_video_masks.py b/OVOW/engine/tools/augment_video_masks.py new file mode 100644 index 0000000000000000000000000000000000000000..7a4787f28106570f2747f5165d4d4366d5fccafa --- /dev/null +++ b/OVOW/engine/tools/augment_video_masks.py @@ -0,0 +1,799 @@ +#!/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-sam3/bin/python +from __future__ import annotations + +import argparse +import json +import shutil +import subprocess +import sys +import tempfile +from datetime import datetime +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence + +import numpy as np +from PIL import Image + +THIS_DIR = Path(__file__).resolve().parent +ONEPOSE_ROOT = THIS_DIR.parent +PROJECT_ROOT = ONEPOSE_ROOT.parent +VIDEO_MASKS_SCRIPT = PROJECT_ROOT / "Grounded_SAM2" / "qwen" / "qwen_sam3_video_masks.py" +RERUN_STEP6_SCRIPT = ONEPOSE_ROOT / "tools" / "rerun_step6_objects.py" +DEFAULT_BATCH_CONFIG = ONEPOSE_ROOT / "config" / "batch_config_example_legacy.json" +DEFAULT_SAM3_CKPT = PROJECT_ROOT / "sam3" / "checkpoints" / "sam3" / "sam3.pt" +DEFAULT_OPG_PY = Path("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Incrementally add video SAM3 masks for new labels and optionally rerun step-6 objects." + ) + parser.add_argument("--run-dir", type=Path, required=True, help="Existing video-pipeline run dir") + parser.add_argument("--labels", type=str, required=True, help="Comma-separated labels to add or retry") + parser.add_argument( + "--default-category", + type=str, + choices=("static", "rigid"), + default="static", + help="Category assigned to newly added labels", + ) + parser.add_argument("--min-obj-area", type=int, default=200, help="Minimum accepted mask area") + parser.add_argument( + "--sam3-ckpt", + type=Path, + default=DEFAULT_SAM3_CKPT, + help="SAM3 checkpoint path", + ) + parser.add_argument( + "--batch-config", + type=Path, + default=None, + help="Optional batch config override; defaults to pipeline_config.json value", + ) + parser.add_argument( + "--rerun-step6", + type=int, + choices=[0, 1], + default=0, + help="1: rerun newly added objects; if none were added, rerun existing objects matching the requested labels", + ) + parser.add_argument( + "--anchor-frame", + type=int, + default=-1, + help="Optional anchor-frame override when --rerun-step6=1", + ) + parser.add_argument( + "--opg-python", + type=Path, + default=DEFAULT_OPG_PY, + help="Python executable used for rerun_step6_objects.py", + ) + parser.add_argument( + "--backup", + type=int, + choices=[0, 1], + default=1, + help="1: create timestamped backups for modified JSON files before writing", + ) + parser.add_argument("--dry-run", action="store_true", help="Analyze and print actions without writing files") + return parser.parse_args() + + +def _simple_normalize(text: Any) -> str: + raw = str(text or "").strip().lower() + raw = raw.replace("-", " ").replace("_", " ") + raw = "".join(ch if (ch.isalnum() or ch.isspace()) else " " for ch in raw) + return " ".join(raw.split()).strip() + + +def _safe_id(name: str) -> str: + out = [] + for ch in str(name or "").lower(): + if ch.isalnum(): + out.append(ch) + elif ch in (" ", "-", "_"): + out.append("_") + cleaned = "".join(out).strip("_") + while "__" in cleaned: + cleaned = cleaned.replace("__", "_") + return cleaned or "obj" + + +def normalize_labels(raw: str) -> List[str]: + labels: List[str] = [] + seen = set() + for piece in str(raw or "").split(","): + name = _simple_normalize(piece) + if not name or name in seen: + continue + seen.add(name) + labels.append(name) + return labels + + +def ordered_union(*sequences: Sequence[str]) -> List[str]: + out: List[str] = [] + seen = set() + for seq in sequences: + for item in seq: + name = _simple_normalize(item) + if not name or name in seen: + continue + seen.add(name) + out.append(name) + return out + + +def load_json(path: Path) -> Dict[str, Any]: + return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} + + +def save_json(path: Path, payload: Dict[str, Any], dry_run: bool) -> None: + if dry_run: + return + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8") + + +def backup_file(path: Path, dry_run: bool) -> None: + if dry_run or not path.exists(): + return + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + backup = path.with_name(f"{path.name}.bak_{ts}") + shutil.copy2(path, backup) + + +def resolve_workspace_root(run_dir: Path) -> Path: + marker = run_dir / ".onepose_workspace_root" + if marker.is_file(): + raw = marker.read_text(encoding="utf-8").strip() + if raw: + workspace = Path(raw).expanduser().resolve() + if workspace.is_dir(): + return workspace + + scene_name = run_dir.name + for cand in [run_dir, run_dir.parent, run_dir.parent.parent]: + if not cand: + continue + meta = cand / "metadata" / f"{scene_name}_step_state.json" + if meta.exists(): + return cand.resolve() + raise FileNotFoundError(f"Cannot resolve workspace root from run dir: {run_dir}") + + +def resolve_context(run_dir: Path) -> Dict[str, Path | str]: + run_dir = run_dir.expanduser().resolve() + if not run_dir.is_dir(): + raise FileNotFoundError(f"run dir not found: {run_dir}") + + scene_name = run_dir.name + workspace_root = resolve_workspace_root(run_dir) + labels_json = workspace_root / "metadata" / f"{scene_name}_labels.json" + summary_json = workspace_root / "metadata" / f"{scene_name}_mask_summary.json" + state_json = workspace_root / "metadata" / f"{scene_name}_step_state.json" + cfg_main = workspace_root / "recon_ready" / scene_name / "pipeline_config.json" + cfg_effective = workspace_root / "recon_ready" / scene_name / "pipeline_config_effective.json" + + if not cfg_main.exists(): + raise FileNotFoundError(f"pipeline config not found: {cfg_main}") + + cfg_payload = load_json(cfg_main) + video_raw = str(cfg_payload.get("video_path", "")).strip() + if not video_raw: + labels_payload = load_json(labels_json) + video_raw = str(labels_payload.get("video", "")).strip() + if not video_raw: + raise RuntimeError(f"Cannot resolve video path from {cfg_main} or {labels_json}") + + video_path = Path(video_raw).expanduser() + if not video_path.is_absolute(): + video_path = (workspace_root / video_path).resolve() + else: + video_path = video_path.resolve() + if not video_path.exists(): + raise FileNotFoundError(f"video path not found: {video_path}") + + return { + "run_dir": run_dir, + "workspace_root": workspace_root, + "scene_name": scene_name, + "video_path": video_path, + "labels_json": labels_json, + "summary_json": summary_json, + "state_json": state_json, + "cfg_main": cfg_main, + "cfg_effective": cfg_effective, + } + + +def infer_batch_config(cfg_main_path: Path, override: Optional[Path]) -> Path: + if override is not None: + return override.expanduser().resolve() + payload = load_json(cfg_main_path) + raw = str(payload.get("batch_config", "")).strip() + if raw: + return Path(raw).expanduser().resolve() + return DEFAULT_BATCH_CONFIG.resolve() + + +def next_instance_index(label: str, existing_names: Sequence[str], existing_mask_root: Path) -> int: + label_id = _safe_id(label) + max_idx = 0 + names = set(existing_names) + if existing_mask_root.exists(): + for child in existing_mask_root.iterdir(): + if child.is_dir(): + names.add(child.name) + prefix = f"{label_id}_" + for name in names: + if not name.startswith(prefix): + continue + suffix = name[len(prefix) :] + if suffix.isdigit(): + max_idx = max(max_idx, int(suffix)) + return max_idx + 1 + + +def _parse_frame_id(path: Path) -> Optional[int]: + stem = path.stem + if stem.startswith("frame_"): + stem = stem[len("frame_") :] + try: + return int(stem) + except Exception: + return None + + +def _mask_iou(mask_a: np.ndarray, mask_b: np.ndarray) -> float: + inter = float(np.logical_and(mask_a, mask_b).sum()) + union = float(np.logical_or(mask_a, mask_b).sum()) + if union <= 0.0: + return 0.0 + return inter / union + + +def _mask_cover(mask_a: np.ndarray, mask_b: np.ndarray) -> float: + inter = float(np.logical_and(mask_a, mask_b).sum()) + denom = float(min(mask_a.sum(), mask_b.sum())) + if denom <= 0.0: + return 0.0 + return inter / denom + + +def _sample_frame_ids(frame_ids: Sequence[int], max_samples: int = 7) -> List[int]: + ids = sorted(set(int(x) for x in frame_ids)) + if len(ids) <= max_samples: + return ids + out = [] + for idx in np.linspace(0, len(ids) - 1, num=max_samples): + out.append(ids[int(round(float(idx)))]) + return sorted(set(out)) + + +def _load_mask(path: Path, cache: Dict[Path, np.ndarray]) -> Optional[np.ndarray]: + cached = cache.get(path) + if cached is not None: + return cached + if not path.exists(): + return None + arr = np.asarray(Image.open(path).convert("L")) > 0 + cache[path] = arr + return arr + + +def _list_mask_paths(mask_dir: Path) -> Dict[int, Path]: + out: Dict[int, Path] = {} + if not mask_dir.is_dir(): + return out + for path in sorted(mask_dir.glob("frame_*.png")): + fid = _parse_frame_id(path) + if fid is not None: + out[int(fid)] = path.resolve() + return out + + +def _mask_dir_for_object(obj: Dict[str, Any], fallback_root: Path) -> Path: + raw = str(obj.get("masks_dir", "")).strip() + if raw: + mask_dir = Path(raw).expanduser() + return mask_dir.resolve() if mask_dir.is_absolute() else (fallback_root / mask_dir).resolve() + return (fallback_root / str(obj.get("name", "")).strip()).resolve() + + +def is_duplicate_sequence( + new_mask_dir: Path, + existing_mask_dirs: Sequence[Path], + cache: Dict[Path, np.ndarray], + iou_thresh: float = 0.85, + cover_thresh: float = 0.92, +) -> bool: + new_paths = _list_mask_paths(new_mask_dir) + if not new_paths: + return False + for existing_dir in existing_mask_dirs: + existing_paths = _list_mask_paths(existing_dir) + common = sorted(set(new_paths.keys()) & set(existing_paths.keys())) + if not common: + continue + sample_ids = _sample_frame_ids(common) + ious: List[float] = [] + covers: List[float] = [] + for fid in sample_ids: + new_mask = _load_mask(new_paths[fid], cache) + old_mask = _load_mask(existing_paths[fid], cache) + if new_mask is None or old_mask is None: + continue + ious.append(_mask_iou(new_mask, old_mask)) + covers.append(_mask_cover(new_mask, old_mask)) + if not ious: + continue + if float(np.median(np.asarray(ious, dtype=np.float32))) >= iou_thresh: + return True + if float(np.median(np.asarray(covers, dtype=np.float32))) >= cover_thresh: + return True + return False + + +def collect_object_names_for_labels(objects: Sequence[Dict[str, Any]], labels: Sequence[str]) -> List[str]: + wanted = {_simple_normalize(label) for label in labels if _simple_normalize(label)} + names: List[str] = [] + seen = set() + for obj in objects: + label = _simple_normalize(obj.get("label", "")) + name = str(obj.get("name", "")).strip() + if not name or label not in wanted or name in seen: + continue + seen.add(name) + names.append(name) + return names + + +def update_state_file(state_path: Path, updates: Dict[str, Any], dry_run: bool) -> None: + payload = load_json(state_path) if state_path.exists() else {} + for key, value in updates.items(): + payload[key] = value + save_json(state_path, payload, dry_run=dry_run) + + +def update_category_meta( + meta_path: Path, + labels: Sequence[str], + default_category: str, + backup: bool, + dry_run: bool, +) -> None: + if not meta_path.exists(): + return + payload = load_json(meta_path) + existing_labels = payload.get("labels", []) + payload["labels"] = ordered_union(existing_labels if isinstance(existing_labels, list) else [], labels) + + categories = payload.get("label_categories") + if not isinstance(categories, dict): + categories = {} + reasons = payload.get("label_category_reasons") + if not isinstance(reasons, dict): + reasons = {} + visuals = payload.get("label_visual_descriptions") + if not isinstance(visuals, dict): + visuals = {} + objects = payload.get("parsed_payload", {}).get("objects") + if not isinstance(objects, list): + objects = [] + + existing_object_names = {_simple_normalize(item.get("name")) for item in objects if isinstance(item, dict)} + for label in labels: + categories.setdefault(label, default_category) + reasons.setdefault(label, "manual_label_add") + visuals.setdefault(label, "") + if label not in existing_object_names: + objects.append( + { + "name": label, + "num": 1, + "visual_description": "", + "category": default_category, + "reason": "manual_label_add", + "is_occluded": False, + "occluded_by": [], + } + ) + + payload["label_categories"] = categories + payload["label_category_reasons"] = reasons + payload["label_visual_descriptions"] = visuals + parsed_payload = payload.get("parsed_payload") + if isinstance(parsed_payload, dict): + parsed_payload["objects"] = objects + else: + payload["parsed_payload"] = {"objects": objects} + payload["updated_at"] = datetime.utcnow().isoformat() + "Z" + + if backup: + backup_file(meta_path, dry_run=dry_run) + save_json(meta_path, payload, dry_run=dry_run) + + +def build_temp_mask_command( + video_path: Path, + temp_root: Path, + labels: Sequence[str], + default_category: str, + min_obj_area: int, + sam3_ckpt: Path, + batch_config: Path, +) -> List[str]: + labels_csv = ",".join(labels) + cmd = [ + str(Path(sys.executable).resolve()), + str(VIDEO_MASKS_SCRIPT.resolve()), + "--video-path", + str(video_path.resolve()), + "--mode", + "masks", + "--labels", + labels_csv, + "--output-root", + str(temp_root.resolve()), + "--qwen-label-category-mode", + "legacy", + "--qwen-label-category-strict", + "0", + "--min-obj-area", + str(int(min_obj_area)), + "--sam3-ckpt", + str(sam3_ckpt.resolve()), + "--batch-config", + str(batch_config.resolve()), + ] + if default_category == "static": + cmd.extend(["--static-labels", labels_csv]) + else: + cmd.extend( + [ + "--dynamic-labels", + labels_csv, + "--rigid-labels", + labels_csv, + "--default-dynamic-category", + "rigid", + ] + ) + return cmd + + +def main() -> None: + args = parse_args() + labels = normalize_labels(args.labels) + if not labels: + raise SystemExit("ERROR: at least one valid label is required.") + if int(args.min_obj_area) <= 0: + raise SystemExit(f"ERROR: --min-obj-area must be > 0 (got {args.min_obj_area})") + if int(args.anchor_frame) < -1: + raise SystemExit(f"ERROR: --anchor-frame must be >= -1 (got {args.anchor_frame})") + + ctx = resolve_context(args.run_dir) + run_dir = Path(ctx["run_dir"]) + workspace_root = Path(ctx["workspace_root"]) + scene_name = str(ctx["scene_name"]) + video_path = Path(ctx["video_path"]) + labels_json_path = Path(ctx["labels_json"]) + summary_json_path = Path(ctx["summary_json"]) + state_json_path = Path(ctx["state_json"]) + cfg_main_path = Path(ctx["cfg_main"]) + cfg_effective_path = Path(ctx["cfg_effective"]) + + batch_config = infer_batch_config(cfg_main_path, args.batch_config) + if not batch_config.exists(): + raise FileNotFoundError(f"batch config not found: {batch_config}") + sam3_ckpt = args.sam3_ckpt.expanduser().resolve() + if not sam3_ckpt.exists(): + raise FileNotFoundError(f"SAM3 checkpoint not found: {sam3_ckpt}") + if not labels_json_path.exists(): + raise FileNotFoundError(f"labels json not found: {labels_json_path}") + if not summary_json_path.exists(): + raise FileNotFoundError(f"mask summary not found: {summary_json_path}") + + labels_payload = load_json(labels_json_path) + summary_payload = load_json(summary_json_path) + cfg_main_payload = load_json(cfg_main_path) + state_payload = load_json(state_json_path) if state_json_path.exists() else {} + + existing_labels = [ + _simple_normalize(x) for x in labels_payload.get("labels", []) if _simple_normalize(x) + ] + existing_summary_objects = ( + list(summary_payload.get("objects", [])) + if isinstance(summary_payload.get("objects", []), list) + else [] + ) + existing_cfg_objects = ( + list(cfg_main_payload.get("objects", [])) + if isinstance(cfg_main_payload.get("objects", []), list) + else [] + ) + existing_names = [ + str(obj.get("name", "")).strip() + for obj in existing_summary_objects + if str(obj.get("name", "")).strip() + ] + existing_mask_root = Path(str(summary_payload.get("mask_root", "")).strip() or (workspace_root / "masks" / scene_name)) + existing_mask_root = existing_mask_root.expanduser() + if not existing_mask_root.is_absolute(): + existing_mask_root = (workspace_root / existing_mask_root).resolve() + else: + existing_mask_root = existing_mask_root.resolve() + existing_mask_dirs = [ + _mask_dir_for_object(obj, existing_mask_root) for obj in existing_summary_objects + ] + + created_names: List[str] = [] + new_summary_objects: List[Dict[str, Any]] = [] + new_cfg_objects: List[Dict[str, Any]] = [] + mask_cache: Dict[Path, np.ndarray] = {} + + with tempfile.TemporaryDirectory(prefix="augment_video_masks_") as temp_dir_raw: + temp_root = Path(temp_dir_raw).resolve() + cmd = build_temp_mask_command( + video_path=video_path, + temp_root=temp_root, + labels=labels, + default_category=str(args.default_category), + min_obj_area=int(args.min_obj_area), + sam3_ckpt=sam3_ckpt, + batch_config=batch_config, + ) + print("[sam3] command:") + print(" " + " ".join(cmd)) + subprocess.run(cmd, check=True) + + temp_summary_path = temp_root / "metadata" / f"{video_path.stem}_mask_summary.json" + if not temp_summary_path.exists(): + raise FileNotFoundError(f"Temporary mask summary not found: {temp_summary_path}") + temp_summary = load_json(temp_summary_path) + temp_objects = ( + list(temp_summary.get("objects", [])) + if isinstance(temp_summary.get("objects", []), list) + else [] + ) + temp_mask_root = Path(str(temp_summary.get("mask_root", "")).strip() or (temp_root / "masks" / video_path.stem)) + temp_mask_root = temp_mask_root.expanduser() + if not temp_mask_root.is_absolute(): + temp_mask_root = (temp_root / temp_mask_root).resolve() + else: + temp_mask_root = temp_mask_root.resolve() + + for obj in temp_objects: + label = _simple_normalize(obj.get("label", "")) + if not label: + continue + temp_mask_dir = _mask_dir_for_object(obj, temp_mask_root) + if is_duplicate_sequence(temp_mask_dir, existing_mask_dirs, mask_cache): + continue + + next_idx = next_instance_index(label, existing_names + created_names, existing_mask_root) + new_name = f"{_safe_id(label)}_{next_idx:02d}" + while (existing_mask_root / new_name).exists(): + next_idx += 1 + new_name = f"{_safe_id(label)}_{next_idx:02d}" + + target_mask_dir = existing_mask_root / new_name + if not args.dry_run: + target_mask_dir.parent.mkdir(parents=True, exist_ok=True) + shutil.copytree(temp_mask_dir, target_mask_dir) + + created_names.append(new_name) + existing_names.append(new_name) + existing_mask_dirs.append(target_mask_dir) + + new_obj = dict(obj) + new_obj["name"] = new_name + new_obj["label"] = label + new_obj["category"] = str(args.default_category) + new_obj["category_source"] = "manual_label_add" + if str(args.default_category) == "static": + new_obj["is_static"] = True + new_obj["force_static"] = True + new_obj["force_dynamic"] = False + else: + new_obj["is_static"] = False + new_obj["force_static"] = False + new_obj["force_dynamic"] = True + new_summary_objects.append(new_obj) + new_cfg_objects.append( + { + "name": new_name, + "masks_dir": str(target_mask_dir.resolve()), + "category": str(args.default_category), + } + ) + + all_labels = ordered_union(existing_labels, labels) + existing_lpk = labels_payload.get("labels_per_keyframe", {}) + if not isinstance(existing_lpk, dict): + existing_lpk = {} + keyframes = labels_payload.get("keyframes") + if not isinstance(keyframes, list): + keyframes = summary_payload.get("keyframes", []) + labels_per_keyframe: Dict[str, List[str]] = {} + for raw_key, value in existing_lpk.items(): + labels_per_keyframe[str(raw_key)] = ordered_union(value if isinstance(value, list) else [], labels) + for keyframe in keyframes: + key = str(int(keyframe)) + labels_per_keyframe.setdefault(key, list(all_labels)) + if key not in existing_lpk: + labels_per_keyframe[key] = list(all_labels) + + label_categories = labels_payload.get("label_categories") + if not isinstance(label_categories, dict): + label_categories = {} + label_reasons = labels_payload.get("label_category_reasons") + if not isinstance(label_reasons, dict): + label_reasons = {} + label_visuals = labels_payload.get("label_visual_descriptions") + if not isinstance(label_visuals, dict): + label_visuals = {} + for label in labels: + label_categories.setdefault(label, str(args.default_category)) + label_reasons.setdefault(label, "manual_label_add") + label_visuals.setdefault(label, "") + + labels_payload = dict(labels_payload) + labels_payload["labels"] = list(all_labels) + labels_payload["labels_per_keyframe"] = labels_per_keyframe + labels_payload["label_categories"] = label_categories + labels_payload["label_category_reasons"] = label_reasons + labels_payload["label_visual_descriptions"] = label_visuals + labels_payload.setdefault("video", str(video_path.resolve())) + labels_payload.setdefault("video_name", scene_name) + labels_payload.setdefault("keyframes", keyframes) + + summary_payload = dict(summary_payload) + summary_payload["labels"] = list(all_labels) + summary_payload["labels_per_keyframe"] = labels_per_keyframe + summary_payload["objects"] = existing_summary_objects + new_summary_objects + summary_payload["labels_json"] = str(labels_json_path.resolve()) + summary_payload["label_categories"] = label_categories + summary_payload["label_category_reasons"] = label_reasons + summary_payload["label_visual_descriptions"] = label_visuals + summary_payload["mask_root"] = str(existing_mask_root.resolve()) + + cfg_main_payload = dict(cfg_main_payload) + cfg_main_payload["objects"] = existing_cfg_objects + new_cfg_objects + cfg_main_payload.setdefault("batch_config", str(batch_config.resolve())) + cfg_main_payload.setdefault("video_path", str(video_path.resolve())) + cfg_main_payload.setdefault("output_root", str(workspace_root.resolve())) + cfg_main_payload.setdefault("mask_glob", "frame_*.png") + + print(f"[info] workspace_root: {workspace_root}") + print(f"[info] run_dir: {run_dir}") + print(f"[info] video_path: {video_path}") + print(f"[info] requested labels: {labels}") + print(f"[info] created objects: {created_names if created_names else 'none'}") + + existing_matching_names = collect_object_names_for_labels(existing_summary_objects, labels) + rerun_targets: List[str] = [] + rerun_mode = "" + if int(args.rerun_step6) == 1: + if created_names: + rerun_targets = list(created_names) + rerun_mode = "new_objects" + elif existing_matching_names: + rerun_targets = list(existing_matching_names) + rerun_mode = "existing_label_matches" + if rerun_mode: + print(f"[info] rerun mode: {rerun_mode}") + print(f"[info] rerun targets: {rerun_targets}") + + meta_path_raw = str(labels_payload.get("label_category_meta", "")).strip() + meta_path = None + if meta_path_raw: + meta_path = Path(meta_path_raw).expanduser() + if not meta_path.is_absolute(): + meta_path = (workspace_root / meta_path).resolve() + else: + meta_path = meta_path.resolve() + + if not args.dry_run: + for path in [labels_json_path, summary_json_path, cfg_main_path, state_json_path]: + if int(args.backup) == 1: + backup_file(path, dry_run=False) + save_json(labels_json_path, labels_payload, dry_run=False) + save_json(summary_json_path, summary_payload, dry_run=False) + save_json(cfg_main_path, cfg_main_payload, dry_run=False) + if meta_path is not None and meta_path.exists(): + update_category_meta( + meta_path=meta_path, + labels=labels, + default_category=str(args.default_category), + backup=bool(int(args.backup)), + dry_run=False, + ) + + rerun_ok = False + rerun_attempted = False + rerun_return_code = 0 + if rerun_targets: + rerun_cmd = [ + str(args.opg_python.expanduser().resolve()), + str(RERUN_STEP6_SCRIPT.resolve()), + "--run-dir", + str(run_dir), + "--config", + str(cfg_main_path), + "--output-effective-config", + str(cfg_effective_path), + "--objects", + ",".join(rerun_targets), + "--only-failed", + "0", + ] + if int(args.anchor_frame) >= 0: + rerun_cmd.extend(["--anchor-frame", str(int(args.anchor_frame))]) + print("[rerun] command:") + print(" " + " ".join(rerun_cmd)) + if not args.dry_run: + rerun_attempted = True + completed = subprocess.run(rerun_cmd, check=False) + rerun_return_code = int(completed.returncode) + rerun_ok = rerun_return_code == 0 + if not rerun_ok: + print( + f"[warn] rerun step6 exited with code {rerun_return_code}; " + "rerun step 16 manually before later rendering steps." + ) + + effective_config_value = str(state_payload.get("effective_config", "")).strip() + if rerun_targets and cfg_effective_path.exists(): + effective_config_value = str(cfg_effective_path.resolve()) + + dirty_flag = "1" if created_names and not (rerun_ok or rerun_attempted) else "0" + updates: Dict[str, Any] = { + "labels_json": str(labels_json_path.resolve()), + "mask_summary": str(summary_json_path.resolve()), + "run_dir": str(run_dir.resolve()), + "inputs_dirty": dirty_flag, + } + if effective_config_value: + updates["effective_config"] = effective_config_value + err_json = run_dir / "object_errors_step6.json" + if err_json.exists(): + updates["step6_error_report"] = str(err_json.resolve()) + update_state_file(state_json_path, updates, dry_run=args.dry_run) + + print(f"[ok] labels json: {labels_json_path}") + print(f"[ok] summary json: {summary_json_path}") + print(f"[ok] pipeline config: {cfg_main_path}") + if rerun_ok: + print(f"[ok] rerun step6 succeeded for: {', '.join(rerun_targets)}") + elif rerun_attempted: + print(f"[ok] rerun step6 attempted for: {', '.join(rerun_targets)}") + print("[ok] rerun step6 failed; rerun step 16 manually when ready.") + elif created_names: + print("[next] Added masks/config only. Rerun step 16 before later steps, for example:") + print( + " " + + " ".join( + [ + "bash", + str((ONEPOSE_ROOT / "run_steps_scene_pipeline.sh").resolve()), + "--video", + str(video_path.resolve()), + "--run-dir", + str(run_dir.resolve()), + "--rerun-objects", + ",".join(created_names), + "16", + ] + ) + ) + elif int(args.rerun_step6) == 1 and existing_matching_names: + print("[next] Matching objects were found but rerun did not execute. Re-run without --dry-run.") + else: + print("[next] No new objects were created; check whether the requested labels duplicate existing objects.") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/blender_apply_world_pose_to_fbx_parent.py b/OVOW/engine/tools/blender_apply_world_pose_to_fbx_parent.py new file mode 100644 index 0000000000000000000000000000000000000000..da4dc19307430caea4e7cc73a1195681a8708501 --- /dev/null +++ b/OVOW/engine/tools/blender_apply_world_pose_to_fbx_parent.py @@ -0,0 +1,283 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Tuple + +import bpy +import numpy as np +from mathutils import Matrix + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Import Motion324 FBX, animate a parent node with world poses, and export FBX/GLB." + ) + parser.add_argument("--input-fbx", type=Path, required=True, help="Input deform animation FBX.") + parser.add_argument("--poses-world", type=Path, required=True, help="World pose json (frame -> 4x4).") + parser.add_argument("--output-fbx", type=Path, required=True, help="Output FBX with parent world pose animation.") + parser.add_argument("--output-glb", type=Path, default=None, help="Optional output GLB.") + parser.add_argument("--output-blend", type=Path, default=None, help="Optional debug .blend.") + parser.add_argument("--alignment", type=Path, default=None, help="Optional alignment json with 4x4 T.") + parser.add_argument( + "--coord", + type=str, + default="blender_noflip", + choices=("gltf", "opengl", "blender", "blender_noflip", "blender_zup", "raw"), + help="Coordinate conversion before writing parent transform.", + ) + parser.add_argument("--fps", type=float, default=10.0, help="Timeline fps.") + parser.add_argument( + "--frame-offset", + type=int, + default=None, + help="Pose frame offset in Blender timeline; default auto aligns to imported action start.", + ) + parser.add_argument("--object-name", type=str, default="deform_object", help="Object prefix for parent node.") + argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else [] + return parser.parse_args(argv) + + +def _load_pose_map(path: Path) -> Dict[int, np.ndarray]: + data = json.loads(path.read_text()) + out: Dict[int, np.ndarray] = {} + for k, v in data.items(): + try: + frame = int(k) + except Exception: + continue + mat = np.asarray(v, dtype=np.float32) + if mat.shape != (4, 4): + continue + if not np.all(np.isfinite(mat)): + continue + out[frame] = mat + if not out: + raise ValueError(f"No valid 4x4 poses in {path}") + return out + + +def _load_alignment(path: Optional[Path]) -> np.ndarray: + if path is None: + return np.eye(4, dtype=np.float32) + payload = json.loads(path.read_text()) + if isinstance(payload, dict): + mat = np.asarray(payload.get("T"), dtype=np.float32) + else: + mat = np.asarray(payload, dtype=np.float32) + if mat.shape != (4, 4): + raise ValueError(f"alignment matrix must be 4x4: {path}") + return mat + + +def _coord_matrix(coord: str) -> np.ndarray: + if coord == "raw": + return np.eye(4, dtype=np.float32) + if coord == "opengl": + return np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float32) + if coord == "blender": + rot_x_neg_90 = np.array( + [[1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, -1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0]], + dtype=np.float32, + ) + flip_x = np.diag([-1.0, 1.0, 1.0, 1.0]).astype(np.float32) + return flip_x @ (rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32)) + if coord == "blender_noflip": + rot_x_neg_90 = np.array( + [[1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, -1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0]], + dtype=np.float32, + ) + return rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + if coord == "blender_zup": + return np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + return np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + + +def _gather_imported_objects(input_fbx: Path) -> List[bpy.types.Object]: + before = {obj.name for obj in bpy.data.objects} + bpy.ops.import_scene.fbx(filepath=str(input_fbx)) + imported = [obj for obj in bpy.data.objects if obj.name not in before] + if not imported: + imported = list(bpy.context.selected_objects) + if not imported: + raise RuntimeError(f"Failed to import FBX: {input_fbx}") + return imported + + +def _top_level_objects(objects: Iterable[bpy.types.Object]) -> List[bpy.types.Object]: + obj_set = set(objects) + return [obj for obj in objects if (obj.parent is None or obj.parent not in obj_set)] + + +def _collect_action_ranges(objects: Iterable[bpy.types.Object]) -> List[Tuple[float, float]]: + ranges: List[Tuple[float, float]] = [] + + def _append_action(action) -> None: + if action is None: + return + try: + start, end = float(action.frame_range[0]), float(action.frame_range[1]) + except Exception: + return + if np.isfinite(start) and np.isfinite(end): + ranges.append((start, end)) + + def _append_nla(anim_data) -> None: + if anim_data is None: + return + for track in anim_data.nla_tracks: + for strip in track.strips: + start = float(strip.frame_start) + end = float(strip.frame_end) + if np.isfinite(start) and np.isfinite(end): + ranges.append((start, end)) + + for obj in objects: + _append_action(getattr(getattr(obj, "animation_data", None), "action", None)) + _append_nla(getattr(obj, "animation_data", None)) + if obj.type == "MESH" and getattr(obj.data, "shape_keys", None) is not None: + sk_data = obj.data.shape_keys + _append_action(getattr(getattr(sk_data, "animation_data", None), "action", None)) + _append_nla(getattr(sk_data, "animation_data", None)) + + return ranges + + +def _set_scene_fps(scene: bpy.types.Scene, fps: float) -> None: + fps = max(1.0, float(fps)) + fps_int = max(1, int(round(fps))) + scene.render.fps = fps_int + scene.render.fps_base = fps_int / fps + + +def _to_blender_matrix(mat: np.ndarray) -> Matrix: + return Matrix(tuple(tuple(float(x) for x in row) for row in mat)) + + +def _insert_linear_keys(obj: bpy.types.Object, frame: int, mat: np.ndarray) -> None: + bmat = _to_blender_matrix(mat) + loc, rot, scale = bmat.decompose() + obj.location = loc + obj.rotation_mode = "QUATERNION" + obj.rotation_quaternion = rot + obj.scale = scale + obj.keyframe_insert(data_path="location", frame=frame) + obj.keyframe_insert(data_path="rotation_quaternion", frame=frame) + obj.keyframe_insert(data_path="scale", frame=frame) + + +def main() -> None: + args = parse_args() + + if not args.input_fbx.exists(): + raise FileNotFoundError(args.input_fbx) + if not args.poses_world.exists(): + raise FileNotFoundError(args.poses_world) + if args.alignment is not None and not args.alignment.exists(): + raise FileNotFoundError(args.alignment) + + bpy.ops.wm.read_factory_settings(use_empty=True) + scene = bpy.context.scene + _set_scene_fps(scene, args.fps) + + imported = _gather_imported_objects(args.input_fbx) + roots = _top_level_objects(imported) + if not roots: + roots = imported + + world_root = bpy.data.objects.new(f"{args.object_name}_world_root", None) + world_root.empty_display_type = "PLAIN_AXES" + world_root.rotation_mode = "QUATERNION" + scene.collection.objects.link(world_root) + + for obj in roots: + obj.parent = world_root + obj.matrix_parent_inverse = world_root.matrix_world.inverted() + + pose_map = _load_pose_map(args.poses_world) + pose_ids = sorted(pose_map.keys()) + + action_ranges = _collect_action_ranges(imported) + if args.frame_offset is None: + if action_ranges: + anim_start = min(s for s, _ in action_ranges) + frame_offset = int(round(anim_start)) - int(pose_ids[0]) + else: + frame_offset = 0 + else: + frame_offset = int(args.frame_offset) + + coord_T = _coord_matrix(args.coord) + align_T = _load_alignment(args.alignment) + + keyed_frames: List[int] = [] + for pid in pose_ids: + world_cv = pose_map[pid] + world_blender = coord_T @ (align_T @ world_cv) + if not np.all(np.isfinite(world_blender)): + raise ValueError(f"Non-finite transform at frame {pid}") + frame = int(pid + frame_offset) + _insert_linear_keys(world_root, frame, world_blender) + keyed_frames.append(frame) + + if world_root.animation_data and world_root.animation_data.action: + for fcurve in world_root.animation_data.action.fcurves: + for kp in fcurve.keyframe_points: + kp.interpolation = "LINEAR" + + if keyed_frames: + scene.frame_start = int(min(keyed_frames)) + scene.frame_end = int(max(keyed_frames)) + scene.frame_set(scene.frame_start) + + args.output_fbx.parent.mkdir(parents=True, exist_ok=True) + bpy.ops.export_scene.fbx( + filepath=str(args.output_fbx), + use_selection=False, + add_leaf_bones=False, + bake_anim=True, + bake_anim_use_all_actions=False, + path_mode="COPY", + embed_textures=True, + ) + + if args.output_glb is not None: + args.output_glb.parent.mkdir(parents=True, exist_ok=True) + bpy.ops.export_scene.gltf( + filepath=str(args.output_glb), + export_format="GLB", + export_yup=True, + export_animations=True, + export_image_format="AUTO", + ) + + if args.output_blend is not None: + args.output_blend.parent.mkdir(parents=True, exist_ok=True) + bpy.ops.wm.save_as_mainfile(filepath=str(args.output_blend)) + + summary = { + "input_fbx": str(args.input_fbx.resolve()), + "poses_world": str(args.poses_world.resolve()), + "output_fbx": str(args.output_fbx.resolve()), + "output_glb": str(args.output_glb.resolve()) if args.output_glb is not None else None, + "output_blend": str(args.output_blend.resolve()) if args.output_blend is not None else None, + "coord": args.coord, + "alignment": str(args.alignment.resolve()) if args.alignment is not None else None, + "fps": float(args.fps), + "frame_offset": int(frame_offset), + "pose_frame_min": int(min(pose_ids)), + "pose_frame_max": int(max(pose_ids)), + "scene_frame_start": int(scene.frame_start), + "scene_frame_end": int(scene.frame_end), + "num_imported_objects": int(len(imported)), + "num_root_objects": int(len(roots)), + } + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() + diff --git a/OVOW/engine/tools/blender_drop_sim.py b/OVOW/engine/tools/blender_drop_sim.py new file mode 100644 index 0000000000000000000000000000000000000000..821a0838c954004bbea225bbdb80ba2e16800a74 --- /dev/null +++ b/OVOW/engine/tools/blender_drop_sim.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +import argparse +import sys + +import bpy + + +def _parse_args(): + argv = sys.argv + if "--" in argv: + argv = argv[argv.index("--") + 1 :] + else: + argv = [] + parser = argparse.ArgumentParser(description="Blender rigid body drop simulation for GLB scenes.") + parser.add_argument("--input", required=True, help="Input GLB/GLTF path") + parser.add_argument("--output", required=True, help="Output GLB path") + parser.add_argument("--frames", type=int, default=120, help="Simulation frame count") + parser.add_argument("--substeps", type=int, default=240, help="Rigid body steps per second") + parser.add_argument("--iterations", type=int, default=20, help="Rigid body solver iterations") + parser.add_argument( + "--collision", + type=str, + default="MESH", + choices=("MESH", "CONVEX_HULL", "BOX"), + help="Collision shape for active objects", + ) + parser.add_argument("--plane-name", type=str, default="table_plane", help="Plane object name") + parser.add_argument("--export-animation", action="store_true", help="Export baked animation") + parser.add_argument("--save-blend", type=str, default="", help="Optional .blend output path") + return parser.parse_args(argv) + + +def _ensure_rigidbody_world(scene, steps, iterations): + if scene.rigidbody_world is None: + bpy.ops.rigidbody.world_add() + rw = scene.rigidbody_world + if hasattr(rw, "steps_per_second"): + rw.steps_per_second = steps + elif hasattr(rw, "substeps_per_frame"): + rw.substeps_per_frame = max(1, int(steps / 60)) + if hasattr(rw, "solver_iterations"): + rw.solver_iterations = iterations + + +def _add_rigidbody(obj, is_plane, collision_shape): + obj.select_set(True) + bpy.context.view_layer.objects.active = obj + if obj.rigid_body is None: + bpy.ops.rigidbody.object_add() + if is_plane: + obj.rigid_body.type = "PASSIVE" + obj.rigid_body.collision_shape = "MESH" + obj.rigid_body.friction = 0.8 + obj.rigid_body.restitution = 0.0 + else: + obj.rigid_body.type = "ACTIVE" + obj.rigid_body.collision_shape = collision_shape + obj.rigid_body.mass = 1.0 + obj.rigid_body.friction = 0.6 + obj.rigid_body.restitution = 0.0 + obj.select_set(False) + + +def main(): + args = _parse_args() + + bpy.ops.wm.read_factory_settings(use_empty=True) + bpy.ops.import_scene.gltf(filepath=args.input) + + scene = bpy.context.scene + scene.frame_start = 1 + scene.frame_end = args.frames + scene.frame_set(scene.frame_start) + scene.gravity = (0.0, 0.0, -9.81) + + _ensure_rigidbody_world(scene, args.substeps, args.iterations) + if scene.rigidbody_world and scene.rigidbody_world.point_cache: + scene.rigidbody_world.point_cache.frame_start = scene.frame_start + scene.rigidbody_world.point_cache.frame_end = scene.frame_end + + plane_name = args.plane_name + for obj in list(scene.objects): + if obj.type != "MESH": + continue + if obj.animation_data is not None: + obj.animation_data_clear() + is_plane = obj.name == plane_name or plane_name in obj.name + _add_rigidbody(obj, is_plane, args.collision) + + bpy.ops.ptcache.free_bake_all() + bpy.ops.ptcache.bake_all(bake=True) + try: + bpy.ops.rigidbody.bake_to_keyframes(frame_start=scene.frame_start, frame_end=scene.frame_end) + except TypeError: + bpy.ops.rigidbody.bake_to_keyframes() + + scene.frame_set(args.frames) + + if not args.export_animation: + for obj in list(scene.objects): + if obj.type != "MESH": + continue + obj.animation_data_clear() + + if args.save_blend: + bpy.ops.wm.save_as_mainfile(filepath=args.save_blend) + + bpy.ops.export_scene.gltf( + filepath=args.output, + export_format="GLB", + export_apply=True, + export_animations=args.export_animation, + ) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/blender_export_mesh_frames.py b/OVOW/engine/tools/blender_export_mesh_frames.py new file mode 100644 index 0000000000000000000000000000000000000000..449b15380c904d64789e8b367e697e30149460d1 --- /dev/null +++ b/OVOW/engine/tools/blender_export_mesh_frames.py @@ -0,0 +1,174 @@ +import argparse +import json +import sys +from pathlib import Path + +import bpy + + +def parse_args(): + parser = argparse.ArgumentParser(description="Export per-frame meshes from an animated GLB/FBX.") + parser.add_argument("--input", required=True, help="Input animation file (glb/gltf/fbx).") + parser.add_argument("--output-dir", required=True, help="Output directory for frame_*.obj") + parser.add_argument("--frame-count", type=int, required=True, help="Number of frames to export") + parser.add_argument("--frame-step", type=int, default=1, help="Step between frames") + parser.add_argument("--scale", type=float, default=1.0, help="Uniform scale to apply before export") + return parser.parse_args(sys.argv[sys.argv.index("--") + 1 :]) + + +def _import_anim(path: str): + if path.lower().endswith((".glb", ".gltf")): + bpy.ops.import_scene.gltf(filepath=path) + elif path.lower().endswith(".fbx"): + bpy.ops.import_scene.fbx(filepath=path) + else: + raise RuntimeError(f"Unsupported input: {path}") + + +def _export_obj(path: str): + if hasattr(bpy.ops.wm, "obj_export"): + bpy.ops.wm.obj_export( + filepath=path, + export_selected_objects=True, + export_materials=False, + export_uv=True, + export_normals=True, + export_triangulated_mesh=True, + forward_axis="NEGATIVE_Z", + up_axis="Y", + ) + else: + bpy.ops.export_scene.obj( + filepath=path, + use_selection=True, + use_materials=False, + use_uvs=True, + use_normals=True, + use_triangles=True, + axis_forward="-Z", + axis_up="Y", + ) + + +def _infer_anim_frame_range() -> tuple[int, int]: + ranges = [] + for obj in bpy.context.scene.objects: + ad = getattr(obj, "animation_data", None) + act = getattr(ad, "action", None) + if act is None: + continue + fr = getattr(act, "frame_range", None) + if fr is None or len(fr) != 2: + continue + ranges.append((int(round(fr[0])), int(round(fr[1])))) + + if not ranges: + for act in bpy.data.actions: + fr = getattr(act, "frame_range", None) + if fr is None or len(fr) != 2: + continue + ranges.append((int(round(fr[0])), int(round(fr[1])))) + + if not ranges: + sc = bpy.context.scene + return int(sc.frame_start), int(sc.frame_end) + + start = min(s for s, _ in ranges) + end = max(e for _, e in ranges) + return start, end + + +def _build_source_frames(out_count: int, src_start: int, src_end: int) -> list[int]: + if out_count <= 0: + return [] + if out_count == 1: + return [int(src_start)] + span = float(src_end - src_start) + values = [] + for i in range(out_count): + t = float(i) / float(out_count - 1) + src_f = int(round(src_start + t * span)) + values.append(src_f) + return values + + +def main(): + args = parse_args() + out_dir = Path(args.output_dir) + out_dir.mkdir(parents=True, exist_ok=True) + + bpy.ops.wm.read_factory_settings(use_empty=True) + _import_anim(args.input) + + if args.scale and abs(args.scale - 1.0) > 1e-6: + for obj in bpy.context.scene.objects: + if obj.type in {"MESH", "ARMATURE", "EMPTY"}: + obj.scale = [args.scale, args.scale, args.scale] + bpy.context.view_layer.update() + + mesh_objs = [o for o in bpy.context.scene.objects if o.type == "MESH"] + if not mesh_objs: + raise RuntimeError("No mesh objects found after import") + + depsgraph = bpy.context.evaluated_depsgraph_get() + run_frames = list(range(0, args.frame_count, args.frame_step)) + if not run_frames: + raise RuntimeError("No output frames requested") + + src_start, src_end = _infer_anim_frame_range() + src_frames = _build_source_frames(len(run_frames), src_start, src_end) + mapping = { + "source_frame_start": int(src_start), + "source_frame_end": int(src_end), + "frame_count": int(args.frame_count), + "frame_step": int(args.frame_step), + "run_to_source": {str(rf): int(sf) for rf, sf in zip(run_frames, src_frames)}, + } + (out_dir / "source_frame_mapping.json").write_text(json.dumps(mapping, indent=2)) + print( + f"[mesh_export] source range {src_start}..{src_end}, " + f"output frames={len(run_frames)}, first src={src_frames[0]}, last src={src_frames[-1]}" + ) + + for run_f, src_f in zip(run_frames, src_frames): + bpy.context.scene.frame_set(src_f) + + temp_objs = [] + for obj in mesh_objs: + obj_eval = obj.evaluated_get(depsgraph) + mesh_eval = obj_eval.to_mesh() + if mesh_eval is None: + continue + temp_mesh = bpy.data.meshes.new_from_object(obj_eval) + temp_obj = bpy.data.objects.new(f"temp_{obj.name}", temp_mesh) + bpy.context.collection.objects.link(temp_obj) + temp_objs.append(temp_obj) + obj_eval.to_mesh_clear() + + if not temp_objs: + continue + + bpy.ops.object.select_all(action="DESELECT") + for obj in temp_objs: + obj.select_set(True) + bpy.context.view_layer.objects.active = temp_objs[0] + + if len(temp_objs) > 1: + bpy.ops.object.join() + temp_objs = [bpy.context.view_layer.objects.active] + + out_path = out_dir / f"frame_{run_f:06d}.obj" + _export_obj(str(out_path)) + + bpy.ops.object.select_all(action="DESELECT") + for obj in temp_objs: + obj.select_set(True) + bpy.ops.object.delete() + + for mesh in list(bpy.data.meshes): + if mesh.users == 0: + bpy.data.meshes.remove(mesh) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/blender_fbx_to_glb.py b/OVOW/engine/tools/blender_fbx_to_glb.py new file mode 100644 index 0000000000000000000000000000000000000000..d89f926f39b62eb041ed253967d6918144c0f140 --- /dev/null +++ b/OVOW/engine/tools/blender_fbx_to_glb.py @@ -0,0 +1,32 @@ +import sys +import argparse +import bpy + + +def parse_args(): + parser = argparse.ArgumentParser(description="Convert FBX to GLB via Blender.") + parser.add_argument("--input", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--scale", type=float, default=1.0, help="Optional uniform scale applied before export") + return parser.parse_args(sys.argv[sys.argv.index("--") + 1 :]) + + +def main(): + args = parse_args() + bpy.ops.wm.read_factory_settings(use_empty=True) + bpy.ops.import_scene.fbx(filepath=args.input) + if args.scale and abs(args.scale - 1.0) > 1e-6: + for obj in bpy.context.scene.objects: + if obj.type in {"MESH", "ARMATURE", "EMPTY"}: + obj.scale = [args.scale, args.scale, args.scale] + bpy.context.view_layer.update() + bpy.ops.export_scene.gltf( + filepath=args.output, + export_format="GLB", + export_yup=True, + export_animations=True, + ) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/blender_import_glb_with_step18_camera.py b/OVOW/engine/tools/blender_import_glb_with_step18_camera.py new file mode 100644 index 0000000000000000000000000000000000000000..bd2b5e50c2ef47595854c848aef8d818022e2b4b --- /dev/null +++ b/OVOW/engine/tools/blender_import_glb_with_step18_camera.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +import bpy +from mathutils import Matrix + + +def parse_args() -> argparse.Namespace: + argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else [] + parser = argparse.ArgumentParser( + description="Import a GLB and apply Step-18-aligned camera animation from camera_step18_bundle.json." + ) + parser.add_argument("--glb", required=True, help="Input GLB path") + parser.add_argument("--camera-json", required=True, help="camera_step18_bundle.json path") + parser.add_argument("--camera-name", default="step18_camera", help="Blender camera object name") + parser.add_argument("--clear-scene", action="store_true", help="Reset to an empty scene before import") + parser.add_argument("--fps", type=float, default=-1.0, help="Override scene FPS; <=0 uses JSON fps or 10") + parser.add_argument("--frame", type=int, default=0, help="Frame to jump to after import") + parser.add_argument("--save-blend", default="", help="Optional output .blend path") + return parser.parse_args(argv) + + +def _set_camera_view() -> None: + if bpy.app.background: + return + try: + for window in bpy.context.window_manager.windows: + screen = window.screen + if screen is None: + continue + for area in screen.areas: + if area.type != "VIEW_3D": + continue + for space in area.spaces: + if space.type == "VIEW_3D": + space.region_3d.view_perspective = "CAMERA" + return + except Exception: + pass + + +def _set_linear_keys(anim_owner: object) -> None: + anim_data = getattr(anim_owner, "animation_data", None) + action = getattr(anim_data, "action", None) + if action is None: + return + for fcurve in action.fcurves: + for kp in fcurve.keyframe_points: + kp.interpolation = "LINEAR" + + +def main() -> None: + args = parse_args() + + glb_path = Path(args.glb).expanduser().resolve() + camera_json_path = Path(args.camera_json).expanduser().resolve() + save_blend_path = Path(args.save_blend).expanduser().resolve() if args.save_blend else None + + if not glb_path.exists(): + raise FileNotFoundError(glb_path) + if not camera_json_path.exists(): + raise FileNotFoundError(camera_json_path) + + payload = json.loads(camera_json_path.read_text(encoding="utf-8")) + frames = payload.get("frames", []) + if not frames: + raise ValueError(f"No camera frames found in {camera_json_path}") + + if args.clear_scene: + bpy.ops.wm.read_factory_settings(use_empty=True) + + scene = bpy.context.scene + bpy.ops.import_scene.gltf(filepath=str(glb_path)) + + width = int(payload.get("image_size", {}).get("width", 0) or 0) + height = int(payload.get("image_size", {}).get("height", 0) or 0) + if width > 0: + scene.render.resolution_x = width + if height > 0: + scene.render.resolution_y = height + scene.render.resolution_percentage = 100 + + frame_count = int(payload.get("frame_count", len(frames))) + scene.frame_start = 0 + scene.frame_end = max(0, frame_count - 1) + + fps = float(args.fps) + if fps <= 0: + fps = float(payload.get("fps", 10.0) or 10.0) + fps = max(1e-6, fps) + scene.render.fps = int(round(fps)) + scene.render.fps_base = float(scene.render.fps) / fps + + cam = bpy.data.objects.get(args.camera_name) + if cam is None: + cam_data = bpy.data.cameras.new(args.camera_name) + cam = bpy.data.objects.new(args.camera_name, cam_data) + scene.collection.objects.link(cam) + else: + if cam.type != "CAMERA": + raise ValueError(f"Existing object is not a camera: {args.camera_name}") + cam_data = cam.data + + scene.camera = cam + cam.rotation_mode = "QUATERNION" + + if cam.animation_data is not None: + cam.animation_data_clear() + if cam_data.animation_data is not None: + cam_data.animation_data_clear() + + for item in frames: + frame = int(item["frame"]) + bc = item["blender_camera"] + + cam.matrix_world = Matrix(item["blender_matrix_world"]) + cam.scale = (1.0, 1.0, 1.0) + cam_data.type = bc.get("type", "PERSP") + cam_data.sensor_fit = bc.get("sensor_fit", "HORIZONTAL") + cam_data.lens = float(bc["lens"]) + cam_data.sensor_width = float(bc["sensor_width"]) + cam_data.sensor_height = float(bc["sensor_height"]) + cam_data.shift_x = float(bc["shift_x"]) + cam_data.shift_y = float(bc["shift_y"]) + cam_data.clip_start = float(bc.get("clip_start", 1e-3)) + cam_data.clip_end = float(bc.get("clip_end", 1e5)) + + cam.keyframe_insert(data_path="location", frame=frame) + cam.keyframe_insert(data_path="rotation_quaternion", frame=frame) + cam.keyframe_insert(data_path="scale", frame=frame) + cam_data.keyframe_insert(data_path="lens", frame=frame) + cam_data.keyframe_insert(data_path="sensor_height", frame=frame) + cam_data.keyframe_insert(data_path="shift_x", frame=frame) + cam_data.keyframe_insert(data_path="shift_y", frame=frame) + + _set_linear_keys(cam) + _set_linear_keys(cam_data) + + scene.frame_set(int(args.frame)) + _set_camera_view() + + if save_blend_path is not None: + save_blend_path.parent.mkdir(parents=True, exist_ok=True) + bpy.ops.wm.save_as_mainfile(filepath=str(save_blend_path)) + print(f"[OK] Saved blend: {save_blend_path}") + + print(f"[OK] Imported GLB: {glb_path}") + print(f"[OK] Applied camera JSON: {camera_json_path}") + print(f"[OK] Active camera: {cam.name}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/blender_merge_glb.py b/OVOW/engine/tools/blender_merge_glb.py new file mode 100644 index 0000000000000000000000000000000000000000..a5297d7db79104e87468a446d46be423febff912 --- /dev/null +++ b/OVOW/engine/tools/blender_merge_glb.py @@ -0,0 +1,32 @@ +import sys +import argparse +import bpy + + +def parse_args(): + parser = argparse.ArgumentParser(description="Merge multiple GLBs into one using Blender.") + parser.add_argument("--base", required=True) + parser.add_argument("--add", action="append", default=[]) + parser.add_argument("--out", required=True) + return parser.parse_args(sys.argv[sys.argv.index("--") + 1 :]) + + +def main(): + args = parse_args() + + bpy.ops.wm.read_factory_settings(use_empty=True) + + bpy.ops.import_scene.gltf(filepath=args.base) + for p in args.add: + bpy.ops.import_scene.gltf(filepath=p) + + bpy.ops.export_scene.gltf( + filepath=args.out, + export_format="GLB", + export_yup=False, + export_animations=True, + ) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/blender_merge_scene_assets_export_fbx.py b/OVOW/engine/tools/blender_merge_scene_assets_export_fbx.py new file mode 100644 index 0000000000000000000000000000000000000000..87bd010600f97a22f3c5b2430d747994048e89c4 --- /dev/null +++ b/OVOW/engine/tools/blender_merge_scene_assets_export_fbx.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Iterable, List, Set, Tuple + +import bpy + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Merge a base GLB and deform FBX assets in Blender, then export a single FBX scene." + ) + parser.add_argument("--base-glb", type=Path, required=True, help="Base scene GLB (typically rigid/static physics).") + parser.add_argument("--deform-manifest", type=Path, default=None, help="Manifest from pipe_deform_fbx.sh.") + parser.add_argument("--add-fbx", type=Path, nargs="*", default=None, help="Extra FBX assets to import.") + parser.add_argument("--output-fbx", type=Path, required=True, help="Merged FBX output.") + parser.add_argument("--output-blend", type=Path, default=None, help="Optional .blend output for debug.") + parser.add_argument("--fps", type=float, default=10.0, help="Scene fps.") + argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else [] + return parser.parse_args(argv) + + +def _set_fps(scene: bpy.types.Scene, fps: float) -> None: + fps = max(1.0, float(fps)) + fps_int = max(1, int(round(fps))) + scene.render.fps = fps_int + scene.render.fps_base = fps_int / fps + + +def _import_glb(path: Path) -> List[bpy.types.Object]: + before = {o.name for o in bpy.data.objects} + bpy.ops.import_scene.gltf(filepath=str(path)) + return [o for o in bpy.data.objects if o.name not in before] + + +def _import_fbx(path: Path) -> List[bpy.types.Object]: + before = {o.name for o in bpy.data.objects} + bpy.ops.import_scene.fbx(filepath=str(path)) + return [o for o in bpy.data.objects if o.name not in before] + + +def _collect_from_manifest(path: Path) -> List[Path]: + payload = json.loads(path.read_text()) + out: List[Path] = [] + for item in payload.get("objects", []): + p = item.get("output_fbx") + if isinstance(p, str) and p.strip(): + out.append(Path(p).resolve()) + return out + + +def _action_frame_range() -> Tuple[int, int]: + starts: List[float] = [] + ends: List[float] = [] + for action in bpy.data.actions: + try: + s = float(action.frame_range[0]) + e = float(action.frame_range[1]) + except Exception: + continue + starts.append(s) + ends.append(e) + if not starts: + return 1, 1 + return int(round(min(starts))), int(round(max(ends))) + + +def _dedup_paths(paths: Iterable[Path]) -> List[Path]: + out: List[Path] = [] + seen: Set[str] = set() + for p in paths: + rp = str(p.resolve()) + if rp in seen: + continue + seen.add(rp) + out.append(Path(rp)) + return out + + +def main() -> None: + args = parse_args() + if not args.base_glb.exists(): + raise FileNotFoundError(args.base_glb) + + bpy.ops.wm.read_factory_settings(use_empty=True) + scene = bpy.context.scene + _set_fps(scene, args.fps) + + imported_base = _import_glb(args.base_glb) + + fbx_paths: List[Path] = [] + if args.deform_manifest is not None: + if not args.deform_manifest.exists(): + raise FileNotFoundError(args.deform_manifest) + fbx_paths.extend(_collect_from_manifest(args.deform_manifest)) + if args.add_fbx: + fbx_paths.extend([p.resolve() for p in args.add_fbx]) + fbx_paths = _dedup_paths(fbx_paths) + + imported_deform: List[bpy.types.Object] = [] + missing: List[str] = [] + for p in fbx_paths: + if not p.exists(): + missing.append(str(p)) + continue + imported_deform.extend(_import_fbx(p)) + + start, end = _action_frame_range() + scene.frame_start = start + scene.frame_end = end + scene.frame_set(start) + + args.output_fbx.parent.mkdir(parents=True, exist_ok=True) + bpy.ops.export_scene.fbx( + filepath=str(args.output_fbx), + use_selection=False, + add_leaf_bones=False, + bake_anim=True, + bake_anim_use_all_actions=False, + bake_anim_simplify_factor=0.0, + path_mode="COPY", + embed_textures=True, + ) + + if args.output_blend is not None: + args.output_blend.parent.mkdir(parents=True, exist_ok=True) + bpy.ops.wm.save_as_mainfile(filepath=str(args.output_blend)) + + summary = { + "base_glb": str(args.base_glb.resolve()), + "deform_manifest": str(args.deform_manifest.resolve()) if args.deform_manifest is not None else None, + "deform_fbx_count": len(fbx_paths), + "deform_fbx_missing": missing, + "output_fbx": str(args.output_fbx.resolve()), + "output_blend": str(args.output_blend.resolve()) if args.output_blend is not None else None, + "frame_start": int(scene.frame_start), + "frame_end": int(scene.frame_end), + "num_imported_base_objects": len(imported_base), + "num_imported_deform_objects": len(imported_deform), + } + print(json.dumps(summary, indent=2)) + + +if __name__ == "__main__": + main() + diff --git a/OVOW/engine/tools/blender_motion324_norm.py b/OVOW/engine/tools/blender_motion324_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..2c0a2f21357a19911425817b7e883b347fd923a6 --- /dev/null +++ b/OVOW/engine/tools/blender_motion324_norm.py @@ -0,0 +1,78 @@ +import sys +import json +import argparse +import bpy + + +def parse_args(): + parser = argparse.ArgumentParser(description="Compute Motion324 normalization params from FBX.") + parser.add_argument("--input", required=True, help="Input FBX path") + parser.add_argument("--output", required=True, help="Output JSON path") + return parser.parse_args(sys.argv[sys.argv.index("--") + 1 :]) + + +def main(): + args = parse_args() + bpy.ops.wm.read_factory_settings(use_empty=True) + input_path = args.input + lower = input_path.lower() + if lower.endswith(".fbx"): + bpy.ops.import_scene.fbx(filepath=input_path) + elif lower.endswith(".glb") or lower.endswith(".gltf"): + bpy.ops.import_scene.gltf(filepath=input_path) + elif lower.endswith(".obj"): + bpy.ops.import_scene.obj(filepath=input_path) + else: + raise RuntimeError(f"Unsupported input format for motion324_norm: {input_path}") + + mesh_objs = [obj for obj in bpy.context.scene.objects if obj.type == "MESH"] + if not mesh_objs: + raise RuntimeError("No mesh objects found after FBX import") + + for obj in mesh_objs: + bpy.context.view_layer.objects.active = obj + bpy.ops.object.transform_apply(location=True, rotation=True, scale=True) + bpy.ops.object.transform_apply(location=True, rotation=True, scale=True) + + verts = [] + for obj in mesh_objs: + mw = obj.matrix_world + for v in obj.data.vertices: + p = mw @ v.co + verts.append([p.x, p.y, p.z]) + + if not verts: + raise RuntimeError("No vertices found") + + import numpy as np + + verts = np.asarray(verts, dtype=np.float32) + center = (verts.max(axis=0) + verts.min(axis=0)) / 2.0 + v_max = np.abs(verts - center).max() + scale = 2.0 * (v_max + 1e-8) + + R_example = [ + [1.0, 0.0, 0.0], + [0.0, 0.0, 1.0], + [0.0, -1.0, 0.0], + ] + R_out = [ + [1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0], + ] + + out = { + "center": center.tolist(), + "scale": float(scale), + "R_example": R_example, + "R_out": R_out, + } + with open(args.output, "w") as f: + json.dump(out, f, indent=2) + + print(f"[OK] Wrote: {args.output}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/blender_render_glb_with_video_camera.py b/OVOW/engine/tools/blender_render_glb_with_video_camera.py new file mode 100644 index 0000000000000000000000000000000000000000..4807a474c7b2901f1071f6956b57caad57a46c0d --- /dev/null +++ b/OVOW/engine/tools/blender_render_glb_with_video_camera.py @@ -0,0 +1,661 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import math +import sys +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +import bpy +import numpy as np +from mathutils import Matrix, Vector + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Render a scene GLB from input-video camera trajectory (result.npz extrinsics/intrinsics)." + ) + parser.add_argument("--input-glb", required=True, help="Input GLB path") + parser.add_argument("--result-npz", required=True, help="Path to run_dir/results/result.npz") + parser.add_argument("--output-video", required=True, help="Output mp4 path") + parser.add_argument("--alignment", default="", help="Optional alignment_plane.json (contains 4x4 T)") + parser.add_argument( + "--camera-ref-glb", + default="", + help="Optional GLB that already contains animated camera aligned to this run; if set, use that camera directly.", + ) + parser.add_argument( + "--camera-ref-name", + default="camera", + help="Preferred camera object base-name in --camera-ref-glb", + ) + parser.add_argument( + "--coord", + default="blender_zup", + choices=("gltf", "opengl", "blender", "blender_noflip", "blender_zup", "raw"), + help="Coordinate conversion used when exporting this GLB", + ) + parser.add_argument("--fps", type=float, default=10.0, help="Render FPS") + parser.add_argument("--engine", default="BLENDER_EEVEE_NEXT", help="Render engine") + parser.add_argument("--resolution-scale", type=float, default=1.0, help="Output resolution scale") + parser.add_argument("--camera-name", default="video_camera", help="Camera object name") + parser.add_argument("--max-frames", type=int, default=-1, help="Optional max rendered frames") + parser.add_argument("--world-strength", type=float, default=1.0, help="World background light strength") + parser.add_argument("--sun-energy", type=float, default=3.0, help="Sun light energy") + parser.add_argument( + "--world-flip-y", + action="store_true", + help="Mirror camera trajectory in world Y (fix front/back inversion for some merged GLBs).", + ) + parser.add_argument("--run-dir", default="", help="Run dir containing objects/*/pose_result for auto calibration") + parser.add_argument( + "--auto-calibrate", + action="store_true", + help="Solve a global CV-world -> imported-GLB-world transform from object poses (recommended)", + ) + parser.add_argument( + "--calib-frame", + type=int, + default=0, + help="Frame id used for auto calibration against imported GLB object transforms", + ) + parser.add_argument( + "--calib-pose-name", + default="poses_physics.json", + help="Preferred pose filename under pose_result for auto calibration", + ) + parser.add_argument( + "--calib-anchor", + default="", + help="Optional object name as calibration anchor; empty means robust multi-object estimation", + ) + parser.add_argument("--camera-roll-180", action="store_true", help="Apply an extra 180deg roll to camera") + parser.add_argument( + "--camera-axis", + default="standard", + choices=("standard", "identity", "flip_xy", "yz_swap", "yz_swap_flipx"), + help="Camera local-axis mapping from Blender camera to OpenCV camera", + ) + parser.add_argument( + "--world-conv", + default="identity", + choices=("identity", "rx90", "rxm90"), + help="Extra conversion from OpenCV world to scene world basis", + ) + return parser.parse_args(sys.argv[sys.argv.index("--") + 1 :]) + + +def _cv_to_gltf_matrix(coord: str) -> np.ndarray: + if coord == "raw": + return np.eye(4, dtype=np.float32) + if coord == "opengl": + return np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float32) + if coord == "blender": + rot_x_neg_90 = np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + flip_x = np.diag([-1.0, 1.0, 1.0, 1.0]).astype(np.float32) + return flip_x @ (rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32)) + if coord == "blender_noflip": + rot_x_neg_90 = np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + if coord == "blender_zup": + return np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + return np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + + +def _load_alignment(path_str: str) -> np.ndarray: + if not path_str: + return np.eye(4, dtype=np.float32) + path = Path(path_str).resolve() + if not path.exists(): + raise FileNotFoundError(path) + payload = json.loads(path.read_text(encoding="utf-8")) + T = np.asarray(payload.get("T", None), dtype=np.float32) + if T.shape != (4, 4): + raise ValueError(f"Alignment T must be 4x4, got {T.shape}") + return T + + +def _set_engine(scene: bpy.types.Scene, engine_name: str) -> None: + enum_items = scene.render.bl_rna.properties["engine"].enum_items + valid = {item.identifier for item in enum_items} + if engine_name in valid: + scene.render.engine = engine_name + return + if "BLENDER_EEVEE_NEXT" in valid: + scene.render.engine = "BLENDER_EEVEE_NEXT" + return + if "BLENDER_EEVEE" in valid: + scene.render.engine = "BLENDER_EEVEE" + return + + +def _set_basic_lighting(scene: bpy.types.Scene, world_strength: float, sun_energy: float) -> None: + world = scene.world + if world is None: + world = bpy.data.worlds.new("World") + scene.world = world + world.use_nodes = True + nt = world.node_tree + if nt is not None: + bg = nt.nodes.get("Background") + if bg is not None and "Strength" in bg.inputs: + bg.inputs["Strength"].default_value = float(world_strength) + + has_light = any(obj.type == "LIGHT" for obj in scene.objects) + if not has_light: + light_data = bpy.data.lights.new(name="Sun", type="SUN") + light_data.energy = float(sun_energy) + light_obj = bpy.data.objects.new(name="Sun", object_data=light_data) + scene.collection.objects.link(light_obj) + light_obj.rotation_euler = (math.radians(55.0), 0.0, math.radians(25.0)) + + +def _set_color_management(scene: bpy.types.Scene) -> None: + try: + view_items = scene.view_settings.bl_rna.properties["view_transform"].enum_items + valid = {item.identifier for item in view_items} + if "Standard" in valid: + scene.view_settings.view_transform = "Standard" + except Exception: + pass + scene.view_settings.exposure = 0.0 + scene.view_settings.gamma = 1.0 + + +def _world_conv_matrix(name: str) -> np.ndarray: + if name == "identity": + return np.eye(4, dtype=np.float32) + if name == "rx90": + return np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + + +def _camera_axis_matrix(name: str) -> np.ndarray: + if name == "identity": + return np.eye(4, dtype=np.float32) + if name == "flip_xy": + return np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + if name == "standard": + return np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float32) + if name == "yz_swap": + return np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return np.array( + [ + [-1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + + +def _find_root_obj() -> bpy.types.Object | None: + for name in ("root_cv2gl", "root"): + obj = bpy.data.objects.get(name) + if obj is not None: + return obj + return None + + +def _import_camera_from_reference_glb(ref_glb: Path, preferred_name: str) -> bpy.types.Object: + if not ref_glb.exists(): + raise FileNotFoundError(ref_glb) + before = {obj.name for obj in bpy.data.objects} + bpy.ops.import_scene.gltf(filepath=str(ref_glb)) + added = [obj for obj in bpy.data.objects if obj.name not in before] + if not added: + raise RuntimeError(f"Failed to import camera ref GLB: {ref_glb}") + + cams = [obj for obj in added if obj.type == "CAMERA"] + if not cams: + raise RuntimeError(f"No camera found in {ref_glb}") + + chosen = None + if preferred_name: + for cam in cams: + if cam.name.split(".", 1)[0] == preferred_name: + chosen = cam + break + if chosen is None: + chosen = cams[0] + + for obj in added: + if obj is chosen: + continue + obj.hide_render = True + obj.hide_viewport = True + + return chosen + + +def _build_world_y_flip_transform(world_seq: List[np.ndarray]) -> np.ndarray: + if not world_seq: + return np.eye(4, dtype=np.float32) + x0 = float(np.mean([m[0, 3] for m in world_seq])) + T = np.array( + [ + [-1.0, 0.0, 0.0, 2.0 * x0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return T + + +def _load_pose_map(pose_json: Path) -> Dict[int, np.ndarray]: + payload = json.loads(pose_json.read_text(encoding="utf-8")) + out: Dict[int, np.ndarray] = {} + for k, v in payload.items(): + try: + idx = int(k) + except Exception: + continue + mat = np.asarray(v, dtype=np.float32) + if mat.shape == (4, 4): + out[idx] = mat + return out + + +def _nearest_pose(pose_map: Dict[int, np.ndarray], frame_id: int) -> Tuple[int, np.ndarray]: + ids = sorted(pose_map.keys()) + if not ids: + raise ValueError("Empty pose map") + if frame_id in pose_map: + return frame_id, pose_map[frame_id] + nid = min(ids, key=lambda x: abs(x - frame_id)) + return nid, pose_map[nid] + + +def _load_category_map(run_dir: Path) -> Dict[str, str]: + cfg_path = run_dir.parent.parent / "recon_ready" / run_dir.name / "pipeline_config.json" + if not cfg_path.exists(): + return {} + try: + payload = json.loads(cfg_path.read_text(encoding="utf-8")) + except Exception: + return {} + out: Dict[str, str] = {} + for obj in payload.get("objects", []): + name = str(obj.get("name", "")).strip() + if not name: + continue + out[name] = str(obj.get("category", "")).strip().lower() + return out + + +def _pick_pose_file(obj_dir: Path, preferred_name: str, category: str) -> Optional[Path]: + pose_dir = obj_dir / "pose_result" + candidates: List[Path] = [] + if category == "static": + candidates.extend([pose_dir / "poses_locked.json", pose_dir / "poses.json"]) + if preferred_name: + candidates.append(pose_dir / preferred_name) + else: + if preferred_name: + candidates.append(pose_dir / preferred_name) + candidates.extend([pose_dir / "poses.json", pose_dir / "poses_physics.json", pose_dir / "poses_locked.json"]) + seen = set() + for p in candidates: + key = str(p.resolve()) + if key in seen: + continue + seen.add(key) + if p.exists(): + return p + return None + + +def _find_blender_object(name: str) -> Optional[bpy.types.Object]: + obj = bpy.data.objects.get(name) + if obj is not None: + return obj + for o in bpy.data.objects: + if o.name.split(".", 1)[0] == name: + return o + return None + + +def _rotation_projection(R: np.ndarray) -> np.ndarray: + U, _, Vt = np.linalg.svd(R) + Rn = U @ Vt + if np.linalg.det(Rn) < 0.0: + U[:, -1] *= -1.0 + Rn = U @ Vt + return Rn.astype(np.float32) + + +def _compute_scene_center_world() -> Optional[np.ndarray]: + bmin = np.array([np.inf, np.inf, np.inf], dtype=np.float32) + bmax = np.array([-np.inf, -np.inf, -np.inf], dtype=np.float32) + has = False + for obj in bpy.data.objects: + if obj.type != "MESH": + continue + if obj.name.startswith("table_plane"): + continue + has = True + for c in obj.bound_box: + pw = obj.matrix_world @ Vector((c[0], c[1], c[2])) + p = np.asarray([pw.x, pw.y, pw.z], dtype=np.float32) + bmin = np.minimum(bmin, p) + bmax = np.maximum(bmax, p) + if not has or not np.isfinite(bmin).all(): + return None + return ((bmin + bmax) * 0.5).astype(np.float32) + + +def _camera_face_score( + C: np.ndarray, + align_T: np.ndarray, + extrinsics: np.ndarray, + cv_cam_to_bl_cam: np.ndarray, + scene_center: np.ndarray, + sample_count: int = 5, +) -> float: + n = int(extrinsics.shape[0]) + if n <= 0: + return -1e9 + if sample_count <= 1: + sample_ids = [0] + else: + sample_ids = sorted({int(round(x)) for x in np.linspace(0, n - 1, num=min(sample_count, n))}) + score = 0.0 + for fid in sample_ids: + cam_to_world_cv = np.linalg.inv(extrinsics[fid]).astype(np.float32) + M = C @ align_T @ cam_to_world_cv @ cv_cam_to_bl_cam + o = M[:3, 3] + fwd = -M[:3, 2] + v = scene_center - o + nf = float(np.linalg.norm(fwd)) + nv = float(np.linalg.norm(v)) + if nf < 1e-8 or nv < 1e-8: + continue + score += float(np.dot(fwd, v) / (nf * nv)) + return score / max(1, len(sample_ids)) + + +def _solve_global_world_map_from_objects( + run_dir: Path, + align_T: np.ndarray, + extrinsics: np.ndarray, + cv_cam_to_bl_cam: np.ndarray, + frame_id: int, + preferred_pose_name: str, + anchor_name: str, +) -> np.ndarray: + if not run_dir.exists(): + raise FileNotFoundError(run_dir) + objects_root = run_dir / "objects" + if not objects_root.exists(): + raise FileNotFoundError(objects_root) + if frame_id < 0 or frame_id >= int(extrinsics.shape[0]): + raise ValueError(f"calib-frame out of range: {frame_id}") + + cam_to_world_cv = np.linalg.inv(extrinsics[frame_id]).astype(np.float32) + category_map = _load_category_map(run_dir) + candidates: List[Tuple[str, np.ndarray]] = [] + for obj_dir in sorted([d for d in objects_root.iterdir() if d.is_dir()]): + name = obj_dir.name + if anchor_name and name != anchor_name: + continue + bobj = _find_blender_object(name) + if bobj is None or bobj.type != "MESH": + continue + category = category_map.get(name, "") + pose_file = _pick_pose_file(obj_dir, preferred_pose_name, category) + if pose_file is None: + continue + pose_map = _load_pose_map(pose_file) + if not pose_map: + continue + _, pose_cam = _nearest_pose(pose_map, frame_id) + obj_world_cv = (align_T @ cam_to_world_cv @ pose_cam).astype(np.float32) + obj_world_glb = np.asarray(bobj.matrix_world, dtype=np.float32) + try: + C_i = obj_world_glb @ np.linalg.inv(obj_world_cv) + except np.linalg.LinAlgError: + continue + candidates.append((name, C_i.astype(np.float32))) + + if not candidates: + raise RuntimeError( + "Auto-calibration failed: no usable objects found. " + "Check --run-dir/--calib-pose-name/--calib-anchor." + ) + + if anchor_name: + C = candidates[0][1] + print(f"[Info] Auto-calib anchor: {candidates[0][0]}") + return C + + scene_center = _compute_scene_center_world() + if scene_center is None: + mats = np.stack([m for _, m in candidates], axis=0) + C = np.median(mats, axis=0).astype(np.float32) + C[:3, :3] = _rotation_projection(C[:3, :3]) + C[3, :] = np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float32) + print(f"[Warn] Auto-calib: scene center unavailable, fallback to median from {len(candidates)} candidates.") + return C + + best_name = "" + best_C = None + best_score = -1e9 + for name, C_i in candidates: + score = _camera_face_score( + C=C_i, + align_T=align_T, + extrinsics=extrinsics, + cv_cam_to_bl_cam=cv_cam_to_bl_cam, + scene_center=scene_center, + sample_count=5, + ) + print(f"[AutoCalib] {name}: face_score={score:.6f}") + if score > best_score: + best_score = score + best_name = name + best_C = C_i + + assert best_C is not None + print(f"[Info] Auto-calib selected anchor={best_name}, face_score={best_score:.6f}") + return best_C + + +def main() -> None: + args = parse_args() + input_glb = Path(args.input_glb).resolve() + result_npz = Path(args.result_npz).resolve() + output_video = Path(args.output_video).resolve() + + if not input_glb.exists(): + raise FileNotFoundError(input_glb) + if not result_npz.exists(): + raise FileNotFoundError(result_npz) + + data = np.load(result_npz) + extrinsics = np.asarray(data["extrinsics"], dtype=np.float32) + intrinsics = np.asarray(data["intrinsics"], dtype=np.float32) + if extrinsics.ndim != 3 or extrinsics.shape[1:] != (4, 4): + raise ValueError(f"Invalid extrinsics shape: {extrinsics.shape}") + if intrinsics.ndim != 3 or intrinsics.shape[1:] != (3, 3): + raise ValueError(f"Invalid intrinsics shape: {intrinsics.shape}") + num_frames = int(extrinsics.shape[0]) + if int(args.max_frames) > 0: + num_frames = min(num_frames, int(args.max_frames)) + + if "video" in data: + video_arr = data["video"] + if video_arr.ndim == 4 and video_arr.shape[1] in (1, 3, 4): + height, width = int(video_arr.shape[2]), int(video_arr.shape[3]) + elif video_arr.ndim == 4: + height, width = int(video_arr.shape[1]), int(video_arr.shape[2]) + else: + raise ValueError(f"Invalid video shape: {video_arr.shape}") + elif "depths" in data: + dep = data["depths"] + if dep.ndim != 3: + raise ValueError(f"Invalid depths shape: {dep.shape}") + height, width = int(dep.shape[1]), int(dep.shape[2]) + else: + raise KeyError("result.npz missing both 'video' and 'depths'") + + align_T = _load_alignment(args.alignment) + cv_to_gltf = _cv_to_gltf_matrix(args.coord) + cv_cam_to_bl_cam = _camera_axis_matrix(args.camera_axis) + if args.camera_roll_180: + cv_cam_to_bl_cam = cv_cam_to_bl_cam @ np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + + fps = float(args.fps) + if fps <= 0: + raise ValueError("fps must be > 0") + + bpy.ops.wm.read_factory_settings(use_empty=True) + scene = bpy.context.scene + scene.render.fps = int(round(fps)) + scene.render.fps_base = float(scene.render.fps) / fps + _set_engine(scene, args.engine) + _set_color_management(scene) + + bpy.ops.import_scene.gltf(filepath=str(input_glb)) + _set_basic_lighting(scene, world_strength=args.world_strength, sun_energy=args.sun_energy) + use_ref_camera = bool(str(args.camera_ref_glb).strip()) + if use_ref_camera: + cam_obj = _import_camera_from_reference_glb(Path(args.camera_ref_glb).resolve(), str(args.camera_ref_name)) + cam_data = cam_obj.data + else: + cam_data = bpy.data.cameras.new(args.camera_name) + cam_obj = bpy.data.objects.new(args.camera_name, cam_data) + bpy.context.scene.collection.objects.link(cam_obj) + + K0 = intrinsics[0] + fy = float(K0[1, 1]) + yfov = 2.0 * math.atan(0.5 * float(height) / max(1e-6, fy)) + cam_data.type = "PERSP" + cam_data.angle_y = float(yfov) + + scene.render.resolution_x = int(round(width * float(args.resolution_scale))) + scene.render.resolution_y = int(round(height * float(args.resolution_scale))) + scene.render.resolution_percentage = 100 + scene.frame_start = 0 + scene.frame_end = max(0, num_frames - 1) + scene.camera = cam_obj + cam_obj.rotation_mode = "QUATERNION" + cam_data.clip_start = 1e-3 + cam_data.clip_end = 1e5 + + world_conv = _world_conv_matrix(args.world_conv) + scene.frame_set(int(np.clip(int(args.calib_frame), 0, max(0, num_frames - 1)))) + + if not use_ref_camera: + if args.auto_calibrate: + if not args.run_dir: + raise ValueError("--auto-calibrate requires --run-dir") + global_world_map = _solve_global_world_map_from_objects( + run_dir=Path(args.run_dir).resolve(), + align_T=align_T, + extrinsics=extrinsics, + cv_cam_to_bl_cam=cv_cam_to_bl_cam, + frame_id=int(np.clip(int(args.calib_frame), 0, max(0, num_frames - 1))), + preferred_pose_name=str(args.calib_pose_name), + anchor_name=str(args.calib_anchor).strip(), + ) + print("[Info] Using auto-calibrated global world map.") + else: + global_world_map = cv_to_gltf @ world_conv + + world_seq: List[np.ndarray] = [] + for i in range(num_frames): + cam_to_world_cv = np.linalg.inv(extrinsics[i]).astype(np.float32) + world_m = global_world_map @ align_T @ cam_to_world_cv @ cv_cam_to_bl_cam + world_seq.append(world_m) + + if args.world_flip_y: + Tflip = _build_world_y_flip_transform(world_seq) + world_seq = [Tflip @ m for m in world_seq] + print(f"[Info] Applied world-flip-y by yaw180-around-z (x pivot={Tflip[0,3] * 0.5:.6f}).") + + for i, world_m in enumerate(world_seq): + m = Matrix(world_m.tolist()) + cam_obj.matrix_world = m + cam_obj.keyframe_insert(data_path="location", frame=i) + cam_obj.keyframe_insert(data_path="rotation_quaternion", frame=i) + cam_obj.keyframe_insert(data_path="scale", frame=i) + + if cam_obj.animation_data and cam_obj.animation_data.action: + for fcurve in cam_obj.animation_data.action.fcurves: + for kp in fcurve.keyframe_points: + kp.interpolation = "LINEAR" + else: + if args.world_flip_y: + world_seq: List[np.ndarray] = [] + for i in range(num_frames): + scene.frame_set(i) + world_seq.append(np.asarray(cam_obj.matrix_world, dtype=np.float32)) + Tflip = _build_world_y_flip_transform(world_seq) + for i, world_m in enumerate(world_seq): + m = Matrix((Tflip @ world_m).tolist()) + cam_obj.matrix_world = m + cam_obj.keyframe_insert(data_path="location", frame=i) + cam_obj.keyframe_insert(data_path="rotation_quaternion", frame=i) + cam_obj.keyframe_insert(data_path="scale", frame=i) + print(f"[Info] Applied world-flip-y to ref camera (x pivot={Tflip[0,3] * 0.5:.6f}).") + print(f"[Info] Using camera animation from ref GLB: {args.camera_ref_glb}") + + output_video.parent.mkdir(parents=True, exist_ok=True) + scene.render.image_settings.file_format = "FFMPEG" + scene.render.ffmpeg.format = "MPEG4" + scene.render.ffmpeg.codec = "H264" + scene.render.ffmpeg.constant_rate_factor = "MEDIUM" + scene.render.ffmpeg.ffmpeg_preset = "GOOD" + scene.render.filepath = str(output_video) + + bpy.ops.render.render(animation=True, write_still=False) + print(f"[OK] Wrote: {output_video}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/blender_render_glb_with_video_camera_fullK.py b/OVOW/engine/tools/blender_render_glb_with_video_camera_fullK.py new file mode 100644 index 0000000000000000000000000000000000000000..4348614222e3c1873d55b0dc2330a66f71d24d33 --- /dev/null +++ b/OVOW/engine/tools/blender_render_glb_with_video_camera_fullK.py @@ -0,0 +1,946 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import math +import sys +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +import bpy +import numpy as np +from mathutils import Matrix, Vector + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Render a scene GLB from input-video camera trajectory (result.npz extrinsics/intrinsics)." + ) + parser.add_argument("--input-glb", required=True, help="Input GLB path") + parser.add_argument("--result-npz", required=True, help="Path to run_dir/results/result.npz") + parser.add_argument("--output-video", required=True, help="Output mp4 path") + parser.add_argument("--alignment", default="", help="Optional alignment_plane.json (contains 4x4 T)") + parser.add_argument( + "--camera-ref-glb", + default="", + help="Optional GLB that already contains animated camera aligned to this run; if set, use that camera directly.", + ) + parser.add_argument( + "--camera-ref-name", + default="camera", + help="Preferred camera object base-name in --camera-ref-glb", + ) + parser.add_argument( + "--coord", + default="blender_zup", + choices=("gltf", "opengl", "blender", "blender_noflip", "blender_zup", "raw"), + help="Coordinate conversion used when exporting this GLB", + ) + parser.add_argument("--fps", type=float, default=10.0, help="Render FPS") + parser.add_argument("--engine", default="BLENDER_EEVEE_NEXT", help="Render engine") + parser.add_argument("--resolution-scale", type=float, default=1.0, help="Output resolution scale") + parser.add_argument("--camera-name", default="video_camera", help="Camera object name") + parser.add_argument( + "--keep-objects", + default="", + help="Comma-separated mesh base names to keep visible/renderable; others are hidden.", + ) + parser.add_argument("--max-frames", type=int, default=-1, help="Optional max rendered frames") + parser.add_argument("--world-strength", type=float, default=1.0, help="World background light strength") + parser.add_argument("--sun-energy", type=float, default=3.0, help="Sun light energy") + parser.add_argument( + "--camera-headlight", + action="store_true", + help="Attach a camera-mounted spot light pointing along camera viewing direction.", + ) + parser.add_argument( + "--camera-headlight-energy", + type=float, + default=2500.0, + help="Energy for --camera-headlight spot light.", + ) + parser.add_argument( + "--camera-headlight-type", + default="spot", + choices=("spot", "point", "sun"), + help="Light type for --camera-headlight.", + ) + parser.add_argument( + "--camera-headlight-angle", + type=float, + default=55.0, + help="Spot cone angle in degrees for --camera-headlight.", + ) + parser.add_argument( + "--ambient-rig", + action="store_true", + help="Add multi-point ambient light rig around scene center (useful with black background clay render).", + ) + parser.add_argument( + "--ambient-rig-energy", + type=float, + default=1200.0, + help="Total energy distributed across ambient rig point lights.", + ) + parser.add_argument( + "--white-matte", + action="store_true", + help="Override mesh materials to constant white emission on black background.", + ) + parser.add_argument( + "--white-clay", + action="store_true", + help="Override mesh materials to white shaded clay (no texture) on black background.", + ) + parser.add_argument( + "--clay-keep-world", + action="store_true", + help="With --white-clay, keep current world background/lighting instead of forcing black background.", + ) + parser.add_argument( + "--matte-emission-strength", + type=float, + default=5.0, + help="Emission strength for --white-matte material.", + ) + parser.add_argument( + "--world-flip-y", + action="store_true", + help="Mirror camera trajectory in world Y (fix front/back inversion for some merged GLBs).", + ) + parser.add_argument("--run-dir", default="", help="Run dir containing objects/*/pose_result for auto calibration") + parser.add_argument( + "--auto-calibrate", + action="store_true", + help="Solve a global CV-world -> imported-GLB-world transform from object poses (recommended)", + ) + parser.add_argument( + "--calib-frame", + type=int, + default=0, + help="Frame id used for auto calibration against imported GLB object transforms", + ) + parser.add_argument( + "--calib-pose-name", + default="poses_physics.json", + help="Preferred pose filename under pose_result for auto calibration", + ) + parser.add_argument( + "--calib-anchor", + default="", + help="Optional object name as calibration anchor; empty means robust multi-object estimation", + ) + parser.add_argument("--camera-roll-180", action="store_true", help="Apply an extra 180deg roll to camera") + parser.add_argument( + "--camera-axis", + default="standard", + choices=("standard", "identity", "flip_xy", "yz_swap", "yz_swap_flipx"), + help="Camera local-axis mapping from Blender camera to OpenCV camera", + ) + parser.add_argument( + "--world-conv", + default="identity", + choices=("identity", "rx90", "rxm90"), + help="Extra conversion from OpenCV world to scene world basis", + ) + return parser.parse_args(sys.argv[sys.argv.index("--") + 1 :]) + + +def _cv_to_gltf_matrix(coord: str) -> np.ndarray: + if coord == "raw": + return np.eye(4, dtype=np.float32) + if coord == "opengl": + return np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float32) + if coord == "blender": + rot_x_neg_90 = np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + flip_x = np.diag([-1.0, 1.0, 1.0, 1.0]).astype(np.float32) + return flip_x @ (rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32)) + if coord == "blender_noflip": + rot_x_neg_90 = np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + if coord == "blender_zup": + return np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + return np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + + +def _load_alignment(path_str: str) -> np.ndarray: + if not path_str: + return np.eye(4, dtype=np.float32) + path = Path(path_str).resolve() + if not path.exists(): + raise FileNotFoundError(path) + payload = json.loads(path.read_text(encoding="utf-8")) + T = np.asarray(payload.get("T", None), dtype=np.float32) + if T.shape != (4, 4): + raise ValueError(f"Alignment T must be 4x4, got {T.shape}") + return T + + +def _set_engine(scene: bpy.types.Scene, engine_name: str) -> None: + enum_items = scene.render.bl_rna.properties["engine"].enum_items + valid = {item.identifier for item in enum_items} + if engine_name in valid: + scene.render.engine = engine_name + return + if "BLENDER_EEVEE_NEXT" in valid: + scene.render.engine = "BLENDER_EEVEE_NEXT" + return + if "BLENDER_EEVEE" in valid: + scene.render.engine = "BLENDER_EEVEE" + return + + +def _set_basic_lighting(scene: bpy.types.Scene, world_strength: float, sun_energy: float) -> None: + world = scene.world + if world is None: + world = bpy.data.worlds.new("World") + scene.world = world + world.use_nodes = True + nt = world.node_tree + if nt is not None: + bg = nt.nodes.get("Background") + if bg is not None and "Strength" in bg.inputs: + bg.inputs["Strength"].default_value = float(world_strength) + + has_light = any(obj.type == "LIGHT" for obj in scene.objects) + if not has_light: + light_data = bpy.data.lights.new(name="Sun", type="SUN") + light_data.energy = float(sun_energy) + light_obj = bpy.data.objects.new(name="Sun", object_data=light_data) + scene.collection.objects.link(light_obj) + light_obj.rotation_euler = (math.radians(55.0), 0.0, math.radians(25.0)) + + +def _set_color_management(scene: bpy.types.Scene) -> None: + try: + view_items = scene.view_settings.bl_rna.properties["view_transform"].enum_items + valid = {item.identifier for item in view_items} + if "Standard" in valid: + scene.view_settings.view_transform = "Standard" + except Exception: + pass + scene.view_settings.exposure = 0.0 + scene.view_settings.gamma = 1.0 + + +def _attach_camera_headlight( + scene: bpy.types.Scene, + cam_obj: bpy.types.Object, + energy: float, + angle_deg: float, + light_type: str, +) -> bpy.types.Object: + kind = str(light_type).lower() + if kind == "spot": + light_kind = "SPOT" + elif kind == "sun": + light_kind = "SUN" + else: + light_kind = "POINT" + light_data = bpy.data.lights.new(name="CameraHeadlight", type=light_kind) + light_data.energy = float(max(0.0, energy)) + if light_kind == "SPOT": + light_data.spot_size = math.radians(float(np.clip(angle_deg, 1.0, 179.0))) + light_data.spot_blend = 0.2 + if hasattr(light_data, "shadow_soft_size"): + light_data.shadow_soft_size = 0.08 + light_data.use_shadow = False + light_obj = bpy.data.objects.new(name="CameraHeadlight", object_data=light_data) + scene.collection.objects.link(light_obj) + light_obj.parent = cam_obj + light_obj.location = (0.0, 0.0, 0.0) + light_obj.rotation_euler = (0.0, 0.0, 0.0) + return light_obj + + +def _compute_scene_center_and_extent() -> Tuple[np.ndarray, float]: + bmin = np.array([np.inf, np.inf, np.inf], dtype=np.float32) + bmax = np.array([-np.inf, -np.inf, -np.inf], dtype=np.float32) + has = False + for obj in bpy.data.objects: + if obj.type != "MESH": + continue + if obj.name.startswith("table_plane"): + continue + if obj.hide_render: + continue + has = True + for c in obj.bound_box: + pw = obj.matrix_world @ Vector((c[0], c[1], c[2])) + p = np.asarray([pw.x, pw.y, pw.z], dtype=np.float32) + bmin = np.minimum(bmin, p) + bmax = np.maximum(bmax, p) + if not has or not np.isfinite(bmin).all(): + return np.zeros(3, dtype=np.float32), 1.0 + center = ((bmin + bmax) * 0.5).astype(np.float32) + extent = float(np.max(bmax - bmin)) + return center, max(1e-3, extent) + + +def _add_ambient_point_rig(scene: bpy.types.Scene, total_energy: float) -> None: + center, extent = _compute_scene_center_and_extent() + dist = max(0.8, min(3.0, 1.2 * extent)) + offsets = [ + (1.0, 0.0, 0.0), + (-1.0, 0.0, 0.0), + (0.0, 1.0, 0.0), + (0.0, -1.0, 0.0), + (0.0, 0.0, 1.0), + (0.0, 0.0, -1.0), + (1.0, 1.0, 1.0), + (-1.0, -1.0, 1.0), + ] + per_light = float(max(0.0, total_energy) / max(1, len(offsets))) + for i, off in enumerate(offsets): + v = Vector(off) + v.normalize() + loc = Vector((float(center[0]), float(center[1]), float(center[2]))) + v * dist + light_data = bpy.data.lights.new(name=f"AmbientPoint_{i:02d}", type="POINT") + light_data.energy = per_light + light_data.shadow_soft_size = max(0.05, 0.25 * dist) + light_data.use_shadow = False + light_obj = bpy.data.objects.new(name=f"AmbientPoint_{i:02d}", object_data=light_data) + scene.collection.objects.link(light_obj) + light_obj.location = loc + + +def _apply_keep_objects(scene: bpy.types.Scene, keep_objects_arg: str) -> None: + keep_raw = [x.strip() for x in str(keep_objects_arg).split(",") if x.strip()] + if not keep_raw: + return + keep = set(keep_raw) + for obj in scene.objects: + if obj.type != "MESH": + continue + base = obj.name.split(".", 1)[0] + visible = base in keep + obj.hide_render = not visible + obj.hide_viewport = not visible + + +def _apply_white_matte(scene: bpy.types.Scene, emission_strength: float) -> None: + mat_name = "Codex_WhiteMatte" + mat = bpy.data.materials.get(mat_name) + if mat is None: + mat = bpy.data.materials.new(name=mat_name) + mat.use_nodes = True + nt = mat.node_tree + if nt is not None: + nt.nodes.clear() + n_out = nt.nodes.new("ShaderNodeOutputMaterial") + n_em = nt.nodes.new("ShaderNodeEmission") + n_em.inputs["Color"].default_value = (1.0, 1.0, 1.0, 1.0) + n_em.inputs["Strength"].default_value = float(max(0.0, emission_strength)) + nt.links.new(n_em.outputs["Emission"], n_out.inputs["Surface"]) + + for obj in scene.objects: + if obj.type != "MESH": + continue + if obj.name.startswith("table_plane"): + continue + if len(obj.data.materials) == 0: + obj.data.materials.append(mat) + else: + for i in range(len(obj.data.materials)): + obj.data.materials[i] = mat + + world = scene.world + if world is None: + world = bpy.data.worlds.new("World") + scene.world = world + world.use_nodes = True + ntw = world.node_tree + if ntw is not None: + bg = ntw.nodes.get("Background") + if bg is not None: + if "Color" in bg.inputs: + bg.inputs["Color"].default_value = (0.0, 0.0, 0.0, 1.0) + if "Strength" in bg.inputs: + bg.inputs["Strength"].default_value = 1.0 + + +def _apply_white_clay(scene: bpy.types.Scene, keep_world: bool = False) -> None: + mat_name = "Codex_WhiteClay" + mat = bpy.data.materials.get(mat_name) + if mat is None: + mat = bpy.data.materials.new(name=mat_name) + mat.use_nodes = True + nt = mat.node_tree + if nt is not None: + nt.nodes.clear() + n_out = nt.nodes.new("ShaderNodeOutputMaterial") + n_bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled") + n_bsdf.inputs["Base Color"].default_value = (1.0, 1.0, 1.0, 1.0) + n_bsdf.inputs["Roughness"].default_value = 0.55 + if "Specular IOR Level" in n_bsdf.inputs: + n_bsdf.inputs["Specular IOR Level"].default_value = 0.2 + elif "Specular" in n_bsdf.inputs: + n_bsdf.inputs["Specular"].default_value = 0.2 + nt.links.new(n_bsdf.outputs["BSDF"], n_out.inputs["Surface"]) + + for obj in scene.objects: + if obj.type != "MESH": + continue + if obj.name.startswith("table_plane"): + continue + if len(obj.data.materials) == 0: + obj.data.materials.append(mat) + else: + for i in range(len(obj.data.materials)): + obj.data.materials[i] = mat + + if not keep_world: + world = scene.world + if world is None: + world = bpy.data.worlds.new("World") + scene.world = world + world.use_nodes = True + ntw = world.node_tree + if ntw is not None: + bg = ntw.nodes.get("Background") + if bg is not None: + if "Color" in bg.inputs: + bg.inputs["Color"].default_value = (0.0, 0.0, 0.0, 1.0) + if "Strength" in bg.inputs: + bg.inputs["Strength"].default_value = 1.0 + + +def _apply_intrinsics_to_camera( + cam_data: bpy.types.Camera, + K: np.ndarray, + width: int, + height: int, +) -> None: + fx = float(K[0, 0]) + fy = float(K[1, 1]) + cx = float(K[0, 2]) + cy = float(K[1, 2]) + W = max(1.0, float(width)) + H = max(1.0, float(height)) + + cam_data.type = "PERSP" + cam_data.sensor_fit = "HORIZONTAL" + cam_data.sensor_width = 36.0 + cam_data.lens = fx * cam_data.sensor_width / W + cam_data.sensor_height = max(1e-6, cam_data.lens * H / max(1e-6, fy)) + cam_data.shift_x = -(cx - 0.5 * W) / W + cam_data.shift_y = (cy - 0.5 * H) / H + + +def _world_conv_matrix(name: str) -> np.ndarray: + if name == "identity": + return np.eye(4, dtype=np.float32) + if name == "rx90": + return np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + + +def _camera_axis_matrix(name: str) -> np.ndarray: + if name == "identity": + return np.eye(4, dtype=np.float32) + if name == "flip_xy": + return np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + if name == "standard": + return np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float32) + if name == "yz_swap": + return np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return np.array( + [ + [-1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + + +def _find_root_obj() -> bpy.types.Object | None: + for name in ("root_cv2gl", "root"): + obj = bpy.data.objects.get(name) + if obj is not None: + return obj + return None + + +def _import_camera_from_reference_glb(ref_glb: Path, preferred_name: str) -> bpy.types.Object: + if not ref_glb.exists(): + raise FileNotFoundError(ref_glb) + before = {obj.name for obj in bpy.data.objects} + bpy.ops.import_scene.gltf(filepath=str(ref_glb)) + added = [obj for obj in bpy.data.objects if obj.name not in before] + if not added: + raise RuntimeError(f"Failed to import camera ref GLB: {ref_glb}") + + cams = [obj for obj in added if obj.type == "CAMERA"] + if not cams: + raise RuntimeError(f"No camera found in {ref_glb}") + + chosen = None + if preferred_name: + for cam in cams: + if cam.name.split(".", 1)[0] == preferred_name: + chosen = cam + break + if chosen is None: + chosen = cams[0] + + for obj in added: + if obj is chosen: + continue + obj.hide_render = True + obj.hide_viewport = True + + return chosen + + +def _build_world_y_flip_transform(world_seq: List[np.ndarray]) -> np.ndarray: + if not world_seq: + return np.eye(4, dtype=np.float32) + x0 = float(np.mean([m[0, 3] for m in world_seq])) + T = np.array( + [ + [-1.0, 0.0, 0.0, 2.0 * x0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return T + + +def _load_pose_map(pose_json: Path) -> Dict[int, np.ndarray]: + payload = json.loads(pose_json.read_text(encoding="utf-8")) + out: Dict[int, np.ndarray] = {} + for k, v in payload.items(): + try: + idx = int(k) + except Exception: + continue + mat = np.asarray(v, dtype=np.float32) + if mat.shape == (4, 4): + out[idx] = mat + return out + + +def _nearest_pose(pose_map: Dict[int, np.ndarray], frame_id: int) -> Tuple[int, np.ndarray]: + ids = sorted(pose_map.keys()) + if not ids: + raise ValueError("Empty pose map") + if frame_id in pose_map: + return frame_id, pose_map[frame_id] + nid = min(ids, key=lambda x: abs(x - frame_id)) + return nid, pose_map[nid] + + +def _load_category_map(run_dir: Path) -> Dict[str, str]: + cfg_path = run_dir.parent.parent / "recon_ready" / run_dir.name / "pipeline_config.json" + if not cfg_path.exists(): + return {} + try: + payload = json.loads(cfg_path.read_text(encoding="utf-8")) + except Exception: + return {} + out: Dict[str, str] = {} + for obj in payload.get("objects", []): + name = str(obj.get("name", "")).strip() + if not name: + continue + out[name] = str(obj.get("category", "")).strip().lower() + return out + + +def _pick_pose_file(obj_dir: Path, preferred_name: str, category: str) -> Optional[Path]: + pose_dir = obj_dir / "pose_result" + candidates: List[Path] = [] + if category == "static": + candidates.extend([pose_dir / "poses_locked.json", pose_dir / "poses.json"]) + if preferred_name: + candidates.append(pose_dir / preferred_name) + else: + if preferred_name: + candidates.append(pose_dir / preferred_name) + candidates.extend([pose_dir / "poses.json", pose_dir / "poses_physics.json", pose_dir / "poses_locked.json"]) + seen = set() + for p in candidates: + key = str(p.resolve()) + if key in seen: + continue + seen.add(key) + if p.exists(): + return p + return None + + +def _find_blender_object(name: str) -> Optional[bpy.types.Object]: + obj = bpy.data.objects.get(name) + if obj is not None: + return obj + for o in bpy.data.objects: + if o.name.split(".", 1)[0] == name: + return o + return None + + +def _rotation_projection(R: np.ndarray) -> np.ndarray: + U, _, Vt = np.linalg.svd(R) + Rn = U @ Vt + if np.linalg.det(Rn) < 0.0: + U[:, -1] *= -1.0 + Rn = U @ Vt + return Rn.astype(np.float32) + + +def _compute_scene_center_world() -> Optional[np.ndarray]: + bmin = np.array([np.inf, np.inf, np.inf], dtype=np.float32) + bmax = np.array([-np.inf, -np.inf, -np.inf], dtype=np.float32) + has = False + for obj in bpy.data.objects: + if obj.type != "MESH": + continue + if obj.name.startswith("table_plane"): + continue + has = True + for c in obj.bound_box: + pw = obj.matrix_world @ Vector((c[0], c[1], c[2])) + p = np.asarray([pw.x, pw.y, pw.z], dtype=np.float32) + bmin = np.minimum(bmin, p) + bmax = np.maximum(bmax, p) + if not has or not np.isfinite(bmin).all(): + return None + return ((bmin + bmax) * 0.5).astype(np.float32) + + +def _camera_face_score( + C: np.ndarray, + align_T: np.ndarray, + extrinsics: np.ndarray, + cv_cam_to_bl_cam: np.ndarray, + scene_center: np.ndarray, + sample_count: int = 5, +) -> float: + n = int(extrinsics.shape[0]) + if n <= 0: + return -1e9 + if sample_count <= 1: + sample_ids = [0] + else: + sample_ids = sorted({int(round(x)) for x in np.linspace(0, n - 1, num=min(sample_count, n))}) + score = 0.0 + for fid in sample_ids: + cam_to_world_cv = np.linalg.inv(extrinsics[fid]).astype(np.float32) + M = C @ align_T @ cam_to_world_cv @ cv_cam_to_bl_cam + o = M[:3, 3] + fwd = -M[:3, 2] + v = scene_center - o + nf = float(np.linalg.norm(fwd)) + nv = float(np.linalg.norm(v)) + if nf < 1e-8 or nv < 1e-8: + continue + score += float(np.dot(fwd, v) / (nf * nv)) + return score / max(1, len(sample_ids)) + + +def _solve_global_world_map_from_objects( + run_dir: Path, + align_T: np.ndarray, + extrinsics: np.ndarray, + cv_cam_to_bl_cam: np.ndarray, + frame_id: int, + preferred_pose_name: str, + anchor_name: str, +) -> np.ndarray: + if not run_dir.exists(): + raise FileNotFoundError(run_dir) + objects_root = run_dir / "objects" + if not objects_root.exists(): + raise FileNotFoundError(objects_root) + if frame_id < 0 or frame_id >= int(extrinsics.shape[0]): + raise ValueError(f"calib-frame out of range: {frame_id}") + + cam_to_world_cv = np.linalg.inv(extrinsics[frame_id]).astype(np.float32) + category_map = _load_category_map(run_dir) + candidates: List[Tuple[str, np.ndarray]] = [] + for obj_dir in sorted([d for d in objects_root.iterdir() if d.is_dir()]): + name = obj_dir.name + if anchor_name and name != anchor_name: + continue + bobj = _find_blender_object(name) + if bobj is None or bobj.type != "MESH": + continue + category = category_map.get(name, "") + pose_file = _pick_pose_file(obj_dir, preferred_pose_name, category) + if pose_file is None: + continue + pose_map = _load_pose_map(pose_file) + if not pose_map: + continue + _, pose_cam = _nearest_pose(pose_map, frame_id) + obj_world_cv = (align_T @ cam_to_world_cv @ pose_cam).astype(np.float32) + obj_world_glb = np.asarray(bobj.matrix_world, dtype=np.float32) + try: + C_i = obj_world_glb @ np.linalg.inv(obj_world_cv) + except np.linalg.LinAlgError: + continue + candidates.append((name, C_i.astype(np.float32))) + + if not candidates: + raise RuntimeError( + "Auto-calibration failed: no usable objects found. " + "Check --run-dir/--calib-pose-name/--calib-anchor." + ) + + if anchor_name: + C = candidates[0][1] + print(f"[Info] Auto-calib anchor: {candidates[0][0]}") + return C + + scene_center = _compute_scene_center_world() + if scene_center is None: + mats = np.stack([m for _, m in candidates], axis=0) + C = np.median(mats, axis=0).astype(np.float32) + C[:3, :3] = _rotation_projection(C[:3, :3]) + C[3, :] = np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float32) + print(f"[Warn] Auto-calib: scene center unavailable, fallback to median from {len(candidates)} candidates.") + return C + + best_name = "" + best_C = None + best_score = -1e9 + for name, C_i in candidates: + score = _camera_face_score( + C=C_i, + align_T=align_T, + extrinsics=extrinsics, + cv_cam_to_bl_cam=cv_cam_to_bl_cam, + scene_center=scene_center, + sample_count=5, + ) + print(f"[AutoCalib] {name}: face_score={score:.6f}") + if score > best_score: + best_score = score + best_name = name + best_C = C_i + + assert best_C is not None + print(f"[Info] Auto-calib selected anchor={best_name}, face_score={best_score:.6f}") + return best_C + + +def main() -> None: + args = parse_args() + input_glb = Path(args.input_glb).resolve() + result_npz = Path(args.result_npz).resolve() + output_video = Path(args.output_video).resolve() + + if not input_glb.exists(): + raise FileNotFoundError(input_glb) + if not result_npz.exists(): + raise FileNotFoundError(result_npz) + + data = np.load(result_npz) + extrinsics = np.asarray(data["extrinsics"], dtype=np.float32) + intrinsics = np.asarray(data["intrinsics"], dtype=np.float32) + if extrinsics.ndim != 3 or extrinsics.shape[1:] != (4, 4): + raise ValueError(f"Invalid extrinsics shape: {extrinsics.shape}") + if intrinsics.ndim != 3 or intrinsics.shape[1:] != (3, 3): + raise ValueError(f"Invalid intrinsics shape: {intrinsics.shape}") + num_frames = int(extrinsics.shape[0]) + if int(args.max_frames) > 0: + num_frames = min(num_frames, int(args.max_frames)) + + if "video" in data: + video_arr = data["video"] + if video_arr.ndim == 4 and video_arr.shape[1] in (1, 3, 4): + height, width = int(video_arr.shape[2]), int(video_arr.shape[3]) + elif video_arr.ndim == 4: + height, width = int(video_arr.shape[1]), int(video_arr.shape[2]) + else: + raise ValueError(f"Invalid video shape: {video_arr.shape}") + elif "depths" in data: + dep = data["depths"] + if dep.ndim != 3: + raise ValueError(f"Invalid depths shape: {dep.shape}") + height, width = int(dep.shape[1]), int(dep.shape[2]) + else: + raise KeyError("result.npz missing both 'video' and 'depths'") + + align_T = _load_alignment(args.alignment) + cv_to_gltf = _cv_to_gltf_matrix(args.coord) + cv_cam_to_bl_cam = _camera_axis_matrix(args.camera_axis) + if args.camera_roll_180: + cv_cam_to_bl_cam = cv_cam_to_bl_cam @ np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + + fps = float(args.fps) + if fps <= 0: + raise ValueError("fps must be > 0") + + bpy.ops.wm.read_factory_settings(use_empty=True) + scene = bpy.context.scene + scene.render.fps = int(round(fps)) + scene.render.fps_base = float(scene.render.fps) / fps + _set_engine(scene, args.engine) + _set_color_management(scene) + + bpy.ops.import_scene.gltf(filepath=str(input_glb)) + _apply_keep_objects(scene, args.keep_objects) + _set_basic_lighting(scene, world_strength=args.world_strength, sun_energy=args.sun_energy) + if args.ambient_rig: + _add_ambient_point_rig(scene, total_energy=float(args.ambient_rig_energy)) + if args.white_matte and args.white_clay: + raise ValueError("--white-matte and --white-clay are mutually exclusive") + if args.white_matte: + _apply_white_matte(scene, emission_strength=float(args.matte_emission_strength)) + if args.white_clay: + _apply_white_clay(scene, keep_world=bool(args.clay_keep_world)) + use_ref_camera = bool(str(args.camera_ref_glb).strip()) + if use_ref_camera: + cam_obj = _import_camera_from_reference_glb(Path(args.camera_ref_glb).resolve(), str(args.camera_ref_name)) + cam_data = cam_obj.data + else: + cam_data = bpy.data.cameras.new(args.camera_name) + cam_obj = bpy.data.objects.new(args.camera_name, cam_data) + bpy.context.scene.collection.objects.link(cam_obj) + _apply_intrinsics_to_camera(cam_data, intrinsics[0], width, height) + + scene.render.resolution_x = int(round(width * float(args.resolution_scale))) + scene.render.resolution_y = int(round(height * float(args.resolution_scale))) + scene.render.resolution_percentage = 100 + scene.frame_start = 0 + scene.frame_end = max(0, num_frames - 1) + scene.camera = cam_obj + if args.camera_headlight: + _attach_camera_headlight( + scene, + cam_obj=cam_obj, + energy=float(args.camera_headlight_energy), + angle_deg=float(args.camera_headlight_angle), + light_type=str(args.camera_headlight_type), + ) + cam_obj.rotation_mode = "QUATERNION" + cam_data.clip_start = 1e-3 + cam_data.clip_end = 1e5 + + world_conv = _world_conv_matrix(args.world_conv) + scene.frame_set(int(np.clip(int(args.calib_frame), 0, max(0, num_frames - 1)))) + + if not use_ref_camera: + if args.auto_calibrate: + if not args.run_dir: + raise ValueError("--auto-calibrate requires --run-dir") + global_world_map = _solve_global_world_map_from_objects( + run_dir=Path(args.run_dir).resolve(), + align_T=align_T, + extrinsics=extrinsics, + cv_cam_to_bl_cam=cv_cam_to_bl_cam, + frame_id=int(np.clip(int(args.calib_frame), 0, max(0, num_frames - 1))), + preferred_pose_name=str(args.calib_pose_name), + anchor_name=str(args.calib_anchor).strip(), + ) + print("[Info] Using auto-calibrated global world map.") + else: + global_world_map = cv_to_gltf @ world_conv + + world_seq: List[np.ndarray] = [] + for i in range(num_frames): + cam_to_world_cv = np.linalg.inv(extrinsics[i]).astype(np.float32) + world_m = global_world_map @ align_T @ cam_to_world_cv @ cv_cam_to_bl_cam + world_seq.append(world_m) + + if args.world_flip_y: + Tflip = _build_world_y_flip_transform(world_seq) + world_seq = [Tflip @ m for m in world_seq] + print(f"[Info] Applied world-flip-y by yaw180-around-z (x pivot={Tflip[0,3] * 0.5:.6f}).") + + for i, world_m in enumerate(world_seq): + _apply_intrinsics_to_camera(cam_data, intrinsics[i], width, height) + m = Matrix(world_m.tolist()) + cam_obj.matrix_world = m + cam_obj.keyframe_insert(data_path="location", frame=i) + cam_obj.keyframe_insert(data_path="rotation_quaternion", frame=i) + cam_obj.keyframe_insert(data_path="scale", frame=i) + cam_data.keyframe_insert(data_path="lens", frame=i) + cam_data.keyframe_insert(data_path="shift_x", frame=i) + cam_data.keyframe_insert(data_path="shift_y", frame=i) + cam_data.keyframe_insert(data_path="sensor_height", frame=i) + + if cam_obj.animation_data and cam_obj.animation_data.action: + for fcurve in cam_obj.animation_data.action.fcurves: + for kp in fcurve.keyframe_points: + kp.interpolation = "LINEAR" + if cam_data.animation_data and cam_data.animation_data.action: + for fcurve in cam_data.animation_data.action.fcurves: + for kp in fcurve.keyframe_points: + kp.interpolation = "LINEAR" + else: + if args.world_flip_y: + world_seq: List[np.ndarray] = [] + for i in range(num_frames): + scene.frame_set(i) + world_seq.append(np.asarray(cam_obj.matrix_world, dtype=np.float32)) + Tflip = _build_world_y_flip_transform(world_seq) + for i, world_m in enumerate(world_seq): + m = Matrix((Tflip @ world_m).tolist()) + cam_obj.matrix_world = m + cam_obj.keyframe_insert(data_path="location", frame=i) + cam_obj.keyframe_insert(data_path="rotation_quaternion", frame=i) + cam_obj.keyframe_insert(data_path="scale", frame=i) + print(f"[Info] Applied world-flip-y to ref camera (x pivot={Tflip[0,3] * 0.5:.6f}).") + print(f"[Info] Using camera animation from ref GLB: {args.camera_ref_glb}") + + output_video.parent.mkdir(parents=True, exist_ok=True) + scene.render.image_settings.file_format = "FFMPEG" + scene.render.ffmpeg.format = "MPEG4" + scene.render.ffmpeg.codec = "H264" + scene.render.ffmpeg.constant_rate_factor = "MEDIUM" + scene.render.ffmpeg.ffmpeg_preset = "GOOD" + scene.render.filepath = str(output_video) + + bpy.ops.render.render(animation=True, write_still=False) + print(f"[OK] Wrote: {output_video}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/blender_render_obj_sequence_with_video_camera.py b/OVOW/engine/tools/blender_render_obj_sequence_with_video_camera.py new file mode 100644 index 0000000000000000000000000000000000000000..f005325f228b1e424aee945720fd1e674978c6cc --- /dev/null +++ b/OVOW/engine/tools/blender_render_obj_sequence_with_video_camera.py @@ -0,0 +1,579 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import math +import re +import sys +from pathlib import Path +from typing import Dict, List, Tuple + +import bpy +import numpy as np +from mathutils import Matrix + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Render per-frame OBJ mesh sequence with camera trajectory from result.npz." + ) + parser.add_argument("--mesh-dir", required=True, help="Directory containing frame_*.obj sequence") + parser.add_argument("--result-npz", required=True, help="Path to run_dir/results/result.npz") + parser.add_argument("--output-video", required=True, help="Output mp4 path") + parser.add_argument( + "--output-rgba-dir", + default="", + help="Optional output directory for transparent RGBA frame sequence (PNG).", + ) + parser.add_argument( + "--transparent-bg", + action="store_true", + help="Render with transparent background (effective with --output-rgba-dir).", + ) + parser.add_argument("--alignment", default="", help="Optional alignment_plane.json (contains 4x4 T)") + parser.add_argument( + "--coord", + default="blender_zup", + choices=("gltf", "opengl", "blender", "blender_noflip", "blender_zup", "raw"), + help="Coordinate conversion from OpenCV world to Blender import world", + ) + parser.add_argument( + "--camera-axis", + default="standard", + choices=("standard", "identity", "flip_xy", "yz_swap", "yz_swap_flipx"), + help="Camera local-axis mapping from Blender camera to OpenCV camera", + ) + parser.add_argument( + "--world-conv", + default="identity", + choices=("identity", "rx90", "rxm90"), + help="Extra conversion from OpenCV world to scene world basis", + ) + parser.add_argument("--frame-glob", default="frame_*.obj", help="Frame filename glob under --mesh-dir") + parser.add_argument("--fps", type=float, default=10.0, help="Render FPS") + parser.add_argument("--engine", default="BLENDER_EEVEE_NEXT", help="Render engine") + parser.add_argument("--resolution-scale", type=float, default=1.0, help="Output resolution scale") + parser.add_argument("--camera-name", default="video_camera", help="Camera object name") + parser.add_argument("--max-frames", type=int, default=-1, help="Optional max rendered frames") + parser.add_argument("--world-strength", type=float, default=1.0, help="World background strength") + parser.add_argument("--sun-energy", type=float, default=3.0, help="Sun light energy") + parser.add_argument("--bg-gray", type=float, default=0.35, help="Background gray level in [0,1]") + parser.add_argument("--white-matte", action="store_true", help="Override mesh materials to white emission") + parser.add_argument("--white-clay", action="store_true", help="Override mesh materials to white clay") + parser.add_argument( + "--matte-emission-strength", + type=float, + default=5.0, + help="Emission strength for --white-matte", + ) + parser.add_argument( + "--camera-headlight", + action="store_true", + help="Attach a camera-mounted light pointing along camera viewing direction.", + ) + parser.add_argument( + "--camera-headlight-energy", + type=float, + default=2500.0, + help="Energy for --camera-headlight.", + ) + parser.add_argument( + "--camera-headlight-type", + default="spot", + choices=("spot", "point", "sun"), + help="Light type for --camera-headlight.", + ) + parser.add_argument( + "--camera-headlight-angle", + type=float, + default=55.0, + help="Spot cone angle in degrees for --camera-headlight.", + ) + return parser.parse_args(sys.argv[sys.argv.index("--") + 1 :]) + + +def _parse_frame_id(path: Path) -> int | None: + stem = path.stem + m = re.search(r"(\d+)$", stem) + if m: + return int(m.group(1)) + m = re.search(r"(\d+)", stem) + if m: + return int(m.group(1)) + return None + + +def _load_obj_vertices_faces(path: Path) -> Tuple[np.ndarray, List[Tuple[int, int, int]]]: + verts: List[Tuple[float, float, float]] = [] + faces: List[Tuple[int, int, int]] = [] + for raw in path.read_text(encoding="utf-8", errors="ignore").splitlines(): + line = raw.strip() + if not line or line.startswith("#"): + continue + if line.startswith("v "): + toks = line.split() + if len(toks) < 4: + continue + verts.append((float(toks[1]), float(toks[2]), float(toks[3]))) + elif line.startswith("f "): + toks = line.split()[1:] + idxs: List[int] = [] + for tok in toks: + head = tok.split("/", 1)[0] + if not head: + continue + vi = int(head) + if vi > 0: + vi = vi - 1 + else: + vi = len(verts) + vi + idxs.append(vi) + if len(idxs) < 3: + continue + for i in range(1, len(idxs) - 1): + faces.append((idxs[0], idxs[i], idxs[i + 1])) + if not verts or not faces: + raise RuntimeError(f"Invalid/empty OBJ mesh: {path}") + return np.asarray(verts, dtype=np.float32), faces + + +def _cv_to_gltf_matrix(coord: str) -> np.ndarray: + if coord == "raw": + return np.eye(4, dtype=np.float32) + if coord == "opengl": + return np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float32) + if coord == "blender": + rot_x_neg_90 = np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + flip_x = np.diag([-1.0, 1.0, 1.0, 1.0]).astype(np.float32) + return flip_x @ (rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32)) + if coord == "blender_noflip": + rot_x_neg_90 = np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + if coord == "blender_zup": + return np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + return np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + + +def _world_conv_matrix(name: str) -> np.ndarray: + if name == "identity": + return np.eye(4, dtype=np.float32) + if name == "rx90": + return np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + + +def _camera_axis_matrix(name: str) -> np.ndarray: + if name == "identity": + return np.eye(4, dtype=np.float32) + if name == "flip_xy": + return np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + if name == "standard": + return np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float32) + if name == "yz_swap": + return np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return np.array( + [ + [-1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + + +def _load_alignment(path_str: str) -> np.ndarray: + if not path_str: + return np.eye(4, dtype=np.float32) + path = Path(path_str).resolve() + if not path.exists(): + raise FileNotFoundError(path) + payload = json.loads(path.read_text(encoding="utf-8")) + T = np.asarray(payload.get("T", None), dtype=np.float32) + if T.shape != (4, 4): + raise ValueError(f"Alignment T must be 4x4, got {T.shape}") + return T + + +def _set_engine(scene: bpy.types.Scene, engine_name: str) -> None: + enum_items = scene.render.bl_rna.properties["engine"].enum_items + valid = {item.identifier for item in enum_items} + if engine_name in valid: + scene.render.engine = engine_name + return + if "BLENDER_EEVEE_NEXT" in valid: + scene.render.engine = "BLENDER_EEVEE_NEXT" + return + if "BLENDER_EEVEE" in valid: + scene.render.engine = "BLENDER_EEVEE" + return + + +def _set_color_management(scene: bpy.types.Scene) -> None: + try: + view_items = scene.view_settings.bl_rna.properties["view_transform"].enum_items + valid = {item.identifier for item in view_items} + if "Standard" in valid: + scene.view_settings.view_transform = "Standard" + except Exception: + pass + scene.view_settings.exposure = 0.0 + scene.view_settings.gamma = 1.0 + + +def _set_world(scene: bpy.types.Scene, gray: float, strength: float) -> None: + world = scene.world + if world is None: + world = bpy.data.worlds.new("World") + scene.world = world + world.use_nodes = True + nt = world.node_tree + if nt is None: + return + bg = nt.nodes.get("Background") + if bg is None: + return + g = float(np.clip(gray, 0.0, 1.0)) + if "Color" in bg.inputs: + bg.inputs["Color"].default_value = (g, g, g, 1.0) + if "Strength" in bg.inputs: + bg.inputs["Strength"].default_value = float(max(0.0, strength)) + + +def _set_basic_lighting(scene: bpy.types.Scene, sun_energy: float) -> None: + has_light = any(obj.type == "LIGHT" for obj in scene.objects) + if has_light: + return + light_data = bpy.data.lights.new(name="Sun", type="SUN") + light_data.energy = float(sun_energy) + light_obj = bpy.data.objects.new(name="Sun", object_data=light_data) + scene.collection.objects.link(light_obj) + light_obj.rotation_euler = (math.radians(55.0), 0.0, math.radians(25.0)) + + +def _attach_camera_headlight( + scene: bpy.types.Scene, + cam_obj: bpy.types.Object, + energy: float, + angle_deg: float, + light_type: str, +) -> bpy.types.Object: + kind = str(light_type).lower() + if kind == "spot": + light_kind = "SPOT" + elif kind == "sun": + light_kind = "SUN" + else: + light_kind = "POINT" + light_data = bpy.data.lights.new(name="CameraHeadlight", type=light_kind) + light_data.energy = float(max(0.0, energy)) + if light_kind == "SPOT": + light_data.spot_size = math.radians(float(np.clip(angle_deg, 1.0, 179.0))) + light_data.spot_blend = 0.2 + if hasattr(light_data, "shadow_soft_size"): + light_data.shadow_soft_size = 0.08 + light_data.use_shadow = False + light_obj = bpy.data.objects.new(name="CameraHeadlight", object_data=light_data) + scene.collection.objects.link(light_obj) + light_obj.parent = cam_obj + light_obj.location = (0.0, 0.0, 0.0) + light_obj.rotation_euler = (0.0, 0.0, 0.0) + return light_obj + + +def _apply_white_matte(objs: List[bpy.types.Object], emission_strength: float) -> None: + mat_name = "Codex_WhiteMatte" + mat = bpy.data.materials.get(mat_name) + if mat is None: + mat = bpy.data.materials.new(name=mat_name) + mat.use_nodes = True + nt = mat.node_tree + if nt is not None: + nt.nodes.clear() + n_out = nt.nodes.new("ShaderNodeOutputMaterial") + n_em = nt.nodes.new("ShaderNodeEmission") + n_em.inputs["Color"].default_value = (1.0, 1.0, 1.0, 1.0) + n_em.inputs["Strength"].default_value = float(max(0.0, emission_strength)) + nt.links.new(n_em.outputs["Emission"], n_out.inputs["Surface"]) + + for obj in objs: + if len(obj.data.materials) == 0: + obj.data.materials.append(mat) + else: + for i in range(len(obj.data.materials)): + obj.data.materials[i] = mat + + +def _apply_white_clay(objs: List[bpy.types.Object]) -> None: + mat_name = "Codex_WhiteClay" + mat = bpy.data.materials.get(mat_name) + if mat is None: + mat = bpy.data.materials.new(name=mat_name) + mat.use_nodes = True + nt = mat.node_tree + if nt is not None: + nt.nodes.clear() + n_out = nt.nodes.new("ShaderNodeOutputMaterial") + n_bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled") + n_bsdf.inputs["Base Color"].default_value = (1.0, 1.0, 1.0, 1.0) + n_bsdf.inputs["Roughness"].default_value = 0.55 + if "Specular IOR Level" in n_bsdf.inputs: + n_bsdf.inputs["Specular IOR Level"].default_value = 0.2 + elif "Specular" in n_bsdf.inputs: + n_bsdf.inputs["Specular"].default_value = 0.2 + nt.links.new(n_bsdf.outputs["BSDF"], n_out.inputs["Surface"]) + + for obj in objs: + if len(obj.data.materials) == 0: + obj.data.materials.append(mat) + else: + for i in range(len(obj.data.materials)): + obj.data.materials[i] = mat + + +def _apply_intrinsics_to_camera( + cam_data: bpy.types.Camera, + K: np.ndarray, + width: int, + height: int, +) -> None: + fx = float(K[0, 0]) + fy = float(K[1, 1]) + cx = float(K[0, 2]) + cy = float(K[1, 2]) + W = max(1.0, float(width)) + H = max(1.0, float(height)) + + cam_data.type = "PERSP" + cam_data.sensor_fit = "HORIZONTAL" + cam_data.sensor_width = 36.0 + cam_data.lens = fx * cam_data.sensor_width / W + cam_data.sensor_height = max(1e-6, cam_data.lens * H / max(1e-6, fy)) + cam_data.shift_x = -(cx - 0.5 * W) / W + cam_data.shift_y = (cy - 0.5 * H) / H + + +def _build_mesh_frame_map(mesh_dir: Path, frame_glob: str) -> Dict[int, Path]: + out: Dict[int, Path] = {} + for p in sorted(mesh_dir.glob(frame_glob)): + fid = _parse_frame_id(p) + if fid is None: + continue + out[fid] = p + return out + + +def _nearest_frame(mesh_ids: List[int], frame_id: int) -> int: + return min(mesh_ids, key=lambda x: abs(x - frame_id)) + + +def main() -> None: + args = parse_args() + mesh_dir = Path(args.mesh_dir).resolve() + result_npz = Path(args.result_npz).resolve() + output_video = Path(args.output_video).resolve() + output_rgba_dir = Path(args.output_rgba_dir).resolve() if args.output_rgba_dir else None + + if not mesh_dir.exists(): + raise FileNotFoundError(mesh_dir) + if not result_npz.exists(): + raise FileNotFoundError(result_npz) + + data = np.load(result_npz) + extrinsics = np.asarray(data["extrinsics"], dtype=np.float32) + intrinsics = np.asarray(data["intrinsics"], dtype=np.float32) + if extrinsics.ndim != 3 or extrinsics.shape[1:] != (4, 4): + raise ValueError(f"Invalid extrinsics shape: {extrinsics.shape}") + if intrinsics.ndim != 3 or intrinsics.shape[1:] != (3, 3): + raise ValueError(f"Invalid intrinsics shape: {intrinsics.shape}") + num_frames = int(extrinsics.shape[0]) + if int(args.max_frames) > 0: + num_frames = min(num_frames, int(args.max_frames)) + + if "video" in data: + video_arr = data["video"] + if video_arr.ndim == 4 and video_arr.shape[1] in (1, 3, 4): + height, width = int(video_arr.shape[2]), int(video_arr.shape[3]) + elif video_arr.ndim == 4: + height, width = int(video_arr.shape[1]), int(video_arr.shape[2]) + else: + raise ValueError(f"Invalid video shape: {video_arr.shape}") + elif "depths" in data: + dep = data["depths"] + if dep.ndim != 3: + raise ValueError(f"Invalid depths shape: {dep.shape}") + height, width = int(dep.shape[1]), int(dep.shape[2]) + else: + raise KeyError("result.npz missing both 'video' and 'depths'") + + mesh_map = _build_mesh_frame_map(mesh_dir, str(args.frame_glob)) + if not mesh_map: + raise FileNotFoundError(f"No mesh frames found in {mesh_dir} (glob={args.frame_glob})") + mesh_ids = sorted(mesh_map.keys()) + + frame_to_mesh_id: List[int] = [] + for i in range(num_frames): + if i in mesh_map: + frame_to_mesh_id.append(i) + else: + frame_to_mesh_id.append(_nearest_frame(mesh_ids, i)) + + bpy.ops.wm.read_factory_settings(use_empty=True) + scene = bpy.context.scene + fps = float(args.fps) + if fps <= 0: + raise ValueError("fps must be > 0") + scene.render.fps = int(round(fps)) + scene.render.fps_base = float(scene.render.fps) / fps + _set_engine(scene, args.engine) + _set_color_management(scene) + _set_world(scene, gray=float(args.bg_gray), strength=float(args.world_strength)) + scene.render.film_transparent = bool(args.transparent_bg) + _set_basic_lighting(scene, sun_energy=float(args.sun_energy)) + + align_T = _load_alignment(args.alignment) + cv_to_gltf = _cv_to_gltf_matrix(args.coord) + world_conv = _world_conv_matrix(args.world_conv) + cv_cam_to_bl_cam = _camera_axis_matrix(args.camera_axis) + obj_world_conv = cv_to_gltf @ world_conv @ align_T + + unique_ids = sorted(set(frame_to_mesh_id)) + obj_by_id: Dict[int, bpy.types.Object] = {} + for fid in unique_ids: + vtx, faces = _load_obj_vertices_faces(mesh_map[fid]) + mesh_data = bpy.data.meshes.new(f"mesh_frame_{fid:06d}") + mesh_data.from_pydata(vtx.tolist(), [], faces) + mesh_data.update() + if len(mesh_data.polygons) > 0: + for poly in mesh_data.polygons: + poly.use_smooth = True + obj = bpy.data.objects.new(f"frame_{fid:06d}", mesh_data) + scene.collection.objects.link(obj) + obj.matrix_world = Matrix(obj_world_conv.tolist()) + obj_by_id[fid] = obj + + all_objs = [obj_by_id[fid] for fid in unique_ids] + if args.white_matte and args.white_clay: + raise ValueError("--white-matte and --white-clay are mutually exclusive") + if args.white_matte: + _apply_white_matte(all_objs, emission_strength=float(args.matte_emission_strength)) + if args.white_clay: + _apply_white_clay(all_objs) + + for i in range(num_frames): + show_fid = frame_to_mesh_id[i] + show_obj = obj_by_id[show_fid] + for obj in all_objs: + visible = obj == show_obj + obj.hide_render = not visible + obj.hide_viewport = not visible + obj.keyframe_insert(data_path="hide_render", frame=i) + obj.keyframe_insert(data_path="hide_viewport", frame=i) + + cam_data = bpy.data.cameras.new(args.camera_name) + cam_obj = bpy.data.objects.new(args.camera_name, cam_data) + scene.collection.objects.link(cam_obj) + scene.camera = cam_obj + cam_obj.rotation_mode = "QUATERNION" + cam_data.clip_start = 1e-3 + cam_data.clip_end = 1e5 + if args.camera_headlight: + _attach_camera_headlight( + scene, + cam_obj=cam_obj, + energy=float(args.camera_headlight_energy), + angle_deg=float(args.camera_headlight_angle), + light_type=str(args.camera_headlight_type), + ) + + scene.render.resolution_x = int(round(width * float(args.resolution_scale))) + scene.render.resolution_y = int(round(height * float(args.resolution_scale))) + scene.render.resolution_percentage = 100 + scene.frame_start = 0 + scene.frame_end = max(0, num_frames - 1) + + for i in range(num_frames): + cam_to_world_cv = np.linalg.inv(extrinsics[i]).astype(np.float32) + world_m = obj_world_conv @ cam_to_world_cv @ cv_cam_to_bl_cam + _apply_intrinsics_to_camera(cam_data, intrinsics[i], width, height) + cam_obj.matrix_world = Matrix(world_m.tolist()) + cam_obj.keyframe_insert(data_path="location", frame=i) + cam_obj.keyframe_insert(data_path="rotation_quaternion", frame=i) + cam_obj.keyframe_insert(data_path="scale", frame=i) + cam_data.keyframe_insert(data_path="lens", frame=i) + cam_data.keyframe_insert(data_path="shift_x", frame=i) + cam_data.keyframe_insert(data_path="shift_y", frame=i) + cam_data.keyframe_insert(data_path="sensor_height", frame=i) + + if cam_obj.animation_data and cam_obj.animation_data.action: + for fcurve in cam_obj.animation_data.action.fcurves: + for kp in fcurve.keyframe_points: + kp.interpolation = "LINEAR" + if cam_data.animation_data and cam_data.animation_data.action: + for fcurve in cam_data.animation_data.action.fcurves: + for kp in fcurve.keyframe_points: + kp.interpolation = "LINEAR" + + if output_rgba_dir is not None: + output_rgba_dir.mkdir(parents=True, exist_ok=True) + scene.render.image_settings.file_format = "PNG" + scene.render.image_settings.color_mode = "RGBA" + scene.render.filepath = str((output_rgba_dir / "frame_").resolve()) + bpy.ops.render.render(animation=True, write_still=False) + print(f"[OK] Wrote RGBA frames: {output_rgba_dir}") + else: + output_video.parent.mkdir(parents=True, exist_ok=True) + scene.render.image_settings.file_format = "FFMPEG" + scene.render.ffmpeg.format = "MPEG4" + scene.render.ffmpeg.codec = "H264" + scene.render.ffmpeg.constant_rate_factor = "MEDIUM" + scene.render.ffmpeg.ffmpeg_preset = "GOOD" + scene.render.filepath = str(output_video) + + bpy.ops.render.render(animation=True, write_still=False) + print(f"[OK] Wrote: {output_video}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/blender_render_scene_textured_with_video_camera.py b/OVOW/engine/tools/blender_render_scene_textured_with_video_camera.py new file mode 100644 index 0000000000000000000000000000000000000000..341be87e1fae1fa5ed86bc5abdaf2beb2abf477b --- /dev/null +++ b/OVOW/engine/tools/blender_render_scene_textured_with_video_camera.py @@ -0,0 +1,1342 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import re +import shlex +import sys +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +import bpy +import numpy as np +from mathutils import Matrix + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Render textured full-scene (rigid/static + deform) with camera trajectory from result.npz." + ) + parser.add_argument("--run-dir", required=True, help="Run dir, e.g. .../video_pipeline_xxx/v10") + parser.add_argument("--config", required=True, help="Pipeline config JSON (effective config preferred)") + parser.add_argument("--result-npz", required=True, help="Path to run_dir/results/result.npz") + parser.add_argument("--output-video", required=True, help="Output mp4 path") + parser.add_argument( + "--output-rgba-dir", + default="", + help="Optional output directory for transparent RGBA frame sequence (PNG).", + ) + parser.add_argument( + "--transparent-bg", + action="store_true", + help="Render with transparent background (effective with --output-rgba-dir).", + ) + parser.add_argument("--alignment", default="", help="Optional alignment_plane.json (contains 4x4 T)") + parser.add_argument( + "--add-plane", + action="store_true", + help="Add a gray support plane for visualization in aligned scene coordinates.", + ) + parser.add_argument("--plane-scale", type=float, default=1.25, help="Plane size scale vs scene bbox") + parser.add_argument("--plane-gray", type=float, default=0.72, help="Plane gray value in [0,1]") + parser.add_argument( + "--coord", + default="blender_zup", + choices=("gltf", "opengl", "blender", "blender_noflip", "blender_zup", "raw"), + help="Coordinate conversion from OpenCV world to Blender scene world", + ) + parser.add_argument( + "--camera-axis", + default="standard", + choices=("standard", "identity", "flip_xy", "yz_swap", "yz_swap_flipx"), + help="Camera local-axis mapping from Blender camera to OpenCV camera", + ) + parser.add_argument( + "--world-conv", + default="identity", + choices=("identity", "rx90", "rxm90"), + help="Extra conversion from OpenCV world to scene world basis", + ) + parser.add_argument("--pose-name", default="", help="Preferred pose json name under pose_result") + parser.add_argument("--use-locked-static", action="store_true", help="Use poses_locked.json for static objects") + parser.add_argument("--deform-root", default="", help="Motion output root, e.g. outputs/motion324_outputs") + parser.add_argument("--deform-manifest", default="", help="Optional deform manifest.json path") + parser.add_argument( + "--deform-frames-dir", + default="world_mesh_frames", + help="Deform mesh directory name under each deform object", + ) + parser.add_argument("--fps", type=float, default=10.0, help="Render FPS") + parser.add_argument("--engine", default="BLENDER_EEVEE_NEXT", help="Render engine") + parser.add_argument("--resolution-scale", type=float, default=1.0, help="Output resolution scale") + parser.add_argument("--camera-name", default="video_camera", help="Camera object name") + parser.add_argument("--max-frames", type=int, default=-1, help="Optional max rendered frames") + parser.add_argument( + "--hdr", + default="", + help=( + "Optional EXR/HDR environment map for world lighting. " + "When set, camera background stays at --bg-gray while lighting/reflections use this map." + ), + ) + parser.add_argument("--world-strength", type=float, default=1.0, help="World background strength") + parser.add_argument("--sun-energy", type=float, default=2.5, help="Sun light energy") + parser.add_argument("--bg-gray", type=float, default=0.35, help="Background gray level in [0,1]") + parser.add_argument( + "--camera-headlight", + action="store_true", + help="Attach a camera-mounted light pointing along camera viewing direction.", + ) + parser.add_argument( + "--camera-headlight-energy", + type=float, + default=8.0, + help="Energy for --camera-headlight.", + ) + parser.add_argument( + "--camera-headlight-type", + default="sun", + choices=("spot", "point", "sun"), + help="Light type for --camera-headlight.", + ) + parser.add_argument( + "--camera-headlight-angle", + type=float, + default=55.0, + help="Spot cone angle in degrees for --camera-headlight.", + ) + parser.add_argument( + "--dark-texture-fallback-ref", + action="store_true", + help=( + "For rigid/static objects, if the detected albedo texture is too dark, " + "prefer auto-brighten on the original UV texture and fallback to " + "objects//mid_files/ref_img.png only when texture is missing/unreadable." + ), + ) + parser.add_argument( + "--dark-texture-thresh", + type=float, + default=40.0, + help="Brightness threshold (p99, [0,255]) for --dark-texture-fallback-ref.", + ) + parser.add_argument( + "--dark-texture-target-p99", + type=float, + default=110.0, + help="Target p99 brightness ([0,255]) when auto-brightening dark textures.", + ) + parser.add_argument( + "--dark-texture-max-gain", + type=float, + default=8.0, + help="Maximum multiplicative gain for dark texture auto-brightening.", + ) + parser.add_argument( + "--unlit-texture", + action="store_true", + help="Use unlit emission material for textured meshes (disable PBR shading).", + ) + parser.add_argument( + "--unlit-emission-strength", + type=float, + default=1.0, + help="Emission strength for --unlit-texture.", + ) + return parser.parse_args(sys.argv[sys.argv.index("--") + 1 :]) + + +def _parse_frame_id(path: Path) -> Optional[int]: + stem = path.stem + m = re.search(r"(\d+)$", stem) + if m: + return int(m.group(1)) + m = re.search(r"(\d+)", stem) + if m: + return int(m.group(1)) + return None + + +def _nearest_key(target: int, keys: List[int]) -> int: + return min(keys, key=lambda x: abs(x - target)) + + +def _safe_name(name: str) -> str: + return "".join(c if c.isalnum() or c in ("-", "_") else "_" for c in name) + + +def _resolve_obj_index(idx: int, count: int) -> int: + return (idx - 1) if idx > 0 else (count + idx) + + +def _load_obj_mesh(path: Path) -> Tuple[np.ndarray, np.ndarray, Optional[np.ndarray]]: + verts_raw: List[Tuple[float, float, float]] = [] + vts_raw: List[Tuple[float, float]] = [] + faces_split: List[Tuple[int, int, int]] = [] + split_verts: List[Tuple[float, float, float]] = [] + split_uvs: List[Optional[Tuple[float, float]]] = [] + pair_to_split: Dict[Tuple[int, int], int] = {} + + lines = path.read_text(encoding="utf-8", errors="ignore").splitlines() + for ln, line in enumerate(lines, start=1): + s = line.strip() + if not s or s.startswith("#"): + continue + if s.startswith("v "): + toks = s.split() + if len(toks) < 4: + continue + verts_raw.append((float(toks[1]), float(toks[2]), float(toks[3]))) + continue + if s.startswith("vt "): + toks = s.split() + if len(toks) < 3: + continue + vts_raw.append((float(toks[1]), float(toks[2]))) + continue + if not s.startswith("f "): + continue + + corners: List[Tuple[int, int]] = [] + for tok in s.split()[1:]: + parts = tok.split("/") + if not parts[0]: + continue + vi = _resolve_obj_index(int(parts[0]), len(verts_raw)) + if vi < 0 or vi >= len(verts_raw): + raise RuntimeError(f"Invalid vertex index in {path}:{ln}") + + vti = -1 + if len(parts) >= 2 and parts[1]: + vti = _resolve_obj_index(int(parts[1]), len(vts_raw)) + if vti < 0 or vti >= len(vts_raw): + raise RuntimeError(f"Invalid texcoord index in {path}:{ln}") + corners.append((vi, vti)) + + if len(corners) < 3: + continue + for i in range(1, len(corners) - 1): + tri = (corners[0], corners[i], corners[i + 1]) + tri_split: List[int] = [] + for vi, vti in tri: + key = (vi, vti) + split_idx = pair_to_split.get(key) + if split_idx is None: + split_idx = len(split_verts) + pair_to_split[key] = split_idx + split_verts.append(verts_raw[vi]) + split_uvs.append(vts_raw[vti] if vti >= 0 else None) + tri_split.append(split_idx) + faces_split.append((tri_split[0], tri_split[1], tri_split[2])) + + if not split_verts or not faces_split: + raise RuntimeError(f"Invalid/empty OBJ mesh: {path}") + + verts = np.asarray(split_verts, dtype=np.float32) + faces = np.asarray(faces_split, dtype=np.int64) + if any(uv is not None for uv in split_uvs): + uv_arr = np.zeros((len(split_uvs), 2), dtype=np.float32) + for i, uv in enumerate(split_uvs): + if uv is not None: + uv_arr[i, 0] = float(uv[0]) + uv_arr[i, 1] = float(uv[1]) + return verts, faces, uv_arr + return verts, faces, None + + +def _pick_mesh_path(obj_dir: Path) -> Path: + candidates: List[Path] = [] + candidates.append(obj_dir / "mid_files" / "scaled_mesh.obj") + candidates.extend(sorted((obj_dir / "model" / "middle_file").glob("*_high_mesh.obj"))) + candidates.append(obj_dir / "model" / "model.obj") + for p in candidates: + if p.exists(): + return p + raise FileNotFoundError(f"No mesh found in {obj_dir}") + + +def _pick_pose_json(obj_dir: Path, category: str, pose_name: str, use_locked_static: bool) -> Path: + pose_dir = obj_dir / "pose_result" + if pose_name: + preferred = pose_dir / pose_name + if preferred.exists(): + return preferred + if use_locked_static and category == "static": + locked = pose_dir / "poses_locked.json" + if locked.exists(): + return locked + default = pose_dir / "poses.json" + if default.exists(): + return default + locked = pose_dir / "poses_locked.json" + if locked.exists(): + return locked + raise FileNotFoundError(f"No pose json found under {pose_dir}") + + +def _load_pose_map(path: Path) -> Dict[int, np.ndarray]: + payload = json.loads(path.read_text(encoding="utf-8")) + out: Dict[int, np.ndarray] = {} + for k, v in payload.items(): + try: + fid = int(k) + except Exception: + continue + arr = np.asarray(v, dtype=np.float32) + if arr.shape != (4, 4): + continue + out[fid] = arr + if not out: + raise ValueError(f"No valid poses in {path}") + return out + + +def _load_alignment(path_str: str) -> np.ndarray: + if not path_str: + return np.eye(4, dtype=np.float32) + path = Path(path_str).resolve() + if not path.exists(): + raise FileNotFoundError(path) + payload = json.loads(path.read_text(encoding="utf-8")) + T = np.asarray(payload.get("T"), dtype=np.float32) + if T.shape != (4, 4): + raise ValueError(f"Alignment T must be 4x4, got {T.shape}") + return T + + +def _find_obj_texture(mesh_path: Path) -> Optional[Path]: + try: + lines = mesh_path.read_text(encoding="utf-8", errors="ignore").splitlines() + except Exception: + return None + + mtl_files: List[Path] = [] + for line in lines: + s = line.strip() + if not s or s.startswith("#"): + continue + if s.lower().startswith("mtllib "): + rel = s.split(None, 1)[1].strip() + p = (mesh_path.parent / rel).resolve() + if p.exists(): + mtl_files.append(p) + + for mtl in mtl_files: + try: + mtl_lines = mtl.read_text(encoding="utf-8", errors="ignore").splitlines() + except Exception: + continue + for line in mtl_lines: + s = line.strip() + if not s or s.startswith("#"): + continue + if not s.lower().startswith("map_kd "): + continue + try: + toks = shlex.split(s, comments=False, posix=True) + except Exception: + toks = s.split() + if len(toks) < 2: + continue + tex = (mtl.parent / toks[-1]).resolve() + if tex.exists(): + return tex + return None + + +def _resolve_hunyuan_dir(obj_payload: dict) -> Optional[Path]: + processed_dir = str(obj_payload.get("processed_dir", "")).strip() + if processed_dir: + p = Path(processed_dir).resolve() / "Hunyuan_Gen_Input" + if p.exists(): + return p + + ref_mesh = str(obj_payload.get("ref_mesh", "")).strip() + if ref_mesh: + p = Path(ref_mesh).resolve().parent + if p.exists(): + return p + return None + + +def _pick_deform_uv_template_from_source(obj_payload: dict) -> Optional[Path]: + hdir = _resolve_hunyuan_dir(obj_payload) + if hdir is None: + return None + candidates = [ + hdir / "000000_hunyuan_original_wo_remap_converted.obj", + hdir / "000000_hunyuan_original_wo_remap.obj", + hdir / "000000_hunyuan_original_watertight.obj", + ] + for p in candidates: + if p.exists(): + return p.resolve() + converted = sorted(hdir.glob("*converted.obj")) + if converted: + return converted[0].resolve() + any_objs = sorted(hdir.glob("*.obj")) + if any_objs: + return any_objs[0].resolve() + return None + + +def _pick_deform_texture_from_source(obj_payload: dict) -> Optional[Path]: + hdir = _resolve_hunyuan_dir(obj_payload) + if hdir is None: + return None + for p in [hdir / "material_0.png", hdir / "material.png"]: + if p.exists(): + return p.resolve() + return None + + +def _load_rgb_255(path: Path) -> Optional[np.ndarray]: + try: + from PIL import Image # type: ignore + return np.asarray(Image.open(path).convert("RGB"), dtype=np.float32) + except Exception: + pass + + try: + img = bpy.data.images.load(str(path), check_existing=True) + px = np.asarray(img.pixels[:], dtype=np.float32) + if px.size < 4: + return None + rgba = px.reshape(-1, 4) + return rgba[:, :3] * 255.0 + except Exception: + return None + + +def _texture_luma_p99(path: Path) -> Optional[float]: + rgb255 = _load_rgb_255(path) + if rgb255 is None or rgb255.size == 0: + return None + lum = 0.2126 * rgb255[..., 0] + 0.7152 * rgb255[..., 1] + 0.0722 * rgb255[..., 2] + return float(np.percentile(lum, 99.0)) + + +def _texture_is_too_dark(path: Path, p99_thresh: float) -> bool: + p99 = _texture_luma_p99(path) + return p99 is not None and p99 < float(p99_thresh) + + +def _texture_dark_gain(path: Path, p99_thresh: float, target_p99: float, max_gain: float) -> Tuple[Optional[float], float]: + p99 = _texture_luma_p99(path) + if p99 is None: + return None, 1.0 + if p99 >= float(p99_thresh): + return p99, 1.0 + safe_p99 = max(1.0, float(p99)) + gain = float(target_p99) / safe_p99 + gain = float(np.clip(gain, 1.0, float(max_gain))) + return p99, gain + + +def _load_obj_uv_split_template( + template_obj: Path, +) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int]: + lines = template_obj.read_text(encoding="utf-8", errors="ignore").splitlines() + + vt_list: List[Tuple[float, float]] = [] + num_v = 0 + pair_to_split: Dict[Tuple[int, int], int] = {} + split_to_orig_v: List[int] = [] + uv_split: List[Tuple[float, float]] = [] + faces_split: List[List[int]] = [] + faces_orig_v: List[List[int]] = [] + + for ln, line in enumerate(lines, start=1): + s = line.strip() + if not s or s.startswith("#"): + continue + if s.startswith("v "): + num_v += 1 + continue + if s.startswith("vt "): + toks = s.split() + if len(toks) < 3: + raise RuntimeError(f"Invalid vt line at {template_obj}:{ln}") + u = float(toks[1]) + v = float(toks[2]) + vt_list.append((u, v)) + continue + if not s.startswith("f "): + continue + + corners: List[Tuple[int, int]] = [] + for tok in s.split()[1:]: + parts = tok.split("/") + if len(parts) < 2 or not parts[0] or not parts[1]: + raise RuntimeError(f"Template OBJ must contain v/vt faces: {template_obj}:{ln}") + v_idx = _resolve_obj_index(int(parts[0]), num_v) + vt_idx = _resolve_obj_index(int(parts[1]), len(vt_list)) + if v_idx < 0 or v_idx >= num_v: + raise RuntimeError(f"Invalid vertex index at {template_obj}:{ln}") + if vt_idx < 0 or vt_idx >= len(vt_list): + raise RuntimeError(f"Invalid texcoord index at {template_obj}:{ln}") + corners.append((v_idx, vt_idx)) + + if len(corners) < 3: + continue + for i in range(1, len(corners) - 1): + tri = (corners[0], corners[i], corners[i + 1]) + tri_split: List[int] = [] + tri_orig: List[int] = [] + for v_idx, vt_idx in tri: + key = (v_idx, vt_idx) + split_idx = pair_to_split.get(key) + if split_idx is None: + split_idx = len(split_to_orig_v) + pair_to_split[key] = split_idx + split_to_orig_v.append(v_idx) + uv_split.append(vt_list[vt_idx]) + tri_split.append(split_idx) + tri_orig.append(v_idx) + faces_split.append(tri_split) + faces_orig_v.append(tri_orig) + + if not faces_split or not split_to_orig_v: + raise RuntimeError(f"Failed to build UV split template from {template_obj}") + + uv_split_arr = np.asarray(uv_split, dtype=np.float32) + return ( + np.asarray(faces_split, dtype=np.int64), + uv_split_arr, + np.asarray(split_to_orig_v, dtype=np.int64), + np.asarray(faces_orig_v, dtype=np.int64), + int(num_v), + ) + + +def _load_obj_vertices_and_faces_only(path: Path) -> Tuple[np.ndarray, np.ndarray]: + verts: List[Tuple[float, float, float]] = [] + faces: List[Tuple[int, int, int]] = [] + lines = path.read_text(encoding="utf-8", errors="ignore").splitlines() + for ln, line in enumerate(lines, start=1): + s = line.strip() + if not s or s.startswith("#"): + continue + if s.startswith("v "): + toks = s.split() + if len(toks) < 4: + continue + verts.append((float(toks[1]), float(toks[2]), float(toks[3]))) + continue + if not s.startswith("f "): + continue + corners: List[int] = [] + for tok in s.split()[1:]: + parts = tok.split("/") + if not parts[0]: + continue + vi = _resolve_obj_index(int(parts[0]), len(verts)) + if vi < 0 or vi >= len(verts): + raise RuntimeError(f"Invalid vertex index in {path}:{ln}") + corners.append(vi) + if len(corners) < 3: + continue + for i in range(1, len(corners) - 1): + faces.append((corners[0], corners[i], corners[i + 1])) + if not verts or not faces: + raise RuntimeError(f"Invalid/empty OBJ mesh: {path}") + return np.asarray(verts, dtype=np.float32), np.asarray(faces, dtype=np.int64) + + +def _load_deform_mesh_map(mesh_dir: Path) -> Dict[int, Path]: + out: Dict[int, Path] = {} + for p in sorted(mesh_dir.glob("frame_*.obj")): + fid = _parse_frame_id(p) + if fid is None: + continue + out[fid] = p + return out + + +def _cv_to_scene_matrix(coord: str) -> np.ndarray: + if coord == "raw": + return np.eye(4, dtype=np.float32) + if coord == "opengl": + return np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float32) + if coord == "blender": + rot_x_neg_90 = np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + flip_x = np.diag([-1.0, 1.0, 1.0, 1.0]).astype(np.float32) + return flip_x @ (rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32)) + if coord == "blender_noflip": + rot_x_neg_90 = np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + if coord == "blender_zup": + return np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + return np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + + +def _world_conv_matrix(name: str) -> np.ndarray: + if name == "identity": + return np.eye(4, dtype=np.float32) + if name == "rx90": + return np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + + +def _camera_axis_matrix(name: str) -> np.ndarray: + if name == "identity": + return np.eye(4, dtype=np.float32) + if name == "flip_xy": + return np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + if name == "standard": + return np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float32) + if name == "yz_swap": + return np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return np.array( + [ + [-1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + + +def _set_engine(scene: bpy.types.Scene, engine_name: str) -> None: + enum_items = scene.render.bl_rna.properties["engine"].enum_items + valid = {item.identifier for item in enum_items} + if engine_name in valid: + scene.render.engine = engine_name + return + if "BLENDER_EEVEE_NEXT" in valid: + scene.render.engine = "BLENDER_EEVEE_NEXT" + return + if "BLENDER_EEVEE" in valid: + scene.render.engine = "BLENDER_EEVEE" + return + + +def _set_color_management(scene: bpy.types.Scene) -> None: + try: + view_items = scene.view_settings.bl_rna.properties["view_transform"].enum_items + valid = {item.identifier for item in view_items} + if "Standard" in valid: + scene.view_settings.view_transform = "Standard" + except Exception: + pass + scene.view_settings.exposure = 0.0 + scene.view_settings.gamma = 1.0 + + +def _set_world(scene: bpy.types.Scene, gray: float, strength: float, hdr_path: Optional[Path] = None) -> None: + world = scene.world + if world is None: + world = bpy.data.worlds.new("World") + scene.world = world + world.use_nodes = True + nt = world.node_tree + if nt is None: + return + nodes = nt.nodes + links = nt.links + nodes.clear() + + g = float(np.clip(gray, 0.0, 1.0)) + strength = float(max(0.0, strength)) + + if hdr_path is not None: + light_path = nodes.new("ShaderNodeLightPath") + env_tex = nodes.new("ShaderNodeTexEnvironment") + bg_env = nodes.new("ShaderNodeBackground") + bg_cam = nodes.new("ShaderNodeBackground") + mix_shader = nodes.new("ShaderNodeMixShader") + world_out = nodes.new("ShaderNodeOutputWorld") + + light_path.location = (-820.0, -140.0) + env_tex.location = (-820.0, 120.0) + bg_env.location = (-520.0, 120.0) + bg_cam.location = (-520.0, -120.0) + mix_shader.location = (-240.0, 0.0) + world_out.location = (40.0, 0.0) + + env_tex.image = bpy.data.images.load(str(hdr_path), check_existing=True) + bg_env.inputs["Strength"].default_value = strength + bg_cam.inputs["Color"].default_value = (g, g, g, 1.0) + bg_cam.inputs["Strength"].default_value = strength + + links.new(env_tex.outputs["Color"], bg_env.inputs["Color"]) + links.new(light_path.outputs["Is Camera Ray"], mix_shader.inputs["Fac"]) + links.new(bg_env.outputs["Background"], mix_shader.inputs[1]) + links.new(bg_cam.outputs["Background"], mix_shader.inputs[2]) + links.new(mix_shader.outputs["Shader"], world_out.inputs["Surface"]) + return + + bg = nodes.new("ShaderNodeBackground") + world_out = nodes.new("ShaderNodeOutputWorld") + bg.location = (-240.0, 0.0) + world_out.location = (40.0, 0.0) + bg.inputs["Color"].default_value = (g, g, g, 1.0) + bg.inputs["Strength"].default_value = strength + links.new(bg.outputs["Background"], world_out.inputs["Surface"]) + + +def _set_basic_lighting(scene: bpy.types.Scene, sun_energy: float) -> None: + has_light = any(obj.type == "LIGHT" for obj in scene.objects) + if has_light: + return + light_data = bpy.data.lights.new(name="Sun", type="SUN") + light_data.energy = float(sun_energy) + light_obj = bpy.data.objects.new(name="Sun", object_data=light_data) + scene.collection.objects.link(light_obj) + light_obj.rotation_euler = (math.radians(55.0), 0.0, math.radians(25.0)) + + +def _attach_camera_headlight( + scene: bpy.types.Scene, + cam_obj: bpy.types.Object, + energy: float, + angle_deg: float, + light_type: str, +) -> bpy.types.Object: + kind = str(light_type).lower() + if kind == "spot": + light_kind = "SPOT" + elif kind == "sun": + light_kind = "SUN" + else: + light_kind = "POINT" + light_data = bpy.data.lights.new(name="CameraHeadlight", type=light_kind) + light_data.energy = float(max(0.0, energy)) + if light_kind == "SPOT": + light_data.spot_size = math.radians(float(np.clip(angle_deg, 1.0, 179.0))) + light_data.spot_blend = 0.2 + if hasattr(light_data, "shadow_soft_size"): + light_data.shadow_soft_size = 0.08 + light_data.use_shadow = False + light_obj = bpy.data.objects.new(name="CameraHeadlight", object_data=light_data) + scene.collection.objects.link(light_obj) + light_obj.parent = cam_obj + light_obj.location = (0.0, 0.0, 0.0) + light_obj.rotation_euler = (0.0, 0.0, 0.0) + return light_obj + + +def _apply_intrinsics_to_camera( + cam_data: bpy.types.Camera, + K: np.ndarray, + width: int, + height: int, +) -> None: + fx = float(K[0, 0]) + fy = float(K[1, 1]) + cx = float(K[0, 2]) + cy = float(K[1, 2]) + W = max(1.0, float(width)) + H = max(1.0, float(height)) + + cam_data.type = "PERSP" + cam_data.sensor_fit = "HORIZONTAL" + cam_data.sensor_width = 36.0 + cam_data.lens = fx * cam_data.sensor_width / W + cam_data.sensor_height = max(1e-6, cam_data.lens * H / max(1e-6, fy)) + cam_data.shift_x = -(cx - 0.5 * W) / W + cam_data.shift_y = (cy - 0.5 * H) / H + + +def _build_textured_material( + texture_path: Path, + mat_cache: Dict[str, bpy.types.Material], + color_gain: float = 1.0, + use_unlit: bool = False, + emission_strength: float = 1.0, +) -> bpy.types.Material: + gain = max(1.0, float(color_gain)) + key = ( + f"{texture_path.resolve()}|gain={gain:.3f}|" + f"unlit={int(bool(use_unlit))}|emit={float(emission_strength):.3f}" + ) + mat = mat_cache.get(key) + if mat is not None: + return mat + + tex_id = hashlib.sha1(key.encode("utf-8")).hexdigest()[:10] + mat_name = f"Tex_{_safe_name(texture_path.stem)}_{tex_id}" + mat = bpy.data.materials.get(mat_name) + if mat is None: + mat = bpy.data.materials.new(name=mat_name) + mat.use_nodes = True + nt = mat.node_tree + if nt is None: + mat_cache[key] = mat + return mat + nt.nodes.clear() + n_out = nt.nodes.new("ShaderNodeOutputMaterial") + n_tex = nt.nodes.new("ShaderNodeTexImage") + img = bpy.data.images.load(str(texture_path), check_existing=True) + n_tex.image = img + color_socket = n_tex.outputs["Color"] + if gain > 1.001: + n_hsv = nt.nodes.new("ShaderNodeHueSaturation") + n_hsv.inputs["Value"].default_value = gain + nt.links.new(n_tex.outputs["Color"], n_hsv.inputs["Color"]) + color_socket = n_hsv.outputs["Color"] + if use_unlit: + n_em = nt.nodes.new("ShaderNodeEmission") + n_em.inputs["Strength"].default_value = float(max(0.0, emission_strength)) + nt.links.new(color_socket, n_em.inputs["Color"]) + nt.links.new(n_em.outputs["Emission"], n_out.inputs["Surface"]) + else: + n_bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled") + nt.links.new(color_socket, n_bsdf.inputs["Base Color"]) + nt.links.new(n_bsdf.outputs["BSDF"], n_out.inputs["Surface"]) + mat_cache[key] = mat + return mat + + +def _build_mesh_object( + name: str, + verts: np.ndarray, + faces: np.ndarray, + uv_arr: Optional[np.ndarray], + texture_path: Optional[Path], + texture_gain: float, + mat_cache: Dict[str, bpy.types.Material], + use_unlit: bool, + emission_strength: float, +) -> bpy.types.Object: + mesh_data = bpy.data.meshes.new(_safe_name(name)) + mesh_data.from_pydata(verts.tolist(), [], faces.tolist()) + mesh_data.update() + if len(mesh_data.polygons) > 0: + for poly in mesh_data.polygons: + poly.use_smooth = True + + if uv_arr is not None and uv_arr.ndim == 2 and uv_arr.shape[0] == verts.shape[0] and uv_arr.shape[1] >= 2: + uv_layer = mesh_data.uv_layers.new(name="UVMap") + for li, loop in enumerate(mesh_data.loops): + vi = int(loop.vertex_index) + uv_layer.data[li].uv = (float(uv_arr[vi, 0]), float(uv_arr[vi, 1])) + + obj = bpy.data.objects.new(_safe_name(name), mesh_data) + if texture_path is not None and texture_path.exists(): + mat = _build_textured_material( + texture_path, + mat_cache=mat_cache, + color_gain=float(texture_gain), + use_unlit=bool(use_unlit), + emission_strength=float(emission_strength), + ) + if len(mesh_data.materials) == 0: + mesh_data.materials.append(mat) + else: + for i in range(len(mesh_data.materials)): + mesh_data.materials[i] = mat + return obj + + +def _transform_points(T: np.ndarray, verts: np.ndarray) -> np.ndarray: + ones = np.ones((verts.shape[0], 1), dtype=np.float32) + verts_h = np.concatenate([verts, ones], axis=1) + return (T @ verts_h.T).T[:, :3] + + +def _update_bbox(bbox_min: np.ndarray, bbox_max: np.ndarray, verts: np.ndarray) -> None: + if verts.size <= 0: + return + bbox_min[:] = np.minimum(bbox_min, np.min(verts, axis=0)) + bbox_max[:] = np.maximum(bbox_max, np.max(verts, axis=0)) + + +def _build_flat_material( + mat_cache: Dict[str, bpy.types.Material], + gray: float, +) -> bpy.types.Material: + g = float(np.clip(gray, 0.0, 1.0)) + key = f"flat_gray|{g:.3f}" + mat = mat_cache.get(key) + if mat is not None: + return mat + + mat_name = f"FlatGray_{int(round(g * 1000.0)):03d}" + mat = bpy.data.materials.get(mat_name) + if mat is None: + mat = bpy.data.materials.new(name=mat_name) + mat.use_nodes = True + nt = mat.node_tree + if nt is None: + mat_cache[key] = mat + return mat + nt.nodes.clear() + n_out = nt.nodes.new("ShaderNodeOutputMaterial") + n_bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled") + n_bsdf.inputs["Base Color"].default_value = (g, g, g, 1.0) + n_bsdf.inputs["Roughness"].default_value = 0.95 + if "Specular IOR Level" in n_bsdf.inputs: + n_bsdf.inputs["Specular IOR Level"].default_value = 0.0 + elif "Specular" in n_bsdf.inputs: + n_bsdf.inputs["Specular"].default_value = 0.0 + nt.links.new(n_bsdf.outputs["BSDF"], n_out.inputs["Surface"]) + mat_cache[key] = mat + return mat + + +def _add_visual_plane( + scene: bpy.types.Scene, + bbox_min: np.ndarray, + bbox_max: np.ndarray, + mat_cache: Dict[str, bpy.types.Material], + plane_scale: float, + plane_gray: float, +) -> None: + if not np.isfinite(bbox_min).all() or not np.isfinite(bbox_max).all(): + return + extent = bbox_max - bbox_min + max_extent = float(max(extent[0], extent[1], 1.0e-2)) + half = max_extent * max(float(plane_scale), 0.2) * 0.5 + cx = float(0.5 * (bbox_min[0] + bbox_max[0])) + cy = float(0.5 * (bbox_min[1] + bbox_max[1])) + plane_z = float(-max(1.0e-4, 1.0e-3 * max_extent)) + verts = np.asarray( + [ + [cx - half, cy - half, plane_z], + [cx + half, cy - half, plane_z], + [cx + half, cy + half, plane_z], + [cx - half, cy + half, plane_z], + ], + dtype=np.float32, + ) + faces = np.asarray([[0, 1, 2], [0, 2, 3]], dtype=np.int64) + mesh_data = bpy.data.meshes.new("table_plane") + mesh_data.from_pydata(verts.tolist(), [], faces.tolist()) + mesh_data.update() + mat = _build_flat_material(mat_cache, gray=plane_gray) + mesh_data.materials.append(mat) + obj = bpy.data.objects.new("table_plane", mesh_data) + scene.collection.objects.link(obj) + + +def main() -> None: + args = parse_args() + + run_dir = Path(args.run_dir).resolve() + config_path = Path(args.config).resolve() + result_npz = Path(args.result_npz).resolve() + output_video = Path(args.output_video).resolve() + output_rgba_dir = Path(args.output_rgba_dir).resolve() if args.output_rgba_dir else None + deform_root = Path(args.deform_root).resolve() if args.deform_root else None + deform_manifest = Path(args.deform_manifest).resolve() if args.deform_manifest else None + + if not run_dir.exists(): + raise FileNotFoundError(run_dir) + if not config_path.exists(): + raise FileNotFoundError(config_path) + if not result_npz.exists(): + raise FileNotFoundError(result_npz) + + cfg = json.loads(config_path.read_text(encoding="utf-8")) + categories = {o["name"]: str(o.get("category", "")).lower() for o in cfg.get("objects", [])} + + data = np.load(result_npz) + extrinsics = np.asarray(data["extrinsics"], dtype=np.float32) + intrinsics = np.asarray(data["intrinsics"], dtype=np.float32) + if extrinsics.ndim != 3 or extrinsics.shape[1:] != (4, 4): + raise ValueError(f"Invalid extrinsics shape: {extrinsics.shape}") + if intrinsics.ndim != 3 or intrinsics.shape[1:] != (3, 3): + raise ValueError(f"Invalid intrinsics shape: {intrinsics.shape}") + num_frames = int(extrinsics.shape[0]) + if int(args.max_frames) > 0: + num_frames = min(num_frames, int(args.max_frames)) + + if "video" in data: + video_arr = data["video"] + if video_arr.ndim == 4 and video_arr.shape[1] in (1, 3, 4): + height, width = int(video_arr.shape[2]), int(video_arr.shape[3]) + elif video_arr.ndim == 4: + height, width = int(video_arr.shape[1]), int(video_arr.shape[2]) + else: + raise ValueError(f"Invalid video shape: {video_arr.shape}") + elif "depths" in data: + dep = data["depths"] + if dep.ndim != 3: + raise ValueError(f"Invalid depths shape: {dep.shape}") + height, width = int(dep.shape[1]), int(dep.shape[2]) + else: + raise KeyError("result.npz missing both 'video' and 'depths'") + + bpy.ops.wm.read_factory_settings(use_empty=True) + scene = bpy.context.scene + fps = float(args.fps) + if fps <= 0: + raise ValueError("fps must be > 0") + scene.render.fps = int(round(fps)) + scene.render.fps_base = float(scene.render.fps) / fps + _set_engine(scene, args.engine) + _set_color_management(scene) + hdr_path = None + if str(args.hdr).strip(): + hdr_path = Path(str(args.hdr)).expanduser().resolve() + if not hdr_path.exists(): + raise FileNotFoundError(hdr_path) + _set_world(scene, gray=float(args.bg_gray), strength=float(args.world_strength), hdr_path=hdr_path) + scene.render.film_transparent = bool(args.transparent_bg) + _set_basic_lighting(scene, sun_energy=float(args.sun_energy)) + + align_T = _load_alignment(args.alignment) + cv_to_scene = _cv_to_scene_matrix(args.coord) + world_conv = _world_conv_matrix(args.world_conv) + cv_cam_to_bl_cam = _camera_axis_matrix(args.camera_axis) + scene_from_cv_aligned = cv_to_scene @ world_conv @ align_T + + mat_cache: Dict[str, bpy.types.Material] = {} + bbox_min_scene = np.full(3, np.inf, dtype=np.float32) + bbox_max_scene = np.full(3, -np.inf, dtype=np.float32) + + rigid_objects: List[Dict[str, object]] = [] + objects_root = run_dir / "objects" + if objects_root.exists(): + for obj_dir in sorted([d for d in objects_root.iterdir() if d.is_dir()]): + name = obj_dir.name + category = categories.get(name, "") + if category == "deform": + continue + try: + mesh_path = _pick_mesh_path(obj_dir) + pose_json = _pick_pose_json( + obj_dir, + category=category, + pose_name=str(args.pose_name), + use_locked_static=bool(args.use_locked_static), + ) + except Exception as exc: + print(f"[Warn] Skip rigid/static {name}: {exc}") + continue + + try: + verts, faces, uv_arr = _load_obj_mesh(mesh_path) + except Exception as exc: + print(f"[Warn] Skip rigid/static {name}: mesh parse failed: {exc}") + continue + tex_path = _find_obj_texture(mesh_path) + tex_gain = 1.0 + if args.dark_texture_fallback_ref: + ref_img = obj_dir / "mid_files" / "ref_img.png" + if tex_path is not None and tex_path.exists(): + p99, gain = _texture_dark_gain( + tex_path, + p99_thresh=float(args.dark_texture_thresh), + target_p99=float(args.dark_texture_target_p99), + max_gain=float(args.dark_texture_max_gain), + ) + if gain > 1.001: + tex_gain = gain + p99_str = f"{p99:.2f}" if p99 is not None else "n/a" + print(f"[Info] rigid/static {name}: dark texture p99={p99_str}, apply gain x{gain:.2f} on {tex_path}") + elif ref_img.exists(): + prev = str(tex_path) if tex_path is not None else "" + tex_path = ref_img.resolve() + print(f"[Info] rigid/static {name}: fallback missing texture {prev} -> {tex_path}") + obj = _build_mesh_object( + name=name, + verts=verts, + faces=faces, + uv_arr=uv_arr, + texture_path=tex_path, + texture_gain=tex_gain, + mat_cache=mat_cache, + use_unlit=bool(args.unlit_texture), + emission_strength=float(args.unlit_emission_strength), + ) + scene.collection.objects.link(obj) + obj.rotation_mode = "QUATERNION" + + pose_map = _load_pose_map(pose_json) + pose_ids = sorted(pose_map.keys()) + if pose_ids: + pf0 = 0 if 0 in pose_map else _nearest_key(0, pose_ids) + c_T_o0 = pose_map[pf0] + w_T_o0 = np.linalg.inv(extrinsics[0]).astype(np.float32) @ c_T_o0 + scene_T_o0 = scene_from_cv_aligned @ w_T_o0 + _update_bbox(bbox_min_scene, bbox_max_scene, _transform_points(scene_T_o0, verts)) + rigid_objects.append( + { + "name": name, + "obj": obj, + "pose_map": pose_map, + "pose_ids": pose_ids, + } + ) + + deform_objects: List[Dict[str, object]] = [] + manifest_path: Optional[Path] = None + if deform_root is not None: + if deform_manifest is not None: + manifest_path = deform_manifest + else: + manifest_path = deform_root / run_dir.name / "manifest.json" + if manifest_path is not None and manifest_path.exists(): + payload = json.loads(manifest_path.read_text(encoding="utf-8")) + for obj_payload in payload.get("objects", []): + name = str(obj_payload.get("name", "")).strip() + if not name: + continue + if deform_root is None: + continue + frames_dir = deform_root / run_dir.name / name / str(args.deform_frames_dir) + fallback_dir = deform_root / run_dir.name / name / "world_mesh_frames" + if not frames_dir.exists(): + if str(args.deform_frames_dir) == "world_mesh_frames_physics" and fallback_dir.exists(): + print( + f"[Warn] Deform {name}: missing physics frames {frames_dir}, " + f"fallback to {fallback_dir}" + ) + frames_dir = fallback_dir + else: + print(f"[Warn] Skip deform {name}: missing {frames_dir}") + continue + mesh_map = _load_deform_mesh_map(frames_dir) + if not mesh_map: + if ( + str(args.deform_frames_dir) == "world_mesh_frames_physics" + and frames_dir != fallback_dir + and fallback_dir.exists() + ): + print( + f"[Warn] Deform {name}: empty physics frames in {frames_dir}, " + f"fallback to {fallback_dir}" + ) + frames_dir = fallback_dir + mesh_map = _load_deform_mesh_map(frames_dir) + if not mesh_map: + print(f"[Warn] Skip deform {name}: empty frames in {frames_dir}") + continue + tex_override = _pick_deform_texture_from_source(obj_payload) + uv_template_obj = _pick_deform_uv_template_from_source(obj_payload) + template_faces_split: Optional[np.ndarray] = None + template_uv_split: Optional[np.ndarray] = None + template_split_to_orig_v: Optional[np.ndarray] = None + template_faces_orig_v: Optional[np.ndarray] = None + template_orig_v_count: Optional[int] = None + if uv_template_obj is not None: + try: + ( + template_faces_split, + template_uv_split, + template_split_to_orig_v, + template_faces_orig_v, + template_orig_v_count, + ) = _load_obj_uv_split_template(uv_template_obj) + print( + f"[Info] Deform {name}: use UV split template {uv_template_obj} " + f"(orig_v={template_orig_v_count}, split_v={template_uv_split.shape[0]})" + ) + except Exception as exc: + print(f"[Warn] Deform {name}: UV template parse failed, fallback to frame UVs: {exc}") + template_faces_split = None + template_uv_split = None + template_split_to_orig_v = None + template_faces_orig_v = None + template_orig_v_count = None + obj_by_fid: Dict[int, bpy.types.Object] = {} + for fid in sorted(mesh_map.keys()): + mesh_path = mesh_map[fid] + try: + if ( + template_faces_split is not None + and template_uv_split is not None + and template_split_to_orig_v is not None + and template_faces_orig_v is not None + and template_orig_v_count is not None + ): + verts_raw, faces_raw = _load_obj_vertices_and_faces_only(mesh_path) + if verts_raw.shape[0] != template_orig_v_count: + raise RuntimeError( + f"vertex count mismatch: frame={verts_raw.shape[0]} template={template_orig_v_count}" + ) + if ( + faces_raw.shape != template_faces_orig_v.shape + or not np.array_equal(faces_raw, template_faces_orig_v) + ): + raise RuntimeError("face topology mismatch with UV template") + verts = verts_raw[template_split_to_orig_v] + faces = template_faces_split + uv_arr = template_uv_split + else: + verts, faces, uv_arr = _load_obj_mesh(mesh_path) + except Exception as exc: + print(f"[Warn] Skip deform frame {name}:{fid}: {exc}") + continue + tex_path = tex_override if tex_override is not None else _find_obj_texture(mesh_path) + obj = _build_mesh_object( + name=f"{name}_frame_{fid:06d}", + verts=verts, + faces=faces, + uv_arr=uv_arr, + texture_path=tex_path, + texture_gain=1.0, + mat_cache=mat_cache, + use_unlit=bool(args.unlit_texture), + emission_strength=float(args.unlit_emission_strength), + ) + scene.collection.objects.link(obj) + obj.matrix_world = Matrix(scene_from_cv_aligned.tolist()) + if fid == min(mesh_map.keys()): + _update_bbox(bbox_min_scene, bbox_max_scene, _transform_points(scene_from_cv_aligned, verts)) + obj_by_fid[fid] = obj + if not obj_by_fid: + print(f"[Warn] Skip deform {name}: no valid frames after OBJ parse.") + continue + deform_objects.append( + { + "name": name, + "mesh_map": mesh_map, + "mesh_ids": sorted(mesh_map.keys()), + "obj_by_fid": obj_by_fid, + } + ) + print(f"[Info] Deform {name}: frames={len(mesh_map)}, texture={tex_override}") + elif manifest_path is not None: + print(f"[Warn] Deform manifest not found: {manifest_path}. Render rigid/static only.") + + if args.add_plane: + _add_visual_plane( + scene, + bbox_min=bbox_min_scene, + bbox_max=bbox_max_scene, + mat_cache=mat_cache, + plane_scale=float(args.plane_scale), + plane_gray=float(args.plane_gray), + ) + + for frame in range(num_frames): + cam_to_world_cv = np.linalg.inv(extrinsics[frame]).astype(np.float32) + for robj in rigid_objects: + pose_map = robj["pose_map"] + pose_ids = robj["pose_ids"] + pf = frame if frame in pose_map else _nearest_key(frame, pose_ids) + c_T_o = pose_map[pf] + w_T_o = cam_to_world_cv @ c_T_o + world_m = scene_from_cv_aligned @ w_T_o + obj = robj["obj"] + obj.matrix_world = Matrix(world_m.tolist()) + obj.keyframe_insert(data_path="location", frame=frame) + obj.keyframe_insert(data_path="rotation_quaternion", frame=frame) + obj.keyframe_insert(data_path="scale", frame=frame) + + for frame in range(num_frames): + for dobj in deform_objects: + mesh_map = dobj["mesh_map"] + mesh_ids = dobj["mesh_ids"] + show_fid = frame if frame in mesh_map else _nearest_key(frame, mesh_ids) + obj_by_fid = dobj["obj_by_fid"] + for fid, obj in obj_by_fid.items(): + visible = int(fid) == int(show_fid) + obj.hide_render = not visible + obj.hide_viewport = not visible + obj.keyframe_insert(data_path="hide_render", frame=frame) + obj.keyframe_insert(data_path="hide_viewport", frame=frame) + + cam_data = bpy.data.cameras.new(args.camera_name) + cam_obj = bpy.data.objects.new(args.camera_name, cam_data) + scene.collection.objects.link(cam_obj) + scene.camera = cam_obj + cam_obj.rotation_mode = "QUATERNION" + cam_data.clip_start = 1e-3 + cam_data.clip_end = 1e5 + if args.camera_headlight: + _attach_camera_headlight( + scene, + cam_obj=cam_obj, + energy=float(args.camera_headlight_energy), + angle_deg=float(args.camera_headlight_angle), + light_type=str(args.camera_headlight_type), + ) + + scene.render.resolution_x = int(round(width * float(args.resolution_scale))) + scene.render.resolution_y = int(round(height * float(args.resolution_scale))) + scene.render.resolution_percentage = 100 + scene.frame_start = 0 + scene.frame_end = max(0, num_frames - 1) + + for frame in range(num_frames): + cam_to_world_cv = np.linalg.inv(extrinsics[frame]).astype(np.float32) + world_m = scene_from_cv_aligned @ cam_to_world_cv @ cv_cam_to_bl_cam + _apply_intrinsics_to_camera(cam_data, intrinsics[frame], width, height) + cam_obj.matrix_world = Matrix(world_m.tolist()) + cam_obj.keyframe_insert(data_path="location", frame=frame) + cam_obj.keyframe_insert(data_path="rotation_quaternion", frame=frame) + cam_obj.keyframe_insert(data_path="scale", frame=frame) + cam_data.keyframe_insert(data_path="lens", frame=frame) + cam_data.keyframe_insert(data_path="shift_x", frame=frame) + cam_data.keyframe_insert(data_path="shift_y", frame=frame) + cam_data.keyframe_insert(data_path="sensor_height", frame=frame) + + if cam_obj.animation_data and cam_obj.animation_data.action: + for fcurve in cam_obj.animation_data.action.fcurves: + for kp in fcurve.keyframe_points: + kp.interpolation = "LINEAR" + if cam_data.animation_data and cam_data.animation_data.action: + for fcurve in cam_data.animation_data.action.fcurves: + for kp in fcurve.keyframe_points: + kp.interpolation = "LINEAR" + + if output_rgba_dir is not None: + output_rgba_dir.mkdir(parents=True, exist_ok=True) + scene.render.image_settings.file_format = "PNG" + scene.render.image_settings.color_mode = "RGBA" + scene.render.filepath = str((output_rgba_dir / "frame_").resolve()) + bpy.ops.render.render(animation=True, write_still=False) + print(f"[OK] Wrote RGBA frames: {output_rgba_dir}") + else: + output_video.parent.mkdir(parents=True, exist_ok=True) + scene.render.image_settings.file_format = "FFMPEG" + scene.render.ffmpeg.format = "MPEG4" + scene.render.ffmpeg.codec = "H264" + scene.render.ffmpeg.constant_rate_factor = "MEDIUM" + scene.render.ffmpeg.ffmpeg_preset = "GOOD" + scene.render.filepath = str(output_video) + + bpy.ops.render.render(animation=True, write_still=False) + print(f"[OK] Wrote: {output_video}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/blender_setup_world_hdri.py b/OVOW/engine/tools/blender_setup_world_hdri.py new file mode 100644 index 0000000000000000000000000000000000000000..77ef801fb69fbb01cfde44c5f410c7856ef1e9d8 --- /dev/null +++ b/OVOW/engine/tools/blender_setup_world_hdri.py @@ -0,0 +1,105 @@ +import argparse +import sys +from pathlib import Path + +import bpy + + +def parse_args(): + parser = argparse.ArgumentParser(description="Import scene GLB and save .blend with world HDR lighting.") + parser.add_argument("--input", required=True, help="Input GLB path") + parser.add_argument("--output-blend", required=True, help="Output .blend path") + parser.add_argument("--hdri", required=True, help="HDR/EXR environment map path") + parser.add_argument("--strength", type=float, default=1.0, help="World background strength") + parser.add_argument("--engine", default="BLENDER_EEVEE_NEXT", help="Render engine (e.g. BLENDER_EEVEE_NEXT)") + parser.add_argument("--view-transform", default="Standard", help="Color management view transform") + parser.add_argument("--exposure", type=float, default=0.0, help="Color management exposure") + parser.add_argument("--gamma", type=float, default=1.0, help="Color management gamma") + return parser.parse_args(sys.argv[sys.argv.index("--") + 1 :]) + + +def _set_render_engine(scene: bpy.types.Scene, engine_name: str) -> None: + enum_items = scene.render.bl_rna.properties["engine"].enum_items + valid = {item.identifier for item in enum_items} + if engine_name in valid: + scene.render.engine = engine_name + return + if "BLENDER_EEVEE_NEXT" in valid: + scene.render.engine = "BLENDER_EEVEE_NEXT" + return + if "BLENDER_EEVEE" in valid: + scene.render.engine = "BLENDER_EEVEE" + return + + +def _set_world_hdri(scene: bpy.types.Scene, hdri_path: Path, strength: float) -> None: + world = bpy.data.worlds.new("SceneWorldHDR") + scene.world = world + world.use_nodes = True + nt = world.node_tree + nodes = nt.nodes + links = nt.links + nodes.clear() + + node_env = nodes.new("ShaderNodeTexEnvironment") + node_bg = nodes.new("ShaderNodeBackground") + node_out = nodes.new("ShaderNodeOutputWorld") + + node_env.location = (-400.0, 0.0) + node_bg.location = (-120.0, 0.0) + node_out.location = (120.0, 0.0) + + node_env.image = bpy.data.images.load(str(hdri_path), check_existing=True) + node_bg.inputs["Strength"].default_value = float(strength) + + links.new(node_env.outputs["Color"], node_bg.inputs["Color"]) + links.new(node_bg.outputs["Background"], node_out.inputs["Surface"]) + + +def _set_color_management(scene: bpy.types.Scene, view_transform: str, exposure: float, gamma: float) -> None: + view_items = scene.view_settings.bl_rna.properties["view_transform"].enum_items + valid_view = {item.identifier for item in view_items} + if view_transform in valid_view: + scene.view_settings.view_transform = view_transform + scene.view_settings.exposure = float(exposure) + scene.view_settings.gamma = float(gamma) + + +def _fit_timeline(scene: bpy.types.Scene) -> None: + max_frame = 1 + for act in bpy.data.actions: + fr = getattr(act, "frame_range", None) + if fr is None or len(fr) != 2: + continue + max_frame = max(max_frame, int(round(fr[1]))) + scene.frame_start = 1 + scene.frame_end = max_frame + + +def main(): + args = parse_args() + input_glb = Path(args.input).resolve() + output_blend = Path(args.output_blend).resolve() + hdri = Path(args.hdri).resolve() + + if not input_glb.exists(): + raise FileNotFoundError(input_glb) + if not hdri.exists(): + raise FileNotFoundError(hdri) + + bpy.ops.wm.read_factory_settings(use_empty=True) + bpy.ops.import_scene.gltf(filepath=str(input_glb)) + + scene = bpy.context.scene + _set_render_engine(scene, args.engine) + _set_world_hdri(scene, hdri, args.strength) + _set_color_management(scene, args.view_transform, args.exposure, args.gamma) + _fit_timeline(scene) + + output_blend.parent.mkdir(parents=True, exist_ok=True) + bpy.ops.wm.save_as_mainfile(filepath=str(output_blend)) + print(f"[OK] Wrote blend with HDR world: {output_blend}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/build_deform_videos.py b/OVOW/engine/tools/build_deform_videos.py new file mode 100644 index 0000000000000000000000000000000000000000..22f4b2491158a30fded6366e28f5a089fc1d2f09 --- /dev/null +++ b/OVOW/engine/tools/build_deform_videos.py @@ -0,0 +1,469 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +import cv2 +import numpy as np + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Build per-object masked videos for deform objects.") + parser.add_argument("--summary", type=Path, required=True, help="mask summary json (metadata/*_mask_summary.json)") + parser.add_argument("--output-root", type=Path, required=True, help="output root for motion324 inputs") + parser.add_argument("--video-path", type=Path, default=None, help="override video path") + parser.add_argument( + "--objects", + type=str, + default="", + help="comma-separated object names to process (default: all deform)", + ) + parser.add_argument( + "--category", + type=str, + default="deform", + help="category name to select (default: deform)", + ) + parser.add_argument( + "--normalize-zoom", + type=str, + default="0", + help="enable zoom normalization before writing masked videos (true/false/1/0)", + ) + parser.add_argument( + "--normalize-target-ratio", + type=float, + default=0.65, + help="target object size ratio relative to output side when normalize is enabled", + ) + parser.add_argument( + "--normalize-smooth", + type=int, + default=7, + help="temporal smoothing window for normalize parameters (odd number)", + ) + parser.add_argument( + "--normalize-out-size", + type=int, + default=512, + help="output square size for normalized masked videos", + ) + parser.add_argument( + "--normalize-min-box", + type=int, + default=8, + help="minimum bbox side in pixels to treat a mask as valid", + ) + parser.add_argument( + "--normalize-min-scale", + type=float, + default=0.4, + help="minimum allowed normalization scale", + ) + parser.add_argument( + "--normalize-max-scale", + type=float, + default=2.5, + help="maximum allowed normalization scale", + ) + return parser.parse_args() + + +def _ensure_dir(p: Path) -> None: + p.mkdir(parents=True, exist_ok=True) + + +def _load_summary(path: Path) -> Dict[str, object]: + return json.loads(path.read_text()) + + +def _mask_path(mask_dir: Path, frame_id: int) -> Path: + return mask_dir / f"frame_{frame_id:06d}.png" + + +def _parse_boolish(value: str) -> bool: + v = str(value).strip().lower() + if v in {"1", "true", "yes", "on"}: + return True + if v in {"0", "false", "no", "off"}: + return False + raise ValueError(f"Invalid boolean value: {value}") + + +def _ensure_odd_positive(value: int) -> int: + out = max(1, int(value)) + if out % 2 == 0: + out += 1 + return out + + +def _parse_frame_id(path: Path) -> Optional[int]: + stem = path.stem + if stem.startswith("frame_"): + stem = stem[len("frame_") :] + try: + return int(stem) + except Exception: + return None + + +def _infer_mask_frame_count(mask_dir: Path) -> int: + max_frame = -1 + for p in sorted(mask_dir.glob("frame_*.png")): + frame_id = _parse_frame_id(p) + if frame_id is None: + continue + max_frame = max(max_frame, frame_id) + return max_frame + 1 if max_frame >= 0 else 0 + + +def _load_mask(mask_dir: Path, frame_id: int, width: int, height: int) -> np.ndarray: + mask_path = _mask_path(mask_dir, frame_id) + if mask_path.exists(): + mask = cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE) + if mask is None: + mask = np.zeros((height, width), dtype=np.uint8) + else: + mask = np.zeros((height, width), dtype=np.uint8) + if mask.shape[:2] != (height, width): + mask = cv2.resize(mask, (width, height), interpolation=cv2.INTER_NEAREST) + return mask + + +def _bbox_from_mask(mask: np.ndarray, min_box: int) -> Optional[Tuple[int, int, int, int]]: + ys, xs = np.where(mask > 0) + if ys.size == 0: + return None + x0 = int(xs.min()) + x1 = int(xs.max()) + y0 = int(ys.min()) + y1 = int(ys.max()) + bw = x1 - x0 + 1 + bh = y1 - y0 + 1 + if max(bw, bh) < int(min_box): + return None + return x0, y0, bw, bh + + +def _fill_missing_with_interp(values: np.ndarray, valid: np.ndarray, fallback: float) -> np.ndarray: + out = values.astype(np.float32).copy() + if out.size == 0: + return out + if np.any(valid): + idx = np.arange(out.shape[0], dtype=np.float32) + out[~valid] = np.interp(idx[~valid], idx[valid], out[valid]) + else: + out.fill(float(fallback)) + return out + + +def _median_filter_1d(values: np.ndarray, window: int) -> np.ndarray: + if values.size == 0 or window <= 1: + return values.astype(np.float32).copy() + radius = window // 2 + out = np.empty_like(values, dtype=np.float32) + for i in range(values.shape[0]): + left = max(0, i - radius) + right = min(values.shape[0], i + radius + 1) + out[i] = float(np.median(values[left:right])) + return out + + +def _moving_average_1d(values: np.ndarray, window: int) -> np.ndarray: + if values.size == 0 or window <= 1: + return values.astype(np.float32).copy() + pad = window // 2 + kernel = np.ones(window, dtype=np.float32) / float(window) + padded = np.pad(values.astype(np.float32), (pad, pad), mode="edge") + out = np.convolve(padded, kernel, mode="valid") + return out.astype(np.float32) + + +def _smooth_series(values: np.ndarray, window: int) -> np.ndarray: + if window <= 1 or values.size == 0: + return values.astype(np.float32).copy() + med = _median_filter_1d(values, window) + return _moving_average_1d(med, window) + + +def _build_normalization_params( + mask_dir: Path, + num_frames: int, + width: int, + height: int, + out_size: int, + target_ratio: float, + smooth_window: int, + min_box: int, + min_scale: float, + max_scale: float, +) -> Dict[str, object]: + cxs = np.full(num_frames, np.nan, dtype=np.float32) + cys = np.full(num_frames, np.nan, dtype=np.float32) + sizes = np.full(num_frames, np.nan, dtype=np.float32) + valid = np.zeros(num_frames, dtype=bool) + bboxes = np.full((num_frames, 4), -1, dtype=np.int32) + + for frame_id in range(num_frames): + mask = _load_mask(mask_dir, frame_id, width, height) + bbox = _bbox_from_mask(mask, min_box=min_box) + if bbox is None: + continue + x0, y0, bw, bh = bbox + bboxes[frame_id] = np.array([x0, y0, bw, bh], dtype=np.int32) + cxs[frame_id] = float(x0 + bw * 0.5) + cys[frame_id] = float(y0 + bh * 0.5) + sizes[frame_id] = float(max(bw, bh)) + valid[frame_id] = True + + default_size = float(max(min_box, min(width, height) * 0.5)) + cxs_filled = _fill_missing_with_interp(cxs, valid, fallback=float(width) * 0.5) + cys_filled = _fill_missing_with_interp(cys, valid, fallback=float(height) * 0.5) + sizes_filled = _fill_missing_with_interp(sizes, valid, fallback=default_size) + + target_size = max(1.0, float(out_size) * float(target_ratio)) + scales = target_size / np.maximum(sizes_filled, 1.0) + scales = np.clip(scales, float(min_scale), float(max_scale)).astype(np.float32) + + smooth_window = _ensure_odd_positive(smooth_window) + scales_sm = _smooth_series(scales, smooth_window) + cxs_sm = _smooth_series(cxs_filled, smooth_window) + cys_sm = _smooth_series(cys_filled, smooth_window) + + return { + "scale": scales_sm, + "cx": cxs_sm, + "cy": cys_sm, + "valid": valid, + "bboxes": bboxes, + "smooth_window": smooth_window, + } + + +def main() -> None: + args = parse_args() + summary = _load_summary(args.summary) + normalize_zoom = _parse_boolish(args.normalize_zoom) + + video_path = Path(args.video_path) if args.video_path else Path(str(summary.get("video", ""))) + if not video_path.exists(): + raise FileNotFoundError(f"Video not found: {video_path}") + + video_name = str(summary.get("video_name", video_path.stem)) + objects = summary.get("objects", []) + if not isinstance(objects, list): + objects = [] + + selected = [] + for obj in objects: + if not isinstance(obj, dict): + continue + name = str(obj.get("name", "")) + category = str(obj.get("category", "")).lower() + if category != args.category: + continue + selected.append(obj) + + if args.objects.strip(): + allow = {x.strip() for x in args.objects.split(",") if x.strip()} + selected = [o for o in selected if str(o.get("name", "")) in allow] + + out_root = args.output_root / video_name + _ensure_dir(out_root) + + cap = cv2.VideoCapture(str(video_path)) + if not cap.isOpened(): + raise RuntimeError(f"Failed to open video: {video_path}") + + fps = float(summary.get("fps", cap.get(cv2.CAP_PROP_FPS) or 10.0)) + width = int(summary.get("width", 0) or cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0) + height = int(summary.get("height", 0) or cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0) + num_frames = int(summary.get("num_frames", 0) or cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) + cap_frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) + + if width <= 0 or height <= 0: + ok, first_frame = cap.read() + if not ok or first_frame is None: + raise RuntimeError(f"Failed to read first frame: {video_path}") + height, width = first_frame.shape[:2] + cap.set(cv2.CAP_PROP_POS_FRAMES, 0) + + param_frames = num_frames if num_frames > 0 else cap_frame_count + if param_frames <= 0: + param_frames = 0 + for obj in selected: + name = str(obj.get("name", "")) + mask_dir_raw = str(obj.get("masks_dir", "") or "").strip() + mask_dir = Path(mask_dir_raw) if mask_dir_raw else Path("") + if not mask_dir_raw or not mask_dir.exists(): + mask_dir = Path(str(summary.get("mask_root", ""))) / name + param_frames = max(param_frames, _infer_mask_frame_count(mask_dir)) + if param_frames <= 0: + param_frames = 1 + + out_size = max(32, int(args.normalize_out_size)) + smooth_window = _ensure_odd_positive(args.normalize_smooth) + target_ratio = float(args.normalize_target_ratio) + if target_ratio <= 0.0: + raise ValueError("--normalize-target-ratio must be > 0") + min_box = max(1, int(args.normalize_min_box)) + min_scale = max(1e-4, float(args.normalize_min_scale)) + max_scale = max(min_scale, float(args.normalize_max_scale)) + + writers: Dict[str, cv2.VideoWriter] = {} + metas: Dict[str, Dict[str, object]] = {} + norm_params_by_name: Dict[str, Dict[str, object]] = {} + normalize_meta_paths: Dict[str, Path] = {} + writer_width = out_size if normalize_zoom else width + writer_height = out_size if normalize_zoom else height + + for obj in selected: + name = str(obj.get("name", "")) + mask_dir_raw = str(obj.get("masks_dir", "") or "").strip() + if mask_dir_raw: + mask_dir = Path(mask_dir_raw) + else: + mask_dir = Path("") + if not mask_dir_raw or not mask_dir.exists(): + mask_dir = Path(str(summary.get("mask_root", ""))) / name + obj_dir = out_root / name + _ensure_dir(obj_dir) + out_video = obj_dir / "masked.mp4" + normalize_meta_path = obj_dir / "normalize_meta.json" + + fourcc = cv2.VideoWriter_fourcc(*"mp4v") + writer = cv2.VideoWriter(str(out_video), fourcc, fps, (writer_width, writer_height)) + writers[name] = writer + normalize_meta_paths[name] = normalize_meta_path + + if normalize_zoom: + norm_params_by_name[name] = _build_normalization_params( + mask_dir=mask_dir, + num_frames=param_frames, + width=width, + height=height, + out_size=out_size, + target_ratio=target_ratio, + smooth_window=smooth_window, + min_box=min_box, + min_scale=min_scale, + max_scale=max_scale, + ) + + metas[name] = { + "name": name, + "category": str(obj.get("category", "")), + "mask_dir": str(mask_dir), + "video": str(out_video), + "fps": fps, + "width": writer_width, + "height": writer_height, + "normalize_zoom": bool(normalize_zoom), + "normalize_meta": str(normalize_meta_path) if normalize_zoom else None, + } + + frame_idx = 0 + while True: + ok, frame = cap.read() + if not ok: + break + if width <= 0 or height <= 0: + height, width = frame.shape[:2] + for obj in selected: + name = str(obj.get("name", "")) + mask_dir = Path(metas[name]["mask_dir"]) + mask = _load_mask(mask_dir, frame_idx, width, height) + + if mask.max() > 1: + mask_bool = mask > 0 + else: + mask_bool = mask.astype(bool) + + out_frame = np.zeros_like(frame) + out_frame[mask_bool] = frame[mask_bool] + + if normalize_zoom: + params = norm_params_by_name[name] + n_params = int(len(params["scale"])) + idx = min(frame_idx, max(0, n_params - 1)) + scale = float(params["scale"][idx]) + cx = float(params["cx"][idx]) + cy = float(params["cy"][idx]) + tx = float(out_size) * 0.5 - scale * cx + ty = float(out_size) * 0.5 - scale * cy + mat = np.array([[scale, 0.0, tx], [0.0, scale, ty]], dtype=np.float32) + normalized = cv2.warpAffine( + out_frame, + mat, + (out_size, out_size), + flags=cv2.INTER_LINEAR, + borderMode=cv2.BORDER_CONSTANT, + borderValue=(0, 0, 0), + ) + writers[name].write(normalized) + else: + writers[name].write(out_frame) + + frame_idx += 1 + if num_frames and frame_idx >= num_frames: + break + + cap.release() + for writer in writers.values(): + writer.release() + + if normalize_zoom: + for obj in selected: + name = str(obj.get("name", "")) + params = norm_params_by_name[name] + frames_meta: List[Dict[str, object]] = [] + valid = params["valid"] + bboxes = params["bboxes"] + for idx in range(int(len(params["scale"]))): + bbox = bboxes[idx].tolist() if bool(valid[idx]) else None + frames_meta.append( + { + "frame": int(idx), + "valid_mask": bool(valid[idx]), + "bbox": bbox, + "cx": float(params["cx"][idx]), + "cy": float(params["cy"][idx]), + "scale": float(params["scale"][idx]), + } + ) + normalize_payload = { + "normalize_zoom": True, + "input_width": int(width), + "input_height": int(height), + "output_size": int(out_size), + "target_ratio": float(target_ratio), + "smooth_window": int(params["smooth_window"]), + "min_box": int(min_box), + "min_scale": float(min_scale), + "max_scale": float(max_scale), + "num_frames_params": int(len(params["scale"])), + "num_frames_written": int(frame_idx), + "frames": frames_meta, + } + normalize_meta_paths[name].write_text(json.dumps(normalize_payload, indent=2)) + + manifest = { + "video_name": video_name, + "video_path": str(video_path), + "fps": fps, + "width": writer_width, + "height": writer_height, + "num_frames": frame_idx, + "objects": [metas[str(obj.get("name", ""))] for obj in selected], + } + + manifest_path = out_root / "deform_manifest.json" + manifest_path.write_text(json.dumps(manifest, indent=2)) + print(str(manifest_path)) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/check_alignment.py b/OVOW/engine/tools/check_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..97978de0e27cdc9f26d8f4b4c12f6e135e4b5333 --- /dev/null +++ b/OVOW/engine/tools/check_alignment.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +""" +Quick visual + numeric sanity check for alignment between: + - session rgb frame (e.g., rgb/000000.jpg) + - session depth (e.g., depth/000000.png) + - a given mask (e.g., .png or per-object masks) + +Outputs a side-by-side image: + [RGB + mask overlay] | [Depth colormap + mask contour] | [Depth edges + mask contour] + +Example: + python OnePoseviaGen/tools/check_alignment.py \ + --session-dir OnePoseviaGen/temp_local/batch_run_xxx/scene_09 +""" + +from __future__ import annotations + +import argparse +from pathlib import Path +from typing import Optional, Tuple + +import numpy as np + +try: + import cv2 # type: ignore +except Exception as exc: # noqa: BLE001 + raise SystemExit( + "OpenCV (cv2) is required. Please run with an environment that has opencv-python installed." + ) from exc + + +def _read_rgb(path: Path) -> np.ndarray: + img = cv2.imread(str(path), cv2.IMREAD_COLOR) + if img is None: + raise FileNotFoundError(f"Failed to read rgb image: {path}") + return img + + +def _read_depth(path: Path) -> np.ndarray: + dep = cv2.imread(str(path), cv2.IMREAD_UNCHANGED) + if dep is None: + raise FileNotFoundError(f"Failed to read depth image: {path}") + if dep.ndim != 2: + raise ValueError(f"Depth must be single-channel, got shape={dep.shape} from {path}") + return dep + + +def _read_mask(path: Path) -> np.ndarray: + msk = cv2.imread(str(path), cv2.IMREAD_GRAYSCALE) + if msk is None: + raise FileNotFoundError(f"Failed to read mask image: {path}") + if msk.ndim != 2: + raise ValueError(f"Mask must be single-channel, got shape={msk.shape} from {path}") + return msk + + +def _find_default_mask(session_dir: Path) -> Path: + mp4s = sorted([p for p in session_dir.glob("*.mp4") if p.is_file()]) + if len(mp4s) == 1: + candidate = mp4s[0].with_suffix(".png") + if candidate.is_file(): + return candidate + + cands = sorted( + [ + p + for p in session_dir.glob("*.png") + if p.is_file() and not p.name.startswith("__") and p.name != "__align_check.png" + ] + ) + if not cands: + raise FileNotFoundError( + f"No suitable root-level mask *.png found in {session_dir}. " + "Please pass --mask explicitly." + ) + return cands[0] + + +def _to_mask_binary(mask: np.ndarray) -> np.ndarray: + return (mask > 127).astype(np.uint8) + + +def _mask_contours(mask_bin: np.ndarray): + contours, _ = cv2.findContours(mask_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + return contours + + +def _normalize_depth_for_viz(depth_raw: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: + """ + Returns: + - depth_m: float32 depth in meters + - depth_8u: uint8 normalized depth for visualization/edge detection + """ + if depth_raw.dtype == np.uint16: + depth_m = depth_raw.astype(np.float32) / 1000.0 + else: + depth_m = depth_raw.astype(np.float32) + + valid = depth_m > 1e-6 + if valid.any(): + vmin, vmax = np.percentile(depth_m[valid], [2, 98]).astype(np.float32) + else: + vmin, vmax = np.float32(0.0), np.float32(1.0) + + norm = np.zeros_like(depth_m, dtype=np.float32) + if valid.any() and float(vmax) > float(vmin): + norm[valid] = (depth_m[valid] - vmin) / (vmax - vmin) + norm = np.clip(norm, 0.0, 1.0) + depth_8u = (norm * 255.0).astype(np.uint8) + return depth_m, depth_8u + + +def _edge_overlap_score(mask_bin: np.ndarray, depth_8u: np.ndarray, *, canny1: int, canny2: int) -> float: + edges = cv2.Canny(depth_8u, canny1, canny2) + mask_edge = cv2.morphologyEx(mask_bin, cv2.MORPH_GRADIENT, np.ones((3, 3), np.uint8)) + if not (mask_edge > 0).any(): + return 0.0 + edge_dil = cv2.dilate((edges > 0).astype(np.uint8), np.ones((5, 5), np.uint8), iterations=1) + return float((edge_dil[mask_edge > 0] > 0).mean()) + + +def _make_viz( + rgb: np.ndarray, + depth_8u: np.ndarray, + mask_bin: np.ndarray, + *, + canny1: int, + canny2: int, +) -> np.ndarray: + contours = _mask_contours(mask_bin) + + rgb_vis = rgb.copy() + rgb_vis[mask_bin > 0] = (0.6 * rgb_vis[mask_bin > 0] + 0.4 * np.array([0, 255, 0])).astype( + np.uint8 + ) + cv2.drawContours(rgb_vis, contours, -1, (0, 0, 255), 2) + + dep_vis = cv2.applyColorMap(depth_8u, cv2.COLORMAP_TURBO) + cv2.drawContours(dep_vis, contours, -1, (255, 255, 255), 2) + + edges = cv2.Canny(depth_8u, canny1, canny2) + rgb_edges = rgb.copy() + rgb_edges[edges > 0] = (0, 255, 255) + cv2.drawContours(rgb_edges, contours, -1, (0, 0, 255), 2) + + return np.hstack([rgb_vis, dep_vis, rgb_edges]) + + +def parse_args() -> argparse.Namespace: + p = argparse.ArgumentParser(description="Check RGB/depth/mask alignment in a OnePoseviaGen session.") + p.add_argument("--session-dir", type=Path, required=True, help="Session directory (contains rgb/, depth/).") + p.add_argument( + "--rgb", + type=str, + default="rgb/000000.jpg", + help="RGB path relative to session-dir (default: rgb/000000.jpg).", + ) + p.add_argument( + "--depth", + type=str, + default="depth/000000.png", + help="Depth path relative to session-dir (default: depth/000000.png).", + ) + p.add_argument( + "--mask", + type=Path, + default=None, + help="Mask image path. If omitted, uses the first root-level *.png under session-dir.", + ) + p.add_argument( + "--output", + type=Path, + default=None, + help="Output visualization path (default: /__align_check.png).", + ) + p.add_argument("--canny1", type=int, default=40, help="Canny low threshold (default: 40).") + p.add_argument("--canny2", type=int, default=120, help="Canny high threshold (default: 120).") + return p.parse_args() + + +def main() -> None: + args = parse_args() + session_dir = args.session_dir.resolve() + if not session_dir.is_dir(): + raise SystemExit(f"--session-dir is not a directory: {session_dir}") + + rgb_path = (session_dir / args.rgb).resolve() + depth_path = (session_dir / args.depth).resolve() + mask_path = args.mask.resolve() if args.mask else _find_default_mask(session_dir) + + rgb = _read_rgb(rgb_path) + depth_raw = _read_depth(depth_path) + mask_raw = _read_mask(mask_path) + + H, W = rgb.shape[:2] + if mask_raw.shape != (H, W): + mask_raw = cv2.resize(mask_raw, (W, H), interpolation=cv2.INTER_NEAREST) + + mask_bin = _to_mask_binary(mask_raw) + _, depth_8u = _normalize_depth_for_viz(depth_raw) + + score = _edge_overlap_score(mask_bin, depth_8u, canny1=args.canny1, canny2=args.canny2) + viz = _make_viz(rgb, depth_8u, mask_bin, canny1=args.canny1, canny2=args.canny2) + + out_path = args.output.resolve() if args.output else (session_dir / "__align_check.png") + out_path.parent.mkdir(parents=True, exist_ok=True) + ok = cv2.imwrite(str(out_path), viz) + if not ok: + raise RuntimeError(f"Failed to write output image: {out_path}") + + print(f"rgb: {rgb_path} shape={rgb.shape}") + print(f"depth: {depth_path} shape={depth_raw.shape} dtype={depth_raw.dtype}") + print(f"mask: {mask_path} resized_to={mask_raw.shape}") + print(f"edge_overlap_score: {score:.4f} (higher usually means better alignment)") + print(f"saved: {out_path}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/compose_side_by_side_image.py b/OVOW/engine/tools/compose_side_by_side_image.py new file mode 100644 index 0000000000000000000000000000000000000000..1875d67103bb7997064f3c7ceaecd654de76cef0 --- /dev/null +++ b/OVOW/engine/tools/compose_side_by_side_image.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +from pathlib import Path + +from PIL import Image + + +_RESAMPLE = getattr(Image, "Resampling", Image) + + +def _load_rgb(path: Path) -> Image.Image: + img = Image.open(path) + if img.mode == "RGBA": + bg = Image.new("RGBA", img.size, (255, 255, 255, 255)) + img = Image.alpha_composite(bg, img) + return img.convert("RGB") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Compose two images side-by-side.") + parser.add_argument("--left", type=Path, required=True, help="Left image path") + parser.add_argument("--right", type=Path, required=True, help="Right image path") + parser.add_argument("--output", type=Path, required=True, help="Output path") + parser.add_argument( + "--left-output", + type=Path, + default=None, + help="Optional output path for the normalized left image", + ) + parser.add_argument( + "--separator", + type=int, + default=2, + help="Separator width in pixels (default: 2)", + ) + parser.add_argument( + "--separator-gray", + type=int, + default=255, + help="Separator gray level in [0,255] (default: 255)", + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + left = _load_rgb(args.left) + right = _load_rgb(args.right) + + if right.height != left.height: + new_w = max(1, int(round(right.width * (left.height / float(max(1, right.height)))))) + right = right.resize((new_w, left.height), resample=_RESAMPLE.LANCZOS) + + sep_w = max(0, int(args.separator)) + sep_gray = max(0, min(255, int(args.separator_gray))) + out_w = left.width + sep_w + right.width + out_h = max(left.height, right.height) + out = Image.new("RGB", (out_w, out_h), (sep_gray, sep_gray, sep_gray)) + out.paste(left, (0, 0)) + out.paste(right, (left.width + sep_w, 0)) + + args.output.parent.mkdir(parents=True, exist_ok=True) + out.save(args.output) + if args.left_output is not None: + args.left_output.parent.mkdir(parents=True, exist_ok=True) + left.save(args.left_output) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/deform_apply_world_pose.py b/OVOW/engine/tools/deform_apply_world_pose.py new file mode 100644 index 0000000000000000000000000000000000000000..70b7fbc56f7cde6b261c9f045a3b2502272420e6 --- /dev/null +++ b/OVOW/engine/tools/deform_apply_world_pose.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Dict, List, Tuple + +import numpy as np +import trimesh + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Apply per-frame world poses to deform mesh frames and export world-space OBJ sequence." + ) + parser.add_argument("--mesh-frames", type=Path, required=True, help="Directory with frame_*.obj mesh sequence") + parser.add_argument("--poses-world", type=Path, required=True, help="Per-frame world poses json") + parser.add_argument("--output-dir", type=Path, required=True, help="Output world mesh directory") + parser.add_argument("--scale-json", type=Path, default=None, help="Optional scale.json with key scale") + parser.add_argument("--scale", type=float, default=None, help="Optional explicit uniform scale") + parser.add_argument("--frame-glob", type=str, default="frame_*.obj", help="Glob for mesh frame files") + parser.add_argument("--num-frames", type=int, default=-1, help="Override output frame count; <=0 uses poses") + parser.add_argument( + "--mapping-out", + type=Path, + default=None, + help="Optional output json for frame mapping metadata (default: /mapping.json)", + ) + return parser.parse_args() + + +def _parse_frame_id(path: Path) -> int | None: + stem = path.stem + for part in reversed(stem.split("_")): + if part.isdigit(): + return int(part) + digits = "".join(ch if ch.isdigit() else " " for ch in stem).split() + if digits: + return int(digits[-1]) + return None + + +def _load_pose_map(path: Path) -> Dict[int, np.ndarray]: + data = json.loads(path.read_text()) + pose_map: Dict[int, np.ndarray] = {} + for k, v in data.items(): + try: + frame = int(k) + except Exception: + continue + arr = np.asarray(v, dtype=np.float32) + if arr.shape != (4, 4): + continue + pose_map[frame] = arr + if not pose_map: + raise ValueError(f"No valid 4x4 poses in {path}") + return pose_map + + +def _nearest_key(target: int, keys: List[int]) -> int: + return min(keys, key=lambda x: abs(x - target)) + + +def _mesh_from_path(path: Path) -> trimesh.Trimesh: + mesh = trimesh.load(str(path), force="mesh", process=False, maintain_order=True) + if isinstance(mesh, trimesh.Scene): + geos = [g for g in mesh.geometry.values() if isinstance(g, trimesh.Trimesh)] + if not geos: + raise RuntimeError(f"No geometry in scene mesh: {path}") + mesh = trimesh.util.concatenate(geos) + if not isinstance(mesh, trimesh.Trimesh): + raise RuntimeError(f"Invalid mesh: {path}") + return mesh + + +def _load_scale(args: argparse.Namespace) -> float: + if args.scale is not None: + return float(args.scale) + if args.scale_json is None: + return 1.0 + payload = json.loads(args.scale_json.read_text()) + return float(payload.get("scale", 1.0)) + + +def main() -> None: + args = parse_args() + + if not args.mesh_frames.exists(): + raise FileNotFoundError(args.mesh_frames) + if not args.poses_world.exists(): + raise FileNotFoundError(args.poses_world) + if args.scale_json is not None and not args.scale_json.exists(): + raise FileNotFoundError(args.scale_json) + + pose_map = _load_pose_map(args.poses_world) + pose_ids = sorted(pose_map.keys()) + + mesh_map: Dict[int, Path] = {} + for path in sorted(args.mesh_frames.glob(args.frame_glob)): + fid = _parse_frame_id(path) + if fid is None: + continue + mesh_map[fid] = path + if not mesh_map: + raise FileNotFoundError(f"No mesh frames found in {args.mesh_frames} (glob={args.frame_glob})") + mesh_ids = sorted(mesh_map.keys()) + + num_frames = int(args.num_frames) + if num_frames <= 0: + num_frames = max(pose_ids) + 1 + + scale = _load_scale(args) + + args.output_dir.mkdir(parents=True, exist_ok=True) + mapping_out = args.mapping_out or (args.output_dir / "mapping.json") + + mapping: Dict[str, Dict[str, object]] = {} + + for frame in range(num_frames): + pose_f = frame if frame in pose_map else _nearest_key(frame, pose_ids) + mesh_f = frame if frame in mesh_map else _nearest_key(frame, mesh_ids) + + mesh = _mesh_from_path(mesh_map[mesh_f]) + verts = np.asarray(mesh.vertices, dtype=np.float32) * scale + + w_T_o = pose_map[pose_f] + R = w_T_o[:3, :3] + t = w_T_o[:3, 3] + verts_world = (R @ verts.T).T + t + + out_mesh = mesh.copy() + out_mesh.vertices = verts_world + + out_path = args.output_dir / f"frame_{frame:06d}.obj" + out_mesh.export(out_path) + + mapping[str(frame)] = { + "pose_frame": int(pose_f), + "mesh_frame": int(mesh_f), + "mesh_path": str(mesh_map[mesh_f]), + "output": str(out_path), + } + + payload = { + "scale": float(scale), + "num_frames": int(num_frames), + "mesh_frames_dir": str(args.mesh_frames), + "poses_world": str(args.poses_world), + "frames": mapping, + } + mapping_out.write_text(json.dumps(payload, indent=2)) + print(f"[OK] Wrote world mesh sequence: {args.output_dir} ({num_frames} frames, scale={scale:.6f})") + print(f"[OK] Mapping: {mapping_out}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/deform_pose_pipeline.py b/OVOW/engine/tools/deform_pose_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..97ba108b7070d6fa4b06b0177257f4731d66b463 --- /dev/null +++ b/OVOW/engine/tools/deform_pose_pipeline.py @@ -0,0 +1,1341 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import os +import shutil +import subprocess +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +import cv2 +import numpy as np +import trimesh + +import sys +_ROOT = Path(__file__).resolve().parents[1] +if str(_ROOT) not in sys.path: + sys.path.insert(0, str(_ROOT)) +_FPOSE = _ROOT / "oneposeviagen" / "fpose" +if _FPOSE.exists() and str(_FPOSE) not in sys.path: + sys.path.insert(0, str(_FPOSE)) + +from oneposeviagen.scripts.render_normals import render_high_model_to_normal_video +from oneposeviagen.fpose.fpose.Utils import nvdiffrast_render, make_mesh_tensors +from fpose.estimater import (FoundationPose, ScorePredictor, PoseRefinePredictor, + get_cached_scorer, get_cached_refiner) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Deform object scale+pose pipeline (post Motion324).") + parser.add_argument("--run-dir", type=Path, required=True, help="OPG run dir (video_pipeline_*/)") + parser.add_argument("--mask-summary", type=Path, required=True, help="mask summary json") + parser.add_argument("--object-name", type=str, required=True, help="deform object name") + parser.add_argument("--motion-output-root", type=Path, required=True, help="motion324 output root") + parser.add_argument("--manifest", type=Path, default=None, help="motion324 manifest.json") + parser.add_argument("--anim-path", type=Path, default=None, help="motion324 animation file (fbx/glb)") + parser.add_argument("--ref-mesh", type=Path, default=None, help="motion324 reference mesh") + parser.add_argument( + "--pose-mode", + type=str, + choices=("ref", "frame_mesh", "single_track", "frame_track"), + default="ref", + help="ref=single scaled_ref_mesh; frame_mesh=per-frame register; single_track=register once + track_all; " + "frame_track=per-frame mesh + temporal refine + quality gate", + ) + parser.add_argument("--frame-step", type=int, default=1, help="frame step for pose estimation") + parser.add_argument( + "--mask-stride", + type=int, + default=1, + help="Mask frame stride relative to run frames. E.g. 3 means run frame f uses mask frame ~3*f", + ) + parser.add_argument("--min-mask-pix", type=int, default=50, help="min mask pixels to run pose") + parser.add_argument( + "--track-anchor-frame", + type=int, + default=-1, + help="Anchor run-frame id for single_track mode; <0 selects max-mask frame automatically", + ) + parser.add_argument("--iter", type=int, default=5, help="FoundationPose refinement iterations") + parser.add_argument("--blender-bin", type=Path, default=Path("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/opt/blender-4.2.3-linux-x64/blender")) + parser.add_argument("--blender-lib", type=Path, default=Path("")) + parser.add_argument("--force-scale", action="store_true", help="force recompute scale") + parser.add_argument("--force-poses", action="store_true", help="force recompute poses") + parser.add_argument("--render-video", action="store_true", help="render normal overlay video") + parser.add_argument( + "--export-video-frames", + action="store_true", + help="export pose preview frames to pose_result/normal_video_frames", + ) + parser.add_argument("--fps", type=float, default=None, help="override fps") + return parser.parse_args() + + +def _load_summary(path: Path) -> Dict[str, object]: + return json.loads(path.read_text()) + + +def _find_mask_dir(summary: Dict[str, object], obj_name: str) -> Path: + mask_root = Path(str(summary.get("mask_root", ""))) + for obj in summary.get("objects", []): + if not isinstance(obj, dict): + continue + if str(obj.get("name", "")) != obj_name: + continue + mdir_raw = str(obj.get("masks_dir", "") or "").strip() + mdir = Path(mdir_raw) if mdir_raw else Path("") + if not mdir_raw or mdir_raw == "." or not mdir.exists(): + mdir = mask_root / obj_name + if not mdir.exists(): + raise FileNotFoundError(f"Mask dir not found for {obj_name}: {mdir}") + return mdir + raise ValueError(f"Object {obj_name} not found in mask summary") + + +def _load_manifest(path: Path) -> Dict[str, object]: + return json.loads(path.read_text()) + + +def _load_npz(run_dir: Path) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + result_npz = run_dir / "results" / "result.npz" + if not result_npz.exists(): + raise FileNotFoundError(result_npz) + data = np.load(result_npz) + return data["video"], data["depths"], data["intrinsics"], data["extrinsics"] + + +def _parse_frame_id(path: Path) -> Optional[int]: + stem = path.stem + if stem.startswith("frame_"): + stem = stem[len("frame_") :] + try: + return int(stem) + except Exception: + return None + + +def _pick_nearest_frame(target: int, frames: List[int]) -> int: + if not frames: + raise ValueError("Empty frame list") + return min(frames, key=lambda x: abs(x - target)) + + +def _build_frame_map(root: Path, glob_pat: str) -> Dict[int, Path]: + mapping: Dict[int, Path] = {} + for p in sorted(root.glob(glob_pat)): + fid = _parse_frame_id(p) + if fid is None: + continue + mapping[int(fid)] = p + return mapping + + +def _load_mask_aligned( + mask_map: Dict[int, Path], + mask_ids: List[int], + run_frame_id: int, + mask_stride: int, + shape: Tuple[int, int], +) -> Tuple[np.ndarray, int]: + target = int(run_frame_id * max(1, int(mask_stride))) + use_id = target if target in mask_map else _pick_nearest_frame(target, mask_ids) + mask_path = mask_map[use_id] + if not mask_path.exists(): + return np.zeros(shape, dtype=np.uint8), use_id + mask = cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE) + if mask is None: + return np.zeros(shape, dtype=np.uint8), use_id + if mask.shape[0] != shape[0] or mask.shape[1] != shape[1]: + mask = cv2.resize(mask, (shape[1], shape[0]), interpolation=cv2.INTER_NEAREST) + return mask, use_id + + +def _to_bgr(frame: np.ndarray) -> np.ndarray: + if frame.ndim == 3 and frame.shape[0] == 3: + frame = np.transpose(frame, (1, 2, 0)) + if frame.max() <= 1.5: + frame = (frame * 255.0).clip(0, 255) + return frame.astype(np.uint8) + + +def _fill_missing(poses: Dict[int, np.ndarray], num_frames: int) -> Dict[int, np.ndarray]: + if not poses: + return {i: np.eye(4, dtype=np.float32) for i in range(num_frames)} + frame_ids = sorted(poses.keys()) + filled: Dict[int, np.ndarray] = {} + for i in range(num_frames): + if i in poses: + filled[i] = poses[i] + else: + nearest = min(frame_ids, key=lambda x: abs(x - i)) + filled[i] = poses[nearest] + return filled + + +def _mesh_from_path(path: Path) -> trimesh.Trimesh: + mesh = trimesh.load(str(path), force="mesh", process=False, maintain_order=True) + if isinstance(mesh, trimesh.Scene): + geos = [g for g in mesh.geometry.values()] + mesh = trimesh.util.concatenate(geos) + if not isinstance(mesh, trimesh.Trimesh): + raise RuntimeError(f"Invalid mesh: {path}") + if mesh.vertex_normals is None or len(mesh.vertex_normals) == 0: + mesh.rezero() + mesh.compute_vertex_normals() + return mesh + + +def _mesh_diag(mesh: trimesh.Trimesh) -> float: + verts = np.asarray(mesh.vertices, dtype=np.float32) + if verts.size == 0: + return 0.0 + extent = verts.max(axis=0) - verts.min(axis=0) + return float(np.linalg.norm(extent)) + + +def _normalize_mesh_frames_to_ref( + mesh_frames_dir: Path, + scaled_ref_mesh: Path, + info_out: Optional[Path] = None, + eps: float = 1e-4, +) -> float: + mesh_paths = sorted(mesh_frames_dir.glob("frame_*.obj")) + if not mesh_paths: + raise FileNotFoundError(f"No mesh frames found in {mesh_frames_dir}") + + ref_mesh = _mesh_from_path(scaled_ref_mesh) + ref_diag = _mesh_diag(ref_mesh) + if ref_diag <= eps: + raise RuntimeError(f"Invalid scaled ref mesh size: {scaled_ref_mesh}") + + sample_mesh = _mesh_from_path(mesh_paths[0]) + anim_diag = _mesh_diag(sample_mesh) + if anim_diag <= eps: + raise RuntimeError(f"Invalid animation mesh size: {mesh_paths[0]}") + + factor = float(ref_diag / anim_diag) + applied = abs(factor - 1.0) > 1e-3 + if applied: + for p in mesh_paths: + mesh = _mesh_from_path(p) + verts = np.asarray(mesh.vertices, dtype=np.float32) * factor + mesh.vertices = verts + mesh.export(p) + + payload = { + "scaled_ref_mesh": str(scaled_ref_mesh), + "mesh_frames_dir": str(mesh_frames_dir), + "ref_diag": float(ref_diag), + "anim_diag_before": float(anim_diag), + "factor": float(factor), + "applied": bool(applied), + "num_mesh_frames": int(len(mesh_paths)), + } + if info_out is not None: + info_out.write_text(json.dumps(payload, indent=2)) + + msg = "applied" if applied else "skip" + print(f"[mesh-scale] {mesh_frames_dir.name}: factor={factor:.6f} ({msg})") + return factor + + +def _resolve_manifest_path(base: Path, value: Optional[Path]) -> Optional[Path]: + if value is None: + return None + if value.exists(): + return value + candidate = (base / value).resolve() + if candidate.exists(): + return candidate + return value + + +def _prefer_obj_mesh(path: Path) -> Path: + """Prefer a .obj mesh when ref mesh is glb/fbx.""" + if path.suffix.lower() == ".obj" and path.exists(): + return path + if path.exists(): + cand_dir = path.parent + else: + cand_dir = path.parent + candidates = list(cand_dir.glob("*.obj")) + if not candidates: + return path + for key in ("wo_remap_converted.obj", "converted.obj"): + for c in candidates: + if c.name.endswith(key): + return c + return candidates[0] + + +def _run_recover_scale(args: argparse.Namespace, obj_root: Path) -> Path: + scale_json = obj_root / "scale.json" + if scale_json.exists() and not args.force_scale: + return scale_json + rds_argv = [ + "--run-dir", str(args.run_dir), + "--mask-summary", str(args.mask_summary), + "--object-name", args.object_name, + "--mask-stride", str(max(1, int(args.mask_stride))), + "--ref-mesh", str(args.ref_mesh), + "--output-dir", str(obj_root), + ] + if os.environ.get("OPG_ROMAV2_INPROC", "0") == "1": + import recover_deform_scale as _rds + _old = sys.argv + try: + sys.argv = ["recover_deform_scale.py"] + rds_argv + _rds.run(_rds.parse_args()) + finally: + sys.argv = _old + else: + subprocess.check_call( + [str(Path(sys.executable)), str(_ROOT / "tools" / "recover_deform_scale.py")] + rds_argv) + return scale_json + + +def _read_scale(scale_json: Path) -> float: + data = json.loads(scale_json.read_text()) + return float(data.get("scale", 1.0)) + + +def _export_mesh_frames(anim_path: Path, out_dir: Path, frame_count: int, frame_step: int, scale: float, + blender_bin: Path, blender_lib: Path) -> None: + out_dir.mkdir(parents=True, exist_ok=True) + cmd = [ + str(blender_bin), "-b", "-P", str(_ROOT / "tools" / "blender_export_mesh_frames.py"), "--", + "--input", str(anim_path), + "--output-dir", str(out_dir), + "--frame-count", str(frame_count), + "--frame-step", str(frame_step), + "--scale", str(scale), + ] + env = dict(**os.environ) + env["LD_LIBRARY_PATH"] = f"{blender_lib}:{env.get('LD_LIBRARY_PATH','')}" + subprocess.check_call(cmd, env=env) + + +def _render_fixed_mesh_video(poses: List[np.ndarray], rgb_paths: List[Path], intr_list: List[np.ndarray], + mesh_path: Path, output: Path, fps: float) -> None: + render_high_model_to_normal_video( + poses, + [str(p) for p in rgb_paths], + intr_list, + str(mesh_path), + str(output), + fps=fps, + device="cuda", + ) + + +def _render_mesh_sequence_video(poses: List[np.ndarray], rgb_paths: List[Path], intr_list: List[np.ndarray], + mesh_paths: List[Path], output: Path, fps: float) -> None: + import torch + video_frames = [] + glctx = None + for i, pose in enumerate(poses): + mesh = _mesh_from_path(mesh_paths[i]) + mesh_tensors = make_mesh_tensors(mesh, device="cuda") + rgb = cv2.imread(str(rgb_paths[i])) + H, W = rgb.shape[:2] + K = np.asarray(intr_list[i]) + pose_tensor = torch.tensor(pose, dtype=torch.float32, device="cuda").unsqueeze(0) + _, _, normal_map = nvdiffrast_render( + K=K, H=H, W=W, + ob_in_cams=pose_tensor, + glctx=glctx, + context="cuda", + get_normal=True, + mesh_tensors=mesh_tensors, + mesh=None, + projection_mat=None, + bbox2d=None, + output_size=(H, W), + use_light=False, + ) + normal_map = normal_map[0].detach().cpu().numpy() + normal_map = (-normal_map + 1.0) / 2.0 + normal_map = (normal_map * 255).astype(np.uint8) + overlay = cv2.addWeighted(normal_map, 0.7, rgb, 0.3, 0) + video_frames.append(overlay) + + height, width, _ = video_frames[0].shape + fourcc = cv2.VideoWriter_fourcc(*"mp4v") + writer = cv2.VideoWriter(str(output), fourcc, fps, (width, height)) + for frame in video_frames: + writer.write(frame) + writer.release() + + +def _resolve_ffmpeg_bin() -> Optional[str]: + ffmpeg_bin = shutil.which("ffmpeg") + if ffmpeg_bin: + return ffmpeg_bin + try: + import imageio_ffmpeg # type: ignore + except Exception: + return None + try: + return imageio_ffmpeg.get_ffmpeg_exe() + except Exception: + return None + + +def _transcode_h264(input_path: Path, output_path: Path) -> bool: + ffmpeg_bin = _resolve_ffmpeg_bin() + if ffmpeg_bin is None: + print(f"[Warn] ffmpeg unavailable; keep original mp4v file: {input_path}") + return False + + tmp_out = output_path.with_name(output_path.stem + "_h264_tmp.mp4") + cmd = [ + ffmpeg_bin, + "-y", + "-i", str(input_path), + "-c:v", "libx264", + "-pix_fmt", "yuv420p", + "-movflags", "+faststart", + "-an", + str(tmp_out), + ] + try: + subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + tmp_out.replace(output_path) + return True + except Exception as ex: + print(f"[Warn] h264 transcode failed ({input_path}): {ex}") + if tmp_out.exists(): + tmp_out.unlink(missing_ok=True) + return False + + +def _export_video_frames(video_path: Path, frames_dir: Path) -> int: + if not video_path.exists(): + raise FileNotFoundError(video_path) + + frames_dir.mkdir(parents=True, exist_ok=True) + for stale in frames_dir.glob("frame_*.png"): + stale.unlink(missing_ok=True) + + cap = cv2.VideoCapture(str(video_path)) + if not cap.isOpened(): + raise RuntimeError(f"Failed to open video for frame export: {video_path}") + + frame_idx = 0 + while True: + ok, frame = cap.read() + if not ok: + break + frame_path = frames_dir / f"frame_{frame_idx:06d}.png" + if not cv2.imwrite(str(frame_path), frame): + cap.release() + raise RuntimeError(f"Failed to write frame image: {frame_path}") + frame_idx += 1 + + cap.release() + if frame_idx <= 0: + raise RuntimeError(f"No frames exported from video: {video_path}") + return frame_idx + + +def run_deform(args) -> None: + """可被常驻服务进程内调用(模型已载好)。args 为 parse_args() 的 Namespace。""" + run_dir = args.run_dir + name = run_dir.name + obj_root = args.motion_output_root / name / args.object_name + obj_root.mkdir(parents=True, exist_ok=True) + + manifest = args.manifest or (args.motion_output_root / name / "manifest.json") + if not manifest.exists(): + raise FileNotFoundError(manifest) + manifest_data = _load_manifest(manifest) + if args.anim_path is None or args.ref_mesh is None: + for obj in manifest_data.get("objects", []): + if obj.get("name") == args.object_name: + if args.anim_path is None and obj.get("animation") is not None: + args.anim_path = Path(obj.get("animation")) + if args.ref_mesh is None and obj.get("ref_mesh") is not None: + args.ref_mesh = Path(obj.get("ref_mesh")) + break + args.anim_path = _resolve_manifest_path(manifest.parent, args.anim_path) + args.ref_mesh = _resolve_manifest_path(manifest.parent, args.ref_mesh) + if args.ref_mesh is not None: + args.ref_mesh = _prefer_obj_mesh(args.ref_mesh) + _mesh_frames_provided = os.environ.get("OPG_DEFORM_MESH_FRAMES_PROVIDED", "0") == "1" + if args.ref_mesh is None or (args.anim_path is None and not _mesh_frames_provided): + raise RuntimeError("Missing anim_path or ref_mesh for deform object") + + scale_json = _run_recover_scale(args, obj_root) + scale_val = _read_scale(scale_json) + scaled_ref = obj_root / "scaled_ref_mesh.obj" + if not scaled_ref.exists(): + raise FileNotFoundError(scaled_ref) + + video, depths, intrinsics, extrinsics = _load_npz(run_dir) + num_frames = video.shape[0] + summary = _load_summary(args.mask_summary) + mask_dir = _find_mask_dir(summary, args.object_name) + mask_map = _build_frame_map(mask_dir, "frame_*.png") + if not mask_map: + raise FileNotFoundError(f"No masks found under {mask_dir}") + mask_ids = sorted(mask_map.keys()) + mask_stride = max(1, int(args.mask_stride)) + H, W = depths.shape[1], depths.shape[2] + + poses_cam_path = obj_root / "poses_fp_cam.json" + poses_world_path = obj_root / "poses_fp_world.json" + poses_cam: Dict[int, np.ndarray] = {} + if poses_cam_path.exists() and poses_world_path.exists() and not args.force_poses: + poses_cam = {int(k): np.asarray(v, dtype=np.float32) for k, v in json.loads(poses_cam_path.read_text()).items()} + else: + poses_cam = {} + if poses_cam: + pass + elif args.pose_mode == "ref": + ref_mesh = _mesh_from_path(scaled_ref) + est = FoundationPose( + model_pts=ref_mesh.vertices, + model_normals=ref_mesh.vertex_normals, + mesh=ref_mesh, + debug=0, + debug_dir=str(obj_root / "pose_result"), + export_mesh_path=False, + ) + for f in range(0, num_frames, args.frame_step): + mask, _ = _load_mask_aligned(mask_map, mask_ids, f, mask_stride, (H, W)) + if int((mask > 0).sum()) < args.min_mask_pix: + continue + rgb = _to_bgr(video[f]) + depth = depths[f].astype(np.float32) + K = intrinsics[f].astype(np.float32) + pose_cam = est.register(K=K, rgb=rgb, depth=depth, ob_mask=(mask > 0), iteration=args.iter) + poses_cam[f] = pose_cam.astype(np.float32) + elif args.pose_mode == "frame_mesh": + mesh_frames_dir = obj_root / "mesh_frames" + if (not mesh_frames_dir.exists() or args.force_poses) and os.environ.get("OPG_DEFORM_MESH_FRAMES_PROVIDED", "0") != "1": + _export_mesh_frames( + args.anim_path, + mesh_frames_dir, + num_frames, + args.frame_step, + scale_val, + args.blender_bin, + args.blender_lib, + ) + _normalize_mesh_frames_to_ref( + mesh_frames_dir=mesh_frames_dir, + scaled_ref_mesh=scaled_ref, + info_out=obj_root / "mesh_frames_scale_info.json", + ) + mesh_map = _build_frame_map(mesh_frames_dir, "frame_*.obj") + if not mesh_map: + raise FileNotFoundError(f"No mesh frames found in {mesh_frames_dir}") + mesh_ids = sorted(mesh_map.keys()) + scorer = get_cached_scorer() + refiner = get_cached_refiner() + for f in range(0, num_frames, args.frame_step): + mf = f if f in mesh_map else _pick_nearest_frame(f, mesh_ids) + mesh_path = mesh_map[mf] + mesh = _mesh_from_path(mesh_path) + est = FoundationPose( + model_pts=mesh.vertices, + model_normals=mesh.vertex_normals, + mesh=mesh, + scorer=scorer, + refiner=refiner, + debug=0, + debug_dir=str(obj_root / "pose_result"), + export_mesh_path=False, + ) + mask, _ = _load_mask_aligned(mask_map, mask_ids, f, mask_stride, (H, W)) + if int((mask > 0).sum()) < args.min_mask_pix: + continue + rgb = _to_bgr(video[f]) + depth = depths[f].astype(np.float32) + K = intrinsics[f].astype(np.float32) + pose_cam = est.register(K=K, rgb=rgb, depth=depth, ob_mask=(mask > 0), iteration=args.iter) + poses_cam[f] = pose_cam.astype(np.float32) + elif args.pose_mode == "frame_track": + import torch + from scipy.spatial.transform import Rotation as _Rot + from scipy.spatial.transform import Slerp as _Slerp + + mesh_frames_dir = obj_root / "mesh_frames" + if (not mesh_frames_dir.exists() or args.force_poses) and os.environ.get("OPG_DEFORM_MESH_FRAMES_PROVIDED", "0") != "1": + _export_mesh_frames( + args.anim_path, + mesh_frames_dir, + num_frames, + args.frame_step, + scale_val, + args.blender_bin, + args.blender_lib, + ) + _normalize_mesh_frames_to_ref( + mesh_frames_dir=mesh_frames_dir, + scaled_ref_mesh=scaled_ref, + info_out=obj_root / "mesh_frames_scale_info.json", + ) + mesh_map = _build_frame_map(mesh_frames_dir, "frame_*.obj") + if not mesh_map: + raise FileNotFoundError(f"No mesh frames found in {mesh_frames_dir}") + mesh_ids = sorted(mesh_map.keys()) + frame_candidates = list(range(0, num_frames, args.frame_step)) or [0] + + if args.track_anchor_frame >= 0: + anchor_frame = int(max(0, min(num_frames - 1, args.track_anchor_frame))) + else: + anchor_frame = frame_candidates[0] + best_area = -1 + for f in frame_candidates: + mask, _ = _load_mask_aligned(mask_map, mask_ids, f, mask_stride, (H, W)) + area = int((mask > 0).sum()) + if area > best_area: + best_area = area + anchor_frame = f + + SIL_OK = 0.30 + SIL_MIN = 0.12 + + _est_holder: Dict[str, FoundationPose] = {} + + def _get_est() -> FoundationPose: + if "est" not in _est_holder: + mf0 = anchor_frame if anchor_frame in mesh_map else _pick_nearest_frame(anchor_frame, mesh_ids) + m0 = _mesh_from_path(mesh_map[mf0]) + _est_holder["est"] = FoundationPose( + model_pts=m0.vertices, + model_normals=m0.vertex_normals, + mesh=m0, + scorer=get_cached_scorer(), + refiner=get_cached_refiner(), + debug=0, + debug_dir=str(obj_root / "pose_result"), + export_mesh_path=False, + ) + return _est_holder["est"] + quality_by_frame: Dict[int, dict] = {} + verts_by_frame: Dict[int, np.ndarray] = {} + faces_by_frame: Dict[int, np.ndarray] = {} + + def _bbox_iou(pose, verts, K, mask_b): + P = (pose[:3, :3] @ verts.T).T + pose[:3, 3] + if (P[:, 2] <= 1e-6).all(): + return 0.0, 1e9 + uv = (K @ P.T).T + uv = uv[:, :2] / np.clip(uv[:, 2:3], 1e-6, None) + ys, xs = np.where(mask_b) + if len(xs) == 0: + return 0.0, 1e9 + pb = [uv[:, 0].min(), uv[:, 1].min(), uv[:, 0].max(), uv[:, 1].max()] + mb = [xs.min(), ys.min(), xs.max(), ys.max()] + ix1, iy1 = max(pb[0], mb[0]), max(pb[1], mb[1]) + ix2, iy2 = min(pb[2], mb[2]), min(pb[3], mb[3]) + inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1) + a1 = max(0.0, (pb[2] - pb[0]) * (pb[3] - pb[1])) + a2 = max(0.0, (mb[2] - mb[0]) * (mb[3] - mb[1])) + iou = inter / max(a1 + a2 - inter, 1e-6) + pc = uv.mean(0) + mc = np.array([xs.mean(), ys.mean()]) + return float(iou), float(np.linalg.norm(pc - mc)) + + DS = 4 + + def _align_translation(pose, verts, K, mask_b, iters=3): + T = pose.copy().astype(np.float64) + ys, xs = np.where(mask_b) + if len(xs) < 16: + return pose, None + mw, mh = float(xs.max() - xs.min()), float(ys.max() - ys.min()) + if mw <= 2 or mh <= 2: + return pose, None + mc = np.array([(xs.min() + xs.max()) / 2.0, (ys.min() + ys.max()) / 2.0]) + fx, fy = float(K[0, 0]), float(K[1, 1]) + s_total = 1.0 + for _ in range(iters): + P = (T[:3, :3] @ verts.T).T + T[:3, 3] + uv = (K @ P.T).T + uv = uv[:, :2] / np.clip(uv[:, 2:3], 1e-6, None) + pw = float(uv[:, 0].max() - uv[:, 0].min()) + ph = float(uv[:, 1].max() - uv[:, 1].min()) + if pw <= 2 or ph <= 2: + return pose, None + s = float(np.clip(np.sqrt((pw * ph) / (mw * mh)), 0.5, 2.0)) + T[:3, 3] *= s + s_total *= s + P = (T[:3, :3] @ verts.T).T + T[:3, 3] + uv = (K @ P.T).T + uv = uv[:, :2] / np.clip(uv[:, 2:3], 1e-6, None) + pc = np.array([ + (uv[:, 0].min() + uv[:, 0].max()) / 2.0, + (uv[:, 1].min() + uv[:, 1].max()) / 2.0, + ]) + Z = float(T[2, 3]) + T[0, 3] += (mc[0] - pc[0]) * Z / fx + T[1, 3] += (mc[1] - pc[1]) * Z / fy + return T.astype(np.float32), s_total + + def _sil_iou_lr(T, verts, faces, K, m_small): + P = (T[:3, :3] @ verts.T).T + T[:3, 3] + uv = (K @ P.T).T + uv = uv[:, :2] / np.clip(uv[:, 2:3], 1e-6, None) / DS + sil = np.zeros(m_small.shape, np.uint8) + cv2.fillPoly(sil, [t for t in uv[faces].astype(np.int32)], 1) + inter = int((sil & m_small).sum()) + union = int((sil | m_small).sum()) + return inter / max(union, 1) + + _frame_cache: Dict[int, tuple] = {} + + def _frame_data(f): + if f not in _frame_cache: + mf = f if f in mesh_map else _pick_nearest_frame(f, mesh_ids) + mesh_f = _mesh_from_path(mesh_map[mf]) + verts = np.asarray(mesh_f.vertices) + faces = np.asarray(mesh_f.faces) + verts_by_frame[f] = verts + faces_by_frame[f] = faces + mask, _ = _load_mask_aligned(mask_map, mask_ids, f, mask_stride, (H, W)) + mask_b = mask > 0 + m_small = cv2.resize(mask_b.astype(np.uint8), (W // DS, H // DS), interpolation=cv2.INTER_NEAREST) + K = intrinsics[f].astype(np.float32) + _frame_cache[f] = (mf, verts, faces, mask_b, m_small, K) + return _frame_cache[f] + + def _sil_refine(f, T_in, span, step): + """旋转局部搜索:每个候选重对齐平移,按低分辨率轮廓 IoU 取优(不使用深度)。 + 返回 (best_T, best_iou, 全部候选[(iou,T),...]),供外观重排使用。""" + mf, verts, faces, mask_b, m_small, K = _frame_data(f) + T_base, s0 = _align_translation(T_in.astype(np.float32), verts, K, mask_b) + if s0 is None: + return T_in.astype(np.float32), -1.0, [] + best_T = T_base.astype(np.float32) + best_i = _sil_iou_lr(best_T, verts, faces, K, m_small) + cands = [(best_i, best_T)] + R0 = T_base[:3, :3].copy() + angles = np.arange(-span, span + 1e-6, step) + for ax in angles: + for ay in angles: + for az in angles: + if ax == 0 and ay == 0 and az == 0: + continue + dR = _Rot.from_euler('xyz', [ax, ay, az], degrees=True).as_matrix() + Tc = T_base.copy().astype(np.float64) + Tc[:3, :3] = dR @ R0 + Tc, s = _align_translation(Tc.astype(np.float32), verts, K, mask_b) + if s is None: + continue + i = _sil_iou_lr(Tc, verts, faces, K, m_small) + cands.append((i, Tc.astype(np.float32))) + if i > best_i: + best_i, best_T = i, Tc.astype(np.float32) + return best_T, best_i, cands + + APP_RESCORE = True + APP_TOPK = 6 + APP_SIL_TOL = 0.05 + _r3d: Dict[str, object] = {} + + def _appearance_scores(f, Ts): + try: + if "render" not in _r3d: + from oneposeviagen.locate.fit_object_scale import render_image as _ri + _r3d["render"] = _ri + mp = obj_root / "mid_files" / "scaled_mesh.obj" + _r3d["mesh"] = str(mp if mp.exists() else scaled_ref) + mf, verts, faces, mask_b, m_small, K = _frame_data(f) + fx = float(K[0, 0]) + fov = 2.0 * np.arctan(0.5 * W / fx) + Trs = [] + for T in Ts: + Tr = np.eye(4, dtype=np.float64) + Tr[:3, :3] = np.linalg.inv(T[:3, :3].astype(np.float64)) + Tr[3, :3] = T[:3, 3].astype(np.float64) + Tr[:, :2] = -Tr[:, :2] + Trs.append(Tr) + colors, _ = _r3d["render"](_r3d["mesh"], np.stack(Trs), W, H, fov, "cuda") + if colors.ndim == 3: + colors = colors[None] + ys, xs = np.where(mask_b) + x1, x2, y1, y2 = xs.min(), xs.max() + 1, ys.min(), ys.max() + 1 + real = cv2.cvtColor(_to_bgr(video[f]), cv2.COLOR_BGR2GRAY)[y1:y2, x1:x2].astype(np.float32) + real = cv2.resize(real, (128, 128)) + mk = cv2.resize(mask_b[y1:y2, x1:x2].astype(np.uint8), (128, 128)) > 0 + b = real[mk] + out = [] + for c in colors: + g = cv2.cvtColor(c, cv2.COLOR_RGB2GRAY)[y1:y2, x1:x2].astype(np.float32) + g = cv2.resize(g, (128, 128)) + a = g[mk] + if a.std() < 1e-3 or b.std() < 1e-3: + out.append(-1.0) + continue + out.append(float(np.corrcoef(a, b)[0, 1])) + return out + except Exception as ex: # noqa: BLE001 + print(f"[frame_track] appearance scoring failed at frame {f}: {ex}") + return None + + APP_MARGIN = 0.06 + APP_ROT_PEN = 0.004 + + def _rot_deg_pair(a, b): + R = a[:3, :3].T @ b[:3, :3] + return float(np.degrees(np.arccos(np.clip((np.trace(R) - 1) / 2, -1.0, 1.0)))) + + def _app_rerank(f, best_T, best_i, cands, rec, T_init=None): + """在轮廓近优候选内用外观消歧;保守策略:优势显著才推翻轮廓第一名, + 并惩罚偏离传播初始位姿的旋转(光照差异可能愚弄 NCC,连续性兜底)。""" + if not APP_RESCORE or not cands: + return best_T, best_i + pool = [(i, T) for i, T in sorted(cands, key=lambda x: -x[0])[:APP_TOPK * 3] + if i >= best_i - APP_SIL_TOL][:APP_TOPK] + if len(pool) < 2: + return best_T, best_i + scores = _appearance_scores(f, [T for _, T in pool]) + if scores is None: + return best_T, best_i + adj = [] + for s, (i, T) in zip(scores, pool): + pen = APP_ROT_PEN * _rot_deg_pair(T, T_init) if T_init is not None else 0.0 + adj.append(float(s) - pen) + j = int(np.argmax(adj)) + rec["app_score"] = round(float(scores[j]), 3) + if j == 0 or adj[j] < adj[0] + APP_MARGIN: + rec["app_rank_changed"] = False + return pool[0][1], pool[0][0] + rec["app_rank_changed"] = True + return pool[j][1], pool[j][0] + + def _register_fallback(f, mask_b): + """兜底:FoundationPose register(mask 门控输入),结果仍交给轮廓搜索评估。""" + est = _get_est() + mf, verts, faces, _, _, K = _frame_data(f) + mesh_f = _mesh_from_path(mesh_map[mf]) + est.reset_object(model_pts=mesh_f.vertices, model_normals=mesh_f.vertex_normals, mesh=mesh_f) + rgb = _to_bgr(video[f]).copy() + depth = depths[f].astype(np.float32).copy() + rgb[~mask_b] = 0 + depth[~mask_b] = 0 + return np.asarray( + est.register(K=K, rgb=rgb, depth=depth, ob_mask=mask_b, iteration=args.iter) + ).reshape(4, 4) + + PNP_EVERY = 5 + _pnp_ctx: Dict[str, object] = {} + + def _pnp_keyframe_refine(f, T_cur): + try: + if "ready" not in _pnp_ctx: + from oneposeviagen.locate.fit_object_scale import render_image as _ri + from oneposeviagen.locate.fit_object_scale import project_2d_to_3d as _p23 + from oneposeviagen.locate.match_pairs import image_pair_matching as _ipm + _pnp_ctx["render"] = _ri + _pnp_ctx["p23"] = _p23 + _pnp_ctx["match"] = _ipm + mp = obj_root / "mid_files" / "scaled_mesh.obj" + _pnp_ctx["mesh_path"] = str(mp if mp.exists() else scaled_ref) + _pnp_ctx["ready"] = True + mf, verts, faces, mask_b, m_small, K = _frame_data(f) + fx = float(K[0, 0]) + fov = 2.0 * np.arctan(0.5 * W / fx) + Tr = np.eye(4, dtype=np.float64) + Tr[:3, :3] = np.linalg.inv(T_cur[:3, :3].astype(np.float64)) + Tr[3, :3] = T_cur[:3, 3].astype(np.float64) + Tr[:, :2] = -Tr[:, :2] + color, depth_r = _pnp_ctx["render"](_pnp_ctx["mesh_path"], Tr, W, H, fov, "cuda") + color = color[0] if color.ndim == 4 else color + gray_r = cv2.cvtColor(color, cv2.COLOR_RGB2GRAY) + real = _to_bgr(video[f]).copy() + real[~mask_b] = 0 + gray_q = cv2.cvtColor(real, cv2.COLOR_BGR2GRAY) + + def _crop_zoom(gray, bbox, size=512): + x1, y1, x2, y2 = bbox + crop = gray[y1:y2, x1:x2] + if crop.size == 0: + return None, None + s = size / max(crop.shape) + out = cv2.resize(crop, (int(round(crop.shape[1] * s)), int(round(crop.shape[0] * s)))) + return out, (x1, y1, 1.0 / s) + + def _bbox_of(m, margin=0.12): + ys, xs = np.where(m > 0) + if len(xs) < 8: + return None + x1, x2, y1, y2 = xs.min(), xs.max(), ys.min(), ys.max() + mx, my = int((x2 - x1) * margin), int((y2 - y1) * margin) + return (max(0, x1 - mx), max(0, y1 - my), min(W, x2 + mx), min(H, y2 + my)) + + bb_q = _bbox_of(mask_b.astype(np.uint8)) + bb_r = _bbox_of((gray_r > 10).astype(np.uint8)) + if bb_q is None or bb_r is None: + return None, 0 + gq, back_q = _crop_zoom(gray_q, bb_q) + gr, back_r = _crop_zoom(gray_r, bb_r) + if gq is None or gr is None: + return None, 0 + out_tmp = obj_root / "pose_result" / "pnp_keyframes" + out_tmp.mkdir(parents=True, exist_ok=True) + _, match_result = _pnp_ctx["match"]( + [gr], gq, str(out_tmp), resize=[-1], viz=False, save=False, + keypoint_threshold=0.001, match_threshold=0.01, + ) + matches = match_result["matches"] + kp0 = match_result["keypoints0"][matches > -1] + kp1 = match_result["keypoints1"][matches[matches > -1]] + if len(kp0) < 10: + return None, int(len(kp0)) + kp0 = kp0 * back_r[2] + np.array([back_r[0], back_r[1]]) + kp1 = kp1 * back_q[2] + np.array([back_q[0], back_q[1]]) + K_r = np.array([[fx, 0, W / 2], [0, fx, H / 2], [0, 0, 1]], dtype=np.float64) + world_pts, valid = _pnp_ctx["p23"](kp0, depth_r, K_r, Tr) + kp1 = kp1[valid] + if len(world_pts) < 10: + return None, int(len(world_pts)) + okf, rvec, tvec, inl = cv2.solvePnPRansac( + np.float32(world_pts), np.float32(kp1), np.float32(K), + distCoeffs=np.zeros(4, np.float32), iterationsCount=300, + reprojectionError=6.0, confidence=0.99, flags=cv2.SOLVEPNP_ITERATIVE, + ) + if not okf or inl is None or len(inl) < 10: + return None, 0 if inl is None else int(len(inl)) + Rm, _ = cv2.Rodrigues(rvec) + Tn = np.eye(4, dtype=np.float32) + Tn[:3, :3] = Rm + Tn[:3, 3] = tvec.squeeze() + return Tn, int(len(inl)) + except Exception as ex: # noqa: BLE001 + print(f"[frame_track] pnp keyframe failed at frame {f}: {ex}") + return None, 0 + + def _maybe_pnp(f, p, rec): + """传播路径上的关键帧 PnP 矫正;返回(可能被矫正的)位姿。""" + if p is None or rec.get("status") not in ("ok", "low_quality"): + return p + if (f - anchor_frame) % (PNP_EVERY * args.frame_step) != 0 or f == anchor_frame: + return p + Tn, ninl = _pnp_keyframe_refine(f, p) + if Tn is None: + rec["pnp_keyframe"] = {"inliers": ninl, "applied": False} + return p + T2, i2, _ = _sil_refine(f, Tn, span=6, step=3) + cur = rec.get("iou_sil") or 0.0 + applied = i2 >= cur - 0.02 + rec["pnp_keyframe"] = {"inliers": ninl, "iou_sil": round(max(i2, 0.0), 3), "applied": bool(applied)} + if applied: + rec["iou_sil"] = round(max(i2, 0.0), 3) + rec["status"] = "ok" if i2 >= SIL_OK else "low_quality" + return T2 + return p + + def _solve_frame(f, T_init, span, step, source): + mf, verts, faces, mask_b, m_small, K = _frame_data(f) + npix = int(mask_b.sum()) + rec = {"frame": int(f), "mesh_frame": int(mf), "mask_pix": npix, "source": source} + if npix < args.min_mask_pix: + rec.update({"status": "no_mask", "iou_sil": None}) + return (T_init.astype(np.float32) if T_init is not None else None), rec + best_T, best_i = None, -1.0 + if T_init is not None: + best_T, best_i, _ = _sil_refine(f, T_init, span, step) + if best_i >= 0: + best_T, i2, cands2 = _sil_refine(f, best_T, span=4, step=2) + best_i = max(best_i, i2) + best_T, best_i = _app_rerank(f, best_T, best_i, cands2, rec, T_init=T_init) + if best_i < SIL_MIN: + try: + T_r, i_r, _ = _sil_refine(f, _register_fallback(f, mask_b), span=12, step=6) + if i_r > best_i: + best_T, best_i = T_r, i_r + rec["source"] = f"{source}+register_fallback" + except Exception as ex: # noqa: BLE001 + print(f"[frame_track] register fallback failed at frame {f}: {ex}") + rec["iou_sil"] = round(max(best_i, 0.0), 3) + if best_T is None or best_i < SIL_MIN: + rec["status"] = "invalid" + return None, rec + rec["status"] = "ok" if best_i >= SIL_OK else "low_quality" + return best_T.astype(np.float32), rec + + pnp_init, pnp_frame = None, -1 + pnp_json = obj_root / "pnp_anchor_pose.json" + if pnp_json.exists(): + try: + pdata = json.loads(pnp_json.read_text()) + pnp_frame = int(pdata.get("anchor_run_frame", -1)) + pnp_init = np.asarray(pdata["pose_cam"], dtype=np.float32).reshape(4, 4) + except Exception as ex: # noqa: BLE001 + print(f"[frame_track] ignore pnp_anchor_pose.json: {ex}") + + def _solve_anchor_at(c): + init = pnp_init if c == pnp_frame else None + return _solve_frame(c, init, span=12, step=6, source="pnp" if init is not None else "none") + + def _propagate(start_frame, start_pose, lo, hi): + """从 start_frame 向两侧传播求解,覆盖 [lo, hi](含端点,不含 start 本身)。""" + prev = start_pose + for f in range(start_frame + args.frame_step, hi + 1, args.frame_step): + p, rec = _solve_frame(f, prev, span=12, step=6, source="propagate") + p = _maybe_pnp(f, p, rec) + quality_by_frame[f] = rec + if p is not None: + poses_cam[f] = p + if rec.get("status") != "no_mask": + prev = p + prev = start_pose + for f in range(start_frame - args.frame_step, lo - 1, -args.frame_step): + p, rec = _solve_frame(f, prev, span=12, step=6, source="propagate") + p = _maybe_pnp(f, p, rec) + quality_by_frame[f] = rec + if p is not None: + poses_cam[f] = p + if rec.get("status") != "no_mask": + prev = p + + anchor2_frame, pose_a2, rec_a2 = -1, None, None + if args.track_anchor_frame >= 0: + pose_a, rec_a = _solve_anchor_at(anchor_frame) + else: + area_list = [] + for f in frame_candidates: + mask, _ = _load_mask_aligned(mask_map, mask_ids, f, mask_stride, (H, W)) + area_list.append((int((mask > 0).sum()), f)) + seg = max(1, num_frames // 3) + cand_anchors = [] + for lo_s in range(0, num_frames, seg): + seg_list = [(a, f) for a, f in area_list if lo_s <= f < lo_s + seg and a >= args.min_mask_pix] + if seg_list: + cand_anchors.append(max(seg_list)[1]) + top_global = max(area_list)[1] + for extra in (top_global, pnp_frame): + if extra >= 0 and extra not in cand_anchors: + cand_anchors.append(extra) + trials = [] + for c in sorted(set(cand_anchors)): + p, r = _solve_anchor_at(c) + trials.append(((r.get("iou_sil") or -1.0), c, p, r)) + print(f"[frame_track] {args.object_name}: anchor candidate {c} iou_sil={r.get('iou_sil')}") + trials.sort(key=lambda x: -x[0]) + _, anchor_frame, pose_a, rec_a = trials[0] + for sc, c, p, r in trials: + if p is not None and "pnp" in str(r.get("source")) and sc >= trials[0][0] - 0.10: + anchor_frame, pose_a, rec_a = c, p, r + break + for sc, c, p, r in trials: + if c != anchor_frame and p is not None and sc >= SIL_OK and abs(c - anchor_frame) >= num_frames // 3: + anchor2_frame, pose_a2, rec_a2 = c, p, r + break + + rec_a["anchor"] = True + quality_by_frame[anchor_frame] = rec_a + if pose_a is None: + raise RuntimeError( + f"frame_track: anchor frame {anchor_frame} failed (iou_sil={rec_a.get('iou_sil')})" + ) + poses_cam[anchor_frame] = pose_a + print( + f"[frame_track] {args.object_name}: anchor={anchor_frame} " + f"iou_sil={rec_a.get('iou_sil')} source={rec_a.get('source')}" + ) + + _propagate(anchor_frame, pose_a, 0, num_frames - 1) + + if anchor2_frame >= 0 and pose_a2 is not None: + prop_at_a2 = poses_cam.get(anchor2_frame) + dd = _rot_deg_pair(prop_at_a2, pose_a2) if prop_at_a2 is not None else 999.0 + if dd <= 30.0: + rec_a2["anchor"] = True + quality_by_frame[anchor2_frame] = rec_a2 + poses_cam[anchor2_frame] = pose_a2 + mid = (anchor_frame + anchor2_frame) // 2 + print(f"[frame_track] {args.object_name}: dual-anchor {anchor_frame}/{anchor2_frame} (rot_diff={dd:.1f}°), re-solve far half") + if anchor2_frame > anchor_frame: + _propagate(anchor2_frame, pose_a2, mid + 1, num_frames - 1) + else: + _propagate(anchor2_frame, pose_a2, 0, mid) + else: + print(f"[frame_track] {args.object_name}: reject secondary anchor {anchor2_frame} (rot_diff={dd:.1f}° vs trusted chain)") + + evidence_ids = [ + f for f in sorted(poses_cam.keys()) + if quality_by_frame.get(f, {}).get("status") in ("ok", "low_quality") and f in verts_by_frame + ] + for f in evidence_ids: + mask, _ = _load_mask_aligned(mask_map, mask_ids, f, mask_stride, (H, W)) + mask_b = mask > 0 + K = intrinsics[f].astype(np.float32) + aligned, s_tot = _align_translation(poses_cam[f], verts_by_frame[f], K, mask_b) + if s_tot is None: + continue + poses_cam[f] = aligned + iou_a, cerr_a = _bbox_iou(aligned, verts_by_frame[f], K, mask_b) + quality_by_frame[f]["iou_aligned"] = round(iou_a, 3) + quality_by_frame[f]["center_err_aligned"] = round(cerr_a, 1) + quality_by_frame[f]["z_scale_corr"] = round(s_tot, 3) + + for f in sorted(poses_cam.keys()): + if quality_by_frame.get(f, {}).get("status") != "no_mask" or not evidence_ids: + continue + lo = max((v for v in evidence_ids if v < f), default=None) + hi = min((v for v in evidence_ids if v > f), default=None) + if lo is None and hi is None: + continue + if lo is None or hi is None: + t_ref = poses_cam[lo if hi is None else hi][:3, 3] + poses_cam[f][:3, 3] = t_ref + else: + t = (f - lo) / max(hi - lo, 1) + poses_cam[f][:3, 3] = (1 - t) * poses_cam[lo][:3, 3] + t * poses_cam[hi][:3, 3] + quality_by_frame[f]["translation"] = "interp_from_aligned" + + valid_ids = sorted(poses_cam.keys()) + for f in frame_candidates: + if f in poses_cam or not valid_ids: + continue + lo = max((v for v in valid_ids if v < f), default=None) + hi = min((v for v in valid_ids if v > f), default=None) + if lo is None and hi is None: + continue + if lo is None or hi is None: + poses_cam[f] = poses_cam[lo if hi is None else hi].copy() + else: + t = (f - lo) / max(hi - lo, 1) + Ta, Tb = poses_cam[lo], poses_cam[hi] + sl = _Slerp([0, 1], _Rot.from_matrix(np.stack([Ta[:3, :3], Tb[:3, :3]]))) + M = np.eye(4, dtype=np.float32) + M[:3, :3] = sl([t]).as_matrix()[0] + M[:3, 3] = (1 - t) * Ta[:3, 3] + t * Tb[:3, 3] + poses_cam[f] = M + if f in quality_by_frame: + quality_by_frame[f]["filled"] = "interp" + + recs = [quality_by_frame[k] for k in sorted(quality_by_frame)] + summary = { + "ok": sum(1 for r in recs if r.get("status") == "ok"), + "low_quality": sum(1 for r in recs if r.get("status") == "low_quality"), + "invalid": sum(1 for r in recs if r.get("status") == "invalid"), + "no_mask": sum(1 for r in recs if r.get("status") == "no_mask"), + "register_fallbacks": sum(1 for r in recs if "register_fallback" in str(r.get("source"))), + } + qpath = obj_root / "pose_result" / "pose_quality.json" + qpath.parent.mkdir(parents=True, exist_ok=True) + qpath.write_text(json.dumps({ + "mode": "frame_track", + "anchor_frame": int(anchor_frame), + "sil_ok": SIL_OK, + "sil_min": SIL_MIN, + "summary": summary, + "frames": recs, + }, indent=2)) + print(f"[frame_track] {args.object_name}: {summary} -> {qpath}") + else: + mesh_frames_dir = obj_root / "mesh_frames" + if (not mesh_frames_dir.exists() or args.force_poses) and os.environ.get("OPG_DEFORM_MESH_FRAMES_PROVIDED", "0") != "1": + _export_mesh_frames( + args.anim_path, + mesh_frames_dir, + num_frames, + args.frame_step, + scale_val, + args.blender_bin, + args.blender_lib, + ) + _normalize_mesh_frames_to_ref( + mesh_frames_dir=mesh_frames_dir, + scaled_ref_mesh=scaled_ref, + info_out=obj_root / "mesh_frames_scale_info.json", + ) + mesh_map = _build_frame_map(mesh_frames_dir, "frame_*.obj") + if not mesh_map: + raise FileNotFoundError(f"No mesh frames found in {mesh_frames_dir}") + mesh_ids = sorted(mesh_map.keys()) + frame_candidates = list(range(0, num_frames, args.frame_step)) or [0] + + if args.track_anchor_frame >= 0: + anchor_frame = int(max(0, min(num_frames - 1, args.track_anchor_frame))) + else: + anchor_frame = frame_candidates[0] + best_area = -1 + for f in frame_candidates: + mask, _ = _load_mask_aligned(mask_map, mask_ids, f, mask_stride, (H, W)) + area = int((mask > 0).sum()) + if area > best_area: + best_area = area + anchor_frame = f + + anchor_mesh_frame = anchor_frame if anchor_frame in mesh_map else _pick_nearest_frame(anchor_frame, mesh_ids) + anchor_mesh = _mesh_from_path(mesh_map[anchor_mesh_frame]) + scorer = get_cached_scorer() + refiner = get_cached_refiner() + + def _make_estimator() -> FoundationPose: + return FoundationPose( + model_pts=anchor_mesh.vertices, + model_normals=anchor_mesh.vertex_normals, + mesh=anchor_mesh, + scorer=scorer, + refiner=refiner, + debug=0, + debug_dir=str(obj_root / "pose_result"), + export_mesh_path=False, + ) + + def _register_at_frame(est: FoundationPose, frame_id: int) -> np.ndarray: + mask, mask_f = _load_mask_aligned(mask_map, mask_ids, frame_id, mask_stride, (H, W)) + area = int((mask > 0).sum()) + if area < args.min_mask_pix: + print( + f"[Warn] {args.object_name}: low mask area at run frame {frame_id} " + f"(mask frame {mask_f}, area={area})" + ) + rgb = _to_bgr(video[frame_id]) + depth = depths[frame_id].astype(np.float32) + K = intrinsics[frame_id].astype(np.float32) + pose = est.register(K=K, rgb=rgb, depth=depth, ob_mask=(mask > 0), iteration=args.iter) + return pose.astype(np.float32) + + print( + f"[single_track] {args.object_name}: anchor={anchor_frame}, " + f"mesh_frame={anchor_mesh_frame}, mask_stride={mask_stride}" + ) + + est_fwd = _make_estimator() + anchor_pose = _register_at_frame(est_fwd, anchor_frame) + poses_cam[anchor_frame] = anchor_pose + + prev_pose = anchor_pose + for f in range(anchor_frame + args.frame_step, num_frames, args.frame_step): + rgb = _to_bgr(video[f]) + depth = depths[f].astype(np.float32) + K = intrinsics[f].astype(np.float32) + try: + pose_cam = est_fwd.track_one(rgb=rgb, depth=depth, K=K, iteration=args.iter) + pose_cam = np.asarray(pose_cam, dtype=np.float32) + except Exception as ex: + mask, mask_f = _load_mask_aligned(mask_map, mask_ids, f, mask_stride, (H, W)) + area = int((mask > 0).sum()) + if area >= args.min_mask_pix: + try: + pose_cam = est_fwd.register(K=K, rgb=rgb, depth=depth, ob_mask=(mask > 0), iteration=args.iter) + pose_cam = np.asarray(pose_cam, dtype=np.float32) + print(f"[single_track] {args.object_name}: re-register frame {f} (mask frame {mask_f})") + except Exception: + print(f"[Warn] {args.object_name}: track/register failed at frame {f}: {ex}") + pose_cam = prev_pose + else: + print( + f"[Warn] {args.object_name}: track failed at frame {f} and mask too small " + f"(mask frame {mask_f}, area={area}); keep previous pose" + ) + pose_cam = prev_pose + poses_cam[f] = pose_cam.astype(np.float32) + prev_pose = poses_cam[f] + + if anchor_frame - args.frame_step >= 0: + est_bwd = _make_estimator() + _ = _register_at_frame(est_bwd, anchor_frame) + prev_pose = anchor_pose + for f in range(anchor_frame - args.frame_step, -1, -args.frame_step): + rgb = _to_bgr(video[f]) + depth = depths[f].astype(np.float32) + K = intrinsics[f].astype(np.float32) + try: + pose_cam = est_bwd.track_one(rgb=rgb, depth=depth, K=K, iteration=args.iter) + pose_cam = np.asarray(pose_cam, dtype=np.float32) + except Exception as ex: + mask, mask_f = _load_mask_aligned(mask_map, mask_ids, f, mask_stride, (H, W)) + area = int((mask > 0).sum()) + if area >= args.min_mask_pix: + try: + pose_cam = est_bwd.register( + K=K, + rgb=rgb, + depth=depth, + ob_mask=(mask > 0), + iteration=args.iter, + ) + pose_cam = np.asarray(pose_cam, dtype=np.float32) + print(f"[single_track] {args.object_name}: re-register frame {f} (mask frame {mask_f})") + except Exception: + print(f"[Warn] {args.object_name}: backward track/register failed at frame {f}: {ex}") + pose_cam = prev_pose + else: + print( + f"[Warn] {args.object_name}: backward track failed at frame {f} and mask too small " + f"(mask frame {mask_f}, area={area}); keep previous pose" + ) + pose_cam = prev_pose + poses_cam[f] = pose_cam.astype(np.float32) + prev_pose = poses_cam[f] + + poses_cam = _fill_missing(poses_cam, num_frames) + poses_world: Dict[int, np.ndarray] = {} + for f, pose_cam in poses_cam.items(): + poses_world[f] = (np.linalg.inv(extrinsics[f]) @ pose_cam).astype(np.float32) + + poses_cam_json = {str(k): v.tolist() for k, v in poses_cam.items()} + poses_world_json = {str(k): v.tolist() for k, v in poses_world.items()} + + poses_cam_path.write_text(json.dumps(poses_cam_json, indent=2)) + poses_world_path.write_text(json.dumps(poses_world_json, indent=2)) + + pose_dir = obj_root / "pose_result" + pose_dir.mkdir(parents=True, exist_ok=True) + (pose_dir / "poses_fp_cam.json").write_text(json.dumps(poses_cam_json, indent=2)) + (pose_dir / "poses_fp_world.json").write_text(json.dumps(poses_world_json, indent=2)) + (pose_dir / "poses.json").write_text(json.dumps(poses_cam_json, indent=2)) + (pose_dir / "poses_world.json").write_text(json.dumps(poses_world_json, indent=2)) + + if args.render_video: + fps = args.fps + if fps is None and args.mask_summary.exists(): + try: + fps = float(json.loads(args.mask_summary.read_text()).get("fps", 10.0)) + except Exception: + fps = 10.0 + if fps is None: + fps = 10.0 + + rgb_paths = [] + rgb_dir = run_dir / "rgb" + for ext in ("*.jpg", "*.png", "*.jpeg"): + rgb_paths.extend(rgb_dir.glob(ext)) + rgb_paths = sorted(rgb_paths, key=lambda p: int(p.stem)) + + intr_list = [intrinsics[min(i, len(intrinsics) - 1)] for i in range(num_frames)] + poses_list = [poses_cam[i] for i in range(num_frames)] + + out_video = pose_dir / "normal_video_converted.mp4" + raw_video = pose_dir / "normal_video_raw.mp4" + if args.pose_mode == "ref": + _render_fixed_mesh_video(poses_list, rgb_paths, intr_list, scaled_ref, raw_video, fps) + else: + mesh_frames_dir = obj_root / "mesh_frames" + available = sorted([int(p.stem.split("_")[-1]) for p in mesh_frames_dir.glob("frame_*.obj")]) + if not available: + raise RuntimeError("No mesh frames found for rendering.") + def _nearest_frame(fid: int) -> int: + return min(available, key=lambda x: abs(x - fid)) + mesh_paths = [mesh_frames_dir / f"frame_{_nearest_frame(i):06d}.obj" for i in range(num_frames)] + _render_mesh_sequence_video(poses_list, rgb_paths, intr_list, mesh_paths, raw_video, fps) + + if _transcode_h264(raw_video, out_video): + raw_video.unlink(missing_ok=True) + elif raw_video != out_video: + raw_video.replace(out_video) + if args.export_video_frames: + frames_dir = pose_dir / "normal_video_frames" + frame_count = _export_video_frames(out_video, frames_dir) + print(f"[OK] Wrote pose preview frames: {frames_dir} ({frame_count} frames)") + print(f"[OK] Wrote: {out_video}") + + +def main() -> None: + run_deform(parse_args()) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/export_combined_pointcloud.py b/OVOW/engine/tools/export_combined_pointcloud.py new file mode 100644 index 0000000000000000000000000000000000000000..a7eb9636afd5d202d6574337a9667f1c3c88fcb6 --- /dev/null +++ b/OVOW/engine/tools/export_combined_pointcloud.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python +""" +Combine VGGT scene points with the recovered object mesh in a single point cloud. + +Usage: + python export_combined_pointcloud.py \ + --session OnePoseviaGen/temp_local/session_xxxxxxxx \ + --frame-id 0 \ + --output combined.ply + +The script: +1. Loads VGGT outputs (result.npz) for the specified session. +2. Reads FoundationPose results (pose_result/poses.json). +3. Finds the high-resolution mesh generated by OnePoseviaGen. +4. Transforms the mesh into the world coordinate frame for the chosen frame. +5. Back-projects VGGT depth maps into world coordinates to obtain a scene point cloud. +6. Samples both mesh and scene points, merges them, and exports a .ply file. +""" + +import argparse +import glob +import json +from pathlib import Path + +import numpy as np +import trimesh + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Export combined scene + object point cloud.") + parser.add_argument( + "--session", + type=Path, + required=True, + help="Path to temp session folder, e.g. OnePoseviaGen/temp_local/session_xxxxxxxx", + ) + parser.add_argument( + "--frame-id", + type=int, + default=0, + help="Frame index to align the mesh against (default: 0).", + ) + parser.add_argument( + "--mesh-file", + type=Path, + default=None, + help="Optional explicit mesh path. Defaults to *_high_mesh.obj under model/middle_file.", + ) + parser.add_argument( + "--mesh-points", + type=int, + default=20000, + help="Number of points to sample from the mesh surface.", + ) + parser.add_argument( + "--scene-step", + type=int, + default=4, + help="Pixel stride when back-projecting depth maps (>=1).", + ) + parser.add_argument( + "--scene-frame", + type=int, + default=-1, + help="Frame index for scene depth. -1 = use all frames.", + ) + parser.add_argument( + "--output", + type=Path, + default=None, + help="Output PLY path. Defaults to /combined_cloud_frame_.ply", + ) + return parser.parse_args() + + +def find_high_mesh(session: Path) -> Path: + if not (session / "model").exists(): + raise FileNotFoundError(f"No model folder found under {session}") + candidates = sorted( + glob.glob(str(session / "model" / "middle_file" / "*_high_mesh.obj")) + ) + if not candidates: + scaled = session / "model" / "mid_files" / "scaled_mesh.obj" + if not scaled.exists(): + raise FileNotFoundError( + f"Could not find *_high_mesh.obj or scaled_mesh.obj under {session}" + ) + return scaled + return Path(candidates[-1]) + + +def load_pose_matrix(poses_json: Path, frame_id: int) -> np.ndarray: + with open(poses_json, "r") as f: + poses = json.load(f) + key = str(frame_id) + if key not in poses: + raise KeyError(f"Frame {frame_id} not found in {poses_json}") + pose = np.array(poses[key], dtype=np.float32) + if pose.shape != (4, 4): + raise ValueError(f"Pose for frame {frame_id} must be 4x4, got {pose.shape}") + return pose + + +def build_world_object_transform( + extrinsics: np.ndarray, frame_id: int, pose_cam_obj: np.ndarray +) -> np.ndarray: + if frame_id >= len(extrinsics): + raise IndexError(f"Frame {frame_id} out of bounds for extrinsics array") + cam_to_world = np.linalg.inv(extrinsics[frame_id]) + return cam_to_world @ pose_cam_obj + + +def _depth_to_camera_points(depth: np.ndarray, intrinsic: np.ndarray, stride: int) -> np.ndarray: + """Back-project a depth map (in meters) to camera coordinates.""" + if stride < 1: + raise ValueError("scene-step must be >= 1") + h, w = depth.shape + ys = np.arange(0, h, stride, dtype=np.int32) + xs = np.arange(0, w, stride, dtype=np.int32) + grid_y, grid_x = np.meshgrid(ys, xs, indexing="ij") + sampled_depth = depth[grid_y, grid_x] + valid = sampled_depth > 1e-6 + if not np.any(valid): + return np.zeros((0, 3), dtype=np.float32) + fx = intrinsic[0, 0] + fy = intrinsic[1, 1] + cx = intrinsic[0, 2] + cy = intrinsic[1, 2] + grid_x = grid_x.astype(np.float32) + grid_y = grid_y.astype(np.float32) + sampled_depth = sampled_depth.astype(np.float32) + x = (grid_x - cx) / fx * sampled_depth + y = (grid_y - cy) / fy * sampled_depth + pts = np.stack([x, y, sampled_depth], axis=-1) + return pts[valid].reshape(-1, 3) + + +def _transform_points(points: np.ndarray, transform: np.ndarray) -> np.ndarray: + if len(points) == 0: + return points + ones = np.ones((len(points), 1), dtype=points.dtype) + pts_h = np.concatenate([points, ones], axis=1) + pts_world = pts_h @ transform.T + return pts_world[:, :3] + + +def normalize_extrinsics(extrinsics: np.ndarray) -> np.ndarray: + """ + Ensure extrinsics are (N, 4, 4). + + Accepts (N, 4, 4) or (N, 3, 4) (and rarely (N, 3, 3)) by padding the bottom + row to [0, 0, 0, 1]. Raises for other shapes to surface data issues early. + """ + extrinsics = np.asarray(extrinsics) + if extrinsics.ndim != 3: + raise ValueError(f"extrinsics must be 3D, got shape {extrinsics.shape}") + + n, h, w = extrinsics.shape + if (h, w) == (4, 4): + return extrinsics + if (h, w) in [(3, 4), (3, 3)]: + padded = np.zeros((n, 4, 4), dtype=extrinsics.dtype) + padded[:, :h, :w] = extrinsics + padded[:, 3, 3] = 1.0 + return padded + + raise ValueError(f"Unsupported extrinsics shape {extrinsics.shape}; expected (N,4,4) or (N,3,4)") + + +def load_scene_points( + depths: np.ndarray, intrs: np.ndarray, extrs: np.ndarray, scene_frame: int, step: int +) -> np.ndarray: + total_frames = len(depths) + + if scene_frame >= 0: + if scene_frame >= total_frames: + raise IndexError(f"scene_frame {scene_frame} out of range (0-{total_frames-1})") + frame_ids = [scene_frame] + else: + frame_ids = list(range(total_frames)) + + collected = [] + for fid in frame_ids: + depth = depths[fid] + intrinsic = intrs[fid] + cam_pts = _depth_to_camera_points(depth, intrinsic, step) + if len(cam_pts) == 0: + continue + cam_to_world = np.linalg.inv(extrs[fid]) + world_pts = _transform_points(cam_pts, cam_to_world) + collected.append(world_pts) + + if not collected: + return np.zeros((0, 3), dtype=np.float32) + return np.concatenate(collected, axis=0) + + +def sample_mesh_points(mesh: trimesh.Trimesh, count: int) -> np.ndarray: + count = max(1, count) + pts, _ = trimesh.sample.sample_surface_even(mesh, count) + return pts + + +def main(): + args = parse_args() + session = args.session.resolve() + if not session.exists(): + raise FileNotFoundError(f"Session folder not found: {session}") + + result_npz = session / "results" / "result.npz" + poses_json = session / "pose_result" / "poses.json" + if not result_npz.exists(): + raise FileNotFoundError(f"{result_npz} does not exist") + if not poses_json.exists(): + raise FileNotFoundError(f"{poses_json} does not exist") + + mesh_path: Path = args.mesh_file or find_high_mesh(session) + if not mesh_path.exists(): + raise FileNotFoundError(f"Mesh file not found: {mesh_path}") + + with np.load(result_npz) as data: + required = {"extrinsics", "intrinsics", "depths"} + missing = required - set(data.files) + if missing: + raise KeyError(f"{result_npz} missing keys: {', '.join(sorted(missing))}") + extrinsics = normalize_extrinsics(data["extrinsics"]) + intrinsics = data["intrinsics"] + depths = data["depths"] + + pose_cam_obj = load_pose_matrix(poses_json, args.frame_id) + world_obj = build_world_object_transform(extrinsics, args.frame_id, pose_cam_obj) + + mesh = trimesh.load(mesh_path, force="mesh") + mesh_world = mesh.copy() + mesh_world.apply_transform(world_obj) + + scene_pts = load_scene_points(depths, intrinsics, extrinsics, args.scene_frame, args.scene_step) + mesh_pts = sample_mesh_points(mesh_world, args.mesh_points) + + mesh_colors = np.tile(np.array([[255, 0, 0]], dtype=np.uint8), (len(mesh_pts), 1)) + scene_colors = np.tile( + np.array([[120, 120, 120]], dtype=np.uint8), (len(scene_pts), 1) + ) + + points = np.vstack([mesh_pts, scene_pts]) + colors = np.vstack([mesh_colors, scene_colors]) + + cloud = trimesh.points.PointCloud(points, colors=colors) + + output = args.output + if output is None: + output = session / f"combined_cloud_frame_{args.frame_id}.ply" + output = Path(output) + output.parent.mkdir(parents=True, exist_ok=True) + + cloud.export(output) + print( + f"Combined point cloud saved to {output} " + f"(mesh pts={len(mesh_pts)}, scene pts={len(scene_pts)})" + ) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/export_deform_mesh_sequence_glb.py b/OVOW/engine/tools/export_deform_mesh_sequence_glb.py new file mode 100644 index 0000000000000000000000000000000000000000..29955697fde52652604eb0aea3bff7891e0cbf16 --- /dev/null +++ b/OVOW/engine/tools/export_deform_mesh_sequence_glb.py @@ -0,0 +1,729 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import re +import shlex +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +import cv2 +import numpy as np +import trimesh +from pygltflib import ( + Accessor, + Animation, + AnimationChannel, + AnimationChannelTarget, + AnimationSampler, + Asset, + Buffer, + BufferView, + GLTF2, + Image, + Material, + Mesh, + Node, + PbrMetallicRoughness, + Primitive, + Scene, + Sampler, + Texture, + TextureInfo, +) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Export deform OBJ mesh sequence as a single GLB morph-target animation." + ) + parser.add_argument("--mesh-dir", type=Path, required=True, help="Directory containing frame_*.obj") + parser.add_argument("--output", type=Path, required=True, help="Output GLB path") + parser.add_argument("--object-name", type=str, default="deform_object", help="Object/node name in GLB") + parser.add_argument("--frame-glob", type=str, default="frame_*.obj", help="Glob pattern for mesh frames") + parser.add_argument("--fps", type=float, default=10.0, help="Animation FPS") + parser.add_argument( + "--coord", + type=str, + default="blender_noflip", + choices=("gltf", "opengl", "blender", "blender_noflip", "blender_zup", "raw"), + help="Coordinate conversion from OpenCV world", + ) + parser.add_argument("--alignment", type=Path, default=None, help="Optional alignment json with 4x4 T") + parser.add_argument( + "--uv-template-obj", + type=Path, + default=None, + help=( + "Optional OBJ used as UV source (and topology reference). " + "Use this to lock deform UV to upstream source asset." + ), + ) + parser.add_argument( + "--texture-path", + type=Path, + default=None, + help="Optional explicit texture path (overrides auto texture guessing).", + ) + parser.add_argument( + "--summary-out", + type=Path, + default=None, + help="Optional summary json path (default: .summary.json)", + ) + parser.add_argument( + "--visibility-mask-dir", + type=Path, + default=None, + help="Optional original mask dir; frames without a non-empty mask are hidden in the GLB.", + ) + parser.add_argument( + "--visibility-mask-glob", + type=str, + default="frame_*.png", + help="Glob for --visibility-mask-dir (default: frame_*.png).", + ) + return parser.parse_args() + + +def _parse_frame_id(path: Path) -> Optional[int]: + stem = path.stem + m = re.search(r"(\d+)$", stem) + if m: + return int(m.group(1)) + m = re.search(r"(\d+)", stem) + if m: + return int(m.group(1)) + return None + + +def _load_visible_mask_frames(mask_dir: Optional[Path], mask_glob: str) -> Optional[set[int]]: + if mask_dir is None: + return None + mask_dir = mask_dir.resolve() + if not mask_dir.exists(): + print(f"[Warn] Visibility mask dir missing: {mask_dir}") + return None + visible: set[int] = set() + found = False + for path in sorted(mask_dir.glob(mask_glob)): + frame_id = _parse_frame_id(path) + if frame_id is None: + continue + mask = cv2.imread(str(path), cv2.IMREAD_GRAYSCALE) + if mask is None: + continue + found = True + if int(np.count_nonzero(mask)) > 0: + visible.add(frame_id) + if not found: + print(f"[Warn] No readable visibility masks in {mask_dir} ({mask_glob})") + return None + return visible + + +def _safe_name(name: str) -> str: + return "".join(c if c.isalnum() or c in ("-", "_") else "_" for c in name) + + +def _mesh_from_path(path: Path) -> trimesh.Trimesh: + mesh = trimesh.load(str(path), force="mesh", process=False, maintain_order=True) + if isinstance(mesh, trimesh.Scene): + geos = [g for g in mesh.geometry.values() if isinstance(g, trimesh.Trimesh)] + if not geos: + raise RuntimeError(f"No geometry in {path}") + mesh = trimesh.util.concatenate(geos) + if not isinstance(mesh, trimesh.Trimesh): + raise RuntimeError(f"Invalid mesh: {path}") + return mesh + + +def _load_template_uv_and_faces(template_obj: Path) -> tuple[np.ndarray, np.ndarray]: + mesh = _mesh_from_path(template_obj) + faces = np.asarray(mesh.faces, dtype=np.int64) + uv = getattr(mesh.visual, "uv", None) + if uv is None: + raise RuntimeError(f"Template OBJ has no UV: {template_obj}") + uv_arr = np.asarray(uv, dtype=np.float32) + if uv_arr.ndim != 2 or uv_arr.shape[1] < 2: + raise RuntimeError(f"Template OBJ UV format invalid: {template_obj}") + uv_gltf = uv_arr[:, :2].copy() + uv_gltf[:, 1] = 1.0 - uv_gltf[:, 1] + return faces, uv_gltf + + +def _resolve_obj_index(idx: int, count: int) -> int: + return (idx - 1) if idx > 0 else (count + idx) + + +def _load_obj_uv_split_template( + template_obj: Path, +) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, int, int]: + """ + Build a glTF-ready template that preserves OBJ corner UV semantics. + + OBJ allows one vertex index to map to multiple UV indices across faces. + glTF uses one UV per vertex index, so we split vertices by (v, vt) pairs. + Returns: + - faces_split: (F, 3) triangle indices over split vertices + - uv_split_gltf: (Vsplit, 2) UV array (V already flipped for glTF) + - split_to_orig_v: (Vsplit,) map split vertex -> original vertex index + - faces_orig_v: (F, 3) original vertex indices per triangle corner + - num_v: original OBJ vertex count + - num_vt: original OBJ texcoord count + """ + lines = template_obj.read_text(encoding="utf-8", errors="ignore").splitlines() + + vt_list: List[Tuple[float, float]] = [] + num_v = 0 + pair_to_split: Dict[Tuple[int, int], int] = {} + split_to_orig_v: List[int] = [] + uv_split: List[Tuple[float, float]] = [] + faces_split: List[List[int]] = [] + faces_orig_v: List[List[int]] = [] + + for ln, line in enumerate(lines, start=1): + s = line.strip() + if not s or s.startswith("#"): + continue + if s.startswith("v "): + num_v += 1 + continue + if s.startswith("vt "): + toks = s.split() + if len(toks) < 3: + raise RuntimeError(f"Invalid vt line at {template_obj}:{ln}") + u = float(toks[1]) + v = float(toks[2]) + vt_list.append((u, v)) + continue + if not s.startswith("f "): + continue + + corners: List[Tuple[int, int]] = [] + for tok in s.split()[1:]: + parts = tok.split("/") + if len(parts) < 2 or not parts[0] or not parts[1]: + raise RuntimeError( + f"Template OBJ must contain v/vt on faces for UV-preserving export: {template_obj}:{ln}" + ) + v_idx = _resolve_obj_index(int(parts[0]), num_v) + vt_idx = _resolve_obj_index(int(parts[1]), len(vt_list)) + if v_idx < 0 or v_idx >= num_v: + raise RuntimeError(f"Invalid vertex index at {template_obj}:{ln}") + if vt_idx < 0 or vt_idx >= len(vt_list): + raise RuntimeError(f"Invalid texcoord index at {template_obj}:{ln}") + corners.append((v_idx, vt_idx)) + + if len(corners) < 3: + continue + for i in range(1, len(corners) - 1): + tri = (corners[0], corners[i], corners[i + 1]) + tri_split: List[int] = [] + tri_orig: List[int] = [] + for v_idx, vt_idx in tri: + key = (v_idx, vt_idx) + split_idx = pair_to_split.get(key) + if split_idx is None: + split_idx = len(split_to_orig_v) + pair_to_split[key] = split_idx + split_to_orig_v.append(v_idx) + uv_split.append(vt_list[vt_idx]) + tri_split.append(split_idx) + tri_orig.append(v_idx) + faces_split.append(tri_split) + faces_orig_v.append(tri_orig) + + if not faces_split or not split_to_orig_v: + raise RuntimeError(f"Failed to build UV split template from {template_obj}") + + uv_split_arr = np.asarray(uv_split, dtype=np.float32) + uv_split_arr[:, 1] = 1.0 - uv_split_arr[:, 1] + return ( + np.asarray(faces_split, dtype=np.int64), + uv_split_arr, + np.asarray(split_to_orig_v, dtype=np.int64), + np.asarray(faces_orig_v, dtype=np.int64), + int(num_v), + int(len(vt_list)), + ) + + +def _find_obj_texture(mesh_path: Path) -> Optional[Path]: + try: + lines = mesh_path.read_text(encoding="utf-8", errors="ignore").splitlines() + except Exception: + return None + + mtl_files: List[Path] = [] + for line in lines: + s = line.strip() + if not s or s.startswith("#"): + continue + if s.lower().startswith("mtllib "): + rel = s.split(None, 1)[1].strip() + p = (mesh_path.parent / rel).resolve() + if p.exists(): + mtl_files.append(p) + + for mtl in mtl_files: + try: + mtl_lines = mtl.read_text(encoding="utf-8", errors="ignore").splitlines() + except Exception: + continue + for line in mtl_lines: + s = line.strip() + if not s or s.startswith("#"): + continue + if not s.lower().startswith("map_kd "): + continue + try: + toks = shlex.split(s, comments=False, posix=True) + except Exception: + toks = s.split() + if len(toks) < 2: + continue + tex = (mtl.parent / toks[-1]).resolve() + if tex.exists(): + return tex + return None + + +def _guess_deform_texture(mesh_dir: Path, first_mesh_path: Path) -> Optional[Path]: + candidates: List[Path] = [] + tex = _find_obj_texture(first_mesh_path) + if tex is not None: + candidates.append(tex) + candidates.extend( + [ + mesh_dir / "material_0.png", + mesh_dir / "material.png", + mesh_dir.parent / "material_0.png", + mesh_dir.parent / "material.png", + mesh_dir.parent / "mid_files" / "material_0.png", + mesh_dir.parent / "mid_files" / "material.png", + mesh_dir.parent / "model" / "material_0.png", + mesh_dir.parent / "model" / "material.png", + ] + ) + + uniq: List[Path] = [] + seen = set() + for p in candidates: + rp = p.resolve() + key = str(rp) + if key in seen or not rp.exists(): + continue + seen.add(key) + uniq.append(rp) + if not uniq: + return None + + def _score(p: Path) -> tuple[int, int]: + area = 0 + try: + from PIL import Image # type: ignore + + with Image.open(p) as img: + w, h = img.size + area = int(w) * int(h) + except Exception: + area = 0 + try: + size = int(p.stat().st_size) + except Exception: + size = 0 + return (area, size) + + best = max(uniq, key=_score) + return best + + +def _load_alignment(path: Optional[Path]) -> Optional[np.ndarray]: + if path is None: + return None + if not path.exists(): + raise FileNotFoundError(path) + payload = json.loads(path.read_text()) + T = np.asarray(payload.get("T"), dtype=np.float32) + if T.shape != (4, 4): + raise ValueError(f"alignment.T must be 4x4, got {T.shape}") + return T + + +def _apply_transform(T: np.ndarray, verts: np.ndarray) -> np.ndarray: + ones = np.ones((verts.shape[0], 1), dtype=np.float32) + verts_h = np.concatenate([verts.astype(np.float32), ones], axis=1) + return (T @ verts_h.T).T[:, :3].astype(np.float32) + + +def _coord_matrix(coord: str) -> np.ndarray: + if coord == "raw": + return np.eye(4, dtype=np.float32) + if coord == "opengl": + return np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float32) + if coord == "blender": + rot_x_neg_90 = np.array( + [[1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, -1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0]], + dtype=np.float32, + ) + flip_x = np.diag([-1.0, 1.0, 1.0, 1.0]).astype(np.float32) + return flip_x @ (rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32)) + if coord == "blender_noflip": + rot_x_neg_90 = np.array( + [[1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, -1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0]], + dtype=np.float32, + ) + return rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + if coord == "blender_zup": + return np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + return np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + + +class BufferBuilder: + def __init__(self) -> None: + self.buffer = bytearray() + self.buffer_views: List[BufferView] = [] + self.accessors: List[Accessor] = [] + + def _align(self, n: int = 4) -> None: + pad = (-len(self.buffer)) % n + if pad: + self.buffer.extend(b"\x00" * pad) + + def add_array(self, arr: np.ndarray, accessor_type: str, component_type: int) -> int: + arr = np.ascontiguousarray(arr) + self._align(4) + offset = len(self.buffer) + data = arr.tobytes() + self.buffer.extend(data) + + bv = BufferView(buffer=0, byteOffset=offset, byteLength=len(data)) + bv_index = len(self.buffer_views) + self.buffer_views.append(bv) + + if arr.ndim == 1: + count = int(arr.shape[0]) + else: + count = int(arr.shape[0]) + + acc = Accessor( + bufferView=bv_index, + byteOffset=0, + componentType=component_type, + count=count, + type=accessor_type, + min=None, + max=None, + ) + acc_index = len(self.accessors) + self.accessors.append(acc) + return acc_index + + +def main() -> None: + args = parse_args() + + if not args.mesh_dir.exists(): + raise FileNotFoundError(args.mesh_dir) + + mesh_map: Dict[int, Path] = {} + for p in sorted(args.mesh_dir.glob(args.frame_glob)): + fid = _parse_frame_id(p) + if fid is None: + continue + mesh_map[int(fid)] = p + if not mesh_map: + raise FileNotFoundError(f"No mesh frames found in {args.mesh_dir} ({args.frame_glob})") + + frame_ids = sorted(mesh_map.keys()) + visible_frames = _load_visible_mask_frames(args.visibility_mask_dir, args.visibility_mask_glob) + if visible_frames is not None: + visible_count = sum(1 for frame_id in frame_ids if frame_id in visible_frames) + if visible_count < len(frame_ids): + print( + f"[Info] {args.object_name}: visible in {visible_count}/{len(frame_ids)} mesh frames " + "from visibility masks" + ) + align_T = _load_alignment(args.alignment) + first_mesh_path = mesh_map[frame_ids[0]] + + template_faces: Optional[np.ndarray] = None + template_uv: Optional[np.ndarray] = None + template_faces_split: Optional[np.ndarray] = None + template_uv_split: Optional[np.ndarray] = None + template_split_to_orig_v: Optional[np.ndarray] = None + template_faces_orig_v: Optional[np.ndarray] = None + template_orig_v_count: Optional[int] = None + use_uv_corner_split = False + if args.uv_template_obj is not None: + template_path = args.uv_template_obj.resolve() + if not template_path.exists(): + raise FileNotFoundError(template_path) + template_faces, template_uv = _load_template_uv_and_faces(template_path) + try: + ( + template_faces_split, + template_uv_split, + template_split_to_orig_v, + template_faces_orig_v, + template_orig_v_count, + _, + ) = _load_obj_uv_split_template(template_path) + use_uv_corner_split = True + print( + f"[Info] {args.object_name}: use UV corner split template " + f"(orig_v={template_orig_v_count}, split_v={template_uv_split.shape[0]})" + ) + except Exception as exc: + print( + f"[Warn] {args.object_name}: failed UV corner split parse from {template_path}: {exc}. " + "Fallback to per-vertex UV mapping." + ) + + frames_verts: List[np.ndarray] = [] + frames_normals: List[np.ndarray] = [] + faces_ref: Optional[np.ndarray] = None + uv_ref: Optional[np.ndarray] = None + + for i, fid in enumerate(frame_ids): + mesh = _mesh_from_path(mesh_map[fid]) + verts_raw = np.asarray(mesh.vertices, dtype=np.float32) + faces_raw = np.asarray(mesh.faces, dtype=np.int64) + uv = getattr(mesh.visual, "uv", None) + uv_arr: Optional[np.ndarray] = None + if uv is not None: + uv_tmp = np.asarray(uv, dtype=np.float32) + if uv_tmp.ndim == 2 and uv_tmp.shape[0] == verts_raw.shape[0] and uv_tmp.shape[1] >= 2: + uv_arr = uv_tmp[:, :2].copy() + uv_arr[:, 1] = 1.0 - uv_arr[:, 1] + + verts = verts_raw + faces = faces_raw + uv_use = uv_arr + if use_uv_corner_split: + if ( + template_faces_split is None + or template_uv_split is None + or template_split_to_orig_v is None + or template_faces_orig_v is None + or template_orig_v_count is None + ): + raise RuntimeError("Internal error: UV split template not initialized") + if verts_raw.shape[0] != template_orig_v_count: + raise RuntimeError( + f"Vertex count mismatch for UV split at frame {fid}: " + f"{verts_raw.shape[0]} vs template {template_orig_v_count}" + ) + if ( + faces_raw.shape != template_faces_orig_v.shape + or not np.array_equal(faces_raw, template_faces_orig_v) + ): + raise RuntimeError( + f"Face topology mismatch for UV split at frame {fid}: " + f"{mesh_map[fid]} vs template {args.uv_template_obj}" + ) + verts = verts_raw[template_split_to_orig_v] + faces = template_faces_split + uv_use = template_uv_split + + if i == 0: + faces_ref = faces.copy() + if use_uv_corner_split and uv_use is not None: + uv_ref = uv_use.copy() + elif template_faces is not None and template_uv is not None: + if faces_ref.shape != template_faces.shape or not np.array_equal(faces_ref, template_faces): + raise RuntimeError( + "Topology mismatch between mesh frames and --uv-template-obj " + f"({mesh_map[fid]} vs {args.uv_template_obj})" + ) + if template_uv.shape[0] != verts.shape[0]: + raise RuntimeError( + f"UV vertex count mismatch: template={template_uv.shape[0]} vs frame={verts.shape[0]}" + ) + uv_ref = template_uv.copy() + elif uv_use is not None: + uv_ref = uv_use.copy() + else: + if verts.shape[0] != frames_verts[0].shape[0]: + raise RuntimeError( + f"Vertex count mismatch at frame {fid}: {verts.shape[0]} vs {frames_verts[0].shape[0]}" + ) + if faces_ref is None or faces.shape != faces_ref.shape or not np.array_equal(faces, faces_ref): + raise RuntimeError(f"Topology mismatch at frame {fid}: face indices changed") + + if align_T is not None: + verts = _apply_transform(align_T, verts) + + frame_mesh = trimesh.Trimesh(vertices=verts, faces=faces, process=False) + frame_normals = np.asarray(frame_mesh.vertex_normals, dtype=np.float32) + if frame_normals.shape != verts.shape: + frame_normals = np.zeros_like(verts, dtype=np.float32) + frame_normals[:, 2] = 1.0 + frames_verts.append(verts) + frames_normals.append(frame_normals) + + assert faces_ref is not None + base_positions = frames_verts[0] + faces_u32 = faces_ref.astype(np.uint32).reshape(-1) + + normals = frames_normals[0].astype(np.float32) + if normals.shape != base_positions.shape: + normals = np.zeros_like(base_positions, dtype=np.float32) + normals[:, 2] = 1.0 + + builder = BufferBuilder() + + pos_acc = builder.add_array(base_positions.astype(np.float32), "VEC3", 5126) + nrm_acc = builder.add_array(normals.astype(np.float32), "VEC3", 5126) + idx_acc = builder.add_array(faces_u32, "SCALAR", 5125) + uv_acc: Optional[int] = None + if uv_ref is not None and uv_ref.shape[0] == base_positions.shape[0]: + uv_acc = builder.add_array(uv_ref.astype(np.float32), "VEC2", 5126) + + targets = [] + for verts, frame_normals in zip(frames_verts, frames_normals): + delta = (verts - base_positions).astype(np.float32) + d_acc = builder.add_array(delta, "VEC3", 5126) + dn = (frame_normals - normals).astype(np.float32) + dn_acc = builder.add_array(dn, "VEC3", 5126) + targets.append({"POSITION": d_acc, "NORMAL": dn_acc}) + + attrs = {"POSITION": pos_acc, "NORMAL": nrm_acc} + if uv_acc is not None: + attrs["TEXCOORD_0"] = uv_acc + + if args.texture_path is not None: + texture_path = args.texture_path.resolve() + if not texture_path.exists(): + raise FileNotFoundError(texture_path) + else: + texture_path = _guess_deform_texture(args.mesh_dir.resolve(), first_mesh_path.resolve()) + materials = [ + Material( + name="default", + pbrMetallicRoughness=PbrMetallicRoughness( + baseColorFactor=[1.0, 1.0, 1.0, 1.0], + metallicFactor=0.0, + roughnessFactor=1.0, + ), + ) + ] + images: List[Image] = [] + textures: List[Texture] = [] + samplers: List[Sampler] = [] + material_index = 0 + if texture_path is not None and uv_acc is not None: + samplers.append(Sampler(wrapS=33071, wrapT=33071, magFilter=9729, minFilter=9729)) + images.append(Image(uri=str(texture_path.resolve()))) + textures.append(Texture(source=0, sampler=0)) + materials.append( + Material( + name=f"tex_{_safe_name(args.object_name)}", + pbrMetallicRoughness=PbrMetallicRoughness( + baseColorFactor=[1.0, 1.0, 1.0, 1.0], + metallicFactor=0.0, + roughnessFactor=1.0, + baseColorTexture=TextureInfo(index=0), + ), + ) + ) + material_index = 1 + + primitive = Primitive(attributes=attrs, indices=idx_acc, targets=targets, material=material_index) + + num_frames = len(frame_ids) + num_targets = len(targets) + if num_targets != num_frames: + raise RuntimeError("Internal error: num_targets != num_frames") + + mesh_weights0 = np.zeros((num_targets,), dtype=np.float32) + mesh_weights0[0] = 1.0 + mesh = Mesh(primitives=[primitive], name=_safe_name(args.object_name), weights=mesh_weights0.tolist()) + + fps = max(1e-6, float(args.fps)) + times = (np.asarray(frame_ids, dtype=np.float32) - float(frame_ids[0])) / fps + weights = np.zeros((num_frames, num_targets), dtype=np.float32) + for i in range(num_frames): + weights[i, i] = 1.0 + + time_acc = builder.add_array(times.astype(np.float32), "SCALAR", 5126) + weight_acc = builder.add_array(weights.reshape(-1).astype(np.float32), "SCALAR", 5126) + + root = Node(name="root_cv2gl", matrix=_coord_matrix(args.coord).T.flatten().tolist(), children=[1]) + node = Node(name=_safe_name(args.object_name), mesh=0) + sampler = AnimationSampler(input=time_acc, output=weight_acc, interpolation="STEP") + channel = AnimationChannel(sampler=0, target=AnimationChannelTarget(node=1, path="weights")) + anim_samplers = [sampler] + anim_channels = [channel] + visibility_hidden_count = 0 + if visible_frames is not None: + scales = np.asarray( + [[1.0, 1.0, 1.0] if frame_id in visible_frames else [0.0, 0.0, 0.0] for frame_id in frame_ids], + dtype=np.float32, + ) + visibility_hidden_count = int(np.count_nonzero(scales[:, 0] == 0.0)) + if visibility_hidden_count > 0: + if scales[0, 0] == 0.0: + node.scale = [0.0, 0.0, 0.0] + scale_acc = builder.add_array(scales, "VEC3", 5126) + scale_sampler = AnimationSampler(input=time_acc, output=scale_acc, interpolation="STEP") + scale_sampler_index = len(anim_samplers) + anim_samplers.append(scale_sampler) + anim_channels.append( + AnimationChannel( + sampler=scale_sampler_index, + target=AnimationChannelTarget(node=1, path="scale"), + ) + ) + anim = Animation(samplers=anim_samplers, channels=anim_channels, name=f"{_safe_name(args.object_name)}_morph") + + gltf = GLTF2(asset=Asset(version="2.0")) + gltf.meshes = [mesh] + gltf.nodes = [root, node] + gltf.scenes = [Scene(nodes=[0])] + gltf.scene = 0 + gltf.materials = materials + if images: + gltf.images = images + if textures: + gltf.textures = textures + if samplers: + gltf.samplers = samplers + gltf.animations = [anim] + gltf.bufferViews = builder.buffer_views + gltf.accessors = builder.accessors + gltf.buffers = [Buffer(byteLength=len(builder.buffer))] + gltf.set_binary_blob(bytes(builder.buffer)) + + args.output.parent.mkdir(parents=True, exist_ok=True) + gltf.save_binary(str(args.output)) + + summary = { + "mesh_dir": str(args.mesh_dir), + "output": str(args.output), + "object_name": args.object_name, + "frame_ids": frame_ids, + "num_frames": int(num_frames), + "num_vertices": int(base_positions.shape[0]), + "num_faces": int(faces_ref.shape[0]), + "num_morph_targets": int(num_targets), + "fps": float(args.fps), + "coord": args.coord, + "alignment": str(args.alignment) if args.alignment is not None else None, + "uv_template_obj": str(args.uv_template_obj) if args.uv_template_obj is not None else None, + "uv_corner_split": bool(use_uv_corner_split), + "uv_vertices_after_split": int(uv_ref.shape[0]) if uv_ref is not None else 0, + "texture": str(texture_path) if texture_path is not None else None, + "visibility_mask_dir": str(args.visibility_mask_dir) if args.visibility_mask_dir is not None else None, + "visibility_hidden_frames": int(visibility_hidden_count), + } + summary_out = args.summary_out or args.output.with_suffix(".summary.json") + summary_out.write_text(json.dumps(summary, indent=2)) + print(f"[OK] Wrote: {args.output}") + print(f"[OK] Summary: {summary_out}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/export_scene_glb_anim.py b/OVOW/engine/tools/export_scene_glb_anim.py new file mode 100644 index 0000000000000000000000000000000000000000..4b1851e8ad6d5a099e0a355d4fce6f36f29141c4 --- /dev/null +++ b/OVOW/engine/tools/export_scene_glb_anim.py @@ -0,0 +1,675 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import math +import shlex +from pathlib import Path +from typing import Dict, List, Tuple + +import cv2 +import numpy as np +import trimesh +from pygltflib import ( + Accessor, + Animation, + AnimationChannel, + AnimationChannelTarget, + AnimationSampler, + Asset, + Buffer, + BufferView, + Camera, + GLTF2, + Image, + Material, + Mesh, + Node, + PbrMetallicRoughness, + Primitive, + Scene, + Texture, + TextureInfo, +) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Export animated GLB for OnePoseviaGen results.") + parser.add_argument("--run-dir", type=Path, required=True, help="Run dir, e.g. .../video_pipeline_xxx/V1") + parser.add_argument("--config", type=Path, required=True, help="Pipeline config JSON used for categories") + parser.add_argument("--output", type=Path, required=True, help="Output .glb path") + parser.add_argument( + "--alignment", + type=Path, + default=None, + help="Optional alignment JSON with 4x4 transform matrix 'T' to apply in world coordinates", + ) + parser.add_argument("--fps", type=float, default=10.0, help="Frames per second for animation timeline") + parser.add_argument("--use-locked-static", action="store_true", help="Use poses_locked.json if exists for static objects") + parser.add_argument( + "--pose-name", + type=str, + default="", + help="Override pose json filename under pose_result (e.g., poses_physics.json)", + ) + parser.add_argument("--animate-camera", action="store_true", help="Export animated camera from result.npz") + parser.add_argument("--add-plane", action="store_true", help="Add a static plane at Z=0 for visualization") + parser.add_argument("--plane-scale", type=float, default=1.2, help="Plane size scale vs scene bbox") + parser.add_argument( + "--plane-z", + type=str, + default="zero", + choices=("zero", "minz", "static_minz"), + help="Plane Z position: zero=Z=0, minz=use scene minimum Z, static_minz=use static objects minimum Z", + ) + parser.add_argument( + "--coord", + type=str, + default="gltf", + choices=("gltf", "opengl", "blender", "blender_noflip", "blender_zup", "raw"), + help=( + "Coordinate conversion from OpenCV world: gltf=flipY, opengl=flipY+flipZ, " + "blender=旧版带flip_x, blender_noflip=推荐(不翻转X), blender_zup=Z-up, raw=no change" + ), + ) + return parser.parse_args() + + +def _safe_name(name: str) -> str: + return "".join(c if c.isalnum() or c in ("-", "_") else "_" for c in name) + + +def _pick_mesh_path(obj_dir: Path) -> Path: + candidates: List[Path] = [] + candidates.append(obj_dir / "mid_files" / "scaled_mesh.obj") + candidates.extend(sorted((obj_dir / "model" / "middle_file").glob("*_high_mesh.obj"))) + candidates.append(obj_dir / "model" / "model.obj") + for c in candidates: + if c.exists(): + return c + raise FileNotFoundError(f"No mesh found in {obj_dir}") + + +def _find_obj_texture(mesh_path: Path) -> Path | None: + try: + lines = mesh_path.read_text(encoding="utf-8", errors="ignore").splitlines() + except Exception: + return None + + mtl_files: List[Path] = [] + for line in lines: + s = line.strip() + if not s or s.startswith("#"): + continue + if s.lower().startswith("mtllib "): + rel = s.split(None, 1)[1].strip() + p = (mesh_path.parent / rel).resolve() + if p.exists(): + mtl_files.append(p) + + for mtl in mtl_files: + try: + mtl_lines = mtl.read_text(encoding="utf-8", errors="ignore").splitlines() + except Exception: + continue + for line in mtl_lines: + s = line.strip() + if not s or s.startswith("#"): + continue + if not s.lower().startswith("map_kd "): + continue + try: + toks = shlex.split(s, comments=False, posix=True) + except Exception: + toks = s.split() + if len(toks) < 2: + continue + tex_rel = toks[-1] + tex = (mtl.parent / tex_rel).resolve() + if tex.exists(): + return tex + return None + + +def _load_pose_json(obj_dir: Path, use_locked: bool, pose_name: str = "") -> Path: + pose_dir = obj_dir / "pose_result" + if pose_name: + custom = pose_dir / pose_name + if custom.exists(): + return custom + locked = pose_dir / "poses_locked.json" + default = pose_dir / "poses.json" + if use_locked and locked.exists(): + return locked + if default.exists(): + return default + raise FileNotFoundError(f"No poses.json under {pose_dir}") + + +def _load_pose_sequence(pose_json: Path, num_frames: int) -> List[np.ndarray]: + with pose_json.open("r", encoding="utf-8") as f: + data = json.load(f) + pose_map: Dict[int, np.ndarray] = {} + for k, v in data.items(): + try: + idx = int(k) + except Exception: + continue + pose_map[idx] = np.asarray(v, dtype=np.float32) + if not pose_map: + raise ValueError(f"No valid poses in {pose_json}") + available = sorted(pose_map.keys()) + seq: List[np.ndarray] = [] + for i in range(num_frames): + if i in pose_map: + seq.append(pose_map[i]) + else: + nearest = min(available, key=lambda x: abs(x - i)) + seq.append(pose_map[nearest]) + return seq + + +def _parse_frame_id(path: Path) -> int | None: + stem = path.stem + if stem.startswith("frame_"): + stem = stem[len("frame_") :] + try: + return int(stem) + except Exception: + return None + + +def _load_visible_mask_frames(mask_dir: Path) -> set[int] | None: + if not mask_dir.exists(): + return None + visible: set[int] = set() + found = False + for path in sorted(mask_dir.glob("*.png")): + frame_id = _parse_frame_id(path) + if frame_id is None: + continue + mask = cv2.imread(str(path), cv2.IMREAD_GRAYSCALE) + if mask is None: + continue + found = True + if int(np.count_nonzero(mask)) > 0: + visible.add(frame_id) + return visible if found else None + + +def _matrix_to_quat(m: np.ndarray) -> np.ndarray: + r = m[:3, :3] + trace = np.trace(r) + if trace > 0.0: + s = math.sqrt(trace + 1.0) * 2.0 + w = 0.25 * s + x = (r[2, 1] - r[1, 2]) / s + y = (r[0, 2] - r[2, 0]) / s + z = (r[1, 0] - r[0, 1]) / s + else: + if r[0, 0] > r[1, 1] and r[0, 0] > r[2, 2]: + s = math.sqrt(1.0 + r[0, 0] - r[1, 1] - r[2, 2]) * 2.0 + w = (r[2, 1] - r[1, 2]) / s + x = 0.25 * s + y = (r[0, 1] + r[1, 0]) / s + z = (r[0, 2] + r[2, 0]) / s + elif r[1, 1] > r[2, 2]: + s = math.sqrt(1.0 + r[1, 1] - r[0, 0] - r[2, 2]) * 2.0 + w = (r[0, 2] - r[2, 0]) / s + x = (r[0, 1] + r[1, 0]) / s + y = 0.25 * s + z = (r[1, 2] + r[2, 1]) / s + else: + s = math.sqrt(1.0 + r[2, 2] - r[0, 0] - r[1, 1]) * 2.0 + w = (r[1, 0] - r[0, 1]) / s + x = (r[0, 2] + r[2, 0]) / s + y = (r[1, 2] + r[2, 1]) / s + z = 0.25 * s + quat = np.array([x, y, z, w], dtype=np.float32) + quat = quat / np.linalg.norm(quat) + return quat + + +def _load_alignment(path: Path | None) -> np.ndarray | None: + if path is None: + return None + if not path.exists(): + raise FileNotFoundError(path) + with path.open("r", encoding="utf-8") as f: + data = json.load(f) + if "T" not in data: + raise KeyError(f"'T' not found in alignment file: {path}") + T = np.asarray(data["T"], dtype=np.float32) + if T.shape != (4, 4): + raise ValueError(f"Alignment 'T' must be 4x4, got {T.shape}") + return T + + +class BufferBuilder: + def __init__(self) -> None: + self.buffer = bytearray() + self.bufferViews: List[BufferView] = [] + self.accessors: List[Accessor] = [] + + def _align(self, alignment: int = 4) -> None: + padding = (-len(self.buffer)) % alignment + if padding: + self.buffer.extend(b"\x00" * padding) + + def add_array(self, arr: np.ndarray, accessor_type: str, component_type: int, normalized: bool = False) -> int: + arr = np.asarray(arr) + self._align(4) + byte_offset = len(self.buffer) + data = arr.tobytes() + self.buffer.extend(data) + view = BufferView(buffer=0, byteOffset=byte_offset, byteLength=len(data)) + view_index = len(self.bufferViews) + self.bufferViews.append(view) + + count = arr.shape[0] + accessor = Accessor( + bufferView=view_index, + byteOffset=0, + componentType=component_type, + count=count, + type=accessor_type, + normalized=normalized, + ) + if accessor_type == "VEC3" and component_type == 5126: + accessor.min = arr.min(axis=0).tolist() + accessor.max = arr.max(axis=0).tolist() + if accessor_type == "SCALAR" and component_type == 5126: + accessor.min = [float(arr.min())] + accessor.max = [float(arr.max())] + + accessor_index = len(self.accessors) + self.accessors.append(accessor) + return accessor_index + + +def main() -> None: + args = parse_args() + run_dir = args.run_dir.resolve() + config_path = args.config.resolve() + output_path = args.output.resolve() + + if not run_dir.exists(): + raise FileNotFoundError(run_dir) + if not config_path.exists(): + raise FileNotFoundError(config_path) + + with config_path.open("r", encoding="utf-8") as f: + cfg = json.load(f) + categories = {o["name"]: str(o.get("category", "")).lower() for o in cfg.get("objects", [])} + + result_npz = run_dir / "results" / "result.npz" + if not result_npz.exists(): + raise FileNotFoundError(result_npz) + data = np.load(result_npz) + extrinsics = data["extrinsics"] + intrinsics = data["intrinsics"] + num_frames = extrinsics.shape[0] + + align_T = _load_alignment(args.alignment) + + fps = float(args.fps) + times = np.arange(num_frames, dtype=np.float32) / max(1e-6, fps) + + if args.coord == "raw": + cv_to_gltf = np.eye(4, dtype=np.float32) + elif args.coord == "opengl": + cv_to_gltf = np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float32) + elif args.coord == "blender": + rot_x_neg_90 = np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + flip_x = np.diag([-1.0, 1.0, 1.0, 1.0]).astype(np.float32) + cv_to_gltf = flip_x @ (rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32)) + elif args.coord == "blender_noflip": + rot_x_neg_90 = np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + cv_to_gltf = rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + elif args.coord == "blender_zup": + cv_to_gltf = np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + else: + cv_to_gltf = np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + + builder = BufferBuilder() + gltf = GLTF2(asset=Asset(version="2.0")) + gltf.images = [] + gltf.textures = [] + gltf.materials = [ + Material( + name="default", + pbrMetallicRoughness=PbrMetallicRoughness( + baseColorFactor=[1.0, 1.0, 1.0, 1.0], + metallicFactor=0.0, + roughnessFactor=1.0, + ), + ) + ] + texture_mat_cache: Dict[str, int] = {} + + def _material_for_texture_path(tex_path: Path | None, has_uv: bool) -> int: + if tex_path is None or not has_uv: + return 0 + key = str(tex_path.resolve()) + if key in texture_mat_cache: + return texture_mat_cache[key] + img_index = len(gltf.images) + gltf.images.append(Image(uri=key)) + tex_index = len(gltf.textures) + gltf.textures.append(Texture(source=img_index)) + mat = Material( + name=f"tex_{tex_path.stem}", + pbrMetallicRoughness=PbrMetallicRoughness( + baseColorFactor=[1.0, 1.0, 1.0, 1.0], + metallicFactor=0.0, + roughnessFactor=1.0, + baseColorTexture=TextureInfo(index=tex_index), + ), + ) + mat_index = len(gltf.materials) + gltf.materials.append(mat) + texture_mat_cache[key] = mat_index + return mat_index + + nodes: List[Node] = [] + meshes: List[Mesh] = [] + + root = Node(name="root_cv2gl", matrix=cv_to_gltf.T.flatten().tolist()) + root_index = 0 + nodes.append(root) + + animation_channels: List[AnimationChannel] = [] + animation_samplers: List[AnimationSampler] = [] + + def _append_visibility_scale_animation(node_index: int, node: Node, visible_frames: set[int] | None) -> None: + if visible_frames is None: + return + bounded_visible = {idx for idx in visible_frames if 0 <= idx < num_frames} + if len(bounded_visible) >= num_frames: + return + scales = np.asarray( + [[1.0, 1.0, 1.0] if i in bounded_visible else [0.0, 0.0, 0.0] for i in range(num_frames)], + dtype=np.float32, + ) + if 0 not in bounded_visible: + node.scale = [0.0, 0.0, 0.0] + time_acc = builder.add_array(times, "SCALAR", 5126) + scale_acc = builder.add_array(scales, "VEC3", 5126) + scale_sampler = AnimationSampler(input=time_acc, output=scale_acc, interpolation="STEP") + scale_sampler_index = len(animation_samplers) + animation_samplers.append(scale_sampler) + animation_channels.append( + AnimationChannel( + sampler=scale_sampler_index, + target=AnimationChannelTarget(node=node_index, path="scale"), + ) + ) + + objects_root = run_dir / "objects" + bbox_min = np.array([np.inf, np.inf, np.inf], dtype=np.float32) + bbox_max = np.array([-np.inf, -np.inf, -np.inf], dtype=np.float32) + bbox_min_static = np.array([np.inf, np.inf, np.inf], dtype=np.float32) + for obj_dir in sorted([d for d in objects_root.iterdir() if d.is_dir()]): + name = obj_dir.name + if name not in categories: + print(f"[Warn] Skip unknown object dir not in config: {name}") + continue + category = categories.get(name, "") + visible_frames = _load_visible_mask_frames(obj_dir / "masks") + if visible_frames is not None and len(visible_frames) < num_frames: + print(f"[Info] {name}: visible in {len(visible_frames)}/{num_frames} frames from masks") + + try: + pose_path = _load_pose_json( + obj_dir, use_locked=(args.use_locked_static and category == "static"), pose_name=args.pose_name + ) + pose_seq = _load_pose_sequence(pose_path, num_frames) + except Exception as exc: + print(f"[Warn] Skip {name}: pose load failed: {exc}") + continue + + try: + mesh_path = _pick_mesh_path(obj_dir) + mesh = trimesh.load(mesh_path, force="mesh") + except Exception as exc: + print(f"[Warn] Skip {name}: mesh load failed: {exc}") + continue + if mesh.vertex_normals is None or len(mesh.vertex_normals) == 0: + mesh.rezero() + mesh = mesh.copy() + mesh.vertex_normals = mesh.vertex_normals + + positions = np.asarray(mesh.vertices, dtype=np.float32) + normals = np.asarray(mesh.vertex_normals, dtype=np.float32) + indices = np.asarray(mesh.faces, dtype=np.uint32).reshape(-1) + + pos_acc = builder.add_array(positions, "VEC3", 5126) + nrm_acc = builder.add_array(normals, "VEC3", 5126) + idx_acc = builder.add_array(indices, "SCALAR", 5125) + + attrs = {"POSITION": pos_acc, "NORMAL": nrm_acc} + uv = getattr(mesh.visual, "uv", None) + has_uv = False + if uv is not None: + uv_arr = np.asarray(uv, dtype=np.float32) + if uv_arr.ndim == 2 and uv_arr.shape[0] == positions.shape[0] and uv_arr.shape[1] >= 2: + uv_gltf = uv_arr[:, :2].copy() + uv_gltf[:, 1] = 1.0 - uv_gltf[:, 1] + uv_acc = builder.add_array(uv_gltf, "VEC2", 5126) + attrs["TEXCOORD_0"] = uv_acc + has_uv = True + + if getattr(mesh.visual, "vertex_colors", None) is not None: + colors = np.asarray(mesh.visual.vertex_colors, dtype=np.uint8) + if colors.shape[1] == 3: + alpha = np.full((colors.shape[0], 1), 255, dtype=np.uint8) + colors = np.concatenate([colors, alpha], axis=1) + col_acc = builder.add_array(colors, "VEC4", 5121, normalized=True) + attrs["COLOR_0"] = col_acc + + texture_path = _find_obj_texture(mesh_path) + material_index = _material_for_texture_path(texture_path, has_uv=has_uv) + primitive = Primitive(attributes=attrs, indices=idx_acc, material=material_index) + mesh_gltf = Mesh(primitives=[primitive], name=_safe_name(name)) + mesh_index = len(meshes) + meshes.append(mesh_gltf) + + node = Node(name=name, mesh=mesh_index) + node_index = len(nodes) + nodes.append(node) + + root.children = (root.children or []) + [node_index] + + if category == "static" and args.use_locked_static: + ref_frame = min(visible_frames) if visible_frames else 0 + ref_frame = int(np.clip(ref_frame, 0, num_frames - 1)) + w_T_o = np.linalg.inv(extrinsics[ref_frame]) @ pose_seq[ref_frame] + if align_T is not None: + w_T_o = align_T @ w_T_o + if visible_frames is None or visible_frames: + verts_h = np.concatenate( + [positions.astype(np.float32), np.ones((positions.shape[0], 1), dtype=np.float32)], axis=1 + ) + verts_w = (w_T_o @ verts_h.T).T[:, :3] + bbox_min = np.minimum(bbox_min, verts_w.min(axis=0)) + bbox_max = np.maximum(bbox_max, verts_w.max(axis=0)) + bbox_min_static = np.minimum(bbox_min_static, verts_w.min(axis=0)) + t = w_T_o[:3, 3] + q = _matrix_to_quat(w_T_o) + node.translation = t.tolist() + node.rotation = q.tolist() + _append_visibility_scale_animation(node_index, node, visible_frames) + continue + + translations: List[List[float]] = [] + rotations: List[List[float]] = [] + bbox_recorded = False + for i in range(num_frames): + w_T_o = np.linalg.inv(extrinsics[i]) @ pose_seq[i] + if align_T is not None: + w_T_o = align_T @ w_T_o + translations.append(w_T_o[:3, 3].astype(np.float32).tolist()) + rotations.append(_matrix_to_quat(w_T_o).tolist()) + visible = visible_frames is None or i in visible_frames + if visible and not bbox_recorded: + verts_h = np.concatenate( + [positions.astype(np.float32), np.ones((positions.shape[0], 1), dtype=np.float32)], axis=1 + ) + verts_w = (w_T_o @ verts_h.T).T[:, :3] + bbox_min = np.minimum(bbox_min, verts_w.min(axis=0)) + bbox_max = np.maximum(bbox_max, verts_w.max(axis=0)) + if category == "static": + bbox_min_static = np.minimum(bbox_min_static, verts_w.min(axis=0)) + bbox_recorded = True + + time_acc = builder.add_array(times, "SCALAR", 5126) + trans_acc = builder.add_array(np.asarray(translations, dtype=np.float32), "VEC3", 5126) + rot_acc = builder.add_array(np.asarray(rotations, dtype=np.float32), "VEC4", 5126) + + trans_sampler = AnimationSampler(input=time_acc, output=trans_acc, interpolation="LINEAR") + rot_sampler = AnimationSampler(input=time_acc, output=rot_acc, interpolation="LINEAR") + + trans_sampler_index = len(animation_samplers) + animation_samplers.append(trans_sampler) + rot_sampler_index = len(animation_samplers) + animation_samplers.append(rot_sampler) + + animation_channels.append( + AnimationChannel( + sampler=trans_sampler_index, + target=AnimationChannelTarget(node=node_index, path="translation"), + ) + ) + animation_channels.append( + AnimationChannel( + sampler=rot_sampler_index, + target=AnimationChannelTarget(node=node_index, path="rotation"), + ) + ) + _append_visibility_scale_animation(node_index, node, visible_frames) + + if args.animate_camera: + K0 = intrinsics[0] + height = int(data["video"].shape[2]) if "video" in data else int(data["depths"].shape[1]) + width = int(data["video"].shape[3]) if "video" in data else int(data["depths"].shape[2]) + fy = float(K0[1, 1]) + yfov = 2.0 * math.atan(0.5 * height / max(1e-6, fy)) + aspect = float(width) / float(height) + + gltf.cameras = [Camera(type="perspective", perspective={"yfov": yfov, "aspectRatio": aspect, "znear": 0.01})] + cam_node = Node(name="camera", camera=0) + cam_node_index = len(nodes) + nodes.append(cam_node) + root.children = (root.children or []) + [cam_node_index] + + cam_translations: List[List[float]] = [] + cam_rotations: List[List[float]] = [] + for i in range(num_frames): + cam_to_world = np.linalg.inv(extrinsics[i]) + if align_T is not None: + cam_to_world = align_T @ cam_to_world + cam_translations.append(cam_to_world[:3, 3].astype(np.float32).tolist()) + cam_rotations.append(_matrix_to_quat(cam_to_world).tolist()) + + time_acc = builder.add_array(times, "SCALAR", 5126) + trans_acc = builder.add_array(np.asarray(cam_translations, dtype=np.float32), "VEC3", 5126) + rot_acc = builder.add_array(np.asarray(cam_rotations, dtype=np.float32), "VEC4", 5126) + + trans_sampler = AnimationSampler(input=time_acc, output=trans_acc, interpolation="LINEAR") + rot_sampler = AnimationSampler(input=time_acc, output=rot_acc, interpolation="LINEAR") + trans_sampler_index = len(animation_samplers) + animation_samplers.append(trans_sampler) + rot_sampler_index = len(animation_samplers) + animation_samplers.append(rot_sampler) + + animation_channels.append( + AnimationChannel( + sampler=trans_sampler_index, + target=AnimationChannelTarget(node=cam_node_index, path="translation"), + ) + ) + animation_channels.append( + AnimationChannel( + sampler=rot_sampler_index, + target=AnimationChannelTarget(node=cam_node_index, path="rotation"), + ) + ) + + if args.add_plane and np.isfinite(bbox_min).all(): + center = (bbox_min + bbox_max) * 0.5 + extent = bbox_max - bbox_min + max_extent = float(np.max(extent)) + half = args.plane_scale * max_extent * 0.5 + z0 = 0.0 + if args.plane_z == "minz": + z0 = float(bbox_min[2]) + elif args.plane_z == "static_minz": + if np.isfinite(bbox_min_static).all(): + z0 = float(bbox_min_static[2]) + else: + z0 = float(bbox_min[2]) + plane_verts = np.array( + [ + [center[0] + half, center[1] + half, z0], + [center[0] - half, center[1] + half, z0], + [center[0] - half, center[1] - half, z0], + [center[0] + half, center[1] - half, z0], + ], + dtype=np.float32, + ) + plane_faces = np.array([0, 1, 2, 0, 2, 3], dtype=np.uint32) + plane_colors = np.tile(np.array([200, 200, 200, 255], dtype=np.uint8), (4, 1)) + + plane_pos_acc = builder.add_array(plane_verts, "VEC3", 5126) + plane_normals = np.tile(np.array([0.0, 0.0, 1.0], dtype=np.float32), (4, 1)) + plane_nrm_acc = builder.add_array(plane_normals, "VEC3", 5126) + plane_idx_acc = builder.add_array(plane_faces, "SCALAR", 5125) + plane_col_acc = builder.add_array(plane_colors, "VEC4", 5121, normalized=True) + + plane_attrs = {"POSITION": plane_pos_acc, "NORMAL": plane_nrm_acc, "COLOR_0": plane_col_acc} + plane_primitive = Primitive(attributes=plane_attrs, indices=plane_idx_acc, material=0) + plane_mesh = Mesh(primitives=[plane_primitive], name="table_plane") + plane_mesh_index = len(meshes) + meshes.append(plane_mesh) + plane_node = Node(name="table_plane", mesh=plane_mesh_index) + plane_node_index = len(nodes) + nodes.append(plane_node) + root.children = (root.children or []) + [plane_node_index] + + gltf.meshes = meshes + gltf.nodes = nodes + gltf.scenes = [Scene(nodes=[root_index])] + gltf.scene = 0 + + if animation_channels: + gltf.animations = [Animation(samplers=animation_samplers, channels=animation_channels)] + + gltf.bufferViews = builder.bufferViews + gltf.accessors = builder.accessors + gltf.buffers = [Buffer(byteLength=len(builder.buffer))] + gltf.set_binary_blob(bytes(builder.buffer)) + + output_path.parent.mkdir(parents=True, exist_ok=True) + gltf.save_binary(output_path) + print(f"[OK] Wrote: {output_path}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/export_scene_glb_with_deform.py b/OVOW/engine/tools/export_scene_glb_with_deform.py new file mode 100644 index 0000000000000000000000000000000000000000..26eabf33dfa14f58f8afcd05f6656f388fabb36f --- /dev/null +++ b/OVOW/engine/tools/export_scene_glb_with_deform.py @@ -0,0 +1,309 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import os +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Dict, List, Optional, Tuple + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Export a full-scene GLB by merging rigid/static GLB with deform mesh-sequence animations." + ) + parser.add_argument("--run-dir", type=Path, required=True, help="Run dir, e.g. .../video_pipeline_xxx/V0") + parser.add_argument("--config", type=Path, required=True, help="Pipeline config path") + parser.add_argument("--output", type=Path, required=True, help="Final merged GLB output path") + parser.add_argument( + "--motion-output-root", + type=Path, + required=True, + help="Motion output root, e.g. outputs/motion324_outputs", + ) + parser.add_argument( + "--motion-manifest", + type=Path, + default=None, + help="Optional motion manifest path (default: //manifest.json)", + ) + parser.add_argument( + "--deform-frames-dir", + type=str, + default="world_mesh_frames", + help="Mesh-frame dir name under each deform object", + ) + parser.add_argument("--alignment", type=Path, default=None, help="Optional alignment_plane.json") + parser.add_argument( + "--coord", + type=str, + default="blender_zup", + choices=("gltf", "opengl", "blender", "blender_noflip", "blender_zup", "raw"), + help="Coordinate conversion for both rigid and deform exports", + ) + parser.add_argument("--fps", type=float, default=10.0, help="Animation FPS") + parser.add_argument("--blender-bin", type=Path, required=True, help="Blender binary for final merge") + parser.add_argument("--blender-lib", type=Path, default=None, help="Optional Blender lib path for LD_LIBRARY_PATH") + parser.add_argument( + "--base-glb", + type=Path, + default=None, + help="Optional existing rigid/static GLB (skip rigid export when provided)", + ) + parser.add_argument("--pose-name", type=str, default="", help="Optional pose json name for rigid/static export") + parser.add_argument("--no-locked-static", action="store_true", help="Disable locked static behavior") + parser.add_argument("--no-plane", action="store_true", help="Do not add plane in rigid/static base GLB") + parser.add_argument( + "--plane-z", + type=str, + default="static_minz", + choices=("static_minz", "zero", "minz"), + help="Plane mode for rigid/static base GLB", + ) + parser.add_argument("--keep-temp", action="store_true", help="Keep temporary intermediate files") + return parser.parse_args() + + +def _run(cmd: List[str], env: dict | None = None) -> None: + print("[CMD]", " ".join(cmd)) + subprocess.check_call(cmd, env=env) + + +def _safe_name(name: str) -> str: + return "".join(c if c.isalnum() or c in ("-", "_") else "_" for c in name) + + +def _find_first_existing(candidates: List[Path]) -> Optional[Path]: + for p in candidates: + if p.exists(): + return p.resolve() + return None + + +def _resolve_cfg_path(base: Path, value: str) -> Path: + path = Path(value) + return path if path.is_absolute() else (base / path).resolve() + + +def _load_config_mask_info(config_path: Path) -> Tuple[Dict[str, Path], str]: + payload = json.loads(config_path.read_text()) + base = config_path.parent.resolve() + mask_glob = str(payload.get("mask_glob", "frame_*.png")) + mask_dirs: Dict[str, Path] = {} + for obj in payload.get("objects", []): + if not isinstance(obj, dict): + continue + name = str(obj.get("name") or obj.get("id") or "").strip() + masks_raw = str(obj.get("masks_dir") or obj.get("masks") or "").strip() + if name and masks_raw: + mask_dirs[name] = _resolve_cfg_path(base, masks_raw) + return mask_dirs, mask_glob + + +def _resolve_hunyuan_dir(obj_payload: dict) -> Optional[Path]: + processed_dir = str(obj_payload.get("processed_dir", "")).strip() + if processed_dir: + p = Path(processed_dir).resolve() / "Hunyuan_Gen_Input" + if p.exists(): + return p + + ref_mesh = str(obj_payload.get("ref_mesh", "")).strip() + if ref_mesh: + p = Path(ref_mesh).resolve().parent + if p.exists(): + return p + return None + + +def _pick_deform_uv_and_texture_from_source(obj_payload: dict) -> Tuple[Optional[Path], Optional[Path]]: + """ + Prefer Hunyuan source OBJ+texture for deform material consistency. + """ + hdir = _resolve_hunyuan_dir(obj_payload) + if hdir is None: + return None, None + + uv_obj = _find_first_existing( + [ + hdir / "000000_hunyuan_original_wo_remap_converted.obj", + hdir / "000000_hunyuan_original_wo_remap.obj", + hdir / "000000_hunyuan_original_watertight.obj", + ] + ) + if uv_obj is None: + obj_paths = sorted(hdir.glob("*converted.obj")) + if obj_paths: + uv_obj = obj_paths[0].resolve() + else: + any_objs = sorted(hdir.glob("*.obj")) + if any_objs: + uv_obj = any_objs[0].resolve() + + tex = _find_first_existing( + [ + hdir / "material_0.png", + hdir / "material.png", + ] + ) + return uv_obj, tex + + +def main() -> None: + args = parse_args() + + run_dir = args.run_dir.resolve() + cfg = args.config.resolve() + out_glb = args.output.resolve() + motion_root = args.motion_output_root.resolve() + + if not run_dir.exists(): + raise FileNotFoundError(run_dir) + if not cfg.exists(): + raise FileNotFoundError(cfg) + if not args.blender_bin.exists(): + resolved = shutil.which(str(args.blender_bin)) + if resolved is None: + raise FileNotFoundError(args.blender_bin) + args.blender_bin = Path(resolved) + + config_mask_dirs, config_mask_glob = _load_config_mask_info(cfg) + + video_name = run_dir.name + manifest = ( + args.motion_manifest.resolve() + if args.motion_manifest is not None + else (motion_root / video_name / "manifest.json") + ) + motion_root_exists = motion_root.exists() + + tmp_ctx = tempfile.TemporaryDirectory(prefix=f"scene_glb_with_deform_{video_name}_") + tmp_dir = Path(tmp_ctx.name) + if args.keep_temp: + print(f"[Info] keep-temp enabled, temp dir: {tmp_dir}") + + try: + if args.base_glb is not None: + base_glb = args.base_glb.resolve() + if not base_glb.exists(): + raise FileNotFoundError(base_glb) + else: + base_glb = tmp_dir / "base_rigid_static.glb" + rigid_cmd = [ + str(Path(sys.executable)), + str(Path(__file__).resolve().parent / "export_scene_glb_anim.py"), + "--run-dir", + str(run_dir), + "--config", + str(cfg), + "--output", + str(base_glb), + "--coord", + args.coord, + "--fps", + str(float(args.fps)), + ] + if args.pose_name: + rigid_cmd.extend(["--pose-name", args.pose_name]) + if not args.no_locked_static: + rigid_cmd.append("--use-locked-static") + if not args.no_plane: + rigid_cmd.extend(["--add-plane", "--plane-z", args.plane_z]) + if args.alignment is not None: + rigid_cmd.extend(["--alignment", str(args.alignment.resolve())]) + _run(rigid_cmd) + + deform_glbs: List[Path] = [] + if manifest.exists(): + payload = json.loads(manifest.read_text()) + for obj in payload.get("objects", []): + name = str(obj.get("name", "")).strip() + if not name: + continue + mesh_dir = motion_root / video_name / name / args.deform_frames_dir + if not mesh_dir.exists(): + print(f"[Warn] Skip deform {name}: missing {mesh_dir}") + continue + out_obj_glb = tmp_dir / f"deform_{_safe_name(name)}.glb" + deform_cmd = [ + str(Path(sys.executable)), + str(Path(__file__).resolve().parent / "export_deform_mesh_sequence_glb.py"), + "--mesh-dir", + str(mesh_dir), + "--output", + str(out_obj_glb), + "--object-name", + name, + "--fps", + str(float(args.fps)), + "--coord", + args.coord, + ] + mask_dir = config_mask_dirs.get(name) + if mask_dir is not None: + deform_cmd.extend(["--visibility-mask-dir", str(mask_dir), "--visibility-mask-glob", config_mask_glob]) + uv_obj, tex_path = _pick_deform_uv_and_texture_from_source(obj) + if uv_obj is not None: + deform_cmd.extend(["--uv-template-obj", str(uv_obj)]) + print(f"[Info] deform {name}: use UV template {uv_obj}") + if tex_path is not None: + deform_cmd.extend(["--texture-path", str(tex_path)]) + print(f"[Info] deform {name}: use texture {tex_path}") + if args.alignment is not None: + deform_cmd.extend(["--alignment", str(args.alignment.resolve())]) + _run(deform_cmd) + deform_glbs.append(out_obj_glb) + else: + if not motion_root_exists: + print(f"[Info] Motion output root not found: {motion_root}. Output rigid/static GLB only.") + else: + print(f"[Warn] Motion manifest not found: {manifest}. Output rigid/static GLB only.") + + out_glb.parent.mkdir(parents=True, exist_ok=True) + merge_cmd = [ + str(Path(sys.executable)), + str(Path(__file__).resolve().parent / "merge_glb_anim.py"), + "--base", + str(base_glb), + "--output", + str(out_glb), + "--blender", + str(args.blender_bin), + ] + for p in deform_glbs: + merge_cmd.extend(["--add", str(p)]) + + env = dict(os.environ) + if args.blender_lib is not None: + env["LD_LIBRARY_PATH"] = f"{args.blender_lib}:{env.get('LD_LIBRARY_PATH', '')}" + + if not deform_glbs: + print("[Info] No deform GLBs found. Re-exporting base GLB via Blender for stable texture embedding.") + _run(merge_cmd, env=env) + + merged_clip_glb = tmp_dir / "merged_single_clip.glb" + merge_clip_cmd = [ + str(Path(sys.executable)), + str(Path(__file__).resolve().parent / "merge_glb_animation_clips.py"), + "--input", + str(out_glb), + "--output", + str(merged_clip_glb), + "--name", + f"{video_name}_all_animations", + ] + _run(merge_clip_cmd) + shutil.move(str(merged_clip_glb), str(out_glb)) + print("[Info] Collapsed scene animation clips into a single clip for stable playback.") + + print(f"[OK] Wrote merged scene GLB: {out_glb}") + finally: + if not args.keep_temp: + tmp_ctx.cleanup() + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/export_scene_mesh_frames.py b/OVOW/engine/tools/export_scene_mesh_frames.py new file mode 100644 index 0000000000000000000000000000000000000000..d0a26bb46666ec14b9de74d6a6f01b8f70804a29 --- /dev/null +++ b/OVOW/engine/tools/export_scene_mesh_frames.py @@ -0,0 +1,381 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Dict, List, Optional + +import cv2 +import numpy as np +import trimesh + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Export per-frame scene OBJ sequence by composing static/rigid objects with deform world-mesh frames." + ) + parser.add_argument("--run-dir", type=Path, required=True, help="Run dir, e.g. .../video_pipeline_xxx/V1") + parser.add_argument("--config", type=Path, required=True, help="Pipeline config JSON") + parser.add_argument("--output-dir", type=Path, required=True, help="Output scene frame directory") + parser.add_argument( + "--alignment", + type=Path, + default=None, + help="Optional alignment json with 4x4 transform matrix T", + ) + parser.add_argument( + "--pose-name", + type=str, + default="", + help="Preferred pose filename for static/rigid objects under pose_result", + ) + parser.add_argument("--use-locked-static", action="store_true", help="Fallback to poses_locked.json for static") + parser.add_argument( + "--deform-root", + type=Path, + default=None, + help="Motion output root (e.g., outputs/motion324_outputs)", + ) + parser.add_argument( + "--deform-manifest", + type=Path, + default=None, + help="Optional deform manifest.json", + ) + parser.add_argument( + "--deform-frames-dir", + type=str, + default="world_mesh_frames", + help="Deform mesh directory name under each object", + ) + parser.add_argument( + "--max-frames", + type=int, + default=-1, + help="Optional max frames; <=0 uses result.npz length", + ) + parser.add_argument( + "--mapping-name", + type=str, + default="scene_mesh_frames_manifest.json", + help="Output mapping json filename under output-dir", + ) + return parser.parse_args() + + +def _parse_frame_id(path: Path) -> Optional[int]: + stem = path.stem + for part in reversed(stem.split("_")): + if part.isdigit(): + return int(part) + digits = "".join(ch if ch.isdigit() else " " for ch in stem).split() + if digits: + return int(digits[-1]) + return None + + +def _nearest_key(target: int, keys: List[int]) -> int: + return min(keys, key=lambda x: abs(x - target)) + + +def _safe_name(name: str) -> str: + return "".join(c if c.isalnum() or c in ("-", "_") else "_" for c in name) + + +def _mesh_from_path(path: Path) -> trimesh.Trimesh: + mesh = trimesh.load(str(path), force="mesh") + if isinstance(mesh, trimesh.Scene): + geos = [g for g in mesh.geometry.values() if isinstance(g, trimesh.Trimesh)] + if not geos: + raise RuntimeError(f"No geometry in mesh scene: {path}") + mesh = trimesh.util.concatenate(geos) + if not isinstance(mesh, trimesh.Trimesh): + raise RuntimeError(f"Invalid mesh: {path}") + return mesh + + +def _pick_mesh_path(obj_dir: Path) -> Path: + candidates: List[Path] = [] + candidates.append(obj_dir / "mid_files" / "scaled_mesh.obj") + candidates.extend(sorted((obj_dir / "model" / "middle_file").glob("*_high_mesh.obj"))) + candidates.append(obj_dir / "model" / "model.obj") + for p in candidates: + if p.exists(): + return p + raise FileNotFoundError(f"No mesh found in {obj_dir}") + + +def _pick_pose_json(obj_dir: Path, category: str, pose_name: str, use_locked_static: bool) -> Path: + pose_dir = obj_dir / "pose_result" + if pose_name: + preferred = pose_dir / pose_name + if preferred.exists(): + return preferred + if use_locked_static and category == "static": + locked = pose_dir / "poses_locked.json" + if locked.exists(): + return locked + default = pose_dir / "poses.json" + if default.exists(): + return default + locked = pose_dir / "poses_locked.json" + if locked.exists(): + return locked + raise FileNotFoundError(f"No pose json found under {pose_dir}") + + +def _load_pose_map(path: Path) -> Dict[int, np.ndarray]: + payload = json.loads(path.read_text()) + out: Dict[int, np.ndarray] = {} + for k, v in payload.items(): + try: + fid = int(k) + except Exception: + continue + arr = np.asarray(v, dtype=np.float32) + if arr.shape != (4, 4): + continue + out[fid] = arr + if not out: + raise ValueError(f"No valid poses in {path}") + return out + + +def _load_alignment(path: Optional[Path]) -> Optional[np.ndarray]: + if path is None: + return None + if not path.exists(): + raise FileNotFoundError(path) + payload = json.loads(path.read_text()) + T = np.asarray(payload.get("T"), dtype=np.float32) + if T.shape != (4, 4): + raise ValueError(f"Alignment T must be 4x4, got {T.shape}") + return T + + +def _transform_points(T: np.ndarray, verts: np.ndarray) -> np.ndarray: + ones = np.ones((verts.shape[0], 1), dtype=np.float32) + verts_h = np.concatenate([verts, ones], axis=1) + return (T @ verts_h.T).T[:, :3] + + +def _load_deform_mesh_map(mesh_dir: Path) -> Dict[int, Path]: + out: Dict[int, Path] = {} + for p in sorted(mesh_dir.glob("frame_*.obj")): + fid = _parse_frame_id(p) + if fid is None: + continue + out[fid] = p + return out + + +def _load_visible_mask_frames(mask_dir: Optional[Path]) -> Optional[set[int]]: + """ + Return frame ids whose mask has non-zero foreground. + If mask directory is missing or unreadable, return None (no visibility gating). + """ + if mask_dir is None or not mask_dir.exists(): + return None + visible: set[int] = set() + has_any = False + for p in sorted(mask_dir.glob("*.png")): + fid = _parse_frame_id(p) + if fid is None: + continue + has_any = True + m = cv2.imread(str(p), cv2.IMREAD_GRAYSCALE) + if m is None: + continue + if int(np.count_nonzero(m)) > 0: + visible.add(int(fid)) + if not has_any: + return None + return visible + + +def main() -> None: + args = parse_args() + + run_dir = args.run_dir.resolve() + config_path = args.config.resolve() + output_dir = args.output_dir.resolve() + + if not run_dir.exists(): + raise FileNotFoundError(run_dir) + if not config_path.exists(): + raise FileNotFoundError(config_path) + + align_T = _load_alignment(args.alignment.resolve() if args.alignment else None) + + with config_path.open("r", encoding="utf-8") as f: + cfg = json.load(f) + categories = {o["name"]: str(o.get("category", "")).lower() for o in cfg.get("objects", [])} + config_base = config_path.parent.resolve() + mask_dirs: Dict[str, Path] = {} + for obj in cfg.get("objects", []): + if not isinstance(obj, dict): + continue + name = str(obj.get("name") or obj.get("id") or "").strip() + masks_raw = str(obj.get("masks_dir") or obj.get("masks") or "").strip() + if not name or not masks_raw: + continue + mask_path = Path(masks_raw) + mask_dirs[name] = mask_path if mask_path.is_absolute() else (config_base / mask_path).resolve() + + result_npz = run_dir / "results" / "result.npz" + if not result_npz.exists(): + raise FileNotFoundError(result_npz) + data = np.load(result_npz) + extrinsics = data["extrinsics"] + num_frames = int(extrinsics.shape[0]) + if args.max_frames > 0: + num_frames = min(num_frames, int(args.max_frames)) + + rigid_objects: List[Dict[str, object]] = [] + objects_root = run_dir / "objects" + if objects_root.exists(): + for obj_dir in sorted([d for d in objects_root.iterdir() if d.is_dir()]): + name = obj_dir.name + category = categories.get(name, "") + if category == "deform": + continue + try: + mesh_path = _pick_mesh_path(obj_dir) + pose_json = _pick_pose_json( + obj_dir, + category=category, + pose_name=args.pose_name, + use_locked_static=args.use_locked_static, + ) + except Exception as exc: + print(f"[Warn] Skip rigid/static {name}: {exc}") + continue + + mesh = _mesh_from_path(mesh_path) + verts_local = np.asarray(mesh.vertices, dtype=np.float32) + faces = np.asarray(mesh.faces, dtype=np.int64) + pose_map = _load_pose_map(pose_json) + + rigid_objects.append( + { + "name": name, + "category": category, + "verts_local": verts_local, + "faces": faces, + "pose_map": pose_map, + "pose_ids": sorted(pose_map.keys()), + "visible_frames": _load_visible_mask_frames(obj_dir / "masks"), + } + ) + + deform_objects: List[Dict[str, object]] = [] + if args.deform_root is not None: + deform_root = args.deform_root.resolve() + video_name = run_dir.name + manifest_path = ( + args.deform_manifest.resolve() + if args.deform_manifest is not None + else (deform_root / video_name / "manifest.json") + ) + if manifest_path.exists(): + manifest = json.loads(manifest_path.read_text()) + for obj in manifest.get("objects", []): + name = str(obj.get("name", "")).strip() + if not name: + continue + obj_root = deform_root / video_name / name + frames_dir = obj_root / args.deform_frames_dir + if not frames_dir.exists(): + continue + mesh_map = _load_deform_mesh_map(frames_dir) + if not mesh_map: + continue + deform_objects.append( + { + "name": name, + "root": obj_root, + "mesh_map": mesh_map, + "mesh_ids": sorted(mesh_map.keys()), + "visible_frames": _load_visible_mask_frames(mask_dirs.get(name)), + } + ) + + output_dir.mkdir(parents=True, exist_ok=True) + + mapping: Dict[str, object] = { + "run_dir": str(run_dir), + "config": str(config_path), + "alignment": str(args.alignment) if args.alignment else None, + "pose_name": args.pose_name or "auto", + "deform_frames_dir": args.deform_frames_dir, + "num_frames": num_frames, + "frames": {}, + } + + for frame in range(num_frames): + meshes_frame: List[trimesh.Trimesh] = [] + frame_info = {"rigid": [], "deform": []} + + for robj in rigid_objects: + visible_frames = robj.get("visible_frames") + if visible_frames is not None and frame not in visible_frames: + continue + pose_map = robj["pose_map"] + pose_ids = robj["pose_ids"] + pf = frame if frame in pose_map else _nearest_key(frame, pose_ids) + c_T_o = pose_map[pf] + w_T_o = np.linalg.inv(extrinsics[frame]) @ c_T_o + if align_T is not None: + w_T_o = align_T @ w_T_o + + verts_world = _transform_points(w_T_o, robj["verts_local"]) + mesh_obj = trimesh.Trimesh(vertices=verts_world, faces=robj["faces"], process=False) + meshes_frame.append(mesh_obj) + frame_info["rigid"].append({"name": robj["name"], "pose_frame": int(pf)}) + + for dobj in deform_objects: + visible_frames = dobj.get("visible_frames") + if visible_frames is not None and frame not in visible_frames: + continue + mesh_map = dobj["mesh_map"] + mesh_ids = dobj["mesh_ids"] + mf = frame if frame in mesh_map else _nearest_key(frame, mesh_ids) + mesh_path = mesh_map[mf] + mesh = _mesh_from_path(mesh_path) + + if align_T is not None: + verts = _transform_points(align_T, np.asarray(mesh.vertices, dtype=np.float32)) + mesh = mesh.copy() + mesh.vertices = verts + + meshes_frame.append(mesh) + frame_info["deform"].append( + { + "name": dobj["name"], + "mesh_frame": int(mf), + "mesh_path": str(mesh_path), + } + ) + + if not meshes_frame: + continue + + if len(meshes_frame) == 1: + merged = meshes_frame[0] + else: + merged = trimesh.util.concatenate(meshes_frame) + + out_path = output_dir / f"frame_{frame:06d}.obj" + merged.export(out_path) + frame_info["output"] = str(out_path) + mapping["frames"][str(frame)] = frame_info + + mapping_path = output_dir / args.mapping_name + mapping_path.write_text(json.dumps(mapping, indent=2)) + print(f"[OK] Wrote scene mesh sequence: {output_dir}") + print(f"[OK] Mapping: {mapping_path}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/export_step18_camera_bundle.py b/OVOW/engine/tools/export_step18_camera_bundle.py new file mode 100644 index 0000000000000000000000000000000000000000..af24d4caff77932fa053a355658945d161a3d126 --- /dev/null +++ b/OVOW/engine/tools/export_step18_camera_bundle.py @@ -0,0 +1,304 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Tuple + +import numpy as np + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Export raw and Blender-ready camera data matching Step 18 camera placement." + ) + parser.add_argument("--run-dir", type=Path, required=True, help="Run dir, e.g. .../outputs/") + parser.add_argument("--result-npz", type=Path, required=True, help="Path to run_dir/results/result.npz") + parser.add_argument("--alignment", type=Path, default=None, help="Optional alignment_plane.json") + parser.add_argument( + "--coord", + type=str, + default="blender_zup", + choices=("gltf", "opengl", "blender", "blender_noflip", "blender_zup", "raw"), + help="Coordinate conversion from OpenCV world to Blender scene world", + ) + parser.add_argument( + "--camera-axis", + type=str, + default="standard", + choices=("standard", "identity", "flip_xy", "yz_swap", "yz_swap_flipx"), + help="Camera local-axis mapping from Blender camera to OpenCV camera", + ) + parser.add_argument( + "--world-conv", + type=str, + default="identity", + choices=("identity", "rx90", "rxm90"), + help="Extra conversion from OpenCV world to scene world basis", + ) + parser.add_argument("--fps", type=float, default=10.0, help="Reference FPS for Blender scene setup") + parser.add_argument("--output-json", type=Path, required=True, help="Output JSON bundle path") + parser.add_argument("--output-npz", type=Path, required=True, help="Output NPZ bundle path") + return parser.parse_args() + + +def _load_alignment(path: Path | None) -> np.ndarray: + if path is None: + return np.eye(4, dtype=np.float32) + path = path.resolve() + if not path.exists(): + raise FileNotFoundError(path) + payload = json.loads(path.read_text(encoding="utf-8")) + T = np.asarray(payload.get("T"), dtype=np.float32) + if T.shape != (4, 4): + raise ValueError(f"Alignment T must be 4x4, got {T.shape}") + return T + + +def _cv_to_scene_matrix(coord: str) -> np.ndarray: + if coord == "raw": + return np.eye(4, dtype=np.float32) + if coord == "opengl": + return np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float32) + if coord == "blender": + rot_x_neg_90 = np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + flip_x = np.diag([-1.0, 1.0, 1.0, 1.0]).astype(np.float32) + return flip_x @ (rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32)) + if coord == "blender_noflip": + rot_x_neg_90 = np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return rot_x_neg_90 @ np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + if coord == "blender_zup": + return np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + return np.diag([1.0, -1.0, 1.0, 1.0]).astype(np.float32) + + +def _world_conv_matrix(name: str) -> np.ndarray: + if name == "identity": + return np.eye(4, dtype=np.float32) + if name == "rx90": + return np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + + +def _camera_axis_matrix(name: str) -> np.ndarray: + if name == "identity": + return np.eye(4, dtype=np.float32) + if name == "flip_xy": + return np.diag([-1.0, -1.0, 1.0, 1.0]).astype(np.float32) + if name == "standard": + return np.diag([1.0, -1.0, -1.0, 1.0]).astype(np.float32) + if name == "yz_swap": + return np.array( + [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + return np.array( + [ + [-1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, -1.0, 0.0], + [0.0, -1.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + + +def _image_size_from_result(data: np.lib.npyio.NpzFile) -> Tuple[int, int]: + if "video" in data: + video_arr = data["video"] + if video_arr.ndim == 4 and video_arr.shape[1] in (1, 3, 4): + return int(video_arr.shape[3]), int(video_arr.shape[2]) + if video_arr.ndim == 4: + return int(video_arr.shape[2]), int(video_arr.shape[1]) + raise ValueError(f"Invalid video shape: {video_arr.shape}") + if "depths" in data: + dep = data["depths"] + if dep.ndim != 3: + raise ValueError(f"Invalid depths shape: {dep.shape}") + return int(dep.shape[2]), int(dep.shape[1]) + raise KeyError("result.npz missing both 'video' and 'depths'") + + +def _camera_params_from_intrinsics(K: np.ndarray, width: int, height: int) -> Tuple[float, float, float, float]: + fx = float(K[0, 0]) + fy = float(K[1, 1]) + cx = float(K[0, 2]) + cy = float(K[1, 2]) + W = max(1.0, float(width)) + H = max(1.0, float(height)) + + sensor_width = 36.0 + lens = fx * sensor_width / W + sensor_height = max(1e-6, lens * H / max(1e-6, fy)) + shift_x = -(cx - 0.5 * W) / W + shift_y = (cy - 0.5 * H) / H + return lens, sensor_width, sensor_height, shift_x, shift_y + + +def main() -> None: + args = parse_args() + + run_dir = args.run_dir.resolve() + result_npz = args.result_npz.resolve() + output_json = args.output_json.resolve() + output_npz = args.output_npz.resolve() + alignment_path = args.alignment.resolve() if args.alignment is not None else None + + if not run_dir.exists(): + raise FileNotFoundError(run_dir) + if not result_npz.exists(): + raise FileNotFoundError(result_npz) + + data = np.load(result_npz) + extrinsics = np.asarray(data["extrinsics"], dtype=np.float32) + intrinsics = np.asarray(data["intrinsics"], dtype=np.float32) + if extrinsics.ndim != 3 or extrinsics.shape[1:] != (4, 4): + raise ValueError(f"Invalid extrinsics shape: {extrinsics.shape}") + if intrinsics.ndim != 3 or intrinsics.shape[1:] != (3, 3): + raise ValueError(f"Invalid intrinsics shape: {intrinsics.shape}") + if extrinsics.shape[0] != intrinsics.shape[0]: + raise ValueError("extrinsics/intrinsics frame counts do not match") + + width, height = _image_size_from_result(data) + num_frames = int(extrinsics.shape[0]) + frame_ids = np.arange(num_frames, dtype=np.int32) + + align_T = _load_alignment(alignment_path) + cv_to_scene = _cv_to_scene_matrix(args.coord) + world_conv = _world_conv_matrix(args.world_conv) + cv_cam_to_bl_cam = _camera_axis_matrix(args.camera_axis) + scene_from_cv_aligned = cv_to_scene @ world_conv @ align_T + + camera_to_world_cv = np.zeros_like(extrinsics, dtype=np.float32) + blender_matrix_world = np.zeros_like(extrinsics, dtype=np.float32) + lens_arr = np.zeros((num_frames,), dtype=np.float32) + sensor_width_arr = np.zeros((num_frames,), dtype=np.float32) + sensor_height_arr = np.zeros((num_frames,), dtype=np.float32) + shift_x_arr = np.zeros((num_frames,), dtype=np.float32) + shift_y_arr = np.zeros((num_frames,), dtype=np.float32) + + frames_payload = [] + for frame in range(num_frames): + cam_to_world_cv = np.linalg.inv(extrinsics[frame]).astype(np.float32) + matrix_world = (scene_from_cv_aligned @ cam_to_world_cv @ cv_cam_to_bl_cam).astype(np.float32) + lens, sensor_width, sensor_height, shift_x, shift_y = _camera_params_from_intrinsics( + intrinsics[frame], width, height + ) + + camera_to_world_cv[frame] = cam_to_world_cv + blender_matrix_world[frame] = matrix_world + lens_arr[frame] = lens + sensor_width_arr[frame] = sensor_width + sensor_height_arr[frame] = sensor_height + shift_x_arr[frame] = shift_x + shift_y_arr[frame] = shift_y + + frames_payload.append( + { + "frame": int(frame), + "intrinsics": intrinsics[frame].tolist(), + "extrinsics_world_to_camera_cv": extrinsics[frame].tolist(), + "camera_to_world_cv": cam_to_world_cv.tolist(), + "blender_matrix_world": matrix_world.tolist(), + "blender_camera": { + "type": "PERSP", + "sensor_fit": "HORIZONTAL", + "lens": float(lens), + "sensor_width": float(sensor_width), + "sensor_height": float(sensor_height), + "shift_x": float(shift_x), + "shift_y": float(shift_y), + "clip_start": 1e-3, + "clip_end": 1e5, + }, + } + ) + + output_json.parent.mkdir(parents=True, exist_ok=True) + output_npz.parent.mkdir(parents=True, exist_ok=True) + + payload = { + "run_dir": str(run_dir), + "result_npz": str(result_npz), + "alignment_path": str(alignment_path) if alignment_path is not None else "", + "coord": args.coord, + "camera_axis": args.camera_axis, + "world_conv": args.world_conv, + "fps": float(args.fps), + "frame_count": num_frames, + "image_size": {"width": int(width), "height": int(height)}, + "alignment_T": align_T.tolist(), + "cv_to_scene": cv_to_scene.tolist(), + "world_conv_matrix": world_conv.tolist(), + "cv_cam_to_bl_cam": cv_cam_to_bl_cam.tolist(), + "scene_from_cv_aligned": scene_from_cv_aligned.tolist(), + "frames": frames_payload, + } + output_json.write_text(json.dumps(payload, indent=2), encoding="utf-8") + + np.savez_compressed( + output_npz, + frame_ids=frame_ids, + intrinsics=intrinsics, + extrinsics_world_to_camera_cv=extrinsics, + camera_to_world_cv=camera_to_world_cv, + blender_matrix_world=blender_matrix_world, + lens=lens_arr, + sensor_width=sensor_width_arr, + sensor_height=sensor_height_arr, + shift_x=shift_x_arr, + shift_y=shift_y_arr, + width=np.asarray([width], dtype=np.int32), + height=np.asarray([height], dtype=np.int32), + fps=np.asarray([float(args.fps)], dtype=np.float32), + alignment_T=align_T, + cv_to_scene=cv_to_scene, + world_conv_matrix=world_conv, + cv_cam_to_bl_cam=cv_cam_to_bl_cam, + scene_from_cv_aligned=scene_from_cv_aligned, + ) + + print(f"[OK] Wrote camera bundle JSON: {output_json}") + print(f"[OK] Wrote camera bundle NPZ: {output_npz}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/filter_pipeline_config.py b/OVOW/engine/tools/filter_pipeline_config.py new file mode 100644 index 0000000000000000000000000000000000000000..2355a825d40264787aaf730bf0660b46922810f6 --- /dev/null +++ b/OVOW/engine/tools/filter_pipeline_config.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import List + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Filter pipeline_config.json by object categories.") + parser.add_argument("--input", type=Path, required=True, help="input pipeline_config.json") + parser.add_argument("--output", type=Path, required=True, help="output pipeline_config.json") + parser.add_argument( + "--exclude-category", + type=str, + default="", + help="comma-separated categories to exclude", + ) + parser.add_argument( + "--include-category", + type=str, + default="", + help="comma-separated categories to include (if set, only these remain)", + ) + parser.add_argument( + "--drop-missing-masks", + action="store_true", + help="drop objects whose masks_dir is missing or has no mask files", + ) + parser.add_argument( + "--mask-glob", + type=str, + default="", + help="mask glob for --drop-missing-masks (default: config.mask_glob or frame_*.png)", + ) + return parser.parse_args() + + +def _resolve_path(base: Path, raw: object) -> Path: + path = Path(str(raw or "").strip()) + if not path.is_absolute(): + path = (base / path).resolve() + return path + + +def main() -> None: + args = parse_args() + cfg = json.loads(args.input.read_text()) + objs = cfg.get("objects", []) + if not isinstance(objs, list): + objs = [] + + exclude = {x.strip().lower() for x in args.exclude_category.split(",") if x.strip()} + include = {x.strip().lower() for x in args.include_category.split(",") if x.strip()} + mask_glob = args.mask_glob.strip() or str(cfg.get("mask_glob", "")).strip() or "frame_*.png" + cfg_base = args.input.parent.resolve() + + filtered: List[dict] = [] + dropped_missing: List[str] = [] + for obj in objs: + if not isinstance(obj, dict): + continue + cat = str(obj.get("category", "")).lower() + if include and cat not in include: + continue + if exclude and cat in exclude: + continue + if args.drop_missing_masks: + masks_dir = _resolve_path(cfg_base, obj.get("masks_dir", "")) + has_masks = masks_dir.exists() and any(masks_dir.glob(mask_glob)) + if not has_masks: + dropped_missing.append(str(obj.get("name", ""))) + continue + filtered.append(obj) + + cfg["objects"] = filtered + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(cfg, indent=2)) + + if dropped_missing: + print( + f"[filter] dropped {len(dropped_missing)} objects with missing masks " + f"(glob={mask_glob}): {', '.join(dropped_missing)}" + ) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/fit_plane_align.py b/OVOW/engine/tools/fit_plane_align.py new file mode 100644 index 0000000000000000000000000000000000000000..00f48d963fe8f623fb15430d0b438f23a06dd3fb --- /dev/null +++ b/OVOW/engine/tools/fit_plane_align.py @@ -0,0 +1,601 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +import numpy as np +import trimesh +from PIL import Image + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Fit tabletop plane from point cloud candidates and static mesh geometry." + ) + parser.add_argument("--run-dir", type=Path, required=True, help="Run dir, e.g. .../video_pipeline_xxx/V1") + parser.add_argument("--config", type=Path, required=True, help="Pipeline config JSON for static objects") + parser.add_argument( + "--pcd", + type=Path, + default=None, + help="Point cloud path (default: run-dir/scene_point_cloud_frame_all.ply)", + ) + parser.add_argument( + "--out", + type=Path, + default=None, + help="Output alignment JSON (default: run-dir/alignment_plane.json)", + ) + parser.add_argument("--static-only", action="store_true", help="Use static objects only for mesh evaluation") + parser.add_argument("--num-planes", type=int, default=5, help="Number of candidate planes to extract") + parser.add_argument("--max-iter", type=int, default=2000, help="RANSAC iterations per plane") + parser.add_argument("--dist-th", type=float, default=0.0, help="RANSAC inlier distance threshold") + parser.add_argument("--downsample", type=float, default=0.0, help="Voxel size for point cloud downsample") + parser.add_argument( + "--bottom-percent", + type=float, + default=0.03, + help="Percent (0-1) of closest mesh points to evaluate plane proximity", + ) + parser.add_argument( + "--camera-up-prior", + type=int, + default=1, + choices=(0, 1), + help="If enabled, prefer plane normal pointing to image-up in camera coords (OpenCV -Y).", + ) + parser.add_argument( + "--camera-up-samples", + type=int, + default=5, + help="Number of frames sampled for camera-up prior sign check.", + ) + parser.add_argument( + "--gravity-sign-mode", + type=str, + default="camera_up", + choices=("camera_up", "object_region", "auto", "none"), + help=( + "How to disambiguate the fitted plane normal sign: " + "camera_up=legacy image-up prior, object_region=use object masks and the " + "camera plane perpendicular to the fitted plane, auto=object_region then " + "fallback to camera_up, none=keep mesh-above sign only." + ), + ) + parser.add_argument( + "--gravity-sign-samples", + type=int, + default=5, + help="Number of frames sampled for object-region gravity sign voting.", + ) + parser.add_argument("--seed", type=int, default=0, help="Random seed") + return parser.parse_args() + + +def _extract_points(obj: trimesh.Trimesh | trimesh.PointCloud | trimesh.Scene) -> np.ndarray: + if isinstance(obj, trimesh.Scene): + pts = [] + for geom in obj.geometry.values(): + if hasattr(geom, "vertices"): + pts.append(np.asarray(geom.vertices)) + if not pts: + raise ValueError("No vertices found in scene geometry") + return np.vstack(pts) + if hasattr(obj, "vertices"): + return np.asarray(obj.vertices) + raise ValueError("Unsupported point cloud type") + + +def _voxel_downsample(points: np.ndarray, voxel: float) -> np.ndarray: + if voxel <= 0.0: + return points + scaled = np.floor(points / voxel).astype(np.int64) + _, idx = np.unique(scaled, axis=0, return_index=True) + return points[idx] + + +def _fit_plane_ransac( + points: np.ndarray, max_iter: int, dist_th: float, rng: np.random.Generator +) -> Tuple[np.ndarray, np.ndarray]: + best_inliers = None + best_count = -1 + best_plane = None + n_points = points.shape[0] + if n_points < 3: + raise ValueError("Not enough points for plane fitting") + + for _ in range(max_iter): + ids = rng.choice(n_points, size=3, replace=False) + p1, p2, p3 = points[ids] + v1 = p2 - p1 + v2 = p3 - p1 + n = np.cross(v1, v2) + norm = np.linalg.norm(n) + if norm < 1e-8: + continue + n = n / norm + d = -float(np.dot(n, p1)) + dist = np.abs(points @ n + d) + inliers = dist <= dist_th + count = int(inliers.sum()) + if count > best_count: + best_count = count + best_plane = (n, d) + best_inliers = inliers + + if best_inliers is None or best_plane is None: + raise RuntimeError("RANSAC failed to find a plane") + + inlier_pts = points[best_inliers] + if inlier_pts.shape[0] < 3: + n_ref, d_ref = best_plane + return np.asarray([*n_ref, d_ref], dtype=np.float32), best_inliers + centroid = inlier_pts.mean(axis=0) + cov = np.cov((inlier_pts - centroid).T) + eigvals, eigvecs = np.linalg.eigh(cov) + n_ref = eigvecs[:, 0] + n_ref = n_ref / max(1e-8, np.linalg.norm(n_ref)) + if np.dot(n_ref, best_plane[0]) < 0.0: + n_ref = -n_ref + d_ref = -float(np.dot(n_ref, centroid)) + return np.asarray([*n_ref, d_ref], dtype=np.float32), best_inliers + + +def _rotation_to_z(n: np.ndarray) -> np.ndarray: + n = n / max(1e-8, np.linalg.norm(n)) + target = np.array([0.0, 0.0, 1.0], dtype=np.float32) + if np.allclose(n, target, atol=1e-6): + return np.eye(3, dtype=np.float32) + if np.allclose(n, -target, atol=1e-6): + axis = np.array([1.0, 0.0, 0.0], dtype=np.float32) + return _axis_angle_to_matrix(axis, np.pi) + v = np.cross(n, target) + s = np.linalg.norm(v) + c = float(np.dot(n, target)) + vx = _skew(v) + r = np.eye(3, dtype=np.float32) + vx + (vx @ vx) * ((1.0 - c) / max(1e-8, s * s)) + return r.astype(np.float32) + + +def _skew(v: np.ndarray) -> np.ndarray: + return np.array( + [ + [0.0, -v[2], v[1]], + [v[2], 0.0, -v[0]], + [-v[1], v[0], 0.0], + ], + dtype=np.float32, + ) + + +def _axis_angle_to_matrix(axis: np.ndarray, angle: float) -> np.ndarray: + axis = axis / max(1e-8, np.linalg.norm(axis)) + v = axis * angle + s = np.sin(angle) + c = np.cos(angle) + vx = _skew(axis) + return np.eye(3, dtype=np.float32) + s * vx + (1.0 - c) * (vx @ vx) + + +def _pick_mesh_path(obj_dir: Path) -> Path: + candidates: List[Path] = [] + candidates.append(obj_dir / "mid_files" / "scaled_mesh.obj") + candidates.extend(sorted((obj_dir / "model" / "middle_file").glob("*_high_mesh.obj"))) + candidates.append(obj_dir / "model" / "model.obj") + for c in candidates: + if c.exists(): + return c + raise FileNotFoundError(f"No mesh found in {obj_dir}") + + +def _load_pose_json(obj_dir: Path) -> Path: + pose_dir = obj_dir / "pose_result" + locked = pose_dir / "poses_locked.json" + default = pose_dir / "poses.json" + if locked.exists(): + return locked + if default.exists(): + return default + raise FileNotFoundError(f"No poses.json under {pose_dir}") + + +def _load_pose_sequence(pose_json: Path) -> Dict[int, np.ndarray]: + data = json.loads(pose_json.read_text()) + pose_map: Dict[int, np.ndarray] = {} + for k, v in data.items(): + try: + idx = int(k) + except Exception: + continue + pose_map[idx] = np.asarray(v, dtype=np.float32) + return pose_map + + +def _collect_static_mesh_points( + run_dir: Path, config_path: Path, rng: np.random.Generator, max_points_per_obj: int = 20000 +) -> np.ndarray: + with config_path.open("r", encoding="utf-8") as f: + cfg = json.load(f) + static_names = {o["name"] for o in cfg.get("objects", []) if str(o.get("category", "")).lower() == "static"} + + result_npz = run_dir / "results" / "result.npz" + if not result_npz.exists(): + raise FileNotFoundError(result_npz) + data = np.load(result_npz) + extrinsics = data["extrinsics"] + + points: List[np.ndarray] = [] + objects_root = run_dir / "objects" + if not objects_root.exists(): + return np.empty((0, 3), dtype=np.float32) + + for obj_dir in sorted([d for d in objects_root.iterdir() if d.is_dir()]): + if static_names and obj_dir.name not in static_names: + continue + try: + mesh_path = _pick_mesh_path(obj_dir) + pose_json = _load_pose_json(obj_dir) + except FileNotFoundError: + continue + + pose_map = _load_pose_sequence(pose_json) + if not pose_map: + continue + frame_ids = sorted(pose_map.keys()) + frame_id = frame_ids[0] + pose = pose_map[frame_id] + if frame_id >= extrinsics.shape[0]: + frame_id = 0 + pose = pose_map[frame_ids[0]] + + w_T_o = np.linalg.inv(extrinsics[frame_id]) @ pose + + mesh = trimesh.load(mesh_path, force="mesh") + verts = np.asarray(mesh.vertices, dtype=np.float32) + if verts.shape[0] > max_points_per_obj: + idx = rng.choice(verts.shape[0], size=max_points_per_obj, replace=False) + verts = verts[idx] + + ones = np.ones((verts.shape[0], 1), dtype=np.float32) + verts_h = np.concatenate([verts, ones], axis=1) + verts_w = (w_T_o @ verts_h.T).T[:, :3] + points.append(verts_w) + + if not points: + return np.empty((0, 3), dtype=np.float32) + return np.vstack(points) + + +def _parse_frame_id(path: Path) -> Optional[int]: + stem = path.stem + for part in reversed(stem.split("_")): + if part.isdigit(): + return int(part) + digits = "".join(ch if ch.isdigit() else " " for ch in stem).split() + if digits: + return int(digits[-1]) + return None + + +def _build_mask_frame_map(mask_dir: Path) -> Dict[int, Path]: + out: Dict[int, Path] = {} + for p in sorted(mask_dir.glob("*.png")): + fid = _parse_frame_id(p) + if fid is None: + continue + out[fid] = p + return out + + +def _nearest_frame_path(frame_map: Dict[int, Path], frame_id: int) -> Optional[Path]: + if frame_id in frame_map: + return frame_map[frame_id] + if not frame_map: + return None + nearest = min(frame_map.keys(), key=lambda x: abs(x - frame_id)) + return frame_map.get(nearest) + + +def _load_mask_centroid(mask_path: Path) -> Tuple[float, float, int]: + try: + mask = np.asarray(Image.open(mask_path).convert("L"), dtype=np.uint8) + except Exception: + return 0.0, 0.0, 0 + ys, xs = np.nonzero(mask > 0) + area = int(xs.size) + if area <= 0: + return 0.0, 0.0, 0 + return float(xs.mean()), float(ys.mean()), area + + +def _load_mask_specs(config_path: Path) -> List[Dict[str, object]]: + payload = json.loads(config_path.read_text(encoding="utf-8")) + out: List[Dict[str, object]] = [] + for obj in payload.get("objects", []): + name = str(obj.get("name", "")).strip() + mask_dir_raw = str(obj.get("masks_dir", "")).strip() + if not name or not mask_dir_raw: + continue + mask_dir = Path(mask_dir_raw).resolve() + if not mask_dir.exists(): + continue + frame_map = _build_mask_frame_map(mask_dir) + if not frame_map: + continue + out.append({"name": name, "mask_dir": mask_dir, "frame_map": frame_map}) + return out + + +def _evaluate_plane( + plane: np.ndarray, mesh_points: np.ndarray, dist_eps: float, near_percent: float +) -> Dict[str, float | np.ndarray]: + n = plane[:3].astype(np.float32) + d = float(plane[3]) + dist = mesh_points @ n + d + if float(np.median(dist)) < 0.0: + n = -n + d = -d + dist = -dist + + ratio_above = float(np.mean(dist >= -dist_eps)) + abs_dist = np.abs(dist) + k = max(1, int(len(abs_dist) * max(1e-6, near_percent))) + closest = np.partition(abs_dist, k - 1)[:k] + median_close = float(np.median(closest)) + return {"n": n, "d": d, "ratio_above": ratio_above, "median_close": median_close} + + +def _maybe_flip_normal_by_camera_up( + run_dir: Path, n: np.ndarray, d: float, samples: int +) -> Tuple[np.ndarray, float, Optional[float], bool]: + result_npz = run_dir / "results" / "result.npz" + if not result_npz.exists(): + return n, d, None, False + data = np.load(result_npz) + if "extrinsics" not in data: + return n, d, None, False + extrinsics = data["extrinsics"] + if extrinsics.ndim != 3 or extrinsics.shape[1:] != (4, 4) or extrinsics.shape[0] == 0: + return n, d, None, False + + num = max(1, min(int(samples), int(extrinsics.shape[0]))) + frame_ids = np.linspace(0, extrinsics.shape[0] - 1, num=num, dtype=np.int32) + ys: List[float] = [] + for idx in frame_ids: + r_wc = extrinsics[int(idx), :3, :3] + n_cam = r_wc @ n + ys.append(float(n_cam[1])) + + median_y = float(np.median(np.asarray(ys, dtype=np.float32))) + if median_y > 0.0: + return -n, -float(d), median_y, True + return n, d, median_y, False + + +def _maybe_flip_normal_by_object_region( + run_dir: Path, + config_path: Path, + n: np.ndarray, + d: float, + samples: int, +) -> Tuple[np.ndarray, float, Optional[float], int, bool]: + result_npz = run_dir / "results" / "result.npz" + if not result_npz.exists(): + return n, d, None, 0, False + + mask_specs = _load_mask_specs(config_path) + if not mask_specs: + return n, d, None, 0, False + + data = np.load(result_npz) + if "extrinsics" not in data or "intrinsics" not in data: + return n, d, None, 0, False + extrinsics = data["extrinsics"] + intrinsics = data["intrinsics"] + if extrinsics.ndim != 3 or extrinsics.shape[1:] != (4, 4) or extrinsics.shape[0] == 0: + return n, d, None, 0, False + if intrinsics.ndim != 3 or intrinsics.shape[1:] != (3, 3): + return n, d, None, 0, False + + num = max(1, min(int(samples), int(extrinsics.shape[0]))) + frame_ids = np.linspace(0, extrinsics.shape[0] - 1, num=num, dtype=np.int32) + total_score = 0.0 + valid_frames = 0 + + for idx in frame_ids: + frame_id = int(idx) + try: + line = np.linalg.inv(intrinsics[frame_id]).T @ (extrinsics[frame_id, :3, :3] @ n) + except np.linalg.LinAlgError: + continue + denom = float(np.linalg.norm(line[:2])) + if denom <= 1e-8: + continue + line = line / denom + + frame_score = 0.0 + frame_weight = 0.0 + for spec in mask_specs: + frame_map = spec["frame_map"] + if not isinstance(frame_map, dict): + continue + mask_path = _nearest_frame_path(frame_map, frame_id) + if mask_path is None: + continue + cx, cy, area = _load_mask_centroid(mask_path) + if area <= 0: + continue + weight = float(np.sqrt(area)) + signed_side = float(line[0] * cx + line[1] * cy + line[2]) + frame_score += weight * signed_side + frame_weight += weight + if frame_weight <= 0.0: + continue + total_score += frame_score + valid_frames += 1 + + if valid_frames <= 0: + return n, d, None, 0, False + if total_score < 0.0: + return -n, -float(d), total_score, valid_frames, True + return n, d, total_score, valid_frames, False + + +def main() -> None: + args = parse_args() + rng = np.random.default_rng(args.seed) + + run_dir = args.run_dir.resolve() + config_path = args.config.resolve() + if args.pcd is None: + pcd_path = run_dir / "scene_point_cloud_frame_all.ply" + else: + pcd_path = args.pcd.resolve() + out_path = args.out.resolve() if args.out is not None else run_dir / "alignment_plane.json" + + if not run_dir.exists(): + raise FileNotFoundError(run_dir) + if not config_path.exists(): + raise FileNotFoundError(config_path) + if not pcd_path.exists(): + raise FileNotFoundError(pcd_path) + + pcd_obj = trimesh.load(pcd_path, force="mesh") + pcd_points = _extract_points(pcd_obj).astype(np.float32) + if pcd_points.shape[0] < 3: + raise ValueError("Point cloud is empty") + + bbox_diag = float(np.linalg.norm(pcd_points.max(axis=0) - pcd_points.min(axis=0))) + dist_th = args.dist_th if args.dist_th > 0.0 else 0.005 * bbox_diag + downsample = args.downsample if args.downsample > 0.0 else 0.01 * bbox_diag + + pcd_points = _voxel_downsample(pcd_points, downsample) + if pcd_points.shape[0] < 3: + raise ValueError("Point cloud too small after downsample") + + mesh_points = _collect_static_mesh_points(run_dir, config_path, rng) if args.static_only else np.empty((0, 3)) + + candidates: List[Dict[str, object]] = [] + remaining = pcd_points + for i in range(max(1, args.num_planes)): + if remaining.shape[0] < 3: + break + plane, inliers = _fit_plane_ransac(remaining, args.max_iter, dist_th, rng) + candidates.append({"plane": plane, "inliers": int(inliers.sum())}) + remaining = remaining[~inliers] + + if not candidates: + raise RuntimeError("No plane candidates found") + + chosen = candidates[0] + selection_stats: Dict[str, object] = {} + if mesh_points.shape[0] > 0: + evals = [] + for idx, cand in enumerate(candidates): + res = _evaluate_plane(cand["plane"], mesh_points, dist_th, args.bottom_percent) + evals.append( + { + "idx": idx, + "n": np.asarray(res["n"], dtype=np.float32).tolist(), + "d": float(res["d"]), + "ratio_above": float(res["ratio_above"]), + "median_close": float(res["median_close"]), + "inliers": int(cand["inliers"]), + } + ) + evals.sort(key=lambda x: (-x["ratio_above"], x["median_close"], -x["inliers"])) + best = evals[0] + chosen = candidates[int(best["idx"])] + chosen["plane"] = np.asarray([*best["n"], best["d"]], dtype=np.float32) + selection_stats = best + + plane = chosen["plane"].astype(np.float32) + n = plane[:3] + n = n / max(1e-8, np.linalg.norm(n)) + d = float(plane[3]) + gravity_sign_mode = str(args.gravity_sign_mode).strip().lower() + gravity_sign_source = "mesh_above" + gravity_sign_score: Optional[float] = None + gravity_sign_valid_frames = 0 + gravity_sign_flipped = False + camera_up_median_y: Optional[float] = None + camera_up_flipped = False + + if gravity_sign_mode in {"object_region", "auto"}: + n_new, d_new, gravity_sign_score, gravity_sign_valid_frames, gravity_sign_flipped = ( + _maybe_flip_normal_by_object_region( + run_dir, + config_path, + n, + d, + args.gravity_sign_samples, + ) + ) + if gravity_sign_valid_frames > 0: + n, d = n_new, d_new + gravity_sign_source = "object_region" + + if ( + gravity_sign_source == "mesh_above" + and gravity_sign_mode in {"camera_up", "auto"} + and int(args.camera_up_prior) == 1 + ): + n, d, camera_up_median_y, camera_up_flipped = _maybe_flip_normal_by_camera_up( + run_dir, n, d, args.camera_up_samples + ) + if camera_up_median_y is not None: + gravity_sign_source = "camera_up" + gravity_sign_flipped = bool(camera_up_flipped) + + plane = np.asarray([float(n[0]), float(n[1]), float(n[2]), float(d)], dtype=np.float32) + + r = _rotation_to_z(n) + n_rot = r @ n + t = (d * n_rot).astype(np.float32) + + t_mat = np.eye(4, dtype=np.float32) + t_mat[:3, :3] = r + t_mat[:3, 3] = t + + out = { + "plane": plane.tolist(), + "R": r.tolist(), + "t": t.tolist(), + "T": t_mat.tolist(), + "stats": { + "bbox_diag": bbox_diag, + "dist_th": dist_th, + "downsample": downsample, + "num_planes": len(candidates), + "selected_inliers": int(chosen["inliers"]), + "gravity_sign_mode": gravity_sign_mode, + "gravity_sign_source": gravity_sign_source, + "gravity_sign_samples": int(args.gravity_sign_samples), + "gravity_sign_score": gravity_sign_score, + "gravity_sign_valid_frames": int(gravity_sign_valid_frames), + "gravity_sign_flipped": bool(gravity_sign_flipped), + "camera_up_prior": int(args.camera_up_prior), + "camera_up_samples": int(args.camera_up_samples), + "camera_up_median_y": camera_up_median_y, + "camera_up_flipped": bool(camera_up_flipped), + }, + } + if selection_stats: + out["selection"] = selection_stats + + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text(json.dumps(out, indent=2)) + print(f"[OK] Wrote: {out_path}") + print(f"[Plane] n={plane[:3].tolist()} d={plane[3]:.6f}") + if selection_stats: + print( + f"[Select] ratio_above={selection_stats['ratio_above']:.3f} " + f"median_close={selection_stats['median_close']:.6f} inliers={selection_stats['inliers']}" + ) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/flux2_edit_image.py b/OVOW/engine/tools/flux2_edit_image.py new file mode 100644 index 0000000000000000000000000000000000000000..941840fd0c554562e85dd32c2fccaa3c119c6c62 --- /dev/null +++ b/OVOW/engine/tools/flux2_edit_image.py @@ -0,0 +1,342 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import os +import shutil +import subprocess +import sys +from datetime import datetime +from pathlib import Path + +from PIL import Image + + +DEFAULT_FLUX_PY = Path("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-flux/bin/python") +DEFAULT_FLUX_REPO = Path("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/flux2") +DEFAULT_MODEL_NAME = "flux.2-klein-9b" +DEFAULT_CKPT_ROOT = Path("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/flux2") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Simple FLUX.2 single-image edit wrapper: input image + prompt + output dir." + ) + parser.add_argument("img_path", type=Path, help="Input image path") + parser.add_argument("prompt", type=str, help="Edit prompt") + parser.add_argument("output_dir", type=Path, help="Output directory") + parser.add_argument("--seed", type=int, default=1234, help="Sampling seed") + parser.add_argument( + "--gpu", + type=str, + default="", + help="Optional CUDA_VISIBLE_DEVICES value, e.g. 0 or 1", + ) + parser.add_argument( + "--model-name", + type=str, + default=DEFAULT_MODEL_NAME, + choices=[ + "flux.2-klein-4b", + "flux.2-klein-9b", + "flux.2-klein-base-4b", + "flux.2-klein-base-9b", + "flux.2-dev", + ], + help="FLUX.2 model name", + ) + parser.add_argument( + "--flux-python", + type=Path, + default=DEFAULT_FLUX_PY, + help="Python executable inside the FLUX environment", + ) + parser.add_argument( + "--flux-repo", + type=Path, + default=DEFAULT_FLUX_REPO, + help="Path to the local flux2 repository", + ) + parser.add_argument( + "--model-path", + type=Path, + default=DEFAULT_CKPT_ROOT / "flux-2-klein-9b.safetensors", + help="Path to the FLUX model weights", + ) + parser.add_argument( + "--ae-path", + type=Path, + default=DEFAULT_CKPT_ROOT / "ae.safetensors", + help="Path to the FLUX autoencoder weights", + ) + parser.add_argument( + "--text-encoder-dir", + type=Path, + default=DEFAULT_CKPT_ROOT / "text_encoder", + help="Path to the Qwen text encoder directory for klein models", + ) + parser.add_argument( + "--tokenizer-dir", + type=Path, + default=DEFAULT_CKPT_ROOT / "tokenizer", + help="Path to the tokenizer directory for klein models", + ) + parser.add_argument( + "--width", + type=int, + default=0, + help="Output width; default is auto-computed from the input image", + ) + parser.add_argument( + "--height", + type=int, + default=0, + help="Output height; default is auto-computed from the input image", + ) + parser.add_argument( + "--max-side", + type=int, + default=1024, + help="When width/height are not set, resize the input to this max side while keeping aspect ratio", + ) + parser.add_argument( + "--match-image-size", + type=str, + default="none", + help="Pass through to flux2 CLI, e.g. 0 or none", + ) + parser.add_argument( + "--cpu-offloading", + action="store_true", + help="Enable FLUX CPU offloading", + ) + parser.add_argument( + "--enable-aux-model", + action="store_true", + help="Enable FLUX2 auxiliary model for local prompt upsampling and checks", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Print the final command without running FLUX", + ) + return parser.parse_args() + + +def shlex_quote(value: str) -> str: + if not value: + return "''" + if all(ch.isalnum() or ch in "._-/:=," for ch in value): + return value + return "'" + value.replace("'", "'\"'\"'") + "'" + + +def require_file(path: Path, label: str) -> Path: + path = path.expanduser() + if not path.is_file(): + raise FileNotFoundError(f"{label} not found: {path}") + return path.resolve() + + +def require_dir(path: Path, label: str) -> Path: + path = path.expanduser() + if not path.is_dir(): + raise FileNotFoundError(f"{label} not found: {path}") + return path.resolve() + + +def model_env_name(model_name: str) -> str: + mapping = { + "flux.2-klein-4b": "KLEIN_4B_MODEL_PATH", + "flux.2-klein-9b": "KLEIN_9B_MODEL_PATH", + "flux.2-klein-base-4b": "KLEIN_4B_BASE_MODEL_PATH", + "flux.2-klein-base-9b": "KLEIN_9B_BASE_MODEL_PATH", + "flux.2-dev": "FLUX2_MODEL_PATH", + } + try: + return mapping[model_name] + except KeyError as exc: + raise ValueError(f"Unsupported model name: {model_name}") from exc + + +def qwen_variant(model_name: str) -> str | None: + if "klein" not in model_name: + return None + if "4b" in model_name: + return "4B" + if "9b" in model_name: + return "8B" + raise ValueError(f"Cannot infer Qwen variant from model name: {model_name}") + + +def find_latest_sample(output_dir: Path) -> Path: + samples = sorted(output_dir.glob("sample_*.png"), key=lambda path: path.stat().st_mtime) + if not samples: + raise RuntimeError(f"No sample_*.png found under {output_dir}") + return samples[-1] + + +def floor_to_multiple(value: int, base: int) -> int: + if base <= 0: + raise ValueError(f"Invalid base: {base}") + return max(base, (int(value) // base) * base) + + +def auto_output_size(input_width: int, input_height: int, max_side: int) -> tuple[int, int]: + if input_width <= 0 or input_height <= 0: + raise ValueError(f"Invalid input size: {input_width}x{input_height}") + + if max_side <= 0: + raw_width = input_width + raw_height = input_height + else: + scale = min(1.0, float(max_side) / float(max(input_width, input_height))) + raw_width = max(16, int(round(input_width * scale))) + raw_height = max(16, int(round(input_height * scale))) + + return floor_to_multiple(raw_width, 16), floor_to_multiple(raw_height, 16) + + +def main() -> None: + args = parse_args() + + prompt = args.prompt.strip() + if not prompt: + raise ValueError("Prompt cannot be empty.") + + img_path = require_file(args.img_path, "Input image") + flux_python = require_file(args.flux_python, "FLUX python") + flux_repo = require_dir(args.flux_repo, "FLUX repo") + cli_script = require_file(flux_repo / "scripts" / "cli.py", "FLUX CLI script") + model_path = require_file(args.model_path, "FLUX model weights") + ae_path = require_file(args.ae_path, "FLUX AE weights") + + qwen_model_dir: Path | None = None + tokenizer_dir: Path | None = None + variant = qwen_variant(args.model_name) + if variant is not None: + qwen_model_dir = require_dir(args.text_encoder_dir, "Qwen text encoder dir") + tokenizer_dir = require_dir(args.tokenizer_dir, "Qwen tokenizer dir") + + with Image.open(img_path) as img: + input_width, input_height = img.size + + auto_sized = int(args.width) <= 0 and int(args.height) <= 0 + if auto_sized: + out_width, out_height = auto_output_size(input_width, input_height, int(args.max_side)) + else: + if int(args.width) > 0 and int(args.height) > 0: + out_width = int(args.width) + out_height = int(args.height) + elif int(args.width) > 0: + out_width = int(args.width) + out_height = max(16, int(round(input_height * (float(out_width) / float(input_width))))) + elif int(args.height) > 0: + out_height = int(args.height) + out_width = max(16, int(round(input_width * (float(out_height) / float(input_height))))) + else: + out_width = int(input_width) + out_height = int(input_height) + out_width = floor_to_multiple(out_width, 16) + out_height = floor_to_multiple(out_height, 16) + if out_width <= 0 or out_height <= 0: + raise ValueError(f"Invalid output size: {out_width}x{out_height}") + + output_dir = args.output_dir.expanduser() + output_dir.mkdir(parents=True, exist_ok=True) + + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + run_dir = (output_dir / f"run_{timestamp}_seed{args.seed}").resolve() + run_dir.mkdir(parents=True, exist_ok=True) + raw_output_dir = run_dir / "output" + raw_output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + str(flux_python), + str(cli_script), + f"--model_name={args.model_name}", + "--single_eval=True", + f"--prompt={prompt}", + f"--input_images={img_path}", + f"--width={out_width}", + f"--height={out_height}", + f"--match_image_size={args.match_image_size}", + f"--seed={args.seed}", + "--upsample_prompt_mode=none", + ] + if args.cpu_offloading: + cmd.append("--cpu_offloading=True") + + env = os.environ.copy() + flux_src = str((flux_repo / "src").resolve()) + env["PYTHONPATH"] = f"{flux_src}:{env['PYTHONPATH']}" if env.get("PYTHONPATH") else flux_src + env[model_env_name(args.model_name)] = str(model_path) + env["AE_MODEL_PATH"] = str(ae_path) + env["FLUX2_ENABLE_AUX_MODEL"] = "1" if args.enable_aux_model else "0" + if variant is not None and qwen_model_dir is not None and tokenizer_dir is not None: + env[f"QWEN3_{variant}_MODEL_PATH"] = str(qwen_model_dir) + env[f"QWEN3_{variant}_TOKENIZER_PATH"] = str(tokenizer_dir) + if args.gpu: + env["CUDA_VISIBLE_DEVICES"] = args.gpu + + print("[flux2-edit] command:") + print(" " + " ".join(shlex_quote(item) for item in cmd)) + print( + f"[flux2-edit] input size: {input_width}x{input_height} -> output size: {out_width}x{out_height}" + ) + print(f"[flux2-edit] run dir: {run_dir}") + + if args.dry_run: + print("[flux2-edit] dry-run enabled, skip execution.") + return + + subprocess.run(cmd, cwd=str(run_dir), env=env, check=True) + + raw_output = find_latest_sample(raw_output_dir) + final_output = output_dir.resolve() / f"edited_{timestamp}_seed{args.seed}.png" + latest_output = output_dir.resolve() / "latest.png" + shutil.copy2(raw_output, final_output) + shutil.copy2(final_output, latest_output) + + run_info = { + "input_image": str(img_path), + "prompt": prompt, + "output_dir": str(output_dir.resolve()), + "run_dir": str(run_dir), + "model_name": args.model_name, + "seed": args.seed, + "gpu": args.gpu, + "input_width": int(input_width), + "input_height": int(input_height), + "output_width": int(out_width), + "output_height": int(out_height), + "auto_sized": bool(auto_sized), + "max_side": int(args.max_side), + "match_image_size": args.match_image_size, + "cpu_offloading": bool(args.cpu_offloading), + "enable_aux_model": bool(args.enable_aux_model), + "raw_output": str(raw_output), + "final_output": str(final_output), + "latest_output": str(latest_output), + "command": cmd, + } + + run_json = run_dir / "run_info.json" + latest_json = output_dir.resolve() / "latest.json" + run_json.write_text(json.dumps(run_info, indent=2, ensure_ascii=False), encoding="utf-8") + latest_json.write_text(json.dumps(run_info, indent=2, ensure_ascii=False), encoding="utf-8") + + print(f"[OK] final output: {final_output}") + print(f"[OK] latest output: {latest_output}") + print(f"[OK] run metadata: {run_json}") + print(f"[OK] latest metadata: {latest_json}") + print(f"FINAL_OUTPUT={final_output}") + + +if __name__ == "__main__": + try: + main() + except Exception as exc: + print(f"[ERROR] {type(exc).__name__}: {exc}", file=sys.stderr) + raise diff --git a/OVOW/engine/tools/flux2_generate_image.py b/OVOW/engine/tools/flux2_generate_image.py new file mode 100644 index 0000000000000000000000000000000000000000..307cfc4ae76449d686bfd2c24ea279c478a08a33 --- /dev/null +++ b/OVOW/engine/tools/flux2_generate_image.py @@ -0,0 +1,272 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import os +import shutil +import subprocess +import sys +from datetime import datetime +from pathlib import Path + + +DEFAULT_FLUX_PY = Path("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-flux/bin/python") +DEFAULT_FLUX_REPO = Path("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/flux2") +DEFAULT_MODEL_NAME = "flux.2-klein-9b" +DEFAULT_CKPT_ROOT = Path("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/flux2") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Simple FLUX.2 text-to-image wrapper: prompt + output dir." + ) + parser.add_argument("prompt", type=str, help="Generation prompt") + parser.add_argument("output_dir", type=Path, help="Output directory") + parser.add_argument("--seed", type=int, default=1234, help="Sampling seed") + parser.add_argument( + "--gpu", + type=str, + default="", + help="Optional CUDA_VISIBLE_DEVICES value, e.g. 0 or 1", + ) + parser.add_argument( + "--model-name", + type=str, + default=DEFAULT_MODEL_NAME, + choices=[ + "flux.2-klein-4b", + "flux.2-klein-9b", + "flux.2-klein-base-4b", + "flux.2-klein-base-9b", + "flux.2-dev", + ], + help="FLUX.2 model name", + ) + parser.add_argument( + "--flux-python", + type=Path, + default=DEFAULT_FLUX_PY, + help="Python executable inside the FLUX environment", + ) + parser.add_argument( + "--flux-repo", + type=Path, + default=DEFAULT_FLUX_REPO, + help="Path to the local flux2 repository", + ) + parser.add_argument( + "--model-path", + type=Path, + default=DEFAULT_CKPT_ROOT / "flux-2-klein-9b.safetensors", + help="Path to the FLUX model weights", + ) + parser.add_argument( + "--ae-path", + type=Path, + default=DEFAULT_CKPT_ROOT / "ae.safetensors", + help="Path to the FLUX autoencoder weights", + ) + parser.add_argument( + "--text-encoder-dir", + type=Path, + default=DEFAULT_CKPT_ROOT / "text_encoder", + help="Path to the Qwen text encoder directory for klein models", + ) + parser.add_argument( + "--tokenizer-dir", + type=Path, + default=DEFAULT_CKPT_ROOT / "tokenizer", + help="Path to the tokenizer directory for klein models", + ) + parser.add_argument("--width", type=int, default=1024, help="Output width") + parser.add_argument("--height", type=int, default=1024, help="Output height") + parser.add_argument( + "--cpu-offloading", + action="store_true", + help="Enable FLUX CPU offloading", + ) + parser.add_argument( + "--enable-aux-model", + action="store_true", + help="Enable FLUX2 auxiliary model for local prompt upsampling and checks", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Print the final command without running FLUX", + ) + return parser.parse_args() + + +def shlex_quote(value: str) -> str: + if not value: + return "''" + if all(ch.isalnum() or ch in "._-/:=," for ch in value): + return value + return "'" + value.replace("'", "'\"'\"'") + "'" + + +def require_file(path: Path, label: str) -> Path: + path = path.expanduser() + if not path.is_file(): + raise FileNotFoundError(f"{label} not found: {path}") + return path.resolve() + + +def require_dir(path: Path, label: str) -> Path: + path = path.expanduser() + if not path.is_dir(): + raise FileNotFoundError(f"{label} not found: {path}") + return path.resolve() + + +def model_env_name(model_name: str) -> str: + mapping = { + "flux.2-klein-4b": "KLEIN_4B_MODEL_PATH", + "flux.2-klein-9b": "KLEIN_9B_MODEL_PATH", + "flux.2-klein-base-4b": "KLEIN_4B_BASE_MODEL_PATH", + "flux.2-klein-base-9b": "KLEIN_9B_BASE_MODEL_PATH", + "flux.2-dev": "FLUX2_MODEL_PATH", + } + try: + return mapping[model_name] + except KeyError as exc: + raise ValueError(f"Unsupported model name: {model_name}") from exc + + +def qwen_variant(model_name: str) -> str | None: + if "klein" not in model_name: + return None + if "4b" in model_name: + return "4B" + if "9b" in model_name: + return "8B" + raise ValueError(f"Cannot infer Qwen variant from model name: {model_name}") + + +def find_latest_sample(output_dir: Path) -> Path: + samples = sorted(output_dir.glob("sample_*.png"), key=lambda path: path.stat().st_mtime) + if not samples: + raise RuntimeError(f"No sample_*.png found under {output_dir}") + return samples[-1] + + +def floor_to_multiple(value: int, base: int) -> int: + if base <= 0: + raise ValueError(f"Invalid base: {base}") + return max(base, (int(value) // base) * base) + + +def main() -> None: + args = parse_args() + + prompt = args.prompt.strip() + if not prompt: + raise ValueError("Prompt cannot be empty.") + + flux_python = require_file(args.flux_python, "FLUX python") + flux_repo = require_dir(args.flux_repo, "FLUX repo") + cli_script = require_file(flux_repo / "scripts" / "cli.py", "FLUX CLI script") + model_path = require_file(args.model_path, "FLUX model weights") + ae_path = require_file(args.ae_path, "FLUX AE weights") + + qwen_model_dir: Path | None = None + tokenizer_dir: Path | None = None + variant = qwen_variant(args.model_name) + if variant is not None: + qwen_model_dir = require_dir(args.text_encoder_dir, "Qwen text encoder dir") + tokenizer_dir = require_dir(args.tokenizer_dir, "Qwen tokenizer dir") + + out_width = floor_to_multiple(int(args.width), 16) + out_height = floor_to_multiple(int(args.height), 16) + if out_width <= 0 or out_height <= 0: + raise ValueError(f"Invalid output size: {out_width}x{out_height}") + + output_dir = args.output_dir.expanduser() + output_dir.mkdir(parents=True, exist_ok=True) + + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + run_dir = (output_dir / f"run_{timestamp}_seed{args.seed}").resolve() + run_dir.mkdir(parents=True, exist_ok=True) + raw_output_dir = run_dir / "output" + raw_output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + str(flux_python), + str(cli_script), + f"--model_name={args.model_name}", + "--single_eval=True", + f"--prompt={prompt}", + f"--width={out_width}", + f"--height={out_height}", + f"--seed={args.seed}", + "--upsample_prompt_mode=none", + ] + if args.cpu_offloading: + cmd.append("--cpu_offloading=True") + + env = os.environ.copy() + flux_src = str((flux_repo / "src").resolve()) + env["PYTHONPATH"] = f"{flux_src}:{env['PYTHONPATH']}" if env.get("PYTHONPATH") else flux_src + env[model_env_name(args.model_name)] = str(model_path) + env["AE_MODEL_PATH"] = str(ae_path) + env["FLUX2_ENABLE_AUX_MODEL"] = "1" if args.enable_aux_model else "0" + if variant is not None and qwen_model_dir is not None and tokenizer_dir is not None: + env[f"QWEN3_{variant}_MODEL_PATH"] = str(qwen_model_dir) + env[f"QWEN3_{variant}_TOKENIZER_PATH"] = str(tokenizer_dir) + if args.gpu: + env["CUDA_VISIBLE_DEVICES"] = args.gpu + + print("[flux2-generate] command:") + print(" " + " ".join(shlex_quote(item) for item in cmd)) + print(f"[flux2-generate] output size: {out_width}x{out_height}") + print(f"[flux2-generate] run dir: {run_dir}") + + if args.dry_run: + print("[flux2-generate] dry-run enabled, skip execution.") + return + + subprocess.run(cmd, cwd=str(run_dir), env=env, check=True) + + raw_output = find_latest_sample(raw_output_dir) + final_output = output_dir.resolve() / f"generated_{timestamp}_seed{args.seed}.png" + latest_output = output_dir.resolve() / "latest.png" + shutil.copy2(raw_output, final_output) + shutil.copy2(final_output, latest_output) + + run_info = { + "prompt": prompt, + "output_dir": str(output_dir.resolve()), + "run_dir": str(run_dir), + "model_name": args.model_name, + "seed": args.seed, + "gpu": args.gpu, + "output_width": int(out_width), + "output_height": int(out_height), + "cpu_offloading": bool(args.cpu_offloading), + "enable_aux_model": bool(args.enable_aux_model), + "raw_output": str(raw_output), + "final_output": str(final_output), + "latest_output": str(latest_output), + "command": cmd, + } + + run_json = run_dir / "run_info.json" + latest_json = output_dir.resolve() / "latest.json" + run_json.write_text(json.dumps(run_info, indent=2, ensure_ascii=False), encoding="utf-8") + latest_json.write_text(json.dumps(run_info, indent=2, ensure_ascii=False), encoding="utf-8") + + print(f"[OK] final output: {final_output}") + print(f"[OK] latest output: {latest_output}") + print(f"[OK] run metadata: {run_json}") + print(f"[OK] latest metadata: {latest_json}") + print(f"FINAL_OUTPUT={final_output}") + + +if __name__ == "__main__": + try: + main() + except Exception as exc: + print(f"[ERROR] {type(exc).__name__}: {exc}", file=sys.stderr) + raise diff --git a/OVOW/engine/tools/flux2_single_ref_edit.py b/OVOW/engine/tools/flux2_single_ref_edit.py new file mode 100644 index 0000000000000000000000000000000000000000..8a8741d630709bf854a9d153b03945e2c704edb8 --- /dev/null +++ b/OVOW/engine/tools/flux2_single_ref_edit.py @@ -0,0 +1,445 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import os +import shutil +import subprocess +import sys +from datetime import datetime +from pathlib import Path + +import numpy as np +from PIL import Image, ImageFilter + +if hasattr(Image, "Resampling"): + RESAMPLE_NEAREST = Image.Resampling.NEAREST + RESAMPLE_LANCZOS = Image.Resampling.LANCZOS +else: + RESAMPLE_NEAREST = Image.NEAREST + RESAMPLE_LANCZOS = Image.LANCZOS + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Run FLUX.2 single-reference editing for one object in a OnePose run directory." + ) + parser.add_argument("--run-dir", type=Path, required=True, help="Scene run dir that contains objects/ and rgb/") + parser.add_argument("--obj-name", type=str, required=True, help="Object folder name under objects/") + parser.add_argument("--mode", type=str, required=True, choices=["amodal", "view"], help="Editing mode") + parser.add_argument( + "--flux-python", + type=Path, + default=Path("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-flux/bin/python"), + help="Python executable in flux environment", + ) + parser.add_argument( + "--flux-repo", + type=Path, + default=Path("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/flux2"), + help="flux2 repository path", + ) + parser.add_argument("--model-name", type=str, default="flux.2-klein-9b", help="flux2 model name") + parser.add_argument("--seed", type=int, default=1234, help="Sampling seed") + parser.add_argument("--crop-expand", type=float, default=1.35, help="BBox expand ratio around mask") + parser.add_argument( + "--min-side", + type=int, + default=64, + help="If crop is too thin/small, upscale so shorter side >= this value before FLUX", + ) + parser.add_argument("--out-width", type=int, default=518, help="Output width for FLUX generation") + parser.add_argument("--out-height", type=int, default=518, help="Output height for FLUX generation") + parser.add_argument( + "--match-image-size", + type=str, + default="none", + help="Set to input index (e.g. 0) to match reference size; use 'none' for fixed output resolution", + ) + parser.add_argument( + "--use-rgb-crop-ref", + type=int, + default=0, + choices=[0, 1], + help="1: pass both reference_crop.png and rgb_crop.png to FLUX; 0: keep legacy single-image input", + ) + parser.add_argument("--min-mask-area", type=int, default=64, help="Minimal mask area to accept a frame") + parser.add_argument( + "--prompt-amodal", + type=str, + default="", + help="Optional custom prompt for amodal completion mode", + ) + parser.add_argument( + "--prompt-view", + type=str, + default="", + help="Optional custom prompt for viewpoint-change mode", + ) + parser.add_argument( + "--overwrite-mode-output", + type=int, + default=1, + choices=[0, 1], + help="1: clear existing objects/fluxoutput// before writing new output", + ) + parser.add_argument("--bg-gray", type=int, default=255, help="Background gray value for masked reference image") + parser.add_argument("--no-mask-bg", action="store_true", help="Keep original background in reference crop") + parser.add_argument("--dry-run", action="store_true", help="Only prepare inputs and print command") + return parser.parse_args() + + +def resolve_scene_run_dir(run_dir: Path, obj_name: str) -> Path: + run_dir = run_dir.resolve() + if (run_dir / "objects" / obj_name).is_dir() and (run_dir / "rgb").is_dir(): + return run_dir + + candidates = sorted(run_dir.glob(f"*/objects/{obj_name}")) + if len(candidates) == 1: + scene_dir = candidates[0].parents[1] + if (scene_dir / "rgb").is_dir(): + return scene_dir + + if len(candidates) > 1: + cand_str = "\n".join(str(p.parents[1]) for p in candidates) + raise RuntimeError( + f"Found multiple scene directories for object '{obj_name}'. " + f"Please pass a precise --run-dir.\nCandidates:\n{cand_str}" + ) + raise RuntimeError( + f"Cannot resolve scene run dir from '{run_dir}' for object '{obj_name}'. " + "Expect run_dir/objects//masks and run_dir/rgb/." + ) + + +def find_rgb_frame(rgb_dir: Path, frame_stem: str) -> Path: + exts = [".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG"] + for ext in exts: + cand = rgb_dir / f"{frame_stem}{ext}" + if cand.is_file(): + return cand + cands = sorted(rgb_dir.glob(f"{frame_stem}.*")) + if cands: + return cands[0] + raise FileNotFoundError(f"No rgb frame matches stem '{frame_stem}' under {rgb_dir}") + + +def select_best_mask(mask_dir: Path, min_mask_area: int) -> tuple[Path, int]: + mask_paths = sorted(mask_dir.glob("*.png")) + if not mask_paths: + raise RuntimeError(f"No mask png files found in {mask_dir}") + + best_path = None + best_area = -1 + for p in mask_paths: + m = np.array(Image.open(p).convert("L")) + area = int((m > 0).sum()) + if area > best_area: + best_area = area + best_path = p + + if best_path is None or best_area < min_mask_area: + raise RuntimeError( + f"Best mask area too small in {mask_dir}: area={best_area}, min_mask_area={min_mask_area}" + ) + return best_path, best_area + + +def expand_bbox(mask: np.ndarray, expand_ratio: float) -> tuple[int, int, int, int]: + ys, xs = np.where(mask > 0) + if len(xs) == 0: + raise RuntimeError("Mask is empty after thresholding.") + x0 = int(xs.min()) + x1 = int(xs.max()) + y0 = int(ys.min()) + y1 = int(ys.max()) + + h, w = mask.shape + cx = 0.5 * (x0 + x1) + cy = 0.5 * (y0 + y1) + bw = (x1 - x0 + 1) * max(1.0, expand_ratio) + bh = (y1 - y0 + 1) * max(1.0, expand_ratio) + + nx0 = max(0, int(round(cx - 0.5 * bw))) + ny0 = max(0, int(round(cy - 0.5 * bh))) + nx1 = min(w - 1, int(round(cx + 0.5 * bw))) + ny1 = min(h - 1, int(round(cy + 0.5 * bh))) + if nx1 <= nx0 or ny1 <= ny0: + raise RuntimeError("Expanded bbox is invalid.") + return nx0, ny0, nx1, ny1 + + +def build_default_prompt(obj_name: str, mode: str) -> str: + obj_phrase = obj_name.replace("_", " ").strip() + if mode == "amodal": + return ( + f"Studio product photo of a single {obj_phrase}. " + "Complete the full object shape and restore all occluded or missing parts. " + "The object should occupy most of the image area while remaining fully visible. " + "Keep about 5% clean margin on all four sides. " + "No cropping, no truncation, no cut-off, no part outside the image. " + "Keep exact identity, geometry proportions, material, color, and texture consistent with the reference. " + "Pure white background, shadowless lighting, no cast shadow, no floor shadow, no halo, no ring at the bottom, no base, no pedestal, no extra objects, no text." + ) + if mode == "view": + return ( + f"Studio product photo of the same {obj_phrase} from a different viewpoint, around 30 to 60 degree yaw change. " + "Treat the reference as a partially occluded observation of the same object, not as a truncated object. " + "The reference object may be partially occluded, so complete and restore all occluded, hidden, or missing parts, and remove any occlusion artifact instead of preserving it. " + "Infer the full object shape from the visible parts while preserving its identity. " + "Preserve geometry identity, material, color, and texture from the reference image. " + "Keep the whole object visible and make it occupy most of the image area with about 5% clean margin on all four sides. " + "Pure white background, shadowless lighting, no cast shadow, no floor shadow, no halo, no ring at the bottom, no base, no pedestal, no extra objects, no text." + ) + raise ValueError(f"Unsupported mode: {mode}") + + +def prepare_reference_image( + rgb_path: Path, + mask_path: Path, + out_dir: Path, + crop_expand: float, + min_side: int, + bg_gray: int, + keep_bg: bool, +) -> dict[str, str | int]: + rgb_img = Image.open(rgb_path).convert("RGB") + mask_img = Image.open(mask_path).convert("L") + if rgb_img.size != mask_img.size: + mask_img = mask_img.resize(rgb_img.size, resample=RESAMPLE_NEAREST) + + mask_np = np.array(mask_img) + x0, y0, x1, y1 = expand_bbox(mask_np, crop_expand) + + crop_box = (x0, y0, x1 + 1, y1 + 1) + rgb_crop = rgb_img.crop(crop_box) + mask_crop = mask_img.crop(crop_box) + + if keep_bg: + ref_img = rgb_crop + else: + bg_gray = max(0, min(255, int(bg_gray))) + bg = Image.new("RGB", rgb_crop.size, (bg_gray, bg_gray, bg_gray)) + soft_mask = mask_crop.filter(ImageFilter.GaussianBlur(radius=1.2)) + ref_img = Image.composite(rgb_crop, bg, soft_mask) + + short_side = min(ref_img.size) + resize_scale = 1.0 + if int(min_side) > 0 and short_side < int(min_side): + resize_scale = float(min_side) / float(max(1, short_side)) + new_w = max(1, int(round(ref_img.size[0] * resize_scale))) + new_h = max(1, int(round(ref_img.size[1] * resize_scale))) + rgb_crop = rgb_crop.resize((new_w, new_h), resample=RESAMPLE_LANCZOS) + ref_img = ref_img.resize((new_w, new_h), resample=RESAMPLE_LANCZOS) + mask_crop = mask_crop.resize((new_w, new_h), resample=RESAMPLE_NEAREST) + + out_dir.mkdir(parents=True, exist_ok=True) + ref_path = out_dir / "reference_crop.png" + rgb_crop_path = out_dir / "rgb_crop.png" + mask_crop_path = out_dir / "mask_crop.png" + ref_img.save(ref_path) + rgb_crop.save(rgb_crop_path) + mask_crop.save(mask_crop_path) + + return { + "reference_path": str(ref_path), + "rgb_crop_path": str(rgb_crop_path), + "mask_crop_path": str(mask_crop_path), + "bbox_x0": x0, + "bbox_y0": y0, + "bbox_x1": x1, + "bbox_y1": y1, + "crop_width": int(x1 - x0 + 1), + "crop_height": int(y1 - y0 + 1), + "prepared_width": int(ref_img.size[0]), + "prepared_height": int(ref_img.size[1]), + "resize_scale": float(resize_scale), + } + + +def run_flux_single_ref( + flux_python: Path, + flux_repo: Path, + model_name: str, + prompt: str, + ref_image_paths: list[Path], + seed: int, + out_width: int, + out_height: int, + match_image_size: str, + work_dir: Path, + dry_run: bool, +) -> Path | None: + cli_script = flux_repo / "scripts" / "cli.py" + if not cli_script.is_file(): + raise FileNotFoundError(f"flux2 cli script not found: {cli_script}") + + if not flux_python.is_file(): + raise FileNotFoundError(f"flux python not found: {flux_python}") + + work_dir.mkdir(parents=True, exist_ok=True) + out_dir = work_dir / "output" + out_dir.mkdir(parents=True, exist_ok=True) + before = set(out_dir.glob("sample_*.png")) + + cmd = [ + str(flux_python), + str(cli_script), + f"--model_name={model_name}", + "--single_eval=True", + f"--prompt={prompt}", + f"--input_images={','.join(str(p) for p in ref_image_paths)}", + f"--width={int(out_width)}", + f"--height={int(out_height)}", + f"--match_image_size={match_image_size}", + f"--seed={seed}", + "--upsample_prompt_mode=none", + ] + + env = os.environ.copy() + py_path = str((flux_repo / "src").resolve()) + if env.get("PYTHONPATH"): + env["PYTHONPATH"] = f"{py_path}:{env['PYTHONPATH']}" + else: + env["PYTHONPATH"] = py_path + + print("[flux2] command:") + print(" " + " ".join(shlex_quote(x) for x in cmd)) + if dry_run: + return None + + subprocess.run(cmd, cwd=str(work_dir), env=env, check=True) + + after = sorted(out_dir.glob("sample_*.png"), key=lambda p: p.stat().st_mtime) + if not after: + raise RuntimeError("No output images found under flux work dir.") + new_files = [p for p in after if p not in before] + if new_files: + return new_files[-1] + return after[-1] + + +def shlex_quote(s: str) -> str: + if not s: + return "''" + if all(c.isalnum() or c in "._-/:=" for c in s): + return s + return "'" + s.replace("'", "'\"'\"'") + "'" + + +def main() -> None: + args = parse_args() + if int(args.out_width) <= 0 or int(args.out_height) <= 0: + raise ValueError(f"Invalid output size: {args.out_width}x{args.out_height}") + match_image_size = str(args.match_image_size).strip().lower() + if match_image_size in {"", "none", "null", "-1"}: + match_image_size = "none" + elif not match_image_size.isdigit(): + raise ValueError("--match-image-size must be a non-negative integer or 'none'") + + scene_run_dir = resolve_scene_run_dir(args.run_dir, args.obj_name) + obj_dir = scene_run_dir / "objects" / args.obj_name + mask_dir = obj_dir / "masks" + rgb_dir = scene_run_dir / "rgb" + + if not obj_dir.is_dir(): + raise RuntimeError(f"Object dir not found: {obj_dir}") + if not mask_dir.is_dir(): + raise RuntimeError(f"Mask dir not found: {mask_dir}") + if not rgb_dir.is_dir(): + raise RuntimeError(f"RGB dir not found: {rgb_dir}") + + best_mask_path, best_area = select_best_mask(mask_dir, args.min_mask_area) + frame_stem = best_mask_path.stem + rgb_path = find_rgb_frame(rgb_dir, frame_stem) + + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + mode_out_dir = scene_run_dir / "objects" / "fluxoutput" / args.obj_name / args.mode + if int(args.overwrite_mode_output) == 1 and mode_out_dir.exists(): + shutil.rmtree(mode_out_dir, ignore_errors=True) + job_dir = mode_out_dir / f"{ts}_seed{args.seed}" + prep_dir = job_dir / "inputs" + prep_info = prepare_reference_image( + rgb_path=rgb_path, + mask_path=best_mask_path, + out_dir=prep_dir, + crop_expand=args.crop_expand, + min_side=args.min_side, + bg_gray=args.bg_gray, + keep_bg=args.no_mask_bg, + ) + + if args.mode == "amodal": + prompt = args.prompt_amodal.strip() or build_default_prompt(args.obj_name, "amodal") + else: + prompt = args.prompt_view.strip() or build_default_prompt(args.obj_name, "view") + + ref_image_paths = [Path(str(prep_info["reference_path"])).resolve()] + if int(args.use_rgb_crop_ref) == 1: + ref_image_paths.append(Path(str(prep_info["rgb_crop_path"])).resolve()) + + flux_work_dir = job_dir / "flux_work" + generated_path = run_flux_single_ref( + flux_python=args.flux_python.resolve(), + flux_repo=args.flux_repo.resolve(), + model_name=args.model_name, + prompt=prompt, + ref_image_paths=ref_image_paths, + seed=args.seed, + out_width=args.out_width, + out_height=args.out_height, + match_image_size=match_image_size, + work_dir=flux_work_dir, + dry_run=args.dry_run, + ) + + run_info = { + "scene_run_dir": str(scene_run_dir), + "obj_name": args.obj_name, + "mode": args.mode, + "seed": args.seed, + "model_name": args.model_name, + "output_width": int(args.out_width), + "output_height": int(args.out_height), + "match_image_size": match_image_size, + "use_rgb_crop_ref": bool(args.use_rgb_crop_ref), + "input_images": [str(p) for p in ref_image_paths], + "prompt": prompt, + "best_mask_frame": frame_stem, + "best_mask_path": str(best_mask_path), + "best_mask_area": int(best_area), + "rgb_path": str(rgb_path), + "prepared_inputs": prep_info, + "flux_work_dir": str(flux_work_dir), + "dry_run": bool(args.dry_run), + } + + if generated_path is not None: + final_path = job_dir / f"{args.obj_name}_{args.mode}_seed{args.seed}.png" + shutil.copy2(generated_path, final_path) + run_info["flux_raw_output"] = str(generated_path) + run_info["final_output"] = str(final_path) + print(f"[OK] generated image: {final_path}") + else: + final_path = None + + job_dir.mkdir(parents=True, exist_ok=True) + run_json = job_dir / "run_info.json" + run_json.write_text(json.dumps(run_info, indent=2, ensure_ascii=False), encoding="utf-8") + + latest_json = mode_out_dir / "latest.json" + latest_json.write_text(json.dumps(run_info, indent=2, ensure_ascii=False), encoding="utf-8") + + print(f"[OK] run metadata: {run_json}") + print(f"[OK] latest metadata: {latest_json}") + if final_path is not None: + print(f"FINAL_OUTPUT={final_path}") + + +if __name__ == "__main__": + try: + main() + except Exception as exc: + print(f"[ERROR] {type(exc).__name__}: {exc}", file=sys.stderr) + raise diff --git a/OVOW/engine/tools/image_to_looped_video.py b/OVOW/engine/tools/image_to_looped_video.py new file mode 100644 index 0000000000000000000000000000000000000000..a2199ce2cd19c64bd9f8825538bb7daaeeae2e89 --- /dev/null +++ b/OVOW/engine/tools/image_to_looped_video.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +"""Repeat a single RGB image into a short MP4 clip for OnePoseviaGen.""" +import argparse +import shutil +import subprocess +import sys +from pathlib import Path +from typing import Optional + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=( + "Wrap ffmpeg so that a single image can be fed to OnePoseviaGen's " + "video-based Gradio interface." + ) + ) + parser.add_argument("image", type=Path, help="Input image path (jpg/png/etc.)") + parser.add_argument( + "output", type=Path, help="Output MP4 file that OnePoseviaGen can ingest" + ) + parser.add_argument( + "--fps", type=float, default=3.0, help="Target frame rate (default: 3 fps)" + ) + parser.add_argument( + "--seconds", type=float, default=2.0, help="Clip duration in seconds (default: 2)" + ) + parser.add_argument( + "--min-side", + type=int, + default=512, + help="Shorter side after resizing; preserves aspect ratio (default: 512)", + ) + parser.add_argument( + "--codec", default="libx264", help="ffmpeg video codec (default: libx264)" + ) + return parser.parse_args() + + +def _resolve_ffmpeg_bin() -> Optional[str]: + ffmpeg_bin = shutil.which("ffmpeg") + if ffmpeg_bin: + return ffmpeg_bin + try: + import imageio_ffmpeg # type: ignore + except Exception: + return None + try: + return imageio_ffmpeg.get_ffmpeg_exe() + except Exception: + return None + + +def run_ffmpeg(args: argparse.Namespace) -> None: + ffmpeg_bin = _resolve_ffmpeg_bin() + if ffmpeg_bin is None: + raise SystemExit( + "ffmpeg not found in PATH and imageio-ffmpeg is unavailable; install ffmpeg or imageio-ffmpeg." + ) + + if not args.image.exists(): + raise SystemExit(f"Input image not found: {args.image}") + + if args.output.suffix.lower() != ".mp4": + raise SystemExit("Output file must have .mp4 extension") + + args.output.parent.mkdir(parents=True, exist_ok=True) + + vf = f"scale={args.min_side}:-2:flags=lanczos" + cmd = [ + ffmpeg_bin, + "-y", + "-loop", + "1", + "-i", + str(args.image), + "-c:v", + args.codec, + "-t", + f"{args.seconds}", + "-r", + f"{args.fps}", + "-vf", + vf, + "-pix_fmt", + "yuv420p", + str(args.output), + ] + + print("Running:", " ".join(cmd)) + subprocess.run(cmd, check=True) + + +def main() -> None: + args = parse_args() + run_ffmpeg(args) + print(f"Created {args.output} from {args.image}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/image_zoompan_video.py b/OVOW/engine/tools/image_zoompan_video.py new file mode 100644 index 0000000000000000000000000000000000000000..0200e850aa57f7e9e3ef7376b5f89c2c43ca43f7 --- /dev/null +++ b/OVOW/engine/tools/image_zoompan_video.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +"""Generate a jittered MP4 from a single image using ffmpeg zoompan.""" +import argparse +import shutil +import subprocess +from pathlib import Path + + +def parse_size(value: str) -> tuple[int, int]: + if "x" not in value: + raise argparse.ArgumentTypeError("尺寸格式必须是 <宽>x<高>,例如 720x720") + w_str, h_str = value.lower().split("x", 1) + try: + width = int(w_str) + height = int(h_str) + except ValueError as exc: # pragma: no cover + raise argparse.ArgumentTypeError("尺寸数值必须是整数,例如 720x720") from exc + if width <= 0 or height <= 0: + raise argparse.ArgumentTypeError("尺寸必须为正整数") + return width, height + + +def build_cmd(args: argparse.Namespace, ffmpeg_bin: str) -> list[str]: + width, height = args.size + time_expr = f"(on/{max(args.fps, 1e-6)})" + zoom_expr = ( + "zoompan=" + f"z='{args.base_zoom}+{args.zoom_amp}*sin(2*PI*{args.frequency}*{time_expr})'" + f":d={args.hold_frames}:s={width}x{height}" + ) + cmd = [ + ffmpeg_bin, + "-y", + "-loop", + "1", + "-i", + str(args.image), + "-filter_complex", + zoom_expr, + "-c:v", + args.codec, + "-pix_fmt", + args.pix_fmt, + "-r", + str(args.fps), + "-t", + str(args.duration), + str(args.output), + ] + return cmd + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="用 zoompan 给单张图片制造轻微视角抖动,输出 MP4 伪视频。" + ) + parser.add_argument("image", type=Path, help="输入图片路径(jpg/png 等)") + parser.add_argument("output", type=Path, help="输出 MP4 路径") + parser.add_argument("--fps", type=float, default=2.0, help="输出视频帧率,默认 2") + parser.add_argument("--duration", type=float, default=2.0, help="视频时长(秒),默认 2") + parser.add_argument( + "--size", + type=parse_size, + default=(720, 720), + help="缩放后分辨率,格式 <宽>x<高>,默认 720x720", + ) + parser.add_argument( + "--zoom-amp", + type=float, + default=0.03, + help="缩放抖动幅度,默认 0.03 (±3%)", + ) + parser.add_argument( + "--base-zoom", + type=float, + default=1.0, + help="基础缩放倍率,默认 1.0", + ) + parser.add_argument( + "--frequency", + type=float, + default=1.0, + help="sin 波频率(Hz),默认 1", + ) + parser.add_argument( + "--hold-frames", + type=int, + default=5, + help="zoompan 中的 d 参数,控制每个输入帧复制次数,默认 5", + ) + parser.add_argument( + "--codec", + default="libx264", + help="ffmpeg 视频编码器,默认 libx264", + ) + parser.add_argument( + "--pix-fmt", + default="yuv420p", + help="像素格式,默认 yuv420p(兼容性最好)", + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + if args.output.suffix.lower() != ".mp4": + raise SystemExit("输出文件必须是 .mp4") + + ffmpeg_bin = shutil.which("ffmpeg") + if ffmpeg_bin is None: + raise SystemExit("未检测到 ffmpeg,请先安装或放到 PATH 中") + + if not args.image.exists(): + raise SystemExit(f"输入图片不存在: {args.image}") + + args.output.parent.mkdir(parents=True, exist_ok=True) + + cmd = build_cmd(args, ffmpeg_bin) + print("Running:", " ".join(cmd)) + subprocess.run(cmd, check=True) + print(f"✅ 已生成 {args.output} (约 {args.duration}s @ {args.fps}fps)") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/merge_glb_anim.py b/OVOW/engine/tools/merge_glb_anim.py new file mode 100644 index 0000000000000000000000000000000000000000..aea4cffa7e0e465a11be4163294315d975c1a859 --- /dev/null +++ b/OVOW/engine/tools/merge_glb_anim.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import subprocess +from pathlib import Path + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Merge multiple GLBs into one using Blender.") + parser.add_argument("--base", type=Path, required=True, help="base glb") + parser.add_argument("--add", type=Path, action="append", default=[], help="additional glb (repeatable)") + parser.add_argument("--output", type=Path, required=True, help="output glb") + parser.add_argument("--blender", type=Path, required=True, help="blender binary") + return parser.parse_args() + + +def main() -> None: + args = parse_args() + if not args.base.exists(): + raise FileNotFoundError(args.base) + if not args.blender.exists(): + raise FileNotFoundError(args.blender) + + script = Path(__file__).parent / "blender_merge_glb.py" + cmd = [str(args.blender), "-b", "-P", str(script), "--", "--base", str(args.base), "--out", str(args.output)] + for p in args.add: + cmd.extend(["--add", str(p)]) + + subprocess.check_call(cmd) + print(f"[OK] Wrote: {args.output}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/merge_glb_animation_clips.py b/OVOW/engine/tools/merge_glb_animation_clips.py new file mode 100644 index 0000000000000000000000000000000000000000..aac2b234f71a1c1b52a5d17668b8e16fe9b8b3a9 --- /dev/null +++ b/OVOW/engine/tools/merge_glb_animation_clips.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import shutil +from copy import deepcopy +from pathlib import Path + +from pygltflib import Animation, GLTF2 + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Merge multiple GLB animation clips into a single clip.") + parser.add_argument("--input", type=Path, required=True, help="Input GLB path") + parser.add_argument("--output", type=Path, required=True, help="Output GLB path") + parser.add_argument("--name", type=str, default="MergedAnimation", help="Merged animation name") + return parser.parse_args() + + +def main() -> None: + args = parse_args() + in_glb = args.input.resolve() + out_glb = args.output.resolve() + + if not in_glb.exists(): + raise FileNotFoundError(in_glb) + + gltf = GLTF2().load(str(in_glb)) + animations = gltf.animations or [] + + if len(animations) <= 1: + if in_glb != out_glb: + out_glb.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(in_glb, out_glb) + print(f"[Info] No clip merge needed ({len(animations)} clip).") + print(f"[OK] Wrote: {out_glb}") + return + + merged_samplers = [] + merged_channels = [] + for anim in animations: + base = len(merged_samplers) + if anim.samplers: + merged_samplers.extend(deepcopy(anim.samplers)) + if anim.channels: + for ch in anim.channels: + ch_new = deepcopy(ch) + ch_new.sampler = int(ch_new.sampler) + base + merged_channels.append(ch_new) + + gltf.animations = [Animation(name=args.name, samplers=merged_samplers, channels=merged_channels)] + out_glb.parent.mkdir(parents=True, exist_ok=True) + gltf.save_binary(str(out_glb)) + print( + f"[OK] Merged {len(animations)} clips -> 1 " + f"(samplers={len(merged_samplers)}, channels={len(merged_channels)})" + ) + print(f"[OK] Wrote: {out_glb}") + + +if __name__ == "__main__": + main() + diff --git a/OVOW/engine/tools/merge_video_label_masks.py b/OVOW/engine/tools/merge_video_label_masks.py new file mode 100644 index 0000000000000000000000000000000000000000..5c75b6ef6bba3183f50caca2645264c759bfda3a --- /dev/null +++ b/OVOW/engine/tools/merge_video_label_masks.py @@ -0,0 +1,522 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import math +import shutil +from datetime import datetime +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence, Tuple + +import numpy as np +from PIL import Image + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=( + "Merge masks from exactly two source labels into one object label and " + "update mask_summary / pipeline_config metadata." + ) + ) + parser.add_argument("--workspace-root", type=Path, required=True, help="Workspace root, e.g. demo_video_output/demo10") + parser.add_argument("--scene-name", type=str, required=True, help="Scene/video name, e.g. demo10") + parser.add_argument( + "--source-labels", + type=str, + required=True, + help="Exactly two comma-separated source labels to merge", + ) + parser.add_argument( + "--merged-label", + type=str, + default="", + help="Optional output label name (default: ' with ')", + ) + parser.add_argument( + "--category", + type=str, + required=True, + choices=("static", "rigid", "deform"), + help="Category for the merged object", + ) + parser.add_argument( + "--backup", + type=int, + choices=[0, 1], + default=1, + help="Create timestamped backups for JSON files before writing", + ) + parser.add_argument("--dry-run", action="store_true", help="Print planned changes without writing") + return parser.parse_args() + + +def _simple_normalize(text: Any) -> str: + raw = str(text or "").strip().lower() + raw = raw.replace("-", " ").replace("_", " ") + raw = "".join(ch if (ch.isalnum() or ch.isspace()) else " " for ch in raw) + return " ".join(raw.split()).strip() + + +def _safe_id(name: str) -> str: + out: List[str] = [] + for ch in str(name or "").lower(): + if ch.isalnum(): + out.append(ch) + elif ch in (" ", "-", "_"): + out.append("_") + cleaned = "".join(out).strip("_") + while "__" in cleaned: + cleaned = cleaned.replace("__", "_") + return cleaned or "obj" + + +def _load_json(path: Path) -> Dict[str, Any]: + return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} + + +def _save_json(path: Path, payload: Dict[str, Any], dry_run: bool) -> None: + if dry_run: + return + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + + +def _backup_file(path: Path, enabled: bool, dry_run: bool) -> Optional[Path]: + if not enabled or dry_run or not path.exists(): + return None + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + backup = path.with_name(f"{path.name}.bak_{ts}") + shutil.copy2(path, backup) + return backup + + +def _next_instance_index(label: str, existing_names: Sequence[str], mask_root: Path) -> int: + label_id = _safe_id(label) + names = set(existing_names) + if mask_root.exists(): + for child in mask_root.iterdir(): + if child.is_dir(): + names.add(child.name) + prefix = f"{label_id}_" + max_idx = 0 + for name in names: + if not name.startswith(prefix): + continue + suffix = name[len(prefix) :] + if suffix.isdigit(): + max_idx = max(max_idx, int(suffix)) + return max_idx + 1 + + +def _load_mask(mask_path: Path) -> Optional[np.ndarray]: + if not mask_path.exists(): + return None + arr = np.array(Image.open(mask_path).convert("L"), dtype=np.uint8) + return arr > 0 + + +def _save_masks(obj_dir: Path, num_frames: int, masks_by_frame: Dict[int, np.ndarray], dry_run: bool) -> None: + if dry_run: + return + obj_dir.mkdir(parents=True, exist_ok=True) + for stale in obj_dir.glob("frame_*.png"): + stale.unlink(missing_ok=True) + if masks_by_frame: + sample = next(iter(masks_by_frame.values())) + blank = np.zeros(sample.shape[:2], dtype=np.uint8) + else: + blank = np.zeros((1, 1), dtype=np.uint8) + for fid in range(num_frames): + mask = masks_by_frame.get(fid) + out = (mask.astype(np.uint8) * 255) if mask is not None else blank + Image.fromarray(out).save(obj_dir / f"frame_{fid:06d}.png") + + +def _mask_iou(a: np.ndarray, b: np.ndarray) -> float: + inter = np.logical_and(a, b).sum() + union = np.logical_or(a, b).sum() + return float(inter) / float(union) if union else 0.0 + + +def _mask_centroid(mask: np.ndarray) -> Optional[Tuple[float, float]]: + ys, xs = np.where(mask) + if len(xs) == 0: + return None + return float(xs.mean()), float(ys.mean()) + + +def _classify_stats( + masks_by_frame: Dict[int, np.ndarray], + static_iou_thresh: float = 0.6, + static_motion_px: float = 10.0, + occlusion_area_ratio: float = 0.6, + min_valid_frames: int = 10, + high_iou_thresh: float = 0.8, + high_iou_motion_mult: float = 3.0, +) -> Tuple[bool, float, float, int, int, float]: + if not masks_by_frame: + return False, 0.0, 0.0, 0, 0, 0.0 + frame_ids = sorted(masks_by_frame.keys()) + areas = np.array([int(masks_by_frame[f].sum()) for f in frame_ids], dtype=np.float32) + if len(areas) == 0: + return False, 0.0, 0.0, 0, 0, 0.0 + area_med = float(np.median(areas)) + if area_med <= 0: + return False, 0.0, 0.0, 0, 0, area_med + + valid_ids = [fid for fid, area in zip(frame_ids, areas) if area >= area_med * occlusion_area_ratio] + occluded_frames = len(frame_ids) - len(valid_ids) + if len(valid_ids) < max(1, min_valid_frames): + return False, 0.0, 0.0, len(valid_ids), occluded_frames, area_med + + ref_mask = masks_by_frame[valid_ids[0]] + ref_centroid = _mask_centroid(ref_mask) + if ref_centroid is None: + return False, 0.0, 0.0, len(valid_ids), occluded_frames, area_med + + ious: List[float] = [] + motions: List[float] = [] + for fid in valid_ids: + mask = masks_by_frame[fid] + ious.append(_mask_iou(ref_mask, mask)) + cent = _mask_centroid(mask) + if cent is None: + continue + dx = cent[0] - ref_centroid[0] + dy = cent[1] - ref_centroid[1] + motions.append(math.hypot(dx, dy)) + + med_iou = float(np.median(ious)) if ious else 0.0 + med_motion = float(np.median(motions)) if motions else 0.0 + is_static = ( + (med_iou >= static_iou_thresh and med_motion <= static_motion_px) + or (med_iou >= high_iou_thresh and med_motion <= static_motion_px * high_iou_motion_mult) + ) + return is_static, med_iou, med_motion, len(valid_ids), occluded_frames, area_med + + +def _replace_labels(seq: Sequence[Any], source_norms: set[str], merged_label: str) -> List[str]: + out: List[str] = [] + added = False + seen = set() + merged_norm = _simple_normalize(merged_label) + for item in seq: + label = str(item) + norm = _simple_normalize(label) + if not norm: + continue + if norm in source_norms or norm == merged_norm: + if not added and merged_norm not in seen: + out.append(merged_label) + seen.add(merged_norm) + added = True + continue + if norm not in seen: + out.append(label) + seen.add(norm) + if not added and merged_norm not in seen: + out.append(merged_label) + return out + + +def _remove_mapping_keys(mapping: Any, remove_norms: set[str]) -> Dict[str, Any]: + if not isinstance(mapping, dict): + return {} + return {str(k): v for k, v in mapping.items() if _simple_normalize(k) not in remove_norms} + + +def _collect_texts(mapping: Any, source_norms: set[str]) -> List[str]: + if not isinstance(mapping, dict): + return [] + vals: List[str] = [] + seen = set() + for key, value in mapping.items(): + if _simple_normalize(key) not in source_norms: + continue + text = str(value or "").strip() + if not text: + continue + norm = text.casefold() + if norm in seen: + continue + seen.add(norm) + vals.append(text) + return vals + + +def _make_reason(src_labels: Sequence[str]) -> str: + return "manual_mask_merge: " + " + ".join(src_labels) + + +def main() -> int: + args = parse_args() + + workspace_root = args.workspace_root.expanduser().resolve() + scene_name = str(args.scene_name).strip() + if not workspace_root.is_dir(): + raise FileNotFoundError(f"workspace root not found: {workspace_root}") + if not scene_name: + raise RuntimeError("--scene-name cannot be empty") + + raw_src = [x.strip() for x in str(args.source_labels).split(",") if x.strip()] + if len(raw_src) != 2: + raise RuntimeError("--source-labels must contain exactly two labels") + src_norms = {_simple_normalize(x) for x in raw_src} + if len(src_norms) != 2: + raise RuntimeError("The two source labels must be different") + + merged_label = str(args.merged_label).strip() or f"{raw_src[0]} with {raw_src[1]}" + merged_norm = _simple_normalize(merged_label) + if not merged_norm: + raise RuntimeError("Merged label is empty after normalization") + category = str(args.category).strip().lower() + + labels_json = workspace_root / "metadata" / f"{scene_name}_labels.json" + summary_json = workspace_root / "metadata" / f"{scene_name}_mask_summary.json" + cfg_main = workspace_root / "recon_ready" / scene_name / "pipeline_config.json" + cfg_effective = workspace_root / "recon_ready" / scene_name / "pipeline_config_effective.json" + + if not labels_json.exists(): + raise FileNotFoundError(labels_json) + if not summary_json.exists(): + raise FileNotFoundError(summary_json) + if not cfg_main.exists(): + raise FileNotFoundError(cfg_main) + + labels_payload = _load_json(labels_json) + summary_payload = _load_json(summary_json) + cfg_main_payload = _load_json(cfg_main) + cfg_effective_payload = _load_json(cfg_effective) if cfg_effective.exists() else None + + meta_path_raw = str(labels_payload.get("label_category_meta", "")).strip() + meta_path = Path(meta_path_raw).expanduser() + if meta_path_raw: + if not meta_path.is_absolute(): + meta_path = (labels_json.parent / meta_path).resolve() + else: + meta_path = meta_path.resolve() + else: + meta_path = None + meta_payload = _load_json(meta_path) if meta_path and meta_path.exists() else None + + mask_root = Path(str(summary_payload.get("mask_root", "")).strip() or (workspace_root / "masks" / scene_name)) + if not mask_root.is_absolute(): + mask_root = (workspace_root / mask_root).resolve() + else: + mask_root = mask_root.resolve() + if not mask_root.exists(): + raise FileNotFoundError(f"mask_root not found: {mask_root}") + + summary_objects = list(summary_payload.get("objects", [])) if isinstance(summary_payload.get("objects"), list) else [] + if not summary_objects: + raise RuntimeError(f"No objects found in summary: {summary_json}") + source_objects = [obj for obj in summary_objects if _simple_normalize(obj.get("label", "")) in src_norms] + if not source_objects: + raise RuntimeError(f"No summary objects found for source labels: {raw_src}") + + existing_merged = [ + obj for obj in summary_objects + if _simple_normalize(obj.get("label", "")) == merged_norm + and obj.get("name") not in {o.get("name") for o in source_objects} + ] + if existing_merged: + raise RuntimeError( + f"Merged label '{merged_label}' already exists as {[obj.get('name') for obj in existing_merged]}; " + "please remove it first or choose a different --merged-label." + ) + + num_frames = int(summary_payload.get("num_frames", 0) or 0) + if num_frames <= 0: + raise RuntimeError(f"Invalid num_frames in summary: {num_frames}") + + union_masks: Dict[int, np.ndarray] = {} + shape: Optional[Tuple[int, int]] = None + src_names = [str(obj.get("name")) for obj in source_objects if str(obj.get("name", "")).strip()] + for obj_name in src_names: + obj_dir = mask_root / obj_name + if not obj_dir.exists(): + raise FileNotFoundError(f"Source mask dir missing: {obj_dir}") + for fid in range(num_frames): + mask = _load_mask(obj_dir / f"frame_{fid:06d}.png") + if mask is None: + continue + if shape is None: + shape = mask.shape[:2] + if mask.any(): + union_masks[fid] = mask if fid not in union_masks else np.logical_or(union_masks[fid], mask) + elif fid not in union_masks and shape is None: + shape = mask.shape[:2] + + if shape is None or not union_masks: + raise RuntimeError("Merged masks are empty; nothing to write.") + + kept_names = [str(obj.get("name")) for obj in summary_objects if str(obj.get("name")) not in src_names] + new_idx = _next_instance_index(merged_label, kept_names, mask_root) + merged_name = f"{_safe_id(merged_label)}_{new_idx:02d}" + merged_dir = mask_root / merged_name + + _save_masks(merged_dir, num_frames, union_masks, dry_run=args.dry_run) + + _, med_iou, med_motion, valid_frames, occluded_frames, area_med = _classify_stats(union_masks) + max_area = max(int(mask.sum()) for mask in union_masks.values()) if union_masks else 0 + + merged_obj = { + "name": merged_name, + "label": merged_label, + "sam3_obj_id": -1, + "frames_with_mask": int(len(union_masks)), + "max_area": int(max_area), + "median_area": float(area_med), + "valid_frames": int(valid_frames), + "occluded_frames": int(occluded_frames), + "median_iou": float(med_iou), + "median_motion_px": float(med_motion), + "is_static": bool(category == "static"), + "category": category, + "category_source": "manual_label_merge", + "force_static": bool(category == "static"), + "force_dynamic": bool(category != "static"), + "seed_dynamic": bool(category != "static"), + } + + first_src_index = min( + idx for idx, obj in enumerate(summary_objects) if str(obj.get("name")) in src_names + ) + new_summary_objects: List[Dict[str, Any]] = [] + inserted = False + for idx, obj in enumerate(summary_objects): + if idx == first_src_index and not inserted: + new_summary_objects.append(merged_obj) + inserted = True + if str(obj.get("name")) in src_names: + continue + new_summary_objects.append(obj) + if not inserted: + new_summary_objects.append(merged_obj) + + combined_reason = _make_reason(raw_src) + summary_visuals = summary_payload.get("label_visual_descriptions") + source_visuals = _collect_texts(summary_visuals, src_norms) + combined_visual = " + ".join(source_visuals) + + for payload in [labels_payload, summary_payload]: + payload["labels"] = _replace_labels(payload.get("labels", []), src_norms, merged_label) + lpk = payload.get("labels_per_keyframe") + if isinstance(lpk, dict): + payload["labels_per_keyframe"] = { + str(k): _replace_labels(v if isinstance(v, list) else [], src_norms, merged_label) + for k, v in lpk.items() + } + moving = payload.get("moving_labels") + if isinstance(moving, list): + new_moving = _replace_labels(moving, src_norms, merged_label) + if category == "static": + new_moving = [x for x in new_moving if _simple_normalize(x) != merged_norm] + payload["moving_labels"] = new_moving + + categories = _remove_mapping_keys(payload.get("label_categories"), src_norms | {merged_norm}) + reasons = _remove_mapping_keys(payload.get("label_category_reasons"), src_norms | {merged_norm}) + visuals = _remove_mapping_keys(payload.get("label_visual_descriptions"), src_norms | {merged_norm}) + categories[merged_label] = category + reasons[merged_label] = combined_reason + visuals[merged_label] = combined_visual + payload["label_categories"] = categories + payload["label_category_reasons"] = reasons + payload["label_visual_descriptions"] = visuals + + summary_payload["objects"] = new_summary_objects + summary_payload["mask_root"] = str(mask_root) + + if meta_payload is not None: + meta_payload["labels"] = _replace_labels(meta_payload.get("labels", []), src_norms, merged_label) + categories = _remove_mapping_keys(meta_payload.get("label_categories"), src_norms | {merged_norm}) + reasons = _remove_mapping_keys(meta_payload.get("label_category_reasons"), src_norms | {merged_norm}) + visuals = _remove_mapping_keys(meta_payload.get("label_visual_descriptions"), src_norms | {merged_norm}) + categories[merged_label] = category + reasons[merged_label] = combined_reason + visuals[merged_label] = combined_visual + meta_payload["label_categories"] = categories + meta_payload["label_category_reasons"] = reasons + meta_payload["label_visual_descriptions"] = visuals + + parsed_payload = meta_payload.get("parsed_payload") + if not isinstance(parsed_payload, dict): + parsed_payload = {} + meta_payload["parsed_payload"] = parsed_payload + parsed_objects = parsed_payload.get("objects") + if not isinstance(parsed_objects, list): + parsed_objects = [] + parsed_objects = [ + obj + for obj in parsed_objects + if _simple_normalize(obj.get("name", "")) not in src_norms | {merged_norm} + ] + parsed_objects.append( + { + "name": merged_label, + "num": 1, + "visual_description": combined_visual, + "category": category, + "reason": combined_reason, + "is_occluded": False, + "occluded_by": [], + } + ) + parsed_payload["objects"] = parsed_objects + + cfg_objects = list(cfg_main_payload.get("objects", [])) if isinstance(cfg_main_payload.get("objects"), list) else [] + cfg_main_payload["objects"] = [ + obj for obj in cfg_objects if str(obj.get("name")) not in src_names + ] + [ + { + "name": merged_name, + "masks_dir": str((mask_root / merged_name).resolve()), + "category": category, + } + ] + + if isinstance(cfg_effective_payload, dict): + eff_objects = list(cfg_effective_payload.get("objects", [])) if isinstance(cfg_effective_payload.get("objects"), list) else [] + cfg_effective_payload["objects"] = [ + obj for obj in eff_objects if str(obj.get("name")) not in src_names + ] + [ + { + "name": merged_name, + "masks_dir": str((mask_root / merged_name).resolve()), + "category": category, + } + ] + + backup_enabled = bool(int(args.backup)) + for path in [labels_json, summary_json, cfg_main, cfg_effective if cfg_effective.exists() else None, meta_path]: + if path is None: + continue + _backup_file(path, enabled=backup_enabled, dry_run=args.dry_run) + + _save_json(labels_json, labels_payload, dry_run=args.dry_run) + _save_json(summary_json, summary_payload, dry_run=args.dry_run) + _save_json(cfg_main, cfg_main_payload, dry_run=args.dry_run) + if isinstance(cfg_effective_payload, dict) and cfg_effective.exists(): + _save_json(cfg_effective, cfg_effective_payload, dry_run=args.dry_run) + if meta_path is not None and meta_payload is not None: + _save_json(meta_path, meta_payload, dry_run=args.dry_run) + + print(f"[ok] merged labels: {raw_src[0]} + {raw_src[1]} -> {merged_label}") + print(f"[ok] merged object: {merged_name}") + print(f"[ok] category: {category}") + print(f"[ok] source objects: {src_names}") + print(f"[ok] output mask dir: {merged_dir}") + print(f"[ok] updated labels json: {labels_json}") + print(f"[ok] updated mask summary: {summary_json}") + print(f"[ok] updated pipeline config: {cfg_main}") + if meta_path is not None and meta_payload is not None: + print(f"[ok] updated label category meta: {meta_path}") + if args.dry_run: + print("[dry-run] no files written") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/OVOW/engine/tools/model_server/__init__.py b/OVOW/engine/tools/model_server/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/OVOW/engine/tools/model_server/client.py b/OVOW/engine/tools/model_server/client.py new file mode 100644 index 0000000000000000000000000000000000000000..c5fcfa03d660996f723c540c9fb0d7973c89b10b --- /dev/null +++ b/OVOW/engine/tools/model_server/client.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +"""opg-server 通用客户端:提交一个 op,打印结果。供 run_steps 各 step 在 SERVER_MODE 下调用。 + +step6 兼容:打印 `Done. Output: `,让 run_steps 现有的 grep 逻辑不变。 +""" +import argparse +import json +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import ipc # noqa: E402 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--queue", required=True) + ap.add_argument("--op", required=True) + ap.add_argument("--args", default="{}", help="JSON 字符串") + ap.add_argument("--timeout", type=int, default=7200) + a = ap.parse_args() + r = ipc.submit(a.queue, a.op, json.loads(a.args), timeout=a.timeout) + res = r.get("result", {}) + if a.op == "step6" and "run_dir" in res: + print(f"Done. Output: {res['run_dir']}") + print(json.dumps(res)) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/model_server/ipc.py b/OVOW/engine/tools/model_server/ipc.py new file mode 100644 index 0000000000000000000000000000000000000000..6244d6bd750edc3bfd072b1577d7693ec488789a --- /dev/null +++ b/OVOW/engine/tools/model_server/ipc.py @@ -0,0 +1,85 @@ +"""文件队列 IPC:跨 conda env 安全的常驻模型服务请求/响应协议。 + +约定(原子性靠"最后写 .ready/.done 标记"保证): + client 写 req_.json -> 写 req_.ready + server 见 .ready -> 删 .ready,处理 -> 写 resp_.json -> 写 resp_.done + client 见 .done -> 读 resp_.json -> 清理 +server 启动末尾写 `ready`(模型已载),client 用 wait_ready 等它。 +""" +import json +import os +import time +import uuid +import traceback +from pathlib import Path + + +def server_loop(queue_dir, handlers, on_start=None, poll=0.2): + qd = Path(queue_dir) + qd.mkdir(parents=True, exist_ok=True) + (qd / "alive").write_text(str(os.getpid())) + if on_start is not None: + on_start() + (qd / "ready").write_text("1") + print(f"[server] ready, queue={qd}", flush=True) + while True: + markers = sorted(qd.glob("req_*.ready")) + if not markers: + time.sleep(poll) + continue + for rdy in markers: + rid = rdy.stem[len("req_"):] + try: + spec = json.loads((qd / f"req_{rid}.json").read_text()) + except Exception: + rdy.unlink(missing_ok=True) + continue + rdy.unlink(missing_ok=True) + op = spec.get("op") + if op == "shutdown": + (qd / f"resp_{rid}.json").write_text(json.dumps({"ok": True})) + (qd / f"resp_{rid}.done").write_text("1") + print("[server] shutdown", flush=True) + return + t0 = time.time() + try: + result = handlers[op](spec.get("args", {})) + resp = {"ok": True, "result": result, "elapsed": round(time.time() - t0, 1)} + except Exception as e: # noqa: BLE001 + resp = {"ok": False, "error": str(e), "tb": traceback.format_exc(), + "elapsed": round(time.time() - t0, 1)} + (qd / f"resp_{rid}.json").write_text(json.dumps(resp)) + (qd / f"resp_{rid}.done").write_text("1") + print(f"[server] op={op} done in {resp['elapsed']}s ok={resp['ok']}", flush=True) + + +def wait_ready(queue_dir, timeout=1800, poll=0.5): + rd = Path(queue_dir) / "ready" + t0 = time.time() + while not rd.exists(): + if time.time() - t0 > timeout: + raise TimeoutError(f"server not ready: {queue_dir}") + time.sleep(poll) + + +def is_alive(queue_dir): + return (Path(queue_dir) / "ready").exists() + + +def submit(queue_dir, op, args=None, timeout=7200, poll=0.3): + qd = Path(queue_dir) + rid = uuid.uuid4().hex[:12] + (qd / f"req_{rid}.json").write_text(json.dumps({"op": op, "args": args or {}})) + (qd / f"req_{rid}.ready").write_text("1") + done = qd / f"resp_{rid}.done" + t0 = time.time() + while not done.exists(): + if time.time() - t0 > timeout: + raise TimeoutError(f"request timeout op={op}") + time.sleep(poll) + resp = json.loads((qd / f"resp_{rid}.json").read_text()) + for f in (qd / f"req_{rid}.json", qd / f"resp_{rid}.json", done): + f.unlink(missing_ok=True) + if not resp.get("ok"): + raise RuntimeError(f"server op={op} failed: {resp.get('error')}\n{resp.get('tb','')}") + return resp diff --git a/OVOW/engine/tools/model_server/opg_server.py b/OVOW/engine/tools/model_server/opg_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c00a222f805fac337400eb8202fa52ed51747ebc --- /dev/null +++ b/OVOW/engine/tools/model_server/opg_server.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""opg 常驻模型服务:启动时把全部 opg ckpt 载入一次,之后跨视频/跨 step 复用。 + +服务的 op: + - "deform": 进程内调 deform_pose_pipeline.run_deform(args)(args.argv = 原 CLI 参数列表) + - "step6" : 进程内调 pipeline.run_pipeline(config) (静态/刚体重建) + - "shutdown" + +载入一次的模型:pipeline_core(Hi3DGen/TRELLIS/深度/tracker)、RoMaV2(INPROC)、FoundationPose(FP_RESIDENT)。 +跑在 opg env: + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python tools/model_server/opg_server.py --queue +""" +import argparse +import os +import sys +from pathlib import Path + +os.environ.setdefault("OPG_MATCHER", "romav2") +os.environ.setdefault("OPG_SCALE_REFINE_ITERS", "0") +os.environ.setdefault("OPG_ROMAV2_INPROC", "1") +os.environ.setdefault("OPG_FP_RESIDENT", "1") +os.environ.setdefault("PYOPENGL_PLATFORM", "egl") + +_REPO = Path(__file__).resolve().parents[2] +for p in (str(_REPO), str(_REPO / "oneposeviagen" / "fpose"), + str(_REPO / "tools"), str(_REPO / "tools" / "model_server")): + if p not in sys.path: + sys.path.insert(0, p) + +import ipc # noqa: E402 (tools/model_server 在 path 上) + + +def _warm_models(): + """一次性加载所有 opg ckpt。""" + print("[opg-server] 加载 opg 核心模型(Hi3DGen/TRELLIS/深度/tracker)...", flush=True) + import pipeline_core # noqa: F401 导入即触发 "Initializing core models" + print("[opg-server] 预热 RoMaV2(INPROC)+ FoundationPose(resident)...", flush=True) + try: + from oneposeviagen.locate.match_pairs import _ensure_romav2_inproc + _ensure_romav2_inproc() + except Exception as e: # noqa: BLE001 + print(f"[opg-server] romav2 预热跳过: {e}", flush=True) + try: + from fpose.estimater import get_cached_scorer, get_cached_refiner, get_cached_glctx + get_cached_scorer(); get_cached_refiner(); get_cached_glctx() + except Exception as e: # noqa: BLE001 + print(f"[opg-server] FoundationPose 预热跳过: {e}", flush=True) + print("[opg-server] 全部 ckpt 载入完成。", flush=True) + + +def _handle_deform(args): + import deform_pose_pipeline as dpp + argv = args["argv"] + old = sys.argv + try: + sys.argv = ["deform_pose_pipeline.py"] + list(argv) + ns = dpp.parse_args() + dpp.run_deform(ns) + finally: + sys.argv = old + return {"object": args.get("object_name", "")} + + +def _handle_step6(args): + import pipeline as pl + cfg = pl.load_pipeline_config(Path(args["config"])) + run_root = pl.run_pipeline(cfg, continue_on_object_error=True) + return {"run_dir": str(run_root)} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--queue", required=True, help="请求队列目录") + args = ap.parse_args() + handlers = {"deform": _handle_deform, "step6": _handle_step6} + ipc.server_loop(args.queue, handlers, on_start=_warm_models) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/model_server/opg_server_ctl.sh b/OVOW/engine/tools/model_server/opg_server_ctl.sh new file mode 100644 index 0000000000000000000000000000000000000000..4e0f358ac3e2c2753d88f23b5cc06b2e74f43c00 --- /dev/null +++ b/OVOW/engine/tools/model_server/opg_server_ctl.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +set -uo pipefail +REPO="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine" +OPG_PY="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python" +QUEUE="${OPG_SERVER_QUEUE:-/tmp/opg_server_main_q}" +PIDFILE="$QUEUE/server.pid" +LOGDIR="$QUEUE" + +CMD="${1:-status}"; shift || true +GPU=6 +while [[ $# -gt 0 ]]; do case "$1" in + --gpu) GPU="$2"; shift 2;; + --backend) shift 2;; + *) shift;; esac; done + +_server_pid() { + if [[ -f "$PIDFILE" ]]; then + cat "$PIDFILE" 2>/dev/null + elif [[ -f "$QUEUE/alive" ]]; then + cat "$QUEUE/alive" 2>/dev/null + fi +} + +_alive() { + local pid + pid="$(_server_pid)" + [[ -n "$pid" ]] && [[ -f "$QUEUE/ready" ]] && kill -0 "$pid" 2>/dev/null +} + +start() { + mkdir -p "$QUEUE"; rm -f "$QUEUE/ready" + local log="$LOGDIR/opgserver_main_$(date +%Y%m%d_%H%M%S).log" + echo "[ctl] 启动 opg-server (gpu=$GPU queue=$QUEUE)" + ( cd "$REPO" + CUDA_VISIBLE_DEVICES="$GPU" \ + nohup "$OPG_PY" tools/model_server/opg_server.py --queue "$QUEUE" > "$log" 2>&1 & + echo $! > "$PIDFILE" ) + echo "[ctl] pid=$(cat "$PIDFILE") log=$log,等待模型载入就绪..." + local t0=$(date +%s) + until [[ -f "$QUEUE/ready" ]]; do + local pid + pid="$(_server_pid)" + [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null || { echo "[ctl] 服务进程退出,见日志: $log" >&2; tail -5 "$log"; exit 1; } + sleep 3 + done + echo "[ctl] 就绪 (载入耗时 $(( $(date +%s) - t0 ))s)" +} + +case "$CMD" in + start) start ;; + ensure) if _alive; then echo "[ctl] 已在跑 (pid=$(_server_pid), queue=$QUEUE)"; else start; fi ;; + status) if _alive; then echo "RUNNING pid=$(_server_pid) queue=$QUEUE"; else echo "NOT RUNNING (queue=$QUEUE)"; fi ;; + stop) + if _alive; then + "$OPG_PY" -c "import sys;sys.path.insert(0,'$REPO/tools/model_server');import ipc;ipc.submit('$QUEUE','shutdown',timeout=60)" 2>/dev/null || true + sleep 2; kill "$(_server_pid)" 2>/dev/null || true + rm -f "$QUEUE/ready" "$PIDFILE" "$QUEUE/alive"; echo "[ctl] 已停" + else echo "[ctl] 未在跑"; fi ;; + *) echo "用法: $0 start|ensure|status|stop [--gpu N]"; exit 1 ;; +esac diff --git a/OVOW/engine/tools/model_server/run_fullpipe_batch.sh b/OVOW/engine/tools/model_server/run_fullpipe_batch.sh new file mode 100644 index 0000000000000000000000000000000000000000..d86570fd46c2153c39f6a74ddf191c24a4339d2f --- /dev/null +++ b/OVOW/engine/tools/model_server/run_fullpipe_batch.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +set -uo pipefail +REPO="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine" +VIDEO_ROOT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/examples/videos" +APIKEY_FILE="" +QUEUE="/tmp/opg_fullpipe_q" +CTL="$REPO/tools/model_server/opg_server_ctl.sh" + +VIDEOS_ARG=""; VIDEO_DIR=""; GPU=7; STEPS="1 2 3 4 5 6 7 8 10 13 14 17 18"; OUT="" +while [[ $# -gt 0 ]]; do case "$1" in + --videos) VIDEOS_ARG="$2"; shift 2;; --gpu) GPU="$2"; shift 2;; + --video-dir) VIDEO_DIR="$2"; shift 2;; + --out) OUT="$2"; shift 2;; + --steps) STEPS="$2"; shift 2;; *) echo "未知参数: $1" >&2; exit 1;; esac; done +if [[ -n "$VIDEO_DIR" ]]; then + [[ -d "$VIDEO_DIR" ]] || { echo "找不到 --video-dir: $VIDEO_DIR" >&2; exit 1; } + VIDEO_ROOT="$VIDEO_DIR" + mapfile -t _found < <(find "$VIDEO_DIR" -maxdepth 1 -type f \ + \( -iname '*.mp4' -o -iname '*.mov' -o -iname '*.mkv' -o -iname '*.avi' -o -iname '*.webm' \) \ + -printf '%f\n' | sed -E 's/\.[^.]+$//' | sort -u) + [[ ${#_found[@]} -gt 0 ]] || { echo "$VIDEO_DIR 下没找到视频(mp4/mov/mkv/avi/webm)" >&2; exit 1; } + VIDEOS_ARG="$(IFS=,; echo "${_found[*]}")" + echo "[--video-dir] $VIDEO_DIR 发现 ${#_found[@]} 个视频: $VIDEOS_ARG" +fi +[[ -n "$VIDEOS_ARG" ]] || { echo "用法: $0 (--videos a,b,c | --video-dir DIR) [--gpu N] [--out DIR] [--steps ...]" >&2; exit 1; } +IFS=',' read -r -a VIDEOS <<< "$VIDEOS_ARG" +KEY=""; [[ -f "$APIKEY_FILE" ]] && KEY="$(grep -oE 'sk-[A-Za-z0-9]+' "$APIKEY_FILE" | head -1)" + + +SAM3_QUEUE="/tmp/sam3_fullpipe_q" +SAM3_CTL="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/masking/sam3_server_ctl.sh" + +echo "=== 全链路批量(opg+sam3 常驻)| ${#VIDEOS[@]} 视频 | GPU $GPU | steps: $STEPS ===" +T0=$(date +%s) +OPG_SERVER_QUEUE="$QUEUE" bash "$CTL" ensure --gpu "$GPU" +SAM3_SERVER_QUEUE="$SAM3_QUEUE" bash "$SAM3_CTL" ensure --gpu "$GPU" + +declare -a SUMMARY=() +for v in "${VIDEOS[@]}"; do + vpath="" + for ext in mp4 mov mkv avi webm MP4 MOV MKV; do + [[ -f "$VIDEO_ROOT/$v.$ext" ]] && { vpath="$VIDEO_ROOT/$v.$ext"; break; } + done + [[ -n "$vpath" ]] || { echo "[skip] $v 在 $VIDEO_ROOT 找不到视频文件"; SUMMARY+=("$v SKIP"); continue; } + echo "----- 视频 $v 开始 $(date '+%H:%M:%S') -----" + vt0=$(date +%s) + CUDA_VISIBLE_DEVICES="$GPU" DASHSCOPE_API_KEY="$KEY" \ + OPG_SERVER_QUEUE="$QUEUE" SAM3_SERVER_QUEUE="$SAM3_QUEUE" \ + OPG_MATCHER=romav2 OPG_SCALE_REFINE_ITERS=0 OPG_ROMAV2_INPROC=1 OPG_FP_RESIDENT=1 \ + bash "$REPO/run_steps_scene_pipeline.sh" --name "$v" --video "$vpath" \ + ${OUT:+--out "$OUT"} \ + ${QWEN_BACKEND:+--qwen-backend "$QWEN_BACKEND"} \ + --recon-backbone uplegacy --new-workspace 1 \ + --deform-force-scale 1 --deform-force-poses 1 $STEPS \ + && rc=OK || rc="FAIL" + dur=$(( $(date +%s) - vt0 )) + echo "----- 视频 $v $rc 耗时 $((dur/60))m$((dur%60))s -----" + SUMMARY+=("$v $rc $((dur/60))m$((dur%60))s") +done + +OPG_SERVER_QUEUE="$QUEUE" bash "$CTL" stop +SAM3_SERVER_QUEUE="$SAM3_QUEUE" bash "$SAM3_CTL" stop +TOTAL=$(( $(date +%s) - T0 )) +echo "==================================================" +echo "全链路批量完成,总墙钟 $((TOTAL/60))m$((TOTAL%60))s(opg + sam3 模型整批各只载一次)" +for s in "${SUMMARY[@]}"; do echo " $s"; done diff --git a/OVOW/engine/tools/model_server/run_pool_batch.py b/OVOW/engine/tools/model_server/run_pool_batch.py new file mode 100644 index 0000000000000000000000000000000000000000..6ab2fa4e87093dbb80ae0b6502308fd8adebf108 --- /dev/null +++ b/OVOW/engine/tools/model_server/run_pool_batch.py @@ -0,0 +1,542 @@ +#!/usr/bin/env python3 +"""多卡常驻批量漏斗:扫输入目录 → 每卡起 1 个常驻 opg-server(模型只载一次)→ +各卡 worker 自取下一个未处理项跑完整 pipeline(step6/step8 走本卡常驻)→ 全部跑完自动收尾。 + +为 10 万级图片/视频设计: + - 常驻:每卡模型只载一次,省掉 N 次重载(step6 Hi3DGen / 视频 step8 位姿)。 + - 多卡并行:k 卡线性加速,各卡独立 queue 互不干扰。 + - 断点续跑:已 .done 的项自动跳过(中断/重启安全);失败默认跳过,可 --retry-failed。 + - 失败隔离:单条挂掉只记日志、标 .failed、重试 --retries 次,不拖垮整卡。 + - 一条命令:跑完自动停所有 server。 + +用法: + python run_pool_batch.py --in /path/to/folder --gpus 0,1,2,3,4,5,6,7 [--out DIR] + [--kinds both|image|video] [--retries 1] [--retry-failed] + [--image-steps "1 2 6 7 13 14 17 18"] [--video-steps "1 2 3 4 5 6 7 8 10 13 14 17 18"] + [--precomputed-image-steps "6 7 13 14 17 18"] + [--precomputed-video-steps "3 4 5 6 7 8 10 13 14 17 18"] + [--per-gpu 1] + +step2(SAM3 掩码)目前逐项在进程内跑(不常驻),仅 step6/step8 走常驻 server。 +若输入目录下是已带 scene.json / masks / metadata / recon_ready 的预计算样本目录, +会自动跳过 step1/step2。 +""" +import argparse +import json +import multiprocessing as mp +import os +import queue as _q +import re +import shlex +import shutil +import subprocess +import sys +import time +from pathlib import Path + +_HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(_HERE)) +import ipc # noqa: E402 + +REPO = Path(os.environ.get("OVOW_ENGINE_DIR", + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine")) +OPG_PY = os.environ.get("OPG_PY", + "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python") +APIKEY_FILE = os.environ.get("APIKEY_FILE", + "") +CTL = REPO / "tools/model_server/opg_server_ctl.sh" +IMAGE_PIPELINE = REPO / "run_steps_scene_image_pipeline.sh" +VIDEO_PIPELINE = REPO / "run_steps_scene_pipeline.sh" + +IMG_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".bmp"} +VID_EXTS = {".mp4", ".mov", ".mkv", ".avi", ".webm"} + +COMMON_ENV = { + "OPG_MATCHER": "romav2", "OPG_SCALE_REFINE_ITERS": "0", + "OPG_ROMAV2_INPROC": "1", "OPG_FP_RESIDENT": "1", +} + + +def slugify(name: str) -> str: + s = re.sub(r"\s+", "_", name.strip()) + return re.sub(r"[^A-Za-z0-9_.-]", "_", s) + + +def read_api_key() -> str: + try: + txt = Path(APIKEY_FILE).read_text(encoding="utf-8") + m = re.search(r"sk-[A-Za-z0-9]+", txt) + return m.group(0) if m else "" + except Exception: + return "" + + +def _first_child_video(scene_dir: Path) -> Path | None: + preferred = [scene_dir / f"{scene_dir.name}{ext}" for ext in sorted(VID_EXTS)] + for p in preferred: + if p.is_file(): + return p + videos = sorted(p for p in scene_dir.iterdir() if p.is_file() and p.suffix.lower() in VID_EXTS) + return videos[0] if videos else None + + +def _is_precomputed_image_scene(scene_dir: Path) -> bool: + if not scene_dir.is_dir(): + return False + if not (scene_dir / "scene.json").is_file(): + return False + if not (scene_dir / "masks").is_dir(): + return False + name = slugify(scene_dir.name) + return ( + (scene_dir / "metadata" / f"{name}_mask_summary.json").is_file() + and (scene_dir / "recon_ready" / name / "pipeline_config.json").is_file() + ) + + +def _is_precomputed_video_scene(scene_dir: Path) -> tuple[bool, Path | None]: + if not scene_dir.is_dir(): + return False, None + video = _first_child_video(scene_dir) + if video is None: + return False, None + name = slugify(video.stem) + ok = ( + (scene_dir / "metadata" / f"{name}_mask_summary.json").is_file() + and (scene_dir / "recon_ready" / name / "pipeline_config.json").is_file() + and (scene_dir / "masks" / name).is_dir() + ) + return ok, video if ok else None + + +def _scan_precomputed_dir(scene_dir: Path, kinds: str): + if kinds in ("both", "image") and _is_precomputed_image_scene(scene_dir): + return { + "kind": "image", + "name": slugify(scene_dir.name), + "path": str(scene_dir.resolve()), + "precomputed": True, + } + if kinds in ("both", "video"): + ok, video = _is_precomputed_video_scene(scene_dir) + if ok and video is not None: + return { + "kind": "video", + "name": slugify(video.stem), + "path": str(video.resolve()), + "scene_dir": str(scene_dir.resolve()), + "precomputed": True, + } + return None + + +def _link_or_copy(src: Path, dst: Path) -> None: + """Materialize large prepared inputs without duplicating them when possible.""" + src = src.resolve() + dst.parent.mkdir(parents=True, exist_ok=True) + if dst.exists() or dst.is_symlink(): + return + try: + dst.symlink_to(src, target_is_directory=src.is_dir()) + except OSError: + if src.is_dir(): + shutil.copytree(src, dst, dirs_exist_ok=True) + else: + shutil.copy2(src, dst) + + +def _copy_selected_metadata(src_dir: Path, dst_dir: Path) -> None: + if not src_dir.is_dir(): + return + dst_dir.mkdir(parents=True, exist_ok=True) + for p in sorted(src_dir.iterdir()): + if not p.is_file(): + continue + name = p.name + if "step_state" in name or "step_errors" in name: + continue + if name.endswith(".json"): + shutil.copy2(p, dst_dir / name) + + +def _rewrite_precomputed_config(cfg_path: Path, *, kind: str, name: str, scene_dir: Path, + media_path: Path, output_root: Path) -> None: + if not cfg_path.is_file(): + return + cfg = json.loads(cfg_path.read_text(encoding="utf-8")) + cfg["output_root"] = str(output_root.resolve()) + cfg["mask_glob"] = str(cfg.get("mask_glob", "frame_*.png")) + if kind == "video": + cfg["video_path"] = str(media_path.resolve()) + mask_base = scene_dir / "masks" / name + else: + cfg["scene_dir"] = str(scene_dir.resolve()) + cfg["scene_name"] = name + cfg["image_path"] = str(media_path.resolve()) + mask_base = scene_dir / "masks" + objects = cfg.get("objects", []) + if isinstance(objects, list): + for obj in objects: + if not isinstance(obj, dict): + continue + obj_name = str(obj.get("name") or obj.get("id") or "").strip() + if obj_name: + obj["masks_dir"] = str((mask_base / obj_name).resolve()) + cfg_path.write_text(json.dumps(cfg, indent=2, ensure_ascii=False), encoding="utf-8") + + +def _rewrite_precomputed_summary(summary_path: Path, *, kind: str, name: str, + scene_dir: Path, media_path: Path) -> None: + if not summary_path.is_file(): + return + try: + payload = json.loads(summary_path.read_text(encoding="utf-8")) + except Exception: + return + if kind == "video": + payload["video"] = str(media_path.resolve()) + payload["video_name"] = name + payload["mask_root"] = str((scene_dir / "masks" / name).resolve()) + else: + payload["scene_dir"] = str(scene_dir.resolve()) + payload["scene_name"] = name + payload["video"] = str(media_path.resolve()) + payload["image"] = str(media_path.resolve()) + payload["image_name"] = media_path.name + payload["mask_root"] = str((scene_dir / "masks").resolve()) + payload["labels_json"] = str((scene_dir / "metadata" / f"{name}_labels.json").resolve()) + for obj in payload.get("objects", []) if isinstance(payload.get("objects"), list) else []: + if not isinstance(obj, dict): + continue + obj_name = str(obj.get("name") or obj.get("id") or "").strip() + if obj_name: + if kind == "video": + obj["masks_dir"] = str((scene_dir / "masks" / name / obj_name).resolve()) + else: + obj["masks_dir"] = str((scene_dir / "masks" / obj_name).resolve()) + summary_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8") + + +def materialize_precomputed_scene(item: dict, out_dir: Path) -> tuple[Path, Path]: + """Stage a prepared scene under output/img|video while keeping input data read-only.""" + name = item["name"] + kind = item["kind"] + src_scene = Path(item.get("scene_dir") or item["path"]).resolve() + dst_scene = (out_dir / ("video" if kind == "video" else "img") / name).resolve() + dst_scene.mkdir(parents=True, exist_ok=True) + + src_media = Path(item["path"]).resolve() if kind == "video" else None + if kind == "image": + image_files = sorted(p for p in src_scene.iterdir() + if p.is_file() and p.suffix.lower() in IMG_EXTS) + if not image_files: + raise FileNotFoundError(f"precomputed image scene has no image file: {src_scene}") + src_media = image_files[0] + assert src_media is not None + dst_media = dst_scene / src_media.name + _link_or_copy(src_media, dst_media) + + for fname in ("scene.json", "source_metadata.json"): + src_file = src_scene / fname + if src_file.is_file(): + shutil.copy2(src_file, dst_scene / fname) + for dname in ("frames", "masks"): + src_child = src_scene / dname + if src_child.exists(): + _link_or_copy(src_child, dst_scene / dname) + _copy_selected_metadata(src_scene / "metadata", dst_scene / "metadata") + + src_cfg = src_scene / "recon_ready" / name / "pipeline_config.json" + dst_cfg_dir = dst_scene / "recon_ready" / name + dst_cfg_dir.mkdir(parents=True, exist_ok=True) + shutil.copy2(src_cfg, dst_cfg_dir / "pipeline_config.json") + + _rewrite_precomputed_config( + dst_cfg_dir / "pipeline_config.json", + kind=kind, + name=name, + scene_dir=dst_scene, + media_path=dst_media, + output_root=dst_scene, + ) + _rewrite_precomputed_summary( + dst_scene / "metadata" / f"{name}_mask_summary.json", + kind=kind, + name=name, + scene_dir=dst_scene, + media_path=dst_media, + ) + return dst_scene, dst_media.resolve() + + +def scan_items(in_dir: Path, kinds: str): + """扫输入目录,按扩展名或预计算 scene 目录分流为 image/video 工作项。""" + items, seen = [], set() + for p in sorted(in_dir.iterdir()): + if p.is_dir(): + item = _scan_precomputed_dir(p, kinds) + if item is not None: + name = item["name"] + if name in seen: + print(f"[scan] 跳过重名项: {p.name} (name={name} 已存在)", flush=True) + continue + seen.add(name) + items.append(item) + continue + for child in sorted(x for x in p.iterdir() if x.is_dir()): + item = _scan_precomputed_dir(child, kinds) + if item is None: + continue + name = item["name"] + if name in seen: + print(f"[scan] 跳过重名项: {child.name} (name={name} 已存在)", flush=True) + continue + seen.add(name) + items.append(item) + continue + if not p.is_file(): + continue + ext = p.suffix.lower() + if ext in IMG_EXTS and kinds in ("both", "image"): + kind = "image" + elif ext in VID_EXTS and kinds in ("both", "video"): + kind = "video" + else: + continue + name = slugify(p.stem) + if name in seen: + print(f"[scan] 跳过重名项: {p.name} (name={name} 已存在)", flush=True) + continue + seen.add(name) + items.append({"kind": kind, "name": name, "path": str(p.resolve()), "precomputed": False}) + return items + + +def build_cmd_env(item, gpu, queue_dir, out_dir, scenes_root, args, api_key): + env = {**os.environ, **COMMON_ENV, + "CUDA_VISIBLE_DEVICES": str(gpu), + "OPG_SERVER_QUEUE": str(queue_dir), + "DASHSCOPE_API_KEY": api_key} + name = item["name"] + if item["kind"] == "video": + if item.get("precomputed"): + if out_dir: + scene_dir, video_path = materialize_precomputed_scene(item, out_dir) + else: + scene_dir = Path(item.get("scene_dir") or Path(item["path"]).parent).resolve() + video_path = Path(item["path"]).resolve() + cmd = ["bash", str(VIDEO_PIPELINE), "--name", name, "--video", str(video_path)] + cmd += ["--out", str(scene_dir), "--workspace-root", str(scene_dir)] + elif out_dir: + cmd = ["bash", str(VIDEO_PIPELINE), "--name", name, "--video", item["path"]] + cmd += ["--out", str(out_dir)] + else: + cmd = ["bash", str(VIDEO_PIPELINE), "--name", name, "--video", item["path"]] + cmd += ["--recon-backbone", "uplegacy", + "--new-workspace", "0" if item.get("precomputed") else "1", + "--deform-force-scale", "1", "--deform-force-poses", "1"] + if args.video_extra_args: + cmd += shlex.split(args.video_extra_args) + steps = args.precomputed_video_steps if item.get("precomputed") else args.video_steps + cmd += steps.split() + else: + if item.get("precomputed"): + if out_dir: + scene_dir, _ = materialize_precomputed_scene(item, out_dir) + else: + scene_dir = Path(item["path"]).resolve() + else: + scene_dir = scenes_root / name + scene_dir.mkdir(parents=True, exist_ok=True) + link = scene_dir / Path(item["path"]).name + if not link.exists(): + try: + link.symlink_to(item["path"]) + except FileExistsError: + pass + cmd = ["bash", str(IMAGE_PIPELINE), "--scene-dir", str(scene_dir), "--name", name] + if item.get("precomputed"): + cmd += ["--out", str(scene_dir)] + elif out_dir: + cmd += ["--out", str(out_dir / name)] + cmd += ["--recon-backbone", "legacy"] + if args.image_extra_args: + cmd += shlex.split(args.image_extra_args) + steps = args.precomputed_image_steps if item.get("precomputed") else args.image_steps + cmd += steps.split() + return cmd, env + + +def worker(gpu, queue_dir, jobq, state_dir, log_dir, out_dir, scenes_root, args, api_key): + api_key = api_key or read_api_key() + while True: + try: + item = jobq.get_nowait() + except _q.Empty: + return + name = item["name"] + done_mk = state_dir / f"{name}.done" + fail_mk = state_dir / f"{name}.failed" + if done_mk.exists(): + continue + cmd, env = build_cmd_env(item, gpu, queue_dir, out_dir, scenes_root, args, api_key) + log_path = log_dir / f"{name}.log" + rc = 1 + for attempt in range(1, args.retries + 2): + with open(log_path, "ab") as lf: + lf.write(f"\n===== [gpu{gpu}] {name} attempt {attempt} {time.strftime('%F %T')} =====\n" + .encode()) + lf.flush() + rc = subprocess.call(cmd, env=env, stdout=lf, stderr=subprocess.STDOUT, cwd=str(REPO)) + if rc == 0: + break + print(f"[gpu{gpu}] {name} attempt {attempt} FAIL rc={rc}", flush=True) + if rc == 0: + fail_mk.unlink(missing_ok=True) + done_mk.write_text(time.strftime("%F %T")) + print(f"[gpu{gpu}] {name} OK", flush=True) + else: + fail_mk.write_text(f"{time.strftime('%F %T')} rc={rc} log={log_path}") + print(f"[gpu{gpu}] {name} FAILED (见 {log_path})", flush=True) + + +def start_servers(gpus, queues, server_backend): + """并发起每卡 server(各自阻塞等模型载入),返回时全部 ready。""" + procs = [] + for g, q in zip(gpus, queues): + Path(q).mkdir(parents=True, exist_ok=True) + env = {**os.environ, "OPG_SERVER_QUEUE": str(q)} + print(f"[pool] 起 opg-server gpu={g} queue={q} backend={server_backend}", flush=True) + procs.append(subprocess.Popen( + ["bash", str(CTL), "ensure", "--gpu", str(g), "--backend", server_backend], env=env)) + for p in procs: + p.wait() + for q in queues: + ipc.wait_ready(str(q), timeout=3600) + print("[pool] 所有卡 server 就绪", flush=True) + + +def stop_servers(queues): + for q in queues: + env = {**os.environ, "OPG_SERVER_QUEUE": str(q)} + subprocess.call(["bash", str(CTL), "stop"], env=env) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--in", dest="in_dir", required=True, help="输入文件夹(扫一层)") + ap.add_argument("--gpus", required=True, help="逗号分隔,如 0,1,2,3,4,5,6,7") + ap.add_argument("--out", default="", help="输出根目录(可空,用 pipeline 默认)") + ap.add_argument("--kinds", default="both", choices=["both", "image", "video"]) + ap.add_argument("--retries", type=int, default=1, help="失败重试次数(默认 1)") + ap.add_argument("--retry-failed", action="store_true", help="重跑上次标记 .failed 的项") + ap.add_argument("--per-gpu", type=int, default=1, help="每卡并发 worker 数(默认 1)") + ap.add_argument("--image-steps", default="1 2 6 7 13 14 17 18") + ap.add_argument("--video-steps", default="1 2 3 4 5 6 7 8 10 13 14 17 18") + ap.add_argument("--precomputed-image-steps", default="6 7 13 14 17 18", + help="Steps for image scene dirs that already contain masks/config") + ap.add_argument("--precomputed-video-steps", default="3 4 5 6 7 8 10 13 14 17 18", + help="Steps for video scene dirs that already contain masks/config") + ap.add_argument("--video-extra-args", default="", + help="Extra args inserted before video pipeline steps, e.g. '--lock-static-mode off'") + ap.add_argument("--image-extra-args", default="", + help="Extra args inserted before image pipeline steps") + ap.add_argument("--state-dir", default="", help="进度/标记目录(默认 /_pool_state)") + ap.add_argument("--queue-prefix", default="/tmp/ovow_pool_q", help="每卡 queue 目录前缀") + ap.add_argument("--dry-run", action="store_true") + args = ap.parse_args() + + in_dir = Path(args.in_dir).expanduser().resolve() + assert in_dir.is_dir(), f"--in 不是目录: {in_dir}" + gpus = [int(x) for x in args.gpus.split(",") if x.strip() != ""] + out_dir = Path(args.out).expanduser().resolve() if args.out else None + base = out_dir if out_dir else in_dir + state_dir = Path(args.state_dir).resolve() if args.state_dir else base / "_pool_state" + log_dir = base / "_pool_logs" + scenes_root = base / "_pool_scenes" + for d in (state_dir, log_dir, scenes_root): + d.mkdir(parents=True, exist_ok=True) + if out_dir: + out_dir.mkdir(parents=True, exist_ok=True) + + items = scan_items(in_dir, args.kinds) + n_img = sum(1 for it in items if it["kind"] == "image") + n_vid = sum(1 for it in items if it["kind"] == "video") + n_pre = sum(1 for it in items if it.get("precomputed")) + + pending = [] + skipped_done = skipped_failed = 0 + for it in items: + if (state_dir / f"{it['name']}.done").exists(): + skipped_done += 1 + continue + if (state_dir / f"{it['name']}.failed").exists() and not args.retry_failed: + skipped_failed += 1 + continue + pending.append(it) + + print(f"=== pool batch | 扫到 {len(items)} 项 (图{n_img}/视频{n_vid}/预计算{n_pre}) | " + f"已完成跳过 {skipped_done} | 失败跳过 {skipped_failed} | 待跑 {len(pending)} ===") + print(f"=== GPU {gpus} | 每卡 {args.per_gpu} worker | " + f"retries={args.retries} ===") + print(f"=== out={out_dir} state={state_dir} logs={log_dir} ===") + if args.dry_run: + for it in pending[:20]: + tag = " precomputed" if it.get("precomputed") else "" + print(f" [{it['kind']}{tag}] {it['name']} <- {it['path']}") + if len(pending) > 20: + print(f" ... 及另外 {len(pending) - 20} 项") + return + if not pending: + print("没有待跑项,结束。") + return + + queues = [f"{args.queue_prefix}_gpu{g}" for g in gpus] + server_backend = "none" + api_key = read_api_key() + if not api_key: + print("[warn] 未读到 sk- API key,step1(Qwen 标注)可能失败", flush=True) + + t0 = time.time() + start_servers(gpus, queues, server_backend) + try: + jobq = mp.Queue() + for it in pending: + jobq.put(it) + procs = [] + for g, q in zip(gpus, queues): + for _ in range(args.per_gpu): + p = mp.Process(target=worker, + args=(g, q, jobq, state_dir, log_dir, out_dir, scenes_root, args, api_key)) + p.start() + procs.append(p) + total = len(pending) + while any(p.is_alive() for p in procs): + time.sleep(15) + done = len(list(state_dir.glob("*.done"))) + failed = len(list(state_dir.glob("*.failed"))) + acc = done + failed + pct = int(100 * acc / max(total, 1)) + el = int(time.time() - t0) + print(f"[pool] {pct}% done={done} failed={failed} 待={max(total - acc, 0)} " + f"用时 {el // 60}m{el % 60}s", flush=True) + for p in procs: + p.join() + finally: + stop_servers(queues) + + done = len(list(state_dir.glob("*.done"))) + failed = sorted(p.stem for p in state_dir.glob("*.failed")) + el = int(time.time() - t0) + print("==================================================") + print(f"pool batch 完成 | 总墙钟 {el // 60}m{el % 60}s | done={done} failed={len(failed)}") + if failed: + print(f"失败项({len(failed)}),清单见 {state_dir}/*.failed:") + for n in failed[:30]: + print(f" {n}") + if len(failed) > 30: + print(f" ... 及另外 {len(failed) - 30} 项 (重跑: 加 --retry-failed)") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/motion324_apply_inv_local.py b/OVOW/engine/tools/motion324_apply_inv_local.py new file mode 100644 index 0000000000000000000000000000000000000000..f08d2f836274970912d01e2ce4438351932af346 --- /dev/null +++ b/OVOW/engine/tools/motion324_apply_inv_local.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Tuple + +import numpy as np +from pygltflib import GLTF2 + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Apply inverse Motion324 local transform to animation GLB.") + parser.add_argument("--input-glb", type=Path, required=True) + parser.add_argument("--norm-json", type=Path, required=True) + parser.add_argument("--output-glb", type=Path, required=True) + return parser.parse_args() + + +def _dtype_from_component(comp: int): + if comp == 5126: + return np.float32 + if comp == 5123: + return np.uint16 + if comp == 5121: + return np.uint8 + raise ValueError(f"Unsupported componentType: {comp}") + + +def _components_for_type(t: str) -> int: + return {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT4": 16}[t] + + +def _read_accessor(gltf: GLTF2, acc_idx: int) -> np.ndarray: + acc = gltf.accessors[acc_idx] + bv = gltf.bufferViews[acc.bufferView] + blob = gltf.binary_blob() + dtype = _dtype_from_component(acc.componentType) + comps = _components_for_type(acc.type) + count = acc.count + offset = (bv.byteOffset or 0) + (acc.byteOffset or 0) + stride = bv.byteStride or (np.dtype(dtype).itemsize * comps) + + data = np.zeros((count, comps), dtype=dtype) + for i in range(count): + start = offset + i * stride + data[i] = np.frombuffer(blob, dtype=dtype, count=comps, offset=start) + return data + + +def _write_accessor(gltf: GLTF2, acc_idx: int, arr: np.ndarray) -> None: + acc = gltf.accessors[acc_idx] + bv = gltf.bufferViews[acc.bufferView] + blob = bytearray(gltf.binary_blob() or b"") + dtype = _dtype_from_component(acc.componentType) + comps = _components_for_type(acc.type) + offset = (bv.byteOffset or 0) + (acc.byteOffset or 0) + stride = bv.byteStride or (np.dtype(dtype).itemsize * comps) + + arr = arr.astype(dtype) + for i in range(acc.count): + start = offset + i * stride + blob[start : start + comps * np.dtype(dtype).itemsize] = arr[i].tobytes() + + acc.min = None + acc.max = None + gltf.set_binary_blob(bytes(blob)) + + +def _apply_inv_transform(pts: np.ndarray, R: np.ndarray, scale: float, center: np.ndarray, is_delta: bool) -> np.ndarray: + if pts.size == 0: + return pts + out = pts @ R + out = out * scale + if not is_delta: + out = out + center + return out + + +def main() -> None: + args = parse_args() + if not args.input_glb.exists(): + raise FileNotFoundError(args.input_glb) + if not args.norm_json.exists(): + raise FileNotFoundError(args.norm_json) + + norm = json.loads(args.norm_json.read_text()) + center = np.asarray(norm["center"], dtype=np.float32) + scale = float(norm["scale"]) + R_example = np.asarray(norm["R_example"], dtype=np.float32) + R_out = np.asarray(norm["R_out"], dtype=np.float32) + + R = (R_out.T @ R_example).astype(np.float32) + + gltf = GLTF2().load(args.input_glb) + + for mesh in gltf.meshes or []: + for prim in mesh.primitives or []: + if prim.attributes and prim.attributes.POSITION is not None: + pos = _read_accessor(gltf, prim.attributes.POSITION) + pos = _apply_inv_transform(pos, R, scale, center, is_delta=False) + _write_accessor(gltf, prim.attributes.POSITION, pos) + if prim.attributes and getattr(prim.attributes, "NORMAL", None) is not None: + nrm = _read_accessor(gltf, prim.attributes.NORMAL) + nrm = (nrm @ R).astype(np.float32) + nrm = nrm / (np.linalg.norm(nrm, axis=1, keepdims=True) + 1e-8) + _write_accessor(gltf, prim.attributes.NORMAL, nrm) + + for target in prim.targets or []: + if "POSITION" in target: + dpos = _read_accessor(gltf, target["POSITION"]) + dpos = _apply_inv_transform(dpos, R, scale, center, is_delta=True) + _write_accessor(gltf, target["POSITION"], dpos) + if "NORMAL" in target: + dnrm = _read_accessor(gltf, target["NORMAL"]) + dnrm = (dnrm @ R).astype(np.float32) + dnrm = dnrm / (np.linalg.norm(dnrm, axis=1, keepdims=True) + 1e-8) + _write_accessor(gltf, target["NORMAL"], dnrm) + + args.output_glb.parent.mkdir(parents=True, exist_ok=True) + gltf.save(args.output_glb) + print(f"[OK] Wrote: {args.output_glb}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/open_glb_with_step18_camera_in_blender.sh b/OVOW/engine/tools/open_glb_with_step18_camera_in_blender.sh new file mode 100644 index 0000000000000000000000000000000000000000..93c405ddf78b4d38f01768f746c730f1cec44bef --- /dev/null +++ b/OVOW/engine/tools/open_glb_with_step18_camera_in_blender.sh @@ -0,0 +1,111 @@ +#!/usr/bin/env bash +set -euo pipefail + +BLENDER_BIN="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/opt/blender-4.2.3-linux-x64/blender" +BLENDER_BIN="$(command -v "$BLENDER_BIN" 2>/dev/null || echo "$BLENDER_BIN")" +BLENDER_LIB="" +SCRIPT="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/blender_import_glb_with_step18_camera.py" +RUN_DIR="" +GLB="" +CAMERA_JSON="" +SAVE_BLEND="" +FPS="" +CLEAR_SCENE="1" +BACKGROUND="0" + +usage() { + cat <<'USAGE' +Usage: + bash open_glb_with_step18_camera_in_blender.sh --run-dir /path/to/run_dir [options] + bash open_glb_with_step18_camera_in_blender.sh --glb /path/to/file.glb --camera-json /path/to/camera_step18_bundle.json [options] + +Options: + --run-dir DIR Run dir containing Step 14 GLB and camera_step18_bundle.json + --glb PATH Explicit GLB path + --camera-json PATH Explicit camera_step18_bundle.json path + --blender-bin PATH Blender binary (default: built-in path) + --blender-lib PATH Blender lib dir for LD_LIBRARY_PATH + --save-blend PATH Optional .blend output path + --fps N Optional FPS override + --clear-scene 0|1 Reset scene before import (default: 1) + --background 0|1 Run Blender in background mode (default: 0) +USAGE +} + +normalize_bool() { + local raw="${1:-}" + local v + v="$(echo "$raw" | tr '[:upper:]' '[:lower:]')" + case "$v" in + 1|true|yes|on) echo "1" ;; + 0|false|no|off) echo "0" ;; + *) echo "ERROR: invalid boolean '$raw'" >&2; exit 1 ;; + esac +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --run-dir) RUN_DIR="$2"; shift 2 ;; + --glb) GLB="$2"; shift 2 ;; + --camera-json) CAMERA_JSON="$2"; shift 2 ;; + --blender-bin) BLENDER_BIN="$2"; shift 2 ;; + --blender-lib) BLENDER_LIB="$2"; shift 2 ;; + --save-blend) SAVE_BLEND="$2"; shift 2 ;; + --fps) FPS="$2"; shift 2 ;; + --clear-scene) CLEAR_SCENE="$2"; shift 2 ;; + --background) BACKGROUND="$2"; shift 2 ;; + --help|-h) usage; exit 0 ;; + *) echo "ERROR: unknown option $1" >&2; usage; exit 1 ;; + esac +done + +CLEAR_SCENE="$(normalize_bool "$CLEAR_SCENE")" +BACKGROUND="$(normalize_bool "$BACKGROUND")" + +if [[ -n "$RUN_DIR" ]]; then + RUN_DIR="$(python3 - "$RUN_DIR" <<'PY' +from pathlib import Path +import sys +print(Path(sys.argv[1]).expanduser().resolve()) +PY +)" + [[ -n "$GLB" ]] || GLB="$RUN_DIR/scene_anim_blender_physics_with_deform.glb" + [[ -n "$CAMERA_JSON" ]] || CAMERA_JSON="$RUN_DIR/camera_step18_bundle.json" +fi + +[[ -n "$GLB" ]] || { echo "ERROR: missing --glb or --run-dir" >&2; usage; exit 1; } +[[ -n "$CAMERA_JSON" ]] || { echo "ERROR: missing --camera-json or --run-dir" >&2; usage; exit 1; } +[[ -x "$BLENDER_BIN" ]] || { echo "ERROR: blender not executable: $BLENDER_BIN" >&2; exit 1; } +[[ -d "$BLENDER_LIB" ]] || { echo "ERROR: blender lib dir not found: $BLENDER_LIB" >&2; exit 1; } +[[ -f "$SCRIPT" ]] || { echo "ERROR: import script not found: $SCRIPT" >&2; exit 1; } +[[ -f "$GLB" ]] || { echo "ERROR: glb not found: $GLB" >&2; exit 1; } +[[ -f "$CAMERA_JSON" ]] || { echo "ERROR: camera json not found: $CAMERA_JSON" >&2; exit 1; } + +cmd=( + "$BLENDER_BIN" +) + +if [[ "$BACKGROUND" == "1" ]]; then + cmd+=(-b) +fi + +cmd+=( + -P "$SCRIPT" + -- + --glb "$GLB" + --camera-json "$CAMERA_JSON" +) + +if [[ "$CLEAR_SCENE" == "1" ]]; then + cmd+=(--clear-scene) +fi +if [[ -n "$SAVE_BLEND" ]]; then + cmd+=(--save-blend "$SAVE_BLEND") +fi +if [[ -n "$FPS" ]]; then + cmd+=(--fps "$FPS") +fi + +echo "[Run] ${cmd[*]}" +export LD_LIBRARY_PATH="$BLENDER_LIB:${LD_LIBRARY_PATH:-}" +exec "${cmd[@]}" diff --git a/OVOW/engine/tools/physics_project_z.py b/OVOW/engine/tools/physics_project_z.py new file mode 100644 index 0000000000000000000000000000000000000000..5d24065acf85b304b8159b337c498f0ff6fb14ce --- /dev/null +++ b/OVOW/engine/tools/physics_project_z.py @@ -0,0 +1,342 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Dict, List, Tuple + +import numpy as np +import trimesh + +try: + from scipy.spatial import cKDTree # type: ignore +except Exception: + cKDTree = None + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Project poses to table plane with Z-only correction.") + parser.add_argument("--run-dir", type=Path, required=True, help="Run dir, e.g. .../video_pipeline_xxx/V1") + parser.add_argument("--config", type=Path, required=True, help="Pipeline config JSON for categories") + parser.add_argument("--alignment", type=Path, required=True, help="alignment_plane.json with plane and T") + parser.add_argument( + "--output-name", + type=str, + default="poses_physics.json", + help="Output pose filename under pose_result/", + ) + parser.add_argument( + "--plane-z", + type=str, + default="zero", + choices=("zero", "minz", "static_minz"), + help="Plane offset: zero=original, minz=all objects min, static_minz=static objects min", + ) + parser.add_argument("--use-locked-static", action="store_true", help="Use poses_locked.json for static input") + parser.add_argument("--bottom-percent", type=float, default=0.03, help="Bottom vertex fraction for contact") + parser.add_argument("--epsilon", type=float, default=0.0, help="Contact tolerance; <=0 uses auto") + parser.add_argument( + "--max-drop", + type=float, + default=0.0, + help="Max downward correction; <=0 uses auto (2% scene diag)", + ) + parser.add_argument( + "--contact-objects", + action="store_true", + help="Enable object-object contact using nearest surface distance", + ) + parser.add_argument( + "--contact-dist", + type=float, + default=0.0, + help="Max 3D distance to treat as contact; <=0 uses auto (3% scene diag)", + ) + parser.add_argument( + "--targets", + type=str, + default="all", + choices=("all", "dynamic", "static"), + help="Which objects to adjust", + ) + parser.add_argument("--max-verts", type=int, default=20000, help="Max vertices sampled per object") + parser.add_argument("--max-contact-verts", type=int, default=2000, help="Max vertices for contact queries") + parser.add_argument("--seed", type=int, default=0, help="Random seed") + parser.add_argument("--allow-down", action="store_true", help="Allow downward settle within max-drop") + parser.add_argument("--iters", type=int, default=1, help="Contact projection iterations per frame") + return parser.parse_args() + + +def _pick_mesh_path(obj_dir: Path) -> Path: + candidates: List[Path] = [] + candidates.append(obj_dir / "mid_files" / "scaled_mesh.obj") + candidates.extend(sorted((obj_dir / "model" / "middle_file").glob("*_high_mesh.obj"))) + candidates.append(obj_dir / "model" / "model.obj") + for c in candidates: + if c.exists(): + return c + raise FileNotFoundError(f"No mesh found in {obj_dir}") + + +def _load_pose_json(obj_dir: Path, use_locked: bool) -> Path: + pose_dir = obj_dir / "pose_result" + locked = pose_dir / "poses_locked.json" + default = pose_dir / "poses.json" + if use_locked and locked.exists(): + return locked + if default.exists(): + return default + raise FileNotFoundError(f"No poses.json under {pose_dir}") + + +def _load_pose_map(pose_json: Path) -> Dict[int, np.ndarray]: + data = json.loads(pose_json.read_text()) + pose_map: Dict[int, np.ndarray] = {} + for k, v in data.items(): + try: + idx = int(k) + except Exception: + continue + pose_map[idx] = np.asarray(v, dtype=np.float32) + return pose_map + + +def _nearest_pose(frame: int, pose_map: Dict[int, np.ndarray], frames: List[int]) -> np.ndarray: + if frame in pose_map: + return pose_map[frame] + nearest = min(frames, key=lambda x: abs(x - frame)) + return pose_map[nearest] + + +def _transform_points(T: np.ndarray, verts: np.ndarray) -> np.ndarray: + ones = np.ones((verts.shape[0], 1), dtype=np.float32) + verts_h = np.concatenate([verts, ones], axis=1) + return (T @ verts_h.T).T[:, :3] + + +def _closest_points_from_verts( + points: np.ndarray, verts: np.ndarray, tree: "cKDTree | None", chunk: int = 256 +) -> np.ndarray: + if points.shape[0] == 0: + return points + if tree is not None: + _, idx = tree.query(points, k=1) + return verts[idx] + out = [] + for i in range(0, points.shape[0], chunk): + p = points[i : i + chunk] + diff = p[:, None, :] - verts[None, :, :] + d2 = np.sum(diff * diff, axis=2) + idx = np.argmin(d2, axis=1) + out.append(verts[idx]) + return np.vstack(out) + + +def main() -> None: + args = parse_args() + rng = np.random.default_rng(args.seed) + + run_dir = args.run_dir.resolve() + config_path = args.config.resolve() + align_path = args.alignment.resolve() + + if not run_dir.exists(): + raise FileNotFoundError(run_dir) + if not config_path.exists(): + raise FileNotFoundError(config_path) + if not align_path.exists(): + raise FileNotFoundError(align_path) + + with config_path.open("r", encoding="utf-8") as f: + cfg = json.load(f) + categories = {o["name"]: str(o.get("category", "")).lower() for o in cfg.get("objects", [])} + static_names = {n for n, c in categories.items() if c == "static"} + + align = json.loads(align_path.read_text()) + plane = np.asarray(align["plane"], dtype=np.float32) + n = plane[:3] + d = float(plane[3]) + n = n / max(1e-8, np.linalg.norm(n)) + + result_npz = run_dir / "results" / "result.npz" + if not result_npz.exists(): + raise FileNotFoundError(result_npz) + data = np.load(result_npz) + extrinsics = data["extrinsics"] + num_frames = extrinsics.shape[0] + + objects_root = run_dir / "objects" + objects = [] + for obj_dir in sorted([d for d in objects_root.iterdir() if d.is_dir()]): + name = obj_dir.name + if name not in categories: + print(f"[Warn] Skip unknown object dir not in config: {name}") + continue + category = categories.get(name, "") + pose_json = _load_pose_json(obj_dir, use_locked=(args.use_locked_static and category == "static")) + pose_map = _load_pose_map(pose_json) + if not pose_map: + continue + mesh_path = _pick_mesh_path(obj_dir) + mesh = trimesh.load(mesh_path, force="mesh") + verts = np.asarray(mesh.vertices, dtype=np.float32) + if verts.shape[0] > args.max_verts: + idx = rng.choice(verts.shape[0], size=args.max_verts, replace=False) + verts = verts[idx] + frame_ids = sorted(pose_map.keys()) + verts_contact = verts + if verts_contact.shape[0] > args.max_contact_verts: + idx2 = rng.choice(verts_contact.shape[0], size=args.max_contact_verts, replace=False) + verts_contact = verts_contact[idx2] + tree = cKDTree(verts_contact) if cKDTree is not None else None + objects.append( + { + "name": name, + "category": category, + "pose_map": pose_map, + "frame_ids": frame_ids, + "verts": verts, + "contact_verts": verts_contact, + "contact_tree": tree, + } + ) + + if not objects: + raise RuntimeError("No objects found for physics projection") + + def collect_world_points(filter_static: bool) -> np.ndarray: + pts = [] + for obj in objects: + if filter_static and obj["name"] not in static_names: + continue + pose = _nearest_pose(0, obj["pose_map"], obj["frame_ids"]) + w_T_o = np.linalg.inv(extrinsics[0]) @ pose + pts.append(_transform_points(w_T_o, obj["verts"])) + if not pts: + return np.empty((0, 3), dtype=np.float32) + return np.vstack(pts) + + static_pts = collect_world_points(True) + + if args.plane_z in ("minz", "static_minz"): + pts = static_pts if args.plane_z == "static_minz" and static_pts.shape[0] > 0 else collect_world_points(False) + if pts.shape[0] > 0: + min_dist = float(np.min(pts @ n + d)) + d = d - min_dist + + all_pts = collect_world_points(False) + if all_pts.shape[0] == 0: + raise RuntimeError("Failed to compute scene bbox for auto thresholds") + bbox_diag = float(np.linalg.norm(all_pts.max(axis=0) - all_pts.min(axis=0))) + epsilon = args.epsilon if args.epsilon > 0.0 else 0.002 * bbox_diag + max_drop = args.max_drop if args.max_drop > 0.0 else 0.02 * bbox_diag + contact_dist = args.contact_dist if args.contact_dist > 0.0 else 0.03 * bbox_diag + + bottom_percent = min(max(args.bottom_percent, 1e-4), 0.5) + + def _is_target(obj: Dict[str, object]) -> bool: + if args.targets == "all": + return True + if args.targets == "dynamic": + return obj["category"] != "static" + if args.targets == "static": + return obj["category"] == "static" + return True + + pose_out: Dict[str, Dict[str, List[List[float]]]] = {obj["name"]: {} for obj in objects} + + for f in range(num_frames): + w_T: Dict[str, np.ndarray] = {} + for obj in objects: + pose = _nearest_pose(f, obj["pose_map"], obj["frame_ids"]) + w_T[obj["name"]] = np.linalg.inv(extrinsics[f]) @ pose + + iters = max(1, int(args.iters)) + for _ in range(iters): + order = [] + for obj in objects: + verts_w = _transform_points(w_T[obj["name"]], obj["verts"]) + dist = verts_w @ n + d + order.append((float(np.min(dist)), obj)) + order.sort(key=lambda x: x[0]) + + processed = set() + for _, obj in order: + name = obj["name"] + if not _is_target(obj): + processed.add(name) + continue + + w_T_o = w_T[name] + verts_w = _transform_points(w_T_o, obj["verts"]) + dist = verts_w @ n + d + + k = max(1, int(len(dist) * bottom_percent)) + kth = np.partition(dist, k - 1)[k - 1] + bottom_mask = dist <= kth + bottom = dist[bottom_mask] + min_dist = float(np.min(bottom)) if bottom.size > 0 else float(np.min(dist)) + + min_pos = float(np.min(dist[dist > epsilon])) if np.any(dist > epsilon) else float("inf") + + if args.contact_objects and np.any(bottom_mask): + bottom_pts = verts_w[bottom_mask] + if bottom_pts.shape[0] > 0: + if bottom_pts.shape[0] > 2000: + idx = rng.choice(bottom_pts.shape[0], size=2000, replace=False) + bottom_pts = bottom_pts[idx] + for other in objects: + if other["name"] == name: + continue + if other["name"] not in processed: + continue + w_T_b = w_T[other["name"]] + o_T_w_b = np.linalg.inv(w_T_b) + pts_b = _transform_points(o_T_w_b, bottom_pts) + closest_b = _closest_points_from_verts( + pts_b, other["contact_verts"], other["contact_tree"] + ) + closest_w = _transform_points(w_T_b, closest_b) + delta_vec = bottom_pts - closest_w + dist3 = np.linalg.norm(delta_vec, axis=1) + near_mask = dist3 <= contact_dist + if np.any(near_mask): + s = np.dot(delta_vec[near_mask], n) + if s.size > 0: + min_dist = min(min_dist, float(np.min(s))) + pos_mask = s > epsilon + if np.any(pos_mask): + min_pos = min(min_pos, float(np.min(s[pos_mask]))) + + delta = 0.0 + if min_dist < -epsilon: + delta = -(min_dist + epsilon) + elif args.allow_down and min_pos < float("inf"): + drop = min_pos - epsilon + drop = min(drop, max_drop) + delta = -drop + + if abs(delta) > 1e-8: + w_T_o = w_T_o.copy() + w_T_o[:3, 3] = w_T_o[:3, 3] + n * delta + w_T[name] = w_T_o + + processed.add(name) + + for obj in objects: + c_T_o = extrinsics[f] @ w_T[obj["name"]] + pose_out[obj["name"]][str(f)] = c_T_o.astype(np.float32).tolist() + + for obj in objects: + out_path = run_dir / "objects" / obj["name"] / "pose_result" / args.output_name + out_path.write_text(json.dumps(pose_out[obj["name"]], indent=2)) + + print(f"[OK] Wrote {args.output_name} for {len(objects)} objects.") + print( + f"[Plane] n={n.tolist()} d={d:.6f} eps={epsilon:.6f} max_drop={max_drop:.6f} contact_dist={contact_dist:.6f}" + ) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/physics_project_z_deform_seq.py b/OVOW/engine/tools/physics_project_z_deform_seq.py new file mode 100644 index 0000000000000000000000000000000000000000..3b036878445e9517d74759836ab665cd276a9572 --- /dev/null +++ b/OVOW/engine/tools/physics_project_z_deform_seq.py @@ -0,0 +1,587 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +import numpy as np +import trimesh + +try: + from scipy.spatial import cKDTree # type: ignore +except Exception: + cKDTree = None + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Apply plane/contact physics projection to deform world-mesh sequences." + ) + parser.add_argument("--run-dir", type=Path, required=True, help="Run dir, e.g. .../video_pipeline_xxx/V1") + parser.add_argument("--config", type=Path, required=True, help="Pipeline config JSON (for object categories)") + parser.add_argument("--alignment", type=Path, required=True, help="alignment_plane.json") + parser.add_argument( + "--motion-output-root", + type=Path, + required=True, + help="Motion324 output root, e.g. .../outputs/motion324_outputs", + ) + parser.add_argument("--video-name", type=str, default="", help="Video name; default: run-dir basename") + parser.add_argument( + "--manifest", + type=Path, + default=None, + help="Optional manifest path (default: //manifest.json)", + ) + parser.add_argument( + "--deform-frames-dir", + type=str, + default="world_mesh_frames", + help="Input deform world mesh dir under each object", + ) + parser.add_argument( + "--deform-pose-world-name", + type=str, + default="poses_fp_world.json", + help="Input world pose filename under each deform object", + ) + parser.add_argument( + "--deform-output-pose-name", + type=str, + default="poses_physics.json", + help="Output camera-pose filename under each deform object", + ) + parser.add_argument( + "--deform-output-world-name", + type=str, + default="poses_physics_world.json", + help="Output world-pose filename under each deform object", + ) + parser.add_argument( + "--deform-output-frames-dir", + type=str, + default="world_mesh_frames_physics", + help="Output deform world mesh directory after physics projection", + ) + parser.add_argument( + "--rigid-pose-name", + type=str, + default="poses_physics.json", + help="Preferred rigid/static pose filename under run_dir/objects/*/pose_result", + ) + parser.add_argument("--use-locked-static", action="store_true", help="Fallback to poses_locked.json for static") + parser.add_argument( + "--plane-z", + type=str, + default="zero", + choices=("zero", "minz", "static_minz"), + help="Plane offset mode", + ) + parser.add_argument("--bottom-percent", type=float, default=0.03, help="Bottom vertex fraction") + parser.add_argument("--epsilon", type=float, default=0.0, help="Contact tolerance; <=0 uses auto") + parser.add_argument( + "--max-drop", + type=float, + default=0.0, + help="Max downward correction; <=0 uses auto (2%% scene diag)", + ) + parser.add_argument("--contact-objects", action="store_true", help="Enable object-object contact") + parser.add_argument( + "--contact-dist", + type=float, + default=0.0, + help="Max 3D distance for contact; <=0 uses auto (3%% scene diag)", + ) + parser.add_argument("--max-verts", type=int, default=20000, help="Max sampled verts per object/frame") + parser.add_argument( + "--max-contact-verts", + type=int, + default=2000, + help="Max sampled verts for contact queries", + ) + parser.add_argument("--seed", type=int, default=0, help="Random seed") + parser.add_argument("--allow-down", action="store_true", help="Allow downward settle") + parser.add_argument("--iters", type=int, default=1, help="Projection iterations per frame") + parser.add_argument( + "--mapping-name", + type=str, + default="physics_mapping.json", + help="Per-object mapping output filename", + ) + return parser.parse_args() + + +def _parse_frame_id(path: Path) -> Optional[int]: + stem = path.stem + for part in reversed(stem.split("_")): + if part.isdigit(): + return int(part) + digits = "".join(ch if ch.isdigit() else " " for ch in stem).split() + if digits: + return int(digits[-1]) + return None + + +def _nearest_key(target: int, keys: List[int]) -> int: + return min(keys, key=lambda x: abs(x - target)) + + +def _pick_mesh_path(obj_dir: Path) -> Path: + candidates: List[Path] = [] + candidates.append(obj_dir / "mid_files" / "scaled_mesh.obj") + candidates.extend(sorted((obj_dir / "model" / "middle_file").glob("*_high_mesh.obj"))) + candidates.append(obj_dir / "model" / "model.obj") + for p in candidates: + if p.exists(): + return p + raise FileNotFoundError(f"No mesh found in {obj_dir}") + + +def _pick_rigid_pose_json( + obj_dir: Path, + category: str, + preferred_name: str, + use_locked_static: bool, +) -> Optional[Path]: + pose_dir = obj_dir / "pose_result" + preferred = pose_dir / preferred_name + if preferred_name and preferred.exists(): + return preferred + if use_locked_static and category == "static": + locked = pose_dir / "poses_locked.json" + if locked.exists(): + return locked + default = pose_dir / "poses.json" + if default.exists(): + return default + locked = pose_dir / "poses_locked.json" + if locked.exists(): + return locked + return None + + +def _load_pose_map(path: Path) -> Dict[int, np.ndarray]: + data = json.loads(path.read_text()) + out: Dict[int, np.ndarray] = {} + for k, v in data.items(): + try: + fid = int(k) + except Exception: + continue + arr = np.asarray(v, dtype=np.float32) + if arr.shape != (4, 4): + continue + out[fid] = arr + return out + + +def _mesh_from_path(path: Path) -> trimesh.Trimesh: + mesh = trimesh.load(str(path), force="mesh") + if isinstance(mesh, trimesh.Scene): + geos = [g for g in mesh.geometry.values() if isinstance(g, trimesh.Trimesh)] + if not geos: + raise RuntimeError(f"No mesh geometry: {path}") + mesh = trimesh.util.concatenate(geos) + if not isinstance(mesh, trimesh.Trimesh): + raise RuntimeError(f"Invalid mesh: {path}") + return mesh + + +def _sample_points(verts: np.ndarray, max_count: int, rng: np.random.Generator) -> np.ndarray: + if verts.shape[0] <= max_count: + return verts + idx = rng.choice(verts.shape[0], size=max_count, replace=False) + return verts[idx] + + +def _transform_points(T: np.ndarray, verts: np.ndarray) -> np.ndarray: + ones = np.ones((verts.shape[0], 1), dtype=np.float32) + verts_h = np.concatenate([verts, ones], axis=1) + return (T @ verts_h.T).T[:, :3] + + +def _closest_points_from_verts( + points: np.ndarray, + verts: np.ndarray, + tree: "cKDTree | None", + chunk: int = 256, +) -> np.ndarray: + if points.shape[0] == 0: + return points + if tree is not None: + _, idx = tree.query(points, k=1) + return verts[idx] + + out = [] + for i in range(0, points.shape[0], chunk): + p = points[i : i + chunk] + diff = p[:, None, :] - verts[None, :, :] + d2 = np.sum(diff * diff, axis=2) + idx = np.argmin(d2, axis=1) + out.append(verts[idx]) + return np.vstack(out) + + +def _load_alignment_plane(path: Path) -> Tuple[np.ndarray, float]: + payload = json.loads(path.read_text()) + plane = np.asarray(payload["plane"], dtype=np.float32) + n = plane[:3] + d = float(plane[3]) + n = n / max(1e-8, np.linalg.norm(n)) + return n, d + + +def _load_mesh_map(mesh_dir: Path) -> Dict[int, Path]: + mesh_map: Dict[int, Path] = {} + for p in sorted(mesh_dir.glob("frame_*.obj")): + fid = _parse_frame_id(p) + if fid is None: + continue + mesh_map[fid] = p + return mesh_map + + +def main() -> None: + args = parse_args() + rng = np.random.default_rng(args.seed) + + run_dir = args.run_dir.resolve() + config_path = args.config.resolve() + align_path = args.alignment.resolve() + + if not run_dir.exists(): + raise FileNotFoundError(run_dir) + if not config_path.exists(): + raise FileNotFoundError(config_path) + if not align_path.exists(): + raise FileNotFoundError(align_path) + + with config_path.open("r", encoding="utf-8") as f: + cfg = json.load(f) + categories = {o["name"]: str(o.get("category", "")).lower() for o in cfg.get("objects", [])} + static_names = {n for n, c in categories.items() if c == "static"} + + result_npz = run_dir / "results" / "result.npz" + if not result_npz.exists(): + raise FileNotFoundError(result_npz) + data = np.load(result_npz) + extrinsics = data["extrinsics"] + num_frames = int(extrinsics.shape[0]) + + video_name = args.video_name or run_dir.name + motion_video_root = (args.motion_output_root / video_name).resolve() + manifest_path = args.manifest.resolve() if args.manifest else (motion_video_root / "manifest.json") + + if not manifest_path.exists(): + raise FileNotFoundError(manifest_path) + manifest = json.loads(manifest_path.read_text()) + + support_objects: List[Dict[str, object]] = [] + objects_root = run_dir / "objects" + if objects_root.exists(): + for obj_dir in sorted([d for d in objects_root.iterdir() if d.is_dir()]): + name = obj_dir.name + category = categories.get(name, "") + if category == "deform": + continue + pose_json = _pick_rigid_pose_json( + obj_dir, + category=category, + preferred_name=args.rigid_pose_name, + use_locked_static=args.use_locked_static, + ) + if pose_json is None: + continue + pose_map = _load_pose_map(pose_json) + if not pose_map: + continue + mesh_path = _pick_mesh_path(obj_dir) + mesh = _mesh_from_path(mesh_path) + verts_full = np.asarray(mesh.vertices, dtype=np.float32) + verts_sample = _sample_points(verts_full, max(1, int(args.max_verts)), rng) + verts_contact = _sample_points(verts_full, max(1, int(args.max_contact_verts)), rng) + support_objects.append( + { + "name": name, + "category": category, + "pose_map": pose_map, + "pose_ids": sorted(pose_map.keys()), + "verts_sample": verts_sample, + "verts_contact": verts_contact, + } + ) + + deform_objects: List[Dict[str, object]] = [] + for obj in manifest.get("objects", []): + name = str(obj.get("name", "")).strip() + if not name: + continue + obj_root = motion_video_root / name + pose_world_path = obj_root / args.deform_pose_world_name + frames_dir = obj_root / args.deform_frames_dir + if not pose_world_path.exists() or not frames_dir.exists(): + print(f"[Warn] Skip deform {name}: missing {pose_world_path} or {frames_dir}") + continue + + pose_world_map = _load_pose_map(pose_world_path) + if not pose_world_map: + print(f"[Warn] Skip deform {name}: no valid world poses in {pose_world_path}") + continue + mesh_map = _load_mesh_map(frames_dir) + if not mesh_map: + print(f"[Warn] Skip deform {name}: no mesh frames under {frames_dir}") + continue + + deform_objects.append( + { + "name": name, + "root": obj_root, + "pose_world_map": pose_world_map, + "pose_world_ids": sorted(pose_world_map.keys()), + "mesh_map": mesh_map, + "mesh_ids": sorted(mesh_map.keys()), + "poses_cam_out": {}, + "poses_world_out": {}, + "mapping": {}, + } + ) + + if not deform_objects: + print("[Warn] No deform objects available for sequence physics projection.") + return + + n, d = _load_alignment_plane(align_path) + + def collect_reference_points(static_only: bool) -> np.ndarray: + pts: List[np.ndarray] = [] + + for sup in support_objects: + if static_only and sup["name"] not in static_names: + continue + pose_ids = sup["pose_ids"] + pose_map = sup["pose_map"] + fid = 0 if 0 in pose_map else _nearest_key(0, pose_ids) + c_T_o = pose_map[fid] + w_T_o = np.linalg.inv(extrinsics[0]) @ c_T_o + pts.append(_transform_points(w_T_o, sup["verts_sample"])) + + if not static_only: + for dobj in deform_objects: + mesh_ids = dobj["mesh_ids"] + mf = 0 if 0 in dobj["mesh_map"] else _nearest_key(0, mesh_ids) + mesh = _mesh_from_path(dobj["mesh_map"][mf]) + verts = np.asarray(mesh.vertices, dtype=np.float32) + verts = _sample_points(verts, max(1, int(args.max_verts)), rng) + pts.append(verts) + + if not pts: + return np.empty((0, 3), dtype=np.float32) + return np.vstack(pts) + + static_pts = collect_reference_points(static_only=True) + all_pts_ref = collect_reference_points(static_only=False) + + if args.plane_z in ("minz", "static_minz"): + pts = static_pts if args.plane_z == "static_minz" and static_pts.shape[0] > 0 else all_pts_ref + if pts.shape[0] > 0: + min_dist = float(np.min(pts @ n + d)) + d = d - min_dist + + if all_pts_ref.shape[0] == 0: + raise RuntimeError("Failed to compute scene bbox for auto thresholds") + + bbox_diag = float(np.linalg.norm(all_pts_ref.max(axis=0) - all_pts_ref.min(axis=0))) + epsilon = float(args.epsilon) if args.epsilon > 0.0 else 0.002 * bbox_diag + max_drop = float(args.max_drop) if args.max_drop > 0.0 else 0.02 * bbox_diag + contact_dist = float(args.contact_dist) if args.contact_dist > 0.0 else 0.03 * bbox_diag + bottom_percent = min(max(float(args.bottom_percent), 1e-4), 0.5) + + for frame in range(num_frames): + support_states: Dict[str, Dict[str, np.ndarray]] = {} + for sup in support_objects: + pose_map = sup["pose_map"] + pose_ids = sup["pose_ids"] + pf = frame if frame in pose_map else _nearest_key(frame, pose_ids) + c_T_o = pose_map[pf] + w_T_o = np.linalg.inv(extrinsics[frame]) @ c_T_o + verts_world = _transform_points(w_T_o, sup["verts_sample"]) + contact_world = _transform_points(w_T_o, sup["verts_contact"]) + support_states[sup["name"]] = { + "verts_world": verts_world, + "contact_world": contact_world, + } + + deform_states: Dict[str, Dict[str, object]] = {} + for dobj in deform_objects: + mesh_ids = dobj["mesh_ids"] + mesh_f = frame if frame in dobj["mesh_map"] else _nearest_key(frame, mesh_ids) + mesh_path = dobj["mesh_map"][mesh_f] + mesh = _mesh_from_path(mesh_path) + verts_full = np.asarray(mesh.vertices, dtype=np.float32) + verts_sample = _sample_points(verts_full, max(1, int(args.max_verts)), rng) + verts_contact = _sample_points(verts_full, max(1, int(args.max_contact_verts)), rng) + + pose_world_map = dobj["pose_world_map"] + pose_world_ids = dobj["pose_world_ids"] + pose_f = frame if frame in pose_world_map else _nearest_key(frame, pose_world_ids) + w_T_o = pose_world_map[pose_f].copy() + + deform_states[dobj["name"]] = { + "mesh": mesh, + "verts_full": verts_full, + "verts_sample": verts_sample, + "verts_contact": verts_contact, + "mesh_frame": int(mesh_f), + "mesh_path": mesh_path, + "pose_frame": int(pose_f), + "pose_world": w_T_o, + "offset": 0.0, + } + + for _ in range(max(1, int(args.iters))): + order: List[Tuple[float, str, str]] = [] + + for name, state in support_states.items(): + dist = state["verts_world"] @ n + d + order.append((float(np.min(dist)), "support", name)) + + for name, state in deform_states.items(): + verts_curr = state["verts_sample"] + n[None, :] * float(state["offset"]) + dist = verts_curr @ n + d + order.append((float(np.min(dist)), "deform", name)) + + order.sort(key=lambda x: x[0]) + + processed: List[Dict[str, object]] = [] + for _, kind, name in order: + if kind == "support": + contact_points = support_states[name]["contact_world"] + tree = cKDTree(contact_points) if cKDTree is not None else None + processed.append( + { + "name": name, + "contact_points": contact_points, + "contact_tree": tree, + } + ) + continue + + state = deform_states[name] + offset = float(state["offset"]) + verts_curr = state["verts_sample"] + n[None, :] * offset + dist = verts_curr @ n + d + + k = max(1, int(len(dist) * bottom_percent)) + kth = np.partition(dist, k - 1)[k - 1] + bottom_mask = dist <= kth + bottom = dist[bottom_mask] + min_dist = float(np.min(bottom)) if bottom.size > 0 else float(np.min(dist)) + min_pos = float(np.min(dist[dist > epsilon])) if np.any(dist > epsilon) else float("inf") + + if args.contact_objects and np.any(bottom_mask): + bottom_pts = verts_curr[bottom_mask] + if bottom_pts.shape[0] > 2000: + idx = rng.choice(bottom_pts.shape[0], size=2000, replace=False) + bottom_pts = bottom_pts[idx] + + for proc in processed: + contact_points = proc["contact_points"] + if contact_points.shape[0] == 0: + continue + closest = _closest_points_from_verts(bottom_pts, contact_points, proc["contact_tree"]) + delta_vec = bottom_pts - closest + dist3 = np.linalg.norm(delta_vec, axis=1) + near_mask = dist3 <= contact_dist + if not np.any(near_mask): + continue + s = np.dot(delta_vec[near_mask], n) + if s.size == 0: + continue + min_dist = min(min_dist, float(np.min(s))) + pos_mask = s > epsilon + if np.any(pos_mask): + min_pos = min(min_pos, float(np.min(s[pos_mask]))) + + delta = 0.0 + if min_dist < -epsilon: + delta = -(min_dist + epsilon) + elif args.allow_down and min_pos < float("inf"): + drop = min_pos - epsilon + drop = min(drop, max_drop) + delta = -drop + + if abs(delta) > 1e-8: + state["offset"] = float(state["offset"] + delta) + + contact_points = state["verts_contact"] + n[None, :] * float(state["offset"]) + tree = cKDTree(contact_points) if cKDTree is not None else None + processed.append( + { + "name": name, + "contact_points": contact_points, + "contact_tree": tree, + } + ) + + for dobj in deform_objects: + name = dobj["name"] + state = deform_states[name] + offset = float(state["offset"]) + + w_T_o = np.asarray(state["pose_world"], dtype=np.float32).copy() + w_T_o[:3, 3] = w_T_o[:3, 3] + n * offset + c_T_o = extrinsics[frame] @ w_T_o + + dobj["poses_world_out"][str(frame)] = w_T_o.astype(np.float32).tolist() + dobj["poses_cam_out"][str(frame)] = c_T_o.astype(np.float32).tolist() + + out_dir = dobj["root"] / args.deform_output_frames_dir + out_dir.mkdir(parents=True, exist_ok=True) + + mesh_out = state["mesh"].copy() + verts_out = np.asarray(state["verts_full"], dtype=np.float32) + n[None, :] * offset + mesh_out.vertices = verts_out + out_path = out_dir / f"frame_{frame:06d}.obj" + mesh_out.export(out_path) + + dobj["mapping"][str(frame)] = { + "mesh_frame": int(state["mesh_frame"]), + "mesh_path": str(state["mesh_path"]), + "pose_frame": int(state["pose_frame"]), + "normal_offset": float(offset), + "output": str(out_path), + } + + for dobj in deform_objects: + root = dobj["root"] + cam_path = root / args.deform_output_pose_name + world_path = root / args.deform_output_world_name + mapping_path = root / args.mapping_name + + cam_path.write_text(json.dumps(dobj["poses_cam_out"], indent=2)) + world_path.write_text(json.dumps(dobj["poses_world_out"], indent=2)) + + mapping_payload = { + "input_mesh_dir": str(root / args.deform_frames_dir), + "output_mesh_dir": str(root / args.deform_output_frames_dir), + "plane_normal": n.tolist(), + "plane_d": float(d), + "epsilon": float(epsilon), + "max_drop": float(max_drop), + "contact_dist": float(contact_dist), + "frames": dobj["mapping"], + } + mapping_path.write_text(json.dumps(mapping_payload, indent=2)) + + print(f"[OK] {dobj['name']}: {cam_path}") + print(f"[OK] {dobj['name']}: {root / args.deform_output_frames_dir}") + + print( + f"[Plane] n={n.tolist()} d={d:.6f} eps={epsilon:.6f} max_drop={max_drop:.6f} contact_dist={contact_dist:.6f}" + ) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/prune_video_labels.py b/OVOW/engine/tools/prune_video_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..316c794af840d72c5fbf4b7951e8aba130b0e9eb --- /dev/null +++ b/OVOW/engine/tools/prune_video_labels.py @@ -0,0 +1,229 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import shutil +from datetime import datetime, timezone +from json import JSONDecodeError +from pathlib import Path +from typing import Any, Dict, List, Sequence, Tuple + + +def _parse_label_csv(raw: str) -> List[str]: + labels: List[str] = [] + seen = set() + for part in str(raw or "").split(","): + label = part.strip() + if not label: + continue + norm = label.casefold() + if norm in seen: + continue + seen.add(norm) + labels.append(label) + return labels + + +def _normalize_label(raw: Any) -> str: + return str(raw or "").strip().casefold() + + +def _load_json(path: Path) -> Dict[str, Any]: + text = path.read_text(encoding="utf-8") + try: + data = json.loads(text) + except JSONDecodeError: + repaired_text = _strip_trailing_commas(text) + if repaired_text == text: + raise + data = json.loads(repaired_text) + print(f"[warn] repaired malformed JSON while reading: {path}") + if not isinstance(data, dict): + raise RuntimeError(f"Expected JSON object: {path}") + return data + + +def _write_json(path: Path, payload: Dict[str, Any]) -> None: + path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + + +def _backup_file(path: Path) -> Path: + ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + backup_path = path.with_name(f"{path.name}.bak.{ts}") + shutil.copy2(path, backup_path) + return backup_path + + +def _strip_trailing_commas(text: str) -> str: + out: List[str] = [] + in_string = False + escaped = False + idx = 0 + + while idx < len(text): + ch = text[idx] + if in_string: + out.append(ch) + if escaped: + escaped = False + elif ch == "\\": + escaped = True + elif ch == '"': + in_string = False + idx += 1 + continue + + if ch == '"': + in_string = True + out.append(ch) + idx += 1 + continue + + if ch == ",": + look_ahead = idx + 1 + while look_ahead < len(text) and text[look_ahead] in " \t\r\n": + look_ahead += 1 + if look_ahead < len(text) and text[look_ahead] in "]}": + idx += 1 + continue + + out.append(ch) + idx += 1 + + return "".join(out) + + +def _filter_str_list(items: Any, drop_set: set[str]) -> List[str]: + if not isinstance(items, list): + return [] + out: List[str] = [] + for item in items: + if not isinstance(item, str): + continue + if _normalize_label(item) in drop_set: + continue + out.append(item) + return out + + +def _filter_mapping_keys(items: Any, drop_set: set[str]) -> Dict[str, Any]: + if not isinstance(items, dict): + return {} + out: Dict[str, Any] = {} + for key, value in items.items(): + if _normalize_label(key) in drop_set: + continue + out[str(key)] = value + return out + + +def _prune_meta_payload(payload: Dict[str, Any], drop_set: set[str]) -> None: + if "labels" in payload: + payload["labels"] = _filter_str_list(payload.get("labels"), drop_set) + + for key in ("label_categories", "label_category_reasons", "label_visual_descriptions"): + if key in payload: + payload[key] = _filter_mapping_keys(payload.get(key), drop_set) + + parsed = payload.get("parsed_payload") + if isinstance(parsed, dict): + objects = parsed.get("objects") + if isinstance(objects, list): + parsed["objects"] = [ + item + for item in objects + if not ( + isinstance(item, dict) + and _normalize_label(item.get("name") or item.get("label")) in drop_set + ) + ] + + +def _prune_labels_payload(payload: Dict[str, Any], drop_set: set[str]) -> Tuple[List[str], List[str]]: + before_labels = _filter_str_list(payload.get("labels"), set()) + after_labels = _filter_str_list(payload.get("labels"), drop_set) + payload["labels"] = after_labels + + labels_per_keyframe = payload.get("labels_per_keyframe") + if isinstance(labels_per_keyframe, dict): + filtered: Dict[str, List[str]] = {} + for key, value in labels_per_keyframe.items(): + filtered[str(key)] = _filter_str_list(value, drop_set) + payload["labels_per_keyframe"] = filtered + + if "moving_labels" in payload: + payload["moving_labels"] = _filter_str_list(payload.get("moving_labels"), drop_set) + + for key in ("label_categories", "label_category_reasons", "label_visual_descriptions"): + if key in payload: + payload[key] = _filter_mapping_keys(payload.get(key), drop_set) + + removed = [label for label in before_labels if _normalize_label(label) in drop_set] + return before_labels, removed + + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Prune mistaken Qwen labels from a video labels JSON.") + parser.add_argument("--labels-json", type=Path, required=True, help="Path to *_labels.json") + parser.add_argument( + "--drop-labels", + type=str, + required=True, + help="Comma-separated labels to remove, e.g. sandbox,table", + ) + parser.add_argument( + "--print-json", + action="store_true", + help="Print the updated labels JSON after overwriting it", + ) + args = parser.parse_args(argv) + + labels_json = args.labels_json.expanduser().resolve() + if not labels_json.is_file(): + raise FileNotFoundError(f"labels json not found: {labels_json}") + + drop_labels = _parse_label_csv(args.drop_labels) + if not drop_labels: + raise RuntimeError("No valid labels were provided in --drop-labels.") + drop_set = {_normalize_label(x) for x in drop_labels} + + payload = _load_json(labels_json) + before_labels, removed = _prune_labels_payload(payload, drop_set) + after_labels = payload.get("labels", []) + + labels_backup = _backup_file(labels_json) + _write_json(labels_json, payload) + + meta_backup = None + meta_path_raw = payload.get("label_category_meta") + if isinstance(meta_path_raw, str) and meta_path_raw.strip(): + meta_path = Path(meta_path_raw).expanduser() + if not meta_path.is_absolute(): + meta_path = (labels_json.parent / meta_path).resolve() + else: + meta_path = meta_path.resolve() + if meta_path.is_file(): + meta_payload = _load_json(meta_path) + _prune_meta_payload(meta_payload, drop_set) + meta_backup = _backup_file(meta_path) + _write_json(meta_path, meta_payload) + + missing = [label for label in drop_labels if label.casefold() not in {_normalize_label(x) for x in before_labels}] + print(f"[ok] labels json updated: {labels_json}") + print(f"[ok] backup: {labels_backup}") + print(f"[ok] labels before: {before_labels}") + print(f"[ok] labels after: {after_labels}") + print(f"[ok] removed labels: {removed}") + if missing: + print(f"[warn] labels not found: {missing}") + if meta_backup is not None: + print(f"[ok] synced label_category_meta backup: {meta_backup}") + + if args.print_json: + print(json.dumps(payload, indent=2, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/OVOW/engine/tools/recover_deform_scale.py b/OVOW/engine/tools/recover_deform_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..57351ffae89a828e649ce0353afa679b600fff44 --- /dev/null +++ b/OVOW/engine/tools/recover_deform_scale.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import shutil +from pathlib import Path +from typing import Dict, Optional, Tuple, List + +import cv2 +import numpy as np + +import sys + +_ROOT = Path(__file__).resolve().parents[1] +_FPOSE = _ROOT / "oneposeviagen" / "fpose" +if str(_ROOT) not in sys.path: + sys.path.insert(0, str(_ROOT)) +if _FPOSE.exists() and str(_FPOSE) not in sys.path: + sys.path.insert(0, str(_FPOSE)) + +from fpose.recover_scale import recover_scale + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Recover true scale for deform objects (same as static/rigid legacy path)." + ) + parser.add_argument("--run-dir", type=Path, required=True, help="OPG run dir (video_pipeline_*/)") + parser.add_argument("--mask-summary", type=Path, required=True, help="mask summary json (metadata/*_mask_summary.json)") + parser.add_argument("--object-name", type=str, required=True, help="deform object name (e.g., rhinoceros_01)") + parser.add_argument("--ref-mesh", type=Path, required=True, help="reference mesh path (Motion324 ref mesh)") + parser.add_argument( + "--output-dir", + type=Path, + required=True, + help="output directory for scale.json and scaled_ref_mesh.obj", + ) + parser.add_argument( + "--anchor-frame", + type=int, + default=-1, + help="optional run-frame index (default: use max aligned mask area)", + ) + parser.add_argument( + "--mask-stride", + type=int, + default=1, + help="Mask frame stride relative to run frames (e.g., 3 means run frame f uses mask ~3*f)", + ) + return parser.parse_args() + + +def _load_summary(path: Path) -> Dict[str, object]: + return json.loads(path.read_text()) + + +def _find_mask_dir(summary: Dict[str, object], obj_name: str) -> Path: + mask_root = Path(str(summary.get("mask_root", ""))) + for obj in summary.get("objects", []): + if not isinstance(obj, dict): + continue + if str(obj.get("name", "")) != obj_name: + continue + mdir_raw = str(obj.get("masks_dir", "") or "").strip() + mdir = Path(mdir_raw) if mdir_raw else Path("") + if not mdir_raw or mdir_raw == "." or not mdir.exists(): + mdir = mask_root / obj_name + if not mdir.exists(): + raise FileNotFoundError(f"Mask dir not found for {obj_name}: {mdir}") + return mdir + raise ValueError(f"Object {obj_name} not found in mask summary") + + +def _mask_area(mask_path: Path) -> int: + mask = cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE) + if mask is None: + return 0 + return int((mask > 0).sum()) + + +def _parse_frame_id(path: Path) -> Optional[int]: + stem = path.stem + if stem.startswith("frame_"): + stem = stem[len("frame_") :] + try: + return int(stem) + except Exception: + return None + + +def _build_mask_map(mask_dir: Path) -> Dict[int, Path]: + mapping: Dict[int, Path] = {} + for p in sorted(mask_dir.glob("frame_*.png")): + fid = _parse_frame_id(p) + if fid is None: + continue + mapping[int(fid)] = p + return mapping + + +def _pick_nearest_frame(target: int, frames: List[int]) -> int: + if not frames: + raise ValueError("Empty frame list") + return min(frames, key=lambda x: abs(x - target)) + + +def _pick_mask_for_run_frame( + mask_map: Dict[int, Path], + mask_ids: List[int], + run_frame: int, + mask_stride: int, +) -> Tuple[int, Path]: + target = int(run_frame * max(1, int(mask_stride))) + mask_fid = target if target in mask_map else _pick_nearest_frame(target, mask_ids) + return mask_fid, mask_map[mask_fid] + + +def _infer_num_run_frames(run_dir: Path) -> int: + npz = run_dir / "results" / "result.npz" + if npz.exists(): + with np.load(npz) as data: + if "video" in data: + return int(data["video"].shape[0]) + rgb_dir = run_dir / "rgb" + ids: List[int] = [] + for ext in (".jpg", ".png", ".jpeg"): + for p in rgb_dir.glob(f"*{ext}"): + try: + ids.append(int(p.stem)) + except Exception: + continue + if ids: + return max(ids) + 1 + raise RuntimeError(f"Cannot infer run frame count from {run_dir}") + + +def _pick_anchor_run_frame( + run_num_frames: int, + mask_map: Dict[int, Path], + mask_ids: List[int], + mask_stride: int, + override: int, +) -> int: + if override is not None and override >= 0: + return int(max(0, min(run_num_frames - 1, override))) + + best_run = None + best_area = -1 + for run_f in range(run_num_frames): + _, mp = _pick_mask_for_run_frame(mask_map, mask_ids, run_f, mask_stride) + area = _mask_area(mp) + if area > best_area: + best_area, best_run = area, run_f + if best_run is None: + raise RuntimeError("Failed to pick anchor run frame") + return int(best_run) + + +def _load_intrinsic(run_dir: Path, frame_id: int) -> np.ndarray: + intr_path = run_dir / "intrinsics.json" + if not intr_path.exists(): + raise FileNotFoundError(intr_path) + data = json.loads(intr_path.read_text()) + if isinstance(data, dict): + key = str(frame_id) + if key not in data: + key = sorted(data.keys())[0] + return np.asarray(data[key], dtype=np.float32) + if isinstance(data, list) and data: + idx = min(frame_id, len(data) - 1) + return np.asarray(data[idx], dtype=np.float32) + raise ValueError("Invalid intrinsics.json format") + + +def _pick_rgb_path(run_dir: Path, frame_id: int) -> Path: + rgb_dir = run_dir / "rgb" + for ext in (".jpg", ".png", ".jpeg"): + p = rgb_dir / f"{frame_id:06d}{ext}" + if p.exists(): + return p + raise FileNotFoundError(f"RGB frame not found: {rgb_dir}/{frame_id:06d}.[jpg|png]") + + +def _pick_depth_path(run_dir: Path, frame_id: int) -> Path: + depth_dir = run_dir / "depth" + p = depth_dir / f"{frame_id:06d}.png" + if not p.exists(): + raise FileNotFoundError(p) + return p + + +def run(args) -> None: + """可进程内调用(复用常驻 romav2/FoundationPose,避免子进程冷加载)。""" + summary = _load_summary(args.mask_summary) + mask_dir = _find_mask_dir(summary, args.object_name) + mask_map = _build_mask_map(mask_dir) + if not mask_map: + raise RuntimeError(f"No valid masks found in {mask_dir}") + mask_ids = sorted(mask_map.keys()) + mask_stride = max(1, int(args.mask_stride)) + run_num_frames = _infer_num_run_frames(args.run_dir) + anchor_run_frame = _pick_anchor_run_frame( + run_num_frames=run_num_frames, + mask_map=mask_map, + mask_ids=mask_ids, + mask_stride=mask_stride, + override=args.anchor_frame, + ) + anchor_mask_frame, anchor_mask = _pick_mask_for_run_frame( + mask_map=mask_map, + mask_ids=mask_ids, + run_frame=anchor_run_frame, + mask_stride=mask_stride, + ) + + anchor_rgb = _pick_rgb_path(args.run_dir, anchor_run_frame) + anchor_depth = _pick_depth_path(args.run_dir, anchor_run_frame) + intrinsic = _load_intrinsic(args.run_dir, anchor_run_frame) + + args.output_dir.mkdir(parents=True, exist_ok=True) + intrinsic_path = args.output_dir / "anchor_file" + intrinsic_path.mkdir(parents=True, exist_ok=True) + intrinsic_file = intrinsic_path / "intrinsic.txt" + np.savetxt(intrinsic_file, intrinsic, fmt="%.6f") + mid_dir = args.output_dir / "mid_files" + mid_dir.mkdir(parents=True, exist_ok=True) + + anchor_mask_original = anchor_mask + mask_path_use = anchor_mask + rgb_img = cv2.imread(str(anchor_rgb)) + mask_img = cv2.imread(str(anchor_mask), cv2.IMREAD_GRAYSCALE) + if rgb_img is None or mask_img is None: + raise RuntimeError("Failed to load anchor rgb or mask.") + h, w = rgb_img.shape[:2] + if mask_img.shape[0] != h or mask_img.shape[1] != w: + mask_resized = cv2.resize(mask_img, (w, h), interpolation=cv2.INTER_NEAREST) + mask_path_use = mid_dir / "anchor_mask_resized.png" + cv2.imwrite(str(mask_path_use), mask_resized) + anchor_mask_used = mask_path_use + anchor_mask_used_copy = mid_dir / "anchor_mask_used.png" + if anchor_mask_used.exists(): + shutil.copyfile(anchor_mask_used, anchor_mask_used_copy) + + scaled_mesh, _, scale = recover_scale( + str(args.ref_mesh), + str(anchor_depth), + str(anchor_rgb), + str(mask_path_use), + str(intrinsic_file), + "deform", + str(mid_dir), + ) + scaled_mesh_path = mid_dir / "scaled_mesh.obj" + scaled_mesh.export(scaled_mesh_path) + scaled_ref = args.output_dir / "scaled_ref_mesh.obj" + if scaled_mesh_path.exists() and scaled_mesh_path != scaled_ref: + scaled_ref.write_bytes(scaled_mesh_path.read_bytes()) + + pnp_npz = mid_dir / "anchor_pose_pnp.npz" + if pnp_npz.exists(): + try: + import trimesh as _tm + data = np.load(str(pnp_npz), allow_pickle=True) + M = np.asarray(data["M"], dtype=np.float64) + s_pnp = float(data["scale"]) + mesh_state = str(data["mesh_state"]) + R_pnp = M[:3, :3] / s_pnp + t_pnp = M[:3, 3] / s_pnp + + def _verts(p): + m = _tm.load(str(p), force="mesh", process=False, maintain_order=True) + return np.asarray(m.vertices, dtype=np.float64) + + if mesh_state == "rotated": + X = _verts(scaled_ref) + src = mid_dir / "rotated_model.obj" + Y = _verts(src) if src.exists() else X + ok = len(X) == len(Y) + if ok: + Xc, Yc = X - X.mean(0), Y - Y.mean(0) + U, S, Vt = np.linalg.svd(Yc.T @ Xc) + D = np.eye(3) + D[2, 2] = np.sign(np.linalg.det(U @ Vt)) + R_cum = U @ D @ Vt + s_rel = float(np.trace(np.diag(S) @ D) / (Xc ** 2).sum()) + else: + R_cum = np.eye(3) + s_rel = 1.0 / max(s_pnp, 1e-9) + ok = True + if ok: + T_init = np.eye(4) + T_init[:3, :3] = R_pnp @ R_cum + T_init[:3, 3] = t_pnp / max(s_rel, 1e-6) + out_pose = { + "anchor_run_frame": int(anchor_run_frame), + "pose_cam": T_init.tolist(), + "K_render": np.asarray(data["K"], dtype=np.float64).tolist(), + "mesh_state": mesh_state, + "s_rel": s_rel, + "note": "PnP anchor pose in canonical scaled_ref coords; K is renderer-approx, use for init only", + } + (args.output_dir / "pnp_anchor_pose.json").write_text(json.dumps(out_pose, indent=2)) + print(f"[recover-scale] saved PnP anchor init pose (state={mesh_state}, s_rel={s_rel:.3f})") + else: + print("[recover-scale] skip PnP anchor pose: vertex count mismatch") + except Exception as ex: # noqa: BLE001 + print(f"[recover-scale] skip PnP anchor pose: {ex}") + + out = { + "object": args.object_name, + "scale": float(scale), + "anchor_frame": int(anchor_run_frame), + "anchor_run_frame": int(anchor_run_frame), + "anchor_mask_frame": int(anchor_mask_frame), + "mask_stride": int(mask_stride), + "anchor_rgb": str(anchor_rgb), + "anchor_depth": str(anchor_depth), + "anchor_mask": str(anchor_mask_used), + "anchor_mask_original": str(anchor_mask_original), + "anchor_mask_used": str(anchor_mask_used), + "anchor_mask_used_copy": str(anchor_mask_used_copy), + "anchor_rgb_shape": [int(h), int(w)], + "anchor_mask_original_shape": [int(mask_img.shape[0]), int(mask_img.shape[1])], + "anchor_mask_used_shape": [int(h), int(w)], + "scaled_mesh": str(scaled_ref if scaled_ref.exists() else scaled_mesh_path), + "ref_mesh": str(args.ref_mesh), + } + (args.output_dir / "scale.json").write_text(json.dumps(out, indent=2)) + print(str(args.output_dir / "scale.json")) + + +def main() -> None: + run(parse_args()) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/register_deform_foundationpose.py b/OVOW/engine/tools/register_deform_foundationpose.py new file mode 100644 index 0000000000000000000000000000000000000000..e2c536dbbcdd1b5cb4d7d93416111193c37d74a6 --- /dev/null +++ b/OVOW/engine/tools/register_deform_foundationpose.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +import cv2 +import numpy as np +import trimesh + +from fpose.estimater import FoundationPose + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Register Motion324 deform objects back to scene using FoundationPose.") + parser.add_argument("--run-dir", type=Path, required=True, help="OPG run dir (video_pipeline_*/)") + parser.add_argument("--manifest", type=Path, required=True, help="motion324 outputs manifest.json") + parser.add_argument("--mask-summary", type=Path, required=True, help="mask summary json (metadata/*_mask_summary.json)") + parser.add_argument("--output-root", type=Path, required=True, help="motion324 output root/") + parser.add_argument("--min-mask-pix", type=int, default=50, help="min mask pixels to run pose") + parser.add_argument("--iter", type=int, default=5, help="FoundationPose refinement iterations") + parser.add_argument( + "--debug-dir", + type=Path, + default=Path("/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs/fpose_debug"), + help="debug output directory for FoundationPose", + ) + return parser.parse_args() + + +def _load_summary(path: Path) -> Dict[str, object]: + return json.loads(path.read_text()) + + +def _load_manifest(path: Path) -> Dict[str, object]: + return json.loads(path.read_text()) + + +def _mask_path(mask_dir: Path, frame_id: int) -> Path: + return mask_dir / f"frame_{frame_id:06d}.png" + + +def _load_mask(mask_dir: Path, frame_id: int, shape: Tuple[int, int]) -> np.ndarray: + mask_path = _mask_path(mask_dir, frame_id) + if not mask_path.exists(): + return np.zeros(shape, dtype=np.uint8) + mask = cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE) + if mask is None: + return np.zeros(shape, dtype=np.uint8) + if mask.shape[0] != shape[0] or mask.shape[1] != shape[1]: + mask = cv2.resize(mask, (shape[1], shape[0]), interpolation=cv2.INTER_NEAREST) + return mask + + +def _to_bgr(frame: np.ndarray) -> np.ndarray: + if frame.ndim == 3 and frame.shape[0] == 3: + frame = np.transpose(frame, (1, 2, 0)) + if frame.max() <= 1.5: + frame = (frame * 255.0).clip(0, 255) + return frame.astype(np.uint8) + + +def _fill_missing(poses: Dict[int, np.ndarray], num_frames: int) -> Dict[int, np.ndarray]: + if not poses: + return {i: np.eye(4, dtype=np.float32) for i in range(num_frames)} + frame_ids = sorted(poses.keys()) + filled: Dict[int, np.ndarray] = {} + for i in range(num_frames): + if i in poses: + filled[i] = poses[i] + else: + nearest = min(frame_ids, key=lambda x: abs(x - i)) + filled[i] = poses[nearest] + return filled + + +def main() -> None: + args = parse_args() + + run_dir = args.run_dir + result_npz = run_dir / "results" / "result.npz" + if not result_npz.exists(): + raise FileNotFoundError(result_npz) + data = np.load(result_npz) + video = data["video"] + depths = data["depths"] + intrinsics = data["intrinsics"] + extrinsics = data["extrinsics"] + num_frames = video.shape[0] + + summary = _load_summary(args.mask_summary) + objects_summary = summary.get("objects", []) + mask_root = Path(str(summary.get("mask_root", ""))) + + deform_masks: Dict[str, Path] = {} + for obj in objects_summary: + if not isinstance(obj, dict): + continue + if str(obj.get("category", "")).lower() != "deform": + continue + name = str(obj.get("name", "")) + mdir = Path(str(obj.get("masks_dir", ""))) + if not mdir.exists(): + mdir = mask_root / name + deform_masks[name] = mdir + + manifest = _load_manifest(args.manifest) + objects = manifest.get("objects", []) + if not isinstance(objects, list): + objects = [] + + for obj in objects: + name = str(obj.get("name", "")) + if name not in deform_masks: + continue + mask_dir = deform_masks[name] + + ref_mesh_path = obj.get("ref_mesh") + scaled_ref = args.output_root / name / "scaled_ref_mesh.obj" + scale_json = args.output_root / name / "scale.json" + if scale_json.exists(): + try: + payload = json.loads(scale_json.read_text()) + candidate = Path(str(payload.get("scaled_mesh", ""))) + if candidate.exists(): + scaled_ref = candidate + except Exception: + pass + if scaled_ref.exists(): + ref_mesh_path = str(scaled_ref) + if not ref_mesh_path: + print(f"[Skip] {name}: ref_mesh not found") + continue + ref_mesh = trimesh.load(ref_mesh_path, force="mesh") + if not isinstance(ref_mesh, trimesh.Trimesh): + print(f"[Skip] {name}: invalid mesh") + continue + + est = FoundationPose( + model_pts=ref_mesh.vertices, + model_normals=ref_mesh.vertex_normals, + mesh=ref_mesh, + debug=0, + debug_dir=str(args.debug_dir / name), + export_mesh_path=False, + ) + + H, W = depths.shape[1], depths.shape[2] + areas = [] + for f in range(num_frames): + mask = _load_mask(mask_dir, f, (H, W)) + areas.append(int((mask > 0).sum())) + ref_frame = int(np.argmax(np.array(areas))) if areas else 0 + + poses_cam: Dict[int, np.ndarray] = {} + + for f in range(num_frames): + mask = _load_mask(mask_dir, f, (H, W)) + if int((mask > 0).sum()) < args.min_mask_pix: + continue + rgb = _to_bgr(video[f]) + depth = depths[f].astype(np.float32) + K = intrinsics[f].astype(np.float32) + pose_cam = est.register(K=K, rgb=rgb, depth=depth, ob_mask=(mask > 0), iteration=args.iter) + poses_cam[f] = pose_cam.astype(np.float32) + + poses_cam = _fill_missing(poses_cam, num_frames) + + poses_world: Dict[int, np.ndarray] = {} + for f, pose_cam in poses_cam.items(): + w_T_o = np.linalg.inv(extrinsics[f]) @ pose_cam + poses_world[f] = w_T_o.astype(np.float32) + + out_dir = args.output_root / name + out_dir.mkdir(parents=True, exist_ok=True) + + cam_path = out_dir / "poses_fp_cam.json" + world_path = out_dir / "poses_fp_world.json" + + cam_path.write_text(json.dumps({str(k): v.tolist() for k, v in poses_cam.items()}, indent=2)) + world_path.write_text(json.dumps({str(k): v.tolist() for k, v in poses_world.items()}, indent=2)) + + print(f"[OK] {name}: {world_path}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/render_deform_scale_video.py b/OVOW/engine/tools/render_deform_scale_video.py new file mode 100644 index 0000000000000000000000000000000000000000..7fc0314b3be2e5f7e595f2265cf9b6a8c7881a88 --- /dev/null +++ b/OVOW/engine/tools/render_deform_scale_video.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Dict, List, Tuple + +import numpy as np + +from oneposeviagen.scripts.render_normals import render_high_model_to_normal_video + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Render deform scale-check overlay video (normals on RGB).") + parser.add_argument("--run-dir", type=Path, required=True, help="OPG run dir (video_pipeline_*/)") + parser.add_argument("--object-name", type=str, required=True, help="deform object name") + parser.add_argument( + "--motion-output-root", + type=Path, + required=True, + help="motion324 output root/", + ) + parser.add_argument("--poses-cam", type=Path, default=None, help="poses_fp_cam.json (camera-space)") + parser.add_argument("--mesh", type=Path, default=None, help="scaled_ref_mesh.obj (fallback to scale.json)") + parser.add_argument("--output", type=Path, default=None, help="output mp4") + parser.add_argument("--fps", type=float, default=10.0, help="fps override") + return parser.parse_args() + + +def _load_intrinsics(path: Path, num_frames: int) -> List[np.ndarray]: + data = json.loads(path.read_text()) + intr_list: List[np.ndarray] = [] + if isinstance(data, dict): + keys = sorted(data.keys(), key=lambda x: int(x) if str(x).isdigit() else x) + for i in range(num_frames): + key = str(i) + if key not in data: + key = keys[0] + intr_list.append(np.asarray(data[key], dtype=np.float32)) + elif isinstance(data, list): + for i in range(num_frames): + idx = min(i, len(data) - 1) + intr_list.append(np.asarray(data[idx], dtype=np.float32)) + else: + raise ValueError("Invalid intrinsics.json format") + return intr_list + + +def _load_poses(path: Path, num_frames: int) -> List[np.ndarray]: + data = json.loads(path.read_text()) + poses: Dict[int, np.ndarray] = {} + for k, v in data.items(): + try: + idx = int(k) + except Exception: + continue + poses[idx] = np.asarray(v, dtype=np.float32) + if not poses: + raise RuntimeError(f"No poses found in {path}") + frame_ids = sorted(poses.keys()) + filled: List[np.ndarray] = [] + for i in range(num_frames): + if i in poses: + filled.append(poses[i]) + else: + nearest = min(frame_ids, key=lambda x: abs(x - i)) + filled.append(poses[nearest]) + return filled + + +def _rgb_paths(run_dir: Path) -> List[Path]: + rgb_dir = run_dir / "rgb" + if not rgb_dir.exists(): + raise FileNotFoundError(rgb_dir) + exts = ("*.jpg", "*.png", "*.jpeg") + paths = [] + for ext in exts: + paths.extend(rgb_dir.glob(ext)) + def _key(p: Path) -> int: + try: + return int(p.stem) + except Exception: + return 0 + return sorted(paths, key=_key) + + +def _pick_mesh(obj_root: Path) -> Path: + scaled_ref = obj_root / "scaled_ref_mesh.obj" + if scaled_ref.exists(): + return scaled_ref + scale_json = obj_root / "scale.json" + if scale_json.exists(): + try: + data = json.loads(scale_json.read_text()) + candidate = Path(str(data.get("scaled_mesh", ""))) + if candidate.exists(): + return candidate + except Exception: + pass + raise FileNotFoundError("scaled_ref_mesh.obj not found") + + +def main() -> None: + args = parse_args() + run_dir = args.run_dir + name = run_dir.name + obj_root = args.motion_output_root / name / args.object_name + obj_root.mkdir(parents=True, exist_ok=True) + + poses_cam = args.poses_cam or (obj_root / "poses_fp_cam.json") + if not poses_cam.exists(): + raise FileNotFoundError(poses_cam) + + mesh_path = args.mesh or _pick_mesh(obj_root) + if not mesh_path.exists(): + raise FileNotFoundError(mesh_path) + + rgb_paths = _rgb_paths(run_dir) + num_frames = len(rgb_paths) + + intr_path = run_dir / "intrinsics.json" + if not intr_path.exists(): + raise FileNotFoundError(intr_path) + intr_list = _load_intrinsics(intr_path, num_frames) + poses = _load_poses(poses_cam, num_frames) + + out_path = args.output or (obj_root / "pose_result" / "normal_video_converted.mp4") + out_path.parent.mkdir(parents=True, exist_ok=True) + + render_high_model_to_normal_video( + poses, + [str(p) for p in rgb_paths], + intr_list, + str(mesh_path), + str(out_path), + fps=args.fps, + device="cuda", + ) + print(f"[OK] Wrote: {out_path}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/rerun_step6_objects.py b/OVOW/engine/tools/rerun_step6_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..218bb15f99608562c78ad7eac88fbd6f9b58c2b2 --- /dev/null +++ b/OVOW/engine/tools/rerun_step6_objects.py @@ -0,0 +1,443 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import shutil +import sys +import traceback +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from typing import Dict, List, Optional, Sequence, Set + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +import batch_scene_pipeline as bsp + + +@dataclass +class ObjSpec: + name: str + masks_dir: Path + category: str + is_occluded: bool + seed: Optional[int] + ref_image: Optional[Path] = None + + +def _resolve_path(base: Path, raw: object) -> Path: + p = Path(str(raw)) + return p if p.is_absolute() else (base / p).resolve() + + +def _parse_mask_frame_id(path: Path) -> Optional[int]: + stem = path.stem + if stem.startswith("frame_"): + stem = stem[len("frame_") :] + try: + return int(stem) + except Exception: + return None + + +def _pick_nearest_frame(target: int, frames: Sequence[int]) -> int: + import bisect + + pos = bisect.bisect_left(frames, target) + cand: List[int] = [] + if pos < len(frames): + cand.append(frames[pos]) + if pos > 0: + cand.append(frames[pos - 1]) + return min(cand, key=lambda x: abs(x - target)) + + +def _build_object_mask_sequence(masks_dir: Path, mask_glob: str, num_frames: int, sample_stride: int) -> List[Path]: + files = sorted(masks_dir.glob(mask_glob)) + mapping: Dict[int, Path] = {} + for p in files: + fid = _parse_mask_frame_id(p) + if fid is None: + continue + mapping[int(fid)] = p + if not mapping: + raise FileNotFoundError(f"No masks found in {masks_dir} (glob={mask_glob})") + frame_ids = sorted(mapping.keys()) + seq: List[Path] = [] + for i in range(num_frames): + target = int(i * sample_stride) + nearest = _pick_nearest_frame(target, frame_ids) + seq.append(mapping[nearest].resolve()) + return seq + + +def _load_config(config_path: Path) -> tuple[Path, str, List[ObjSpec], dict]: + payload = json.loads(config_path.read_text(encoding="utf-8")) + base = config_path.parent.resolve() + batch_cfg = _resolve_path(base, payload["batch_config"]) + mask_glob = str(payload.get("mask_glob", "frame_*.png")) + raw_objects = payload.get("objects", []) + specs: List[ObjSpec] = [] + for entry in raw_objects: + name = entry.get("name") or entry.get("id") + masks_dir = entry.get("masks_dir") or entry.get("masks") + if not name or not masks_dir: + continue + specs.append( + ObjSpec( + name=str(name), + masks_dir=_resolve_path(base, masks_dir), + category=str(entry.get("category", "static")).lower(), + is_occluded=bool(entry.get("is_occluded", False)), + seed=entry.get("seed"), + ref_image=None, + ) + ) + return batch_cfg, mask_glob, specs, payload + + +def _load_ref_map(ref_map_path: Path) -> Dict[str, Path]: + payload = json.loads(ref_map_path.read_text(encoding="utf-8")) + if not isinstance(payload, dict): + raise ValueError(f"--ref-map must be a JSON object: {ref_map_path}") + base = ref_map_path.parent.resolve() + out: Dict[str, Path] = {} + for raw_name, raw_cfg in payload.items(): + name = str(raw_name).strip() + if not name: + continue + if not isinstance(raw_cfg, dict): + raise ValueError(f"--ref-map entry for '{name}' must be an object") + ref_image_raw = str(raw_cfg.get("ref_image", "")).strip() + if not ref_image_raw: + raise ValueError(f"--ref-map entry for '{name}' is missing 'ref_image'") + ref_image = _resolve_path(base, ref_image_raw) + if not ref_image.exists(): + raise FileNotFoundError(f"ref_image not found for '{name}': {ref_image}") + out[name] = ref_image.resolve() + return out + + +def _pick_mesh_path(obj_dir: Path) -> Optional[Path]: + candidates: List[Path] = [] + candidates.append(obj_dir / "mid_files" / "scaled_mesh.obj") + candidates.extend(sorted((obj_dir / "model" / "middle_file").glob("*_high_mesh.obj"))) + candidates.append(obj_dir / "model" / "model.obj") + for c in candidates: + if c.exists(): + return c + return None + + +def _pick_pose_json(obj_dir: Path) -> Optional[Path]: + pose_dir = obj_dir / "pose_result" + for c in [pose_dir / "poses.json", pose_dir / "poses_locked.json"]: + if c.exists(): + return c + return None + + +def _pick_pose_video(obj_dir: Path, fallback: Path) -> Path: + pose_dir = obj_dir / "pose_result" + for c in [pose_dir / "normal_video_converted.mp4", pose_dir / "normal_video.mp4"]: + if c.exists(): + return c + return fallback + + +def _collect_object_results(run_dir: Path, specs: List[ObjSpec]) -> List[bsp.ObjectResult]: + results: List[bsp.ObjectResult] = [] + for spec in specs: + if spec.category not in {"static", "rigid"}: + continue + obj_dir = run_dir / "objects" / spec.name + if not obj_dir.exists(): + continue + pose_json = _pick_pose_json(obj_dir) + mesh_path = _pick_mesh_path(obj_dir) + if pose_json is None or mesh_path is None: + continue + scaled_mesh = obj_dir / "mid_files" / "scaled_mesh.obj" + if not scaled_mesh.exists(): + scaled_mesh = mesh_path + pose_video = _pick_pose_video(obj_dir, pose_json) + results.append( + bsp.ObjectResult( + name=spec.name, + object_dir=obj_dir.resolve(), + scaled_mesh=scaled_mesh.resolve(), + high_mesh=mesh_path.resolve(), + pose_json=pose_json.resolve(), + pose_video=pose_video.resolve(), + ) + ) + return results + + +def _load_failed_names(report_path: Path) -> Set[str]: + if not report_path.exists(): + return set() + try: + payload = json.loads(report_path.read_text(encoding="utf-8")) + except Exception: + return set() + names = payload.get("failed_names", []) + out = {str(x) for x in names if str(x)} + if out: + return out + for item in payload.get("failed_objects", []): + name = str(item.get("name", "")).strip() + if name: + out.add(name) + return out + + +def _update_error_report( + report_path: Path, + run_dir: Path, + success_names: Set[str], + failed_entries: List[dict], +) -> None: + payload: Dict[str, object] + if report_path.exists(): + try: + payload = json.loads(report_path.read_text(encoding="utf-8")) + except Exception: + payload = {} + else: + payload = {} + + existing = payload.get("failed_objects", []) + if not isinstance(existing, list): + existing = [] + kept = [] + for item in existing: + name = str(item.get("name", "")).strip() + if name and name not in success_names: + kept.append(item) + merged = {str(item.get("name", "")).strip(): item for item in kept if str(item.get("name", "")).strip()} + for item in failed_entries: + merged[str(item["name"])] = item + + failed_objects = list(merged.values()) + failed_names = sorted({str(item["name"]) for item in failed_objects}) + payload.update( + { + "run_dir": str(run_dir), + "generated_at": datetime.utcnow().isoformat() + "Z", + "failed_objects": failed_objects, + "failed_names": failed_names, + } + ) + report_path.parent.mkdir(parents=True, exist_ok=True) + report_path.write_text(json.dumps(payload, indent=2), encoding="utf-8") + + +def _update_effective_config(config_payload: dict, output_path: Path, failed_names: Set[str]) -> None: + objects = config_payload.get("objects", []) + if not isinstance(objects, list): + objects = [] + filtered = [] + dropped = [] + for obj in objects: + name = str(obj.get("name") or obj.get("id") or "").strip() + if name and name in failed_names: + dropped.append(name) + continue + filtered.append(obj) + config_payload = dict(config_payload) + config_payload["objects"] = filtered + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(json.dumps(config_payload, indent=2, ensure_ascii=False), encoding="utf-8") + if dropped: + print(f"[rerun] effective config dropped failed objects: {', '.join(sorted(set(dropped)))}") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Rerun failed Step-6 objects and refresh scene point clouds.") + parser.add_argument("--run-dir", type=Path, required=True, help="Existing run dir, e.g. .../video_pipeline_xxx/v15") + parser.add_argument("--config", type=Path, required=True, help="Pipeline config JSON (full config)") + parser.add_argument( + "--error-report", + type=Path, + default=None, + help="object error report JSON (default: /object_errors_step6.json)", + ) + parser.add_argument( + "--objects", + type=str, + default="", + help="Comma-separated object names to rerun (overrides --only-failed)", + ) + parser.add_argument( + "--only-failed", + type=int, + choices=[0, 1], + default=1, + help="When --objects is empty, rerun only failed objects from report (default: 1)", + ) + parser.add_argument( + "--output-effective-config", + type=Path, + default=None, + help="Optional output path for updated effective pipeline config", + ) + parser.add_argument( + "--anchor-frame", + type=int, + default=-1, + help="Override scale anchor frame for rerun object generation (-1 keeps batch config).", + ) + parser.add_argument( + "--ref-map", + type=Path, + default=None, + help="Optional JSON map: object_name -> {'ref_image': '/path/to/image'} for external mesh generation input.", + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + run_dir = args.run_dir.resolve() + config_path = args.config.resolve() + report_path = args.error_report.resolve() if args.error_report else (run_dir / "object_errors_step6.json") + if not run_dir.exists(): + raise FileNotFoundError(run_dir) + if not config_path.exists(): + raise FileNotFoundError(config_path) + if int(args.anchor_frame) < -1: + raise ValueError(f"--anchor-frame must be >= -1, got {args.anchor_frame}") + ref_map_path = args.ref_map.resolve() if args.ref_map else None + if ref_map_path is not None and not ref_map_path.exists(): + raise FileNotFoundError(ref_map_path) + + batch_cfg_path, mask_glob, specs, config_payload = _load_config(config_path) + ref_image_map: Dict[str, Path] = _load_ref_map(ref_map_path) if ref_map_path is not None else {} + base_cfg = bsp.load_batch_config(batch_cfg_path) + if int(args.anchor_frame) >= 0: + base_cfg.scale.anchor_frame = int(args.anchor_frame) + print(f"[rerun] anchor frame override: {base_cfg.scale.anchor_frame}") + rgb_paths, depth_paths, intrinsics = bsp.load_session_sequences(run_dir) + num_frames = len(rgb_paths) + sample_stride = max(1, int(base_cfg.tracker.sample_stride)) + + object_map = {spec.name: spec for spec in specs} + for name, ref_image in ref_image_map.items(): + spec = object_map.get(name) + if spec is None: + print(f"[rerun] Warning: ref-map object not found in config, skip: {name}") + continue + spec.ref_image = ref_image + + explicit = {x.strip() for x in args.objects.split(",") if x.strip()} + if explicit: + target_names = sorted(name for name in explicit if name in object_map) + elif args.only_failed == 1: + failed_names = _load_failed_names(report_path) + target_names = sorted(name for name in failed_names if name in object_map) + else: + target_names = sorted(object_map.keys()) + + if not target_names: + print("[rerun] No objects selected. Nothing to do.") + return + + success_names: Set[str] = set() + failed_entries: List[dict] = [] + generation_sources: Dict[str, dict] = {} + for name in target_names: + spec = object_map[name] + if spec.category not in {"static", "rigid"}: + print(f"[rerun] Skip {name}: category={spec.category}") + continue + source = "external_image" if spec.ref_image is not None else "anchor_frame" + source_ref = str(spec.ref_image) if spec.ref_image is not None else None + generation_sources[name] = { + "source": source, + "generation_image_path": source_ref, + } + print(f"[rerun] Reprocessing {name} (source={source})") + obj_dir = run_dir / "objects" / name + archived_dir = run_dir / "objects_failed" / name + if obj_dir.exists(): + shutil.rmtree(obj_dir, ignore_errors=True) + if archived_dir.exists(): + shutil.rmtree(archived_dir, ignore_errors=True) + try: + masks = _build_object_mask_sequence(spec.masks_dir, mask_glob, num_frames, sample_stride) + scene_obj = bsp.SceneObject( + name=spec.name, + mask_path=masks[0], + is_occluded=spec.is_occluded, + seed=spec.seed, + ) + bsp.process_object( + scene_obj, + masks, + run_dir, + run_dir, + rgb_paths, + depth_paths, + intrinsics, + base_cfg.generation, + base_cfg.scale, + generation_image_path=spec.ref_image, + ) + success_names.add(name) + print(f"[rerun] OK {name}") + except Exception as exc: # noqa: BLE001 + err_msg = str(exc) + failed_entries.append( + { + "name": name, + "category": spec.category, + "stage": "rerun_process_object", + "error": err_msg, + "traceback": traceback.format_exc(), + "time": datetime.utcnow().isoformat() + "Z", + "generation_source": source, + "generation_image_path": source_ref, + } + ) + print(f"[rerun] FAIL {name}: {err_msg}") + + point_cloud = bsp.export_scene_point_cloud(run_dir, base_cfg.generation) + object_results = _collect_object_results(run_dir, specs) + combined_cloud = bsp.export_scene_objects_combined(run_dir, point_cloud, object_results, base_cfg.generation) + + _update_error_report(report_path, run_dir, success_names, failed_entries) + latest_failed_names = _load_failed_names(report_path) + if args.output_effective_config is not None: + _update_effective_config(config_payload, args.output_effective_config.resolve(), latest_failed_names) + + rerun_summary = { + "run_dir": str(run_dir), + "generated_at": datetime.utcnow().isoformat() + "Z", + "anchor_frame": int(base_cfg.scale.anchor_frame), + "anchor_frame_override": int(args.anchor_frame) if int(args.anchor_frame) >= 0 else None, + "selected": target_names, + "succeeded": sorted(success_names), + "failed": [entry["name"] for entry in failed_entries], + "scene_point_cloud": str(point_cloud) if point_cloud else None, + "combined_cloud": str(combined_cloud) if combined_cloud else None, + "error_report": str(report_path), + "ref_map": str(ref_map_path) if ref_map_path is not None else None, + "generation_inputs": generation_sources, + } + summary_path = run_dir / "step6_rerun_summary.json" + summary_path.write_text(json.dumps(rerun_summary, indent=2), encoding="utf-8") + print(f"[rerun] Scene point cloud: {point_cloud}") + print(f"[rerun] Combined cloud: {combined_cloud}") + print(f"[rerun] Error report: {report_path}") + print(f"[rerun] Summary: {summary_path}") + + if failed_entries: + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/reuse_mesh_for_duplicates.py b/OVOW/engine/tools/reuse_mesh_for_duplicates.py new file mode 100644 index 0000000000000000000000000000000000000000..b908dbb2395984215f38ca40dc9c1273d5507da3 --- /dev/null +++ b/OVOW/engine/tools/reuse_mesh_for_duplicates.py @@ -0,0 +1,509 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import shutil +import subprocess +import sys +import traceback +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from typing import Dict, List, Optional, Sequence + +import cv2 +import numpy as np + + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +bsp = None + + +def _get_bsp(): + global bsp + if bsp is None: + import batch_scene_pipeline as bsp_mod + + bsp = bsp_mod + return bsp + + +@dataclass +class ObjSpec: + name: str + masks_dir: Path + category: str + is_occluded: bool + seed: Optional[int] + + +def _resolve_path(base: Path, raw: object) -> Path: + p = Path(str(raw)) + return p if p.is_absolute() else (base / p).resolve() + + +def _parse_mask_frame_id(path: Path) -> Optional[int]: + stem = path.stem + if stem.startswith("frame_"): + stem = stem[len("frame_") :] + try: + return int(stem) + except Exception: + return None + + +def _pick_nearest_frame(target: int, frames: Sequence[int]) -> int: + import bisect + + pos = bisect.bisect_left(frames, target) + cand: List[int] = [] + if pos < len(frames): + cand.append(frames[pos]) + if pos > 0: + cand.append(frames[pos - 1]) + return min(cand, key=lambda x: abs(x - target)) + + +def _build_object_mask_sequence( + masks_dir: Path, + mask_glob: str, + num_frames: int, + sample_stride: int, +) -> List[Path]: + files = sorted(masks_dir.glob(mask_glob)) + mapping: Dict[int, Path] = {} + for p in files: + fid = _parse_mask_frame_id(p) + if fid is None: + continue + mapping[int(fid)] = p + if not mapping: + raise FileNotFoundError(f"No masks found in {masks_dir} (glob={mask_glob})") + frame_ids = sorted(mapping.keys()) + seq: List[Path] = [] + for i in range(num_frames): + target = int(i * sample_stride) + nearest = _pick_nearest_frame(target, frame_ids) + seq.append(mapping[nearest].resolve()) + return seq + + +def _load_config(config_path: Path) -> tuple[Path, str, Dict[str, ObjSpec], dict]: + payload = json.loads(config_path.read_text(encoding="utf-8")) + base = config_path.parent.resolve() + batch_cfg = _resolve_path(base, payload["batch_config"]) + mask_glob = str(payload.get("mask_glob", "frame_*.png")) + raw_objects = payload.get("objects", []) + specs: Dict[str, ObjSpec] = {} + for entry in raw_objects: + name = entry.get("name") or entry.get("id") + masks_dir = entry.get("masks_dir") or entry.get("masks") + if not name or not masks_dir: + continue + spec = ObjSpec( + name=str(name), + masks_dir=_resolve_path(base, masks_dir), + category=str(entry.get("category", "static")).lower(), + is_occluded=bool(entry.get("is_occluded", False)), + seed=entry.get("seed"), + ) + specs[spec.name] = spec + return batch_cfg, mask_glob, specs, payload + + +def _infer_group_prefix(source_name: str) -> str: + if "_" in source_name: + prefix, suffix = source_name.rsplit("_", 1) + if suffix.isdigit(): + return prefix + "_" + return source_name + + +def _pick_scaled_mesh(obj_dir: Path) -> Optional[Path]: + candidates = [ + obj_dir / "mid_files" / "scaled_mesh.obj", + obj_dir / "model" / "model.obj", + ] + candidates.extend(sorted((obj_dir / "model" / "middle_file").glob("*_high_mesh.obj"))) + for p in candidates: + if p.exists(): + return p.resolve() + return None + + +def _pick_high_mesh(obj_dir: Path, scaled_mesh: Path) -> Path: + candidates = list(sorted((obj_dir / "model" / "middle_file").glob("*_high_mesh.obj"))) + candidates.append(obj_dir / "model" / "model.obj") + for p in candidates: + if p.exists(): + return p.resolve() + return scaled_mesh.resolve() + + +def _pick_pose_json(obj_dir: Path) -> Optional[Path]: + pose_dir = obj_dir / "pose_result" + for p in [pose_dir / "poses.json", pose_dir / "poses_locked.json"]: + if p.exists(): + return p.resolve() + return None + + +def _has_source_ready(obj_dir: Path) -> bool: + scaled = _pick_scaled_mesh(obj_dir) + if scaled is None: + return False + pose = _pick_pose_json(obj_dir) + return pose is not None + + +def _run_rerun_source(run_dir: Path, config_path: Path, source_object: str) -> None: + cmd = [ + sys.executable, + str(REPO_ROOT / "tools" / "rerun_step6_objects.py"), + "--run-dir", + str(run_dir), + "--config", + str(config_path), + "--objects", + source_object, + "--only-failed", + "0", + ] + print("[reuse-mesh] Source not ready, run:", " ".join(cmd)) + subprocess.run(cmd, check=True) + + +def _copy_if_exists(src: Path, dst: Path) -> None: + if not src.exists(): + return + if src.is_dir(): + shutil.copytree(src, dst, dirs_exist_ok=True) + else: + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, dst) + + +def _prepare_target_dir(source_dir: Path, target_dir: Path, overwrite: bool) -> None: + if target_dir.exists(): + if not overwrite: + raise FileExistsError(f"Target object dir exists: {target_dir}") + shutil.rmtree(target_dir) + target_dir.mkdir(parents=True, exist_ok=True) + + _copy_if_exists(source_dir / "model", target_dir / "model") + _copy_if_exists(source_dir / "mid_files", target_dir / "mid_files") + _copy_if_exists(source_dir / "anchor_file", target_dir / "anchor_file") + _copy_if_exists(source_dir / "final_mask.png", target_dir / "final_mask.png") + + (target_dir / "masks").mkdir(parents=True, exist_ok=True) + (target_dir / "pose_result").mkdir(parents=True, exist_ok=True) + (target_dir / "pose_debug").mkdir(parents=True, exist_ok=True) + + +def _write_target_masks( + mask_sequence: Sequence[Path], + rgb_paths: Sequence[Path], + out_dir: Path, +) -> List[Path]: + ref = cv2.imread(str(rgb_paths[0])) + if ref is None: + raise FileNotFoundError(f"Missing RGB frame: {rgb_paths[0]}") + h, w = ref.shape[:2] + out_dir.mkdir(parents=True, exist_ok=True) + + out_paths: List[Path] = [] + for idx, src in enumerate(mask_sequence): + mask = cv2.imread(str(src), cv2.IMREAD_GRAYSCALE) + if mask is None: + raise FileNotFoundError(f"Missing mask frame: {src}") + if mask.shape != (h, w): + mask = cv2.resize(mask, (w, h), interpolation=cv2.INTER_NEAREST) + binary = np.zeros((h, w), dtype=np.uint8) + binary[mask > 0] = 255 + out_path = out_dir / f"{idx:06d}.png" + cv2.imwrite(str(out_path), binary) + out_paths.append(out_path) + return out_paths + + +def _run_pose_only( + target_dir: Path, + scaled_mesh: Path, + high_mesh: Path, + mask_paths: Sequence[Path], + rgb_paths: Sequence[Path], + depth_paths: Sequence[Path], + intrinsics: Sequence[List[float]], + run_dir: Path, + mask_inputs: bool, + render_video: bool, +) -> None: + bsp_mod = _get_bsp() + pose_dir = target_dir / "pose_result" + debug_dir = target_dir / "pose_debug" + pose_dir.mkdir(parents=True, exist_ok=True) + debug_dir.mkdir(parents=True, exist_ok=True) + + npz_path = run_dir / "results" / "result.npz" + if not npz_path.exists(): + raise FileNotFoundError(f"Missing session result: {npz_path}") + + intr_list = [intrinsics[i] for i in range(len(rgb_paths))] + mask_list = [str(mask_paths[i]) for i in range(len(mask_paths))] + poses = bsp_mod.estimate_poses( + str(npz_path), + [str(p) for p in rgb_paths], + [str(p) for p in depth_paths], + mask_list, + intr_list, + str(scaled_mesh), + str(debug_dir), + debug=0, + est_refine_iter=5, + mask_inputs=bool(mask_inputs), + ) + + pose_json = pose_dir / "poses.json" + pose_json.write_text( + json.dumps({str(i): poses[i].tolist() for i in range(len(poses))}, indent=2), + encoding="utf-8", + ) + + if not render_video: + return + + normal_video_path = pose_dir / "normal_video.mp4" + bsp_mod.render_high_model_to_normal_video( + poses, + [str(p) for p in rgb_paths], + intr_list, + str(high_mesh), + str(normal_video_path), + fps=bsp_mod.VIDEO_FPS, + device="cuda", + ) + converted = pose_dir / "normal_video_converted.mp4" + bsp_mod.convert_video_to_mp4(str(normal_video_path), str(converted)) + normal_video_path.unlink(missing_ok=True) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Reuse one source object's mesh for repeated duplicate objects (e.g. chair_06 -> all chair_*)." + ) + parser.add_argument("--run-dir", type=Path, required=True, help="Existing step-6 run dir.") + parser.add_argument("--config", type=Path, required=True, help="Pipeline config JSON used by step-6.") + parser.add_argument("--source-object", type=str, required=True, help="Source object name, e.g. chair_06.") + parser.add_argument( + "--targets", + type=str, + default="", + help="Comma-separated target object names; empty means auto-select by prefix.", + ) + parser.add_argument( + "--target-prefix", + type=str, + default="", + help="Auto-select targets by prefix (default: infer from source, e.g. chair_).", + ) + parser.add_argument( + "--auto-rerun-source", + type=int, + choices=[0, 1], + default=1, + help="If source mesh/pose is missing, run rerun_step6_objects.py for source first (default: 1).", + ) + parser.add_argument( + "--overwrite", + type=int, + choices=[0, 1], + default=1, + help="Overwrite existing target object dirs before pose-only rerun (default: 1).", + ) + parser.add_argument( + "--render-video", + type=int, + choices=[0, 1], + default=1, + help="Render pose_result/normal_video_converted.mp4 for each target (default: 1).", + ) + parser.add_argument( + "--continue-on-error", + type=int, + choices=[0, 1], + default=1, + help="Continue processing next target if one target fails (default: 1).", + ) + parser.add_argument( + "--dry-run", + type=int, + choices=[0, 1], + default=0, + help="Only print actions, do not write files.", + ) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + run_dir = args.run_dir.resolve() + config_path = args.config.resolve() + source_object = str(args.source_object).strip() + if not source_object: + raise ValueError("--source-object cannot be empty") + if not run_dir.exists(): + raise FileNotFoundError(run_dir) + if not config_path.exists(): + raise FileNotFoundError(config_path) + + batch_cfg_path, mask_glob, specs, _ = _load_config(config_path) + if source_object not in specs: + raise KeyError(f"source object not found in config: {source_object}") + + if args.targets.strip(): + targets = sorted({x.strip() for x in args.targets.split(",") if x.strip()}) + else: + prefix = args.target_prefix.strip() or _infer_group_prefix(source_object) + targets = sorted([name for name in specs if name.startswith(prefix)]) + targets = [name for name in targets if name != source_object] + if not targets: + print("[reuse-mesh] No target objects selected.") + return + + source_dir = run_dir / "objects" / source_object + source_ready = _has_source_ready(source_dir) + if not source_ready: + if int(args.auto_rerun_source) != 1: + raise RuntimeError( + f"source object is not ready (missing mesh or pose): {source_dir}. " + "Enable --auto-rerun-source 1 or generate source first." + ) + if int(args.dry_run) == 1: + print(f"[dry-run] Would generate source object first: {source_object}") + print("[dry-run] Source is currently missing mesh/pose; dry-run skips hard checks.") + else: + _run_rerun_source(run_dir, config_path, source_object) + source_ready = _has_source_ready(source_dir) + + scaled_mesh = _pick_scaled_mesh(source_dir) + if scaled_mesh is None: + if int(args.dry_run) == 1: + scaled_mesh = source_dir / "mid_files" / "scaled_mesh.obj" + else: + raise FileNotFoundError(f"source scaled mesh not found: {source_dir}") + high_mesh = _pick_high_mesh(source_dir, scaled_mesh) + + if int(args.dry_run) == 1: + print(f"[dry-run] source_ready={source_ready}") + print(f"[dry-run] source_mesh={scaled_mesh}") + for name in targets: + spec = specs.get(name) + if spec is None: + continue + print(f"[dry-run] target={name} masks_dir={spec.masks_dir}") + summary = { + "time": datetime.utcnow().isoformat() + "Z", + "run_dir": str(run_dir), + "config": str(config_path), + "source_object": source_object, + "source_scaled_mesh": str(scaled_mesh), + "source_high_mesh": str(high_mesh), + "targets": targets, + "success": targets, + "failed": [], + "dry_run": True, + } + summary_path = run_dir / f"mesh_reuse_summary_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json" + summary_path.write_text(json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8") + print(f"[reuse-mesh] Dry-run summary: {summary_path}") + return + + bsp_mod = _get_bsp() + base_cfg = bsp_mod.load_batch_config(batch_cfg_path) + rgb_paths, depth_paths, intrinsics = bsp_mod.load_session_sequences(run_dir) + sample_stride = max(1, int(base_cfg.tracker.sample_stride)) + num_frames = len(rgb_paths) + mask_inputs = ( + base_cfg.scale.pose_mask_inputs + if base_cfg.scale.pose_mask_inputs is not None + else (base_cfg.scale.mode != "legacy") + ) + + summary: Dict[str, object] = { + "time": datetime.utcnow().isoformat() + "Z", + "run_dir": str(run_dir), + "config": str(config_path), + "source_object": source_object, + "source_scaled_mesh": str(scaled_mesh), + "source_high_mesh": str(high_mesh), + "targets": targets, + "success": [], + "failed": [], + "dry_run": bool(args.dry_run), + } + + for name in targets: + spec = specs.get(name) + if spec is None: + summary["failed"].append({"name": name, "error": "missing_in_config"}) + continue + if spec.category not in {"static", "rigid"}: + msg = f"skip category={spec.category}" + print(f"[reuse-mesh] {name}: {msg}") + summary["failed"].append({"name": name, "error": msg}) + continue + + print(f"[reuse-mesh] Processing {name} with mesh from {source_object}") + try: + mask_sequence = _build_object_mask_sequence( + spec.masks_dir, mask_glob, num_frames, sample_stride + ) + target_dir = run_dir / "objects" / name + + if int(args.dry_run) == 1: + print(f"[dry-run] target_dir={target_dir}") + print(f"[dry-run] masks={spec.masks_dir} frames={len(mask_sequence)}") + summary["success"].append(name) + continue + + _prepare_target_dir(source_dir, target_dir, overwrite=bool(args.overwrite)) + written_masks = _write_target_masks(mask_sequence, rgb_paths, target_dir / "masks") + _run_pose_only( + target_dir=target_dir, + scaled_mesh=(target_dir / "mid_files" / "scaled_mesh.obj") + if (target_dir / "mid_files" / "scaled_mesh.obj").exists() + else scaled_mesh, + high_mesh=_pick_high_mesh(target_dir, scaled_mesh), + mask_paths=written_masks, + rgb_paths=rgb_paths, + depth_paths=depth_paths, + intrinsics=intrinsics, + run_dir=run_dir, + mask_inputs=bool(mask_inputs), + render_video=bool(args.render_video), + ) + summary["success"].append(name) + print(f"[reuse-mesh] OK {name}") + except Exception as exc: # noqa: BLE001 + err_msg = str(exc) + print(f"[reuse-mesh] FAIL {name}: {err_msg}") + summary["failed"].append( + {"name": name, "error": err_msg, "traceback": traceback.format_exc()} + ) + if int(args.continue_on_error) != 1: + break + + summary_path = run_dir / f"mesh_reuse_summary_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json" + summary_path.write_text(json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8") + print(f"[reuse-mesh] Summary: {summary_path}") + print( + f"[reuse-mesh] Done. success={len(summary['success'])}, failed={len(summary['failed'])}" + ) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/romav2_match_worker.py b/OVOW/engine/tools/romav2_match_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..d8be4e1cdda87d48a360c1c8f6b3163106121eec --- /dev/null +++ b/OVOW/engine/tools/romav2_match_worker.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python +"""RoMaV2 dense-matching worker (runs inside the dedicated `romav2` conda env). + +One-shot subprocess: loads the model once, matches N render views against one +reference crop, writes per-view pixel-space correspondences to an output npz. + +Input npz: + renders: (N, H, W) or (N, H, W, 3) uint8 + ref: (H2, W2) or (H2, W2, 3) uint8 +Output npz: + mkpts0_{i}: (M, 2) float32 render-view pixel coords + mkpts1_{i}: (M, 2) float32 ref pixel coords + conf_{i}: (M,) float32 match confidence (overlap) + counts: (N,) int64 confident-match count per view +""" +import argparse +import sys + +import numpy as np + + +def to_rgb(a): + if a.ndim == 2: + a = np.stack([a] * 3, axis=-1) + return np.ascontiguousarray(a) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--input", required=True) + ap.add_argument("--output", required=True) + ap.add_argument("--num-matches", type=int, default=2000) + ap.add_argument("--cert-th", type=float, default=0.3) + ap.add_argument("--setting", default="precise") + args = ap.parse_args() + + import torch # noqa: F401 (import order: torch before romav2) + from romav2 import RoMaV2 + + data = np.load(args.input) + renders = data["renders"] + ref_rgb = to_rgb(data["ref"]) + H_B, W_B = ref_rgb.shape[:2] + + model = RoMaV2() + model.apply_setting(args.setting) + + out = {} + counts = [] + for i in range(renders.shape[0]): + render_rgb = to_rgb(renders[i]) + H_A, W_A = render_rgb.shape[:2] + try: + with torch.no_grad(): + preds = model.match(render_rgb, ref_rgb) + matches, conf, _, _ = model.sample(preds, args.num_matches) + kpts_a, kpts_b = model.to_pixel_coordinates( + matches, H_A, W_A, H_B, W_B + ) + keep = conf > args.cert_th + kpts_a = kpts_a[keep].cpu().numpy().astype(np.float32) + kpts_b = kpts_b[keep].cpu().numpy().astype(np.float32) + conf = conf[keep].cpu().numpy().astype(np.float32) + except Exception as exc: + print(f"[romav2-worker] view {i} failed: {exc}", file=sys.stderr) + kpts_a = np.zeros((0, 2), np.float32) + kpts_b = np.zeros((0, 2), np.float32) + conf = np.zeros((0,), np.float32) + out[f"mkpts0_{i}"] = kpts_a + out[f"mkpts1_{i}"] = kpts_b + out[f"conf_{i}"] = conf + counts.append(len(kpts_a)) + + out["counts"] = np.asarray(counts, np.int64) + np.savez(args.output, **out) + print(f"[romav2-worker] done counts={counts}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/run_intrhdr_media.sh b/OVOW/engine/tools/run_intrhdr_media.sh new file mode 100644 index 0000000000000000000000000000000000000000..bd54ef4f2c35628f65eb53319a1d88bad9a3d65c --- /dev/null +++ b/OVOW/engine/tools/run_intrhdr_media.sh @@ -0,0 +1,196 @@ +#!/usr/bin/env bash +set -euo pipefail + +PROJECT_DIR="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/IntrinsicHDR" +PYTHON_BIN="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-hdr/bin/python" +GPU_ID="${CUDA_VISIBLE_DEVICES:-1}" +KEEP_TEMP="0" + +IMAGE_PATH="" +VIDEO_PATH="" +OUTPUT_PATH="" + +usage() { + cat <<'USAGE' +Usage: + bash run_intrhdr_media.sh (--image /path/to/input.png | --video /path/to/input.mp4) [options] + +Options: + --image PATH Input image path + --video PATH Input video path; only the first frame is used + --output PATH Output EXR path (default: same dir/same basename .exr) + --gpu ID GPU id for inference (default: current CUDA_VISIBLE_DEVICES, else 1) + --project-dir DIR IntrinsicHDR project dir + --python PATH Python path in hdr env + --keep-temp 0|1 Keep temporary dirs (default: 0) + -h, --help Show this help +USAGE +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --image) + IMAGE_PATH="$2" + shift 2 + ;; + --video) + VIDEO_PATH="$2" + shift 2 + ;; + --output) + OUTPUT_PATH="$2" + shift 2 + ;; + --gpu) + GPU_ID="$2" + shift 2 + ;; + --project-dir) + PROJECT_DIR="$2" + shift 2 + ;; + --python) + PYTHON_BIN="$2" + shift 2 + ;; + --keep-temp) + KEEP_TEMP="$2" + shift 2 + ;; + -h|--help) + usage + exit 0 + ;; + *) + echo "ERROR: unknown arg: $1" >&2 + usage + exit 1 + ;; + esac +done + +if [[ -n "$IMAGE_PATH" && -n "$VIDEO_PATH" ]]; then + echo "ERROR: pass only one of --image or --video." >&2 + exit 1 +fi +if [[ -z "$IMAGE_PATH" && -z "$VIDEO_PATH" ]]; then + echo "ERROR: one of --image or --video is required." >&2 + usage + exit 1 +fi +if [[ -n "$IMAGE_PATH" && ! -f "$IMAGE_PATH" ]]; then + echo "ERROR: image not found: $IMAGE_PATH" >&2 + exit 1 +fi +if [[ -n "$VIDEO_PATH" && ! -f "$VIDEO_PATH" ]]; then + echo "ERROR: video not found: $VIDEO_PATH" >&2 + exit 1 +fi +if [[ ! -f "$PROJECT_DIR/inference.py" ]]; then + echo "ERROR: inference.py not found under project dir: $PROJECT_DIR" >&2 + exit 1 +fi +if [[ ! -x "$PYTHON_BIN" ]]; then + echo "ERROR: python binary not executable: $PYTHON_BIN" >&2 + exit 1 +fi +if [[ "$KEEP_TEMP" != "0" && "$KEEP_TEMP" != "1" ]]; then + echo "ERROR: --keep-temp must be 0 or 1 (got: $KEEP_TEMP)" >&2 + exit 1 +fi + +SOURCE_PATH="$IMAGE_PATH" +SOURCE_KIND="image" +if [[ -n "$VIDEO_PATH" ]]; then + SOURCE_PATH="$VIDEO_PATH" + SOURCE_KIND="video" +fi + +if [[ -z "$OUTPUT_PATH" ]]; then + src_dir="$(dirname "$SOURCE_PATH")" + src_name="$(basename "$SOURCE_PATH")" + src_stem="${src_name%.*}" + OUTPUT_PATH="$src_dir/$src_stem.exr" +fi + +mkdir -p "$(dirname "$OUTPUT_PATH")" + +run_tag="$(date +%Y%m%d_%H%M%S)" +src_stem="$(basename "${SOURCE_PATH%.*}")" +tmp_root="$(dirname "$OUTPUT_PATH")/.intrhdr_tmp_${src_stem}_${run_tag}" +input_dir="$tmp_root/input_exr" +infer_out_dir="$tmp_root/inference_out" +mkdir -p "$input_dir" "$infer_out_dir" + +cleanup() { + if [[ "$KEEP_TEMP" == "0" && -d "$tmp_root" ]]; then + rm -rf "$tmp_root" + fi +} +trap cleanup EXIT + +export OPENCV_IO_ENABLE_OPENEXR=1 +export SOURCE_KIND +export SOURCE_PATH +export INPUT_DIR="$input_dir" + +"$PYTHON_BIN" - <<'PY' +import os +import cv2 +import numpy as np + +source_kind = os.environ["SOURCE_KIND"] +source_path = os.environ["SOURCE_PATH"] +input_dir = os.environ["INPUT_DIR"] +exr_path = os.path.join(input_dir, "frame000.exr") + +if source_kind == "video": + cap = cv2.VideoCapture(source_path) + ok, frame = cap.read() + cap.release() + if not ok or frame is None: + raise RuntimeError(f"Failed to read first frame from {source_path}") +else: + frame = cv2.imread(source_path, cv2.IMREAD_UNCHANGED) + if frame is None: + raise RuntimeError(f"Failed to read image: {source_path}") + if frame.ndim == 2: + frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR) + elif frame.ndim == 3 and frame.shape[2] >= 4: + frame = frame[:, :, :3] + elif frame.ndim != 3 or frame.shape[2] != 3: + raise RuntimeError(f"Unsupported image shape for {source_path}: {frame.shape}") + +if np.issubdtype(frame.dtype, np.integer): + max_val = float(np.iinfo(frame.dtype).max) + frame_f = frame.astype(np.float32) / max(1.0, max_val) +else: + frame_f = frame.astype(np.float32) + frame_max = float(np.nanmax(frame_f)) if frame_f.size else 0.0 + if frame_max > 1.0: + frame_f = frame_f / max(255.0, frame_max) + +frame_f = np.clip(frame_f, 0.0, None) +if not cv2.imwrite(exr_path, frame_f, [cv2.IMWRITE_EXR_COMPRESSION, 1]): + raise RuntimeError(f"Failed to write EXR: {exr_path}") + +print(exr_path) +PY + +export CUDA_VISIBLE_DEVICES="$GPU_ID" +"$PYTHON_BIN" "$PROJECT_DIR/inference.py" \ + --test_imgs "$input_dir" \ + --output_path "$infer_out_dir" \ + --use_exr + +src_exr="$infer_out_dir/predictions/frame000.exr" +if [[ ! -f "$src_exr" ]]; then + echo "ERROR: inference output missing: $src_exr" >&2 + exit 1 +fi + +cp -f "$src_exr" "$OUTPUT_PATH" +echo "[OK] Output EXR: $OUTPUT_PATH" +if [[ "$KEEP_TEMP" == "1" ]]; then + echo "[OK] Temp dir kept: $tmp_root" +fi diff --git a/OVOW/engine/tools/scale_glb_anim.py b/OVOW/engine/tools/scale_glb_anim.py new file mode 100644 index 0000000000000000000000000000000000000000..749b3e6175cbf87d87c853e9f3d244da162658ac --- /dev/null +++ b/OVOW/engine/tools/scale_glb_anim.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import struct +from pathlib import Path +from typing import Tuple + +import numpy as np +from pygltflib import GLTF2 + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Uniformly scale a GLB animation (prefer scale channels if present).") + parser.add_argument("--input", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--scale", type=float, required=True) + parser.add_argument( + "--bake-geometry", + action="store_true", + help="将缩放直接烘焙到网格顶点(POSITION + morph targets),避免后续去掉TRS导致尺度丢失", + ) + return parser.parse_args() + + +def _accessor_info(gltf: GLTF2, acc_idx: int) -> Tuple[int, int, int, int]: + acc = gltf.accessors[acc_idx] + bv = gltf.bufferViews[acc.bufferView] + offset = (bv.byteOffset or 0) + (acc.byteOffset or 0) + comp_map = {5126: ("f", 4), 5123: ("H", 2), 5121: ("B", 1)} + if acc.componentType not in comp_map: + raise ValueError(f"Unsupported componentType: {acc.componentType}") + comp_char, comp_size = comp_map[acc.componentType] + comps = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT4": 16}.get(acc.type, 1) + count = acc.count * comps + return offset, count, comp_size, ord(comp_char.encode("ascii")) + + +def _dtype_from_component(comp: int): + if comp == 5126: + return np.float32 + if comp == 5123: + return np.uint16 + if comp == 5121: + return np.uint8 + raise ValueError(f"Unsupported componentType: {comp}") + + +def _components_for_type(t: str) -> int: + return {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT4": 16}.get(t, 1) + + +def _read_accessor(gltf: GLTF2, blob: bytearray, acc_idx: int, dtype: np.dtype | None = None) -> np.ndarray: + acc = gltf.accessors[acc_idx] + if acc.bufferView is None: + raise ValueError(f"Accessor {acc_idx} has no bufferView") + bv = gltf.bufferViews[acc.bufferView] + dtype = dtype or _dtype_from_component(acc.componentType) + comps = _components_for_type(acc.type) + count = acc.count + offset = (bv.byteOffset or 0) + (acc.byteOffset or 0) + stride = bv.byteStride or (np.dtype(dtype).itemsize * comps) + data = np.zeros((count, comps), dtype=dtype) + for i in range(count): + start = offset + i * stride + data[i] = np.frombuffer(blob, dtype=dtype, count=comps, offset=start) + return data + + +def _write_accessor(gltf: GLTF2, blob: bytearray, acc_idx: int, arr: np.ndarray, dtype: np.dtype | None = None) -> None: + acc = gltf.accessors[acc_idx] + if acc.bufferView is None: + raise ValueError(f"Accessor {acc_idx} has no bufferView") + bv = gltf.bufferViews[acc.bufferView] + dtype = dtype or _dtype_from_component(acc.componentType) + comps = _components_for_type(acc.type) + offset = (bv.byteOffset or 0) + (acc.byteOffset or 0) + stride = bv.byteStride or (np.dtype(dtype).itemsize * comps) + arr = arr.astype(dtype) + for i in range(acc.count): + start = offset + i * stride + blob[start : start + comps * np.dtype(dtype).itemsize] = arr[i].tobytes() + + +def _scale_accessor_minmax(acc, scale: float) -> None: + if acc.min is None and acc.max is None: + return + if acc.min is not None: + mn = np.asarray(acc.min, dtype=np.float32) * scale + acc.min = mn.tolist() + if acc.max is not None: + mx = np.asarray(acc.max, dtype=np.float32) * scale + acc.max = mx.tolist() + if scale < 0.0 and acc.min is not None and acc.max is not None: + mn = np.minimum(acc.min, acc.max) + mx = np.maximum(acc.min, acc.max) + acc.min = mn.tolist() + acc.max = mx.tolist() + + +def _scale_geometry(gltf: GLTF2, blob: bytearray, scale: float) -> bool: + scaled = False + for mesh in gltf.meshes or []: + for prim in mesh.primitives or []: + if prim.attributes and prim.attributes.POSITION is not None: + acc_idx = prim.attributes.POSITION + acc = gltf.accessors[acc_idx] + if acc.componentType != 5126: + print(f"[Warn] POSITION accessor {acc_idx} not float32, skip scaling.") + else: + pos = _read_accessor(gltf, blob, acc_idx, np.float32) + pos = pos * float(scale) + _write_accessor(gltf, blob, acc_idx, pos, np.float32) + _scale_accessor_minmax(acc, scale) + scaled = True + for target in prim.targets or []: + if "POSITION" not in target: + continue + acc_idx = target["POSITION"] + acc = gltf.accessors[acc_idx] + if acc.componentType != 5126: + print(f"[Warn] morph POSITION accessor {acc_idx} not float32, skip scaling.") + continue + dpos = _read_accessor(gltf, blob, acc_idx, np.float32) + dpos = dpos * float(scale) + _write_accessor(gltf, blob, acc_idx, dpos, np.float32) + _scale_accessor_minmax(acc, scale) + scaled = True + return scaled + + +def main() -> None: + args = parse_args() + if not args.input.exists(): + raise FileNotFoundError(args.input) + if abs(args.scale - 1.0) < 1e-6: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_bytes(args.input.read_bytes()) + print(f"[Skip] scale ~1.0, copied: {args.output}") + return + + gltf = GLTF2().load(args.input) + blob = bytearray(gltf.binary_blob() or b"") + + scaled_any = False + has_scale_channel = False + for anim in gltf.animations or []: + if not anim.channels or not anim.samplers: + continue + for ch in anim.channels: + if ch.target and ch.target.path == "scale": + has_scale_channel = True + if args.bake_geometry: + continue + sampler = anim.samplers[ch.sampler] + acc_idx = sampler.output + arr = _read_accessor(gltf, blob, acc_idx, np.float32) + arr = arr * float(args.scale) + _write_accessor(gltf, blob, acc_idx, arr, np.float32) + scaled_any = True + + if args.bake_geometry or not scaled_any: + scaled_geom = _scale_geometry(gltf, blob, float(args.scale)) + if not scaled_geom and not scaled_any: + for n in gltf.nodes or []: + if n.mesh is None: + continue + if n.scale is None: + n.scale = [float(args.scale)] * 3 + else: + n.scale = [float(v) * float(args.scale) for v in n.scale] + print("[Warn] No scale channels/geometry found; applied node.scale instead.") + elif scaled_geom: + print("[OK] Scaled geometry (positions + morph targets).") + if has_scale_channel and args.bake_geometry: + print("[Info] bake-geometry enabled; scale channels left unchanged.") + + gltf.set_binary_blob(bytes(blob)) + args.output.parent.mkdir(parents=True, exist_ok=True) + gltf.save(args.output) + print(f"[OK] Wrote: {args.output}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/scan_motion324_outputs.py b/OVOW/engine/tools/scan_motion324_outputs.py new file mode 100644 index 0000000000000000000000000000000000000000..7dc54f26c0f8106dc63f007136a63e27224dcc12 --- /dev/null +++ b/OVOW/engine/tools/scan_motion324_outputs.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import List, Optional + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Scan Motion324 processed outputs and build manifest.") + parser.add_argument("--input-root", type=Path, required=True, help="motion324 input root (motion324_inputs)") + parser.add_argument("--output-root", type=Path, required=True, help="motion324 output root (motion324_outputs)") + parser.add_argument("--video-name", type=str, required=True, help="video name") + return parser.parse_args() + + +def _find_first(glob_list: List[Path]) -> Optional[Path]: + for p in glob_list: + if p.exists(): + return p + return None + + +def _pick_ref_mesh(proc_dir: Path) -> Optional[Path]: + hu_dir = proc_dir / "Hunyuan_Gen_Input" + if not hu_dir.exists(): + return None + candidates = sorted(hu_dir.glob("*_hunyuan_original_wo_remap.glb")) + candidates += sorted(hu_dir.glob("*_hunyuan_original_watertight.glb")) + candidates += sorted(hu_dir.glob("*_hunyuan_original_wo_remap_converted.fbx")) + return _find_first(candidates) + + +def _pick_animation(proc_dir: Path) -> Optional[Path]: + anim_dir = proc_dir / "animation" + if not anim_dir.exists(): + return None + candidates = [anim_dir / "output_animation.glb", anim_dir / "output_animation.fbx"] + return _find_first(candidates) + + +def main() -> None: + args = parse_args() + in_root = args.input_root / args.video_name + out_root = args.output_root / args.video_name + out_root.mkdir(parents=True, exist_ok=True) + + objects = [] + if in_root.exists(): + for obj_dir in sorted([d for d in in_root.iterdir() if d.is_dir()]): + masked_video = obj_dir / "masked.mp4" + if not masked_video.exists(): + continue + proc_dir = obj_dir / "masked_processed" + anim_path = _pick_animation(proc_dir) + ref_mesh = _pick_ref_mesh(proc_dir) + objects.append( + { + "name": obj_dir.name, + "masked_video": str(masked_video), + "processed_dir": str(proc_dir), + "animation": str(anim_path) if anim_path else None, + "ref_mesh": str(ref_mesh) if ref_mesh else None, + } + ) + + manifest = { + "video_name": args.video_name, + "input_root": str(in_root), + "output_root": str(out_root), + "objects": objects, + } + + manifest_path = out_root / "manifest.json" + manifest_path.write_text(json.dumps(manifest, indent=2)) + print(str(manifest_path)) + + +if __name__ == "__main__": + main() diff --git a/OVOW/engine/tools/view.py b/OVOW/engine/tools/view.py new file mode 100644 index 0000000000000000000000000000000000000000..4fae33c079950e9fbbcdd87104a0de21ee51b0ff --- /dev/null +++ b/OVOW/engine/tools/view.py @@ -0,0 +1,204 @@ +#!/usr/bin/env python3 +"""Batch-render every scene_* folder in a OnePoseviaGen batch run.""" + +from __future__ import annotations + +import argparse +import fnmatch +import shlex +import subprocess +import sys +from pathlib import Path +from typing import Iterable, List, Optional, Sequence, Tuple + + +def _parse_scene_tokens(tokens: Optional[Sequence[str]], prefix: str) -> List[str]: + if not tokens: + return [] + normalized: List[str] = [] + for raw in tokens: + token = (raw or "").strip() + if not token: + continue + if token.startswith(prefix): + normalized.append(token) + continue + lowered = token.lower() + if lowered.startswith("scene"): + stripped = token[5:] + if stripped.startswith("_"): + stripped = stripped[1:] + token = stripped + if token.isdigit(): + normalized.append(f"{prefix}{int(token):02d}") + else: + normalized.append(raw) + return normalized + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=( + "Iterate through every scene_* folder inside a batch directory and " + "invoke each scene's render_combined_mesh.py." + ), + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument( + "--batch-dir", + type=Path, + required=True, + help="Path to OnePoseviaGen/temp_local/batch_run_xxxxxxx directory.", + ) + parser.add_argument( + "--scene-pattern", + default="scene_*", + help="fnmatch-style pattern for sub-folders that should be rendered.", + ) + parser.add_argument( + "--only", + nargs="*", + default=None, + help="Optional whitelist of scene names or numeric ids to render.", + ) + parser.add_argument( + "--skip", + nargs="*", + default=None, + help="Optional blacklist of scene names or numeric ids to ignore.", + ) + parser.add_argument( + "--render-script", + default="render_combined_mesh.py", + help="Relative script name searched inside every scene directory.", + ) + parser.add_argument( + "--python", + default=sys.executable, + help="Python interpreter used to launch each render script.", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Only print the commands that would run without rendering.", + ) + parser.add_argument( + "--stop-on-error", + action="store_true", + help="Abort on the first failed scene instead of continuing.", + ) + parser.add_argument( + "--render-args", + nargs=argparse.REMAINDER, + help=( + "Arguments forwarded verbatim to render_combined_mesh.py. " + "Example: --render-args --frame-index 10 --use-high-mesh" + ), + ) + return parser.parse_args() + + +def find_scene_dirs( + batch_dir: Path, + pattern: str, + only_tokens: Optional[Sequence[str]], + skip_tokens: Optional[Sequence[str]], +) -> List[Path]: + if not batch_dir.exists(): + raise FileNotFoundError(f"Batch directory not found: {batch_dir}") + if not batch_dir.is_dir(): + raise NotADirectoryError(f"{batch_dir} is not a directory") + prefix = "scene_" + only = set(_parse_scene_tokens(only_tokens, prefix)) + skip = set(_parse_scene_tokens(skip_tokens, prefix)) + dirs = [] + for entry in sorted(batch_dir.iterdir()): + if not entry.is_dir(): + continue + if not fnmatch.fnmatch(entry.name, pattern): + continue + if only and entry.name not in only: + continue + if entry.name in skip: + continue + dirs.append(entry) + return dirs + + +def build_command( + python_exec: str, + script_path: Path, + scene_dir: Path, + extra_args: Optional[Sequence[str]], +) -> List[str]: + cmd = [python_exec, str(script_path), "--scene-dir", str(scene_dir)] + if extra_args: + cmd.extend(extra_args) + return cmd + + +def render_scene( + scene_dir: Path, + script_name: str, + python_exec: str, + render_args: Optional[Sequence[str]], + dry_run: bool, +) -> Tuple[bool, str]: + script_path = scene_dir / script_name + if not script_path.exists(): + return False, f"{script_path.name} not found" + cmd = build_command(python_exec, script_path, scene_dir, render_args) + pretty = " ".join(shlex.quote(part) for part in cmd) + print(f"[{scene_dir.name}] {pretty}") + if dry_run: + return True, "dry-run" + result = subprocess.run(cmd, cwd=str(scene_dir)) + if result.returncode == 0: + return True, "ok" + return False, f"exit code {result.returncode}" + + +def main() -> int: + args = parse_args() + render_args = args.render_args or [] + try: + scene_dirs = find_scene_dirs(args.batch_dir.resolve(), args.scene_pattern, args.only, args.skip) + except (FileNotFoundError, NotADirectoryError) as exc: + print(exc) + return 1 + if not scene_dirs: + print("No scene directories matched the given filters.") + return 1 + + successes: List[str] = [] + failures: List[Tuple[str, str]] = [] + for scene_dir in scene_dirs: + ok, message = render_scene( + scene_dir=scene_dir, + script_name=args.render_script, + python_exec=args.python, + render_args=render_args, + dry_run=args.dry_run, + ) + if ok: + successes.append(scene_dir.name) + else: + failures.append((scene_dir.name, message)) + print(f" -> Failed: {message}") + if args.stop_on_error: + break + + print("\nSummary") + print("-------") + if successes: + print(f"Rendered ({len(successes)}): {', '.join(successes)}") + if failures: + failed_str = ", ".join(f"{name} ({reason})" for name, reason in failures) + print(f"Failed ({len(failures)}): {failed_str}") + else: + print("All scenes rendered successfully.") + return 0 if not failures else 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/OVOW/environment/README.md b/OVOW/environment/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a766a7b9122967bbb24c24d34968edb5b2680941 --- /dev/null +++ b/OVOW/environment/README.md @@ -0,0 +1,70 @@ +# 环境重建 + +**推荐直接用一键脚本**:`bash environment/create_envs.sh`(可 `[opg|sam3|motion]` 单建; +结束时打印该填进 `.env` 的解释器路径)。本文档是它背后的版本表与逐条手动命令—— +脚本哪一步失败,就照下面手动补装哪一步。 + +OVOW 用 3 个互不兼容的 conda 环境(torch/CUDA 强耦合,**不能纯 pip 复现**,需对齐 CUDA)。 + +| env | python | torch | 用途 | 依赖清单 | +|---|---|---|---|---| +| `ovow-opg` | 3.11 | 2.4.1+cu121 | 主重建 / scale / 位姿 | `requirements-opg.txt` | +| `ovow-sam3` | 3.12 | 2.7.0+cu118 | SAM3 分割 | `requirements-sam3.txt` | +| `ovow-motion` | 3.11 | 2.4.1+cu124 | Motion324 + Hunyuan deform | `requirements-motion.txt` | + +> **三个环境的 torch 各绑一个 CUDA 版本(cu121 / cu118 / cu124)**——这是 pip wheel 自带的 +> CUDA runtime,互不冲突,也不要求系统装三套 CUDA Toolkit。系统侧只需: +> ① NVIDIA 驱动 ≥550(能跑 cu124 wheel 即可全兼容);② 一套 CUDA Toolkit(建议 12.1+, +> 含 `nvcc`)用于现场编译扩展——opg 的一批(见下表)+ motion 的 custom_rasterizer; +> sam3 无需编译,纯 pip 即装。 +> `requirements-sam3.txt` / `requirements-motion.txt` 已内置对应的 +> `--extra-index-url`(PyTorch 官方 wheel 源),直接 `pip install -r` 即可。 + +重建(以 opg 为例,**顺序重要**): +```bash +conda create -n ovow-opg python=3.11 -y && conda activate ovow-opg +# 1) 先按你的 CUDA 装 torch(示例 cu121) +pip install torch==2.4.1 torchvision==0.19.1 torchaudio==2.4.1 --index-url https://download.pytorch.org/whl/cu121 +# 2) PyPI + git 源依赖 +pip install -r environment/requirements-opg.txt +# 3) 需现场编译的 CUDA 扩展(按目标 CUDA 编译,务必对齐 torch/CUDA) +bash environment/build_cuda_exts.sh # 见下,封装了下面所有 clone+build +# 4) 引擎自带子包(editable,从仓库内 engine/ 安装) +for p in Amodal3R fpose fpose/fpose/bundlesdf/mycuda SpaTrackerV2 trellis DA3; do + pip install -e engine/oneposeviagen/$p +done +``` + +## CUDA 扩展来源(已补全,2026-06-15) + +| 扩展 | 用途 | 来源 / 安装 | +|---|---|---| +| pytorch3d | 3D 算子 | `pip install --no-build-isolation git+https://github.com/facebookresearch/pytorch3d.git` | +| flash-attn | 注意力 | `pip install flash-attn --no-build-isolation`(或用官方预编译 whl 对齐 cu121/torch2.4)| +| nvdiffrast | 可微渲染 | `pip install git+https://github.com/NVlabs/nvdiffrast.git` | +| diffoctreerast | TRELLIS 渲染 | `pip install git+https://github.com/JeffreyXiang/diffoctreerast.git` | +| diff-gaussian-rasterization | 3DGS | clone `autonomousvision/mip-splatting` 后装其 `submodules/diff-gaussian-rasterization/` | +| simple-knn | 3DGS | 同上 mip-splatting 的 `submodules/simple-knn/` | +| **CuMesh**(原缺源)| TRELLIS2 网格/UV | `pip install --no-build-isolation git+https://github.com/JeffreyXiang/CuMesh.git`(需 torch≥2.4 + CUDA≥12.4)| +| **nvdiffrec-renderutils**(原缺源)| TRELLIS2 渲染(模块名 `nvdiffrec_render`)| `git clone -b renderutils https://github.com/JeffreyXiang/nvdiffrec.git /tmp/nvdiffrec && pip install /tmp/nvdiffrec --no-build-isolation` | +| o-voxel / flexgemm | TRELLIS2 | o-voxel 源在仓库内 `engine/oneposeviagen/TRELLIS2/o-voxel`;flexgemm 见 `microsoft/TRELLIS.2` 的 `setup.sh --flexgemm` | +| utils3d | 工具 | `pip install git+https://github.com/EasternJournalist/utils3d.git` | +| custom_rasterizer | Hunyuan 贴图(motion 环境)| 源在仓库内 `third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer`,`pip install -e` 之 | +| FoundationPose 扩展 | 位姿 | `cd engine/oneposeviagen/fpose && bash build_all_conda.sh` | + +> **重要**:CuMesh / nvdiffrec / o-voxel / flexgemm 仅 **TRELLIS2 backbone** 用到。 +> 而 OVOW 入口(`scripts/run_video.sh` / `run_fullpipe_batch.sh`)的默认 backbone 是 **`uplegacy`** +> (= legacy/Hi3DGen 生成后端 + 升级版位姿链路:romav2 匹配 + 零迭代 scale + 全部模型进程内常驻; +> 见 `configs/paths.sh` 的 `OPG_MATCHER=romav2 / OPG_SCALE_REFINE_ITERS=0 / OPG_ROMAV2_INPROC=1 / OPG_FP_RESIDENT=1`)。 +> uplegacy 的生成后端会折叠成 legacy/Hi3DGen,**不走 TRELLIS2**——所以**默认复现不需要 CuMesh/nvdiffrec**, +> 上游 OnePoseviaGen 的 `setup.sh` 也只装前面的 CORE。仅当显式 `--recon-backbone trellis2` 时才需要: +> `bash environment/build_cuda_exts.sh --trellis2`。权威脚本见 +> [microsoft/TRELLIS.2 setup.sh](https://github.com/microsoft/TRELLIS.2/blob/main/setup.sh)。 +> +> OVOW 引擎自带 `engine/setup.sh`(= 上游官方安装流程)是权威参照;`build_cuda_exts.sh` 即对齐它。 + +注意: +- **环境与 CUDA 强耦合,不能纯 pip 一键复现**;step 3/4 需现场编译,务必对齐 CUDA/torch 版本。 +- `requirements-*.txt` 已剔除 dev 机器本地路径,只留 PyPI + git 源;原始 `pip freeze` 见 `*.freeze.bak`(仅版本参考)。 +- 引擎自带 `setup.sh` 也编码了上述步骤,可对照参考。 +- `flux` / `hdr` 环境为可选步骤,未纳入核心复现。 diff --git a/OVOW/environment/build_cuda_exts.sh b/OVOW/environment/build_cuda_exts.sh new file mode 100644 index 0000000000000000000000000000000000000000..f002846e6f345cc4c48235dfdf00f5eb59b8db4a --- /dev/null +++ b/OVOW/environment/build_cuda_exts.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -uo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +TMP="${TMP:-$HOME/jiayin/tmp/ovow_exts}"; mkdir -p "$TMP" +WANT_TRELLIS2=0; [[ "${1:-}" == "--trellis2" ]] && WANT_TRELLIS2=1 +PI() { echo; echo ">>> $*"; "$@"; } + +command -v nvcc >/dev/null 2>&1 || echo "[warn] 未找到 nvcc;CUDA 扩展需 CUDA Toolkit 才能编译" + +conda install -c conda-forge eigen=3.4.0 -y || echo "[warn] eigen 安装失败(FoundationPose 编译需要)" +PI pip install flash-attn --no-build-isolation +PI pip install --no-build-isolation git+https://github.com/facebookresearch/pytorch3d.git +PI pip install git+https://github.com/JeffreyXiang/diffoctreerast.git +PI pip install git+https://github.com/EasternJournalist/utils3d.git +[ -d "$TMP/mip-splatting" ] || git clone https://github.com/autonomousvision/mip-splatting.git "$TMP/mip-splatting" +PI pip install "$TMP/mip-splatting/submodules/diff-gaussian-rasterization/" +PI pip install "$TMP/mip-splatting/submodules/simple-knn/" +( cd "$HERE/engine/oneposeviagen/fpose/fpose" && \ + CMAKE_PREFIX_PATH="$CONDA_PREFIX/lib/python3.11/site-packages/pybind11/share/cmake/pybind11" bash build_all_conda.sh ) \ + || echo "[warn] FoundationPose build_all_conda.sh 失败,见该目录日志" + +if [[ "$WANT_TRELLIS2" -eq 1 ]]; then + echo; echo "=== 安装 TRELLIS2 扩展(CuMesh / nvdiffrec / o-voxel)===" + PI pip install --no-build-isolation git+https://github.com/JeffreyXiang/CuMesh.git + [ -d "$TMP/nvdiffrec" ] || git clone -b renderutils https://github.com/JeffreyXiang/nvdiffrec.git "$TMP/nvdiffrec" + PI pip install --no-build-isolation "$TMP/nvdiffrec" + PI pip install --no-build-isolation -e "$HERE/engine/oneposeviagen/TRELLIS2/o-voxel" + echo "flexgemm/nvdiffrast 见 microsoft/TRELLIS.2 setup.sh(--flexgemm --nvdiffrast)" +else + echo; echo "(跳过 TRELLIS2 扩展;默认 legacy backbone 不需要。需要时加 --trellis2)" +fi + +echo; echo "=== CUDA 扩展安装完成(失败项见上方 [warn];多为 CUDA 版本未对齐)===" diff --git a/OVOW/environment/create_envs.sh b/OVOW/environment/create_envs.sh new file mode 100644 index 0000000000000000000000000000000000000000..5efda370a1003db59e0505b4644ece8542c401a5 --- /dev/null +++ b/OVOW/environment/create_envs.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +set -uo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +command -v conda >/dev/null 2>&1 || { echo "ERROR: 需要 conda(miniconda/anaconda)"; exit 1; } +source "$(conda info --base)/etc/profile.d/conda.sh" + +PICK="${1:-all}" +declare -a OK=() BAD=() + +banner() { echo; echo "==================== $1 ===================="; } + +env_opg() { + conda env list | grep -q '^ovow-opg ' || conda create -n ovow-opg python=3.11 -y || return 1 + conda activate ovow-opg || return 1 + pip install torch==2.4.1 torchvision==0.19.1 torchaudio==2.4.1 \ + --index-url https://download.pytorch.org/whl/cu121 || return 1 + pip install -r "$ROOT/environment/requirements-opg.txt" || return 1 + bash "$ROOT/environment/build_cuda_exts.sh" || return 1 + local p + for p in Amodal3R fpose fpose/fpose/bundlesdf/mycuda SpaTrackerV2 trellis DA3 SAM2-in-video; do + pip install -e "$ROOT/engine/oneposeviagen/$p" || return 1 + done + conda deactivate +} + +env_sam3() { + conda env list | grep -q '^ovow-sam3 ' || conda create -n ovow-sam3 python=3.12 -y || return 1 + conda activate ovow-sam3 || return 1 + pip install -r "$ROOT/environment/requirements-sam3.txt" || return 1 + pip install -e "$ROOT/third_party/sam3" || return 1 + conda deactivate +} + +env_motion() { + conda env list | grep -q '^ovow-motion ' || conda create -n ovow-motion python=3.11 -y || return 1 + conda activate ovow-motion || return 1 + pip install -r "$ROOT/environment/requirements-motion.txt" || return 1 + pip install -e "$ROOT/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer" || return 1 + conda deactivate +} + +run_one() { + local name="$1" + banner "ovow-$name" + if "env_$name"; then OK+=("$name"); echo "[ovow-$name] ✅ 完成" + else BAD+=("$name"); echo "[ovow-$name] ❌ 失败(从上方最后一条报错定位;修复后可单独重跑:bash environment/create_envs.sh $name)" + fi + conda deactivate 2>/dev/null || true +} + +case "$PICK" in + all) for e in opg sam3 motion; do run_one "$e"; done ;; + opg|sam3|motion) run_one "$PICK" ;; + *) echo "用法: $0 [all|opg|sam3|motion]"; exit 1 ;; +esac + +BASE="$(conda info --base)" +banner "汇总" +[[ ${#OK[@]} -gt 0 ]] && echo "成功: ${OK[*]}" +[[ ${#BAD[@]} -gt 0 ]] && echo "失败: ${BAD[*]}(逐个重跑排查)" +echo +echo "把下面几行填进 .env(路径按你的 conda 安装位置,已探测):" +echo " OPG_PY=\"$BASE/envs/ovow-opg/bin/python\"" +echo " SAM3_PY=\"$BASE/envs/ovow-sam3/bin/python\"" +echo " MOTION_PY=\"$BASE/envs/ovow-motion/bin/python\"" +[[ ${#BAD[@]} -eq 0 ]] || exit 1 diff --git a/OVOW/environment/requirements-motion.txt b/OVOW/environment/requirements-motion.txt new file mode 100644 index 0000000000000000000000000000000000000000..239ecd94884dd7864115b7feadfc0814fad4cc4c --- /dev/null +++ b/OVOW/environment/requirements-motion.txt @@ -0,0 +1,159 @@ +# OVOW motion 环境 — 可 pip 安装依赖。Hunyuan custom_rasterizer 需现场编译: +# pip install -e third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer +# packaging 用纯包名;原始 freeze 见 requirements-motion.txt.freeze.bak。 +# torch 带 +cu124 本地版本号,必须从 PyTorch 官方 index 安装(下一行提供)。 +--extra-index-url https://download.pytorch.org/whl/cu124 +packaging +Cython==3.2.4 +Deprecated==1.3.1 +GitPython==3.1.46 +Jinja2==3.1.6 +MarkupSafe==3.0.3 +Pillow==10.0.1 +PyMatting==1.1.14 +PyYAML==6.0.3 +Pygments==2.19.2 +accelerate==1.12.0 +aiohappyeyeballs==2.6.1 +aiohttp==3.13.3 +aiosignal==1.4.0 +annotated-types==0.7.0 +antlr4-python3-runtime==4.8 +asttokens==3.0.1 +attrs==25.4.0 +bpy==4.4.0 +certifi==2026.1.4 +charset-normalizer==3.4.4 +click==8.3.1 +coloredlogs==15.0.1 +contourpy==1.3.3 +cycler==0.12.1 +dataclasses-json==0.6.7 +datasets==2.14.5 +decorator==5.2.1 +diffusers==0.35.2 +dill==0.3.7 +dreamsim==0.2.1 +easydict==1.13 +einops==0.8.1 +executing==2.2.1 +filelock==3.20.3 +flatbuffers==25.12.19 +fonttools==4.61.1 +frozenlist==1.8.0 +fsspec==2023.6.0 +ftfy==6.3.1 +gitdb==4.0.12 +hf-xet==1.2.0 +huggingface-hub==0.36.0 +humanfriendly==10.0 +idna==3.11 +imageio-ffmpeg==0.5.0 +imageio==2.33.0 +importlib_metadata==8.7.1 +ipdb==0.13.13 +ipython==9.9.0 +ipython_pygments_lexers==1.1.1 +jaxtyping==0.3.1 +jedi==0.19.2 +joblib==1.5.3 +jsonschema-specifications==2025.9.1 +jsonschema==4.26.0 +kiwisolver==1.4.9 +lazy_loader==0.4 +lightning-utilities==0.15.2 +llvmlite==0.46.0 +lpips==0.1.4 +markdown-it-py==4.0.0 +marshmallow==3.26.2 +matplotlib-inline==0.2.1 +matplotlib==3.10.8 +mdurl==0.1.2 +mesh_processor==0.0.0 +modelscope==1.34.0 +mpmath==1.3.0 +multidict==6.7.0 +multiprocess==0.70.15 +mypy_extensions==1.1.0 +natsort==8.4.0 +networkx==3.6.1 +ninja==1.13.0 +numba==0.63.1 +numpy==1.26.4 +nvidia-cublas-cu12==12.4.2.65 +nvidia-cuda-cupti-cu12==12.4.99 +nvidia-cuda-nvrtc-cu12==12.4.99 +nvidia-cuda-runtime-cu12==12.4.99 +nvidia-cudnn-cu12==9.1.0.70 +nvidia-cufft-cu12==11.2.0.44 +nvidia-curand-cu12==10.3.5.119 +nvidia-cusolver-cu12==11.6.0.99 +nvidia-cusparse-cu12==12.3.0.142 +nvidia-nccl-cu12==2.20.5 +nvidia-nvjitlink-cu12==12.4.99 +nvidia-nvtx-cu12==12.4.99 +omegaconf==2.1.1 +onnxruntime==1.23.2 +open_clip_torch==3.1.0 +opencv-python-headless==4.11.0.86 +pandas==3.0.0 +parso==0.8.5 +peft==0.17.0 +pexpect==4.9.0 +platformdirs==4.5.1 +pooch==1.8.2 +prompt_toolkit==3.0.52 +propcache==0.4.1 +protobuf==6.33.4 +psutil==7.2.1 +ptyprocess==0.7.0 +pure_eval==0.2.3 +pyarrow==23.0.0 +pybind11==2.13.6 +pydantic==2.12.5 +pydantic_core==2.41.5 +pygltflib==1.16.5 +pymeshlab==2025.7 +pyparsing==3.3.2 +python-dateutil==2.9.0.post0 +referencing==0.37.0 +regex==2026.1.15 +rembg==2.0.68 +requests==2.32.5 +rich==14.3.1 +rpds-py==0.30.0 +safetensors==0.7.0 +scikit-image==0.23.2 +scikit-learn==1.8.0 +scipy==1.17.0 +sentry-sdk==2.50.0 +six==1.17.0 +smmap==5.0.2 +stack-data==0.6.3 +sympy==1.14.0 +threadpoolctl==3.6.0 +tifffile==2026.1.14 +timm==1.0.24 +tokenizers==0.22.2 +torch==2.4.1+cu124 +torchmetrics==1.8.2 +torchvision==0.19.1+cu124 +tqdm==4.67.1 +traitlets==5.14.3 +transformers==4.56.1 +trimesh==4.6.9 +triton==3.0.0 +typing-inspect==0.9.0 +typing-inspection==0.4.2 +typing_extensions==4.15.0 +urllib3==2.6.3 +wadler_lindig==0.1.7 +wandb==0.21.1 +wcwidth==0.4.0 +wrapt==2.0.1 +xatlas==0.0.11 +xformers==0.0.28 +xxhash==3.6.0 +yarl==1.22.0 +zipp==3.23.0 +zstandard==0.25.0 diff --git a/OVOW/environment/requirements-opg.txt b/OVOW/environment/requirements-opg.txt new file mode 100644 index 0000000000000000000000000000000000000000..75fd83499033a6f421c9582deb5d273713191952 --- /dev/null +++ b/OVOW/environment/requirements-opg.txt @@ -0,0 +1,329 @@ +# OVOW opg 环境 — 可 pip 安装的依赖(PyPI + git 源)。仅非商业研究用途。 +# +# 本文件【不含】下列两类,需按 environment/README.md 单独装(它们在 dev pip-freeze 里是本机绝对路径,不可移植): +# 1) 引擎自带子包(从 engine/ 源码 editable 安装): +# pip install -e engine/oneposeviagen/Amodal3R +# pip install -e engine/oneposeviagen/fpose +# pip install -e engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda +# pip install -e engine/oneposeviagen/SpaTrackerV2 +# pip install -e engine/oneposeviagen/trellis +# pip install -e engine/oneposeviagen/DA3 # depth-anything-3 +# 2) 需按目标 CUDA 现场编译的扩展(详见 README;引擎自带 setup.sh 也会建): +# torch==2.4.1 torchvision==0.19.1 torchaudio==2.4.1 (--index-url https://download.pytorch.org/whl/cu121) +# flash-attn / pytorch3d / diffoctreerast / diff-gaussian-rasterization / simple-knn / +# FoundationPose(build_all_conda.sh) / cumesh / flex_gemm / nvdiffrec-renderutils / o_voxel / utils3d / SAM2 +# 原始完整 pip-freeze 见 requirements-opg.txt.freeze.bak(仅作版本参考,勿直接 pip install)。 +# ---------------------------------------------------------------------- + +ConfigArgParse==1.7.1 +Deprecated==1.3.1 +Flask==3.1.2 +GPUtil==1.4.0 +ImageIO==2.37.2 +Jinja2==3.1.6 +MarkupSafe==3.0.3 +PyJWT==2.10.1 +PyMatting==1.1.14 +PySocks==1.7.1 +PyYAML==6.0.3 +Pygments==2.19.2 +Werkzeug==3.1.4 +accelerate==1.12.0 +addict==2.4.0 +aiofiles==24.1.0 +aiohappyeyeballs==2.6.1 +aiohttp-cors==0.8.1 +aiohttp==3.13.2 +aiosignal==1.4.0 +albucore==0.0.24 +albumentations==2.0.8 +annotated-doc==0.0.4 +annotated-types==0.7.0 +antlr4-python3-runtime==4.9.3 +anyio==4.12.0 +argcomplete==3.6.3 +asttokens==3.0.1 +attrs==25.4.0 +beautifulsoup4==4.14.3 +blinker==1.9.0 +cachetools==6.2.2 +ccimport==0.4.4 +certifi==2025.11.12 +charset-normalizer==3.4.4 +cholespy==2.1.0 +click==8.2.1 +colorama==0.4.6 +coloredlogs==15.0.1 +colorful==0.5.8 +comm==0.2.3 +contourpy==1.3.3 +cumm-cu121==0.7.11 +cycler==0.12.1 +dash==3.3.0 +dataclasses-json==0.6.7 +decorator==4.4.2 +decord==0.6.0 +deepspeed==0.18.2 +diffusers==0.36.0 +dill==0.4.0 +diso==0.1.4 +distlib==0.4.0 +distro==1.9.0 +dreamsim==0.2.1 +easydict==1.13 +editables==0.5 +einops==0.8.1 +einx==0.3.0 +entrypoints==0.4 +evo==1.34.0 +executing==2.2.1 +fast_simplification==0.1.13 +fastapi==0.123.0 +fastjsonschema==2.21.2 +ffmpy==1.0.0 +filelock==3.20.0 +fire==0.7.1 +flatbuffers==25.9.23 +flow-vis==0.1 +fonttools==4.61.0 +frozendict==2.4.7 +frozenlist==1.8.0 +fsspec==2025.10.0 +ftfy==6.3.1 +gdown==5.2.0 +glcontext==3.0.0 +gltflib==1.0.13 +google-api-core==2.28.1 +google-auth==2.43.0 +googleapis-common-protos==1.72.0 +gradio==5.31.0 +gradio_client==1.10.1 +groovy==0.1.2 +grpcio==1.76.0 +h11==0.16.0 +h5py==3.15.1 +hatchling==1.28.0 +hf-xet==1.2.0 +hjson==3.1.0 +httpcore==1.0.9 +httpx==0.28.1 +huggingface-hub==0.36.0 +humanfriendly==10.0 +hydra-core==1.3.2 +idna==3.11 +igraph==1.0.0 +imageio-ffmpeg==0.6.0 +importlib_metadata==8.7.0 +iopath==0.1.10 +ipycanvas==0.14.3 +ipyevents==2.0.4 +ipython==9.7.0 +ipython_pygments_lexers==1.1.1 +ipywidgets==8.1.8 +itsdangerous==2.2.0 +jaxtyping==0.3.3 +jedi==0.19.2 +jiter==0.15.0 +joblib==1.5.2 +jsonpatch==1.33 +jsonpointer==3.1.1 +jsonschema-specifications==2025.9.1 +jsonschema==4.25.1 +jupyter_client==7.4.9 +jupyter_core==5.9.1 +jupyterlab_widgets==3.0.16 +kaolin==0.18.0 +kiwisolver==1.4.9 +kornia==0.8.1 +kornia_rs==0.1.10 +largesteps==0.2.2 +lark==1.3.1 +laspy==2.7.0 +lazy_loader==0.4 +lightglue @ git+https://github.com/jytime/LightGlue.git@2f23ca2ea9638cecad7f7220795210fc6b8353c3 +lightning-utilities==0.15.2 +lightning==2.5.2 +llvmlite==0.45.1 +loguru==0.7.3 +lpips==0.1.4 +markdown-it-py==4.0.0 +marshmallow==3.26.1 +matplotlib-inline==0.2.1 +matplotlib==3.10.7 +mdurl==0.1.2 +mediapy==1.2.4 +modelscope==1.33.0 +moderngl==5.12.0 +moviepy==1.0.3 +mpmath==1.3.0 +msgpack==1.1.2 +multidict==6.7.0 +muon-optimizer @ git+https://github.com/KellerJordan/Muon@6399c658d3c4a3356ba823fa6664b10e23871068 +mypy_extensions==1.1.0 +narwhals==2.12.0 +natsort==8.4.0 +nbformat==5.10.4 +nest-asyncio==1.6.0 +networkx==3.6 +ninja==1.13.0 +numba==0.62.1 +numexpr==2.14.1 +numpy==1.26.3 +nvdiffrast @ git+https://github.com/NVlabs/nvdiffrast@20c4135fda78ae29d7658bea28b6c1d5b5e103e5 +nvidia-cublas-cu12==12.1.3.1 +nvidia-cuda-cupti-cu12==12.1.105 +nvidia-cuda-nvrtc-cu12==12.1.105 +nvidia-cuda-runtime-cu12==12.1.105 +nvidia-cudnn-cu12==9.1.0.70 +nvidia-cufft-cu12==11.0.2.54 +nvidia-curand-cu12==10.3.2.106 +nvidia-cusolver-cu12==11.4.5.107 +nvidia-cusparse-cu12==12.1.0.106 +nvidia-ml-py==13.580.82 +nvidia-nccl-cu12==2.20.5 +nvidia-nvjitlink-cu12==12.9.86 +nvidia-nvtx-cu12==12.1.105 +nvitop==1.6.0 +objaverse==0.1.7 +omegaconf==2.3.0 +onnxruntime==1.23.2 +open3d==0.19.0 +open_clip_torch==3.2.0 +openai==2.21.0 +opencensus-context==0.1.3 +opencensus==0.11.4 +opencv-python-headless==4.10.0.84 +opencv-python==4.12.0.88 +opentelemetry-api==1.38.0 +opentelemetry-exporter-prometheus==0.59b0 +opentelemetry-proto==1.38.0 +opentelemetry-sdk==1.38.0 +opentelemetry-semantic-conventions==0.59b0 +orjson==3.11.4 +packaging==24.2 +pandas==2.3.3 +parso==0.8.5 +pathspec==1.0.3 +pccm==0.4.16 +peft==0.18.0 +pexpect==4.9.0 +pillow==11.3.0 +pillow_heif==1.1.1 +platformdirs==4.5.0 +plotly==6.5.0 +pluggy==1.6.0 +plyfile==1.1.3 +pooch==1.8.2 +portalocker==3.2.0 +poselib==2.0.2 +prettytable==3.17.0 +proglog==0.1.12 +prometheus_client==0.23.1 +prompt_toolkit==3.0.52 +propcache==0.4.1 +proto-plus==1.26.1 +protobuf==6.33.1 +psutil==5.9.8 +ptyprocess==0.7.0 +pure_eval==0.2.3 +py-cpuinfo==9.0.0 +py-spy==0.4.1 +pyarrow==22.0.0 +pyasn1==0.6.1 +pyasn1_modules==0.4.2 +pybind11==3.0.1 +pyceres==2.4 +pycolmap==3.11.1 +pycpd==2.0.0 +pydantic==2.10.6 +pydantic_core==2.27.2 +pydub==0.25.1 +pygltflib==1.16.5 +pykdtree==1.4.3 +pymeshfix==0.17.1 +pymeshlab==2025.7 +pyparsing==3.2.5 +pyquaternion==0.9.9 +python-dateutil==2.9.0.post0 +python-multipart==0.0.20 +pytorch-lightning==2.6.0 +pytz==2025.2 +pyvista==0.46.4 +pyzmq==27.1.0 +ray==2.52.1 +referencing==0.37.0 +regex==2025.11.3 +rembg==2.0.68 +requests==2.32.5 +retrying==1.4.2 +rich==14.2.0 +roma==1.5.4 +rosbags==0.11.0 +rpds-py==0.30.0 +rsa==4.9.1 +ruamel.yaml.clib==0.2.15 +ruamel.yaml==0.18.6 +ruff==0.14.7 +safehttpx==0.1.7 +safetensors==0.7.0 +sam2==0.1.0 +scikit-image==0.25.2 +scikit-learn==1.7.2 +scipy==1.16.3 +scooby==0.11.0 +seaborn==0.13.2 +segment_anything @ git+https://github.com/facebookresearch/segment-anything.git@dca509fe793f601edb92606367a655c15ac00fdf +semantic-version==2.10.0 +shellingham==1.5.4 +simsimd==6.5.3 +six==1.17.0 +smart_open==7.5.0 +sniffio==1.3.1 +socksio==1.0.0 +soupsieve==2.8 +spaces==0.43.0 +spconv-cu121==2.3.7 +stack-data==0.6.3 +starlette==0.50.0 +stringzilla==4.4.0 +sympy==1.14.0 +termcolor==3.2.0 +texttable==1.7.0 +threadpoolctl==3.6.0 +tifffile==2025.10.16 +timm==1.0.22 +tokenizers==0.22.1 +tomlkit==0.13.3 +torchmetrics==1.8.2 +tornado==6.5.4 +tqdm==4.67.1 +traitlets==5.14.3 +transformations==2024.6.1 +transformers==4.57.3 +trimesh==4.5.3 +triton==3.0.0 +trove-classifiers==2026.1.14.14 +typeguard==4.5.2 +typer==0.20.0 +typing-inspect==0.9.0 +typing_extensions==4.15.0 +tyro==1.0.2 +tzdata==2025.2 +urllib3==2.5.0 +usd-core==25.11 +uvicorn==0.38.0 +virtualenv==20.35.4 +visdom==0.2.4 +vtk==9.5.2 +wadler_lindig==0.1.7 +warp-lang==1.10.1 +wcwidth==0.2.14 +websocket-client==1.9.0 +websockets==15.0.1 +widgetsnbextension==4.0.15 +wrapt==2.0.1 +xatlas==0.0.11 +xformers==0.0.28 +yarl==1.22.0 +zipp==3.23.0 +zstandard==0.25.0 diff --git a/OVOW/environment/requirements-sam3.txt b/OVOW/environment/requirements-sam3.txt new file mode 100644 index 0000000000000000000000000000000000000000..faecf8a2b29095bee0ed585a06740349daac7db6 --- /dev/null +++ b/OVOW/environment/requirements-sam3.txt @@ -0,0 +1,60 @@ +# OVOW sam3 环境 — 可 pip 安装依赖。SAM3 包从源码 editable 安装:pip install -e third_party/sam3 +# torch 带 +cu118 本地版本号,必须从 PyTorch 官方 index 安装(下一行提供)。 +--extra-index-url https://download.pytorch.org/whl/cu118 +packaging +Jinja2==3.1.6 +MarkupSafe==2.1.5 +PyYAML==6.0.3 +anyio==4.12.1 +certifi==2026.1.4 +charset-normalizer==3.4.4 +click==8.3.1 +decord==0.6.0 +einops==0.8.2 +filelock==3.20.0 +fsspec==2025.12.0 +ftfy==6.1.1 +h11==0.16.0 +hf-xet==1.2.0 +httpcore==1.0.9 +httpx==0.28.1 +huggingface_hub==1.3.5 +idna==3.11 +iopath==0.1.10 +modelscope==1.34.0 +mpmath==1.3.0 +networkx==3.6.1 +numpy==1.26.4 +nvidia-cublas-cu11==11.11.3.6 +nvidia-cuda-cupti-cu11==11.8.87 +nvidia-cuda-nvrtc-cu11==11.8.89 +nvidia-cuda-runtime-cu11==11.8.89 +nvidia-cudnn-cu11==9.1.0.70 +nvidia-cufft-cu11==10.9.0.58 +nvidia-curand-cu11==10.3.0.86 +nvidia-cusolver-cu11==11.4.1.48 +nvidia-cusparse-cu11==11.7.5.86 +nvidia-nccl-cu11==2.21.5 +nvidia-nvtx-cu11==11.8.86 +opencv-python==4.11.0.86 +pillow==12.0.0 +portalocker==3.2.0 +psutil==7.2.2 +pycocotools==2.0.11 +regex==2026.1.15 +requests==2.32.5 +safetensors==0.7.0 +setuptools==80.10.1 +shellingham==1.5.4 +sympy==1.14.0 +timm==1.0.24 +torch==2.7.0+cu118 +torchaudio==2.7.0+cu118 +torchvision==0.22.0+cu118 +tqdm==4.67.1 +triton==3.3.0 +typer-slim==0.21.1 +typing_extensions==4.15.0 +urllib3==2.6.3 +wcwidth==0.5.3 +wheel==0.46.3 diff --git a/OVOW/examples/_common.sh b/OVOW/examples/_common.sh new file mode 100644 index 0000000000000000000000000000000000000000..a2990d3908536061d4b9928fc341ca71c53014f8 --- /dev/null +++ b/OVOW/examples/_common.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash + +ovow_preflight() { + local need_motion="${1:-0}" fail=0 v + + if [[ "${QWEN_BACKEND:-api}" == "api" && -z "$(ovow_api_key)" ]]; then + echo "[预检失败] step1 需要 Qwen 标注:在 .env 里填 DASHSCOPE_API_KEY(或 APIKEY_FILE)," + echo " 或设 QWEN_BACKEND=\"local\" 走本地 Qwen3-VL(见 README「故障排查」)。" + fail=1 + fi + + if ! command -v "$BLENDER_BIN" >/dev/null 2>&1 && [[ ! -x "$BLENDER_BIN" ]]; then + echo "[预检失败] 找不到 blender(合成/渲染步骤需要):装 blender 或在 .env 设 BLENDER_BIN。" + fail=1 + fi + + local pys=(OPG_PY SAM3_PY) + [[ "$need_motion" == "1" ]] && pys+=(MOTION_PY) + for v in "${pys[@]}"; do + if [[ ! -x "${!v}" ]]; then + echo "[预检失败] $v=${!v} 不是可执行的 python:确认 conda 环境已建好且 .env 填的是真实路径。" + fail=1 + fi + done + + if [[ ! -f "$SAM3_CKPT" ]]; then + echo "[预检失败] SAM3 权重缺失:$SAM3_CKPT(先跑 bash download_ckpts.sh,gated 仓库需 HF 登录)。" + fail=1 + fi + + if [[ "$need_motion" == "1" ]]; then + local motion_ckpt_dir="$MOTION324_DIR/experiments/checkpoints" + if ! compgen -G "$motion_ckpt_dir/ckpt_*.pt" >/dev/null 2>&1; then + echo "[预检失败] Motion324 权重缺失:$motion_ckpt_dir/ckpt_*.pt(deform 步骤 step4 需要;" + echo " 先跑 bash download_ckpts.sh)。" + fail=1 + fi + fi + + return "$fail" +} + +ovow_verify_artifacts() { + local out="$1" ext="$2" missing=0 name found sz + local names=( + "scene_anim_blender_physics_with_deform.glb" + "fullscene_deform_objseq_white_left_rgb_right_split10_h264.$ext" + "fullscene_deform_objseq_textured_left_rgb_right_split10_h264.$ext" + ) + + echo "--- 产物校验($out)---" + for name in "${names[@]}"; do + found="$(find "$out" -type f -name "$name" -size +1k 2>/dev/null | sort | tail -1)" + if [[ -n "$found" ]]; then + sz="$(du -h "$found" | cut -f1)" + echo " [OK] $name ($sz)" + else + echo " [缺失] $name" + missing=$((missing + 1)) + fi + done + + if [[ "$missing" -eq 0 ]]; then + echo "--- 三个关键产物齐全,链路跑通。" + return 0 + fi + echo "--- $missing 个产物缺失或为空:退出码为 0 也不算跑通,按上方日志定位。" + return 1 +} diff --git a/OVOW/examples/images/desk_banana.png b/OVOW/examples/images/desk_banana.png new file mode 100644 index 0000000000000000000000000000000000000000..d1659dcfd38987f803a77abae099a6b5bc25a72f --- /dev/null +++ b/OVOW/examples/images/desk_banana.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5150d3968c3019656956d986c03c5828b951860a07182ca39e593204e50d513a +size 2211448 diff --git a/OVOW/examples/smoke_test.sh b/OVOW/examples/smoke_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2efaf0c340298100777dd32ca9ea6e29bea02107 --- /dev/null +++ b/OVOW/examples/smoke_test.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -uo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "$HERE/configs/paths.sh" +source "$HERE/examples/_common.sh" + +IMG="$HERE/examples/images/desk_banana.png" +OUT="$HERE/outputs/smoke" + +ovow_preflight 0 || exit 1 + +echo "=== OVOW smoke test (image): $IMG ===" +bash "$HERE/scripts/run_image.sh" --image "$IMG" --out "$OUT" 1 2 6 7 14 17 18 +rc=$? + +if [[ $rc -ne 0 ]]; then + echo "=== 失败(exit $rc):按上方日志定位;常见问题见 README「故障排查」 ===" + exit $rc +fi + +ovow_verify_artifacts "$OUT" png || exit 1 +echo "=== 完成:产物在 $OUT/(运行目录为 image_pipeline_<时间戳>/desk_banana/)===" diff --git a/OVOW/examples/smoke_test_video.sh b/OVOW/examples/smoke_test_video.sh new file mode 100644 index 0000000000000000000000000000000000000000..43dffd40a5a95305baae9f33e1c259c5039bb8d0 --- /dev/null +++ b/OVOW/examples/smoke_test_video.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +set -uo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "$HERE/configs/paths.sh" +source "$HERE/examples/_common.sh" + +VIDEO="${1:-$HERE/examples/videos/instance_000008.mp4}" +OUT="$HERE/outputs/smoke_video" + +[[ -f "$VIDEO" ]] || { echo "ERROR: video not found: $VIDEO" >&2; exit 1; } +NAME="$(basename "${VIDEO%.*}")" + +ovow_preflight 1 || exit 1 + +echo "=== OVOW smoke test (video): $VIDEO ===" +bash "$HERE/scripts/run_video.sh" --name "$NAME" --video "$VIDEO" --out "$OUT" +rc=$? + +if [[ $rc -ne 0 ]]; then + echo "=== 失败(exit $rc):按上方日志定位;常见问题见 README「故障排查」 ===" + exit $rc +fi + +ovow_verify_artifacts "$OUT" mp4 || exit 1 +echo "=== 完成:产物在 $OUT/ws/${NAME}_<时间戳>/ ===" diff --git a/OVOW/examples/videos/instance_000008.mp4 b/OVOW/examples/videos/instance_000008.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..17c91576ff9a87720db4a2da2afa276bc62d8502 --- /dev/null +++ b/OVOW/examples/videos/instance_000008.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ac5ec5dd13551bd598795b23db87174033bad2a581144c908d5393d2b734f78 +size 220732 diff --git a/OVOW/examples/videos/pipelinecase-input.mp4 b/OVOW/examples/videos/pipelinecase-input.mp4 new file mode 100644 index 0000000000000000000000000000000000000000..365e467d175c25879e7aaaa9e3f218cefb860e83 --- /dev/null +++ b/OVOW/examples/videos/pipelinecase-input.mp4 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ccf998147a556d89a72eff2fd3941245a85804bdcb4fdb5dfdf98531debe6506 +size 1010625 diff --git a/OVOW/masking/download_qwen3_vl_8b_hf_mirror.sh b/OVOW/masking/download_qwen3_vl_8b_hf_mirror.sh new file mode 100644 index 0000000000000000000000000000000000000000..82e2c8b7556f1380e830ba7682644a7a050068c6 --- /dev/null +++ b/OVOW/masking/download_qwen3_vl_8b_hf_mirror.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash + + +set -e + +MODEL_ID="Qwen/Qwen3-VL-8B-Instruct" +TARGET_DIR=${1:-"./model/Qwen3-VL-8B-Instruct"} + +echo "Model ID : ${MODEL_ID}" +echo "Target dir : ${TARGET_DIR}" + +mkdir -p "${TARGET_DIR}" + +echo "[1/3] 安装 huggingface_hub CLI(如已安装会自动跳过)..." +if command -v uv >/dev/null 2>&1; then + UV_HTTP_TIMEOUT=${UV_HTTP_TIMEOUT:-300} uv pip install -U "huggingface-hub==0.36.0" \ + -i https://pypi.tuna.tsinghua.edu.cn/simple +else + python -m pip install -U "huggingface-hub==0.36.0" \ + -i https://pypi.tuna.tsinghua.edu.cn/simple +fi + +echo "[2/3] 配置 HF 镜像..." +export HF_ENDPOINT=${HF_ENDPOINT:-https://hf-mirror.com} +export HF_HUB_ENABLE_HF_TRANSFER=1 + +echo "HF_ENDPOINT: ${HF_ENDPOINT}" +echo "[3/3] 开始下载模型到 ${TARGET_DIR} ..." + +huggingface-cli download "${MODEL_ID}" \ + --local-dir "${TARGET_DIR}" \ + --local-dir-use-symlinks False \ + --resume-download + +echo "完成!模型已保存到: ${TARGET_DIR}" diff --git a/OVOW/masking/grsam_from_label_json.py b/OVOW/masking/grsam_from_label_json.py new file mode 100644 index 0000000000000000000000000000000000000000..2031e361a2ff5d753f7469e6cb7cb90187af5991 --- /dev/null +++ b/OVOW/masking/grsam_from_label_json.py @@ -0,0 +1,586 @@ +#!/usr/bin/env python +""" +读取 label.json(labels + image),调用 GroundingDINO + SAM2 分割每个 label 的所有实例, +按 label_01/label_02/... 命名 mask 文件,写入 masks/,并生成/写回 scene.json。 +""" + +import argparse +import json +import re +from pathlib import Path +from typing import List, Optional + +import cv2 +import numpy as np +import torch +from PIL import Image +from torchvision import transforms as TF +from torchvision.ops import box_convert + +from sam2.build_sam import build_sam2 +from sam2.sam2_image_predictor import SAM2ImagePredictor +from grounding_dino.groundingdino.util.inference import load_model, predict + + +def find_single_image_file(scene_dir: Path) -> Optional[str]: + exts = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG"} + candidates = [p.name for p in scene_dir.iterdir() if p.is_file() and p.suffix in exts] + if len(candidates) == 1: + return candidates[0] + return None + + +def load_image_for_models(image_path: Path, mode: str = "crop", target_size: int = 518): + if mode not in ("crop", "pad"): + raise ValueError("mode 必须是 'crop' 或 'pad'") + + img = Image.open(image_path) + if img.mode == "RGBA": + bg = Image.new("RGBA", img.size, (255, 255, 255, 255)) + img = Image.alpha_composite(bg, img) + img = img.convert("RGB") + + width, height = img.size + + if mode == "pad": + if width >= height: + new_width = target_size + new_height = round(height * (new_width / width) / 14) * 14 + else: + new_height = target_size + new_width = round(width * (new_height / height) / 14) * 14 + else: + new_width = target_size + new_height = round(height * (new_width / width) / 14) * 14 + + img = img.resize((new_width, new_height), Image.Resampling.BICUBIC) + img_tensor = TF.ToTensor()(img) + + if mode == "crop" and new_height > target_size: + start_y = (new_height - target_size) // 2 + img_tensor = img_tensor[:, start_y : start_y + target_size, :] + + if mode == "pad": + h_padding = target_size - img_tensor.shape[1] + w_padding = target_size - img_tensor.shape[2] + if h_padding > 0 or w_padding > 0: + pad_top = h_padding // 2 + pad_bottom = h_padding - pad_top + pad_left = w_padding // 2 + pad_right = w_padding - pad_left + img_tensor = torch.nn.functional.pad( + img_tensor, + (pad_left, pad_right, pad_top, pad_bottom), + mode="constant", + value=1.0, + ) + + image_np = (img_tensor.permute(1, 2, 0).numpy() * 255).astype(np.uint8) + image_bgr = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR) + h, w = img_tensor.shape[1], img_tensor.shape[2] + return img_tensor, image_bgr, h, w + + +def ensure_mask_dir(scene_dir: Path, mask_dir_name: str) -> Path: + mask_dir = scene_dir / mask_dir_name + mask_dir.mkdir(parents=True, exist_ok=True) + return mask_dir + + +def parse_scene_spec(spec: str) -> List[int]: + ids: List[int] = [] + for chunk in spec.split(","): + chunk = chunk.strip() + if not chunk: + continue + if "-" in chunk: + a, b = chunk.split("-", 1) + start, end = int(a), int(b) + if end < start: + start, end = end, start + ids.extend(range(start, end + 1)) + else: + ids.append(int(chunk)) + return sorted(set(ids)) + + +def normalize_phrase(text: str) -> str: + t = text.strip().lower() + while t.endswith((".", ",", ";", " ")): + t = t[:-1] + return t + + +def _as_int(value, default=0) -> int: + try: + return int(value) + except Exception: + return default + + +def parse_labels_and_counts(data: dict): + labels: List[str] = [] + label_counts = {} + label_prompts = {} + + def add_label(name_raw, num_raw=None, prompt_raw=None): + name = normalize_phrase(str(name_raw)) + if not name: + return + labels.append(name) + if num_raw is not None: + num = _as_int(num_raw, default=0) + if num > 0: + label_counts[name] = max(label_counts.get(name, 0), num) + if prompt_raw: + label_prompts.setdefault(name, str(prompt_raw)) + + objects = data.get("objects", []) + if isinstance(objects, list): + for obj in objects: + if isinstance(obj, dict): + add_label( + obj.get("name") or obj.get("label") or obj.get("prompt") or "", + obj.get("num") or obj.get("count") or obj.get("instances"), + obj.get("prompt") or obj.get("name"), + ) + elif isinstance(obj, str): + add_label(obj) + + label_counts_raw = data.get("label_counts", {}) + if isinstance(label_counts_raw, dict): + for k, v in label_counts_raw.items(): + add_label(k, v, None) + + label_items = data.get("labels", []) + if isinstance(label_items, list): + for item in label_items: + if isinstance(item, dict): + add_label( + item.get("name") or item.get("label") or item.get("prompt") or "", + item.get("num") or item.get("count") or item.get("instances"), + item.get("prompt") or item.get("name"), + ) + else: + add_label(item) + + return labels, label_counts, label_prompts + + +def sanitize_id(text: str) -> str: + base = normalize_phrase(text) + base = re.sub(r"[^a-z0-9]+", "_", base).strip("_") + return base or "obj" + +def load_binary_mask(mask_path: Path): + mask = cv2.imread(str(mask_path), cv2.IMREAD_GRAYSCALE) + if mask is None: + return None + return mask > 0 + +def mask_iou(a, b) -> float: + inter = (a & b).sum() + union = (a | b).sum() + return float(inter) / float(union) if union else 0.0 + +def dedupe_objects_by_iou(objects, scene_dir: Path, iou_thresh: float, keep_mode: str): + if iou_thresh <= 0: + return objects + kept = [] + kept_masks = [] + kept_scores = [] + kept_areas = [] + for obj in objects: + mask_path = scene_dir / obj["mask"] + mask = load_binary_mask(mask_path) + if mask is None: + continue + score = float(obj.get("_score", 0.0)) + area = int(mask.sum()) + match_idx = None + for i, km in enumerate(kept_masks): + if mask_iou(mask, km) >= iou_thresh: + match_idx = i + break + if match_idx is None: + kept.append(obj) + kept_masks.append(mask) + kept_scores.append(score) + kept_areas.append(area) + else: + if keep_mode == "area": + better = area > kept_areas[match_idx] + else: + better = score > kept_scores[match_idx] + if better: + kept[match_idx] = obj + kept_masks[match_idx] = mask + kept_scores[match_idx] = score + kept_areas[match_idx] = area + return kept + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Grounded SAM2 根据 label.json 分割物体并写回 scene.json(多实例)" + ) + parser.add_argument("--scene-dir", type=Path, help="单个 scene 目录") + parser.add_argument( + "--scene-range", + type=str, + help='批量模式,形如 "1-4,6,8"(按 scene_{:02d} 命名)', + ) + parser.add_argument( + "--root-dir", + type=Path, + default=Path(__file__).resolve().parents[2] / "data_pose" / "scenes", + help="场景根目录(默认 data_pose/scenes)", + ) + parser.add_argument( + "--label-json-name", + type=str, + default="label.json", + help="label.json 文件名(默认 label.json)", + ) + parser.add_argument( + "--sam2-ckpt", + type=Path, + default=Path("checkpoints/sam2.1_hiera_large.pt"), + help="SAM2 checkpoint 路径", + ) + parser.add_argument( + "--sam2-config", + type=Path, + default=Path("configs/sam2.1/sam2.1_hiera_l.yaml"), + help="SAM2 config 路径", + ) + parser.add_argument( + "--gdino-config", + type=Path, + default=Path("grounding_dino/groundingdino/config/GroundingDINO_SwinB_cfg.py"), + help="GroundingDINO 配置", + ) + parser.add_argument( + "--gdino-ckpt", + type=Path, + default=Path("gdino_checkpoints/groundingdino_swinb_cogcoor.pth"), + help="GroundingDINO checkpoint", + ) + parser.add_argument("--box-threshold", type=float, default=0.2, help="GroundingDINO box threshold") + parser.add_argument("--text-threshold", type=float, default=0.2, help="GroundingDINO text threshold") + parser.add_argument( + "--mask-dir-name", + type=str, + default="masks", + help="mask 输出目录名(相对 scene_dir)", + ) + parser.add_argument( + "--target-size", + type=int, + default=1024, + help="检测/分割输入的目标分辨率(默认 1024)", + ) + parser.add_argument( + "--merge-label-masks", + action=argparse.BooleanOptionalAction, + default=True, + help="每个 label 将所有实例 mask 合并为一张(默认开启)", + ) + parser.add_argument( + "--only-existing-masks", + action="store_true", + help="仅使用已存在的 mask 文件生成 scene.json,不进行检测/分割(默认关闭)", + ) + parser.add_argument( + "--dedupe-iou", + type=float, + default=0.0, + help="跨 label 去重阈值(mask IoU),0 表示关闭", + ) + parser.add_argument( + "--dedupe-keep", + type=str, + default="score", + choices=["score", "area"], + help="去重冲突时保留的策略:score 或 area", + ) + parser.add_argument( + "--max-instances-per-label", + type=int, + default=50, + help="每个 label 最多输出多少个实例(默认 50)", + ) + parser.add_argument( + "--dump-preprocessed", + action="store_true", + help="保存预处理后的检测输入,便于调试(默认关闭)", + ) + + args = parser.parse_args() + + scene_dirs: List[Path] = [] + if args.scene_dir: + scene_dirs = [args.scene_dir.resolve()] + if args.scene_range: + for sid in parse_scene_spec(args.scene_range): + scene_dirs.append(args.root_dir / f"scene_{sid:02d}") + if not scene_dirs: + raise ValueError("必须提供 --scene-dir 或 --scene-range") + + device = "cuda" if torch.cuda.is_available() else "cpu" + gdino = load_model( + model_config_path=str(args.gdino_config), + model_checkpoint_path=str(args.gdino_ckpt), + device=device, + ).to(device) + sam2_config = args.sam2_config + if sam2_config.is_absolute(): + marker = "/sam2/configs/" + s = str(sam2_config) + if marker in s: + sam2_config = Path("configs") / s.split(marker, 1)[1] + sam2_model = build_sam2( + str(sam2_config), + str(args.sam2_ckpt), + device=device, + ).to(device) + sam2_predictor = SAM2ImagePredictor(sam2_model) + + for scene_dir in scene_dirs: + if not scene_dir.is_dir(): + print(f"[WARN] scene 目录不存在,跳过: {scene_dir}") + continue + + label_json = scene_dir / args.label_json_name + if not label_json.is_file(): + print(f"[WARN] label.json 不存在,跳过: {label_json}") + continue + + with label_json.open("r", encoding="utf-8") as f: + data = json.load(f) + + image_name = data.get("image") or find_single_image_file(scene_dir) + labels, label_counts, label_prompts = parse_labels_and_counts(data) + if not image_name: + print(f"[WARN] 未找到场景图片,跳过: {scene_dir}") + continue + if not labels: + print(f"[WARN] label.json labels 为空,跳过: {scene_dir}") + continue + + uniq = [] + seen = set() + for lbl in labels: + t = normalize_phrase(str(lbl)) + if not t or t in seen: + continue + seen.add(t) + uniq.append(t) + labels = uniq + if label_counts: + label_counts = {k: v for k, v in label_counts.items() if k in set(labels)} + + image_path = scene_dir / image_name + if not image_path.is_file(): + print(f"[WARN] 场景图片不存在,跳过: {image_path}") + continue + + image_tensor, image_bgr, h, w = load_image_for_models( + image_path, target_size=args.target_size + ) + if args.dump_preprocessed: + debug_dir = scene_dir / "debug_inputs" + debug_dir.mkdir(exist_ok=True, parents=True) + dump_name = debug_dir / f"{scene_dir.name}_{image_path.stem}_preprocessed.png" + cv2.imwrite(str(dump_name), image_bgr) + print(f"[DEBUG] 已保存预处理图像: {dump_name}") + sam2_predictor.set_image(image_bgr) + + ensure_mask_dir(scene_dir, args.mask_dir_name) + + print(f"\n===== 处理 {scene_dir.name} =====") + + objects: List[dict] = [] + if args.only_existing_masks: + mask_dir = scene_dir / args.mask_dir_name + for lbl in labels: + base_id = sanitize_id(lbl) + max_n = max(1, int(args.max_instances_per_label)) + if args.merge_label_masks: + mask_path = mask_dir / f"{base_id}.png" + if not mask_path.exists(): + print(f"[WARN] 缺少已有 mask:{lbl}") + continue + mask_rel = f"{args.mask_dir_name}/{base_id}.png" + objects.append( + { + "id": base_id, + "name": lbl, + "prompt": lbl, + "is_occluded": False, + "mask": str(mask_rel), + "_score": 0.0, + } + ) + print(f"[OK] {lbl} -> {mask_rel} (existing)") + else: + files = sorted(mask_dir.glob(f"{base_id}_*.png")) + if not files: + print(f"[WARN] 缺少已有 mask:{lbl}") + continue + for mask_path in files[:max_n]: + inst_id = mask_path.stem + mask_rel = f"{args.mask_dir_name}/{inst_id}.png" + objects.append( + { + "id": inst_id, + "name": lbl, + "prompt": lbl, + "is_occluded": False, + "mask": str(mask_rel), + "_score": 0.0, + } + ) + print(f"[OK] {lbl} -> {mask_rel} (existing)") + + if args.dedupe_iou > 0 and objects: + objects = dedupe_objects_by_iou(objects, scene_dir, args.dedupe_iou, args.dedupe_keep) + if not objects: + print(f"[WARN] {scene_dir} 未生成任何 objects") + continue + + scene_json = scene_dir / "scene.json" + for obj in objects: + obj.pop("_score", None) + with scene_json.open("w", encoding="utf-8") as f: + json.dump({"image": image_name, "objects": objects}, f, ensure_ascii=False, indent=2) + print(f"[DONE] 已更新 {scene_json}") + continue + + for lbl in labels: + prompt = label_prompts.get(lbl, lbl) + caption = str(prompt).lower().strip() + if not caption.endswith("."): + caption = caption + "." + + boxes, confidences, _labels = predict( + model=gdino, + image=image_tensor, + caption=caption, + box_threshold=args.box_threshold, + text_threshold=args.text_threshold, + device=device, + ) + if boxes is None or len(boxes) == 0: + print(f"[WARN] GroundingDINO 未检测到:{lbl}") + continue + + keep = confidences >= args.box_threshold + if keep.numel() != 0: + boxes = boxes[keep] + confidences = confidences[keep] + if boxes is None or len(boxes) == 0: + print(f"[WARN] 过滤后无有效框:{lbl}") + continue + + boxes = boxes * torch.tensor([w, h, w, h], device=boxes.device) + boxes_xyxy = box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xyxy").cpu().numpy() + + order = torch.argsort(confidences, descending=True) + boxes_xyxy = boxes_xyxy[order.cpu().numpy()] + conf_sorted = confidences[order].detach().cpu().numpy() + + base_id = sanitize_id(lbl) + max_n = max(1, int(args.max_instances_per_label)) + if label_counts and lbl in label_counts: + max_n = min(max_n, max(1, int(label_counts[lbl]))) + + if args.merge_label_masks: + merged = None + kept = 0 + best_score = 0.0 + for inst_idx, box_xyxy in enumerate(boxes_xyxy, start=1): + if inst_idx > max_n: + break + if inst_idx - 1 < len(conf_sorted): + best_score = max(best_score, float(conf_sorted[inst_idx - 1])) + masks, scores, _ = sam2_predictor.predict( + point_coords=None, + point_labels=None, + box=box_xyxy, + multimask_output=False, + ) + mask = masks[0].astype(np.uint8) * 255 + if merged is None: + merged = mask.copy() + else: + merged = np.maximum(merged, mask) + kept += 1 + + if merged is None: + print(f"[WARN] {lbl} 未生成任何 mask") + continue + + inst_id = base_id + mask_rel = f"{args.mask_dir_name}/{inst_id}.png" + mask_path = scene_dir / mask_rel + mask_path.parent.mkdir(parents=True, exist_ok=True) + cv2.imwrite(str(mask_path), merged) + + objects.append( + { + "id": inst_id, + "name": lbl, + "prompt": lbl, + "is_occluded": False, + "mask": str(mask_rel), + "_score": best_score, + } + ) + print(f"[OK] {lbl} -> {mask_rel} (merged {kept})") + else: + for inst_idx, box_xyxy in enumerate(boxes_xyxy, start=1): + if inst_idx > max_n: + break + masks, scores, _ = sam2_predictor.predict( + point_coords=None, + point_labels=None, + box=box_xyxy, + multimask_output=False, + ) + mask = masks[0].astype(np.uint8) * 255 + + inst_id = f"{base_id}_{inst_idx:02d}" + mask_rel = f"{args.mask_dir_name}/{inst_id}.png" + mask_path = scene_dir / mask_rel + mask_path.parent.mkdir(parents=True, exist_ok=True) + cv2.imwrite(str(mask_path), mask) + + objects.append( + { + "id": inst_id, + "name": lbl, + "prompt": lbl, + "is_occluded": False, + "mask": str(mask_rel), + "_score": float(conf_sorted[inst_idx - 1]) if inst_idx - 1 < len(conf_sorted) else 0.0, + } + ) + print(f"[OK] {lbl} -> {mask_rel}") + + if args.dedupe_iou > 0 and objects: + objects = dedupe_objects_by_iou(objects, scene_dir, args.dedupe_iou, args.dedupe_keep) + if not objects: + print(f"[WARN] {scene_dir} 未生成任何 objects") + continue + + scene_json = scene_dir / "scene.json" + for obj in objects: + obj.pop("_score", None) + with scene_json.open("w", encoding="utf-8") as f: + json.dump({"image": image_name, "objects": objects}, f, ensure_ascii=False, indent=2) + print(f"[DONE] 已更新 {scene_json}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/masking/grsam_from_scene_json.py b/OVOW/masking/grsam_from_scene_json.py new file mode 100644 index 0000000000000000000000000000000000000000..7337ac8d7f01b31e04b1cd59060a5f529e277d02 --- /dev/null +++ b/OVOW/masking/grsam_from_scene_json.py @@ -0,0 +1,405 @@ +#!/usr/bin/env python +""" +读取 scene.json(包含 objects + prompt),调用 GroundingDINO + SAM2 分割每个物体, +按 object 的 id 命名 mask 文件,写入 masks/,并回填 scene.json 的 mask 字段。 + +示例: + conda activate qwen + python Grounded_SAM2/qwen/grsam_from_scene_json.py \ + --scene-dir data_pose/scenes/scene_12 +""" + +import argparse +import json +from pathlib import Path +from typing import List, Optional, Tuple + +import cv2 +import numpy as np +import torch +from PIL import Image +from torchvision import transforms as TF +from torchvision.ops import box_convert + +from sam2.build_sam import build_sam2 +from sam2.sam2_image_predictor import SAM2ImagePredictor +from grounding_dino.groundingdino.util.inference import load_model, predict + + +def find_single_image_file(scene_dir: Path) -> Optional[str]: + exts = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG"} + candidates = [p.name for p in scene_dir.iterdir() if p.is_file() and p.suffix in exts] + if len(candidates) == 1: + return candidates[0] + return None + + +def load_image_for_models(image_path: Path, mode: str = "crop"): + """与 segment.py 一致的预处理:宽度 518px,保持长宽比并根据模式裁剪/填充。""" + if mode not in ("crop", "pad"): + raise ValueError("mode 必须是 'crop' 或 'pad'") + + img = Image.open(image_path) + if img.mode == "RGBA": + bg = Image.new("RGBA", img.size, (255, 255, 255, 255)) + img = Image.alpha_composite(bg, img) + img = img.convert("RGB") + + target_size = 518 + to_tensor = TF.ToTensor() + width, height = img.size + + if mode == "pad": + if width >= height: + new_width = target_size + new_height = round(height * (new_width / width) / 14) * 14 + else: + new_height = target_size + new_width = round(width * (new_height / height) / 14) * 14 + else: + new_width = target_size + new_height = round(height * (new_width / width) / 14) * 14 + + img = img.resize((new_width, new_height), Image.Resampling.BICUBIC) + img_tensor = to_tensor(img) + + if mode == "crop" and new_height > target_size: + start_y = (new_height - target_size) // 2 + img_tensor = img_tensor[:, start_y : start_y + target_size, :] + + if mode == "pad": + h_padding = target_size - img_tensor.shape[1] + w_padding = target_size - img_tensor.shape[2] + if h_padding > 0 or w_padding > 0: + pad_top = h_padding // 2 + pad_bottom = h_padding - pad_top + pad_left = w_padding // 2 + pad_right = w_padding - pad_left + img_tensor = torch.nn.functional.pad( + img_tensor, + (pad_left, pad_right, pad_top, pad_bottom), + mode="constant", + value=1.0, + ) + + image_tensor = img_tensor + image_np = (image_tensor.permute(1, 2, 0).numpy() * 255).astype(np.uint8) + image_bgr = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR) + h, w = image_tensor.shape[1], image_tensor.shape[2] + return image_tensor, image_bgr, h, w + + +def ensure_mask_dir(scene_dir: Path, mask_dir_name: str) -> Path: + mask_dir = scene_dir / mask_dir_name + mask_dir.mkdir(parents=True, exist_ok=True) + return mask_dir + + +def parse_scene_spec(spec: str) -> List[int]: + ids: List[int] = [] + for chunk in spec.split(","): + chunk = chunk.strip() + if not chunk: + continue + if "-" in chunk: + a, b = chunk.split("-", 1) + start, end = int(a), int(b) + if end < start: + start, end = end, start + ids.extend(range(start, end + 1)) + else: + ids.append(int(chunk)) + return sorted(set(ids)) + + +def normalize_phrase(text: str) -> str: + """小写并去掉尾部标点,便于匹配 GDINO 返回的 label。""" + t = text.strip().lower() + while t.endswith((".", ",", ";", " ")): + t = t[:-1] + return t + + +def build_joint_caption(objects: List[dict]) -> Tuple[str, List[str]]: + """ + 把所有 object.prompt 拼成一个 GDINO caption,并返回标准化后的子句列表。 + - 子句形如 "red car on the road" + - caption 形如 "red car on the road. house on the left." + """ + clauses = [] + for obj in objects: + p = obj.get("prompt") or obj.get("name") or "" + p = p.strip() + if not p: + continue + clauses.append(p) + normalized_clauses = [normalize_phrase(c) for c in clauses] + caption = ". ".join(normalized_clauses) + if not caption.endswith("."): + caption += "." + return caption, normalized_clauses + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Grounded SAM2 根据 scene.json 的 prompt 分割物体并写回 mask 路径" + ) + parser.add_argument( + "--scene-dir", + type=Path, + help="单个 scene 目录", + ) + parser.add_argument( + "--scene-range", + type=str, + help='批量模式,形如 "1-4,6,8"(按 scene_{:02d} 命名)', + ) + parser.add_argument( + "--root-dir", + type=Path, + default=Path(__file__).resolve().parents[2] / "data_pose" / "scenes", + help="场景根目录(默认 data_pose/scenes)", + ) + parser.add_argument( + "--sam2-ckpt", + type=Path, + default=Path("checkpoints/sam2.1_hiera_large.pt"), + help="SAM2 checkpoint 路径", + ) + parser.add_argument( + "--sam2-config", + type=Path, + default=Path("configs/sam2.1/sam2.1_hiera_l.yaml"), + help="SAM2 config 路径", + ) + parser.add_argument( + "--gdino-config", + type=Path, + default=Path("grounding_dino/groundingdino/config/GroundingDINO_SwinB_cfg.py"), + help="GroundingDINO 配置", + ) + parser.add_argument( + "--gdino-ckpt", + type=Path, + default=Path("gdino_checkpoints/groundingdino_swinb_cogcoor.pth"), + help="GroundingDINO checkpoint", + ) + parser.add_argument( + "--box-threshold", + type=float, + default=0.2, + help="GroundingDINO box threshold", + ) + parser.add_argument( + "--text-threshold", + type=float, + default=0.2, + help="GroundingDINO text threshold", + ) + parser.add_argument( + "--mask-dir-name", + type=str, + default="masks", + help="mask 输出目录名(相对 scene_dir)", + ) + parser.add_argument( + "--per-object", + action="store_true", + help="逐物体调用 GDINO/SAM2(默认关闭,使用一次性拼接 caption 的模式)", + ) + parser.add_argument( + "--dump-preprocessed", + action="store_true", + help="保存预处理后的检测输入,便于调试(默认关闭)", + ) + + args = parser.parse_args() + + scene_dirs: List[Path] = [] + if args.scene_dir: + scene_dirs = [args.scene_dir.resolve()] + if args.scene_range: + for sid in parse_scene_spec(args.scene_range): + scene_dirs.append(args.root_dir / f"scene_{sid:02d}") + if not scene_dirs: + raise ValueError("必须提供 --scene-dir 或 --scene-range") + + device = "cuda" if torch.cuda.is_available() else "cpu" + gdino = load_model( + model_config_path=str(args.gdino_config), + model_checkpoint_path=str(args.gdino_ckpt), + device=device, + ).to(device) + sam2_model = build_sam2( + str(args.sam2_config), + str(args.sam2_ckpt), + device=device, + ).to(device) + sam2_predictor = SAM2ImagePredictor(sam2_model) + + for scene_dir in scene_dirs: + if not scene_dir.is_dir(): + print(f"[WARN] scene 目录不存在,跳过: {scene_dir}") + continue + + scene_json = scene_dir / "scene.json" + if not scene_json.is_file(): + print(f"[WARN] scene.json 不存在,跳过: {scene_json}") + continue + + with scene_json.open("r", encoding="utf-8") as f: + data = json.load(f) + + image_name = data.get("image") or find_single_image_file(scene_dir) + if not image_name: + print(f"[WARN] 未找到场景图片,跳过: {scene_dir}") + continue + image_path = scene_dir / image_name + if not image_path.is_file(): + print(f"[WARN] 场景图片不存在,跳过: {image_path}") + continue + + objects = data.get("objects", []) + if not objects: + print(f"[WARN] {scene_dir} objects 为空,未执行分割。") + continue + + image_tensor, image_bgr, h, w = load_image_for_models(image_path) + if args.dump_preprocessed: + debug_dir = scene_dir / "debug_inputs" + debug_dir.mkdir(exist_ok=True, parents=True) + dump_name = debug_dir / f"{scene_dir.name}_{image_path.stem}_preprocessed.png" + cv2.imwrite(str(dump_name), image_bgr) + print(f"[DEBUG] 已保存预处理图像: {dump_name}") + sam2_predictor.set_image(image_bgr) + + mask_dir = ensure_mask_dir(scene_dir, args.mask_dir_name) + + print(f"\n===== 处理 {scene_dir.name} =====") + + if args.per_object: + for idx, obj in enumerate(objects): + prompt = obj.get("prompt") or obj.get("name") + if not prompt: + print(f"[WARN] object[{idx}] 缺少 prompt/name,跳过") + continue + + print(f"[PROMPT][per-object] idx={idx}: {prompt}") + + caption = prompt.lower().strip() + if not caption.endswith("."): + caption = caption + "." + + print(caption) + + boxes, confidences, labels = predict( + model=gdino, + image=image_tensor, + caption=caption, + box_threshold=args.box_threshold, + text_threshold=args.text_threshold, + device=device, + ) + if boxes is None or len(boxes) == 0: + print(f"[WARN] GroundingDINO 未检测到:{prompt}") + continue + + best_idx = int(torch.argmax(confidences).item()) + box = boxes[best_idx].to(device) + box = box * torch.tensor([w, h, w, h], device=box.device) + box_xyxy = ( + box_convert(boxes=box.unsqueeze(0), in_fmt="cxcywh", out_fmt="xyxy") + .cpu() + .numpy() + ) + + masks, scores, _ = sam2_predictor.predict( + point_coords=None, + point_labels=None, + box=box_xyxy, + multimask_output=False, + ) + mask = masks[0].astype(np.uint8) * 255 + + obj_id = obj.get("id") or f"obj{idx+1}" + mask_rel = obj.get("mask") or f"{args.mask_dir_name}/{obj_id}.png" + mask_path = scene_dir / mask_rel + mask_path.parent.mkdir(parents=True, exist_ok=True) + cv2.imwrite(str(mask_path), mask) + + obj["id"] = obj_id + obj["mask"] = str(mask_rel) + + print(f"[OK] {prompt} -> {mask_rel}") + + else: + caption, clauses = build_joint_caption(objects) + if not caption.strip(): + print(f"[WARN] 无有效 prompt,跳过 {scene_dir}") + continue + + print(f"[PROMPT][joint] caption: {caption}") + + boxes, confidences, labels = predict( + model=gdino, + image=image_tensor, + caption=caption, + box_threshold=args.box_threshold, + text_threshold=args.text_threshold, + device=device, + ) + if boxes is None or len(boxes) == 0: + print(f"[WARN] GDINO 未检测到任何框,跳过 {scene_dir}") + continue + + norm_labels = [normalize_phrase(l) for l in labels] + boxes = boxes * torch.tensor([w, h, w, h], device=boxes.device) + boxes_xyxy = box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xyxy").cpu().numpy() + + used = set() + for idx, obj in enumerate(objects): + target = normalize_phrase(obj.get("prompt") or obj.get("name") or "") + match_idx = None + for j, lbl in enumerate(norm_labels): + if j in used: + continue + if lbl == target: + match_idx = j + break + if match_idx is None: + for j in range(len(norm_labels)): + if j not in used: + match_idx = j + break + if match_idx is None: + print(f"[WARN] 没有可用的检测结果分配给 object[{idx}]") + continue + + used.add(match_idx) + box_xyxy = boxes_xyxy[match_idx : match_idx + 1] + masks, scores, _ = sam2_predictor.predict( + point_coords=None, + point_labels=None, + box=box_xyxy, + multimask_output=False, + ) + mask = masks[0].astype(np.uint8) * 255 + + obj_id = obj.get("id") or f"obj{idx+1}" + mask_rel = obj.get("mask") or f"{args.mask_dir_name}/{obj_id}.png" + mask_path = scene_dir / mask_rel + mask_path.parent.mkdir(parents=True, exist_ok=True) + cv2.imwrite(str(mask_path), mask) + + obj["id"] = obj_id + obj["mask"] = str(mask_rel) + + print(f"[OK] {obj.get('prompt') or obj.get('name')} -> {mask_rel}") + + with scene_json.open("w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=2) + print(f"[DONE] 已更新 {scene_json}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/masking/grsam_new.py b/OVOW/masking/grsam_new.py new file mode 100644 index 0000000000000000000000000000000000000000..d95832746d8c31c99485a0e567b32d0e79c9c6ee --- /dev/null +++ b/OVOW/masking/grsam_new.py @@ -0,0 +1,434 @@ +#!/usr/bin/env python +""" +读取 scene.json(包含 objects + prompt),调用 GroundingDINO + SAM2 分割每个物体, +按 object 的 label 生成多实例 mask 文件(label_01/label_02/...),写入 masks/, +并回填 scene.json 的 objects 列表。 +""" + +import argparse +import json +import re +from pathlib import Path +from typing import List, Optional, Tuple + +import cv2 +import numpy as np +import torch +from PIL import Image +from torchvision import transforms as TF +from torchvision.ops import box_convert + +from sam2.build_sam import build_sam2 +from sam2.sam2_image_predictor import SAM2ImagePredictor +from grounding_dino.groundingdino.util.inference import load_model, predict + + +def find_single_image_file(scene_dir: Path) -> Optional[str]: + exts = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG"} + candidates = [p.name for p in scene_dir.iterdir() if p.is_file() and p.suffix in exts] + if len(candidates) == 1: + return candidates[0] + return None + + +def load_image_for_models(image_path: Path, mode: str = "crop"): + """与 segment.py 一致的预处理:宽度 518px,保持长宽比并根据模式裁剪/填充。""" + if mode not in ("crop", "pad"): + raise ValueError("mode 必须是 'crop' 或 'pad'") + + img = Image.open(image_path) + if img.mode == "RGBA": + bg = Image.new("RGBA", img.size, (255, 255, 255, 255)) + img = Image.alpha_composite(bg, img) + img = img.convert("RGB") + + target_size = 518 + to_tensor = TF.ToTensor() + width, height = img.size + + if mode == "pad": + if width >= height: + new_width = target_size + new_height = round(height * (new_width / width) / 14) * 14 + else: + new_height = target_size + new_width = round(width * (new_height / height) / 14) * 14 + else: + new_width = target_size + new_height = round(height * (new_width / width) / 14) * 14 + + img = img.resize((new_width, new_height), Image.Resampling.BICUBIC) + img_tensor = to_tensor(img) + + if mode == "crop" and new_height > target_size: + start_y = (new_height - target_size) // 2 + img_tensor = img_tensor[:, start_y : start_y + target_size, :] + + if mode == "pad": + h_padding = target_size - img_tensor.shape[1] + w_padding = target_size - img_tensor.shape[2] + if h_padding > 0 or w_padding > 0: + pad_top = h_padding // 2 + pad_bottom = h_padding - pad_top + pad_left = w_padding // 2 + pad_right = w_padding - pad_left + img_tensor = torch.nn.functional.pad( + img_tensor, + (pad_left, pad_right, pad_top, pad_bottom), + mode="constant", + value=1.0, + ) + + image_tensor = img_tensor + image_np = (image_tensor.permute(1, 2, 0).numpy() * 255).astype(np.uint8) + image_bgr = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR) + h, w = image_tensor.shape[1], image_tensor.shape[2] + return image_tensor, image_bgr, h, w + + +def ensure_mask_dir(scene_dir: Path, mask_dir_name: str) -> Path: + mask_dir = scene_dir / mask_dir_name + mask_dir.mkdir(parents=True, exist_ok=True) + return mask_dir + + +def parse_scene_spec(spec: str) -> List[int]: + ids: List[int] = [] + for chunk in spec.split(","): + chunk = chunk.strip() + if not chunk: + continue + if "-" in chunk: + a, b = chunk.split("-", 1) + start, end = int(a), int(b) + if end < start: + start, end = end, start + ids.extend(range(start, end + 1)) + else: + ids.append(int(chunk)) + return sorted(set(ids)) + + +def normalize_phrase(text: str) -> str: + """小写并去掉尾部标点,便于匹配 GDINO 返回的 label。""" + t = text.strip().lower() + while t.endswith((".", ",", ";", " ")): + t = t[:-1] + return t + + +def build_joint_caption(objects: List[dict]) -> Tuple[str, List[str]]: + """ + 把所有 object.prompt 拼成一个 GDINO caption,并返回标准化后的子句列表。 + - 子句形如 "red car on the road" + - caption 形如 "red car on the road. house on the left." + """ + clauses = [] + for obj in objects: + p = obj.get("prompt") or obj.get("name") or "" + p = p.strip() + if not p: + continue + clauses.append(p) + normalized_clauses = [normalize_phrase(c) for c in clauses] + caption = ". ".join(normalized_clauses) + if not caption.endswith("."): + caption += "." + return caption, normalized_clauses + + +def sanitize_id(text: str) -> str: + base = normalize_phrase(text) + base = re.sub(r"[^a-z0-9]+", "_", base).strip("_") + return base or "obj" + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Grounded SAM2 根据 scene.json 的 prompt 分割物体并写回 mask 路径(多实例)" + ) + parser.add_argument( + "--scene-dir", + type=Path, + help="单个 scene 目录", + ) + parser.add_argument( + "--scene-range", + type=str, + help='批量模式,形如 "1-4,6,8"(按 scene_{:02d} 命名)', + ) + parser.add_argument( + "--root-dir", + type=Path, + default=Path(__file__).resolve().parents[2] / "data_pose" / "scenes", + help="场景根目录(默认 data_pose/scenes)", + ) + parser.add_argument( + "--sam2-ckpt", + type=Path, + default=Path("checkpoints/sam2.1_hiera_large.pt"), + help="SAM2 checkpoint 路径", + ) + parser.add_argument( + "--sam2-config", + type=Path, + default=Path("configs/sam2.1/sam2.1_hiera_l.yaml"), + help="SAM2 config 路径", + ) + parser.add_argument( + "--gdino-config", + type=Path, + default=Path("grounding_dino/groundingdino/config/GroundingDINO_SwinB_cfg.py"), + help="GroundingDINO 配置", + ) + parser.add_argument( + "--gdino-ckpt", + type=Path, + default=Path("gdino_checkpoints/groundingdino_swinb_cogcoor.pth"), + help="GroundingDINO checkpoint", + ) + parser.add_argument( + "--box-threshold", + type=float, + default=0.2, + help="GroundingDINO box threshold", + ) + parser.add_argument( + "--text-threshold", + type=float, + default=0.2, + help="GroundingDINO text threshold", + ) + parser.add_argument( + "--mask-dir-name", + type=str, + default="masks", + help="mask 输出目录名(相对 scene_dir)", + ) + parser.add_argument( + "--per-object", + action="store_true", + help="逐物体调用 GDINO/SAM2(默认关闭,使用一次性拼接 caption 的模式)", + ) + parser.add_argument( + "--dump-preprocessed", + action="store_true", + help="保存预处理后的检测输入,便于调试(默认关闭)", + ) + + args = parser.parse_args() + + scene_dirs: List[Path] = [] + if args.scene_dir: + scene_dirs = [args.scene_dir.resolve()] + if args.scene_range: + for sid in parse_scene_spec(args.scene_range): + scene_dirs.append(args.root_dir / f"scene_{sid:02d}") + if not scene_dirs: + raise ValueError("必须提供 --scene-dir 或 --scene-range") + + device = "cuda" if torch.cuda.is_available() else "cpu" + gdino = load_model( + model_config_path=str(args.gdino_config), + model_checkpoint_path=str(args.gdino_ckpt), + device=device, + ).to(device) + sam2_model = build_sam2( + str(args.sam2_config), + str(args.sam2_ckpt), + device=device, + ).to(device) + sam2_predictor = SAM2ImagePredictor(sam2_model) + + for scene_dir in scene_dirs: + if not scene_dir.is_dir(): + print(f"[WARN] scene 目录不存在,跳过: {scene_dir}") + continue + + scene_json = scene_dir / "scene.json" + if not scene_json.is_file(): + print(f"[WARN] scene.json 不存在,跳过: {scene_json}") + continue + + with scene_json.open("r", encoding="utf-8") as f: + data = json.load(f) + + image_name = data.get("image") or find_single_image_file(scene_dir) + if not image_name: + print(f"[WARN] 未找到场景图片,跳过: {scene_dir}") + continue + image_path = scene_dir / image_name + if not image_path.is_file(): + print(f"[WARN] 场景图片不存在,跳过: {image_path}") + continue + + objects = data.get("objects", []) + if not objects: + print(f"[WARN] {scene_dir} objects 为空,未执行分割。") + continue + + image_tensor, image_bgr, h, w = load_image_for_models(image_path) + if args.dump_preprocessed: + debug_dir = scene_dir / "debug_inputs" + debug_dir.mkdir(exist_ok=True, parents=True) + dump_name = debug_dir / f"{scene_dir.name}_{image_path.stem}_preprocessed.png" + cv2.imwrite(str(dump_name), image_bgr) + print(f"[DEBUG] 已保存预处理图像: {dump_name}") + sam2_predictor.set_image(image_bgr) + + mask_dir = ensure_mask_dir(scene_dir, args.mask_dir_name) + + print(f"\n===== 处理 {scene_dir.name} =====") + + new_objects: List[dict] = [] + + if args.per_object: + for idx, obj in enumerate(objects): + prompt = obj.get("prompt") or obj.get("name") + if not prompt: + print(f"[WARN] object[{idx}] 缺少 prompt/name,跳过") + continue + + print(f"[PROMPT][per-object] idx={idx}: {prompt}") + + caption = prompt.lower().strip() + if not caption.endswith("."): + caption = caption + "." + + boxes, confidences, labels = predict( + model=gdino, + image=image_tensor, + caption=caption, + box_threshold=args.box_threshold, + text_threshold=args.text_threshold, + device=device, + ) + if boxes is None or len(boxes) == 0: + print(f"[WARN] GroundingDINO 未检测到:{prompt}") + continue + + keep = confidences >= args.box_threshold + if keep.numel() != 0: + boxes = boxes[keep] + confidences = confidences[keep] + + if boxes is None or len(boxes) == 0: + print(f"[WARN] 过滤后无有效框:{prompt}") + continue + + boxes = boxes * torch.tensor([w, h, w, h], device=boxes.device) + boxes_xyxy = ( + box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xyxy") + .cpu() + .numpy() + ) + + order = torch.argsort(confidences, descending=True).cpu().numpy() + boxes_xyxy = boxes_xyxy[order] + + base_label = obj.get("name") or obj.get("prompt") or obj.get("id") or f"obj{idx+1}" + base_id = sanitize_id(base_label) + is_occluded = obj.get("is_occluded", False) + + for inst_idx, box_xyxy in enumerate(boxes_xyxy, start=1): + masks, scores, _ = sam2_predictor.predict( + point_coords=None, + point_labels=None, + box=box_xyxy, + multimask_output=False, + ) + mask = masks[0].astype(np.uint8) * 255 + + inst_id = f"{base_id}_{inst_idx:02d}" + mask_rel = f"{args.mask_dir_name}/{inst_id}.png" + mask_path = scene_dir / mask_rel + mask_path.parent.mkdir(parents=True, exist_ok=True) + cv2.imwrite(str(mask_path), mask) + + new_objects.append( + { + "id": inst_id, + "name": base_label, + "prompt": prompt, + "is_occluded": is_occluded, + "mask": str(mask_rel), + } + ) + + print(f"[OK] {prompt} -> {mask_rel}") + + else: + caption, clauses = build_joint_caption(objects) + if not caption.strip(): + print(f"[WARN] 无有效 prompt,跳过 {scene_dir}") + continue + + print(f"[PROMPT][joint] caption: {caption}") + + boxes, confidences, labels = predict( + model=gdino, + image=image_tensor, + caption=caption, + box_threshold=args.box_threshold, + text_threshold=args.text_threshold, + device=device, + ) + if boxes is None or len(boxes) == 0: + print(f"[WARN] GDINO 未检测到任何框,跳过 {scene_dir}") + continue + + norm_labels = [normalize_phrase(l) for l in labels] + boxes = boxes * torch.tensor([w, h, w, h], device=boxes.device) + boxes_xyxy = box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xyxy").cpu().numpy() + + used = set() + for idx, obj in enumerate(objects): + target = normalize_phrase(obj.get("prompt") or obj.get("name") or "") + match_idx = None + for j, lbl in enumerate(norm_labels): + if j in used: + continue + if lbl == target: + match_idx = j + break + if match_idx is None: + for j in range(len(norm_labels)): + if j not in used: + match_idx = j + break + if match_idx is None: + print(f"[WARN] 没有可用的检测结果分配给 object[{idx}]") + continue + + used.add(match_idx) + box_xyxy = boxes_xyxy[match_idx : match_idx + 1] + masks, scores, _ = sam2_predictor.predict( + point_coords=None, + point_labels=None, + box=box_xyxy, + multimask_output=False, + ) + mask = masks[0].astype(np.uint8) * 255 + + obj_id = obj.get("id") or f"obj{idx+1}" + mask_rel = obj.get("mask") or f"{args.mask_dir_name}/{obj_id}.png" + mask_path = scene_dir / mask_rel + mask_path.parent.mkdir(parents=True, exist_ok=True) + cv2.imwrite(str(mask_path), mask) + + obj["id"] = obj_id + obj["mask"] = str(mask_rel) + new_objects.append(obj) + + print(f"[OK] {obj.get('prompt') or obj.get('name')} -> {mask_rel}") + + if new_objects: + data["objects"] = new_objects + + with scene_json.open("w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=2) + print(f"[DONE] 已更新 {scene_json}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/masking/image_to_pose_scene.py b/OVOW/masking/image_to_pose_scene.py new file mode 100644 index 0000000000000000000000000000000000000000..ec26c6ee2d36d17a0269a84ea4e997d3b3a7e5a7 --- /dev/null +++ b/OVOW/masking/image_to_pose_scene.py @@ -0,0 +1,461 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +从单张图片自动生成 data_pose 场景资产结构: + + scene_xx/ + # 拷贝/链接输入图 + scene.json # {"image": "...", "objects": [{"name","mask","is_occluded","seed"} ...]} + masks/ + .png # 每个物体的二值 mask + +实现方式: +1) Qwen3-VL 从图像中识别多个前景物体(name/prompt/is_occluded); +2) GroundingDINO + SAM2 根据 prompt 分割每个物体并写出 masks/*.png; +3) 写入/覆盖 scene.json(保持与 OnePoseviaGen/batch_scene_pipeline.py 兼容)。 + +示例: + python Grounded_SAM2/qwen/image_to_pose_scene.py \ + --image /path/to/room2.jpg \ + --scene-id 4 \ + --with-masks +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import sys +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence, Tuple + + +@dataclass +class _ObjectCandidate: + name: str + prompt: str + is_occluded: bool + + +def _repo_root() -> Path: + return Path(__file__).resolve().parents[2] + + +def _grounded_sam2_root() -> Path: + return Path(__file__).resolve().parents[1] + + +def _sanitize_name(name: str) -> str: + s = (name or "").strip().lower() + s = re.sub(r"\s+", "_", s) + s = re.sub(r"[^a-z0-9_\-]+", "", s) + s = re.sub(r"_+", "_", s).strip("_") + return s or "object" + + +def _make_unique(base: str, used: set[str]) -> str: + if base not in used: + used.add(base) + return base + i = 2 + while f"{base}_{i}" in used: + i += 1 + name = f"{base}_{i}" + used.add(name) + return name + + +def _try_hardlink_or_copy(src: Path, dst: Path) -> None: + dst.parent.mkdir(parents=True, exist_ok=True) + try: + os.link(str(src), str(dst)) + return + except Exception: + pass + shutil.copy2(str(src), str(dst)) + + +def _prepare_scene_dir(scene_dir: Path, *, overwrite: bool) -> None: + if scene_dir.exists(): + if not overwrite: + raise FileExistsError(f"scene_dir already exists: {scene_dir} (use --overwrite to replace)") + shutil.rmtree(scene_dir) + scene_dir.mkdir(parents=True, exist_ok=True) + + +def _pick_next_scene_id(root_dir: Path) -> int: + ids: List[int] = [] + for p in root_dir.glob("scene_*"): + if not p.is_dir(): + continue + m = re.match(r"scene_(\\d+)$", p.name) + if not m: + continue + try: + ids.append(int(m.group(1))) + except Exception: + continue + return (max(ids) + 1) if ids else 1 + + +def _load_image_for_models_fixed_height(image_path: Path, target_h: int) -> Tuple[Any, Any, int, int]: + """ + 返回 (image_tensor, image_bgr, h, w) + - image_tensor: torch.Tensor (3, h, w), 0~1 + - image_bgr: np.ndarray (h, w, 3), uint8 + """ + import cv2 + import numpy as np + import torch + from PIL import Image + from torchvision import transforms as TF + + img = Image.open(image_path) + if img.mode == "RGBA": + bg = Image.new("RGBA", img.size, (255, 255, 255, 255)) + img = Image.alpha_composite(bg, img) + img = img.convert("RGB") + + width, height = img.size + if height <= 0 or width <= 0: + raise ValueError(f"Invalid image size: {image_path} ({width}x{height})") + + if target_h <= 0: + raise ValueError("--mask-height must be > 0") + new_h = int(target_h) + new_w = int(round(width * (new_h / float(height)))) + new_w = max(1, new_w) + + img = img.resize((new_w, new_h), Image.Resampling.BICUBIC) + image_tensor = TF.ToTensor()(img) + if not isinstance(image_tensor, torch.Tensor): + image_tensor = torch.as_tensor(image_tensor) + + image_np = (image_tensor.permute(1, 2, 0).cpu().numpy() * 255.0).astype(np.uint8) + image_bgr = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR) + return image_tensor, image_bgr, int(new_h), int(new_w) + + +def _run_qwen_detect_objects( + *, + image_path: Path, + model_path: str, + max_new_tokens: int, + max_objects: int, + hf_offline: bool, +) -> List[Dict[str, Any]]: + if hf_offline: + os.environ["HF_HUB_OFFLINE"] = "1" + + import torch + from transformers import AutoModelForImageTextToText, AutoProcessor + + import qwen_build_scene_json as qwen + + model = AutoModelForImageTextToText.from_pretrained( + model_path, + dtype="auto", + device_map="auto" if torch.cuda.is_available() else None, + ) + processor = AutoProcessor.from_pretrained(model_path) + + objects = qwen.run_qwen_on_image( + image_path=image_path, + model=model, + processor=processor, + max_new_tokens=int(max_new_tokens), + max_objects=int(max_objects), + ) + return objects or [] + + +def _run_grounded_sam2_segment( + *, + image_path: Path, + candidates: Sequence[_ObjectCandidate], + out_mask_dir: Path, + sam2_ckpt: Path, + sam2_config: Path, + gdino_config: Path, + gdino_ckpt: Path, + box_threshold: float, + text_threshold: float, + mask_height: int, + fail_policy: str, + dump_preprocessed: bool, +) -> List[_ObjectCandidate]: + import cv2 + import numpy as np + import torch + from torchvision.ops import box_convert + + gs_root = _grounded_sam2_root() + for p in [gs_root, gs_root / "grounding_dino", gs_root / "sam2"]: + sp = str(p) + if sp not in sys.path: + sys.path.insert(0, sp) + + from sam2.build_sam import build_sam2 + from sam2.sam2_image_predictor import SAM2ImagePredictor + from grounding_dino.groundingdino.util.inference import load_model, predict + + device = "cuda" if torch.cuda.is_available() else "cpu" + gdino = load_model( + model_config_path=str(gdino_config), + model_checkpoint_path=str(gdino_ckpt), + device=device, + ).to(device) + sam2_model = build_sam2( + str(sam2_config), + str(sam2_ckpt), + device=device, + ).to(device) + sam2_predictor = SAM2ImagePredictor(sam2_model) + + image_tensor, image_bgr, h, w = _load_image_for_models_fixed_height(image_path, target_h=int(mask_height)) + if dump_preprocessed: + out_mask_dir.parent.mkdir(parents=True, exist_ok=True) + cv2.imwrite(str(out_mask_dir.parent / "debug_preprocessed.png"), image_bgr) + + sam2_predictor.set_image(image_bgr) + out_mask_dir.mkdir(parents=True, exist_ok=True) + + kept: List[_ObjectCandidate] = [] + blank = np.zeros((h, w), dtype=np.uint8) + + for idx, obj in enumerate(candidates): + prompt = (obj.prompt or obj.name).strip() + if not prompt: + if fail_policy == "error": + raise ValueError(f"Empty prompt for object[{idx}]") + continue + + caption = prompt.lower().strip() + if not caption.endswith("."): + caption += "." + + boxes, confidences, _labels = predict( + model=gdino, + image=image_tensor, + caption=caption, + box_threshold=float(box_threshold), + text_threshold=float(text_threshold), + device=device, + ) + if boxes is None or len(boxes) == 0: + print(f"[WARN] GroundingDINO 未检测到:{prompt}") + if fail_policy == "error": + raise RuntimeError(f"No boxes detected for prompt: {prompt}") + if fail_policy == "blank": + cv2.imwrite(str(out_mask_dir / f"{obj.name}.png"), blank) + kept.append(obj) + continue + + best_idx = int(torch.argmax(confidences).item()) + box = boxes[best_idx].to(device) + box = box * torch.tensor([w, h, w, h], device=box.device) + box_xyxy = box_convert(boxes=box.unsqueeze(0), in_fmt="cxcywh", out_fmt="xyxy").cpu().numpy() + + masks, _scores, _logits = sam2_predictor.predict( + point_coords=None, + point_labels=None, + box=box_xyxy, + multimask_output=False, + ) + mask = (masks[0].astype(np.uint8) * 255) if masks is not None and len(masks) > 0 else blank + cv2.imwrite(str(out_mask_dir / f"{obj.name}.png"), mask) + kept.append(obj) + + return kept + + +def build_args() -> argparse.ArgumentParser: + repo_root = _repo_root() + gs_root = _grounded_sam2_root() + + parser = argparse.ArgumentParser(description="从单张图片生成 data_pose 场景目录(scene.json + masks)") + parser.add_argument("--image", type=Path, required=True, help="输入图片路径(jpg/png)") + parser.add_argument("--scene-dir", type=Path, default=None, help="输出 scene 目录(如 data_pose/scenes/scene_04)") + parser.add_argument("--scene-id", type=int, default=None, help="输出 scene 编号(输出到 --root-dir/scene_{id:02d})") + parser.add_argument( + "--root-dir", + type=Path, + default=repo_root / "data_pose" / "scenes", + help="场景根目录(默认 data_pose/scenes)", + ) + parser.add_argument("--overwrite", action="store_true", help="若 scene-dir 已存在则覆盖(危险)") + parser.add_argument("--image-mode", choices=["copy", "hardlink"], default="copy", help="把输入图放入 scene-dir 的方式") + parser.add_argument("--image-name", type=str, default="", help="输出到 scene-dir 中的图片文件名(默认使用输入文件名)") + + parser.add_argument( + "--qwen-model", + type=str, + default=str(gs_root / "qwen" / "model" / "Qwen3-VL-8B-Instruct"), + help="Qwen3-VL 模型路径(默认本地 8B)", + ) + parser.add_argument("--max-objects", type=int, default=10, help="Qwen 最多检测多少个物体") + parser.add_argument("--max-new-tokens", type=int, default=512, help="Qwen 生成最大 tokens") + parser.add_argument("--hf-offline", action="store_true", help="设置 HF_HUB_OFFLINE=1(推荐离线环境)") + + parser.add_argument("--with-masks", action="store_true", help="调用 Grounded-SAM2 生成 masks(默认仅写 scene.json)") + parser.add_argument("--mask-dir-name", type=str, default="masks", help="mask 输出目录名(相对 scene-dir)") + parser.add_argument("--mask-height", type=int, default=336, help="分割时使用的图像高度/输出 mask 高度(默认 336)") + parser.add_argument( + "--fail-policy", + choices=["drop", "blank", "error"], + default="drop", + help="分割失败策略:drop=从 scene.json 移除;blank=写空 mask;error=直接报错", + ) + parser.add_argument("--dump-preprocessed", action="store_true", help="保存预处理后的分割输入图(debug_preprocessed.png)") + + parser.add_argument( + "--sam2-ckpt", + type=Path, + default=gs_root / "checkpoints" / "sam2.1_hiera_large.pt", + help="SAM2 checkpoint", + ) + parser.add_argument( + "--sam2-config", + type=Path, + default=gs_root / "sam2" / "configs" / "sam2.1" / "sam2.1_hiera_l.yaml", + help="SAM2 config", + ) + parser.add_argument( + "--gdino-config", + type=Path, + default=gs_root / "grounding_dino" / "groundingdino" / "config" / "GroundingDINO_SwinB_cfg.py", + help="GroundingDINO config", + ) + parser.add_argument( + "--gdino-ckpt", + type=Path, + default=gs_root / "gdino_checkpoints" / "groundingdino_swinb_cogcoor.pth", + help="GroundingDINO checkpoint", + ) + parser.add_argument("--box-threshold", type=float, default=0.2, help="GroundingDINO box threshold") + parser.add_argument("--text-threshold", type=float, default=0.2, help="GroundingDINO text threshold") + + parser.add_argument("--seed", type=int, default=42, help="写入 scene.json 的 seed(默认 42)") + parser.add_argument("--no-seed", action="store_true", help="不在 scene.json 中写入 seed 字段") + parser.add_argument("--dry-run", action="store_true", help="不跑模型;仅创建目录/复制图片并打印计划") + return parser + + +def main() -> None: + parser = build_args() + args = parser.parse_args() + + image_path = args.image.expanduser().resolve() + if not image_path.is_file(): + raise FileNotFoundError(f"image not found: {image_path}") + + root_dir = Path(args.root_dir).expanduser().resolve() + root_dir.mkdir(parents=True, exist_ok=True) + + scene_dir: Optional[Path] = args.scene_dir.expanduser().resolve() if args.scene_dir else None + if scene_dir is None: + if args.scene_id is not None: + scene_dir = root_dir / f"scene_{int(args.scene_id):02d}" + else: + next_id = _pick_next_scene_id(root_dir) + scene_dir = root_dir / f"scene_{int(next_id):02d}" + + _prepare_scene_dir(scene_dir, overwrite=bool(args.overwrite)) + + out_image_name = str(args.image_name or "").strip() or image_path.name + out_image_path = scene_dir / out_image_name + if args.image_mode == "hardlink": + _try_hardlink_or_copy(image_path, out_image_path) + else: + shutil.copy2(str(image_path), str(out_image_path)) + + print(f"[OK] scene_dir = {scene_dir}") + print(f"[OK] image = {out_image_path.name}") + + if args.dry_run: + print("[DryRun] skip Qwen + Grounded-SAM2.") + return + + raw_objects = _run_qwen_detect_objects( + image_path=out_image_path, + model_path=str(args.qwen_model), + max_new_tokens=int(args.max_new_tokens), + max_objects=int(args.max_objects), + hf_offline=bool(args.hf_offline), + ) + if not raw_objects: + raise RuntimeError("Qwen returned no objects; abort.") + + used: set[str] = set() + candidates: List[_ObjectCandidate] = [] + for obj in raw_objects: + prompt = str(obj.get("prompt") or obj.get("name") or "").strip() + raw_name = str(obj.get("name") or prompt or obj.get("id") or "object").strip() + safe = _make_unique(_sanitize_name(raw_name), used) + candidates.append( + _ObjectCandidate( + name=safe, + prompt=prompt or raw_name or safe, + is_occluded=bool(obj.get("is_occluded", False)), + ) + ) + + if not bool(args.with_masks): + objects_out: List[Dict[str, Any]] = [] + for c in candidates: + item: Dict[str, Any] = { + "name": c.name, + "mask": f"{str(args.mask_dir_name).strip().rstrip('/')}/{c.name}.png", + "is_occluded": bool(c.is_occluded), + } + if not bool(args.no_seed): + item["seed"] = int(args.seed) + objects_out.append(item) + + with (scene_dir / "scene.json").open("w", encoding="utf-8") as f: + json.dump({"image": out_image_path.name, "objects": objects_out}, f, ensure_ascii=False, indent=2) + (scene_dir / str(args.mask_dir_name)).mkdir(parents=True, exist_ok=True) + print(f"[OK] wrote scene.json (no masks): {scene_dir / 'scene.json'}") + return + + out_mask_dir = scene_dir / str(args.mask_dir_name) + kept = _run_grounded_sam2_segment( + image_path=out_image_path, + candidates=candidates, + out_mask_dir=out_mask_dir, + sam2_ckpt=Path(args.sam2_ckpt).expanduser().resolve(), + sam2_config=Path(args.sam2_config).expanduser().resolve(), + gdino_config=Path(args.gdino_config).expanduser().resolve(), + gdino_ckpt=Path(args.gdino_ckpt).expanduser().resolve(), + box_threshold=float(args.box_threshold), + text_threshold=float(args.text_threshold), + mask_height=int(args.mask_height), + fail_policy=str(args.fail_policy), + dump_preprocessed=bool(args.dump_preprocessed), + ) + + objects_out = [] + for c in kept: + item = { + "name": c.name, + "mask": f"{str(args.mask_dir_name).strip().rstrip('/')}/{c.name}.png", + "is_occluded": bool(c.is_occluded), + } + if not bool(args.no_seed): + item["seed"] = int(args.seed) + objects_out.append(item) + + scene_json_path = scene_dir / "scene.json" + with scene_json_path.open("w", encoding="utf-8") as f: + json.dump({"image": out_image_path.name, "objects": objects_out}, f, ensure_ascii=False, indent=2) + + print(f"[OK] wrote {scene_json_path}") + print(f"[OK] masks_dir = {out_mask_dir}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/masking/logs/sam3server_20261020_082135.log b/OVOW/masking/logs/sam3server_20261020_082135.log new file mode 100644 index 0000000000000000000000000000000000000000..86bd72b72d9cb2a24e0b306836b82be125a0cdd3 --- /dev/null +++ b/OVOW/masking/logs/sam3server_20261020_082135.log @@ -0,0 +1,54 @@ +[sam3-server] 加载 SAM3 video model(常驻)... +/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/third_party/sam3/sam3/model_builder.py:8: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. + import pkg_resources +INFO 2026-10-20 08:21:52,331 3601955 sam3_video_base.py: 125: setting max_num_objects=10000 and num_obj_for_compile=16 +[INFO] Loading SAM3 checkpoint: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/sam3/sam3.pt +[INFO] SAM3 model resident (cached): /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/sam3/sam3.pt +[sam3-server] SAM3 ckpt 载入完成。 +[server] ready, queue=/tmp/sam3_p2_q +[INFO] Qwen backend: api +[INFO] Qwen API model: qwen3.5-plus-2026-02-15 +[INFO] Qwen API model candidates: ['qwen3.5-plus-2026-02-15', 'qwen3.5-flash-2026-02-23', 'qwen3.5-flash', 'qwen3.5-122b-a10b', 'qwen3.5-35b-a3b'] +[server] op=masks done in 0.1s ok=False +[INFO] Qwen backend: api +[INFO] Qwen API model: qwen3.5-plus-2026-02-15 +[INFO] Qwen API model candidates: ['qwen3.5-plus-2026-02-15', 'qwen3.5-flash-2026-02-23', 'qwen3.5-flash', 'qwen3.5-122b-a10b', 'qwen3.5-35b-a3b'] +[server] op=masks done in 0.0s ok=False +[INFO] Qwen backend: api +[INFO] Qwen API model: qwen3.5-plus-2026-02-15 +[INFO] Qwen API model candidates: ['qwen3.5-plus-2026-02-15', 'qwen3.5-flash-2026-02-23', 'qwen3.5-flash', 'qwen3.5-122b-a10b', 'qwen3.5-35b-a3b'] +[server] op=masks done in 0.0s ok=False +[INFO] Qwen backend: api +[INFO] Qwen API model: qwen3.5-plus-2026-02-15 +[INFO] Qwen API model candidates: ['qwen3.5-plus-2026-02-15', 'qwen3.5-flash-2026-02-23', 'qwen3.5-flash', 'qwen3.5-122b-a10b', 'qwen3.5-35b-a3b'] +[server] op=masks done in 0.0s ok=False +[INFO] Qwen backend: api +[INFO] Qwen API model: qwen3.5-plus-2026-02-15 +[INFO] Qwen API model candidates: ['qwen3.5-plus-2026-02-15', 'qwen3.5-flash-2026-02-23', 'qwen3.5-flash', 'qwen3.5-122b-a10b', 'qwen3.5-35b-a3b'] +[server] op=masks done in 0.0s ok=False +[INFO] Qwen backend: api +[INFO] Qwen API model: qwen3.5-plus-2026-02-15 +[INFO] Qwen API model candidates: ['qwen3.5-plus-2026-02-15', 'qwen3.5-flash-2026-02-23', 'qwen3.5-flash', 'qwen3.5-122b-a10b', 'qwen3.5-35b-a3b'] +[server] op=masks done in 0.0s ok=False +[INFO] Qwen backend: api +[INFO] Qwen API model: qwen3.5-plus-2026-02-15 +[INFO] Qwen API model candidates: ['qwen3.5-plus-2026-02-15', 'qwen3.5-flash-2026-02-23', 'qwen3.5-flash', 'qwen3.5-122b-a10b', 'qwen3.5-35b-a3b'] +[server] op=masks done in 0.0s ok=False +[INFO] Qwen backend: api +[INFO] Qwen API model: qwen3.5-plus-2026-02-15 +[INFO] Qwen API model candidates: ['qwen3.5-plus-2026-02-15', 'qwen3.5-flash-2026-02-23', 'qwen3.5-flash', 'qwen3.5-122b-a10b', 'qwen3.5-35b-a3b'] +OSError: [Errno 28] No space left on device + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/masking/sam3_server.py", line 684, in + main() + File "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/masking/sam3_server.py", line 680, in main + ipc.server_loop(args.queue, handlers, on_start=_warm_models) + File "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/model_server/ipc.py", line 51, in server_loop + (qd / f"resp_{rid}.json").write_text(json.dumps(resp)) + File "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-sam3/lib/python3.12/pathlib.py", line 1047, in write_text + with self.open(mode='w', encoding=encoding, errors=errors, newline=newline) as f: + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +OSError: [Errno 28] No space left on device diff --git a/OVOW/masking/logs/sam3server_20261020_082927.log b/OVOW/masking/logs/sam3server_20261020_082927.log new file mode 100644 index 0000000000000000000000000000000000000000..071bf1a3c0c8f743eb7a4bbb1dc3a5c6cf1b1c84 --- /dev/null +++ b/OVOW/masking/logs/sam3server_20261020_082927.log @@ -0,0 +1,30 @@ +[sam3-server] 加载 SAM3 video model(常驻)... +/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/third_party/sam3/sam3/model_builder.py:8: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. + import pkg_resources +INFO 2026-10-20 08:29:40,520 687764 sam3_video_base.py: 125: setting max_num_objects=10000 and num_obj_for_compile=16 +[INFO] Loading SAM3 checkpoint: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/sam3/sam3.pt +[INFO] SAM3 model resident (cached): /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/sam3/sam3.pt +[sam3-server] SAM3 ckpt 载入完成。 +[server] ready, queue=/tmp/sam3_p2_q +[INFO] Qwen backend: api +[INFO] Qwen API model: qwen3.5-plus-2026-02-15 +[INFO] Qwen API model candidates: ['qwen3.5-plus-2026-02-15', 'qwen3.5-flash-2026-02-23', 'qwen3.5-flash', 'qwen3.5-122b-a10b', 'qwen3.5-35b-a3b'] +[server] op=masks done in 0.1s ok=False +[INFO] Qwen backend: api +[INFO] Qwen API model: qwen3.5-plus-2026-02-15 +[INFO] Qwen API model candidates: ['qwen3.5-plus-2026-02-15', 'qwen3.5-flash-2026-02-23', 'qwen3.5-flash', 'qwen3.5-122b-a10b', 'qwen3.5-35b-a3b'] +[INFO] Labels (4): ['domino', 'desk', 'chair', 'bracelet'] +[INFO] Reuse resident SAM3 model: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/sam3/sam3.pt + frame loading (OpenCV) [rank=0]: 0%| | 0/75 [00:00 + main() + File "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/masking/sam3_server.py", line 680, in main + ipc.server_loop(args.queue, handlers, on_start=_warm_models) + File "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/tools/model_server/ipc.py", line 51, in server_loop + (qd / f"resp_{rid}.json").write_text(json.dumps(resp)) + File "/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-sam3/lib/python3.12/pathlib.py", line 1047, in write_text + with self.open(mode='w', encoding=encoding, errors=errors, newline=newline) as f: + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +OSError: [Errno 28] No space left on device diff --git a/OVOW/masking/logs/sam3server_20261020_084242.log b/OVOW/masking/logs/sam3server_20261020_084242.log new file mode 100644 index 0000000000000000000000000000000000000000..ce7b2c871de971e509bec065a89b7dbfe241eefa --- /dev/null +++ b/OVOW/masking/logs/sam3server_20261020_084242.log @@ -0,0 +1,370 @@ +[sam3-server] 加载 SAM3 video model(常驻)... +/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/third_party/sam3/sam3/model_builder.py:8: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81. + import pkg_resources +INFO 2026-10-20 08:42:54,904 3025640 sam3_video_base.py: 125: setting max_num_objects=10000 and num_obj_for_compile=16 +[INFO] Loading SAM3 checkpoint: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/sam3/sam3.pt +[INFO] SAM3 model resident (cached): /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/sam3/sam3.pt +[sam3-server] SAM3 ckpt 载入完成。 +[server] ready, queue=/tmp/sam3_p2_q +[INFO] Qwen backend: api +[INFO] Qwen API model: qwen3.5-plus-2026-02-15 +[INFO] Qwen API model candidates: ['qwen3.5-plus-2026-02-15', 'qwen3.5-flash-2026-02-23', 'qwen3.5-flash', 'qwen3.5-122b-a10b', 'qwen3.5-35b-a3b'] +[INFO] Labels (7): ['domino', 'desk', 'chair', 'hand', 'bracelet', 'table', 'person'] +[INFO] Reuse resident SAM3 model: /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/sam3/sam3.pt + frame loading (OpenCV) [rank=0]: 0%| | 0/75 [00:00=4.57.0 + - torch>=2.6.0(建议) + +模型: + 默认使用 Qwen/Qwen3-VL-8B-Instruct,你也可以通过 --model 指定本地路径或其他 HF ID。 + +示例: + conda activate qwen + python qwen3_vl_occlusion.py --image /path/to/image.jpg +""" + +import argparse +import json +import os +import re +from typing import Any, Dict, Optional + +from PIL import Image +import torch +from transformers import AutoModelForImageTextToText, AutoProcessor + + +def build_messages(image: Image.Image) -> list: + """构造 Qwen3-VL 所需的 messages 格式输入。""" + + prompt = ( + "你是一个视觉检测专家。请识别图像中的主要物体类别,并判断该物体是否被其他物体遮挡。" + '请只输出一个 JSON,格式如下:' + '{"category": "类别名称", "occluded": true 或 false, "occlusion_reason": "简要中文说明"}。' + "不要输出任何多余的文字。" + ) + + messages = [ + { + "role": "user", + "content": [ + {"type": "image", "image": image}, + {"type": "text", "text": prompt}, + ], + } + ] + return messages + + +def extract_json(text: str) -> Optional[Dict[str, Any]]: + """ + 从模型输出中尽量提取 JSON。 + 如果失败,返回 None。 + """ + try: + return json.loads(text) + except Exception: + pass + + match = re.search(r"\{.*\}", text, flags=re.DOTALL) + if not match: + return None + + candidate = match.group(0) + try: + return json.loads(candidate) + except Exception: + return None + + +def run_inference( + image_path: str, + model_name_or_path: str = "Qwen/Qwen3-VL-8B-Instruct", + max_new_tokens: int = 128, +) -> Optional[Dict[str, Any]]: + if not os.path.isfile(image_path): + raise FileNotFoundError(f"找不到图片文件: {image_path}") + + print(f"[INFO] 使用模型: {model_name_or_path}") + print(f"[INFO] 输入图片: {os.path.abspath(image_path)}") + + device = "cuda" if torch.cuda.is_available() else "cpu" + print(f"[INFO] 推理设备: {device}") + + model = AutoModelForImageTextToText.from_pretrained( + model_name_or_path, + dtype="auto", + device_map="auto" if device == "cuda" else None, + ) + processor = AutoProcessor.from_pretrained(model_name_or_path) + + image = Image.open(image_path).convert("RGB") + + messages = build_messages(image) + + inputs = processor.apply_chat_template( + messages, + tokenize=True, + add_generation_prompt=True, + return_tensors="pt", + return_dict=True, + ) + inputs = {k: v.to(model.device) for k, v in inputs.items()} + + with torch.no_grad(): + generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens) + + generated_ids_trimmed = [ + out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs["input_ids"], generated_ids) + ] + output_texts = processor.batch_decode( + generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False + ) + + if not output_texts: + print("[ERROR] 模型没有返回任何内容") + return None + + raw_output = output_texts[0].strip() + print("\n[RAW OUTPUT]") + print(raw_output) + + parsed = extract_json(raw_output) + if parsed is None: + print("\n[WARN] 未能稳定解析为 JSON,以上是模型原始输出。") + return None + + print("\n[PARSED RESULT]") + print(json.dumps(parsed, ensure_ascii=False, indent=2)) + return parsed + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="使用 Qwen3-VL 进行物体类别与遮挡判断的小脚本", + ) + parser.add_argument( + "--image", + type=str, + required=True, + help="输入图片路径", + ) + parser.add_argument( + "--model", + type=str, + default="Qwen/Qwen3-VL-8B-Instruct", + help="模型名称或本地路径(默认:Qwen/Qwen3-VL-8B-Instruct)", + ) + parser.add_argument( + "--max-new-tokens", + type=int, + default=128, + help="生成的最大 token 数(默认:128)", + ) + return parser.parse_args() + + +if __name__ == "__main__": + args = parse_args() + run_inference( + image_path=args.image, + model_name_or_path=args.model, + max_new_tokens=args.max_new_tokens, + ) diff --git a/OVOW/masking/qwen_build_label_json.py b/OVOW/masking/qwen_build_label_json.py new file mode 100644 index 0000000000000000000000000000000000000000..f39ee9ba06feb14ee3d29f3bbef9fd1fa50029f0 --- /dev/null +++ b/OVOW/masking/qwen_build_label_json.py @@ -0,0 +1,555 @@ +#!/usr/bin/env python +""" +只输入一张 RGB 场景图,让 Qwen3-VL 产出 label.json(只包含物体类别标签)。 + +使用示例: + conda activate qwen + python Grounded_SAM2/qwen/qwen_build_label_json.py \ + --scene-dir data_pose/scenes/scene_12 \ + --model Grounded_SAM2/qwen/model/Qwen3-VL-8B-Instruct +""" + +import argparse +import json +import re +from pathlib import Path +from typing import Any, Dict, List, Optional + +from PIL import Image +import torch +from transformers import AutoModelForImageTextToText, AutoProcessor + + +def find_single_image_file(scene_dir: Path) -> Optional[str]: + exts = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG"} + candidates = [p.name for p in scene_dir.iterdir() if p.is_file() and p.suffix in exts] + if len(candidates) == 1: + return candidates[0] + if len(candidates) == 0: + print(f"[ERROR] {scene_dir} 下未找到 jpg/png 图片") + else: + print(f"[ERROR] {scene_dir} 下存在多张图片 {candidates},无法确定场景图像") + return None + + +def extract_json(text: str) -> Optional[Dict[str, Any]]: + try: + return json.loads(text) + except Exception: + pass + fence = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, flags=re.DOTALL | re.IGNORECASE) + if fence: + try: + return json.loads(fence.group(1)) + except Exception: + pass + m = re.search(r"\{.*\}", text, flags=re.DOTALL) + if not m: + return None + try: + return json.loads(m.group(0)) + except Exception: + return None + + +def build_prompt(max_objects: int, aggregate_threshold: int) -> str: + return ( + "请分析图片用于语义分割任务。识别图中所有可见物体类别,并估计每个类别的实例数量。" + "输出 JSON,且只输出 JSON。" + "规则:" + "1) 特异性优先:使用最具体的功能性名称(如 computer/car),禁止通用词。" + "2) 互斥性:不要输出包含关系或部件词(如 person 与 clothes/hand)。" + "3) name 必须是英文、小写、单数名词;形容词仅放在 visual_description。" + "4) 每个类别只输出一次,附带你检测到的该类别实例数量 num(整数>=1)。" + f"5) 如果某类别数量 > {aggregate_threshold},请用整体类别名替代并将 num=1(如 tree→forest,person→crowd,building→building_complex)。" + "6) 遮挡检测:若被其他物体遮挡面积明显(>10%),is_occluded=true;否则 false。" + "7) occluded_by 只能填列表中已有的 name;否则留空数组。" + "8) 严禁部件级标签:不要输出 hair/head/face/hand/arm/leg 等人体部件;" + "若角色持有装备,仅保留主体类别(如 elf),不要单独输出 armor/sword。" + "9) 忽略背景与装饰:不要输出 sky/path/ground/wall/light/shadow/text/rune inscription 等环境或纹理标签。" + "10) 若场景只有一个核心主体,只输出这一个主体类别(例如 elf)。" + f"最多输出 {max_objects} 个类别。" + "禁止词汇:box, object, thing, item, container, shape。" + "JSON 格式:" + "{\"objects\": [{\"name\": \"computer\", \"num\": , " + "\"visual_description\": \"...\", \"is_occluded\": false, \"occluded_by\": []}]}" + ) + + +_STOP_WORDS = { + "red", "blue", "green", "yellow", "orange", "purple", "pink", "black", "white", + "brown", "gray", "grey", "gold", "silver", "beige", "tan", + "wood", "wooden", "metal", "plastic", "glass", "ceramic", "leather", "fabric", + "cloth", "steel", "iron", "aluminum", "stone", "marble", + "small", "large", "big", "tiny", "round", "square", "rectangular", "circular", + "left", "right", "front", "back", "top", "bottom", "upper", "lower", "center", +} +_BANNED_LABELS = {"box", "object", "thing", "item", "container", "shape"} +_STOP_WORDS.update(_BANNED_LABELS) +_RESERVED_LABELS = { + "objects", + "object", + "labels", + "label", + "name", + "num", + "count", + "instances", + "visual description", + "visual_description", + "description", + "desc", + "is occluded", + "is_occluded", + "occluded by", + "occluded_by", + "category", + "categories", +} + +_AGGREGATE_MAP = { + "tree": "forest", + "trees": "forest", + "person": "crowd", + "people": "crowd", + "building": "building_complex", + "buildings": "building_complex", + "house": "housing_complex", + "houses": "housing_complex", +} + + +def normalize_label(text: str) -> str: + t = text.strip().lower() + t = re.sub(r"[_\-]+", " ", t) + t = re.sub(r"[^\w\s]", " ", t) + tokens = [tok for tok in t.split() if tok and tok not in _STOP_WORDS] + cleaned = " ".join(tokens).strip() + if cleaned in _BANNED_LABELS or cleaned in _RESERVED_LABELS: + return "" + if not cleaned: + return "" if t in _BANNED_LABELS else t + return cleaned + + +def _as_int(value: Any, default: int = 1) -> int: + try: + v = int(value) + except Exception: + return default + return v + + +def _parse_bool(value: Any) -> Optional[bool]: + if isinstance(value, bool): + return value + if isinstance(value, (int, float)): + return bool(int(value)) + if isinstance(value, str): + v = value.strip().lower() + if v in ("true", "yes", "y", "1", "是", "被遮挡"): + return True + if v in ("false", "no", "n", "0", "否", "未遮挡"): + return False + return None + + +def parse_objects_from_text(raw: str) -> List[Dict[str, Any]]: + objects: List[Dict[str, Any]] = [] + + name_matches = list(re.finditer(r'"name"\s*:\s*"([^"]+)"', raw, flags=re.IGNORECASE)) + if name_matches: + for idx, m in enumerate(name_matches): + name = m.group(1).strip() + start = m.end() + end = name_matches[idx + 1].start() if idx + 1 < len(name_matches) else len(raw) + chunk = raw[start:end] + num_match = re.search(r'"num"\s*:\s*(\d+)', chunk, flags=re.IGNORECASE) + obj: Dict[str, Any] = {"name": name} + if num_match: + obj["num"] = num_match.group(1) + objects.append(obj) + return objects + + lines = [ln.strip() for ln in raw.splitlines() if ln.strip()] + current: Dict[str, Any] = {} + + def flush(): + nonlocal current + if current.get("name"): + objects.append(current) + current = {} + + for line in lines: + line = re.sub(r"^\s*[-*\d\.\)\]]+\s*", "", line) + line = line.strip() + if not line: + continue + + m = re.match(r"(?i)^(name|label|类别|名称)\s*[::]\s*(.+)$", line) + if m: + flush() + current["name"] = m.group(2).strip().strip('"') + continue + + m = re.match(r"(?i)^(num|count|instances|数量)\s*[::]\s*(.+)$", line) + if m: + current["num"] = m.group(2).strip().strip('"') + continue + + m = re.match(r"(?i)^(visual_description|visual description|desc|description|描述)\s*[::]\s*(.+)$", line) + if m: + current["visual_description"] = m.group(2).strip().strip('"') + continue + + m = re.match(r"(?i)^(is_occluded|is occluded|occluded|被遮挡)\s*[::]\s*(.+)$", line) + if m: + current["is_occluded"] = m.group(2).strip().strip('"') + continue + + m = re.match(r"(?i)^(occluded_by|occluded by|遮挡者)\s*[::]\s*(.+)$", line) + if m: + current["occluded_by"] = m.group(2).strip().strip('"') + continue + + m = re.match(r"^\d+\s*[\.\)]\s*([a-zA-Z][\w\s\-]+)(?:\s*\(?(?:num|count)\s*=?\s*(\d+)\)?)?$", line) + if m: + flush() + current["name"] = m.group(1).strip() + if m.group(2): + current["num"] = m.group(2).strip() + continue + + flush() + return objects + + +def run_qwen_on_image( + image_path: Path, + model, + processor, + max_new_tokens: int, + max_objects: int, + max_count_per_label: int, + aggregate_threshold: int, +) -> Optional[Dict[str, Any]]: + image = Image.open(image_path).convert("RGB") + prompt = build_prompt(max_objects, aggregate_threshold) + messages = [ + { + "role": "user", + "content": [ + {"type": "image", "image": image}, + {"type": "text", "text": prompt}, + ], + } + ] + + inputs = processor.apply_chat_template( + messages, + tokenize=True, + add_generation_prompt=True, + return_tensors="pt", + return_dict=True, + ) + inputs = {k: v.to(model.device) for k, v in inputs.items()} + + with torch.no_grad(): + generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens) + + trimmed = [ + out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs["input_ids"], generated_ids) + ] + outputs = processor.batch_decode( + trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False + ) + + if not outputs: + print("[ERROR] 模型没有返回内容") + return None + + raw = outputs[0].strip() + print("\n[RAW OUTPUT]") + print(raw) + + parsed = extract_json(raw) + + items: List[Any] = [] + if parsed is None: + parsed_objs = parse_objects_from_text(raw) + if parsed_objs: + print("[WARN] JSON 解析失败,已从文本解析 objects") + items = parsed_objs + else: + m = re.search(r'"labels"\s*:\s*\[', raw) + sub = raw[m.end():] if m else raw + labels = re.findall(r'"([^"]+)"', sub) + labels = [x for x in labels if x.lower() != "labels"] + if labels: + print("[WARN] JSON 不完整,已从文本中提取 labels") + items = labels + else: + print("[ERROR] 解析 JSON 失败") + return None + else: + if isinstance(parsed, dict): + if isinstance(parsed.get("objects"), list): + items = parsed.get("objects", []) + elif isinstance(parsed.get("labels"), list): + items = parsed.get("labels", []) + elif isinstance(parsed, list): + items = parsed + + if not items: + print("[ERROR] 未获取到任何 objects/labels") + return None + + label_order: List[str] = [] + label_counts: Dict[str, int] = {} + label_desc: Dict[str, str] = {} + label_occluded: Dict[str, bool] = {} + label_occluded_by: Dict[str, List[str]] = {} + + for item in items: + if isinstance(item, dict): + name_raw = str( + item.get("name") + or item.get("label") + or item.get("prompt") + or item.get("category") + or "" + ).strip() + num_raw = ( + item.get("num") + or item.get("count") + or item.get("instances") + or item.get("instance_count") + ) + desc = str(item.get("visual_description") or item.get("desc") or "").strip() + occ = item.get("is_occluded", False) + occ_by = item.get("occluded_by", []) + else: + name_raw = str(item).strip() + num_raw = None + desc = "" + occ = False + occ_by = [] + + name = normalize_label(name_raw) + if not name or name in _RESERVED_LABELS: + continue + + num = _as_int(num_raw, default=1) + if num <= 0: + continue + + if aggregate_threshold > 0 and num > aggregate_threshold: + if name in _AGGREGATE_MAP: + name = _AGGREGATE_MAP[name] + else: + name = f"{name}_group" + num = 1 + elif max_count_per_label > 0 and num > max_count_per_label: + num = max_count_per_label + + if name not in label_counts: + label_order.append(name) + label_counts[name] = num + else: + label_counts[name] = max(label_counts[name], num) + + if desc and name not in label_desc: + label_desc[name] = desc + + occ_val = _parse_bool(occ) + if occ_val: + label_occluded[name] = True + + if isinstance(occ_by, list): + label_occluded_by.setdefault(name, []) + label_occluded_by[name].extend([str(x) for x in occ_by if str(x).strip()]) + + if len(label_order) > max_objects: + label_order = label_order[:max_objects] + print(f"[WARN] labels 超出上限,已裁剪到 {len(label_order)} 条") + + objects_out: List[Dict[str, Any]] = [] + for name in label_order: + obj: Dict[str, Any] = { + "name": name, + "num": int(label_counts.get(name, 1)), + } + if name in label_desc: + obj["visual_description"] = label_desc[name] + if label_occluded.get(name, False): + obj["is_occluded"] = True + if name in label_occluded_by: + obj["occluded_by"] = label_occluded_by[name] + objects_out.append(obj) + + return { + "labels": label_order, + "label_counts": {k: int(v) for k, v in label_counts.items() if k in label_order}, + "objects": objects_out, + } + + +def save_label_json( + scene_dir: Path, + image_name: str, + labels: List[str], + label_counts: Optional[Dict[str, int]] = None, + objects: Optional[List[Dict[str, Any]]] = None, +) -> Path: + label_json_path = scene_dir / "label.json" + data = { + "image": image_name, + "labels": labels, + } + if label_counts: + data["label_counts"] = label_counts + if objects: + data["objects"] = objects + with label_json_path.open("w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=2) + return label_json_path + + +def main() -> None: + parser = argparse.ArgumentParser(description="Qwen3-VL 生成 label.json(label-only)") + parser.add_argument("--scene-dir", type=Path, help="单个场景目录,内含一张场景 RGB 图") + parser.add_argument( + "--scene-range", + type=str, + help='批量模式,形如 "1-4,6,8"(按 scene_{:02d} 命名)', + ) + parser.add_argument( + "--root-dir", + type=Path, + default=Path(__file__).resolve().parents[2] / "data_pose" / "scenes", + help="场景根目录(默认 data_pose/scenes)", + ) + parser.add_argument( + "--model", + type=str, + default="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/public_ckpts/model/Qwen3-VL-32B-Instruct", + help="Qwen3-VL 模型路径或 HF ID(默认本地 32B)", + ) + parser.add_argument("--max-objects", type=int, default=15, help="最多检测多少个物体(默认 15)") + parser.add_argument( + "--max-count-per-label", + type=int, + default=20, + help="单个类别允许的最大实例数,超出则自动压缩或聚合(默认 20)", + ) + parser.add_argument( + "--aggregate-threshold", + type=int, + default=10, + help="某类别数量超过阈值时合并为整体类别并将 num=1(默认 10)", + ) + parser.add_argument("--max-new-tokens", type=int, default=512, help="生成最大 tokens(默认 512)") + parser.add_argument( + "--keep-labels", + type=str, + default="", + help="仅保留指定 labels(逗号分隔,如 chair,table)", + ) + parser.add_argument( + "--drop-labels", + type=str, + default="", + help="过滤指定 labels(逗号分隔,如 floor,wall)", + ) + + args = parser.parse_args() + + scene_dirs: List[Path] = [] + if args.scene_dir: + scene_dirs = [args.scene_dir.resolve()] + if args.scene_range: + def parse_scene_spec(spec: str) -> List[int]: + ids: List[int] = [] + for chunk in spec.split(","): + chunk = chunk.strip() + if not chunk: + continue + if "-" in chunk: + a, b = chunk.split("-", 1) + start, end = int(a), int(b) + if end < start: + start, end = end, start + ids.extend(range(start, end + 1)) + else: + ids.append(int(chunk)) + return sorted(set(ids)) + + for sid in parse_scene_spec(args.scene_range): + scene_dirs.append(args.root_dir / f"scene_{sid:02d}") + + if not scene_dirs: + raise ValueError("必须提供 --scene-dir 或 --scene-range") + + print(f"[INFO] 使用模型: {args.model}") + model = AutoModelForImageTextToText.from_pretrained( + args.model, + dtype="auto", + device_map="auto" if torch.cuda.is_available() else None, + ) + processor = AutoProcessor.from_pretrained(args.model) + + keep_set = {normalize_label(x) for x in (args.keep_labels or "").split(",") if x.strip()} + drop_set = {normalize_label(x) for x in (args.drop_labels or "").split(",") if x.strip()} + + for scene_dir in scene_dirs: + if not scene_dir.is_dir(): + print(f"[WARN] scene 目录不存在,跳过: {scene_dir}") + continue + + image_name = find_single_image_file(scene_dir) + if image_name is None: + continue + image_path = scene_dir / image_name + + print(f"\n===== 处理 {scene_dir.name} =====") + result = run_qwen_on_image( + image_path=image_path, + model=model, + processor=processor, + max_new_tokens=args.max_new_tokens, + max_objects=args.max_objects, + max_count_per_label=args.max_count_per_label, + aggregate_threshold=args.aggregate_threshold, + ) + if not result: + print("[ERROR] 没有生成 labels,label.json 不会写入") + continue + + labels = result.get("labels", []) + label_counts = result.get("label_counts", {}) + objects = result.get("objects", []) + + if keep_set: + labels = [x for x in labels if normalize_label(x) in keep_set] + if drop_set: + labels = [x for x in labels if normalize_label(x) not in drop_set] + if not labels: + print("[WARN] 过滤后无 labels,label.json 不会写入") + continue + if label_counts: + label_counts = {k: v for k, v in label_counts.items() if k in set(labels)} + if objects: + objects = [o for o in objects if normalize_label(o.get("name", "")) in set(labels)] + + label_json_path = save_label_json( + scene_dir, + image_name, + labels, + label_counts=label_counts, + objects=objects, + ) + print(f"[OK] 已写入 {label_json_path}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/masking/qwen_build_scene_json.py b/OVOW/masking/qwen_build_scene_json.py new file mode 100644 index 0000000000000000000000000000000000000000..f5a2b5bf96be3b56091af1730822aab887d2bed2 --- /dev/null +++ b/OVOW/masking/qwen_build_scene_json.py @@ -0,0 +1,453 @@ +#!/usr/bin/env python +""" +只输入一张 RGB 场景图,让 Qwen3-VL 产出 scene.json(objects + prompt + is_occluded)。 +此脚本不需要已有 mask,生成的每个 object 会带上默认 mask 路径:masks/{id}.png,供后续 SAM2 使用。 + +使用示例: + conda activate qwen + python Grounded_SAM2/qwen/qwen_build_scene_json.py \ + --scene-dir data_pose/scenes/scene_12 \ + --model Grounded_SAM2/qwen/model/Qwen3-VL-8B-Instruct +""" + +import argparse +import base64 +import json +import os +import re +from pathlib import Path +from typing import Any, Dict, List, Optional + +from PIL import Image + + +def find_single_image_file(scene_dir: Path) -> Optional[str]: + """在目录下寻找唯一的 jpg/png/jpeg 文件,返回文件名。""" + exts = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG"} + candidates = [p.name for p in scene_dir.iterdir() if p.is_file() and p.suffix in exts] + if len(candidates) == 1: + return candidates[0] + if len(candidates) == 0: + print(f"[ERROR] {scene_dir} 下未找到 jpg/png 图片") + else: + print(f"[ERROR] {scene_dir} 下存在多张图片 {candidates},无法确定场景图像") + return None + + +def extract_json(text: str) -> Optional[Dict[str, Any]]: + """尽量从模型输出中提取 JSON。""" + try: + return json.loads(text) + except Exception: + pass + m = re.search(r"\{.*\}", text, flags=re.DOTALL) + if not m: + return None + try: + return json.loads(m.group(0)) + except Exception: + return None + + +def build_prompt(max_objects: int, aggregate_threshold: int) -> str: + return ( + "请分析给定图像用于语义分割任务。识别图中所有可见物体类别,并估计每个类别的实例数量。" + "输出 JSON,且只输出 JSON。" + "规则:" + "1) 特异性优先:使用最具体的功能性名称(如 computer/car),禁止通用词。" + "2) 互斥性:不要输出包含关系或部件词(如 person 与 clothes/hand)。" + "3) name 必须是英文、小写、单数名词;形容词仅放在 visual_description。" + "4) 每个类别只输出一次,附带你检测到的该类别实例数量 num(整数>=1)。" + f"5) 如果某类别数量 > {aggregate_threshold},请用整体类别名替代并将 num=1(如 tree→forest,person→crowd,building→building_complex)。" + "6) 遮挡检测:若被其他物体遮挡面积明显(>10%),is_occluded=true;否则 false。" + "7) occluded_by 只能填列表中已有的 name;否则留空数组。" + "8) 严禁部件级标签:不要输出 hair/head/face/hand/arm/leg 等人体部件;" + "若角色持有装备,仅保留主体类别,不要单独输出装备或部件。" + "9) 忽略背景与装饰:不要输出 sky/path/ground/wall/light/shadow/text/rune inscription 等环境或纹理标签。" + "10) 若目标过小、严重模糊、边界不清、无法稳定分割,则不要输出。" + f"最多输出 {max_objects} 个类别。" + "禁止词汇:box, object, thing, item, container, shape。" + "输出格式:" + "{\"objects\": [{\"name\": \"computer\", \"num\": 1, \"visual_description\": \"...\", " + "\"is_occluded\": false, \"occluded_by\": []}]}" + ) + + +def _normalize_qwen_objects(raw_objects: List[Any]) -> List[Dict[str, Any]]: + objects: List[Dict[str, Any]] = [] + + def compress_prompt(text: str) -> str: + """压缩为“形容词/空间词 + 核心名词”短语,去逗号/动词/介词,保持位置词如 top/bottom/left/right/front/back。""" + stop_words = { + "on", "in", "at", "by", "near", "next", "with", "holding", + "above", "below", "under", "over", "between", "among", + "sitting", "standing", "lying", "placed", "located", "is", "are", + } + text = text.split(".")[0] + text = text.replace(",", " ").replace(";", " ").lower() + tokens = [t for t in text.split() if t and t not in stop_words] + return " ".join(tokens).strip() + + if raw_objects and all(isinstance(x, str) for x in raw_objects): + tmp = [] + for i, phrase in enumerate(raw_objects): + phrase = phrase.strip() + if not phrase: + continue + tmp.append( + { + "id": f"obj{i+1}", + "name": phrase, + "prompt": phrase, + "is_occluded": False, + } + ) + raw_objects = tmp + + for item in raw_objects: + if not isinstance(item, dict): + continue + obj_id = str(item.get("id") or item.get("name") or "").strip() + name = str(item.get("name") or obj_id).strip() + prompt_txt = str(item.get("prompt") or name).strip() + occ = item.get("is_occluded", False) + if not obj_id: + obj_id = f"obj{len(objects)+1}" + + prompt_txt = compress_prompt(prompt_txt) + if prompt_txt: + name = prompt_txt + + objects.append( + { + "id": obj_id, + "name": name, + "prompt": name, + "is_occluded": bool( + str(occ).lower() in ("true", "yes", "y", "1", "是", "被遮挡") + if isinstance(occ, str) + else occ + ), + } + ) + + return objects + + +def _decode_chat_content(content: Any) -> str: + if isinstance(content, str): + return content.strip() + if isinstance(content, list): + chunks: List[str] = [] + for item in content: + if isinstance(item, dict): + txt = item.get("text") + else: + txt = getattr(item, "text", None) + if isinstance(txt, str) and txt.strip(): + chunks.append(txt.strip()) + return "\n".join(chunks).strip() + return str(content).strip() + + +def _extract_completion_text(resp: Any) -> str: + try: + message = resp.choices[0].message + except Exception: + return "" + content = getattr(message, "content", "") + return _decode_chat_content(content) + + +def _encode_image_data_url(image_path: Path) -> str: + suffix = image_path.suffix.lower() + mime_map = { + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".png": "image/png", + ".webp": "image/webp", + } + mime = mime_map.get(suffix, "image/jpeg") + b64 = base64.b64encode(image_path.read_bytes()).decode("ascii") + return f"data:{mime};base64,{b64}" + + +def _parse_qwen_response(raw: str) -> Optional[List[Dict[str, Any]]]: + print("\n[RAW OUTPUT]") + print(raw) + + parsed = extract_json(raw) + if parsed is None or "objects" not in parsed or not isinstance(parsed["objects"], list): + print("[ERROR] 解析 JSON 失败或缺少 objects 字段") + return None + + return _normalize_qwen_objects(parsed["objects"]) + + +def run_qwen_on_image_local( + image_path: Path, + model: Any, + processor: Any, + max_new_tokens: int, + max_objects: int, + aggregate_threshold: int, +) -> Optional[List[Dict[str, Any]]]: + import torch + + image = Image.open(image_path).convert("RGB") + prompt = build_prompt(max_objects, aggregate_threshold) + messages = [ + { + "role": "user", + "content": [ + {"type": "image", "image": image}, + {"type": "text", "text": prompt}, + ], + } + ] + + inputs = processor.apply_chat_template( + messages, + tokenize=True, + add_generation_prompt=True, + return_tensors="pt", + return_dict=True, + ) + inputs = {k: v.to(model.device) for k, v in inputs.items()} + + with torch.no_grad(): + generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens) + + trimmed = [ + out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs["input_ids"], generated_ids) + ] + outputs = processor.batch_decode( + trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False + ) + + if not outputs: + print("[ERROR] 模型没有返回内容") + return None + + raw = outputs[0].strip() + return _parse_qwen_response(raw) + + +def run_qwen_on_image_api( + image_path: Path, + client: Any, + model_name: str, + max_new_tokens: int, + max_objects: int, + aggregate_threshold: int, +) -> Optional[List[Dict[str, Any]]]: + prompt = build_prompt(max_objects, aggregate_threshold) + image_url = _encode_image_data_url(image_path) + resp = client.chat.completions.create( + model=model_name, + messages=[ + { + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": image_url}}, + {"type": "text", "text": prompt}, + ], + } + ], + max_tokens=max_new_tokens, + temperature=0.0, + ) + raw = _extract_completion_text(resp) + if not raw: + print("[ERROR] API 没有返回内容") + return None + return _parse_qwen_response(raw) + + +def save_scene_json( + scene_dir: Path, + image_name: str, + objects: List[Dict[str, Any]], + mask_dir_name: str = "masks", +) -> Path: + scene_json_path = scene_dir / "scene.json" + for obj in objects: + obj["mask"] = f"{mask_dir_name}/{obj['id']}.png" + + data = { + "image": image_name, + "objects": objects, + } + + with scene_json_path.open("w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=2) + return scene_json_path + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Qwen3-VL 生成/更新 scene.json(objects + prompt + is_occluded)" + ) + parser.add_argument( + "--scene-dir", + type=Path, + help="单个场景目录,内含一张场景 RGB 图", + ) + parser.add_argument( + "--scene-range", + type=str, + help='批量模式,形如 "1-4,6,8"(按 scene_{:02d} 命名)', + ) + parser.add_argument( + "--root-dir", + type=Path, + default=Path(__file__).resolve().parents[2] / "data_pose" / "scenes", + help="场景根目录(默认 data_pose/scenes)", + ) + parser.add_argument( + "--backend", + type=str, + default="api", + choices=("api", "local"), + help="Qwen 后端:api(默认)或 local", + ) + parser.add_argument( + "--model", + type=str, + default="Qwen/Qwen3-VL-8B-Instruct", + help="Qwen3-VL 本地模型路径或 HF ID(backend=local 时使用)", + ) + parser.add_argument( + "--qwen-api-model", + type=str, + default="qwen3.5-plus", + help="Qwen API 模型名(backend=api 时使用)", + ) + parser.add_argument( + "--qwen-api-base-url", + type=str, + default="https://dashscope.aliyuncs.com/compatible-mode/v1", + help="DashScope OpenAI-compatible base URL(backend=api 时使用)", + ) + parser.add_argument( + "--qwen-api-key-env", + type=str, + default="DASHSCOPE_API_KEY", + help="存放 API key 的环境变量名(backend=api 时使用)", + ) + parser.add_argument( + "--max-objects", + type=int, + default=10, + help="最多检测多少个物体(默认 10)", + ) + parser.add_argument( + "--aggregate-threshold", + type=int, + default=10, + help="类别聚合阈值,超过时使用整体类别名(默认 10)", + ) + parser.add_argument( + "--max-new-tokens", + type=int, + default=512, + help="生成最大 tokens(默认 512)", + ) + + args = parser.parse_args() + scene_dirs: List[Path] = [] + if args.scene_dir: + scene_dirs = [args.scene_dir.resolve()] + if args.scene_range: + def parse_scene_spec(spec: str) -> List[int]: + ids: List[int] = [] + for chunk in spec.split(","): + chunk = chunk.strip() + if not chunk: + continue + if "-" in chunk: + a, b = chunk.split("-", 1) + start, end = int(a), int(b) + if end < start: + start, end = end, start + ids.extend(range(start, end + 1)) + else: + ids.append(int(chunk)) + return sorted(set(ids)) + + for sid in parse_scene_spec(args.scene_range): + scene_dirs.append(args.root_dir / f"scene_{sid:02d}") + + if not scene_dirs: + raise ValueError("必须提供 --scene-dir 或 --scene-range") + + model = None + processor = None + client = None + if args.backend == "local": + import torch + from transformers import AutoModelForImageTextToText, AutoProcessor + + print(f"[INFO] 使用本地模型: {args.model}") + model = AutoModelForImageTextToText.from_pretrained( + args.model, + dtype="auto", + device_map="auto" if torch.cuda.is_available() else None, + ) + processor = AutoProcessor.from_pretrained(args.model) + else: + try: + from openai import OpenAI # type: ignore + except Exception as exc: + raise RuntimeError( + "当前环境缺少 openai SDK,无法使用 API 模式。" + ) from exc + + api_key = os.getenv(args.qwen_api_key_env, "").strip() + if not api_key: + raise RuntimeError( + f"缺少 API key,请设置环境变量:{args.qwen_api_key_env}" + ) + print(f"[INFO] 使用 API 模型: {args.qwen_api_model}") + print(f"[INFO] API base URL: {args.qwen_api_base_url}") + client = OpenAI(api_key=api_key, base_url=args.qwen_api_base_url) + + for scene_dir in scene_dirs: + if not scene_dir.is_dir(): + print(f"[WARN] scene 目录不存在,跳过: {scene_dir}") + continue + + image_name = find_single_image_file(scene_dir) + if image_name is None: + continue + image_path = scene_dir / image_name + + print(f"\n===== 处理 {scene_dir.name} =====") + if args.backend == "local": + objects = run_qwen_on_image_local( + image_path=image_path, + model=model, + processor=processor, + max_new_tokens=args.max_new_tokens, + max_objects=args.max_objects, + aggregate_threshold=args.aggregate_threshold, + ) + else: + objects = run_qwen_on_image_api( + image_path=image_path, + client=client, + model_name=args.qwen_api_model, + max_new_tokens=args.max_new_tokens, + max_objects=args.max_objects, + aggregate_threshold=args.aggregate_threshold, + ) + if not objects: + print("[ERROR] 没有生成 objects,scene.json 不会写入") + continue + + scene_json_path = save_scene_json(scene_dir, image_name, objects) + print(f"[OK] 已写入 {scene_json_path}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/masking/qwen_build_scene_json_label_only.py b/OVOW/masking/qwen_build_scene_json_label_only.py new file mode 100644 index 0000000000000000000000000000000000000000..5b910cd46fa343086ba611561f806b874b347457 --- /dev/null +++ b/OVOW/masking/qwen_build_scene_json_label_only.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python +""" +只输入一张 RGB 场景图,让 Qwen3-VL 产出 label-only 的 scene.json。 +与 qwen_build_scene_json.py 区别: + - 只要求输出「物体类别标签」(label),不含颜色/材质/空间等描述词 + - 允许同类多实例:用 label 作为 name/prompt,id 自动加序号(chair_01, chair_02) + +使用示例: + conda activate qwen + python Grounded_SAM2/qwen/qwen_build_scene_json_label_only.py \ + --scene-dir data_pose/scenes/scene_12 \ + --model Grounded_SAM2/qwen/model/Qwen3-VL-8B-Instruct +""" + +import argparse +import json +import re +from collections import defaultdict +from pathlib import Path +from typing import Any, Dict, List, Optional + +from PIL import Image +import torch +from transformers import AutoModelForImageTextToText, AutoProcessor + + +def find_single_image_file(scene_dir: Path) -> Optional[str]: + """在目录下寻找唯一的 jpg/png/jpeg 文件,返回文件名。""" + exts = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG"} + candidates = [p.name for p in scene_dir.iterdir() if p.is_file() and p.suffix in exts] + if len(candidates) == 1: + return candidates[0] + if len(candidates) == 0: + print(f"[ERROR] {scene_dir} 下未找到 jpg/png 图片") + else: + print(f"[ERROR] {scene_dir} 下存在多张图片 {candidates},无法确定场景图像") + return None + + +def extract_json(text: str) -> Optional[Dict[str, Any]]: + """尽量从模型输出中提取 JSON。""" + try: + return json.loads(text) + except Exception: + pass + m = re.search(r"\{.*\}", text, flags=re.DOTALL) + if not m: + return None + try: + return json.loads(m.group(0)) + except Exception: + return None + + +def build_prompt(max_objects: int) -> str: + return ( + "You are a vision expert. Detect up to " + f"{max_objects} distinct object instances in the image. " + "OUTPUT ONLY object CATEGORY LABELS (nouns). " + "NO colors, NO materials, NO size/shape words, NO spatial words (left/right/front/back/top/bottom), " + "NO brand names, NO adjectives. " + "If there are multiple instances of the same category, OUTPUT the label ONLY ONCE. " + f"Do NOT exceed {max_objects} total labels. " + "Return JSON ONLY in the form: {\"labels\": [\"chair\", \"table\"]}. " + "Do NOT output object parts (wheels, tires, windows, etc.). " + "Ignore background stuff (sky/road/grass/sea/clouds) unless it is the main subject." + ) + + +_STOP_WORDS = { + "red", "blue", "green", "yellow", "orange", "purple", "pink", "black", "white", + "brown", "gray", "grey", "gold", "silver", "beige", "tan", + "wood", "wooden", "metal", "plastic", "glass", "ceramic", "leather", "fabric", + "cloth", "steel", "iron", "aluminum", "stone", "marble", + "small", "large", "big", "tiny", "round", "square", "rectangular", "circular", + "left", "right", "front", "back", "top", "bottom", "upper", "lower", "center", +} + + +def normalize_label(text: str) -> str: + """尽量去掉描述词,保留 label。""" + t = text.strip().lower() + t = re.sub(r"[_\-]+", " ", t) + t = re.sub(r"[^\w\s]", " ", t) + tokens = [tok for tok in t.split() if tok and tok not in _STOP_WORDS] + cleaned = " ".join(tokens).strip() + return cleaned or t + + +def slugify(text: str) -> str: + t = text.strip().lower() + t = re.sub(r"[^\w\s]", " ", t) + t = re.sub(r"\s+", "_", t).strip("_") + return t or "obj" + + +def run_qwen_on_image( + image_path: Path, + model, + processor, + max_new_tokens: int, + max_objects: int, + max_per_label: int, +) -> Optional[List[str]]: + image = Image.open(image_path).convert("RGB") + prompt = build_prompt(max_objects) + messages = [ + { + "role": "user", + "content": [ + {"type": "image", "image": image}, + {"type": "text", "text": prompt}, + ], + } + ] + + inputs = processor.apply_chat_template( + messages, + tokenize=True, + add_generation_prompt=True, + return_tensors="pt", + return_dict=True, + ) + inputs = {k: v.to(model.device) for k, v in inputs.items()} + + with torch.no_grad(): + generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens) + + trimmed = [ + out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs["input_ids"], generated_ids) + ] + outputs = processor.batch_decode( + trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False + ) + + if not outputs: + print("[ERROR] 模型没有返回内容") + return None + + raw = outputs[0].strip() + print("\n[RAW OUTPUT]") + print(raw) + + parsed = extract_json(raw) + + labels: List[str] = [] + if parsed is None: + m = re.search(r'"labels"\s*:\s*\[', raw) + sub = raw[m.end():] if m else raw + labels = re.findall(r'"([^"]+)"', sub) + labels = [x for x in labels if x.lower() != "labels"] + if labels: + print("[WARN] JSON 不完整,已从文本中提取 labels") + else: + print("[ERROR] 解析 JSON 失败") + return None + + if not labels: + if isinstance(parsed, dict) and isinstance(parsed.get("labels"), list): + labels = [str(x) for x in parsed.get("labels", [])] + elif isinstance(parsed, list): + labels = [str(x) for x in parsed] + elif isinstance(parsed, dict) and isinstance(parsed.get("objects"), list): + for obj in parsed.get("objects", []): + if isinstance(obj, dict): + labels.append(str(obj.get("name") or obj.get("prompt") or "")) + elif isinstance(obj, str): + labels.append(obj) + + labels = [normalize_label(x) for x in labels if str(x).strip()] + labels = [x for x in labels if x] + + uniq: List[str] = [] + seen = set() + for lbl in labels: + if lbl in seen: + continue + seen.add(lbl) + uniq.append(lbl) + + if len(uniq) > max_objects: + uniq = uniq[:max_objects] + print(f"[WARN] labels 超出上限,已裁剪到 {len(uniq)} 条") + return uniq + + +def build_objects_from_labels(labels: List[str]) -> List[Dict[str, Any]]: + objects: List[Dict[str, Any]] = [] + counters = defaultdict(int) + for label in labels: + base = slugify(label) + counters[base] += 1 + obj_id = f"{base}_{counters[base]:02d}" + objects.append( + { + "id": obj_id, + "name": label, + "prompt": label, + "is_occluded": False, + } + ) + return objects + + +def save_scene_json( + scene_dir: Path, + image_name: str, + objects: List[Dict[str, Any]], + mask_dir_name: str = "masks", +) -> Path: + scene_json_path = scene_dir / "scene.json" + for obj in objects: + obj["mask"] = f"{mask_dir_name}/{obj['id']}.png" + + data = { + "image": image_name, + "objects": objects, + } + + with scene_json_path.open("w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, indent=2) + return scene_json_path + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Qwen3-VL 生成/更新 scene.json(label-only)" + ) + parser.add_argument( + "--scene-dir", + type=Path, + help="单个场景目录,内含一张场景 RGB 图", + ) + parser.add_argument( + "--scene-range", + type=str, + help='批量模式,形如 "1-4,6,8"(按 scene_{:02d} 命名)', + ) + parser.add_argument( + "--root-dir", + type=Path, + default=Path(__file__).resolve().parents[2] / "data_pose" / "scenes", + help="场景根目录(默认 data_pose/scenes)", + ) + parser.add_argument( + "--model", + type=str, + default="Qwen/Qwen3-VL-8B-Instruct", + help="Qwen3-VL 模型路径或 HF ID(默认本地 8B)", + ) + parser.add_argument( + "--max-objects", + type=int, + default=15, + help="最多检测多少个物体(默认 15)", + ) + parser.add_argument( + "--max-per-label", + type=int, + default=5, + help="每个 label 最多保留多少个实例(默认 5)", + ) + parser.add_argument( + "--keep-labels", + type=str, + default="", + help="仅保留指定 labels(逗号分隔,如 chair,table)", + ) + parser.add_argument( + "--drop-labels", + type=str, + default="", + help="过滤指定 labels(逗号分隔,如 floor,wall)", + ) + parser.add_argument( + "--max-new-tokens", + type=int, + default=512, + help="生成最大 tokens(默认 512)", + ) + + args = parser.parse_args() + scene_dirs: List[Path] = [] + if args.scene_dir: + scene_dirs = [args.scene_dir.resolve()] + if args.scene_range: + def parse_scene_spec(spec: str) -> List[int]: + ids: List[int] = [] + for chunk in spec.split(","): + chunk = chunk.strip() + if not chunk: + continue + if "-" in chunk: + a, b = chunk.split("-", 1) + start, end = int(a), int(b) + if end < start: + start, end = end, start + ids.extend(range(start, end + 1)) + else: + ids.append(int(chunk)) + return sorted(set(ids)) + + for sid in parse_scene_spec(args.scene_range): + scene_dirs.append(args.root_dir / f"scene_{sid:02d}") + + if not scene_dirs: + raise ValueError("必须提供 --scene-dir 或 --scene-range") + + print(f"[INFO] 使用模型: {args.model}") + model = AutoModelForImageTextToText.from_pretrained( + args.model, + dtype="auto", + device_map="auto" if torch.cuda.is_available() else None, + ) + processor = AutoProcessor.from_pretrained(args.model) + + for scene_dir in scene_dirs: + if not scene_dir.is_dir(): + print(f"[WARN] scene 目录不存在,跳过: {scene_dir}") + continue + + image_name = find_single_image_file(scene_dir) + if image_name is None: + continue + image_path = scene_dir / image_name + + print(f"\n===== 处理 {scene_dir.name} =====") + labels = run_qwen_on_image( + image_path=image_path, + model=model, + processor=processor, + max_new_tokens=args.max_new_tokens, + max_objects=args.max_objects, + max_per_label=args.max_per_label, + ) + if not labels: + print("[ERROR] 没有生成 labels,scene.json 不会写入") + continue + + keep_set = {normalize_label(x) for x in (args.keep_labels or "").split(",") if x.strip()} + drop_set = {normalize_label(x) for x in (args.drop_labels or "").split(",") if x.strip()} + if keep_set: + labels = [x for x in labels if normalize_label(x) in keep_set] + if drop_set: + labels = [x for x in labels if normalize_label(x) not in drop_set] + if not labels: + print("[WARN] 过滤后无 labels,scene.json 不会写入") + continue + + objects = build_objects_from_labels(labels) + scene_json_path = save_scene_json(scene_dir, image_name, objects) + print(f"[OK] 已写入 {scene_json_path}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/masking/qwen_labels.py b/OVOW/masking/qwen_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..7ba0dfec570467d52ff168de5163aab736f4148b --- /dev/null +++ b/OVOW/masking/qwen_labels.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python +""" +Label-only 版本的 Qwen 输出 label.json 入口。 +""" + +from qwen_build_label_json import main + + +if __name__ == "__main__": + main() diff --git a/OVOW/masking/qwen_new.py b/OVOW/masking/qwen_new.py new file mode 100644 index 0000000000000000000000000000000000000000..15fefea3e098839bb527ec513ce325d0122458f6 --- /dev/null +++ b/OVOW/masking/qwen_new.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python +""" +Label-only 版本的 Qwen scene.json 生成入口。 +等价于运行 qwen_build_scene_json_label_only.py。 +""" + +from qwen_build_scene_json_label_only import main + + +if __name__ == "__main__": + main() diff --git a/OVOW/masking/qwen_sam3.sh b/OVOW/masking/qwen_sam3.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a4123d930f9b206bef96dc8886a85419e28091e --- /dev/null +++ b/OVOW/masking/qwen_sam3.sh @@ -0,0 +1,13 @@ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-opg/bin/python \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/masking/qwen_sam3_video_masks.py \ + --mode labels \ + --qwen-motion \ + --video-path /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/examples/videos/scene1/V1.mp4 \ + --output-root /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs + + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/miniconda3/envs/ovow-sam3/bin/python \ + /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/masking/qwen_sam3_video_masks.py \ + --mode masks \ + --dynamic-source hybrid \ + --labels-json /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs/metadata/V1_labels.json \ + --output-root /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/outputs \ No newline at end of file diff --git a/OVOW/masking/qwen_sam3_single_image_masks.py b/OVOW/masking/qwen_sam3_single_image_masks.py new file mode 100644 index 0000000000000000000000000000000000000000..1cfc92243ae188c1eaa03955333015bbb1b52de5 --- /dev/null +++ b/OVOW/masking/qwen_sam3_single_image_masks.py @@ -0,0 +1,1018 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence, Tuple + +import numpy as np +from PIL import Image + +_THIS_DIR = Path(__file__).resolve().parent +_GSAM_ROOT = _THIS_DIR.parent +_REPO_ROOT = _GSAM_ROOT.parent +_SAM3_ROOT = _REPO_ROOT / "sam3" +sys.path.insert(0, str(_THIS_DIR)) +sys.path.insert(0, str(_GSAM_ROOT)) +sys.path.insert(0, str(_SAM3_ROOT)) + +from qwen_sam3_video_masks import ( # type: ignore + DEFAULT_QWEN_API_MODEL, + DEFAULT_QWEN_API_MODEL_LIST, + _build_qwen_api_model_candidates, + _extract_json_payload, + _merge_labels, + _run_qwen_api_chat_with_fallback, + _safe_id, + _simple_normalize, +) + + +def _resolve_path_arg(raw: Path | str, base: Path) -> Path: + path = Path(raw).expanduser() + if not path.is_absolute(): + path = (base / path).resolve() + return path + + +def _parse_csv_set(raw: str) -> set[str]: + items = [_simple_normalize(x) for x in str(raw or "").split(",")] + return {x for x in items if x} + + +def _load_scene_json_image(scene_dir: Path) -> Optional[Path]: + scene_json_path = scene_dir / "scene.json" + if not scene_json_path.is_file(): + return None + try: + payload = json.loads(scene_json_path.read_text(encoding="utf-8")) + except Exception: + return None + image_name = str(payload.get("image") or "").strip() + if not image_name: + return None + image_path = (scene_dir / image_name).resolve() + return image_path if image_path.is_file() else None + + +def _find_single_image(scene_dir: Path) -> Path: + scene_json_image = _load_scene_json_image(scene_dir) + if scene_json_image is not None: + return scene_json_image + + exts = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG"} + candidates = sorted(p.resolve() for p in scene_dir.iterdir() if p.is_file() and p.suffix in exts) + if len(candidates) != 1: + raise RuntimeError(f"Expected exactly one scene image in {scene_dir}, found {len(candidates)}") + return candidates[0] + + +def _image_info(image_path: Path) -> Tuple[int, int]: + with Image.open(image_path) as image: + return int(image.width), int(image.height) + + +def _labels_json_path(output_root: Path, scene_name: str, explicit_path: Optional[Path]) -> Path: + if explicit_path is not None: + return explicit_path.expanduser().resolve() + return (output_root / "metadata" / f"{scene_name}_labels.json").resolve() + + +def _summary_json_path(output_root: Path, scene_name: str) -> Path: + return (output_root / "metadata" / f"{scene_name}_mask_summary.json").resolve() + + +def _pipeline_config_path(output_root: Path, scene_name: str) -> Path: + return (output_root / "recon_ready" / scene_name / "pipeline_config.json").resolve() + + +_RESERVED_LABELS = { + "object", + "objects", + "label", + "labels", + "name", + "num", + "number", + "count", + "visual description", + "visual_description", + "description", + "reason", + "category", + "categories", + "is occluded", + "is_occluded", + "occluded by", + "occluded_by", +} + + +def _build_qwen_single_image_prompt(max_objects: int, aggregate_threshold: int) -> str: + return ( + "请分析给定图像。" + "识别可见物体类别。" + "该单图任务服务于近景物体重建,请只保留用户真正拍摄和想重建的主体物体。" + "输出 JSON,且只输出 JSON。" + "规则:" + "1) 特异性优先:使用最具体的功能性名称(如 computer/car),禁止通用词。" + "2) 互斥性:不要输出包含关系或部件词(如 person 与 clothes/hand)。" + "3) name 必须是英文、小写、单数名词;形容词仅放在 visual_description。" + "4) 每个类别只输出一次,并给出简短 reason。" + f"5) 如果某类别数量 > {aggregate_threshold},请用整体类别名替代并将 num=1(如 tree→forest,person→crowd,building→building_complex)。" + "6) 遮挡检测:若被其他物体遮挡面积明显(>10%),is_occluded=true;否则 false。" + "7) occluded_by 只能填列表中已有的 name;否则留空数组。" + "8) 严禁部件级标签:不要输出 hair/head/face/hand/arm/leg 等人体部件;" + "若角色持有装备,仅保留主体类别(如 elf),不要单独输出 armor/sword。" + "9) 主体优先:只输出近景中明确作为拍摄主体、位于中心关注区域、适合单独重建的物体。" + "10) 忽略陪衬与边缘物:位于画面边缘/角落、明显不在中心关注区域、只露出一小部分、或只是场景陪衬的物体不要输出,即使它清晰可见。" + "11) 忽略大型承载平面:如果 table/desk/floor/counter/shelf 只是用于承载主体或作为背景结构,而不是本次拍摄主体,则不要输出。" + "12) 忽略背景与装饰:不要输出 sky/path/ground/wall/light/shadow/text/rune inscription 等环境或纹理标签。" + f"最多输出 {max_objects} 个类别。" + "禁止词汇:box, object, thing, item, container, shape。" + "输出格式:" + "{\"objects\": [{\"name\": \"computer\", \"num\": 1, " + "\"visual_description\": \"...\", \"reason\": \"...\", " + "\"is_occluded\": false, \"occluded_by\": []}]}" + ) + + +def _clean_label(raw: Any) -> str: + name = _simple_normalize(str(raw or "")) + if not name or name in _RESERVED_LABELS: + return "" + return name + + +def _extract_labels_from_payload_single_image(payload: Any, max_objects: int) -> List[str]: + items: List[Any] = [] + if isinstance(payload, dict): + if isinstance(payload.get("objects"), list): + items = payload.get("objects", []) + elif isinstance(payload.get("labels"), list): + items = payload.get("labels", []) + elif isinstance(payload, list): + items = payload + + labels: List[str] = [] + seen = set() + for item in items: + if isinstance(item, dict): + raw = item.get("name") or item.get("label") + else: + raw = item + name = _clean_label(raw) + if not name or name in seen: + continue + seen.add(name) + labels.append(name) + if len(labels) >= max_objects: + break + return labels + + +def _extract_labels_from_text_fallback_single_image(raw: str, max_objects: int) -> List[str]: + labels: List[str] = [] + seen = set() + + for match in re.finditer(r'"name"\s*:\s*"([^"]+)"', raw, flags=re.IGNORECASE): + name = _clean_label(match.group(1)) + if not name or name in seen: + continue + seen.add(name) + labels.append(name) + if len(labels) >= max_objects: + return labels + + for line in raw.splitlines(): + line = line.strip() + if not line: + continue + match = re.match(r"(?i)^(?:name|label)\s*[::]\s*(.+)$", line) + if not match: + continue + name = _clean_label(match.group(1).strip().strip('",')) + if not name or name in seen: + continue + seen.add(name) + labels.append(name) + if len(labels) >= max_objects: + break + return labels + + +def _write_labels_json( + path: Path, + image_path: Path, + scene_name: str, + width: int, + height: int, + labels: List[str], +) -> None: + payload = { + "video": str(image_path), + "video_name": scene_name, + "image": str(image_path), + "image_name": image_path.name, + "num_frames": 1, + "fps": 1.0, + "width": int(width), + "height": int(height), + "keyframes": [0], + "labels": labels, + "labels_per_keyframe": {"0": list(labels)}, + } + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8") + + +def _load_labels_json(path: Path) -> Dict[str, Any]: + return json.loads(path.read_text(encoding="utf-8")) + + +def _extract_labels_from_json(path: Path) -> Tuple[List[str], Dict[int, List[str]]]: + payload = _load_labels_json(path) + raw_labels = payload.get("labels", []) + labels: List[str] = [] + seen = set() + for item in raw_labels: + name = _simple_normalize(str(item or "")) + if not name or name in seen: + continue + seen.add(name) + labels.append(name) + labels_per_keyframe_raw = payload.get("labels_per_keyframe", {}) + labels_per_keyframe: Dict[int, List[str]] = {} + if isinstance(labels_per_keyframe_raw, dict): + for key, value in labels_per_keyframe_raw.items(): + try: + frame_id = int(key) + except Exception: + continue + if not isinstance(value, list): + continue + frame_labels: List[str] = [] + local_seen = set() + for item in value: + name = _simple_normalize(str(item or "")) + if not name or name in local_seen: + continue + local_seen.add(name) + frame_labels.append(name) + labels_per_keyframe[frame_id] = frame_labels + if not labels_per_keyframe: + labels_per_keyframe = {0: list(labels)} + return labels, labels_per_keyframe + + +def _run_qwen_labels_api( + image_path: Path, + qwen_api_model: str, + qwen_api_model_list: str, + qwen_api_base_url: str, + qwen_api_key_env: str, + max_new_tokens: int, + max_objects: int, + aggregate_threshold: int, + keep_set: Optional[set[str]], + drop_set: Optional[set[str]], +) -> Tuple[List[str], str, Optional[Any]]: + try: + from openai import OpenAI # type: ignore + except Exception as exc: + raise RuntimeError( + "OpenAI SDK not available. Please install `openai` in the current environment." + ) from exc + + api_key = os.getenv(qwen_api_key_env, "").strip() + if not api_key: + raise RuntimeError(f"Missing API key. Set environment variable: {qwen_api_key_env}") + + client = OpenAI(api_key=api_key, base_url=qwen_api_base_url) + print( + f"[INFO] Qwen API fallback candidates: " + f"{_build_qwen_api_model_candidates(qwen_api_model, qwen_api_model_list)}" + ) + prompt = _build_qwen_single_image_prompt( + max_objects=max_objects, + aggregate_threshold=aggregate_threshold, + ) + raw, used_model, _attempted_models = _run_qwen_api_chat_with_fallback( + client=client, + model=qwen_api_model, + fallback_models=qwen_api_model_list, + image_paths=[image_path], + prompt=prompt, + max_new_tokens=max_new_tokens, + ) + if used_model != qwen_api_model: + print(f"[INFO] Qwen single-image API resolved model: {used_model}") + payload = _extract_json_payload(raw) + labels = ( + _extract_labels_from_payload_single_image(payload, max_objects=max_objects) + if payload is not None + else [] + ) + if not labels: + labels = _extract_labels_from_text_fallback_single_image(raw, max_objects=max_objects) + merged_labels = _merge_labels([labels], keep_set, drop_set) + return merged_labels, raw, payload + + +def _run_qwen_labels_local( + image_path: Path, + qwen_model_path: str, + max_new_tokens: int, + max_objects: int, + aggregate_threshold: int, + keep_set: Optional[set[str]], + drop_set: Optional[set[str]], +) -> Tuple[List[str], str, Optional[Any]]: + try: + import torch + from transformers import AutoModelForImageTextToText, AutoProcessor # type: ignore + except Exception as exc: + raise RuntimeError( + "Qwen dependencies not available. Please run label generation in the qwen env." + ) from exc + + model = AutoModelForImageTextToText.from_pretrained( + qwen_model_path, + dtype="auto", + device_map="auto" if torch.cuda.is_available() else None, + ) + processor = AutoProcessor.from_pretrained(qwen_model_path) + + image = Image.open(image_path).convert("RGB") + prompt = _build_qwen_single_image_prompt( + max_objects=max_objects, + aggregate_threshold=aggregate_threshold, + ) + messages = [ + { + "role": "user", + "content": [ + {"type": "image", "image": image}, + {"type": "text", "text": prompt}, + ], + } + ] + inputs = processor.apply_chat_template( + messages, + tokenize=True, + add_generation_prompt=True, + return_tensors="pt", + return_dict=True, + ) + inputs = {k: v.to(model.device) for k, v in inputs.items()} + with torch.no_grad(): + generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens) + trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs["input_ids"], generated_ids)] + outputs = processor.batch_decode( + trimmed, + skip_special_tokens=True, + clean_up_tokenization_spaces=False, + ) + raw = outputs[0].strip() if outputs else "" + payload = _extract_json_payload(raw) + labels = ( + _extract_labels_from_payload_single_image(payload, max_objects=max_objects) + if payload is not None + else [] + ) + if not labels: + labels = _extract_labels_from_text_fallback_single_image(raw, max_objects=max_objects) + merged_labels = _merge_labels([labels], keep_set, drop_set) + return merged_labels, raw, payload + + +def _run_qwen_labels( + image_path: Path, + qwen_backend: str, + qwen_model: str, + qwen_api_model: str, + qwen_api_model_list: str, + qwen_api_base_url: str, + qwen_api_key_env: str, + max_new_tokens: int, + max_objects: int, + aggregate_threshold: int, + keep_set: Optional[set[str]], + drop_set: Optional[set[str]], +) -> Tuple[List[str], str, Optional[Any]]: + if qwen_backend == "api": + return _run_qwen_labels_api( + image_path=image_path, + qwen_api_model=qwen_api_model, + qwen_api_model_list=qwen_api_model_list, + qwen_api_base_url=qwen_api_base_url, + qwen_api_key_env=qwen_api_key_env, + max_new_tokens=max_new_tokens, + max_objects=max_objects, + aggregate_threshold=aggregate_threshold, + keep_set=keep_set, + drop_set=drop_set, + ) + if qwen_backend == "local": + return _run_qwen_labels_local( + image_path=image_path, + qwen_model_path=qwen_model, + max_new_tokens=max_new_tokens, + max_objects=max_objects, + aggregate_threshold=aggregate_threshold, + keep_set=keep_set, + drop_set=drop_set, + ) + raise ValueError(f"Unsupported qwen backend: {qwen_backend}") + + +def _mask_iou(mask_a: np.ndarray, mask_b: np.ndarray) -> float: + inter = float(np.logical_and(mask_a, mask_b).sum()) + union = float(np.logical_or(mask_a, mask_b).sum()) + if union <= 0.0: + return 0.0 + return inter / union + + +def _mask_cover(mask_a: np.ndarray, mask_b: np.ndarray) -> float: + inter = float(np.logical_and(mask_a, mask_b).sum()) + denom = float(min(mask_a.sum(), mask_b.sum())) + if denom <= 0.0: + return 0.0 + return inter / denom + + +def _is_duplicate_mask(mask: np.ndarray, existing_masks: Sequence[np.ndarray]) -> bool: + for existing in existing_masks: + if _mask_iou(mask, existing) >= 0.85: + return True + if _mask_cover(mask, existing) >= 0.92: + return True + return False + + +def _save_mask(mask: np.ndarray, path: Path) -> int: + path.parent.mkdir(parents=True, exist_ok=True) + out = np.zeros(mask.shape, dtype=np.uint8) + out[mask > 0] = 255 + Image.fromarray(out).save(path) + return int((out > 0).sum()) + + +def _collect_sam3_candidates( + image_path: Path, + labels: List[str], + ckpt_path: Optional[str], + confidence_threshold: float, +) -> Tuple[Dict[str, List[Dict[str, Any]]], int, int]: + import torch + from sam3.model.sam3_image_processor import Sam3Processor # type: ignore + from sam3.model_builder import build_sam3_image_model # type: ignore + + device = "cuda" if torch.cuda.is_available() else "cpu" + model = build_sam3_image_model( + checkpoint_path=ckpt_path, + load_from_HF=ckpt_path is None, + device=device, + enable_inst_interactivity=False, + ) + processor = Sam3Processor( + model=model, + device=device, + confidence_threshold=float(confidence_threshold), + ) + + image = Image.open(image_path) + if image.mode == "RGBA": + bg = Image.new("RGBA", image.size, (255, 255, 255, 255)) + image = Image.alpha_composite(bg, image) + image = image.convert("RGB") + width, height = image.size + state = processor.set_image(image) + + label_to_candidates: Dict[str, List[Dict[str, Any]]] = {} + for label in labels: + processor.reset_all_prompts(state) + state = processor.set_text_prompt(prompt=label, state=state) + raw_masks = state.get("masks") + raw_scores = state.get("scores") + candidates: List[Dict[str, Any]] = [] + if raw_masks is not None and raw_scores is not None and len(raw_scores) > 0: + for idx in range(raw_masks.shape[0]): + mask = raw_masks[idx, 0].detach().cpu().numpy().astype(bool) + if not mask.any(): + continue + candidates.append( + { + "mask": mask, + "score": float(raw_scores[idx].detach().cpu().item()), + "proposal_index": int(idx), + } + ) + label_to_candidates[label] = candidates + return label_to_candidates, int(width), int(height) + + +def _load_image_for_sam2(image_path: Path, mode: str = "crop"): + import cv2 + import torch + from torchvision import transforms as TF + + if mode not in ("crop", "pad"): + raise ValueError("mode must be crop or pad") + img = Image.open(image_path) + if img.mode == "RGBA": + bg = Image.new("RGBA", img.size, (255, 255, 255, 255)) + img = Image.alpha_composite(bg, img) + img = img.convert("RGB") + + target_size = 518 + to_tensor = TF.ToTensor() + width, height = img.size + if mode == "pad": + if width >= height: + new_width = target_size + new_height = round(height * (new_width / width) / 14) * 14 + else: + new_height = target_size + new_width = round(width * (new_height / height) / 14) * 14 + else: + new_width = target_size + new_height = round(height * (new_width / width) / 14) * 14 + + img = img.resize((new_width, new_height), Image.Resampling.BICUBIC) + img_tensor = to_tensor(img) + if mode == "crop" and new_height > target_size: + start_y = (new_height - target_size) // 2 + img_tensor = img_tensor[:, start_y : start_y + target_size, :] + if mode == "pad": + h_padding = target_size - img_tensor.shape[1] + w_padding = target_size - img_tensor.shape[2] + if h_padding > 0 or w_padding > 0: + pad_top = h_padding // 2 + pad_bottom = h_padding - pad_top + pad_left = w_padding // 2 + pad_right = w_padding - pad_left + img_tensor = torch.nn.functional.pad( + img_tensor, + (pad_left, pad_right, pad_top, pad_bottom), + mode="constant", + value=1.0, + ) + + image_tensor = img_tensor + image_np = (image_tensor.permute(1, 2, 0).numpy() * 255).astype(np.uint8) + image_bgr = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR) + h, w = image_tensor.shape[1], image_tensor.shape[2] + return image_tensor, image_bgr, h, w + + +def _collect_sam2_candidates( + image_path: Path, + labels: List[str], + sam2_ckpt: Path, + sam2_config: Path, + gdino_config: Path, + gdino_ckpt: Path, + box_threshold: float, + text_threshold: float, +) -> Tuple[Dict[str, List[Dict[str, Any]]], int, int]: + import torch + from torchvision.ops import box_convert + + from grounding_dino.groundingdino.util.inference import load_model, predict + from sam2.build_sam import build_sam2 + from sam2.sam2_image_predictor import SAM2ImagePredictor + + device = "cuda" if torch.cuda.is_available() else "cpu" + gdino = load_model( + model_config_path=str(gdino_config), + model_checkpoint_path=str(gdino_ckpt), + device=device, + ).to(device) + sam2_model = build_sam2(str(sam2_config), str(sam2_ckpt), device=device).to(device) + sam2_predictor = SAM2ImagePredictor(sam2_model) + + image_tensor, image_bgr, h, w = _load_image_for_sam2(image_path) + sam2_predictor.set_image(image_bgr) + + label_to_candidates: Dict[str, List[Dict[str, Any]]] = {} + for label in labels: + caption = label.lower().strip() + if not caption.endswith("."): + caption += "." + boxes, confidences, _labels = predict( + model=gdino, + image=image_tensor, + caption=caption, + box_threshold=box_threshold, + text_threshold=text_threshold, + device=device, + ) + candidates: List[Dict[str, Any]] = [] + if boxes is not None and len(boxes) > 0: + order = torch.argsort(confidences, descending=True).tolist() + for idx in order: + box = boxes[idx].to(device) + box = box * torch.tensor([w, h, w, h], device=box.device) + box_xyxy = box_convert( + boxes=box.unsqueeze(0), + in_fmt="cxcywh", + out_fmt="xyxy", + ).cpu().numpy() + masks, _scores, _ = sam2_predictor.predict( + point_coords=None, + point_labels=None, + box=box_xyxy, + multimask_output=False, + ) + if masks is None or len(masks) == 0: + continue + mask = masks[0].astype(bool) + if not mask.any(): + continue + candidates.append( + { + "mask": mask, + "score": float(confidences[idx].detach().cpu().item()), + "proposal_index": int(idx), + } + ) + label_to_candidates[label] = candidates + return label_to_candidates, int(w), int(h) + + +def _select_instances_for_label( + candidates: Sequence[Dict[str, Any]], + min_obj_area: int, + max_instances_per_label: int, +) -> List[Dict[str, Any]]: + kept: List[Dict[str, Any]] = [] + kept_masks: List[np.ndarray] = [] + ordered = sorted(candidates, key=lambda item: float(item.get("score", 0.0)), reverse=True) + for candidate in ordered: + mask = np.asarray(candidate.get("mask")).astype(bool) + area = int(mask.sum()) + if area < int(min_obj_area): + continue + if _is_duplicate_mask(mask, kept_masks): + continue + item = dict(candidate) + item["mask"] = mask + item["area"] = area + kept.append(item) + kept_masks.append(mask) + if len(kept) >= int(max_instances_per_label): + break + return kept + + +def _write_scene_json( + scene_dir: Path, + image_path: Path, + scene_objects: List[Dict[str, Any]], +) -> Path: + scene_json_path = scene_dir / "scene.json" + payload = { + "image": image_path.name, + "objects": scene_objects, + } + scene_json_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8") + return scene_json_path + + +def _write_mask_outputs( + scene_dir: Path, + image_path: Path, + scene_name: str, + labels: List[str], + labels_per_keyframe: Dict[int, List[str]], + label_to_candidates: Dict[str, List[Dict[str, Any]]], + width: int, + height: int, + output_root: Path, + batch_config: Optional[Path], + default_category: str, + min_obj_area: int, + max_instances_per_label: int, + backend: str, + labels_json_path: Optional[Path], +) -> Tuple[Path, Path, Path]: + mask_root = scene_dir / "masks" + scene_objects: List[Dict[str, Any]] = [] + summary_objects: List[Dict[str, Any]] = [] + dropped_objects: List[Dict[str, Any]] = [] + + for label in labels: + kept_instances = _select_instances_for_label( + candidates=label_to_candidates.get(label, []), + min_obj_area=min_obj_area, + max_instances_per_label=max_instances_per_label, + ) + if not kept_instances: + dropped_objects.append({"label": label, "reason": "no_valid_mask"}) + continue + label_id = _safe_id(label) + for inst_idx, inst in enumerate(kept_instances, start=1): + obj_name = f"{label_id}_{inst_idx:02d}" + mask_rel = Path("masks") / obj_name / "frame_000000.png" + mask_path = (scene_dir / mask_rel).resolve() + area = _save_mask(np.asarray(inst["mask"]).astype(bool), mask_path) + scene_objects.append( + { + "id": obj_name, + "name": obj_name, + "label": label, + "prompt": label, + "mask": str(mask_rel.as_posix()), + "is_occluded": False, + "category": default_category, + } + ) + summary_objects.append( + { + "name": obj_name, + "label": label, + "frames_with_mask": 1, + "max_area": int(area), + "median_area": float(area), + "valid_frames": 1, + "occluded_frames": 0, + "median_iou": 1.0, + "median_motion_px": 0.0, + "is_static": default_category == "static", + "category": default_category, + "category_source": "single_image_default", + "backend": backend, + "score": float(inst.get("score", 0.0)), + "proposal_index": int(inst.get("proposal_index", -1)), + "masks_dir": str(mask_path.parent.resolve()), + "mask": str(mask_rel.as_posix()), + } + ) + + if not summary_objects: + raise RuntimeError("Mask generation produced 0 valid objects") + + scene_json_path = _write_scene_json(scene_dir=scene_dir, image_path=image_path, scene_objects=scene_objects) + + meta_dir = output_root / "metadata" + meta_dir.mkdir(parents=True, exist_ok=True) + summary_path = _summary_json_path(output_root, scene_name) + summary = { + "scene_dir": str(scene_dir), + "scene_name": scene_name, + "video": str(image_path), + "video_name": scene_name, + "image": str(image_path), + "image_name": image_path.name, + "num_frames": 1, + "fps": 1.0, + "width": int(width), + "height": int(height), + "keyframes": [0], + "labels": list(labels), + "labels_per_keyframe": {str(k): v for k, v in labels_per_keyframe.items()}, + "objects": summary_objects, + "dropped_objects": dropped_objects, + "mask_root": str(mask_root.resolve()), + "labels_json": str(labels_json_path.resolve()) if labels_json_path is not None else None, + "backend": backend, + } + summary_path.write_text(json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8") + + cfg_path = _pipeline_config_path(output_root, scene_name) + if batch_config is not None: + cfg_path.parent.mkdir(parents=True, exist_ok=True) + pipeline_cfg = { + "batch_config": str(batch_config.resolve()), + "scene_dir": str(scene_dir), + "scene_name": scene_name, + "image_path": str(image_path), + "output_root": str(output_root.resolve()), + "mask_glob": "frame_*.png", + "tracker_mask_mode": "static", + "objects": [ + { + "name": obj["name"], + "masks_dir": obj["masks_dir"], + "category": obj["category"], + "is_occluded": False, + } + for obj in summary_objects + ], + } + cfg_path.write_text(json.dumps(pipeline_cfg, indent=2, ensure_ascii=False), encoding="utf-8") + return scene_json_path, summary_path, cfg_path + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Single-image Qwen labels + SAM masks pipeline") + parser.add_argument("--scene-dir", type=Path, required=True, help="Scene directory with a single input image") + parser.add_argument( + "--mode", + type=str, + default="all", + choices=("all", "labels", "masks"), + help="Run labels only, masks only, or both", + ) + parser.add_argument("--scene-name", type=str, default="", help="Optional scene name override") + parser.add_argument("--output-root", type=Path, default=Path("outputs"), help="Output root") + parser.add_argument("--labels-json", type=Path, default=None, help="Existing labels json for masks mode") + parser.add_argument("--labels", type=str, default="", help="Comma-separated labels to bypass Qwen") + + parser.add_argument( + "--qwen-backend", + type=str, + default="api", + choices=("api", "local"), + help="Qwen label backend", + ) + parser.add_argument( + "--qwen-model", + type=str, + default="Qwen/Qwen3-VL-8B-Instruct", + help="Local Qwen model path or HF id", + ) + parser.add_argument( + "--qwen-api-model", + type=str, + default=DEFAULT_QWEN_API_MODEL, + help="Qwen API model name", + ) + parser.add_argument( + "--qwen-api-model-list", + type=str, + default=DEFAULT_QWEN_API_MODEL_LIST, + help="Comma/space-separated fallback Qwen API models used when the primary model is unavailable or out of quota", + ) + parser.add_argument( + "--qwen-api-base-url", + type=str, + default="https://dashscope.aliyuncs.com/compatible-mode/v1", + help="DashScope OpenAI-compatible base URL", + ) + parser.add_argument( + "--qwen-api-key-env", + type=str, + default="DASHSCOPE_API_KEY", + help="Environment variable name for API key", + ) + parser.add_argument("--max-objects", type=int, default=15, help="Max labels") + parser.add_argument("--max-new-tokens", type=int, default=2048, help="Qwen max new tokens") + parser.add_argument( + "--aggregate-threshold", + type=int, + default=10, + help="Aggregate threshold for label counts", + ) + parser.add_argument("--keep-labels", type=str, default="", help="Comma-separated keep list") + parser.add_argument("--drop-labels", type=str, default="", help="Comma-separated drop list") + + parser.add_argument( + "--backend", + choices=("sam3",), + default="sam3", + help="Mask backend (single-image path supports sam3 only)", + ) + parser.add_argument( + "--default-category", + type=str, + choices=("static", "rigid"), + default="static", + help="Category assigned to all single-image instances", + ) + parser.add_argument("--min-obj-area", type=int, default=200, help="Minimum accepted mask area") + parser.add_argument( + "--max-instances-per-label", + type=int, + default=20, + help="Maximum kept instances per label", + ) + parser.add_argument( + "--batch-config", + type=Path, + default=None, + help="Batch config path for pipeline_config.json", + ) + parser.add_argument( + "--sam3-ckpt", + type=Path, + default=_REPO_ROOT / "sam3" / "checkpoints" / "sam3" / "sam3.pt", + ) + parser.add_argument("--sam3-confidence-threshold", type=float, default=0.35) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + scene_dir = args.scene_dir.expanduser().resolve() + if not scene_dir.is_dir(): + raise FileNotFoundError(scene_dir) + + scene_name = str(args.scene_name or scene_dir.name).strip() or scene_dir.name + output_root = args.output_root.expanduser().resolve() + image_path = _find_single_image(scene_dir) + width, height = _image_info(image_path) + keep_set = _parse_csv_set(args.keep_labels) + drop_set = _parse_csv_set(args.drop_labels) + labels_json_path = _labels_json_path(output_root, scene_name, args.labels_json) + + labels: List[str] = [] + labels_per_keyframe: Dict[int, List[str]] = {0: []} + + if args.qwen_backend == "api": + print(f"[INFO] Qwen API model: {args.qwen_api_model}") + print( + "[INFO] Qwen API model candidates: " + f"{_build_qwen_api_model_candidates(args.qwen_api_model, args.qwen_api_model_list)}" + ) + + if args.mode in ("labels", "all"): + if args.labels: + raw_labels = [_simple_normalize(x) for x in args.labels.split(",")] + labels = _merge_labels([[x for x in raw_labels if x]], keep_set or None, drop_set or None) + else: + labels, _raw, _payload = _run_qwen_labels( + image_path=image_path, + qwen_backend=args.qwen_backend, + qwen_model=args.qwen_model, + qwen_api_model=args.qwen_api_model, + qwen_api_model_list=args.qwen_api_model_list, + qwen_api_base_url=args.qwen_api_base_url, + qwen_api_key_env=args.qwen_api_key_env, + max_new_tokens=int(args.max_new_tokens), + max_objects=int(args.max_objects), + aggregate_threshold=int(args.aggregate_threshold), + keep_set=keep_set or None, + drop_set=drop_set or None, + ) + if not labels: + raise RuntimeError("Qwen returned 0 labels for the single image.") + labels_per_keyframe = {0: list(labels)} + _write_labels_json( + path=labels_json_path, + image_path=image_path, + scene_name=scene_name, + width=width, + height=height, + labels=labels, + ) + print(f"[OK] Labels: {labels_json_path}") + if args.mode == "labels": + return + + if args.mode == "masks": + if args.labels: + raw_labels = [_simple_normalize(x) for x in args.labels.split(",")] + labels = _merge_labels([[x for x in raw_labels if x]], keep_set or None, drop_set or None) + labels_per_keyframe = {0: list(labels)} + else: + if not labels_json_path.is_file(): + raise FileNotFoundError( + f"Labels not found. Run mode=labels first or pass --labels-json: {labels_json_path}" + ) + labels, labels_per_keyframe = _extract_labels_from_json(labels_json_path) + if not labels: + raise RuntimeError("No labels available for mask generation.") + + batch_config = args.batch_config.expanduser().resolve() if args.batch_config is not None else None + ckpt = _resolve_path_arg(args.sam3_ckpt, _REPO_ROOT) + if not ckpt.exists(): + raise FileNotFoundError(f"SAM3 checkpoint not found: {ckpt}") + label_to_candidates, mask_width, mask_height = _collect_sam3_candidates( + image_path=image_path, + labels=labels, + ckpt_path=str(ckpt), + confidence_threshold=float(args.sam3_confidence_threshold), + ) + + scene_json_path, summary_path, cfg_path = _write_mask_outputs( + scene_dir=scene_dir, + image_path=image_path, + scene_name=scene_name, + labels=labels, + labels_per_keyframe=labels_per_keyframe, + label_to_candidates=label_to_candidates, + width=mask_width, + height=mask_height, + output_root=output_root, + batch_config=batch_config, + default_category=args.default_category, + min_obj_area=int(args.min_obj_area), + max_instances_per_label=int(args.max_instances_per_label), + backend=args.backend, + labels_json_path=labels_json_path if labels_json_path.exists() else None, + ) + print(f"[OK] scene.json: {scene_json_path}") + print(f"[OK] Summary: {summary_path}") + if batch_config is not None: + print(f"[OK] Recon config: {cfg_path}") + + +if __name__ == "__main__": + main() diff --git a/OVOW/masking/qwen_sam3_video_masks.py b/OVOW/masking/qwen_sam3_video_masks.py new file mode 100644 index 0000000000000000000000000000000000000000..eb6f631037f0557b971f354f126720fc802c95d7 --- /dev/null +++ b/OVOW/masking/qwen_sam3_video_masks.py @@ -0,0 +1,2415 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import ast +import base64 +import json +import math +import os +import re +import subprocess +import sys +from datetime import datetime, timezone +from fractions import Fraction +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +import numpy as np +import torch + +_THIS_DIR = Path(__file__).resolve().parent +_FOURD_RECON_ROOT = _THIS_DIR.parents[1] +_SAM3_ROOT = _FOURD_RECON_ROOT / "sam3" +sys.path.insert(0, str(_THIS_DIR)) +sys.path.insert(0, str(_SAM3_ROOT)) + +DEFAULT_QWEN_API_MODEL = "qwen3.5-plus-2026-02-15" +DEFAULT_QWEN_API_MODEL_LIST = ",".join( + [ + "qwen3.5-flash-2026-02-23", + "qwen3.5-plus-2026-02-15", + "qwen3.5-flash", + "qwen3.5-122b-a10b", + "qwen3.5-35b-a3b", + ] +) +_QWEN_API_FALLBACK_STATUS_CODES = {402, 403, 429} +_QWEN_API_FALLBACK_ERROR_TOKENS = ( + "insufficient_quota", + "insufficient quota", + "quota exceeded", + "no available quota", + "out of quota", + "billing", + "balance", + "payment required", + "arrears", + "欠费", + "余额", + "not enabled", + "access denied", + "model is not available", + "model_not_found", +) + + +def _arg_present(flag: str) -> bool: + return any(arg == flag or arg.startswith(flag + "=") for arg in sys.argv[1:]) + + +def _safe_id(name: str) -> str: + out = [] + for c in name.lower(): + if c.isalnum(): + out.append(c) + elif c in (" ", "-", "_"): + out.append("_") + cleaned = "".join(out).strip("_") + while "__" in cleaned: + cleaned = cleaned.replace("__", "_") + return cleaned or "obj" + + +def _video_info(video_path: Path) -> Tuple[int, float, int, int]: + try: + import cv2 # type: ignore + + cap = cv2.VideoCapture(str(video_path)) + if not cap.isOpened(): + raise FileNotFoundError(f"Cannot open video: {video_path}") + try: + num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + fps = float(cap.get(cv2.CAP_PROP_FPS)) + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + finally: + cap.release() + if num_frames <= 0: + num_frames = 0 + cap = cv2.VideoCapture(str(video_path)) + while True: + ok, _ = cap.read() + if not ok: + break + num_frames += 1 + cap.release() + return num_frames, fps, width, height + except Exception: + pass + + try: + import av # type: ignore + + container = av.open(str(video_path)) + stream = container.streams.video[0] + width = int(stream.width or 0) + height = int(stream.height or 0) + fps = 0.0 + if stream.average_rate is not None: + fps = float(stream.average_rate) + elif stream.base_rate is not None: + fps = float(stream.base_rate) + num_frames = int(stream.frames or 0) + if num_frames <= 0: + count = 0 + for _ in container.decode(video=0): + count += 1 + num_frames = count + container.close() + return num_frames, fps, width, height + except Exception: + pass + + cmd = [ + "ffprobe", + "-v", + "error", + "-select_streams", + "v:0", + "-count_frames", + "-show_entries", + "stream=nb_read_frames,r_frame_rate,avg_frame_rate,width,height,duration", + "-of", + "json", + str(video_path), + ] + proc = subprocess.run(cmd, check=True, stdout=subprocess.PIPE, text=True) + data = json.loads(proc.stdout) + stream = (data.get("streams") or [{}])[0] + width = int(stream.get("width") or 0) + height = int(stream.get("height") or 0) + fps_raw = stream.get("avg_frame_rate") or stream.get("r_frame_rate") or "0/1" + try: + fps = float(Fraction(fps_raw)) + except Exception: + fps = 0.0 + nb_frames = stream.get("nb_read_frames") + if nb_frames is not None: + num_frames = int(nb_frames) + else: + duration = float(stream.get("duration") or 0.0) + num_frames = int(round(duration * fps)) if fps > 0 else 0 + return num_frames, fps, width, height + + +def _sample_keyframes(num_frames: int, count: int) -> List[int]: + if num_frames <= 0: + return [0] + if count <= 1: + return [0] + idxs = np.linspace(0, max(0, num_frames - 1), count) + idxs = [int(round(x)) for x in idxs] + return sorted(set(max(0, min(num_frames - 1, x)) for x in idxs)) + + +def _resize_frame(frame: "np.ndarray", max_side: int) -> "np.ndarray": + if max_side <= 0: + return frame + h, w = frame.shape[:2] + m = max(h, w) + if m <= max_side: + return frame + scale = max_side / float(m) + new_w = max(1, int(round(w * scale))) + new_h = max(1, int(round(h * scale))) + return cv2.resize(frame, (new_w, new_h), interpolation=cv2.INTER_AREA) + + +def _extract_keyframes(video_path: Path, frame_indices: List[int], out_dir: Path, max_side: int) -> List[Path]: + out_dir.mkdir(parents=True, exist_ok=True) + out_paths: List[Path] = [] + try: + import cv2 # type: ignore + + cap = cv2.VideoCapture(str(video_path)) + if not cap.isOpened(): + raise FileNotFoundError(f"Cannot open video: {video_path}") + try: + for idx in frame_indices: + cap.set(cv2.CAP_PROP_POS_FRAMES, idx) + ok, frame = cap.read() + if not ok or frame is None: + continue + frame = _resize_frame(frame, max_side) + out_path = out_dir / f"keyframe_{idx:06d}.jpg" + cv2.imwrite(str(out_path), frame) + out_paths.append(out_path) + finally: + cap.release() + return out_paths + except Exception: + pass + + try: + import av # type: ignore + from PIL import Image # type: ignore + + container = av.open(str(video_path)) + frame_set = set(frame_indices) + for idx, frame in enumerate(container.decode(video=0)): + if idx in frame_set: + out_path = out_dir / f"keyframe_{idx:06d}.jpg" + img = frame.to_image() + if max_side > 0: + img.thumbnail((max_side, max_side), Image.BICUBIC) + img.save(out_path) + out_paths.append(out_path) + if len(out_paths) == len(frame_set): + break + container.close() + return out_paths + except Exception: + pass + + scale_filter = "" + if max_side > 0: + scale_filter = ( + f",scale='if(gt(iw,ih),{max_side},-1)':'if(gt(iw,ih),-1,{max_side})'" + ) + for idx in frame_indices: + out_path = out_dir / f"keyframe_{idx:06d}.jpg" + cmd = [ + "ffmpeg", + "-y", + "-hide_banner", + "-loglevel", + "error", + "-i", + str(video_path), + "-vf", + f"select=eq(n\\,{idx}){scale_filter}", + "-vframes", + "1", + str(out_path), + ] + subprocess.run(cmd, check=True) + if out_path.exists(): + out_paths.append(out_path) + return out_paths + + +def _simple_normalize(text: str) -> str: + t = text.strip().lower() + t = t.replace("-", " ").replace("_", " ") + t = "".join(c if (c.isalnum() or c.isspace()) else " " for c in t) + return " ".join(t.split()).strip() + + +def _merge_labels( + label_sets: List[List[str]], + keep_set: Optional[set], + drop_set: Optional[set], +) -> List[str]: + seen = set() + merged: List[str] = [] + for labels in label_sets: + for raw in labels: + name = _simple_normalize(raw) + if not name: + continue + if keep_set and name not in keep_set: + continue + if drop_set and name in drop_set: + continue + if name not in seen: + seen.add(name) + merged.append(name) + return merged + + +def _mask_iou(a: np.ndarray, b: np.ndarray) -> float: + inter = np.logical_and(a, b).sum() + union = np.logical_or(a, b).sum() + return float(inter) / float(union) if union else 0.0 + + +def _mask_centroid(mask: np.ndarray) -> Optional[Tuple[float, float]]: + ys, xs = np.where(mask) + if len(xs) == 0: + return None + return float(xs.mean()), float(ys.mean()) + + +def _classify_static( + masks_by_frame: Dict[int, np.ndarray], + static_iou_thresh: float, + static_motion_px: float, + occlusion_area_ratio: float, + min_valid_frames: int, + high_iou_thresh: float, + high_iou_motion_mult: float, +) -> Tuple[bool, float, float, int, int, float]: + if not masks_by_frame: + return False, 0.0, 0.0, 0, 0, 0.0 + frame_ids = sorted(masks_by_frame.keys()) + areas = np.array([int(masks_by_frame[f].sum()) for f in frame_ids], dtype=np.float32) + if len(areas) == 0: + return False, 0.0, 0.0, 0, 0, 0.0 + area_med = float(np.median(areas)) + if area_med <= 0: + return False, 0.0, 0.0, 0, 0, area_med + + valid_ids = [ + fid for fid, area in zip(frame_ids, areas) + if area >= area_med * occlusion_area_ratio + ] + occluded_frames = len(frame_ids) - len(valid_ids) + if len(valid_ids) < max(1, min_valid_frames): + return False, 0.0, 0.0, len(valid_ids), occluded_frames, area_med + + ref_mask = masks_by_frame[valid_ids[0]] + ref_centroid = _mask_centroid(ref_mask) + if ref_centroid is None: + return False, 0.0, 0.0, len(valid_ids), occluded_frames, area_med + + ious: List[float] = [] + motions: List[float] = [] + for fid in valid_ids: + mask = masks_by_frame[fid] + ious.append(_mask_iou(ref_mask, mask)) + cent = _mask_centroid(mask) + if cent is None: + continue + dx = cent[0] - ref_centroid[0] + dy = cent[1] - ref_centroid[1] + motions.append(math.hypot(dx, dy)) + + med_iou = float(np.median(ious)) if ious else 0.0 + med_motion = float(np.median(motions)) if motions else 0.0 + is_static = ( + (med_iou >= static_iou_thresh and med_motion <= static_motion_px) + or (med_iou >= high_iou_thresh and med_motion <= static_motion_px * high_iou_motion_mult) + ) + return is_static, med_iou, med_motion, len(valid_ids), occluded_frames, area_med + + +def _save_masks( + obj_dir: Path, + num_frames: int, + masks_by_frame: Dict[int, np.ndarray], +) -> None: + obj_dir.mkdir(parents=True, exist_ok=True) + if masks_by_frame: + sample_mask = next(iter(masks_by_frame.values())) + h, w = sample_mask.shape[:2] + else: + h = w = 0 + blank = np.zeros((h, w), dtype=np.uint8) if h and w else None + for fid in range(num_frames): + mask = masks_by_frame.get(fid) + if mask is None: + if blank is None: + continue + out = blank + else: + out = (mask.astype(np.uint8) * 255) + out_path = obj_dir / f"frame_{fid:06d}.png" + from PIL import Image # type: ignore + + Image.fromarray(out).save(out_path) + + +def _load_mask(mask_path: Path) -> Optional[np.ndarray]: + if not mask_path.exists(): + return None + from PIL import Image # type: ignore + + img = Image.open(mask_path).convert("L") + arr = np.array(img, dtype=np.uint8) + return arr > 0 + + +def _list_object_dirs(mask_root: Path) -> List[Path]: + if not mask_root.exists(): + return [] + return sorted([p for p in mask_root.iterdir() if p.is_dir()]) + + +def _parse_label_from_dir(name: str) -> str: + parts = name.split("_") + if len(parts) <= 1: + return name + return "_".join(parts[:-1]) + + +def _refine_with_occlusion( + objects_summary: List[Dict[str, object]], + mask_root: Path, + num_frames: int, + static_iou_thresh: float, + static_motion_px: float, + occlusion_area_ratio: float, + occlusion_overlap_ratio: float, + min_valid_frames: int, + dynamic_seed_motion_mult: float, + dynamic_seed_iou_ratio: float, + high_iou_thresh: float, + high_iou_motion_mult: float, +) -> None: + seed_dynamic = [] + for obj in objects_summary: + if obj.get("force_static"): + continue + mot = float(obj.get("median_motion_px", 0.0) or 0.0) + iou = float(obj.get("median_iou", 0.0) or 0.0) + if obj.get("force_dynamic"): + seed_dynamic.append(obj["name"]) + elif mot >= static_motion_px * dynamic_seed_motion_mult or iou <= static_iou_thresh * dynamic_seed_iou_ratio: + seed_dynamic.append(obj["name"]) + + if not seed_dynamic: + return + + union_masks: List[Optional[np.ndarray]] = [None] * num_frames + for name in seed_dynamic: + obj_dir = mask_root / str(name) + for fid in range(num_frames): + mask = _load_mask(obj_dir / f"frame_{fid:06d}.png") + if mask is None: + continue + if union_masks[fid] is None: + union_masks[fid] = mask.copy() + else: + union_masks[fid] = np.logical_or(union_masks[fid], mask) + + for obj in objects_summary: + name = str(obj["name"]) + if name in seed_dynamic: + obj["seed_dynamic"] = True + continue + if obj.get("force_dynamic"): + obj["seed_dynamic"] = True + continue + if obj.get("force_static"): + obj["seed_dynamic"] = False + continue + obj_dir = mask_root / name + areas = [] + masks_by_frame: Dict[int, np.ndarray] = {} + for fid in range(num_frames): + mask = _load_mask(obj_dir / f"frame_{fid:06d}.png") + if mask is None: + continue + masks_by_frame[fid] = mask + areas.append(int(mask.sum())) + if not areas: + continue + area_med = float(np.median(areas)) + valid_ids = [] + occluded_frames = 0 + for fid, mask in masks_by_frame.items(): + area = float(mask.sum()) + occluded = area < area_med * occlusion_area_ratio + if not occluded and union_masks[fid] is not None: + overlap = float(np.logical_and(mask, union_masks[fid]).sum()) + if area > 0 and overlap / area > occlusion_overlap_ratio: + occluded = True + if occluded: + occluded_frames += 1 + continue + valid_ids.append(fid) + + if len(valid_ids) < max(1, min_valid_frames): + continue + + ref_mask = masks_by_frame[valid_ids[0]] + ref_centroid = _mask_centroid(ref_mask) + if ref_centroid is None: + continue + + ious = [] + motions = [] + for fid in valid_ids: + mask = masks_by_frame[fid] + ious.append(_mask_iou(ref_mask, mask)) + cent = _mask_centroid(mask) + if cent is None: + continue + motions.append(math.hypot(cent[0] - ref_centroid[0], cent[1] - ref_centroid[1])) + + med_iou = float(np.median(ious)) if ious else 0.0 + med_motion = float(np.median(motions)) if motions else 0.0 + is_static = ( + (med_iou >= static_iou_thresh and med_motion <= static_motion_px) + or (med_iou >= high_iou_thresh and med_motion <= static_motion_px * high_iou_motion_mult) + ) + + obj["refined_median_iou"] = med_iou + obj["refined_median_motion_px"] = med_motion + obj["refined_valid_frames"] = len(valid_ids) + obj["refined_occluded_frames"] = occluded_frames + obj["seed_dynamic"] = False + if is_static: + obj["is_static"] = True + obj["category"] = "static" + +def _parse_json_list(raw: str, key: str) -> List[str]: + try: + data = json.loads(raw) + if isinstance(data, dict): + items = data.get(key, []) + else: + items = data + except Exception: + items = [] + if key in raw: + start = raw.find("[") + end = raw.find("]", start + 1) + if start >= 0 and end > start: + segment = raw[start + 1:end] + items = [x.strip().strip('"') for x in segment.split(",") if x.strip()] + if not isinstance(items, list): + return [] + return [_simple_normalize(str(x)) for x in items if _simple_normalize(str(x))] + + +def _load_labels_json(path: Path) -> Dict[str, object]: + with path.open("r", encoding="utf-8") as f: + return json.load(f) + + +def _write_labels_json( + path: Path, + video_path: Path, + num_frames: int, + fps: float, + width: int, + height: int, + keyframes: List[int], + labels: List[str], + labels_per_keyframe: Dict[int, List[str]], +) -> None: + payload = { + "video": str(video_path), + "video_name": video_path.stem, + "num_frames": int(num_frames), + "fps": float(fps), + "width": int(width), + "height": int(height), + "keyframes": keyframes, + "labels": labels, + "labels_per_keyframe": {str(k): v for k, v in labels_per_keyframe.items()}, + } + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="utf-8") as f: + json.dump(payload, f, indent=2) + + +def _build_qwen_api_label_prompt(max_objects: int, aggregate_threshold: int, include_category: bool = False) -> str: + if include_category: + return ( + "请联合分析给定关键帧(同一视频的不同时刻),基于时间变化判断类别。" + "识别可见物体类别,并为每个类别判断 static/rigid/deform。" + "输出 JSON,且只输出 JSON。" + "三类定义(必须严格遵守):" + "1) static:视频时间范围内近似静止(世界位姿几乎不变)。" + "2) rigid:仅刚体运动(平移/旋转),形状保持不变;例如移动的飞船、行驶中的汽车。" + "3) deform:存在非刚体形变(局部/整体形状随时间变化);例如走路/跳舞的人、走路的犀牛。" + "规则:" + "1) 特异性优先:使用最具体的功能性名称(如 computer/car),禁止通用词。" + "2) 互斥性:不要输出包含关系或部件词(如 person 与 clothes/hand)。" + "3) name 必须是英文、小写、单数名词;形容词仅放在 visual_description。" + "4) 每个类别只输出一次,并给出简短 reason。" + f"5) 如果某类别数量 > {aggregate_threshold},请用整体类别名替代并将 num=1(如 tree→forest,person→crowd,building→building_complex)。" + "6) 遮挡检测:若被其他物体遮挡面积明显(>10%),is_occluded=true;否则 false。" + "7) occluded_by 只能填列表中已有的 name;否则留空数组。" + "8) 严禁部件级标签:不要输出 hair/head/face/hand/arm/leg 等人体部件;" + "若角色持有装备,仅保留主体类别(如 elf),不要单独输出 armor/sword。" + "9) 忽略背景与装饰:不要输出 sky/path/ground/wall/light/shadow/text/rune inscription 等环境或纹理标签。" + f"最多输出 {max_objects} 个类别。" + "禁止词汇:box, object, thing, item, container, shape。" + "输出格式:" + "{\"objects\": [{\"name\": \"computer\", \"num\": 1, " + "\"visual_description\": \"...\", \"category\": \"static|rigid|deform\", " + "\"reason\": \"...\", \"is_occluded\": false, \"occluded_by\": []}]}" + ) + return ( + "请分析图片用于语义分割任务。识别图中所有可见物体类别,并估计每个类别的实例数量。" + "输出 JSON,且只输出 JSON。" + "规则:" + "1) 特异性优先:使用最具体的功能性名称(如 computer/car),禁止通用词。" + "2) 互斥性:不要输出包含关系或部件词(如 person 与 clothes/hand)。" + "3) name 必须是英文、小写、单数名词;形容词仅放在 visual_description。" + "4) 每个类别只输出一次,附带你检测到的该类别实例数量 num(整数>=1)。" + f"5) 如果某类别数量 > {aggregate_threshold},请用整体类别名替代并将 num=1(如 tree→forest,person→crowd,building→building_complex)。" + "6) 遮挡检测:若被其他物体遮挡面积明显(>10%),is_occluded=true;否则 false。" + "7) occluded_by 只能填列表中已有的 name;否则留空数组。" + "8) 严禁部件级标签:不要输出 hair/head/face/hand/arm/leg 等人体部件;" + "若角色持有装备,仅保留主体类别(如 elf),不要单独输出 armor/sword。" + "9) 忽略背景与装饰:不要输出 sky/path/ground/wall/light/shadow/text/rune inscription 等环境或纹理标签。" + f"最多输出 {max_objects} 个类别。" + "禁止词汇:box, object, thing, item, container, shape。" + "输出格式:" + "{\"objects\": [{\"name\": \"computer\", \"num\": , " + "\"visual_description\": \"...\", \"is_occluded\": false, \"occluded_by\": []}]}" + ) + + +_ALLOWED_LABEL_CATEGORIES = {"static", "rigid", "deform"} + + +def _normalize_label_category_name(raw: Any) -> str: + text = str(raw or "").strip().lower() + flat = text.replace("-", "_").replace(" ", "_") + alias = { + "static": "static", + "still": "static", + "stationary": "static", + "静态": "static", + "rigid": "rigid", + "rigid_dynamic": "rigid", + "dynamic_rigid": "rigid", + "刚体": "rigid", + "deform": "deform", + "deformable": "deform", + "nonrigid": "deform", + "non_rigid": "deform", + "non-rigid": "deform", + "deform_dynamic": "deform", + "动态形变": "deform", + "形变": "deform", + "可形变": "deform", + } + return alias.get(flat, "") + + +def _build_qwen_api_category_prompt(labels: List[str]) -> str: + labels_text = json.dumps(labels, ensure_ascii=False) + return ( + "You are assisting a 4D reconstruction pipeline.\n" + "Classify each input label into exactly one category: static, rigid, deform.\n" + "Definitions (must follow):\n" + "1) static: world-space pose is approximately unchanged across time.\n" + "2) rigid: rigid-body motion only (translation/rotation), shape remains unchanged " + "(e.g., moving car, flying spaceship).\n" + "3) deform: non-rigid shape deformation over time " + "(e.g., walking/dancing person, walking rhino).\n" + "Input labels:\n" + f"{labels_text}\n" + "Output MUST be JSON only, no extra text. Use this schema:\n" + "{\"categories\":[{\"label\":\"\",\"category\":\"static|rigid|deform\",\"reason\":\"short\"}]}\n" + "Rules:\n" + "- Return every input label exactly once.\n" + "- Do not return labels not present in input.\n" + "- category must be one of static, rigid, deform.\n" + "- Keep label text unchanged from input." + ) + + +def _extract_label_category_mapping( + payload: Any, + labels: List[str], + strict: bool = True, +) -> Dict[str, str]: + label_norm_map = {_simple_normalize(x): x for x in labels} + expected = set(label_norm_map.keys()) + mapping: Dict[str, str] = {} + errors: List[str] = [] + + def _add_pair(raw_label: Any, raw_category: Any) -> None: + label_norm = _simple_normalize(str(raw_label or "")) + if not label_norm: + errors.append("empty label in category payload") + return + cat = _normalize_label_category_name(raw_category) + if not cat: + errors.append(f"unsupported category for '{raw_label}': {raw_category}") + return + if cat not in _ALLOWED_LABEL_CATEGORIES: + errors.append(f"category out of scope for '{raw_label}': {raw_category}") + return + if label_norm not in expected: + errors.append(f"unexpected label in category payload: {raw_label}") + return + prev = mapping.get(label_norm) + if prev is not None and prev != cat: + errors.append(f"conflicting category for label '{raw_label}': {prev} vs {cat}") + return + mapping[label_norm] = cat + + if isinstance(payload, dict): + categories = payload.get("categories") + if isinstance(categories, list): + for item in categories: + if isinstance(item, dict): + _add_pair(item.get("label") or item.get("name"), item.get("category")) + + label_categories = payload.get("label_categories") + if isinstance(label_categories, dict): + for raw_label, raw_cat in label_categories.items(): + _add_pair(raw_label, raw_cat) + + mapping_dict = payload.get("mapping") + if isinstance(mapping_dict, dict): + for raw_label, raw_cat in mapping_dict.items(): + _add_pair(raw_label, raw_cat) + + if not mapping: + scalar_items = { + k: v + for k, v in payload.items() + if isinstance(v, (str, int, float)) + } + if scalar_items: + for raw_label, raw_cat in scalar_items.items(): + _add_pair(raw_label, raw_cat) + elif isinstance(payload, list): + for item in payload: + if isinstance(item, dict): + _add_pair(item.get("label") or item.get("name"), item.get("category")) + + missing = sorted(expected - set(mapping.keys())) + if strict: + if errors: + raise RuntimeError(f"Invalid Qwen category payload: {errors[0]}") + if missing: + missing_raw = [label_norm_map[x] for x in missing[:5]] + raise RuntimeError( + "Qwen category payload missing labels: " + + ", ".join(missing_raw) + ) + if len(mapping) != len(expected): + raise RuntimeError("Qwen category payload size mismatch.") + return mapping + + +def _write_qwen_category_meta(path: Path, payload: Dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="utf-8") as f: + json.dump(payload, f, indent=2, ensure_ascii=False) + + +def _extract_json_payload(raw: str) -> Optional[Any]: + def _try_parse(candidate: str) -> Optional[Any]: + candidate = candidate.strip() + if not candidate: + return None + variants = [candidate, re.sub(r",\s*([}\]])", r"\1", candidate)] + for text_variant in variants: + try: + return json.loads(text_variant) + except Exception: + continue + try: + py_obj = ast.literal_eval(candidate) + if isinstance(py_obj, (dict, list)): + return py_obj + except Exception: + pass + return None + + text = raw.strip() + if not text: + return None + parsed = _try_parse(text) + if parsed is not None: + return parsed + + for fence in re.finditer(r"```(?:json)?\s*([\s\S]*?)\s*```", text, flags=re.IGNORECASE): + parsed = _try_parse(fence.group(1)) + if parsed is not None: + return parsed + + decoder = json.JSONDecoder() + for text_variant in (text, re.sub(r",\s*([}\]])", r"\1", text)): + for match in re.finditer(r"[\{\[]", text_variant): + start = match.start() + try: + obj, _ = decoder.raw_decode(text_variant[start:]) + except Exception: + continue + if isinstance(obj, (dict, list)): + return obj + return None + + +def _print_qwen_raw_debug(stage: str, raw: str, payload: Optional[Any] = None) -> None: + print(f"[ERROR] {stage}", file=sys.stderr) + if raw.strip(): + print("[ERROR] --- Qwen raw answer begin ---", file=sys.stderr) + print(raw, file=sys.stderr) + print("[ERROR] --- Qwen raw answer end ---", file=sys.stderr) + else: + print("[ERROR] Qwen raw answer is empty.", file=sys.stderr) + + if payload is not None: + try: + payload_text = json.dumps(payload, ensure_ascii=False, indent=2) + except Exception: + payload_text = repr(payload) + print("[ERROR] --- Parsed payload begin ---", file=sys.stderr) + print(payload_text, file=sys.stderr) + print("[ERROR] --- Parsed payload end ---", file=sys.stderr) + + +def _extract_labels_from_payload(payload: Any, max_objects: int) -> List[str]: + items: List[Any] = [] + if isinstance(payload, dict): + if isinstance(payload.get("objects"), list): + items = payload.get("objects", []) + elif isinstance(payload.get("labels"), list): + items = payload.get("labels", []) + elif isinstance(payload.get("moving"), list): + items = payload.get("moving", []) + elif isinstance(payload, list): + items = payload + + labels: List[str] = [] + seen = set() + for item in items: + if isinstance(item, dict): + raw = item.get("name") or item.get("label") or item.get("category") or item.get("prompt") + else: + raw = item + name = _simple_normalize(str(raw or "")) + if not name or name in seen: + continue + seen.add(name) + labels.append(name) + if len(labels) >= max_objects: + break + return labels + + +def _extract_label_objects_from_payload( + payload: Any, + max_objects: int, + keep_set: Optional[set] = None, + drop_set: Optional[set] = None, +) -> List[Dict[str, str]]: + items: List[Any] = [] + if isinstance(payload, dict) and isinstance(payload.get("objects"), list): + items = payload.get("objects", []) + elif isinstance(payload, list): + items = payload + + out: List[Dict[str, str]] = [] + seen = set() + for item in items: + if not isinstance(item, dict): + continue + raw_name = item.get("name") or item.get("label") + name = _simple_normalize(str(raw_name or "")) + if not name or name in seen: + continue + if keep_set and name not in keep_set: + continue + if drop_set and name in drop_set: + continue + seen.add(name) + out.append( + { + "name": name, + "category": _normalize_label_category_name(item.get("category")), + "reason": str(item.get("reason") or "").strip(), + "visual_description": str(item.get("visual_description") or "").strip(), + } + ) + if len(out) >= max_objects: + break + return out + + +def _extract_labels_from_text_fallback(raw: str, max_objects: int) -> List[str]: + labels: List[str] = [] + seen = set() + for m in re.finditer(r'"name"\s*:\s*"([^"]+)"', raw, flags=re.IGNORECASE): + name = _simple_normalize(m.group(1)) + if not name or name in seen: + continue + seen.add(name) + labels.append(name) + if len(labels) >= max_objects: + return labels + for m in re.finditer(r'"([^"]+)"', raw): + name = _simple_normalize(m.group(1)) + if not name or name in seen or name in {"objects", "labels", "moving"}: + continue + seen.add(name) + labels.append(name) + if len(labels) >= max_objects: + break + return labels + + +def _decode_chat_content(content: Any) -> str: + if isinstance(content, str): + return content.strip() + if isinstance(content, list): + chunks: List[str] = [] + for item in content: + if isinstance(item, dict): + txt = item.get("text") + else: + txt = getattr(item, "text", None) + if isinstance(txt, str) and txt.strip(): + chunks.append(txt.strip()) + return "\n".join(chunks).strip() + return str(content).strip() + + +def _extract_completion_text(resp: Any) -> str: + try: + message = resp.choices[0].message + except Exception: + return "" + content = getattr(message, "content", "") + return _decode_chat_content(content) + + +def _encode_image_data_url(image_path: Path) -> str: + suffix = image_path.suffix.lower() + mime_map = { + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".png": "image/png", + ".webp": "image/webp", + } + mime = mime_map.get(suffix, "image/jpeg") + b64 = base64.b64encode(image_path.read_bytes()).decode("ascii") + return f"data:{mime};base64,{b64}" + + +def _run_qwen_api_chat( + client: Any, + model: str, + image_paths: List[Path], + prompt: str, + max_new_tokens: int, +) -> str: + content: List[Dict[str, Any]] = [] + for image_path in image_paths: + image_url = _encode_image_data_url(image_path) + content.append({"type": "image_url", "image_url": {"url": image_url}}) + content.append({"type": "text", "text": prompt}) + resp = client.chat.completions.create( + model=model, + messages=[ + {"role": "user", "content": content}, + ], + max_tokens=max_new_tokens, + temperature=0.0, + ) + return _extract_completion_text(resp) + + +def _parse_qwen_api_model_list(raw: str) -> List[str]: + items: List[str] = [] + for part in re.split(r"[\s,]+", str(raw or "").strip()): + model = part.strip() + if model: + items.append(model) + return items + + +def _build_qwen_api_model_candidates(primary_model: str, fallback_models: str) -> List[str]: + candidates: List[str] = [] + seen = set() + for model in [str(primary_model or "").strip(), *_parse_qwen_api_model_list(fallback_models)]: + if not model or model in seen: + continue + seen.add(model) + candidates.append(model) + if not candidates: + raise RuntimeError("No Qwen API models configured.") + return candidates + + +def _qwen_api_error_details(exc: Exception) -> str: + parts: List[str] = [] + response = getattr(exc, "response", None) + status_code = getattr(exc, "status_code", None) + if status_code is None and response is not None: + status_code = getattr(response, "status_code", None) + if status_code is not None: + parts.append(f"status={status_code}") + + code = getattr(exc, "code", None) + body = getattr(exc, "body", None) + if code is None and isinstance(body, dict): + err = body.get("error") + if isinstance(err, dict): + code = err.get("code") or err.get("type") + if code: + parts.append(f"code={code}") + + message = str(exc).strip() + if message: + parts.append(message) + elif body is not None: + try: + parts.append(json.dumps(body, ensure_ascii=False)) + except Exception: + parts.append(repr(body)) + + return " | ".join(parts) if parts else exc.__class__.__name__ + + +def _qwen_api_should_fallback(exc: Exception) -> bool: + response = getattr(exc, "response", None) + status_code = getattr(exc, "status_code", None) + if status_code is None and response is not None: + status_code = getattr(response, "status_code", None) + if status_code in _QWEN_API_FALLBACK_STATUS_CODES: + return True + + details = _qwen_api_error_details(exc).lower() + return any(token in details for token in _QWEN_API_FALLBACK_ERROR_TOKENS) + + +def _run_qwen_api_chat_with_fallback( + client: Any, + model: str, + fallback_models: str, + image_paths: List[Path], + prompt: str, + max_new_tokens: int, +) -> Tuple[str, str, List[str]]: + candidates = _build_qwen_api_model_candidates(model, fallback_models) + attempted_models: List[str] = [] + failures: List[str] = [] + + for idx, candidate in enumerate(candidates, start=1): + attempted_models.append(candidate) + print(f"[INFO] Qwen API attempt {idx}/{len(candidates)} with model: {candidate}") + try: + raw = _run_qwen_api_chat( + client=client, + model=candidate, + image_paths=image_paths, + prompt=prompt, + max_new_tokens=max_new_tokens, + ) + if candidate != model: + print(f"[WARN] Qwen API switched model from {model} to {candidate}") + return raw, candidate, attempted_models + except Exception as exc: + details = _qwen_api_error_details(exc) + failures.append(f"{candidate}: {details}") + is_last = idx >= len(candidates) + if is_last or not _qwen_api_should_fallback(exc): + joined = "; ".join(failures) + raise RuntimeError(f"Qwen API request failed after trying models: {joined}") from exc + print(f"[WARN] Qwen API model {candidate} failed; trying next model. reason: {details}") + + raise RuntimeError("Qwen API request failed without any model attempts.") + + +def _run_qwen_labels_local( + keyframe_paths: List[Path], + qwen_model_path: str, + max_new_tokens: int, + max_objects: int, + max_count_per_label: int, + aggregate_threshold: int, + keep_set: Optional[set], + drop_set: Optional[set], +) -> Tuple[List[str], Dict[int, List[str]]]: + try: + from qwen_build_label_json import run_qwen_on_image, normalize_label # type: ignore + from transformers import AutoModelForImageTextToText, AutoProcessor # type: ignore + except Exception as exc: + raise RuntimeError( + "Qwen dependencies not available. Please run label generation in the qwen env." + ) from exc + + print(f"[INFO] Loading local Qwen model: {qwen_model_path}") + qwen_model = AutoModelForImageTextToText.from_pretrained( + qwen_model_path, + dtype="auto", + device_map="auto" if torch.cuda.is_available() else None, + ) + qwen_processor = AutoProcessor.from_pretrained(qwen_model_path) + + labels_per_keyframe: Dict[int, List[str]] = {} + label_sets: List[List[str]] = [] + for path in keyframe_paths: + frame_id = int(path.stem.split("_")[-1]) + result = run_qwen_on_image( + image_path=path, + model=qwen_model, + processor=qwen_processor, + max_new_tokens=max_new_tokens, + max_objects=max_objects, + max_count_per_label=max_count_per_label, + aggregate_threshold=aggregate_threshold, + ) + if not result: + continue + labels = result.get("labels", []) + labels = [normalize_label(x) for x in labels if normalize_label(x)] + label_sets.append(labels) + labels_per_keyframe[frame_id] = labels + + merged_labels = _merge_labels(label_sets, keep_set, drop_set) + return merged_labels, labels_per_keyframe + + +def _run_qwen_labels_api( + keyframe_paths: List[Path], + qwen_api_model: str, + qwen_api_model_list: str, + qwen_api_base_url: str, + qwen_api_key_env: str, + max_new_tokens: int, + max_objects: int, + aggregate_threshold: int, + keep_set: Optional[set], + drop_set: Optional[set], +) -> Tuple[List[str], Dict[int, List[str]]]: + try: + from openai import OpenAI # type: ignore + except Exception as exc: + raise RuntimeError( + "OpenAI SDK not available. Please install `openai` in the current environment." + ) from exc + + api_key = os.getenv(qwen_api_key_env, "").strip() + if not api_key: + raise RuntimeError( + f"Missing API key. Set environment variable: {qwen_api_key_env}" + ) + + print(f"[INFO] Using Qwen API model: {qwen_api_model}") + print(f"[INFO] API base URL: {qwen_api_base_url}") + print( + f"[INFO] Qwen API fallback candidates: " + f"{_build_qwen_api_model_candidates(qwen_api_model, qwen_api_model_list)}" + ) + client = OpenAI(api_key=api_key, base_url=qwen_api_base_url) + prompt = _build_qwen_api_label_prompt(max_objects=max_objects, aggregate_threshold=aggregate_threshold) + + if not keyframe_paths: + return [], {} + + frame_ids = [int(path.stem.split("_")[-1]) for path in keyframe_paths] + print(f"[INFO] API single-call keyframes: {frame_ids}") + raw, used_model, _attempted_models = _run_qwen_api_chat_with_fallback( + client=client, + model=qwen_api_model, + fallback_models=qwen_api_model_list, + image_paths=keyframe_paths, + prompt=prompt, + max_new_tokens=max_new_tokens, + ) + payload = _extract_json_payload(raw) + labels = _extract_labels_from_payload(payload, max_objects=max_objects) if payload is not None else [] + if not labels: + labels = _extract_labels_from_text_fallback(raw, max_objects=max_objects) + merged_labels = _merge_labels([labels], keep_set, drop_set) + labels_per_keyframe = {fid: list(merged_labels) for fid in frame_ids} + if used_model != qwen_api_model: + print(f"[INFO] Qwen labels API resolved model: {used_model}") + print(f"[INFO] API merged labels: {merged_labels}") + return merged_labels, labels_per_keyframe + + +def _run_qwen_labels_and_categories_api( + keyframe_paths: List[Path], + qwen_api_model: str, + qwen_api_model_list: str, + qwen_api_base_url: str, + qwen_api_key_env: str, + max_new_tokens: int, + max_objects: int, + aggregate_threshold: int, + keep_set: Optional[set], + drop_set: Optional[set], + strict: bool, +) -> Tuple[ + List[str], + Dict[int, List[str]], + Dict[str, str], + Dict[str, str], + Dict[str, str], + Dict[str, Any], +]: + try: + from openai import OpenAI # type: ignore + except Exception as exc: + raise RuntimeError( + "OpenAI SDK not available. Please install `openai` in the current environment." + ) from exc + + api_key = os.getenv(qwen_api_key_env, "").strip() + if not api_key: + raise RuntimeError( + f"Missing API key. Set environment variable: {qwen_api_key_env}" + ) + if not keyframe_paths: + raise RuntimeError("No keyframes available for single-pass label/category call.") + + print(f"[INFO] Using Qwen API model (single_pass): {qwen_api_model}") + print(f"[INFO] API base URL: {qwen_api_base_url}") + print( + f"[INFO] Qwen API fallback candidates: " + f"{_build_qwen_api_model_candidates(qwen_api_model, qwen_api_model_list)}" + ) + client = OpenAI(api_key=api_key, base_url=qwen_api_base_url) + prompt = _build_qwen_api_label_prompt( + max_objects=max_objects, + aggregate_threshold=aggregate_threshold, + include_category=True, + ) + frame_ids = [int(path.stem.split("_")[-1]) for path in keyframe_paths] + print(f"[INFO] API single-pass keyframes: {frame_ids}") + + raw, used_model, attempted_models = _run_qwen_api_chat_with_fallback( + client=client, + model=qwen_api_model, + fallback_models=qwen_api_model_list, + image_paths=keyframe_paths, + prompt=prompt, + max_new_tokens=max_new_tokens, + ) + payload = _extract_json_payload(raw) + if payload is None: + _print_qwen_raw_debug("Qwen single-pass returned non-JSON content.", raw) + raise RuntimeError("Qwen single-pass returned non-JSON content.") + + objs = _extract_label_objects_from_payload( + payload=payload, + max_objects=max_objects, + keep_set=keep_set, + drop_set=drop_set, + ) + if not objs: + if strict: + _print_qwen_raw_debug( + "Qwen single-pass returned empty/invalid objects list.", + raw, + payload, + ) + raise RuntimeError("Qwen single-pass returned empty/invalid objects list.") + labels = _extract_labels_from_payload(payload, max_objects=max_objects) + if not labels: + labels = _extract_labels_from_text_fallback(raw, max_objects=max_objects) + merged_labels = _merge_labels([labels], keep_set, drop_set) + labels_per_keyframe = {fid: list(merged_labels) for fid in frame_ids} + meta = { + "mode": "qwen_single_pass", + "qwen_api_model": used_model, + "qwen_api_model_requested": qwen_api_model, + "qwen_api_attempted_models": attempted_models, + "qwen_api_base_url": qwen_api_base_url, + "prompt": prompt, + "raw_response": raw, + "parsed_payload": payload, + "label_categories": {}, + "label_category_reasons": {}, + "label_visual_descriptions": {}, + "strict": bool(strict), + "created_at": datetime.now(timezone.utc).isoformat(), + } + return merged_labels, labels_per_keyframe, {}, {}, {}, meta + + merged_labels = [obj["name"] for obj in objs] + label_categories = {obj["name"]: obj["category"] for obj in objs if obj["category"]} + label_reasons = {obj["name"]: obj["reason"] for obj in objs if obj["reason"]} + label_visuals = { + obj["name"]: obj["visual_description"] for obj in objs if obj["visual_description"] + } + + if strict: + missing = [name for name in merged_labels if name not in label_categories] + if missing: + _print_qwen_raw_debug( + "Qwen single-pass missing category for some labels.", + raw, + payload, + ) + raise RuntimeError( + "Qwen single-pass missing category for labels: " + ", ".join(missing[:5]) + ) + + labels_per_keyframe = {fid: list(merged_labels) for fid in frame_ids} + meta = { + "mode": "qwen_single_pass", + "qwen_api_model": used_model, + "qwen_api_model_requested": qwen_api_model, + "qwen_api_attempted_models": attempted_models, + "qwen_api_base_url": qwen_api_base_url, + "labels": merged_labels, + "prompt": prompt, + "raw_response": raw, + "parsed_payload": payload, + "label_categories": label_categories, + "label_category_reasons": label_reasons, + "label_visual_descriptions": label_visuals, + "strict": bool(strict), + "created_at": datetime.now(timezone.utc).isoformat(), + } + return merged_labels, labels_per_keyframe, label_categories, label_reasons, label_visuals, meta + + +def _run_qwen_label_categories_api( + labels: List[str], + qwen_api_model: str, + qwen_api_model_list: str, + qwen_api_base_url: str, + qwen_api_key_env: str, + max_new_tokens: int, + strict: bool, +) -> Tuple[Dict[str, str], Dict[str, Any]]: + try: + from openai import OpenAI # type: ignore + except Exception as exc: + raise RuntimeError( + "OpenAI SDK not available. Please install `openai` in the current environment." + ) from exc + + api_key = os.getenv(qwen_api_key_env, "").strip() + if not api_key: + raise RuntimeError( + f"Missing API key. Set environment variable: {qwen_api_key_env}" + ) + if not labels: + raise RuntimeError("No labels available for Qwen category pass.") + + prompt = _build_qwen_api_category_prompt(labels) + client = OpenAI(api_key=api_key, base_url=qwen_api_base_url) + raw, used_model, attempted_models = _run_qwen_api_chat_with_fallback( + client=client, + model=qwen_api_model, + fallback_models=qwen_api_model_list, + image_paths=[], + prompt=prompt, + max_new_tokens=max_new_tokens, + ) + payload = _extract_json_payload(raw) + if payload is None: + _print_qwen_raw_debug("Qwen category pass returned non-JSON content.", raw) + raise RuntimeError("Qwen category pass returned non-JSON content.") + try: + mapping = _extract_label_category_mapping(payload, labels=labels, strict=strict) + except Exception: + _print_qwen_raw_debug("Qwen category pass payload validation failed.", raw, payload) + raise + meta = { + "qwen_api_model": used_model, + "qwen_api_model_requested": qwen_api_model, + "qwen_api_attempted_models": attempted_models, + "qwen_api_base_url": qwen_api_base_url, + "labels": labels, + "definitions": { + "static": "world-space pose approximately unchanged over time", + "rigid": "pose changes over time while shape stays rigid", + "deform": "non-rigid shape deformation over time", + }, + "prompt": prompt, + "raw_response": raw, + "parsed_payload": payload, + "label_categories": mapping, + "strict": bool(strict), + "created_at": datetime.now(timezone.utc).isoformat(), + } + return mapping, meta + + +def _run_qwen_labels( + keyframe_paths: List[Path], + qwen_backend: str, + qwen_model_path: str, + qwen_api_model: str, + qwen_api_model_list: str, + qwen_api_base_url: str, + qwen_api_key_env: str, + max_new_tokens: int, + max_objects: int, + max_count_per_label: int, + aggregate_threshold: int, + keep_set: Optional[set], + drop_set: Optional[set], +) -> Tuple[List[str], Dict[int, List[str]]]: + if qwen_backend == "api": + return _run_qwen_labels_api( + keyframe_paths=keyframe_paths, + qwen_api_model=qwen_api_model, + qwen_api_model_list=qwen_api_model_list, + qwen_api_base_url=qwen_api_base_url, + qwen_api_key_env=qwen_api_key_env, + max_new_tokens=max_new_tokens, + max_objects=max_objects, + aggregate_threshold=aggregate_threshold, + keep_set=keep_set, + drop_set=drop_set, + ) + if qwen_backend == "local": + return _run_qwen_labels_local( + keyframe_paths=keyframe_paths, + qwen_model_path=qwen_model_path, + max_new_tokens=max_new_tokens, + max_objects=max_objects, + max_count_per_label=max_count_per_label, + aggregate_threshold=aggregate_threshold, + keep_set=keep_set, + drop_set=drop_set, + ) + raise ValueError(f"Unsupported qwen backend: {qwen_backend}") + + +def _run_qwen_motion_labels_local( + keyframe_paths: List[Path], + qwen_model_path: str, + max_new_tokens: int, +) -> List[str]: + try: + from transformers import AutoModelForImageTextToText, AutoProcessor # type: ignore + from PIL import Image # type: ignore + except Exception as exc: + raise RuntimeError("Qwen dependencies not available for motion labels.") from exc + + prompt = ( + "你将看到一帧来自视频的图像。请判断哪些物体很可能是运动物体(会移动)。" + "仅输出 JSON:{\"moving\": [\"car\", \"person\"]}。如果无法判断请输出空列表。" + ) + + model = AutoModelForImageTextToText.from_pretrained( + qwen_model_path, + dtype="auto", + device_map="auto" if torch.cuda.is_available() else None, + ) + processor = AutoProcessor.from_pretrained(qwen_model_path) + + moving_sets: List[List[str]] = [] + for path in keyframe_paths: + image = Image.open(path).convert("RGB") + messages = [ + { + "role": "user", + "content": [ + {"type": "image", "image": image}, + {"type": "text", "text": prompt}, + ], + } + ] + inputs = processor.apply_chat_template( + messages, + tokenize=True, + add_generation_prompt=True, + return_tensors="pt", + return_dict=True, + ) + inputs = {k: v.to(model.device) for k, v in inputs.items()} + with torch.no_grad(): + generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens) + trimmed = [ + out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs["input_ids"], generated_ids) + ] + outputs = processor.batch_decode( + trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False + ) + if not outputs: + continue + raw = outputs[0].strip() + moving = _parse_json_list(raw, "moving") + if moving: + moving_sets.append(moving) + + merged = _merge_labels(moving_sets, None, None) + return merged + + +def _run_qwen_motion_labels_api( + keyframe_paths: List[Path], + qwen_api_model: str, + qwen_api_model_list: str, + qwen_api_base_url: str, + qwen_api_key_env: str, + max_new_tokens: int, +) -> List[str]: + try: + from openai import OpenAI # type: ignore + except Exception as exc: + raise RuntimeError( + "OpenAI SDK not available. Please install `openai` in the current environment." + ) from exc + + api_key = os.getenv(qwen_api_key_env, "").strip() + if not api_key: + raise RuntimeError( + f"Missing API key. Set environment variable: {qwen_api_key_env}" + ) + + prompt = ( + "你将看到一帧来自视频的图像。请判断哪些物体很可能是运动物体(会移动)。" + "仅输出 JSON:{\"moving\": [\"car\", \"person\"]}。如果无法判断请输出空列表。" + ) + client = OpenAI(api_key=api_key, base_url=qwen_api_base_url) + print( + f"[INFO] Qwen API fallback candidates: " + f"{_build_qwen_api_model_candidates(qwen_api_model, qwen_api_model_list)}" + ) + + moving_sets: List[List[str]] = [] + for path in keyframe_paths: + raw, used_model, _attempted_models = _run_qwen_api_chat_with_fallback( + client=client, + model=qwen_api_model, + fallback_models=qwen_api_model_list, + image_paths=[path], + prompt=prompt, + max_new_tokens=max_new_tokens, + ) + if used_model != qwen_api_model: + print(f"[INFO] Qwen motion API resolved model: {used_model}") + moving = _parse_json_list(raw, "moving") + if moving: + moving_sets.append(moving) + return _merge_labels(moving_sets, None, None) + + +def _run_qwen_motion_labels( + keyframe_paths: List[Path], + qwen_backend: str, + qwen_model_path: str, + qwen_api_model: str, + qwen_api_model_list: str, + qwen_api_base_url: str, + qwen_api_key_env: str, + max_new_tokens: int, +) -> List[str]: + if qwen_backend == "api": + return _run_qwen_motion_labels_api( + keyframe_paths=keyframe_paths, + qwen_api_model=qwen_api_model, + qwen_api_model_list=qwen_api_model_list, + qwen_api_base_url=qwen_api_base_url, + qwen_api_key_env=qwen_api_key_env, + max_new_tokens=max_new_tokens, + ) + if qwen_backend == "local": + return _run_qwen_motion_labels_local( + keyframe_paths=keyframe_paths, + qwen_model_path=qwen_model_path, + max_new_tokens=max_new_tokens, + ) + raise ValueError(f"Unsupported qwen backend: {qwen_backend}") + + +_SAM3_MODEL_CACHE: Dict[str, Any] = {} + + +def load_once(sam3_ckpt: Optional[str] = None): + """一次性加载 SAM3 video model 并缓存;同一 ckpt 二次调用直接复用句柄。 + + 返回 (sam3_model, resolved_ckpt_path_or_None)。init_state 仍按视频单独调用。 + 注:masks 模式下 Qwen 标签走 API(无需常驻本地模型),故此处只常驻 SAM3。 + """ + ckpt_path = Path(sam3_ckpt).resolve() if sam3_ckpt else None + if ckpt_path is not None and not ckpt_path.exists(): + print(f"[WARN] SAM3 checkpoint not found: {ckpt_path}. Falling back to HF.") + ckpt_path = None + key = str(ckpt_path or "__HF__") + model = _SAM3_MODEL_CACHE.get(key) + if model is None: + print(f"[INFO] Loading SAM3 checkpoint: {ckpt_path or 'HF default'}") + try: + from sam3.model_builder import build_sam3_video_model # type: ignore + except Exception as exc: + raise RuntimeError( + "SAM3 dependencies not available. Please run masks in the sam3 env." + ) from exc + model = build_sam3_video_model( + checkpoint_path=str(ckpt_path) if ckpt_path else None, + load_from_HF=ckpt_path is None, + ) + _SAM3_MODEL_CACHE[key] = model + print(f"[INFO] SAM3 model resident (cached): {ckpt_path or 'HF default'}") + else: + print(f"[INFO] Reuse resident SAM3 model: {ckpt_path or 'HF default'}") + return model, ckpt_path + + +def main(argv: Optional[List[str]] = None) -> None: + parser = argparse.ArgumentParser(description="Qwen + SAM3 video masks for 4D reconstruction") + parser.add_argument("--video-path", type=Path, required=True, help="Input video path") + parser.add_argument( + "--mode", + type=str, + default="all", + choices=("all", "labels", "masks"), + help="Run labels only, masks only, or both", + ) + parser.add_argument( + "--labels-json", + type=Path, + default=None, + help="Use existing labels json (for masks mode)", + ) + parser.add_argument( + "--labels", + type=str, + default="", + help="Comma-separated labels to bypass Qwen", + ) + parser.add_argument( + "--dynamic-source", + type=str, + default="motion", + choices=("motion", "qwen", "hybrid"), + help="How to decide dynamic objects", + ) + parser.add_argument( + "--qwen-motion", + action="store_true", + help="Use Qwen to infer moving labels (used with dynamic-source=qwen/hybrid)", + ) + parser.add_argument( + "--dynamic-labels", + type=str, + default="", + help="Comma-separated dynamic labels (override)", + ) + parser.add_argument( + "--static-labels", + type=str, + default="", + help="Comma-separated static labels (override)", + ) + parser.add_argument( + "--rigid-labels", + type=str, + default="", + help="Comma-separated labels to force rigid category", + ) + parser.add_argument( + "--deform-labels", + type=str, + default="", + help="Comma-separated labels to force deform category", + ) + parser.add_argument( + "--default-dynamic-category", + type=str, + default="rigid", + choices=("rigid", "deform"), + help="Category for dynamic objects not in rigid/deform lists", + ) + parser.add_argument( + "--qwen-backend", + type=str, + default="api", + choices=("api", "local"), + help="Qwen label backend: api (default) or local model", + ) + parser.add_argument( + "--qwen-model", + type=str, + default="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts/public_ckpts/model/Qwen3-VL-32B-Instruct", + help="Local Qwen model path or HF ID (used when backend=local)", + ) + parser.add_argument( + "--qwen-api-model", + type=str, + default=DEFAULT_QWEN_API_MODEL, + help="Qwen API model name (used when backend=api)", + ) + parser.add_argument( + "--qwen-api-model-list", + type=str, + default=DEFAULT_QWEN_API_MODEL_LIST, + help="Comma/space-separated fallback Qwen API models used when the primary model is unavailable or out of quota", + ) + parser.add_argument( + "--qwen-api-base-url", + type=str, + default="https://dashscope.aliyuncs.com/compatible-mode/v1", + help="DashScope OpenAI-compatible base URL (used when backend=api)", + ) + parser.add_argument( + "--qwen-api-key-env", + type=str, + default="DASHSCOPE_API_KEY", + help="Environment variable name for API key", + ) + parser.add_argument( + "--qwen-category-pass", + type=int, + default=0, + choices=(0, 1), + help="Run a second Qwen API call to classify labels into static/rigid/deform", + ) + parser.add_argument( + "--qwen-category-pass-strict", + type=int, + default=1, + choices=(0, 1), + help="Fail if second-pass category payload is invalid or incomplete", + ) + parser.add_argument( + "--qwen-category-api-model", + type=str, + default="", + help="Qwen API model for second-pass category classification (default: --qwen-api-model)", + ) + parser.add_argument( + "--qwen-category-max-new-tokens", + type=int, + default=512, + help="Max new tokens for second-pass category classification", + ) + parser.add_argument( + "--qwen-label-category-mode", + type=str, + default="legacy", + choices=("legacy", "single_pass", "dual_pass"), + help="Category source mode: legacy rules, single-pass labels+category, or dual-pass category API", + ) + parser.add_argument( + "--qwen-label-category-strict", + type=int, + default=1, + choices=(0, 1), + help="Strict validation for qwen-label-category-mode (fail on invalid/missing category)", + ) + parser.add_argument( + "--qwen-label-category-model", + type=str, + default="", + help="Model for qwen-label-category-mode (default: --qwen-api-model)", + ) + parser.add_argument("--keyframe-count", type=int, default=5, help="Number of keyframes") + parser.add_argument( + "--keyframe-max-side", + type=int, + default=1280, + help="Max side length for keyframe images (resize if larger). Set 0 to disable.", + ) + parser.add_argument("--max-objects", type=int, default=15, help="Max labels per keyframe") + parser.add_argument("--max-new-tokens", type=int, default=512, help="Qwen max new tokens") + parser.add_argument( + "--max-count-per-label", + type=int, + default=20, + help="Max instances per label (Qwen post-processing)", + ) + parser.add_argument( + "--aggregate-threshold", + type=int, + default=10, + help="Aggregate threshold for Qwen label counts", + ) + parser.add_argument("--keep-labels", type=str, default="", help="Comma-separated keep list") + parser.add_argument("--drop-labels", type=str, default="", help="Comma-separated drop list") + parser.add_argument( + "--sam3-ckpt", + type=str, + default="/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/third_party/sam3/checkpoints/sam3/sam3.pt", + help="SAM3 checkpoint path", + ) + parser.add_argument( + "--output-root", + type=Path, + default=Path("outputs"), + help="Output root directory", + ) + parser.add_argument( + "--min-obj-area", + type=int, + default=200, + help="Minimum mask area to keep an instance", + ) + parser.add_argument( + "--static-iou-thresh", + type=float, + default=0.6, + help="Mean IoU threshold for static classification", + ) + parser.add_argument( + "--static-motion-px", + type=float, + default=10.0, + help="Mean centroid motion threshold (px) for static classification", + ) + parser.add_argument( + "--high-iou-static", + type=float, + default=0.8, + help="If IoU >= this, allow a higher motion threshold", + ) + parser.add_argument( + "--high-iou-motion-mult", + type=float, + default=3.0, + help="Motion multiplier for high-IoU static objects", + ) + parser.add_argument( + "--occlusion-area-ratio", + type=float, + default=0.6, + help="Frames with area < median*ratio are treated as occluded", + ) + parser.add_argument( + "--occlusion-overlap-ratio", + type=float, + default=0.2, + help="If overlap with dynamic union exceeds this ratio, treat as occluded", + ) + parser.add_argument( + "--min-valid-frames", + type=int, + default=10, + help="Minimum valid frames to judge static", + ) + parser.add_argument( + "--dynamic-seed-motion-mult", + type=float, + default=3.0, + help="Seed dynamic if motion >= static_motion * mult", + ) + parser.add_argument( + "--dynamic-seed-iou-ratio", + type=float, + default=0.5, + help="Seed dynamic if IoU <= static_iou_thresh * ratio", + ) + parser.add_argument( + "--prompt-frame", + type=int, + default=0, + help="Frame index to apply SAM3 text prompt", + ) + parser.add_argument( + "--post-only", + action="store_true", + help="Skip SAM3 inference and recompute summary/config from existing masks", + ) + parser.add_argument( + "--recon-root", + type=Path, + default=None, + help="Output directory for recon-ready config (default: output_root/recon_ready/ +""" +import argparse +import json +import os +import sys +from pathlib import Path + +os.environ.setdefault("PYOPENGL_PLATFORM", "egl") + +_QWEN_DIR = Path(__file__).resolve().parent +_OVOW_ROOT = _QWEN_DIR.parent +_ENGINE_DIR = Path(os.environ.get("ENGINE_DIR", str(_OVOW_ROOT / "engine"))) +_SAM3_DIR = Path(os.environ.get("SAM3_DIR", str(_OVOW_ROOT / "third_party" / "sam3"))) +_IPC_DIR = str(_ENGINE_DIR / "tools" / "model_server") +for p in (_IPC_DIR, str(_QWEN_DIR)): + if p not in sys.path: + sys.path.insert(0, p) + +import ipc # noqa: E402 (tools/model_server 在 path 上) + +_DEFAULT_SAM3_CKPT = os.environ.get("SAM3_CKPT", str(_SAM3_DIR / "checkpoints" / "sam3" / "sam3.pt")) + + +def _warm_models(): + """一次性加载 SAM3 video model(常驻)。""" + print("[sam3-server] 加载 SAM3 video model(常驻)...", flush=True) + import qwen_sam3_video_masks as qsvm # noqa: F401 + qsvm.load_once(os.environ.get("SAM3_CKPT") or _DEFAULT_SAM3_CKPT) + print("[sam3-server] SAM3 ckpt 载入完成。", flush=True) + + +def _handle_masks(args): + """进程内单视频 mask 生成:复用常驻 SAM3,init_state 按视频新建。""" + import qwen_sam3_video_masks as qsvm + argv = args["argv"] + old = sys.argv + try: + sys.argv = ["qwen_sam3_video_masks.py"] + list(argv) + qsvm.main() + finally: + sys.argv = old + return {"video": args.get("video_name", "")} + + +def _as_bool_mask(mask): + import numpy as np + + arr = np.asarray(mask) + arr = np.squeeze(arr) + if arr.ndim != 2: + raise RuntimeError(f"Unexpected SAM3 mask shape: {arr.shape}") + return arr > 0 + + +def _normalize_points(raw_points, width: int, height: int): + points = [] + labels = [] + for item in raw_points: + if isinstance(item, dict): + x = float(item.get("x", item.get("px", 0.0))) + y = float(item.get("y", item.get("py", 0.0))) + label = int(item.get("label", 1)) + else: + x = float(item[0]) + y = float(item[1]) + label = int(item[2]) if len(item) > 2 else 1 + if x > 1.0 or y > 1.0: + x = x / max(1, width) + y = y / max(1, height) + x = min(1.0, max(0.0, x)) + y = min(1.0, max(0.0, y)) + points.append([x, y]) + labels.append(1 if label else 0) + if not any(labels): + raise RuntimeError("manual SAM3 points need at least one positive point") + return points, labels + + +def _prime_empty_cached_outputs(inference_state, num_frames: int): + """Point prompts are tracker refinements; SAM3 expects a per-frame VG cache.""" + cached = inference_state.setdefault("cached_frame_outputs", {}) + for frame_idx in range(max(0, int(num_frames))): + cached.setdefault(frame_idx, {}) + + +def _collect_obj_masks(masks_by_frame: dict, frame_idx: int, out: dict | None, obj_id: int): + if out is None: + return + for oid, mask in zip(out.get("out_obj_ids", []), out.get("out_binary_masks", [])): + if int(oid) != obj_id: + continue + arr = _as_bool_mask(mask) + if int(arr.sum()) > 0: + masks_by_frame[int(frame_idx)] = arr + + +def _save_sparse_masks(obj_dir: Path, masks_by_frame: dict) -> None: + obj_dir.mkdir(parents=True, exist_ok=True) + from PIL import Image # type: ignore + + for fid, mask in sorted(masks_by_frame.items()): + out = (_as_bool_mask(mask).astype("uint8") * 255) + Image.fromarray(out).save(obj_dir / f"frame_{int(fid):06d}.png") + + +def _click_boxes_from_points(points, point_labels, specs): + positives = [p for p, label in zip(points, point_labels) if int(label)] + if not positives: + raise RuntimeError("manual box prompt needs at least one positive point") + x, y = positives[-1] + boxes = [] + for spec in specs or []: + if isinstance(spec, dict): + bw = float(spec.get("w", spec.get("width", 0.55))) + bh = float(spec.get("h", spec.get("height", 0.45))) + else: + bw = float(spec[0]) + bh = float(spec[1] if len(spec) > 1 else spec[0]) + bw = min(0.98, max(0.03, bw)) + bh = min(0.98, max(0.03, bh)) + x0 = min(max(float(x) - bw * 0.5, 0.0), 1.0 - bw) + y0 = min(max(float(y) - bh * 0.5, 0.0), 1.0 - bh) + boxes.append([x0, y0, bw, bh]) + if not boxes: + raise RuntimeError("manual box prompt has no valid click box sizes") + return boxes + + +def _mask_has_point(mask, points, point_labels, radius: int = 4) -> bool: + positives = [p for p, label in zip(points, point_labels) if int(label)] + if not positives: + return False + h, w = mask.shape[:2] + for x_norm, y_norm in positives: + x = int(round(float(x_norm) * max(1, w - 1))) + y = int(round(float(y_norm) * max(1, h - 1))) + x0, x1 = max(0, x - radius), min(w, x + radius + 1) + y0, y1 = max(0, y - radius), min(h, y + radius + 1) + if bool(mask[y0:y1, x0:x1].any()): + return True + return False + + +def _select_prompt_object(out: dict | None, points, point_labels): + if out is None: + return None, None, 0 + best = None + for oid, mask in zip(out.get("out_obj_ids", []), out.get("out_binary_masks", [])): + arr = _as_bool_mask(mask) + area = int(arr.sum()) + if area <= 0: + continue + has_point = _mask_has_point(arr, points, point_labels) + score = (1 if has_point else 0, area) + if best is None or score > best[0]: + best = (score, int(oid), arr, area) + if best is None: + return None, None, 0 + return best[1], best[2], best[3] + + +def _next_object_name(mask_root: Path, label: str) -> str: + safe = label + idx = 1 + while (mask_root / f"{safe}_{idx:02d}").exists(): + idx += 1 + return f"{safe}_{idx:02d}" + + +def _append_unique(items, value): + if value not in items: + items.append(value) + return items + + +def _labels_per_keyframe_dict(payload: dict) -> dict: + out = {} + for key, values in (payload.get("labels_per_keyframe") or {}).items(): + try: + frame = int(key) + except (TypeError, ValueError): + continue + out[frame] = [str(v) for v in (values or [])] + return out + + +def _as_bool(value, default: bool = True) -> bool: + if value is None: + return default + if isinstance(value, bool): + return value + text = str(value).strip().lower() + if text in {"1", "true", "yes", "on"}: + return True + if text in {"0", "false", "no", "off"}: + return False + return default + + +def _commit_object_metadata( + *, output_root, video_path, video_name, num_frames, fps, width, height, + mask_root, obj_dir, obj_name, label, category, frame_idx, points, point_labels, + object_summary, args, +): + """Upsert one manual object into labels_json / mask_summary / pipeline_config. + + Shared by the single-object and batch manual handlers so both emit identical + metadata (upsert-by-name, same schema the review UI + run_recon consume).""" + import qwen_sam3_video_masks as qsvm + meta_dir = output_root / "metadata" + labels_json = meta_dir / f"{video_name}_labels.json" + label_norm = qsvm._simple_normalize(label) + if labels_json.is_file(): + labels_payload = json.loads(labels_json.read_text(encoding="utf-8")) + else: + qsvm._write_labels_json( + labels_json, video_path, num_frames, fps, width, height, [], [], {}, + ) + labels_payload = json.loads(labels_json.read_text(encoding="utf-8")) + keyframes = [int(x) for x in (labels_payload.get("keyframes") or [])] + _append_unique(keyframes, int(frame_idx)) + labels = [str(x) for x in (labels_payload.get("labels") or [])] + _append_unique(labels, label) + labels_per_keyframe = _labels_per_keyframe_dict(labels_payload) + labels_per_keyframe.setdefault(int(frame_idx), []) + _append_unique(labels_per_keyframe[int(frame_idx)], label) + label_categories = dict(labels_payload.get("label_categories") or {}) + label_categories[label_norm] = category + labels_payload.update({ + "video": str(video_path), + "video_name": video_name, + "num_frames": int(num_frames), + "fps": float(fps), + "width": int(width), + "height": int(height), + "keyframes": sorted(keyframes), + "labels": labels, + "labels_per_keyframe": {str(k): v for k, v in sorted(labels_per_keyframe.items())}, + "label_categories": label_categories, + }) + labels_payload["label_category_source"] = "manual_click" + manual_points = list(labels_payload.get("manual_points") or []) + manual_points.append({ + "object": obj_name, + "label": label, + "points": points, + "point_labels": point_labels, + "frame_idx": frame_idx, + }) + labels_payload["manual_points"] = manual_points + labels_json.write_text(json.dumps(labels_payload, indent=2), encoding="utf-8") + + objects_summary = [object_summary] + summary_path = meta_dir / f"{video_name}_mask_summary.json" + meta_dir.mkdir(parents=True, exist_ok=True) + if summary_path.is_file(): + summary = json.loads(summary_path.read_text(encoding="utf-8")) + else: + summary = { + "video": str(video_path), + "video_name": video_name, + "num_frames": int(num_frames), + "fps": float(fps), + "width": int(width), + "height": int(height), + "keyframes": [], + "labels": [], + "labels_per_keyframe": {}, + "moving_labels": [], + "objects": [], + "mask_root": str(mask_root), + "labels_json": str(labels_json), + "qwen_label_category_mode": "manual_click", + "label_category_source": "manual_click", + "label_categories": {}, + "label_category_reasons": {}, + "label_visual_descriptions": {}, + "label_prompt_aliases": {}, + } + summary.update({ + "video": str(video_path), + "video_name": video_name, + "num_frames": int(num_frames), + "fps": float(fps), + "width": int(width), + "height": int(height), + "mask_root": str(mask_root), + "labels_json": str(labels_json), + "qwen_label_category_mode": "manual_click", + "label_category_source": "manual_click", + }) + keyframes = [int(x) for x in (summary.get("keyframes") or [])] + _append_unique(keyframes, int(frame_idx)) + labels = [str(x) for x in (summary.get("labels") or [])] + _append_unique(labels, label) + labels_per_keyframe = _labels_per_keyframe_dict(summary) + labels_per_keyframe.setdefault(int(frame_idx), []) + _append_unique(labels_per_keyframe[int(frame_idx)], label) + moving_labels = [str(x) for x in (summary.get("moving_labels") or [])] + if category in {"rigid", "deform"}: + _append_unique(moving_labels, label) + else: + moving_labels = [x for x in moving_labels if x != label] + label_categories = dict(summary.get("label_categories") or {}) + label_categories[label_norm] = category + existing_objects = [ + obj for obj in (summary.get("objects") or []) + if str(obj.get("name", "")) != obj_name + ] + summary["keyframes"] = sorted(keyframes) + summary["labels"] = labels + summary["labels_per_keyframe"] = {str(k): v for k, v in sorted(labels_per_keyframe.items())} + summary["moving_labels"] = moving_labels + summary["label_categories"] = label_categories + summary["objects"] = existing_objects + objects_summary + summary_path.write_text(json.dumps(summary, indent=2), encoding="utf-8") + + recon_root = output_root / "recon_ready" / video_name + recon_root.mkdir(parents=True, exist_ok=True) + batch_config = args.get("batch_config") or str(_ENGINE_DIR / "config" / "batch_config_example_legacy.json") + cfg_path = recon_root / "pipeline_config.json" + if cfg_path.is_file(): + pipeline_cfg = json.loads(cfg_path.read_text(encoding="utf-8")) + else: + pipeline_cfg = { + "batch_config": str(Path(batch_config).resolve()), + "video_path": str(video_path), + "output_root": str(output_root), + "mask_glob": "frame_*.png", + "tracker_mask_mode": "static", + "objects": [], + } + pipeline_cfg.update({ + "batch_config": str(Path(pipeline_cfg.get("batch_config") or batch_config).resolve()), + "video_path": str(video_path), + "output_root": str(output_root), + "mask_glob": "frame_*.png", + "tracker_mask_mode": "static", + }) + existing_cfg_objects = [ + obj for obj in (pipeline_cfg.get("objects") or []) + if str(obj.get("name", "")) != obj_name + ] + existing_cfg_objects.append({ + "name": obj_name, + "masks_dir": str(obj_dir), + "category": category, + }) + pipeline_cfg["objects"] = existing_cfg_objects + cfg_path.write_text(json.dumps(pipeline_cfg, indent=2), encoding="utf-8") + + return { + "video": video_name, + "object": obj_name, + "category": category, + "frames_with_mask": int(object_summary.get("frames_with_mask", 0)), + "summary": str(summary_path), + "pipeline_config": str(cfg_path), + } + + +def _handle_manual_points_batch(args): + """Segment several manually-clicked objects in ONE video pass. + + A single click only masks one frame; every object still needs its mask propagated + across the whole video (Motion324 wants every frame; the scene animation gates each + object's visibility on masked frames). Running one ``manual_points`` request per object + re-encodes all video frames each time (~50s each) because SAM3 evicts per-frame features + as it propagates (sliding window). Here we point-prompt every object into ONE + ``inference_state`` (distinct obj_ids) and propagate once per prompt-frame group, so each + frame's image features are computed once and shared by every object's tracker at that + frame → ~N× faster. Instance identity is preserved: each obj_id yields its own binary + mask written to its own ``masks/

Motion 3-to-4: 3D Motion Reconstruction for 4D Synthesis +

+ +
+ +[![arXiv](https://img.shields.io/badge/Arxiv-2503.24391-b31b1b.svg?logo=arXiv)](https://arxiv.org/abs/2601.14253) +[![Home Page](https://img.shields.io/badge/Project-Website-green.svg)](https://motion3-to-4.github.io/) + +[Hongyuan Chen](https://hyuanChen.github.io/), +[Xingyu Chen](https://rover-xingyu.github.io/), +[Youjia Zhang](https://youjiazhang.github.io/), +[Zexiang Xu](https://zexiangxu.github.io/), +[Anpei Chen](https://apchenstu.github.io/), +
+
+ +Motion 3-to-4 reconstructs 3D motion from videos for 4D synthesis in a **feedforward** mannar within seconds. +
+ +## Quick Start + +For users who want to quickly try the inference: + +```bash +git clone https://github.com/Inception3D/Motion324.git +cd Motion324 + +# 1. Setup environment +conda create -n Motion324 python=3.11 +conda activate Motion324 +pip install -r requirements.txt +# Install Hunyuan3D-2.0 components(optional) +cd scripts/hy3dgen/texgen/custom_rasterizer +python3 setup.py install +cd ../../../.. +cd scripts/hy3dgen/texgen/differentiable_renderer +python3 setup.py install +cd ../../../.. + +# 2. Download pre-trained checkpoints and place in experiments/checkpoints/ + +# 3. Run inference +chmod +x ./scripts/4D_from_existing.sh +./scripts/4D_from_existing.sh ./examples/chili.glb ./examples/chili.mp4 ./examples/output + +# Hunyuan needed +chmod +x ./scripts/4D_from_video.sh +./scripts/4D_from_video.sh ./examples/tiger.mp4 +``` + +## 1. Preparation + +### Checkpoints + +**Download**: Please download the pre-trained checkpoint from [here](https://huggingface.co/River-Chen/Motion324/tree/main) and place it in `experiments/checkpoints/`. + +### Environment Details +#### Setup up base environment +```bash +conda create -n Motion324 python=3.11 +conda activate Motion324 +pip install -r requirements.txt +``` +The code has been tested with Python 3.11 + Pytorch 2.4.1 + CUDA 12.4. + +#### Setup Hunyuan3D-2.0 Components +```bash +# Install custom rasterizer +cd scripts/hy3dgen/texgen/custom_rasterizer +python3 setup.py install +cd ../../../.. + +# Install differentiable renderer +cd scripts/hy3dgen/texgen/differentiable_renderer +python3 setup.py install +cd ../../../.. +``` +#### Setup Blender +Download and install Blender for 4D asset rendering. + +Our results is rendered with [blender-4.0.0-linux-x64](https://download.blender.org/release/Blender4.0/blender-4.0.0-linux-x64.tar.xz), using the scripts which is modified from [bpy-renderer](https://github.com/huanngzh/bpy-renderer). + +Installation steps: +```bash +# Download Blender +wget https://download.blender.org/release/Blender4.0/blender-4.0.0-linux-x64.tar.xz +tar -xf blender-4.0.0-linux-x64.tar.xz + +# Add Blender to PATH (optional, or use full path in scripts) +export PATH=$PATH:$(pwd)/blender-4.0.0-linux-x64 +``` + +**Note**: As we use [xformers](https://github.com/facebookresearch/xformers) `memory_efficient_attention` with [flash_attn](https://github.com/Dao-AILab/flash-attention/releases/tag/v2.7.4.post1), the GPU device compute capability needs > 8.0. Otherwise, it would pop up an error. Check your GPU compute capability in [CUDA GPUs Page](https://developer.nvidia.com/cuda-gpus#compute). + +### Dataset +- [ ] TODO: Dataset will be provided. Please check back for updates. + +Update the dataset path in `configs/dyscene.yaml`: +```yaml +training: + dataset_path: /path/to/your/dataset + train_lst: /path/to/name_list +``` + +## 2. Training + +Before training, you need to follow the instructions [here](https://docs.wandb.ai/guides/track/public-api-guide/#:~:text=You%20can%20generate%20an%20API,in%20the%20upper%20right%20corner.) to generate the Wandb key file for logging and save it in the `configs` folder as `api_keys.yaml`. + +### Training Command + +The default training uses `configs/dyscene.yaml`: + +```bash +torchrun --nproc_per_node 8 --nnodes 1 --master_port 12344 train.py --config configs/dyscene.yaml +``` + +### Training Configuration + +Key training parameters in `configs/dyscene.yaml`: +You can override any config parameter via command line: + +```bash +torchrun --nproc_per_node 8 --nnodes 1 --master_port 12346 train.py --config configs/dyscene.yaml \ + training.batch_size_per_gpu=32 +``` + +## 3. Inference + +### Generate 4D animation from a single video input + +**Input**: Video file (`.mp4/.avi/.mov`) or image directory (use `./scripts/images2video.py` to convert images to video first) + +**Output**: +- Processed frames and mesh files in `{video_name}_processed/` +- Animation output in `{video_name}_processed/animation/` (FBX format) + +**Example**: +```bash +chmod +x ./scripts/4D_from_video.sh +./scripts/4D_from_video.sh ./examples/tiger.mp4 +``` + +### Reconstruct 4D from an existing mesh and video + +**Inputs**: +- `data_dir`: Mesh file (`.glb` or `.fbx`) - FBX files will be automatically converted to GLB +- `video_path`: Video file (`.mp4/.avi/.mov`) or image directory +- `output_dir`: Output directory for results + +**Output**: +- Animated mesh files (GLB format) in the specified output directory +- Segmented videos if segmentation is enabled + +**Example**: +```bash +chmod +x ./scripts/4D_from_existing.sh +./scripts/4D_from_existing.sh ./examples/chili.glb ./examples/chili.mp4 ./examples/output +``` + +## 4. Evaluation + +You can evaluate video results with the provided `evaluation.py` script. + +Example: + +```bash +python ./evaluation/evaluation.py \ +--gt_paths /paths/to/gt_videos.mp4 \ +--result_paths /paths/to/results_videos.mp4 +``` +This compares the generated result video(s) to the ground-truth and outputs metrics such as FVD, LPIPS, DreamSim, and CLIP Loss. + +You can evaluate mesh geometry with the provided `evaluation_pcd.py` script. + +Example: + +```bash +python ./evaluation/evaluation_pcd.py \ +--gt_path /paths/to/name_pointclouds \ +--result_path /paths/to/mesh.fbx +``` +This compares your mesh result with the ground-truth point cloud and evaluates the geometric error between them. +It outputs metrics such as Chamfer Distance and F-score. + +## 5. Citation + +If you find this work useful in your research, please consider citing: + +```bibtex +@article{chen2026motion3to4, + title={Motion 3-to-4: 3D Motion Reconstruction for 4D Synthesis}, + author={Hongyuan, Chen and Xingyu, Chen and Youjia Zhang, and Zexiang, Xu and Anpei, Chen}, + journal={arXiv preprint arXiv:2601.14253}, + year={2026} +} +``` +## 6. Acknowledgments +- [LVSM](https://github.com/Haian-Jin/LVSM) (for code architecture reference) +- [V2M4](https://github.com/WindVChen/V2M4), [AnimateAnyMesh](https://github.com/JarrentWu1031/AnimateAnyMesh) (for code reference) +- [bpy-renderer](https://github.com/huanngzh/bpy-renderer) (for rendering results) +- [Hunyuan3D-2](https://github.com/Tencent-Hunyuan/Hunyuan3D-2) (for 3D generation) + +## 7. License + +This project is licensed under the [CC BY-NC-SA 4.0 License](LICENSE.md) - see the LICENSE.md file for details. diff --git a/OVOW/third_party/Motion324/configs/api_keys.yaml b/OVOW/third_party/Motion324/configs/api_keys.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1ff54a263d1abae49f63628e4dd0626af01df8d3 --- /dev/null +++ b/OVOW/third_party/Motion324/configs/api_keys.yaml @@ -0,0 +1 @@ +wandb: your_api_key \ No newline at end of file