Showing preview only (602K chars total). Download the full file or copy to clipboard to get everything.
Repository: Tencent-Hunyuan/Hunyuan3D-2
Branch: main
Commit: f8db63096c82
Files: 100
Total size: 570.5 KB
Directory structure:
gitextract_k0kyt9hn/
├── .gitignore
├── .readthedocs.yaml
├── LICENSE
├── NOTICE
├── README.md
├── README_ja_jp.md
├── README_zh_cn.md
├── api_server.py
├── assets/
│ ├── 1.glb
│ ├── example_prompts.txt
│ ├── modelviewer-template.html
│ └── modelviewer-textured-template.html
├── blender_addon.py
├── docs/
│ ├── Makefile
│ ├── README.md
│ ├── make.bat
│ ├── requirements.txt
│ └── source/
│ ├── _static/
│ │ └── css/
│ │ └── custom.css
│ ├── citation.md
│ ├── conf.py
│ ├── index.md
│ ├── installation/
│ │ └── index.md
│ ├── modelzoo.md
│ └── started/
│ ├── api.md
│ ├── blender.md
│ ├── code.md
│ ├── comfyui.md
│ ├── gradio.md
│ ├── index.md
│ └── studio.md
├── examples/
│ ├── fast_shape_gen_multiview.py
│ ├── fast_shape_gen_with_flashvdm.py
│ ├── fast_texture_gen_multiview.py
│ ├── faster_shape_gen_with_flashvdm_mini_turbo.py
│ ├── shape_gen.py
│ ├── shape_gen_mini.py
│ ├── shape_gen_multiview.py
│ ├── shape_gen_v2_1.py
│ ├── textured_shape_gen.py
│ ├── textured_shape_gen_mini.py
│ └── textured_shape_gen_multiview.py
├── gradio_app.py
├── hy3dgen/
│ ├── __init__.py
│ ├── rembg.py
│ ├── shapegen/
│ │ ├── __init__.py
│ │ ├── models/
│ │ │ ├── __init__.py
│ │ │ ├── autoencoders/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── attention_blocks.py
│ │ │ │ ├── attention_processors.py
│ │ │ │ ├── model.py
│ │ │ │ ├── surface_extractors.py
│ │ │ │ └── volume_decoders.py
│ │ │ ├── conditioner.py
│ │ │ └── denoisers/
│ │ │ ├── __init__.py
│ │ │ ├── hunyuan3ddit.py
│ │ │ ├── hunyuandit.py
│ │ │ └── moe_layers.py
│ │ ├── pipelines.py
│ │ ├── postprocessors.py
│ │ ├── preprocessors.py
│ │ ├── schedulers.py
│ │ ├── surface_loaders.py
│ │ └── utils.py
│ ├── texgen/
│ │ ├── __init__.py
│ │ ├── custom_rasterizer/
│ │ │ ├── custom_rasterizer/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── io_glb.py
│ │ │ │ ├── io_obj.py
│ │ │ │ └── render.py
│ │ │ ├── lib/
│ │ │ │ └── custom_rasterizer_kernel/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── grid_neighbor.cpp
│ │ │ │ ├── rasterizer.cpp
│ │ │ │ ├── rasterizer.h
│ │ │ │ └── rasterizer_gpu.cu
│ │ │ └── setup.py
│ │ ├── differentiable_renderer/
│ │ │ ├── __init__.py
│ │ │ ├── camera_utils.py
│ │ │ ├── compile_mesh_painter.bat
│ │ │ ├── mesh_processor.cpp
│ │ │ ├── mesh_processor.py
│ │ │ ├── mesh_render.py
│ │ │ ├── mesh_utils.py
│ │ │ └── setup.py
│ │ ├── hunyuanpaint/
│ │ │ ├── __init__.py
│ │ │ ├── pipeline.py
│ │ │ └── unet/
│ │ │ ├── __init__.py
│ │ │ └── modules.py
│ │ ├── pipelines.py
│ │ └── utils/
│ │ ├── __init__.py
│ │ ├── alignImg4Tex_utils.py
│ │ ├── counter_utils.py
│ │ ├── dehighlight_utils.py
│ │ ├── imagesuper_utils.py
│ │ ├── multiview_utils.py
│ │ ├── simplify_mesh_utils.py
│ │ └── uv_warp_utils.py
│ └── text2image.py
├── minimal_demo.py
├── minimal_vae_demo.py
├── requirements.txt
└── setup.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
!hy3dgen/texgen/custom_rasterizer/lib/
lib64/
parts/
sdist/
var/
wheels/
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
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .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
# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
#uv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__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/
# pytype static type analyzer
.pytype/
.DS_Store
# Cython debug symbols
cython_debug/
gradio_cache/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
================================================
FILE: .readthedocs.yaml
================================================
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
# Required
version: 2
# Set the OS, Python version, and other tools you might need
build:
os: ubuntu-24.04
tools:
python: "3.13"
# Build documentation in the "docs/" directory with Sphinx
sphinx:
configuration: docs/source/conf.py
# Optionally, but recommended,
# declare the Python requirements required to build your documentation
# See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html
python:
install:
- requirements: docs/requirements.txt
================================================
FILE: LICENSE
================================================
TENCENT HUNYUAN 3D 2.0 COMMUNITY LICENSE AGREEMENT
Tencent Hunyuan 3D 2.0 Release Date: January 21, 2025
THIS LICENSE AGREEMENT DOES NOT APPLY IN THE EUROPEAN UNION, UNITED KINGDOM AND SOUTH KOREA AND IS EXPRESSLY LIMITED TO THE TERRITORY, AS DEFINED BELOW.
By clicking to agree or by using, reproducing, modifying, distributing, performing or displaying any portion or element of the Tencent Hunyuan 3D 2.0 Works, including via any Hosted Service, You will be deemed to have recognized and accepted the content of this Agreement, which is effective immediately.
1. DEFINITIONS.
a. “Acceptable Use Policy” shall mean the policy made available by Tencent as set forth in the Exhibit A.
b. “Agreement” shall mean the terms and conditions for use, reproduction, distribution, modification, performance and displaying of Tencent Hunyuan 3D 2.0 Works or any portion or element thereof set forth herein.
c. “Documentation” shall mean the specifications, manuals and documentation for Tencent Hunyuan 3D 2.0 made publicly available by Tencent.
d. “Hosted Service” shall mean a hosted service offered via an application programming interface (API), web access, or any other electronic or remote means.
e. “Licensee,” “You” or “Your” shall mean a natural person or legal entity exercising the rights granted by this Agreement and/or using the Tencent Hunyuan 3D 2.0 Works for any purpose and in any field of use.
f. “Materials” shall mean, collectively, Tencent’s proprietary Tencent Hunyuan 3D 2.0 and Documentation (and any portion thereof) as made available by Tencent under this Agreement.
g. “Model Derivatives” shall mean all: (i) modifications to Tencent Hunyuan 3D 2.0 or any Model Derivative of Tencent Hunyuan 3D 2.0; (ii) works based on Tencent Hunyuan 3D 2.0 or any Model Derivative of Tencent Hunyuan 3D 2.0; or (iii) any other machine learning model which is created by transfer of patterns of the weights, parameters, operations, or Output of Tencent Hunyuan 3D 2.0 or any Model Derivative of Tencent Hunyuan 3D 2.0, to that model in order to cause that model to perform similarly to Tencent Hunyuan 3D 2.0 or a Model Derivative of Tencent Hunyuan 3D 2.0, including distillation methods, methods that use intermediate data representations, or methods based on the generation of synthetic data Outputs by Tencent Hunyuan 3D 2.0 or a Model Derivative of Tencent Hunyuan 3D 2.0 for training that model. For clarity, Outputs by themselves are not deemed Model Derivatives.
h. “Output” shall mean the information and/or content output of Tencent Hunyuan 3D 2.0 or a Model Derivative that results from operating or otherwise using Tencent Hunyuan 3D 2.0 or a Model Derivative, including via a Hosted Service.
i. “Tencent,” “We” or “Us” shall mean the applicable entity or entities in the Tencent corporate family that own(s) intellectual property or other rights embodied in or utilized by the Materials.
* Section 1.i of the previous Hunyuan License Agreement defined “Tencent,” “We” or “Us” to mean THL A29 Limited, and the copyright notices pertaining to the Materials were previously in the name of “THL A29 Limited.” That entity has now been de-registered. You should treat all previously distributed copies of the Materials as if Section 1.i of the Agreement defined “Tencent,” “We” or “Us” to mean “the applicable entity or entities in the Tencent corporate family that own(s) intellectual property or other rights embodied in or utilized by the Materials,” and treat the copyright notice(s) accompanying the Materials as if they were in the name of “Tencent.” When providing a copy of any Agreement to Third Party recipients of the Tencent Hunyuan Works or products or services using them, as required by Section 3.a of the Agreement, you should provide the most current version of the Agreement, including the change of definition in Section 1.i of the Agreement.
j. “Tencent Hunyuan 3D 2.0” shall mean the 3D generation models and their software and algorithms, including trained model weights, parameters (including optimizer states), machine-learning model code, inference-enabling code, training-enabling code, fine-tuning enabling code and other elements of the foregoing made publicly available by Us at https://github.com/Tencent/Hunyuan3D-2.
k. “Tencent Hunyuan 3D 2.0 Works” shall mean: (i) the Materials; (ii) Model Derivatives; and (iii) all derivative works thereof.
l. “Territory” shall mean the worldwide territory, excluding the territory of the European Union, United Kingdom and South Korea.
m. “Third Party” or “Third Parties” shall mean individuals or legal entities that are not under common control with Us or You.
n. “including” shall mean including but not limited to.
2. GRANT OF RIGHTS.
We grant You, for the Territory only, a non-exclusive, non-transferable and royalty-free limited license under Tencent’s intellectual property or other rights owned by Us embodied in or utilized by the Materials to use, reproduce, distribute, create derivative works of (including Model Derivatives), and make modifications to the Materials, only in accordance with the terms of this Agreement and the Acceptable Use Policy, and You must not violate (or encourage or permit anyone else to violate) any term of this Agreement or the Acceptable Use Policy.
3. DISTRIBUTION.
You may, subject to Your compliance with this Agreement, distribute or make available to Third Parties the Tencent Hunyuan 3D 2.0 Works, exclusively in the Territory, provided that You meet all of the following conditions:
a. You must provide all such Third Party recipients of the Tencent Hunyuan 3D 2.0 Works or products or services using them a copy of this Agreement;
b. You must cause any modified files to carry prominent notices stating that You changed the files;
c. You are encouraged to: (i) publish at least one technology introduction blogpost or one public statement expressing Your experience of using the Tencent Hunyuan 3D 2.0 Works; and (ii) mark the products or services developed by using the Tencent Hunyuan 3D 2.0 Works to indicate that the product/service is “Powered by Tencent Hunyuan”; and
d. All distributions to Third Parties (other than through a Hosted Service) must be accompanied by a “Notice” text file that contains the following notice: “Tencent Hunyuan 3D 2.0 is licensed under the Tencent Hunyuan 3D 2.0 Community License Agreement, Copyright © 2025 Tencent. All Rights Reserved. The trademark rights of “Tencent Hunyuan” are owned by Tencent or its affiliate.”
You may add Your own copyright statement to Your modifications and, except as set forth in this Section and in Section 5, may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Model Derivatives as a whole, provided Your use, reproduction, modification, distribution, performance and display of the work otherwise complies with the terms and conditions of this Agreement (including as regards the Territory). If You receive Tencent Hunyuan 3D 2.0 Works from a Licensee as part of an integrated end user product, then this Section 3 of this Agreement will not apply to You.
e. In the event that You use, integrate, implement, or otherwise deploy the Tencent Hunyuan Works, in whole or in part, to provide, enable, or support any service, product, or functionality to third parties, You shall clearly, accurately, and prominently disclose to all end users the full legal name and entity of the actual provider of such service, product, or functionality. You shall expressly and conspicuously state that Tencent is not affiliated with, associated with, sponsoring, or endorsing any such service, product, or functionality. You shall not use or display any name, logo, trademark, trade name, or other indicia of Tencent in any manner that could be construed as, or be likely to create, confusion, deception, or a false impression regarding any relationship, affiliation, sponsorship, or endorsement by Tencent.
4. ADDITIONAL COMMERCIAL TERMS.
If, on the Tencent Hunyuan 3D 2.0 version release date, the monthly active users of all products or services made available by or for Licensee is greater than 1 million monthly active users in the preceding calendar month, You must request a license from Tencent, which Tencent may grant to You in its sole discretion, and You are not authorized to exercise any of the rights under this Agreement unless or until Tencent otherwise expressly grants You such rights.
Subject to Tencent's written approval, you may request a license for the use of Tencent Hunyuan 3D 2.0 by submitting the following information to hunyuan3d@tencent.com:
a. Your company’s name and associated business sector that plans to use Tencent Hunyuan 3D 2.0.
b. Your intended use case and the purpose of using Tencent Hunyuan 3D 2.0.
5. RULES OF USE.
a. Your use of the Tencent Hunyuan 3D 2.0 Works must comply with applicable laws and regulations (including trade compliance laws and regulations) and adhere to the Acceptable Use Policy for the Tencent Hunyuan 3D 2.0 Works, which is hereby incorporated by reference into this Agreement. You must include the use restrictions referenced in these Sections 5(a) and 5(b) as an enforceable provision in any agreement (e.g., license agreement, terms of use, etc.) governing the use and/or distribution of Tencent Hunyuan 3D 2.0 Works and You must provide notice to subsequent users to whom You distribute that Tencent Hunyuan 3D 2.0 Works are subject to the use restrictions in these Sections 5(a) and 5(b).
b. You must not use the Tencent Hunyuan 3D 2.0 Works or any Output or results of the Tencent Hunyuan 3D 2.0 Works to improve any other AI model (other than Tencent Hunyuan 3D 2.0 or Model Derivatives thereof).
c. You must not use, reproduce, modify, distribute, or display the Tencent Hunyuan 3D 2.0 Works, Output or results of the Tencent Hunyuan 3D 2.0 Works outside the Territory. Any such use outside the Territory is unlicensed and unauthorized under this Agreement.
6. INTELLECTUAL PROPERTY.
a. Subject to Tencent’s ownership of Tencent Hunyuan 3D 2.0 Works made by or for Tencent and intellectual property rights therein, conditioned upon Your compliance with the terms and conditions of this Agreement, as between You and Tencent, You will be the owner of any derivative works and modifications of the Materials and any Model Derivatives that are made by or for You.
b. No trademark licenses are granted under this Agreement, and in connection with the Tencent Hunyuan 3D 2.0 Works, Licensee may not use any name or mark owned by or associated with Tencent or any of its affiliates, except as required for reasonable and customary use in describing and distributing the Tencent Hunyuan 3D 2.0 Works. Tencent hereby grants You a license to use “Tencent Hunyuan” (the “Mark”) in the Territory solely as required to comply with the provisions of Section 3(c), provided that You comply with any applicable laws related to trademark protection. All goodwill arising out of Your use of the Mark will inure to the benefit of Tencent.
c. If You commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against Us or any person or entity alleging that the Materials or any Output, or any portion of any of the foregoing, infringe any intellectual property or other right owned or licensable by You, then all licenses granted to You under this Agreement shall terminate as of the date such lawsuit or other proceeding is filed. You will defend, indemnify and hold harmless Us from and against any claim by any Third Party arising out of or related to Your or the Third Party’s use or distribution of the Tencent Hunyuan 3D 2.0 Works.
d. Tencent claims no rights in Outputs You generate. You and Your users are solely responsible for Outputs and their subsequent uses.
7. DISCLAIMERS OF WARRANTY AND LIMITATIONS OF LIABILITY.
a. We are not obligated to support, update, provide training for, or develop any further version of the Tencent Hunyuan 3D 2.0 Works or to grant any license thereto.
b. UNLESS AND ONLY TO THE EXTENT REQUIRED BY APPLICABLE LAW, THE TENCENT HUNYUAN 3D 2.0 WORKS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED “AS IS” WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES OF ANY KIND INCLUDING ANY WARRANTIES OF TITLE, MERCHANTABILITY, NONINFRINGEMENT, COURSE OF DEALING, USAGE OF TRADE, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING, REPRODUCING, MODIFYING, PERFORMING, DISPLAYING OR DISTRIBUTING ANY OF THE TENCENT HUNYUAN 3D 2.0 WORKS OR OUTPUTS AND ASSUME ANY AND ALL RISKS ASSOCIATED WITH YOUR OR A THIRD PARTY’S USE OR DISTRIBUTION OF ANY OF THE TENCENT HUNYUAN 3D 2.0 WORKS OR OUTPUTS AND YOUR EXERCISE OF RIGHTS AND PERMISSIONS UNDER THIS AGREEMENT.
c. TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL TENCENT OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, CONSEQUENTIAL OR PUNITIVE DAMAGES, OR LOST PROFITS OF ANY KIND ARISING FROM THIS AGREEMENT OR RELATED TO ANY OF THE TENCENT HUNYUAN 3D 2.0 WORKS OR OUTPUTS, EVEN IF TENCENT OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
8. SURVIVAL AND TERMINATION.
a. The term of this Agreement shall commence upon Your acceptance of this Agreement or access to the Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein.
b. We may terminate this Agreement if You breach any of the terms or conditions of this Agreement. Upon termination of this Agreement, You must promptly delete and cease use of the Tencent Hunyuan 3D 2.0 Works. Sections 6(a), 6(c), 7 and 9 shall survive the termination of this Agreement.
9. GOVERNING LAW AND JURISDICTION.
a. This Agreement and any dispute arising out of or relating to it will be governed by the laws of the Hong Kong Special Administrative Region of the People’s Republic of China, without regard to conflict of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement.
b. Exclusive jurisdiction and venue for any dispute arising out of or relating to this Agreement will be a court of competent jurisdiction in the Hong Kong Special Administrative Region of the People’s Republic of China, and Tencent and Licensee consent to the exclusive jurisdiction of such court with respect to any such dispute.
EXHIBIT A
ACCEPTABLE USE POLICY
Tencent reserves the right to update this Acceptable Use Policy from time to time.
Last modified: November 5, 2024
Tencent endeavors to promote safe and fair use of its tools and features, including Tencent Hunyuan 3D 2.0. You agree not to use Tencent Hunyuan 3D 2.0 or Model Derivatives:
1. Outside the Territory;
2. In any way that violates any applicable national, federal, state, local, international or any other law or regulation;
3. To harm Yourself or others;
4. To repurpose or distribute output from Tencent Hunyuan 3D 2.0 or any Model Derivatives to harm Yourself or others;
5. To override or circumvent the safety guardrails and safeguards We have put in place;
6. For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
7. To generate or disseminate verifiably false information and/or content with the purpose of harming others or influencing elections;
8. To generate or facilitate false online engagement, including fake reviews and other means of fake online engagement;
9. To intentionally defame, disparage or otherwise harass others;
10. To generate and/or disseminate malware (including ransomware) or any other content to be used for the purpose of harming electronic systems;
11. To generate or disseminate personal identifiable information with the purpose of harming others;
12. To generate or disseminate information (including images, code, posts, articles), and place the information in any public context (including –through the use of bot generated tweets), without expressly and conspicuously identifying that the information and/or content is machine generated;
13. To impersonate another individual without consent, authorization, or legal right;
14. To make high-stakes automated decisions in domains that affect an individual’s safety, rights or wellbeing (e.g., law enforcement, migration, medicine/health, management of critical infrastructure, safety components of products, essential services, credit, employment, housing, education, social scoring, or insurance);
15. In a manner that violates or disrespects the social ethics and moral standards of other countries or regions;
16. To perform, facilitate, threaten, incite, plan, promote or encourage violent extremism or terrorism;
17. For any use intended to discriminate against or harm individuals or groups based on protected characteristics or categories, online or offline social behavior or known or predicted personal or personality characteristics;
18. To intentionally exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
19. For military purposes;
20. To engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or other professional practices.
================================================
FILE: NOTICE
================================================
Usage and Legal Notices:
Tencent is pleased to support the open source community by making Hunyuan 3D 2.0 available.
Copyright (C) 2025 Tencent. All rights reserved. The below software and/or models in this distribution may have been modified by Tencent ("Tencent Modifications"). All Tencent Modifications are Copyright (C) Tencent.
Hunyuan 3D 2.0 is licensed under the TENCENT HUNYUAN 3D 2.0 COMMUNITY LICENSE AGREEMENT except for the third-party components listed below, which is licensed under different terms. Hunyuan 3D 2.0 does not impose any additional limitations beyond what is outlined in the respective licenses of these third-party components. Users must comply with all terms and conditions of original licenses of these third-party components and must ensure that the usage of the third party components adheres to all relevant laws and regulations.
For avoidance of doubts, Hunyuan 3D 2.0 means inference-enabling code, parameters, and weights of this Model only, which are made publicly available by Tencent in accordance with TENCENT HUNYUAN 3D 2.0 COMMUNITY LICENSE AGREEMENT.
Other dependencies and licenses:
Open Source Model Licensed under the MIT and CreativeML Open RAIL++-M License:
--------------------------------------------------------------------
1. Stable Diffusion
Copyright (c) 2022 Stability AI
Terms of the MIT and CreativeML Open RAIL++-M License:
--------------------------------------------------------------------
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.
CreativeML Open RAIL++-M License
dated November 24, 2022
Section I: PREAMBLE
Multimodal generative models are being widely adopted and used, and have the potential to transform the way artists, among other individuals, conceive and benefit from AI or ML technologies as a tool for content creation.
Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations.
In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the Model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for art and content generation.
Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this License aims to strike a balance between both in order to enable responsible open-science in the field of AI.
This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model.
NOW THEREFORE, You and Licensor agree as follows:
1. Definitions
- "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.
- "Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License.
- "Output" means the results of operating a Model as embodied in informational content resulting therefrom.
- "Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material.
- "Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model.
- "Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any.
- "Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access.
- "Licensor" means the copyright owner or entity authorized by the copyright owner that is granting the License, including the persons or entities that may have rights in the Model and/or distributing the Model.
- "You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, image generator.
- "Third Parties" means individuals or legal entities that are not under common control with Licensor or You.
- "Contribution" means any work of authorship, including the original version of the Model and any modifications or additions to that Model or Derivatives of the Model thereof, that is intentionally submitted to Licensor for inclusion in the Model by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
- "Contributor" means Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model.
Section II: INTELLECTUAL PROPERTY RIGHTS
Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in Section III.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model.
3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Model to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model and/or Complementary Material or a Contribution incorporated within the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or Work shall terminate as of the date such litigation is asserted or filed.
Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
4. Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions:
Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material.
You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License;
You must cause any modified files to carry prominent notices stating that You changed the files;
You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. - for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License.
5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5).
6. The Output You Generate. Except as set forth herein, Licensor claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License.
Section IV: OTHER PROVISIONS
7. Updates and Runtime Restrictions. To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License.
8. Trademarks and related. Nothing in this License permits You to make use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors.
9. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model and the Complementary Material (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License.
10. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Model and the Complementary Material (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
11. Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
12. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
END OF TERMS AND CONDITIONS
Attachment A
Use Restrictions
You agree not to use the Model or Derivatives of the Model:
- In any way that violates any applicable national, federal, state, local or international law or regulation;
- For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
- To generate or disseminate verifiably false information and/or content with the purpose of harming others;
- To generate or disseminate personal identifiable information that can be used to harm an individual;
- To defame, disparage or otherwise harass others;
- For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;
- For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;
- To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
- For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories;
- To provide medical advice and medical results interpretation;
- To generate or disseminate information for the purpose to be used for administration of justice, law enforcement, immigration or asylum processes, such as predicting an individual will commit fraud/crime commitment (e.g. by text profiling, drawing causal relationships between assertions made in documents, indiscriminate and arbitrarily-targeted use).
Open Source Model Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT and Other Licenses of the Third-Party Components therein:
--------------------------------------------------------------------
1. HunyuanDiT
Copyright (C) 2024 Tencent. All rights reserved.
Terms of the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT:
--------------------------------------------------------------------
TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT
Tencent Hunyuan Release Date: 2024/5/14
By clicking to agree or by using, reproducing, modifying, distributing, performing or displaying any portion or element of the Tencent Hunyuan Works, including via any Hosted Service, You will be deemed to have recognized and accepted the content of this Agreement, which is effective immediately.
1. DEFINITIONS.
a. “Acceptable Use Policy” shall mean the policy made available by Tencent as set forth in the Exhibit A.
b. “Agreement” shall mean the terms and conditions for use, reproduction, distribution, modification, performance and displaying of the Hunyuan Works or any portion or element thereof set forth herein.
c. “Documentation” shall mean the specifications, manuals and documentation for Tencent Hunyuan made publicly available by Tencent.
d. “Hosted Service” shall mean a hosted service offered via an application programming interface (API), web access, or any other electronic or remote means.
e. “Licensee,” “You” or “Your” shall mean a natural person or legal entity exercising the rights granted by this Agreement and/or using the Tencent Hunyuan Works for any purpose and in any field of use.
f. “Materials” shall mean, collectively, Tencent’s proprietary Tencent Hunyuan and Documentation (and any portion thereof) as made available by Tencent under this Agreement.
g. “Model Derivatives” shall mean all: (i) modifications to Tencent Hunyuan or any Model Derivative of Tencent Hunyuan; (ii) works based on Tencent Hunyuan or any Model Derivative of Tencent Hunyuan; or (iii) any other machine learning model which is created by transfer of patterns of the weights, parameters, operations, or Output of Tencent Hunyuan or any Model Derivative of Tencent Hunyuan, to that model in order to cause that model to perform similarly to Tencent Hunyuan or a Model Derivative of Tencent Hunyuan, including distillation methods, methods that use intermediate data representations, or methods based on the generation of synthetic data Outputs by Tencent Hunyuan or a Model Derivative of Tencent Hunyuan for training that model. For clarity, Outputs by themselves are not deemed Model Derivatives.
h. “Output” shall mean the information and/or content output of Tencent Hunyuan or a Model Derivative that results from operating or otherwise using Tencent Hunyuan or a Model Derivative, including via a Hosted Service.
i. “Tencent,” “We” or “Us” shall mean Tencent.
j. “Tencent Hunyuan” shall mean the large language models, image/video/audio/3D generation models, and multimodal large language models and their software and algorithms, including trained model weights, parameters (including optimizer states), machine-learning model code, inference-enabling code, training-enabling code, fine-tuning enabling code and other elements of the foregoing made publicly available by Us at https://huggingface.co/Tencent-Hunyuan/HunyuanDiT and https://github.com/Tencent/HunyuanDiT .
k. “Tencent Hunyuan Works” shall mean: (i) the Materials; (ii) Model Derivatives; and (iii) all derivative works thereof.
l. “Third Party” or “Third Parties” shall mean individuals or legal entities that are not under common control with Us or You.
m. “including” shall mean including but not limited to.
2. GRANT OF RIGHTS.
We grant You a non-exclusive, worldwide, non-transferable and royalty-free limited license under Tencent’s intellectual property or other rights owned by Us embodied in or utilized by the Materials to use, reproduce, distribute, create derivative works of (including Model Derivatives), and make modifications to the Materials, only in accordance with the terms of this Agreement and the Acceptable Use Policy, and You must not violate (or encourage or permit anyone else to violate) any term of this Agreement or the Acceptable Use Policy.
3. DISTRIBUTION.
You may, subject to Your compliance with this Agreement, distribute or make available to Third Parties the Tencent Hunyuan Works, provided that You meet all of the following conditions:
a. You must provide all such Third Party recipients of the Tencent Hunyuan Works or products or services using them a copy of this Agreement;
b. You must cause any modified files to carry prominent notices stating that You changed the files;
c. You are encouraged to: (i) publish at least one technology introduction blogpost or one public statement expressing Your experience of using the Tencent Hunyuan Works; and (ii) mark the products or services developed by using the Tencent Hunyuan Works to indicate that the product/service is “Powered by Tencent Hunyuan”; and
d. All distributions to Third Parties (other than through a Hosted Service) must be accompanied by a “Notice” text file that contains the following notice: “Tencent Hunyuan is licensed under the Tencent Hunyuan Community License Agreement, Copyright © 2024 Tencent. All Rights Reserved. The trademark rights of “Tencent Hunyuan” are owned by Tencent or its affiliate.”
You may add Your own copyright statement to Your modifications and, except as set forth in this Section and in Section 5, may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Model Derivatives as a whole, provided Your use, reproduction, modification, distribution, performance and display of the work otherwise complies with the terms and conditions of this Agreement. If You receive Tencent Hunyuan Works from a Licensee as part of an integrated end user product, then this Section 3 of this Agreement will not apply to You.
4. ADDITIONAL COMMERCIAL TERMS.
If, on the Tencent Hunyuan version release date, the monthly active users of all products or services made available by or for Licensee is greater than 100 million monthly active users in the preceding calendar month, You must request a license from Tencent, which Tencent may grant to You in its sole discretion, and You are not authorized to exercise any of the rights under this Agreement unless or until Tencent otherwise expressly grants You such rights.
5. RULES OF USE.
a. Your use of the Tencent Hunyuan Works must comply with applicable laws and regulations (including trade compliance laws and regulations) and adhere to the Acceptable Use Policy for the Tencent Hunyuan Works, which is hereby incorporated by reference into this Agreement. You must include the use restrictions referenced in these Sections 5(a) and 5(b) as an enforceable provision in any agreement (e.g., license agreement, terms of use, etc.) governing the use and/or distribution of Tencent Hunyuan Works and You must provide notice to subsequent users to whom You distribute that Tencent Hunyuan Works are subject to the use restrictions in these Sections 5(a) and 5(b).
b. You must not use the Tencent Hunyuan Works or any Output or results of the Tencent Hunyuan Works to improve any other large language model (other than Tencent Hunyuan or Model Derivatives thereof).
6. INTELLECTUAL PROPERTY.
a. Subject to Tencent’s ownership of Tencent Hunyuan Works made by or for Tencent and intellectual property rights therein, conditioned upon Your compliance with the terms and conditions of this Agreement, as between You and Tencent, You will be the owner of any derivative works and modifications of the Materials and any Model Derivatives that are made by or for You.
b. No trademark licenses are granted under this Agreement, and in connection with the Tencent Hunyuan Works, Licensee may not use any name or mark owned by or associated with Tencent or any of its affiliates, except as required for reasonable and customary use in describing and distributing the Tencent Hunyuan Works. Tencent hereby grants You a license to use “Tencent Hunyuan” (the “Mark”) solely as required to comply with the provisions of Section 3(c), provided that You comply with any applicable laws related to trademark protection. All goodwill arising out of Your use of the Mark will inure to the benefit of Tencent.
c. If You commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against Us or any person or entity alleging that the Materials or any Output, or any portion of any of the foregoing, infringe any intellectual property or other right owned or licensable by You, then all licenses granted to You under this Agreement shall terminate as of the date such lawsuit or other proceeding is filed. You will defend, indemnify and hold harmless Us from and against any claim by any Third Party arising out of or related to Your or the Third Party’s use or distribution of the Tencent Hunyuan Works.
d. Tencent claims no rights in Outputs You generate. You and Your users are solely responsible for Outputs and their subsequent uses.
7. DISCLAIMERS OF WARRANTY AND LIMITATIONS OF LIABILITY.
a. We are not obligated to support, update, provide training for, or develop any further version of the Tencent Hunyuan Works or to grant any license thereto.
b. UNLESS AND ONLY TO THE EXTENT REQUIRED BY APPLICABLE LAW, THE TENCENT HUNYUAN WORKS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED “AS IS” WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES OF ANY KIND INCLUDING ANY WARRANTIES OF TITLE, MERCHANTABILITY, NONINFRINGEMENT, COURSE OF DEALING, USAGE OF TRADE, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING, REPRODUCING, MODIFYING, PERFORMING, DISPLAYING OR DISTRIBUTING ANY OF THE TENCENT HUNYUAN WORKS OR OUTPUTS AND ASSUME ANY AND ALL RISKS ASSOCIATED WITH YOUR OR A THIRD PARTY’S USE OR DISTRIBUTION OF ANY OF THE TENCENT HUNYUAN WORKS OR OUTPUTS AND YOUR EXERCISE OF RIGHTS AND PERMISSIONS UNDER THIS AGREEMENT.
c. TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL TENCENT OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, CONSEQUENTIAL OR PUNITIVE DAMAGES, OR LOST PROFITS OF ANY KIND ARISING FROM THIS AGREEMENT OR RELATED TO ANY OF THE TENCENT HUNYUAN WORKS OR OUTPUTS, EVEN IF TENCENT OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
8. SURVIVAL AND TERMINATION.
a. The term of this Agreement shall commence upon Your acceptance of this Agreement or access to the Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein.
b. We may terminate this Agreement if You breach any of the terms or conditions of this Agreement. Upon termination of this Agreement, You must promptly delete and cease use of the Tencent Hunyuan Works. Sections 6(a), 6(c), 7 and 9 shall survive the termination of this Agreement.
9. GOVERNING LAW AND JURISDICTION.
a. This Agreement and any dispute arising out of or relating to it will be governed by the laws of the Hong Kong Special Administrative Region of the People’s Republic of China, without regard to conflict of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement.
b. Exclusive jurisdiction and venue for any dispute arising out of or relating to this Agreement will be a court of competent jurisdiction in the Hong Kong Special Administrative Region of the People’s Republic of China, and Tencent and Licensee consent to the exclusive jurisdiction of such court with respect to any such dispute.
EXHIBIT A
ACCEPTABLE USE POLICY
Tencent reserves the right to update this Acceptable Use Policy from time to time.
Last modified: 2024/5/14
Tencent endeavors to promote safe and fair use of its tools and features, including Tencent Hunyuan. You agree not to use Tencent Hunyuan or Model Derivatives:
1. In any way that violates any applicable national, federal, state, local, international or any other law or regulation;
2. To harm Yourself or others;
3. To repurpose or distribute output from Tencent Hunyuan or any Model Derivatives to harm Yourself or others;
4. To override or circumvent the safety guardrails and safeguards We have put in place;
5. For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
6. To generate or disseminate verifiably false information and/or content with the purpose of harming others or influencing elections;
7. To generate or facilitate false online engagement, including fake reviews and other means of fake online engagement;
8. To intentionally defame, disparage or otherwise harass others;
9. To generate and/or disseminate malware (including ransomware) or any other content to be used for the purpose of harming electronic systems;
10. To generate or disseminate personal identifiable information with the purpose of harming others;
11. To generate or disseminate information (including images, code, posts, articles), and place the information in any public context (including –through the use of bot generated tweets), without expressly and conspicuously identifying that the information and/or content is machine generated;
12. To impersonate another individual without consent, authorization, or legal right;
13. To make high-stakes automated decisions in domains that affect an individual’s safety, rights or wellbeing (e.g., law enforcement, migration, medicine/health, management of critical infrastructure, safety components of products, essential services, credit, employment, housing, education, social scoring, or insurance);
14. In a manner that violates or disrespects the social ethics and moral standards of other countries or regions;
15. To perform, facilitate, threaten, incite, plan, promote or encourage violent extremism or terrorism;
16. For any use intended to discriminate against or harm individuals or groups based on protected characteristics or categories, online or offline social behavior or known or predicted personal or personality characteristics;
17. To intentionally exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
18. For military purposes;
19. To engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or other professional practices.
For the license of other third party components, please refer to the following URL:
https://huggingface.co/Tencent-Hunyuan/HunyuanDiT/blob/main/Notice
--------------------------------------------------------------------
This Model also incorporates insights from Flux's neural network architechtures (https://github.com/black-forest-labs/flux?tab=readme-ov-file). Credits are given to the orginal authors.
================================================
FILE: README.md
================================================
[中文阅读](README_zh_cn.md)
[日本語で読む](README_ja_jp.md)
<p align="center">
<img src="https://github.com/user-attachments/assets/efb402a1-0b09-41e0-a6cb-259d442e76aa">
</p>
<div align="center">
<a href=https://3d.hunyuan.tencent.com target="_blank"><img src=https://img.shields.io/badge/Official%20Site-333399.svg?logo=homepage height=22px></a>
<a href=https://huggingface.co/spaces/tencent/Hunyuan3D-2 target="_blank"><img src=https://img.shields.io/badge/%F0%9F%A4%97%20Demo-276cb4.svg height=22px></a>
<a href=https://huggingface.co/tencent/Hunyuan3D-2 target="_blank"><img src=https://img.shields.io/badge/%F0%9F%A4%97%20Models-d96902.svg height=22px></a>
<a href=https://3d-models.hunyuan.tencent.com/ target="_blank"><img src= https://img.shields.io/badge/Page-bb8a2e.svg?logo=github height=22px></a>
<a href=https://discord.gg/dNBrdrGGMa target="_blank"><img src= https://img.shields.io/badge/Discord-white.svg?logo=discord height=22px></a>
<a href=https://arxiv.org/abs/2501.12202 target="_blank"><img src=https://img.shields.io/badge/Report-b5212f.svg?logo=arxiv height=22px></a>
<a href=https://x.com/TencentHunyuan target="_blank"><img src=https://img.shields.io/badge/Hunyuan-black.svg?logo=x height=22px></a>
<a href="#community-resources" target="_blank"><img src=https://img.shields.io/badge/Community-lavender.svg?logo=homeassistantcommunitystore height=22px></a>
</div>
[//]: # ( <a href=# target="_blank"><img src=https://img.shields.io/badge/Report-b5212f.svg?logo=arxiv height=22px></a>)
[//]: # ( <a href=# target="_blank"><img src= https://img.shields.io/badge/Colab-8f2628.svg?logo=googlecolab height=22px></a>)
[//]: # ( <a href="#"><img alt="PyPI - Downloads" src="https://img.shields.io/pypi/v/mulankit?logo=pypi" height=22px></a>)
<br>
<p align="center">
“ Living out everyone’s imagination on creating and manipulating 3D assets.”
</p>
https://github.com/user-attachments/assets/a2cbc5b8-be22-49d7-b1c3-7aa2b20ba460
## 🔥 News
- July 26, 2025: 🤗 We release the first open-source, simulation-capable, immersive 3D world generation model, [HunyuanWorld-1.0](https://github.com/Tencent-Hunyuan/HunyuanWorld-1.0)!
- June 23, 2025: 📄 Release the system technical report of [Hunyuan3D 2.5](https://arxiv.org/abs/2506.16504).
- June 13, 2025: 🤗 Release [Hunyuan3D-2.1](https://github.com/Tencent-Hunyuan/Hunyuan3D-2.1), fully open-sourced with new PBR model, VAE encoder, and all training code.
- Apr 1, 2025: 🤗 Release turbo paint model [Hunyuan3D-Paint-v2-0-Turbo](https://huggingface.co/tencent/Hunyuan3D-2/tree/main/hunyuan3d-paint-v2-0-turbo), and multiview texture generation pipeline, try it [here](examples/fast_texture_gen_multiview.py)! Stay tuned for our new texture generation model [RomanTex](https://github.com/oakshy/RomanTex) and PBR material generation [MaterialMVP](https://github.com/ZebinHe/MaterialMVP/)!
- Mar 19, 2025: 🤗 Release turbo model [Hunyuan3D-2-Turbo](https://huggingface.co/tencent/Hunyuan3D-2/), [Hunyuan3D-2mini-Turbo](https://huggingface.co/tencent/Hunyuan3D-2mini/) and [FlashVDM](https://github.com/Tencent/FlashVDM).
- Mar 18, 2025: 🤗 Release multiview shape model [Hunyuan3D-2mv](https://huggingface.co/tencent/Hunyuan3D-2mv) and 0.6B
shape model [Hunyuan3D-2mini](https://huggingface.co/tencent/Hunyuan3D-2mini).
- Feb 14, 2025: 🛠️ Release texture enhancement module, please obtain high-definition textures
via [here](minimal_demo.py)!
- Feb 3, 2025: 🐎
Release [Hunyuan3D-DiT-v2-0-Fast](https://huggingface.co/tencent/Hunyuan3D-2/tree/main/hunyuan3d-dit-v2-0-fast), our
guidance distillation model that could half the dit inference time, see [here](minimal_demo.py) for usage.
- Jan 27, 2025: 🛠️ Release Blender addon for Hunyuan3D 2.0, Check it out [here](#blender-addon).
- Jan 23, 2025: 💬 We thank community members for
creating [Windows installation tool](https://github.com/YanWenKun/Hunyuan3D-2-WinPortable), ComfyUI support
with [ComfyUI-Hunyuan3DWrapper](https://github.com/kijai/ComfyUI-Hunyuan3DWrapper)
and [ComfyUI-3D-Pack](https://github.com/MrForExample/ComfyUI-3D-Pack) and other
awesome [extensions](#community-resources).
- Jan 21, 2025: 💬 Enjoy exciting 3D generation on our website [Hunyuan3D Studio](https://3d.hunyuan.tencent.com)!
- Jan 21, 2025: 🤗 Release inference code and pretrained models
of [Hunyuan3D 2.0](https://huggingface.co/tencent/Hunyuan3D-2). Please give it a try
via [huggingface space](https://huggingface.co/spaces/tencent/Hunyuan3D-2) and
our [official site](https://3d.hunyuan.tencent.com)!
> Join our **[Wechat](#)** and **[Discord](https://discord.gg/dNBrdrGGMa)** group to discuss and find help from us.
| Wechat Group | Xiaohongshu | X | Discord |
|--------------------------------------------------|-------------------------------------------------------|---------------------------------------------|---------------------------------------------------|
| <img src="assets/qrcode/wechat.png" height=140> | <img src="assets/qrcode/xiaohongshu.png" height=140> | <img src="assets/qrcode/x.png" height=140> | <img src="assets/qrcode/discord.png" height=140> |
## **Abstract**
We present Hunyuan3D 2.0, an advanced large-scale 3D synthesis system for generating high-resolution textured 3D assets.
This system includes two foundation components: a large-scale shape generation model - Hunyuan3D-DiT, and a large-scale
texture synthesis model - Hunyuan3D-Paint.
The shape generative model, built on a scalable flow-based diffusion transformer, aims to create geometry that properly
aligns with a given condition image, laying a solid foundation for downstream applications.
The texture synthesis model, benefiting from strong geometric and diffusion priors, produces high-resolution and vibrant
texture maps for either generated or hand-crafted meshes.
Furthermore, we build Hunyuan3D-Studio - a versatile, user-friendly production platform that simplifies the re-creation
process of 3D assets. It allows both professional and amateur users to manipulate or even animate their meshes
efficiently.
We systematically evaluate our models, showing that Hunyuan3D 2.0 outperforms previous state-of-the-art models,
including the open-source models and closed-source models in geometry details, condition alignment, texture quality, and
e.t.c.
<p align="center">
<img src="assets/images/system.jpg">
</p>
## ☯️ **Hunyuan3D 2.0**
### Architecture
Hunyuan3D 2.0 features a two-stage generation pipeline, starting with the creation of a bare mesh, followed by the
synthesis of a texture map for that mesh. This strategy is effective for decoupling the difficulties of shape and
texture generation and also provides flexibility for texturing either generated or handcrafted meshes.
<p align="left">
<img src="assets/images/arch.jpg">
</p>
### Performance
We have evaluated Hunyuan3D 2.0 with other open-source as well as close-source 3d-generation methods.
The numerical results indicate that Hunyuan3D 2.0 surpasses all baselines in the quality of generated textured 3D assets
and the condition following ability.
| Model | CMMD(⬇) | FID_CLIP(⬇) | FID(⬇) | CLIP-score(⬆) |
|-------------------------|-----------|-------------|-------------|---------------|
| Top Open-source Model1 | 3.591 | 54.639 | 289.287 | 0.787 |
| Top Close-source Model1 | 3.600 | 55.866 | 305.922 | 0.779 |
| Top Close-source Model2 | 3.368 | 49.744 | 294.628 | 0.806 |
| Top Close-source Model3 | 3.218 | 51.574 | 295.691 | 0.799 |
| Hunyuan3D 2.0 | **3.193** | **49.165** | **282.429** | **0.809** |
Generation results of Hunyuan3D 2.0:
<p align="left">
<img src="assets/images/e2e-1.gif" height=250>
<img src="assets/images/e2e-2.gif" height=250>
</p>
## 🎁 Models Zoo
It takes 6 GB VRAM for shape generation and 16 GB for shape and texture generation in total.
Hunyuan3D-2-1 Series
| Model | Description | Date | Size | Huggingface |
|----------------------|-------------------------------|------------|------|-----------------------------------------------------------------------------------------|
| Hunyuan3D-DiT-v2-1 | Mini Image to Shape Model | 2025-06-13 | 3.0B | [Download](https://huggingface.co/tencent/Hunyuan3D-2.1/tree/main/hunyuan3d-dit-v2-1) |
| Hunyuan3D-Paint-v2-1 | Texture Generation Model | 2025-06-13 | 1.3B | [Download](https://huggingface.co/tencent/Hunyuan3D-2.1/tree/main/hunyuan3d-paintpbr-v2-1) |
Hunyuan3D-2mini Series
| Model | Description | Date | Size | Huggingface |
|-----------------------------|-------------------------------|------------|------|--------------------------------------------------------------------------------------------------|
| Hunyuan3D-DiT-v2-mini-Turbo | Step Distillation Version | 2025-03-19 | 0.6B | [Download](https://huggingface.co/tencent/Hunyuan3D-2mini/tree/main/hunyuan3d-dit-v2-mini-turbo) |
| Hunyuan3D-DiT-v2-mini-Fast | Guidance Distillation Version | 2025-03-18 | 0.6B | [Download](https://huggingface.co/tencent/Hunyuan3D-2mini/tree/main/hunyuan3d-dit-v2-mini-fast) |
| Hunyuan3D-DiT-v2-mini | Mini Image to Shape Model | 2025-03-18 | 0.6B | [Download](https://huggingface.co/tencent/Hunyuan3D-2mini/tree/main/hunyuan3d-dit-v2-mini) |
Hunyuan3D-2mv Series
| Model | Description | Date | Size | Huggingface |
|---------------------------|--------------------------------|------------|------|----------------------------------------------------------------------------------------------|
| Hunyuan3D-DiT-v2-mv-Turbo | Step Distillation Version | 2025-03-19 | 1.1B | [Download](https://huggingface.co/tencent/Hunyuan3D-2mv/tree/main/hunyuan3d-dit-v2-mv-turbo) |
| Hunyuan3D-DiT-v2-mv-Fast | Guidance Distillation Version | 2025-03-18 | 1.1B | [Download](https://huggingface.co/tencent/Hunyuan3D-2mv/tree/main/hunyuan3d-dit-v2-mv-fast) |
| Hunyuan3D-DiT-v2-mv | Multiview Image to Shape Model | 2025-03-18 | 1.1B | [Download](https://huggingface.co/tencent/Hunyuan3D-2mv/tree/main/hunyuan3d-dit-v2-mv) |
Hunyuan3D-2 Series
| Model | Description | Date | Size | Huggingface |
|----------------------------|-----------------------------|------------|------|-------------------------------------------------------------------------------------------|
| Hunyuan3D-DiT-v2-0-Turbo | Step Distillation Model | 2025-03-19 | 1.1B | [Download](https://huggingface.co/tencent/Hunyuan3D-2/tree/main/hunyuan3d-dit-v2-0-turbo) |
| Hunyuan3D-DiT-v2-0-Fast | Guidance Distillation Model | 2025-02-03 | 1.1B | [Download](https://huggingface.co/tencent/Hunyuan3D-2/tree/main/hunyuan3d-dit-v2-0-fast) |
| Hunyuan3D-DiT-v2-0 | Image to Shape Model | 2025-01-21 | 1.1B | [Download](https://huggingface.co/tencent/Hunyuan3D-2/tree/main/hunyuan3d-dit-v2-0) |
| Hunyuan3D-Paint-v2-0 | Texture Generation Model | 2025-01-21 | 1.3B | [Download](https://huggingface.co/tencent/Hunyuan3D-2/tree/main/hunyuan3d-paint-v2-0) |
| Hunyuan3D-Paint-v2-0-Turbo | Distillation Texure Model | 2025-04-01 | 1.3B | [Download](https://huggingface.co/tencent/Hunyuan3D-2/tree/main/hunyuan3d-paint-v2-0-turbo) |
| Hunyuan3D-Delight-v2-0 | Image Delight Model | 2025-01-21 | 1.3B | [Download](https://huggingface.co/tencent/Hunyuan3D-2/tree/main/hunyuan3d-delight-v2-0) |
## 🤗 Get Started with Hunyuan3D 2.0
Hunyuan3D 2.0 supports Macos, Windows, Linux. You may follow the next steps to use Hunyuan3D 2.0 via:
- [Code](#code-usage)
- [Gradio App](#gradio-app)
- [API Server](#api-server)
- [Blender Addon](#blender-addon)
- [Official Site](#official-site)
### Install Requirements
Please install Pytorch via the [official](https://pytorch.org/) site. Then install the other requirements via
```bash
pip install -r requirements.txt
pip install -e .
# for texture
cd hy3dgen/texgen/custom_rasterizer
python3 setup.py install
cd ../../..
cd hy3dgen/texgen/differentiable_renderer
python3 setup.py install
```
### Code Usage
We designed a diffusers-like API to use our shape generation model - Hunyuan3D-DiT and texture synthesis model -
Hunyuan3D-Paint.
You could assess **Hunyuan3D-DiT** via:
```python
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained('tencent/Hunyuan3D-2')
mesh = pipeline(image='assets/demo.png')[0]
```
The output mesh is a [trimesh object](https://trimesh.org/trimesh.html), which you could save to glb/obj (or other
format) file.
For **Hunyuan3D-Paint**, do the following:
```python
from hy3dgen.texgen import Hunyuan3DPaintPipeline
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
# let's generate a mesh first
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained('tencent/Hunyuan3D-2')
mesh = pipeline(image='assets/demo.png')[0]
pipeline = Hunyuan3DPaintPipeline.from_pretrained('tencent/Hunyuan3D-2')
mesh = pipeline(mesh, image='assets/demo.png')
```
Please visit [examples](examples) folder for more advanced usage, such as **multiview image to 3D generation** and *
*texture generation
for handcrafted mesh**.
### Gradio App
You could also host a [Gradio](https://www.gradio.app/) App in your own computer via:
Standard Version
```bash
# Hunyuan3D-2mini
python3 gradio_app.py --model_path tencent/Hunyuan3D-2mini --subfolder hunyuan3d-dit-v2-mini --texgen_model_path tencent/Hunyuan3D-2 --low_vram_mode
# Hunyuan3D-2mv
python3 gradio_app.py --model_path tencent/Hunyuan3D-2mv --subfolder hunyuan3d-dit-v2-mv --texgen_model_path tencent/Hunyuan3D-2 --low_vram_mode
# Hunyuan3D-2
python3 gradio_app.py --model_path tencent/Hunyuan3D-2 --subfolder hunyuan3d-dit-v2-0 --texgen_model_path tencent/Hunyuan3D-2 --low_vram_mode
```
Turbo Version
```bash
# Hunyuan3D-2mini
python3 gradio_app.py --model_path tencent/Hunyuan3D-2mini --subfolder hunyuan3d-dit-v2-mini-turbo --texgen_model_path tencent/Hunyuan3D-2 --low_vram_mode --enable_flashvdm
# Hunyuan3D-2mv
python3 gradio_app.py --model_path tencent/Hunyuan3D-2mv --subfolder hunyuan3d-dit-v2-mv-turbo --texgen_model_path tencent/Hunyuan3D-2 --low_vram_mode --enable_flashvdm
# Hunyuan3D-2
python3 gradio_app.py --model_path tencent/Hunyuan3D-2 --subfolder hunyuan3d-dit-v2-0-turbo --texgen_model_path tencent/Hunyuan3D-2 --low_vram_mode --enable_flashvdm
```
### API Server
You could launch an API server locally, which you could post web request for Image/Text to 3D, Texturing existing mesh,
and e.t.c.
```bash
python api_server.py --host 0.0.0.0 --port 8080
```
A demo post request for image to 3D without texture.
```bash
img_b64_str=$(base64 -i assets/demo.png)
curl -X POST "http://localhost:8080/generate" \
-H "Content-Type: application/json" \
-d '{
"image": "'"$img_b64_str"'",
}' \
-o test2.glb
```
### Blender Addon
With an API server launched, you could also directly use Hunyuan3D 2.0 in your blender with
our [Blender Addon](blender_addon.py). Please follow our tutorial to install and use.
https://github.com/user-attachments/assets/8230bfb5-32b1-4e48-91f4-a977c54a4f3e
### Official Site
Don't forget to visit [Hunyuan3D](https://3d.hunyuan.tencent.com) for quick use, if you don't want to host yourself.
## 📑 Open-Source Plan
- [x] Inference Code
- [x] Model Checkpoints
- [x] Technical Report
- [x] ComfyUI
- [x] Finetuning
- [ ] TensorRT Version
## 🔗 BibTeX
If you found this repository helpful, please cite our reports:
```bibtex
@misc{lai2025hunyuan3d25highfidelity3d,
title={Hunyuan3D 2.5: Towards High-Fidelity 3D Assets Generation with Ultimate Details},
author={Tencent Hunyuan3D Team},
year={2025},
eprint={2506.16504},
archivePrefix={arXiv},
primaryClass={cs.CV},
url={https://arxiv.org/abs/2506.16504},
}
@misc{hunyuan3d22025tencent,
title={Hunyuan3D 2.0: Scaling Diffusion Models for High Resolution Textured 3D Assets Generation},
author={Tencent Hunyuan3D Team},
year={2025},
eprint={2501.12202},
archivePrefix={arXiv},
primaryClass={cs.CV}
}
@misc{yang2024hunyuan3d,
title={Hunyuan3D 1.0: A Unified Framework for Text-to-3D and Image-to-3D Generation},
author={Tencent Hunyuan3D Team},
year={2024},
eprint={2411.02293},
archivePrefix={arXiv},
primaryClass={cs.CV}
}
```
## Community Resources
Thanks for the contributions of community members, here we have these great extensions of Hunyuan3D 2.0:
- [ComfyUI-3D-Pack](https://github.com/MrForExample/ComfyUI-3D-Pack)
- [ComfyUI-Hunyuan3DWrapper](https://github.com/kijai/ComfyUI-Hunyuan3DWrapper)
- [Hunyuan3D-2-for-windows](https://github.com/sdbds/Hunyuan3D-2-for-windows)
- [📦 A bundle for running on Windows | 整合包](https://github.com/YanWenKun/Hunyuan3D-2-WinPortable)
- [Hunyuan3D-2GP](https://github.com/deepbeepmeep/Hunyuan3D-2GP)
- [Kaggle Notebook](https://github.com/darkon12/Hunyuan3D-2GP_Kaggle)
## Acknowledgements
We would like to thank the contributors to
the [Trellis](https://github.com/microsoft/TRELLIS), [DINOv2](https://github.com/facebookresearch/dinov2), [Stable Diffusion](https://github.com/Stability-AI/stablediffusion), [FLUX](https://github.com/black-forest-labs/flux), [diffusers](https://github.com/huggingface/diffusers), [HuggingFace](https://huggingface.co), [CraftsMan3D](https://github.com/wyysf-98/CraftsMan3D),
and [Michelangelo](https://github.com/NeuralCarver/Michelangelo/tree/main) repositories, for their open research and
exploration.
## Star History
<a href="https://star-history.com/#Tencent/Hunyuan3D-2&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Tencent/Hunyuan3D-2&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Tencent/Hunyuan3D-2&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Tencent/Hunyuan3D-2&type=Date" />
</picture>
</a>
================================================
FILE: README_ja_jp.md
================================================
[Read in English](README.md)
[中文阅读](README_zh_cn.md)
<p align="center">
<img src="./assets/images/teaser.jpg">
</p>
<div align="center">
<a href=https://3d.hunyuan.tencent.com target="_blank"><img src=https://img.shields.io/badge/Official%20Site-black.svg?logo=homepage height=22px></a>
<a href=https://huggingface.co/spaces/tencent/Hunyuan3D-2 target="_blank"><img src=https://img.shields.io/badge/%F0%9F%A4%97%20Demo-276cb4.svg height=22px></a>
<a href=https://huggingface.co/tencent/Hunyuan3D-2 target="_blank"><img src=https://img.shields.io/badge/%F0%9F%A4%97%20Models-d96902.svg height=22px></a>
<a href=https://3d-models.hunyuan.tencent.com/ target="_blank"><img src= https://img.shields.io/badge/Page-bb8a2e.svg?logo=github height=22px></a>
<a href=https://discord.gg/dNBrdrGGMa target="_blank"><img src= https://img.shields.io/badge/Discord-white.svg?logo=discord height=22px></a>
<a href=https://github.com/Tencent/Hunyuan3D-2/blob/main/assets/report/Tencent_Hunyuan3D_2_0.pdf target="_blank"><img src=https://img.shields.io/badge/Report-b5212f.svg?logo=arxiv height=22px></a>
</div>
[//]: # ( <a href=# target="_blank"><img src=https://img.shields.io/badge/Report-b5212f.svg?logo=arxiv height=22px></a>)
[//]: # ( <a href=# target="_blank"><img src= https://img.shields.io/badge/Colab-8f2628.svg?logo=googlecolab height=22px></a>)
[//]: # ( <a href="#"><img alt="PyPI - Downloads" src="https://img.shields.io/pypi/v/mulankit?logo=pypi" height=22px></a>)
<br>
<p align="center">
“ 3Dアセットの作成と操作において、すべての人の想像力を実現します。”
</p>
## 🔥 ニュース
- 2025年2月14日: 🛠️ テクスチャ強化モジュールをリリースしました。HD テクスチャ生成を [体験](minimal_demo.py) してください。
- 2025年1月21日: 💬 私たちのウェブサイト [Hunyuan3D Studio](https://3d.hunyuan.tencent.com) でエキサイティングな3D生成を楽しんでください!
- 2025年1月21日: 💬 [Hunyuan3D 2.0](https://huggingface.co/tencent/Hunyuan3D-2) の推論コードと事前学習モデルをリリースしました。
- 2025年1月21日: 💬 Hunyuan3D 2.0をリリースしました。 [huggingface space](https://huggingface.co/spaces/tencent/Hunyuan3D-2) や [公式サイト](https://3d.hunyuan.tencent.com) でお試しください!
## **概要**
Hunyuan3D 2.0は、高解像度のテクスチャ付き3Dアセットを生成するための高度な大規模3D合成システムです。
このシステムには、2つの基盤コンポーネントが含まれています:大規模形状生成モデル - Hunyuan3D-DiT、および大規模
テクスチャ合成モデル - Hunyuan3D-Paint。
形状生成モデルは、スケーラブルなフローに基づく拡散トランスフォーマーに基づいて構築されており、与えられた条件画像に適切に
一致するジオメトリを作成することを目的としており、下流のアプリケーションのための堅固な基盤を提供します。
テクスチャ合成モデルは、強力なジオメトリおよび拡散の事前知識を活用して、生成されたまたは手作りのメッシュのために高解像度で鮮やかな
テクスチャマップを生成します。
さらに、Hunyuan3D-Studioを構築しました。これは、3Dアセットの再作成プロセスを簡素化する多用途で使いやすい制作プラットフォームです。
プロフェッショナルおよびアマチュアユー���ーの両方がメッシュを効率的に操作したり、アニメーション化したりすることができます。
私たちはモデルを体系的に評価し、Hunyuan3D 2.0が以前の最先端モデルを上回ることを示しました。
オープンソースモデルとクローズドソースモデルの両方で、ジオメトリの詳細、条件の整合性、テクスチャの品質などの点で優れています。
<p align="center">
<img src="assets/images/system.jpg">
</p>
## ☯️ **Hunyuan3D 2.0**
### アーキテクチャ
Hunyuan3D 2.0は、ベアメッシュの作成から始まり、そのメッシュのテクスチャマップの合成に至る2段階の生成パイプライン���特徴としています。
この戦略は、形状とテクスチャの生成の難しさを分離するのに効果的であり、生成されたメッシュまたは手作りのメッシュのテクスチャリングに柔軟性を提供します。
<p align="left">
<img src="assets/images/arch.jpg">
</p>
### パフォーマンス
Hunyuan3D 2.0を他のオープンソースおよびクローズドソースの3D生成方法と比較して評価しました。
数値結果は、Hunyuan3D 2.0が生成されたテクスチャ付き3Dアセットの品質と条件の遵守能力においてすべてのベースラインを上回っていることを示しています。
| モデル | CMMD(⬇) | FID_CLIP(⬇) | FID(⬇) | CLIP-score(⬆) |
|-------------------------|-----------|-------------|-------------|---------------|
| トップオープンソースモデル1 | 3.591 | 54.639 | 289.287 | 0.787 |
| トップクローズドソースモデル1 | 3.600 | 55.866 | 305.922 | 0.779 |
| トップクローズドソースモデル2 | 3.368 | 49.744 | 294.628 | 0.806 |
| トップクローズドソースモデル3 | 3.218 | 51.574 | 295.691 | 0.799 |
| Hunyuan3D 2.0 | **3.193** | **49.165** | **282.429** | **0.809** |
Hunyuan3D 2.0の生成結果:
<p align="left">
<img src="assets/images/e2e-1.gif" height=250>
<img src="assets/images/e2e-2.gif" height=250>
</p>
### 事前学習モデル
| モデル | 日付 | Huggingface |
|----------------------|------------|--------------------------------------------------------|
| Hunyuan3D-DiT-v2-0 | 2025-01-21 | [ダウンロード](https://huggingface.co/tencent/Hunyuan3D-2) |
| Hunyuan3D-Paint-v2-0 | 2025-01-21 | [ダウンロード](https://huggingface.co/tencent/Hunyuan3D-2) |
## 🤗 Hunyuan3D 2.0の使い方
次の手順に従って、コードまたはGradioアプリを使用してHunyuan3D 2.0を使用できます。
### 必要なものをインストール
公式サイトからPytorchをインストールしてください。次に、他の必要なものを以下の方法でインストールします。
```bash
pip install -r requirements.txt
# for texture
cd hy3dgen/texgen/custom_rasterizer
python3 setup.py install
cd hy3dgen/texgen/differentiable_renderer
python3 setup.py install
```
### APIの使い方
形状生成モデル - Hunyuan3D-DiTおよびテクスチャ合成モデル - Hunyuan3D-Paintを使用するためのdiffusersのようなAPIを設計しました。
**Hunyuan3D-DiT**にアクセスするには、次のようにします:
```python
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained('tencent/Hunyuan3D-2')
mesh = pipeline(image='assets/demo.png')[0]
```
出力メッシュは[trimeshオブジェクト](https://trimesh.org/trimesh.html)であり、glb/obj(または他の形式)ファイルに保存できます。
**Hunyuan3D-Paint**の場合は、次のようにします:
```python
from hy3dgen.texgen import Hunyuan3DPaintPipeline
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
# まずメッシュを生成しましょう
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained('tencent/Hunyuan3D-2')
mesh = pipeline(image='assets/demo.png')[0]
pipeline = Hunyuan3DPaintPipeline.from_pretrained('tencent/Hunyuan3D-2')
mesh = pipeline(mesh, image='assets/demo.png')
```
より高度な使用法については、[minimal_demo.py](minimal_demo.py)を参照してください。例えば、**テキストから3D**や**手作りメッシュのテクスチャ生成**などです。
### Gradioアプリ
次の方法で自分のコンピュータで[Gradio](https://www.gradio.app/)アプリをホストすることもできます:
```bash
python3 gradio_app.py
```
自分でホストしたくない場合は、[Hunyuan3D](https://3d.hunyuan.tencent.com)を訪れてすぐに使用してください。
## 📑 オープンソース計画
- [x] 推論コード
- [x] モデルチェックポイント
- [x] 技術報告書
- [ ] ComfyUI
- [ ] TensorRTバージョン
## 🔗 BibTeX
このリポジトリが役に立った場合は、以下の方法で報告書を引用してください:
```bibtex
@misc{hunyuan3d22025tencent,
title={Hunyuan3D 2.0: Scaling Diffusion Models for High Resolution Textured 3D Assets Generation},
author={Tencent Hunyuan3D Team},
year={2025},
eprint={2501.12202},
archivePrefix={arXiv},
primaryClass={cs.CV}
}
@misc{yang2024hunyuan3d,
title={Hunyuan3D 1.0: A Unified Framework for Text-to-3D and Image-to-3D Generation},
author={Tencent Hunyuan3D Team},
year={2024},
eprint={2411.02293},
archivePrefix={arXiv},
primaryClass={cs.CV}
}
```
## 謝辞
[DINOv2](https://github.com/facebookresearch/dinov2), [Stable Diffusion](https://github.com/Stability-AI/stablediffusion), [FLUX](https://github.com/black-forest-labs/flux), [diffusers](https://github.com/huggingface/diffusers), [HuggingFace](https://huggingface.co), [CraftsMan3D](https://github.com/wyysf-98/CraftsMan3D), and [Michelangelo](https://github.com/NeuralCarver/Michelangelo/tree/main) リポジトリの貢献者に感謝します。
## スター履歴
<a href="https://star-history.com/#Tencent/Hunyuan3D-2&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Tencent/Hunyuan3D-2&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Tencent/Hunyuan3D-2&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Tencent/Hunyuan3D-2&type=Date" />
</picture>
</a>
================================================
FILE: README_zh_cn.md
================================================
[Read in English](README.md)
[日本語で読む](README_ja_jp.md)
<p align="center">
<img src="./assets/images/teaser.jpg">
</p>
<div align="center">
<a href=https://3d.hunyuan.tencent.com target="_blank"><img src=https://img.shields.io/badge/Official%20Site-333399.svg?logo=homepage height=22px></a>
<a href=https://huggingface.co/spaces/tencent/Hunyuan3D-2 target="_blank"><img src=https://img.shields.io/badge/%F0%9F%A4%97%20Demo-276cb4.svg height=22px></a>
<a href=https://huggingface.co/tencent/Hunyuan3D-2 target="_blank"><img src=https://img.shields.io/badge/%F0%9F%A4%97%20Models-d96902.svg height=22px></a>
<a href=https://3d-models.hunyuan.tencent.com/ target="_blank"><img src= https://img.shields.io/badge/Page-bb8a2e.svg?logo=github height=22px></a>
<a href=https://discord.gg/dNBrdrGGMa target="_blank"><img src= https://img.shields.io/badge/Discord-white.svg?logo=discord height=22px></a>
<a href=https://arxiv.org/abs/2501.12202 target="_blank"><img src=https://img.shields.io/badge/Report-b5212f.svg?logo=arxiv height=22px></a>
<a href=https://x.com/txhunyuan target="_blank"><img src=https://img.shields.io/badge/Hunyuan-black.svg?logo=x height=22px></a>
</div>
[//]: # ( <a href=# target="_blank"><img src=https://img.shields.io/badge/Report-b5212f.svg?logo=arxiv height=22px></a>)
[//]: # ( <a href=# target="_blank"><img src= https://img.shields.io/badge/Colab-8f2628.svg?logo=googlecolab height=22px></a>)
[//]: # ( <a href="#"><img alt="PyPI - Downloads" src="https://img.shields.io/pypi/v/mulankit?logo=pypi" height=22px></a>)
<br>
> 新年快乐!

> 加入我们的 **[微信群](#)** and **[Discord 社区](https://discord.gg/dNBrdrGGMa)** 讨论,获取最新进展以及帮助吧.
| Wechat Group | Xiaohongshu | X | Discord |
| ------------------------------------------------ | ----------------------------------------------------- | ------------------------------------------- | ------------------------------------------------- |
| <img src="assets/qrcode/wechat.png" height=140> | <img src="assets/qrcode/xiaohongshu.png" height=140> | <img src="assets/qrcode/x.png" height=140> | <img src="assets/qrcode/discord.png" height=140> |
---
<br>
<p align="center">
“通过 3D 创作与编辑让每个人的想象变成现实。”
</p>
## 🔥 最新消息
- Jul 26, 2025: 🤗 我们发布了业界首个开源且兼容主流图形管线的3D世界生成模型 [HunyuanWorld-1.0](https://github.com/Tencent-Hunyuan/HunyuanWorld-1.0)!
- Jun 13, 2025: 🤗 我们发布了业界首个完全开源支持物理渲染纹理的3D生成模型 [Hunyuan3D 2.1](https://github.com/Tencent-Hunyuan/Hunyuan3D-2.1)!
- Feb 14, 2025: 🛠️ 发布纹理增强模块,欢迎[体验](minimal_demo.py)高清纹理生成.
- Jan 27, 2025: 🛠️ 发布 Blender 插件,欢迎[体验](#blender-addon).
- Jan 23, 2025: 💬 感谢社区成员的 [Windows 安装工具](https://github.com/YanWenKun/Hunyuan3D-2-WinPortable), ComfyUI 支持 [ComfyUI-Hunyuan3DWrapper](https://github.com/kijai/ComfyUI-Hunyuan3DWrapper), [ComfyUI-3D-Pack](https://github.com/MrForExample/ComfyUI-3D-Pack) 以及其他出色的 [扩展功能](#community-resources).
- Jan 21, 2025: 💬 欢迎来我们的门户网站 [Hunyuan3D Studio](https://3d.hunyuan.tencent.com) 体验更多3D生成功能!
- Jan 21, 2025: 💬 我们开源了 [Hunyuan3D 2.0](https://huggingface.co/tencent/Hunyuan3D-2)的推理代码和预训练权重.
- Jan 21, 2025: 💬 我们发布了 [Hunyuan3D 2.0](https://huggingface.co/spaces/tencent/Hunyuan3D-2). 快来试试吧!
## 概览
混元 3D 2.0 是一款先进的大规模 3D 资产创作系统,它可以用于生成带有高分辨率纹理贴图的高保真度3D模型。该系统包含两个基础组件:一个大规模几何生成模型 — 混元 3D-DiT,以及一个大规模纹理生成模型 — 混元 3D-Paint。
几何生成模型基于流扩散的扩散模型构建,旨在生成与给定条件图像精确匹配的几何模型,为下游应用奠定坚实基础。
纹理生成模型得益于强大的几何和扩散模型先验知识,能够为AI生成的或手工制作的网格模型生成高分辨率且生动逼真的纹理贴图。
此外,我们打造了混元 3D 功能矩阵,一个功能多样、易于使用的创作平台,简化了 3D 模型的制作以及修改过程。它使专业用户和业余爱好者都能高效地对3D模型进行操作,甚至制作动画。
我们对该系统进行了系统评估,结果表明混元 3D 2.0 在几何细节、条件匹配、纹理质量等方面均优于以往的最先进的开源以及闭源模型。
<p align="center">
<img src="assets/images/system.jpg">
</p>
## ☯️ **Hunyuan3D 2.0**
### 模型架构
混元 3D 2.0 采用了一个两阶段的生成过程,它首先创建一个无纹理的几何模型,然后为该几何模型合成纹理贴图。这种策略有效地将形状生成和纹理生成的难点分离开来,同时也为生成的几何模型或手工制作的几何模型进行纹理处理提供了灵活性。
<p align="left">
<img src="assets/images/arch.jpg">
</p>
### 性能评估
我们将混元 3D 2.0 与其他开源及闭源的 3D 生成方法进行了评估对比。
数值结果表明,在生成的带纹理 3D 模型的质量以及对给定条件的遵循能力方面,混元 3D 2.0 超越了所有的基准模型。
| Model | CMMD(⬇) | FID_CLIP(⬇) | FID(⬇) | CLIP-score(⬆) |
| ----------------------- | --------- | ----------- | ----------- | ------------- |
| Top Open-source Model1 | 3.591 | 54.639 | 289.287 | 0.787 |
| Top Close-source Model1 | 3.600 | 55.866 | 305.922 | 0.779 |
| Top Close-source Model2 | 3.368 | 49.744 | 294.628 | 0.806 |
| Top Close-source Model3 | 3.218 | 51.574 | 295.691 | 0.799 |
| Hunyuan3D 2.0 | **3.193** | **49.165** | **282.429** | **0.809** |
一些 Hunyuan3D 2.0 的生成结果:
<p align="left">
<img src="assets/images/e2e-1.gif" height=300>
<img src="assets/images/e2e-2.gif" height=300>
</p>
### 预训练模型
| 模型名称 | 发布日期 | 参数 | Huggingface |
| ---------------------- | ---------- | ---- | ----------------------------------------------------------------------------------- |
| Hunyuan3D-DiT-v2-0 | 2025-01-21 | 2.6B | [下载](https://huggingface.co/tencent/Hunyuan3D-2) |
| Hunyuan3D-Paint-v2-0 | 2025-01-21 | 1.3B | [下载](https://huggingface.co/tencent/Hunyuan3D-2) |
| Hunyuan3D-Delight-v2-0 | 2025-01-21 | 1.3B | [下载](https://huggingface.co/tencent/Hunyuan3D-2/tree/main/hunyuan3d-delight-v2-0) |
## 🤗快速入门 Hunyuan3D 2.0
你可以按照以下步骤,通过代码或 Gradio 来使用混元 3D 2.0。
- [代码使用](#代码使用方法)
- [Gradio](#gradio-app-使用方法)
- [API服务器](#api-服务器)
- [Blender插件](#blender-插件)
- [官方网站](#官方网站)
### 依赖包安装
请通过官方网站安装 PyTorch。然后通过以下方式安装其他所需的依赖项。
```bash
pip install -r requirements.txt
# for texture
cd hy3dgen/texgen/custom_rasterizer
python3 setup.py install
cd ../../..
cd hy3dgen/texgen/differentiable_renderer
python3 setup.py install
```
### 代码使用方法
我们设计了一个类似于 diffusers 的 API 来使用我们的几何生成模型 — 混元 3D-DiT 和纹理合成模型 — 混元 3D-Paint。
你可以通过以下方式使用 混元 3D-DiT:
```python
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained('tencent/Hunyuan3D-2')
mesh = pipeline(image='assets/demo.png')[0]
```
输出的网格是一个 Trimesh 对象,你可以将其保存为 glb/obj(或其他格式)文件。
对于 混元 3D-Paint,请执行以下操作:
```python
from hy3dgen.texgen import Hunyuan3DPaintPipeline
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
# let's generate a mesh first
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained('tencent/Hunyuan3D-2')
mesh = pipeline(image='assets/demo.png')[0]
pipeline = Hunyuan3DPaintPipeline.from_pretrained('tencent/Hunyuan3D-2')
mesh = pipeline(mesh, image='assets/demo.png')
```
请访问 [minimal_demo.py](minimal_demo.py) 以了解更多高级用法,例如 文本转 3D 以及 为手工制作的网格生成纹理。
### Gradio App 使用方法
你也可以通过以下方式在自己的计算机上托管一个Gradio应用程序:
```bash
python3 gradio_app.py
```
### API 服务器
你可以在本地启动一个API服务器,通过它你可以发送将图像/文本转换为3D模型、为现有网格模型添加纹理等的网络请求。
```bash
python api_server.py --host 0.0.0.0 --port 8080
```
A demo post request for image to 3D without texture.
```bash
img_b64_str=$(base64 -i assets/demo.png)
curl -X POST "http://localhost:8080/generate" \
-H "Content-Type: application/json" \
-d '{
"image": "'"$img_b64_str"'",
}' \
-o test2.glb
```
### Blender 插件
API服务器启动后,你还可以通过我们的[Blender插件](blender_addon.py)在Blender中直接使用混元3D 2.0。请按照我们的教程进行安装和使用。
https://github.com/user-attachments/assets/8230bfb5-32b1-4e48-91f4-a977c54a4f3e
### 官方网站
如果你不想自己托管,别忘了访问[混元 3D](https://3d.hunyuan.tencent.com)进行快速使用。
## 📑 开源计划
- [x] 推理代码
- [x] 模型权重
- [x] 技术报告
- [ ] ComfyUI
- [ ] TensorRT 量化
## 🔗 引用
如果你发现我们的工作有帮助,你可以以下面的方式引用我们的报告:
```bibtex
@misc{hunyuan3d22025tencent,
title={Hunyuan3D 2.0: Scaling Diffusion Models for High Resolution Textured 3D Assets Generation},
author={Tencent Hunyuan3D Team},
year={2025},
eprint={2501.12202},
archivePrefix={arXiv},
primaryClass={cs.CV}
}
@misc{yang2024hunyuan3d,
title={Hunyuan3D 1.0: A Unified Framework for Text-to-3D and Image-to-3D Generation},
author={Tencent Hunyuan3D Team},
year={2024},
eprint={2411.02293},
archivePrefix={arXiv},
primaryClass={cs.CV}
}
```
## 致谢
我们要感谢以下内容的贡献者: [DINOv2](https://github.com/facebookresearch/dinov2), [Stable Diffusion](https://github.com/Stability-AI/stablediffusion), [FLUX](https://github.com/black-forest-labs/flux), [diffusers](https://github.com/huggingface/diffusers), [HuggingFace](https://huggingface.co), [CraftsMan3D](https://github.com/wyysf-98/CraftsMan3D), 和 [Michelangelo](https://github.com/NeuralCarver/Michelangelo/tree/main) 各研究机构,感谢它们开展公开研究与探索。
## Star 历史
<a href="https://star-history.com/#Tencent/Hunyuan3D-2&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Tencent/Hunyuan3D-2&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Tencent/Hunyuan3D-2&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Tencent/Hunyuan3D-2&type=Date" />
</picture>
</a>
================================================
FILE: api_server.py
================================================
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
# except for the third-party components listed below.
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
# in the repsective licenses of these third-party components.
# Users must comply with all terms and conditions of original licenses of these third-party
# components and must ensure that the usage of the third party components adheres to
# all relevant laws and regulations.
# For avoidance of doubts, Hunyuan 3D means the large language models and
# their software and algorithms, including trained model weights, parameters (including
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
# fine-tuning enabling code and other elements of the foregoing made publicly available
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
"""
A model worker executes the model.
"""
import argparse
import asyncio
import base64
import logging
import logging.handlers
import os
import sys
import tempfile
import threading
import traceback
import uuid
from io import BytesIO
import torch
import trimesh
import uvicorn
from PIL import Image
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, FileResponse
from hy3dgen.rembg import BackgroundRemover
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline, FloaterRemover, DegenerateFaceRemover, FaceReducer, \
MeshSimplifier
from hy3dgen.texgen import Hunyuan3DPaintPipeline
from hy3dgen.text2image import HunyuanDiTPipeline
LOGDIR = '.'
server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
moderation_msg = "YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE TRY AGAIN."
handler = None
def build_logger(logger_name, logger_filename):
global handler
formatter = logging.Formatter(
fmt="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
# Set the format of root handlers
if not logging.getLogger().handlers:
logging.basicConfig(level=logging.INFO)
logging.getLogger().handlers[0].setFormatter(formatter)
# Redirect stdout and stderr to loggers
stdout_logger = logging.getLogger("stdout")
stdout_logger.setLevel(logging.INFO)
sl = StreamToLogger(stdout_logger, logging.INFO)
sys.stdout = sl
stderr_logger = logging.getLogger("stderr")
stderr_logger.setLevel(logging.ERROR)
sl = StreamToLogger(stderr_logger, logging.ERROR)
sys.stderr = sl
# Get logger
logger = logging.getLogger(logger_name)
logger.setLevel(logging.INFO)
# Add a file handler for all loggers
if handler is None:
os.makedirs(LOGDIR, exist_ok=True)
filename = os.path.join(LOGDIR, logger_filename)
handler = logging.handlers.TimedRotatingFileHandler(
filename, when='D', utc=True, encoding='UTF-8')
handler.setFormatter(formatter)
for name, item in logging.root.manager.loggerDict.items():
if isinstance(item, logging.Logger):
item.addHandler(handler)
return logger
class StreamToLogger(object):
"""
Fake file-like stream object that redirects writes to a logger instance.
"""
def __init__(self, logger, log_level=logging.INFO):
self.terminal = sys.stdout
self.logger = logger
self.log_level = log_level
self.linebuf = ''
def __getattr__(self, attr):
return getattr(self.terminal, attr)
def write(self, buf):
temp_linebuf = self.linebuf + buf
self.linebuf = ''
for line in temp_linebuf.splitlines(True):
# From the io.TextIOWrapper docs:
# On output, if newline is None, any '\n' characters written
# are translated to the system default line separator.
# By default sys.stdout.write() expects '\n' newlines and then
# translates them so this is still cross platform.
if line[-1] == '\n':
self.logger.log(self.log_level, line.rstrip())
else:
self.linebuf += line
def flush(self):
if self.linebuf != '':
self.logger.log(self.log_level, self.linebuf.rstrip())
self.linebuf = ''
def pretty_print_semaphore(semaphore):
if semaphore is None:
return "None"
return f"Semaphore(value={semaphore._value}, locked={semaphore.locked()})"
SAVE_DIR = 'gradio_cache'
os.makedirs(SAVE_DIR, exist_ok=True)
worker_id = str(uuid.uuid4())[:6]
logger = build_logger("controller", f"{SAVE_DIR}/controller.log")
def load_image_from_base64(image):
return Image.open(BytesIO(base64.b64decode(image)))
class ModelWorker:
def __init__(self,
model_path='tencent/Hunyuan3D-2mini',
tex_model_path='tencent/Hunyuan3D-2',
subfolder='hunyuan3d-dit-v2-mini-turbo',
device='cuda',
enable_tex=False):
self.model_path = model_path
self.worker_id = worker_id
self.device = device
logger.info(f"Loading the model {model_path} on worker {worker_id} ...")
self.rembg = BackgroundRemover()
self.pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
model_path,
subfolder=subfolder,
use_safetensors=True,
device=device,
)
self.pipeline.enable_flashvdm(mc_algo='mc')
# self.pipeline_t2i = HunyuanDiTPipeline(
# 'Tencent-Hunyuan/HunyuanDiT-v1.1-Diffusers-Distilled',
# device=device
# )
if enable_tex:
self.pipeline_tex = Hunyuan3DPaintPipeline.from_pretrained(tex_model_path)
def get_queue_length(self):
if model_semaphore is None:
return 0
else:
return args.limit_model_concurrency - model_semaphore._value + (len(
model_semaphore._waiters) if model_semaphore._waiters is not None else 0)
def get_status(self):
return {
"speed": 1,
"queue_length": self.get_queue_length(),
}
@torch.inference_mode()
def generate(self, uid, params):
if 'image' in params:
image = params["image"]
image = load_image_from_base64(image)
else:
if 'text' in params:
text = params["text"]
image = self.pipeline_t2i(text)
else:
raise ValueError("No input image or text provided")
image = self.rembg(image)
params['image'] = image
if 'mesh' in params:
mesh = trimesh.load(BytesIO(base64.b64decode(params["mesh"])), file_type='glb')
else:
seed = params.get("seed", 1234)
params['generator'] = torch.Generator(self.device).manual_seed(seed)
params['octree_resolution'] = params.get("octree_resolution", 128)
params['num_inference_steps'] = params.get("num_inference_steps", 5)
params['guidance_scale'] = params.get('guidance_scale', 5.0)
params['mc_algo'] = 'mc'
import time
start_time = time.time()
mesh = self.pipeline(**params)[0]
logger.info("--- %s seconds ---" % (time.time() - start_time))
if params.get('texture', False):
mesh = FloaterRemover()(mesh)
mesh = DegenerateFaceRemover()(mesh)
mesh = FaceReducer()(mesh, max_facenum=params.get('face_count', 40000))
mesh = self.pipeline_tex(mesh, image)
type = params.get('type', 'glb')
with tempfile.NamedTemporaryFile(suffix=f'.{type}', delete=False) as temp_file:
mesh.export(temp_file.name)
mesh = trimesh.load(temp_file.name)
save_path = os.path.join(SAVE_DIR, f'{str(uid)}.{type}')
mesh.export(save_path)
torch.cuda.empty_cache()
return save_path, uid
app = FastAPI()
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 你可以指定允许的来源
allow_credentials=True,
allow_methods=["*"], # 允许所有方法
allow_headers=["*"], # 允许所有头部
)
@app.post("/generate")
async def generate(request: Request):
logger.info("Worker generating...")
params = await request.json()
uid = uuid.uuid4()
try:
file_path, uid = worker.generate(uid, params)
return FileResponse(file_path)
except ValueError as e:
traceback.print_exc()
print("Caught ValueError:", e)
ret = {
"text": server_error_msg,
"error_code": 1,
}
return JSONResponse(ret, status_code=404)
except torch.cuda.CudaError as e:
print("Caught torch.cuda.CudaError:", e)
ret = {
"text": server_error_msg,
"error_code": 1,
}
return JSONResponse(ret, status_code=404)
except Exception as e:
print("Caught Unknown Error", e)
traceback.print_exc()
ret = {
"text": server_error_msg,
"error_code": 1,
}
return JSONResponse(ret, status_code=404)
@app.post("/send")
async def generate(request: Request):
logger.info("Worker send...")
params = await request.json()
uid = uuid.uuid4()
threading.Thread(target=worker.generate, args=(uid, params,)).start()
ret = {"uid": str(uid)}
return JSONResponse(ret, status_code=200)
@app.get("/status/{uid}")
async def status(uid: str):
save_file_path = os.path.join(SAVE_DIR, f'{uid}.glb')
print(save_file_path, os.path.exists(save_file_path))
if not os.path.exists(save_file_path):
response = {'status': 'processing'}
return JSONResponse(response, status_code=200)
else:
base64_str = base64.b64encode(open(save_file_path, 'rb').read()).decode()
response = {'status': 'completed', 'model_base64': base64_str}
return JSONResponse(response, status_code=200)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--host", type=str, default="0.0.0.0")
parser.add_argument("--port", type=int, default=8081)
parser.add_argument("--model_path", type=str, default='tencent/Hunyuan3D-2mini')
parser.add_argument("--tex_model_path", type=str, default='tencent/Hunyuan3D-2')
parser.add_argument("--device", type=str, default="cuda")
parser.add_argument("--limit-model-concurrency", type=int, default=5)
parser.add_argument('--enable_tex', action='store_true')
args = parser.parse_args()
logger.info(f"args: {args}")
model_semaphore = asyncio.Semaphore(args.limit_model_concurrency)
worker = ModelWorker(model_path=args.model_path, device=args.device, enable_tex=args.enable_tex,
tex_model_path=args.tex_model_path)
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
================================================
FILE: assets/example_prompts.txt
================================================
一片绿色的树叶在白色背景上居中展现,清晰的纹理
一只棕白相间的仓鼠,站在白色背景前。照片采用居中构图方式,卡通风格
一盆绿色植物生长在红色花盆中,居中,写实
a pot of green plants grows in a red flower pot.
a lovely rabbit eating carrots
================================================
FILE: assets/modelviewer-template.html
================================================
<!DOCTYPE html>
<html>
<head>
<!-- Import the component -->
<script src="https://cdn.jsdelivr.net/npm/@google/model-viewer@3.1.1/dist/model-viewer.min.js" type="module"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
const modelViewers = document.querySelectorAll('model-viewer');
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
modelViewers.forEach(modelViewer => {
modelViewer.setAttribute(
"environment-image",
"/static/env_maps/gradient.jpg"
);
// if (!isSafari) {
// modelViewer.setAttribute(
// "environment-image",
// "/static/env_maps/gradient.jpg"
// );
// } else {
// modelViewer.addEventListener('load', (event) => {
// const [material] = modelViewer.model.materials;
// let color = [43, 44, 46, 255];
// color = color.map(x => x / 255);
// material.pbrMetallicRoughness.setMetallicFactor(0.1); // 完全金属
// material.pbrMetallicRoughness.setRoughnessFactor(0.7); // 低粗糙度
// material.pbrMetallicRoughness.setBaseColorFactor(color); // CornflowerBlue in RGB
// });
// }
// modelViewer.addEventListener('load', (event) => {
// const [material] = modelViewer.model.materials;
// let color = [43, 44, 46, 255];
// color = color.map(x => x / 255);
// material.pbrMetallicRoughness.setMetallicFactor(0.1); // 完全金属
// material.pbrMetallicRoughness.setRoughnessFactor(0.7); // 低粗糙度
// material.pbrMetallicRoughness.setBaseColorFactor(color); // CornflowerBlue in RGB
// });
});
});
</script>
<style>
body {
margin: 0;
font-family: Arial, sans-serif;
}
.centered-container {
display: flex;
justify-content: center;
align-items: center;
border-radius: 8px;
border-color: #e5e7eb;
border-style: solid;
border-width: 1px;
}
</style>
</head>
<body>
<div class="centered-container">
<div class="column is-mobile is-centered">
<model-viewer id="modelviewer" style="height: #height#px; width: #width#px;"
rotation-per-second="10deg"
src="#src#" disable-tap
environment-image="neutral"
camera-target="0m 0m 0m"
camera-orbit="0deg 90deg 8m"
orientation="0deg 0deg 0deg"
shadow-intensity=".9"
ar auto-rotate
camera-controls>
</model-viewer>
</div>
</div>
</body>
</html>
================================================
FILE: assets/modelviewer-textured-template.html
================================================
<!DOCTYPE html>
<html>
<head>
<!-- Import the component -->
<script src="https://cdn.jsdelivr.net/npm/@google/model-viewer@3.1.1/dist/model-viewer.min.js"
type="module"></script>
<style>
body {
margin: 0;
font-family: Arial, sans-serif;
}
.centered-container {
display: flex;
justify-content: center;
align-items: center;
}
.modelviewer-panel-button {
height: 30px;
margin: 4px 4px;
padding: 0px 14px;
background: white;
border-radius: 10px;
box-shadow: 0px 0px 4px rgba(0, 0, 0, 0.25);
font-size: 14px;
font-weight: 600;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.2s ease;
}
.modelviewer-panel-button.checked {
background: #6567C9;
color: white;
}
.modelviewer-panel-button:hover {
background-color: #e2e6ea;
}
.modelviewer-panel-button-container {
display: flex;
justify-content: space-around;
}
.centered-container {
display: flex;
flex-direction: column;
align-items: center;
}
</style>
</head>
<body>
<div class="centered-container">
<div class="centered-container">
<div class="column is-mobile is-centered">
<model-viewer id="modelviewer" style="height: #height#px; width: #width#px;"
rotation-per-second="10deg"
src="#src#" disable-tap
environment-image="neutral"
camera-target="0m 0m 0m"
camera-orbit="0deg 90deg 12m"
orientation="0deg 0deg 0deg"
shadow-intensity=".9"
ar auto-rotate
camera-controls>
</model-viewer>
</div>
<div class="modelviewer-panel-button-container">
<div id="appearance-button" class="modelviewer-panel-button small checked" onclick="showTexture()">
Appearance
</div>
<div id="geometry-button" class="modelviewer-panel-button small" onclick="hideTexture()">Geometry</div>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
const modelViewers = document.querySelectorAll('model-viewer');
modelViewers.forEach(modelViewer => {
modelViewer.addEventListener('load', (event) => {
const [material] = modelViewer.model.materials;
material.pbrMetallicRoughness.setMetallicFactor(0.1);
material.pbrMetallicRoughness.setRoughnessFactor(0.5);
});
});
});
var window_state = {};
function hideTexture() {
let appearanceButton = document.getElementById('appearance-button');
let geometryButton = document.getElementById('geometry-button');
appearanceButton.classList.remove('checked');
geometryButton.classList.add('checked');
let modelViewer = document.getElementById('modelviewer');
if (modelViewer.model.materials[0].pbrMetallicRoughness.baseColorTexture.texture === null) return;
window_state.textures = [];
for (let i = 0; i < modelViewer.model.materials.length; i++) {
window_state.textures.push(modelViewer.model.materials[i].pbrMetallicRoughness.baseColorTexture.texture);
}
window_state.exposure = modelViewer.exposure;
modelViewer.environmentImage = '/static/env_maps/gradient.jpg';
for (let i = 0; i < modelViewer.model.materials.length; i++) {
modelViewer.model.materials[i].pbrMetallicRoughness.baseColorTexture.setTexture(null);
}
modelViewer.exposure = 4;
}
function showTexture() {
let appearanceButton = document.getElementById('appearance-button');
let geometryButton = document.getElementById('geometry-button');
appearanceButton.classList.add('checked');
geometryButton.classList.remove('checked');
let modelViewer = document.getElementById('modelviewer');
if (modelViewer.model.materials[0].pbrMetallicRoughness.baseColorTexture.texture !== null) return;
modelViewer.environmentImage = '/static/env_maps/white.jpg';
for (let i = 0; i < modelViewer.model.materials.length; i++) {
modelViewer.model.materials[i].pbrMetallicRoughness.baseColorTexture.setTexture(window_state.textures[i]);
}
modelViewer.exposure = window_state.exposure;
}
</script>
</body>
</html>
================================================
FILE: blender_addon.py
================================================
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
# except for the third-party components listed below.
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
# in the repsective licenses of these third-party components.
# Users must comply with all terms and conditions of original licenses of these third-party
# components and must ensure that the usage of the third party components adheres to
# all relevant laws and regulations.
# For avoidance of doubts, Hunyuan 3D means the large language models and
# their software and algorithms, including trained model weights, parameters (including
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
# fine-tuning enabling code and other elements of the foregoing made publicly available
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
bl_info = {
"name": "Hunyuan3D-2 Generator",
"author": "Tencent Hunyuan3D",
"version": (1, 0),
"blender": (3, 0, 0),
"location": "View3D > Sidebar > Hunyuan3D-2 3D Generator",
"description": "Generate/Texturing 3D models from text descriptions or images",
"category": "3D View",
}
import base64
import os
import tempfile
import threading
import bpy
import requests
from bpy.props import StringProperty, BoolProperty, IntProperty, FloatProperty
class Hunyuan3DProperties(bpy.types.PropertyGroup):
prompt: StringProperty(
name="Text Prompt",
description="Describe what you want to generate",
default=""
)
api_url: StringProperty(
name="API URL",
description="URL of the Text-to-3D API service",
default="http://localhost:8080"
)
is_processing: BoolProperty(
name="Processing",
default=False
)
job_id: StringProperty(
name="Job ID",
default=""
)
status_message: StringProperty(
name="Status Message",
default=""
)
# 添加图片路径属性
image_path: StringProperty(
name="Image",
description="Select an image to upload",
subtype='FILE_PATH'
)
# 修改后的 octree_resolution 属性
octree_resolution: IntProperty(
name="Octree Resolution",
description="Octree resolution for the 3D generation",
default=256,
min=128,
max=512,
)
num_inference_steps: IntProperty(
name="Number of Inference Steps",
description="Number of inference steps for the 3D generation",
default=20,
min=20,
max=50
)
guidance_scale: FloatProperty(
name="Guidance Scale",
description="Guidance scale for the 3D generation",
default=5.5,
min=1.0,
max=10.0
)
# 添加 texture 属性
texture: BoolProperty(
name="Generate Texture",
description="Whether to generate texture for the 3D model",
default=False
)
class Hunyuan3DOperator(bpy.types.Operator):
bl_idname = "object.generate_3d"
bl_label = "Generate 3D Model"
bl_description = "Generate a 3D model from text description, an image or a selected mesh"
job_id = ''
prompt = ""
api_url = ""
image_path = ""
octree_resolution = 256
num_inference_steps = 20
guidance_scale = 5.5
texture = False # 新增属性
selected_mesh_base64 = ""
selected_mesh = None # 新增属性,用于存储选中的 mesh
thread = None
task_finished = False
def modal(self, context, event):
if event.type in {'RIGHTMOUSE', 'ESC'}:
return {'CANCELLED'}
if self.task_finished:
print("Threaded task completed")
self.task_finished = False
props = context.scene.gen_3d_props
props.is_processing = False
return {'PASS_THROUGH'}
def invoke(self, context, event):
# 启动线程
props = context.scene.gen_3d_props
self.prompt = props.prompt
self.api_url = props.api_url
self.image_path = props.image_path
self.octree_resolution = props.octree_resolution
self.num_inference_steps = props.num_inference_steps
self.guidance_scale = props.guidance_scale
self.texture = props.texture # 获取 texture 属性的值
if self.prompt == "" and self.image_path == "":
self.report({'WARNING'}, "Please enter some text or select an image first.")
return {'FINISHED'}
# 保存选中的 mesh 对象引用
for obj in context.selected_objects:
if obj.type == 'MESH':
self.selected_mesh = obj
break
if self.selected_mesh:
temp_glb_file = tempfile.NamedTemporaryFile(delete=False, suffix=".glb")
temp_glb_file.close()
bpy.ops.export_scene.gltf(filepath=temp_glb_file.name, use_selection=True)
with open(temp_glb_file.name, "rb") as file:
mesh_data = file.read()
mesh_b64_str = base64.b64encode(mesh_data).decode()
os.unlink(temp_glb_file.name)
self.selected_mesh_base64 = mesh_b64_str
props.is_processing = True
# 将相对路径转换为相对于 Blender 文件所在目录的绝对路径
blend_file_dir = os.path.dirname(bpy.data.filepath)
self.report({'INFO'}, f"blend_file_dir {blend_file_dir}")
self.report({'INFO'}, f"image_path {self.image_path}")
if self.image_path.startswith('//'):
self.image_path = self.image_path[2:]
self.image_path = os.path.join(blend_file_dir, self.image_path)
if self.selected_mesh and self.texture:
props.status_message = "Texturing Selected Mesh...\n" \
"This may take several minutes depending \n on your GPU power."
else:
mesh_type = 'Textured Mesh' if self.texture else 'White Mesh'
prompt_type = 'Text Prompt' if self.prompt else 'Image'
props.status_message = f"Generating {mesh_type} with {prompt_type}...\n" \
"This may take several minutes depending \n on your GPU power."
self.thread = threading.Thread(target=self.generate_model, args=[context])
self.thread.start()
wm = context.window_manager
wm.modal_handler_add(self)
return {'RUNNING_MODAL'}
def generate_model(self, context):
self.report({'INFO'}, f"Generation Start")
base_url = self.api_url.rstrip('/')
try:
if self.selected_mesh_base64 and self.texture:
# Texturing the selected mesh
if self.image_path and os.path.exists(self.image_path):
self.report({'INFO'}, f"Post Texturing with Image")
# 打开图片文件并以二进制模式读取
with open(self.image_path, "rb") as file:
# 读取文件内容
image_data = file.read()
# 对图片数据进行 Base64 编码
img_b64_str = base64.b64encode(image_data).decode()
response = requests.post(
f"{base_url}/generate",
json={
"mesh": self.selected_mesh_base64,
"image": img_b64_str,
"octree_resolution": self.octree_resolution,
"num_inference_steps": self.num_inference_steps,
"guidance_scale": self.guidance_scale,
"texture": self.texture # 传递 texture 参数
},
)
else:
self.report({'INFO'}, f"Post Texturing with Text")
response = requests.post(
f"{base_url}/generate",
json={
"mesh": self.selected_mesh_base64,
"text": self.prompt,
"octree_resolution": self.octree_resolution,
"num_inference_steps": self.num_inference_steps,
"guidance_scale": self.guidance_scale,
"texture": self.texture # 传递 texture 参数
},
)
else:
if self.image_path:
if not os.path.exists(self.image_path):
self.report({'ERROR'}, f"Image path does not exist {self.image_path}")
raise Exception(f'Image path does not exist {self.image_path}')
self.report({'INFO'}, f"Post Start Image to 3D")
# 打开图片文件并以二进制模式读取
with open(self.image_path, "rb") as file:
# 读取文件内容
image_data = file.read()
# 对图片数据进行 Base64 编码
img_b64_str = base64.b64encode(image_data).decode()
response = requests.post(
f"{base_url}/generate",
json={
"image": img_b64_str,
"octree_resolution": self.octree_resolution,
"num_inference_steps": self.num_inference_steps,
"guidance_scale": self.guidance_scale,
"texture": self.texture # 传递 texture 参数
},
)
else:
self.report({'INFO'}, f"Post Start Text to 3D")
response = requests.post(
f"{base_url}/generate",
json={
"text": self.prompt,
"octree_resolution": self.octree_resolution,
"num_inference_steps": self.num_inference_steps,
"guidance_scale": self.guidance_scale,
"texture": self.texture # 传递 texture 参数
},
)
self.report({'INFO'}, f"Post Done")
self.task_finished = True
props = context.scene.gen_3d_props
props.is_processing = False
if response.status_code != 200:
self.report({'ERROR'}, f"Generation failed: {response.text}")
return
# Decode base64 and save to temporary file
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".glb")
temp_file.write(response.content)
temp_file.close()
# Import the GLB file in the main thread
def import_handler():
bpy.ops.import_scene.gltf(filepath=temp_file.name)
os.unlink(temp_file.name)
# 获取新导入的 mesh
new_obj = bpy.context.selected_objects[0] if bpy.context.selected_objects else None
if new_obj and self.selected_mesh and self.texture:
# 应用选中 mesh 的位置、旋转和缩放
new_obj.location = self.selected_mesh.location
new_obj.rotation_euler = self.selected_mesh.rotation_euler
new_obj.scale = self.selected_mesh.scale
# 隐藏原来的 mesh
self.selected_mesh.hide_set(True)
self.selected_mesh.hide_render = True
return None
bpy.app.timers.register(import_handler)
except Exception as e:
self.report({'ERROR'}, f"Error: {str(e)}")
finally:
self.task_finished = True
props = context.scene.gen_3d_props
props.is_processing = False
self.selected_mesh_base64 = ""
class Hunyuan3DPanel(bpy.types.Panel):
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'Hunyuan3D-2'
bl_label = 'Hunyuan3D-2 3D Generator'
def draw(self, context):
layout = self.layout
props = context.scene.gen_3d_props
layout.prop(props, "api_url")
layout.prop(props, "prompt")
# 添加图片选择器
layout.prop(props, "image_path")
# 添加新属性的 UI 元素
layout.prop(props, "octree_resolution")
layout.prop(props, "num_inference_steps")
layout.prop(props, "guidance_scale")
# 添加 texture 属性的 UI 元素
layout.prop(props, "texture")
row = layout.row()
row.enabled = not props.is_processing
row.operator("object.generate_3d")
if props.is_processing:
if props.status_message:
for line in props.status_message.split("\n"):
layout.label(text=line)
else:
layout.label("Processing...")
classes = (
Hunyuan3DProperties,
Hunyuan3DOperator,
Hunyuan3DPanel,
)
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.Scene.gen_3d_props = bpy.props.PointerProperty(type=Hunyuan3DProperties)
def unregister():
for cls in reversed(classes):
bpy.utils.unregister_class(cls)
del bpy.types.Scene.gen_3d_props
if __name__ == "__main__":
register()
================================================
FILE: docs/Makefile
================================================
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
================================================
FILE: docs/README.md
================================================
# Documentation
Source of the documentation.
- Build html.
```bash
make html
```
- Preview at `build/html/index.html`
================================================
FILE: docs/make.bat
================================================
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.https://www.sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd
================================================
FILE: docs/requirements.txt
================================================
myst-parser
sphinx-rtd-theme
furo
sphinx-copybutton
sphinx-inline-tabs
nbsphinx
nbsphinx_link
linkify-it-py
linkify
ipython
torch
imageio
scikit_image
matplotlib
munch
tfpnp
cvxpy
torchlights
tensorboardX
termcolor
proximal
opencv-python
huggingface_hub
torchvision
================================================
FILE: docs/source/_static/css/custom.css
================================================
/*.sidebar-logo {*/
/* display: block;*/
/* margin: 0;*/
/* max-width: 50%;*/
/*}*/
.nbsphinx-gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 5px;
margin-top: 1em;
margin-bottom: 1em;
}
h1 {
font-size: 2em
}
h2 {
font-size: 1.3em
}
h3 {
font-size: 1.25em
}
h4 {
font-size: 1.125em
}
h5 {
font-size: 1.07em
}
h6 {
font-size: 1em
}
================================================
FILE: docs/source/citation.md
================================================
# Citation
The following publications discuss the ideas behind Hunyuan3D-2:
> **Unleashing Vecset Diffusion Model for Fast Shape Generation** </br>
> Technical Report, 2025.
> **Hunyuan3D 2.0: Scaling Diffusion Models for High Resolution Textured 3D Assets Generation** </br>
> Technical Report, 2024.
> **Hunyuan3D 1.0: A Unified Framework for Text-to-3D and Image-to-3D Generation** </br>
> Technical Report, 2024.
If you found this repository helpful, please cite our reports:
```bibtex
@misc{lai2025flashvdm,
title={Unleashing Vecset Diffusion Model for Fast Shape Generation},
author={Zeqiang Lai and Yunfei Zhao and Zibo Zhao and Haolin Liu and Fuyun Wang and Huiwen Shi and Xianghui Yang and Qinxiang Lin and Jinwei Huang and Yuhong Liu and Jie Jiang and Chunchao Guo and Xiangyu Yue},
year={2025},
eprint={2503.16302},
archivePrefix={arXiv},
primaryClass={cs.CV},
url={https://arxiv.org/abs/2503.16302},
}
@misc{hunyuan3d22025tencent,
title={Hunyuan3D 2.0: Scaling Diffusion Models for High Resolution Textured 3D Assets Generation},
author={Tencent Hunyuan3D Team},
year={2025},
eprint={2501.12202},
archivePrefix={arXiv},
primaryClass={cs.CV}
}
@misc{yang2024hunyuan3d,
title={Hunyuan3D 1.0: A Unified Framework for Text-to-3D and Image-to-3D Generation},
author={Tencent Hunyuan3D Team},
year={2024},
eprint={2411.02293},
archivePrefix={arXiv},
primaryClass={cs.CV}
}
```
================================================
FILE: docs/source/conf.py
================================================
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
import os
import sys
sys.path.insert(0, os.path.abspath("."))
sys.path.insert(0, os.path.abspath("../../"))
# -- Project information -----------------------------------------------------
project = 'Hunyuan3D-2'
copyright = '2025, Tencent Hunyuan3D'
author = 'Hunyuan3D Team'
# The full version, including alpha/beta/rc tags
release = '0.0.1'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'myst_parser',
'nbsphinx',
'nbsphinx_link',
# "myst_nb",
'sphinx_copybutton',
# "sphinx_inline_tabs",
# https://sphinx-codeautolink.readthedocs.io/en/latest/examples.html
'sphinx.ext.autodoc',
"sphinx.ext.intersphinx",
"sphinx.ext.extlinks",
'sphinx.ext.autosummary',
'sphinx.ext.doctest',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
'sphinx.ext.napoleon',
]
# -- Options for extlinks ----------------------------------------------------
#
extlinks = {
"pypi": ("https://pypi.org/project/%s/", "%s"),
}
# -- Options for intersphinx -------------------------------------------------
#
intersphinx_mapping = {
"python": ("https://docs.python.org/3", None),
"sphinx": ("https://www.sphinx-doc.org/en/master", None),
'torch': ('https://pytorch.org/docs/master/', None)
}
napoleon_preprocess_types = True
myst_enable_extensions = [
"amsmath",
"colon_fence",
"deflist",
"dollarmath",
"fieldlist",
"html_admonition",
"html_image",
"linkify",
"replacements",
"smartquotes",
"strikethrough",
"substitution",
"tasklist",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
# html_theme = 'alabaster'
# html_theme = 'sphinx_rtd_theme'
html_theme = "furo"
html_title = "Hunyuan3D-2"
language = "en"
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_theme_options = {
"light_css_variables": {
"font-stack": "Arial,Noto Sans,sans-serif",
"font-stack--monospace": "IBM Plex Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace",
},
"announcement": 'Release 🤗<a href="https://huggingface.co/spaces/tencent/Hunyuan3D-2mini-Turbo">Turbo Series</a> and <a href="https://github.com/Tencent/FlashVDM">FlashVDM</a>, Fast Shape Generation within 1 Second Right Now!',
}
#
# -- Options for TODOs -------------------------------------------------------
#
todo_include_todos = True
#
# -- Options for Markdown files ----------------------------------------------
#
myst_admonition_enable = True
myst_deflist_enable = True
myst_heading_anchors = 3
html_favicon = '_static/favicon.ico'
pygments_style = "default"
pygments_dark_style = "github-dark"
html_css_files = [
'css/custom.css',
]
================================================
FILE: docs/source/index.md
================================================
---
hide-toc: true
---
# Welcome to Hunyuan3D
```{toctree}
:maxdepth: 3
:hidden:
Installation <installation/index>
Get Started <started/index>
Model Zoo <modelzoo>
citation
```
```{toctree}
:caption: Useful Links
:hidden:
PyPI Page <https://pypi.org/project/hy3dgen/>
GitHub Repository <https://github.com/Tencent/Hunyuan3D-2>
Paper <https://arxiv.org/abs/2501.12202>
```
<br/>
☯️ Hunyuan3D 2.0 is an advanced large-scale 3D synthesis system for generating high-resolution textured 3D assets.
The system includes the following foundation components:
1. [Hunyuan3D-DiT](): a large-scale shape generation model.
2. [Hunyuan3D-Paint](): a large-scale texture synthesis model.
3. [Hunyuan3D-Studio](): a versatile, user-friendly production platform that simplifies the re-creation process of 3D
assets. It allows both professional and amateur users to manipulate or even animate their meshes efficiently.
4. [FlashVDM](): a universal acceleration framework.
```{nbgallery}
```
<div class="toctree-wrapper compound">
<div class="nbsphinx-gallery">
<a class="reference internal" href="started/quicktour.html">
<b>Quicktour</b>
<p style="color:var(--color-content-foreground)">Learn the fundamentals of using ∇-Prox. We recommend starting here if you are using 🎉 ∇-Prox for the first time! </p>
</a>
<a class="reference internal" href="tutorials/index.html">
<b>Tutorials</b>
<p style="color:var(--color-content-foreground)">Understand the design of the library and the mathematics behind the code. </p>
</a>
<a class="reference internal" href="api/index.html">
<b>API Documentation</b>
<p style="color:var(--color-content-foreground)">Explore the complete reference guide. Useful if you want to develop programs with ∇-Prox. </p>
</a>
</div>
</div>
================================================
FILE: docs/source/installation/index.md
================================================
# Installation
```{toctree}
:hidden:
```
∇-Prox works with PyTorch. To install Pytorch, please follow the [PyTorch installation instructions](https://pytorch.org/get-started/locally/).
**Install with pip**
```bash
pip install dprox
```
**Install from source**
```bash
pip install git+https://github.com/princeton-computational-imaging/Delta-Prox.git
```
**Editable installation**
You will need an editable install if you would like to:
1. Use the main version of the source code.
2. Need to test changes in the code.
To do so, clone the repository and install 🎉 Delta Prox with the following commands:
```
git clone git+https://github.com/princeton-computational-imaging/Delta-Prox.git
cd DeltaProx
pip install -e .
```
```{caution}
Note that you must keep the DeltaProx folder for editable installation if you want to keep using the library.
```
================================================
FILE: docs/source/modelzoo.md
================================================
# Model Zoo
It takes 6 GB VRAM for shape generation and 24.5 GB for shape and texture generation in total.
## Hunyuan3D-2mini Series
| Model | Description | Date | Size | Huggingface |
|-----------------------------|-------------------------------|------------|------|--------------------------------------------------------------------------------------------------|
| Hunyuan3D-DiT-v2-mini-Turbo | Step Distillation Version | 2025-03-19 | 0.6B | [Download](https://huggingface.co/tencent/Hunyuan3D-2mini/tree/main/hunyuan3d-dit-v2-mini-turbo) |
| Hunyuan3D-DiT-v2-mini-Fast | Guidance Distillation Version | 2025-03-18 | 0.6B | [Download](https://huggingface.co/tencent/Hunyuan3D-2mini/tree/main/hunyuan3d-dit-v2-mini-fast) |
| Hunyuan3D-DiT-v2-mini | Mini Image to Shape Model | 2025-03-18 | 0.6B | [Download](https://huggingface.co/tencent/Hunyuan3D-2mini/tree/main/hunyuan3d-dit-v2-mini) |
## Hunyuan3D-2mv Series
| Model | Description | Date | Size | Huggingface |
|---------------------------|--------------------------------|------------|------|----------------------------------------------------------------------------------------------|
| Hunyuan3D-DiT-v2-mv-Turbo | Step Distillation Version | 2025-03-19 | 1.1B | [Download](https://huggingface.co/tencent/Hunyuan3D-2mv/tree/main/hunyuan3d-dit-v2-mv-turbo) |
| Hunyuan3D-DiT-v2-mv-Fast | Guidance Distillation Version | 2025-03-18 | 1.1B | [Download](https://huggingface.co/tencent/Hunyuan3D-2mv/tree/main/hunyuan3d-dit-v2-mv-fast) |
| Hunyuan3D-DiT-v2-mv | Multiview Image to Shape Model | 2025-03-18 | 1.1B | [Download](https://huggingface.co/tencent/Hunyuan3D-2mv/tree/main/hunyuan3d-dit-v2-mv) |
## Hunyuan3D-2 Series
| Model | Description | Date | Size | Huggingface |
|--------------------------|-----------------------------|------------|------|-------------------------------------------------------------------------------------------|
| Hunyuan3D-DiT-v2-0-Turbo | Step Distillation Model | 2025-03-19 | 1.1B | [Download](https://huggingface.co/tencent/Hunyuan3D-2/tree/main/hunyuan3d-dit-v2-0-turbo) |
| Hunyuan3D-DiT-v2-0-Fast | Guidance Distillation Model | 2025-02-03 | 1.1B | [Download](https://huggingface.co/tencent/Hunyuan3D-2/tree/main/hunyuan3d-dit-v2-0-fast) |
| Hunyuan3D-DiT-v2-0 | Image to Shape Model | 2025-01-21 | 1.1B | [Download](https://huggingface.co/tencent/Hunyuan3D-2/tree/main/hunyuan3d-dit-v2-0) |
| Hunyuan3D-Paint-v2-0 | Texture Generation Model | 2025-01-21 | 1.3B | [Download](https://huggingface.co/tencent/Hunyuan3D-2/tree/main/hunyuan3d-paint-v2-0) |
| Hunyuan3D-Delight-v2-0 | Image Delight Model | 2025-01-21 | 1.3B | [Download](https://huggingface.co/tencent/Hunyuan3D-2/tree/main/hunyuan3d-delight-v2-0) |
================================================
FILE: docs/source/started/api.md
================================================
# API
You could launch an API server locally, which you could post web request for Image/Text to 3D, Texturing existing mesh,
and e.t.c.
```bash
python api_server.py --host 0.0.0.0 --port 8080
```
A demo post request for image to 3D without texture.
```bash
img_b64_str=$(base64 -i assets/demo.png)
curl -X POST "http://localhost:8080/generate" \
-H "Content-Type: application/json" \
-d '{
"image": "'"$img_b64_str"'",
}' \
-o test2.glb
```
================================================
FILE: docs/source/started/blender.md
================================================
# Blender Addon
With an API server launched, you could also directly use Hunyuan3D 2.0 in your blender with
our [Blender Addon](blender_addon.py). Please follow our tutorial to install and use.
https://github.com/user-attachments/assets/8230bfb5-32b1-4e48-91f4-a977c54a4f3e
================================================
FILE: docs/source/started/code.md
================================================
# Code
We designed a diffusers-like API to use our shape generation model - Hunyuan3D-DiT and texture synthesis model -
Hunyuan3D-Paint.
You could assess **Hunyuan3D-DiT** via:
```python
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained('tencent/Hunyuan3D-2')
mesh = pipeline(image='assets/demo.png')[0]
```
The output mesh is a [trimesh object](https://trimesh.org/trimesh.html), which you could save to glb/obj (or other
format) file.
For **Hunyuan3D-Paint**, do the following:
```python
from hy3dgen.texgen import Hunyuan3DPaintPipeline
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
# let's generate a mesh first
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained('tencent/Hunyuan3D-2')
mesh = pipeline(image='assets/demo.png')[0]
pipeline = Hunyuan3DPaintPipeline.from_pretrained('tencent/Hunyuan3D-2')
mesh = pipeline(mesh, image='assets/demo.png')
```
Please visit [examples](examples) folder for more advanced usage, such as **multiview image to 3D generation** and *
*texture generation
for handcrafted mesh**.
================================================
FILE: docs/source/started/comfyui.md
================================================
# Comfyui
comfyui
================================================
FILE: docs/source/started/gradio.md
================================================
# Gradio APP
You could also host a [Gradio](https://www.gradio.app/) App in your own computer via:
Standard Version
```bash
# Hunyuan3D-2mini
python3 gradio_app.py --model_path tencent/Hunyuan3D-2mini --subfolder hunyuan3d-dit-v2-mini --texgen_model_path tencent/Hunyuan3D-2 --low_vram_mode
# Hunyuan3D-2mv
python3 gradio_app.py --model_path tencent/Hunyuan3D-2mv --subfolder hunyuan3d-dit-v2-mv --texgen_model_path tencent/Hunyuan3D-2 --low_vram_mode
# Hunyuan3D-2
python3 gradio_app.py --model_path tencent/Hunyuan3D-2 --subfolder hunyuan3d-dit-v2-0 --texgen_model_path tencent/Hunyuan3D-2 --low_vram_mode
```
Turbo Version
```bash
# Hunyuan3D-2mini
python3 gradio_app.py --model_path tencent/Hunyuan3D-2mini --subfolder hunyuan3d-dit-v2-mini-turbo --texgen_model_path tencent/Hunyuan3D-2 --low_vram_mode --enable_flashvdm
# Hunyuan3D-2mv
python3 gradio_app.py --model_path tencent/Hunyuan3D-2mv --subfolder hunyuan3d-dit-v2-mv-turbo --texgen_model_path tencent/Hunyuan3D-2 --low_vram_mode --enable_flashvdm
# Hunyuan3D-2
python3 gradio_app.py --model_path tencent/Hunyuan3D-2 --subfolder hunyuan3d-dit-v2-0-turbo --texgen_model_path tencent/Hunyuan3D-2 --low_vram_mode --enable_flashvdm
```
================================================
FILE: docs/source/started/index.md
================================================
# Get Started
```{toctree}
:hidden:
gradio
comfyui
api
blender
code
studio
```
## Installation
To get started with ∇-Prox, please follow the [Installation Documentation](install) for detailed instructions on how to install the library.
## Quick Tour
- Take a [Quick Tour](quicktour) to get familiar with the features and functionalities of ∇-Prox.
- Explore the [API Reference](../api/index) for a complete list of classes and functions.
- For advanced topics and best practices, refer to the [tutorials](../tutorials/index).
Happy coding with ∇-Prox! 🎉
================================================
FILE: docs/source/started/studio.md
================================================
# Official Website
Don't forget to visit [Hunyuan3D](https://3d.hunyuan.tencent.com) for quick use, if you don't want to host yourself.
================================================
FILE: examples/fast_shape_gen_multiview.py
================================================
import time
import torch
from PIL import Image
from hy3dgen.rembg import BackgroundRemover
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
images = {
"front": "assets/example_mv_images/1/front.png",
"left": "assets/example_mv_images/1/left.png",
"back": "assets/example_mv_images/1/back.png"
}
for key in images:
image = Image.open(images[key]).convert("RGBA")
if image.mode == 'RGB':
rembg = BackgroundRemover()
image = rembg(image)
images[key] = image
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
'tencent/Hunyuan3D-2mv',
subfolder='hunyuan3d-dit-v2-mv-turbo',
variant='fp16'
)
pipeline.enable_flashvdm()
start_time = time.time()
mesh = pipeline(
image=images,
num_inference_steps=5,
octree_resolution=380,
num_chunks=20000,
generator=torch.manual_seed(12345),
output_type='trimesh'
)[0]
print("--- %s seconds ---" % (time.time() - start_time))
mesh.export(f'demo_mv3.glb')
================================================
FILE: examples/fast_shape_gen_with_flashvdm.py
================================================
# HY3DGEN_DEBUG=1 USE_SAGEATTN=1 python3 examples/fast_shape_gen_with_flashvdm.py
# HY3DGEN_DEBUG=1 USE_SAGEATTN=0 python3 examples/fast_shape_gen_with_flashvdm.py
import os
import time
import torch
from PIL import Image
from hy3dgen.rembg import BackgroundRemover
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
'tencent/Hunyuan3D-2',
subfolder='hunyuan3d-dit-v2-0-turbo',
use_safetensors=True,
)
pipeline.enable_flashvdm()
# pipeline.compile()
image_path = 'assets/demo.png'
image = Image.open(image_path).convert("RGBA")
if image.mode == 'RGB':
rembg = BackgroundRemover()
image = rembg(image)
def run():
return pipeline(
image=image,
num_inference_steps=5,
octree_resolution=380,
num_chunks=200000,
generator=torch.manual_seed(12345),
output_type='trimesh'
)[0]
save_dir = 'tmp/results/'
os.makedirs(save_dir, exist_ok=True)
for it in range(2):
start_time = time.time()
mesh = run()
print("--- %s seconds ---" % (time.time() - start_time))
mesh.export(f'{save_dir}/run_{it}.glb')
================================================
FILE: examples/fast_texture_gen_multiview.py
================================================
import time
import torch
from PIL import Image
import trimesh
from hy3dgen.rembg import BackgroundRemover
from hy3dgen.texgen import Hunyuan3DPaintPipeline
images_path = [
"assets/example_mv_images/1/front.png",
"assets/example_mv_images/1/left.png",
"assets/example_mv_images/1/back.png"
]
images = []
for image_path in images_path:
image = Image.open(image_path)
if image.mode == 'RGB':
rembg = BackgroundRemover()
image = rembg(image)
images.append(image)
pipeline = Hunyuan3DPaintPipeline.from_pretrained(
'tencent/Hunyuan3D-2',
subfolder='hunyuan3d-paint-v2-0-turbo'
)
mesh = trimesh.load('assets/1.glb')
mesh = pipeline(mesh, image=images)
mesh.export('demo_textured.glb')
================================================
FILE: examples/faster_shape_gen_with_flashvdm_mini_turbo.py
================================================
# HY3DGEN_DEBUG=1 USE_SAGEATTN=1 python3 examples/faster_shape_gen_with_flashvdm_mini_turbo.py
# HY3DGEN_DEBUG=1 USE_SAGEATTN=0 python3 examples/faster_shape_gen_with_flashvdm_mini_turbo.py
import os
import time
import torch
from PIL import Image
from hy3dgen.rembg import BackgroundRemover
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
device = 'cuda'
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
'tencent/Hunyuan3D-2mini',
subfolder='hunyuan3d-dit-v2-mini-turbo',
use_safetensors=False,
device=device
)
pipeline.enable_flashvdm(topk_mode='merge')
# pipeline.compile()
image_path = 'assets/demo.png'
image = Image.open(image_path).convert("RGBA")
if image.mode == 'RGB':
rembg = BackgroundRemover()
image = rembg(image)
def run():
return pipeline(
image=image,
num_inference_steps=5,
octree_resolution=380,
num_chunks=20000,
generator=torch.manual_seed(12345),
output_type='trimesh'
)[0]
save_dir = 'tmp/results/'
os.makedirs(save_dir, exist_ok=True)
for it in range(2):
start_time = time.time()
mesh = run()
print("--- %s seconds ---" % (time.time() - start_time))
mesh.export(f'{save_dir}/run_{it}.glb')
================================================
FILE: examples/shape_gen.py
================================================
import time
import torch
from PIL import Image
from hy3dgen.rembg import BackgroundRemover
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
image_path = 'assets/demo.png'
image = Image.open(image_path).convert("RGBA")
if image.mode == 'RGB':
rembg = BackgroundRemover()
image = rembg(image)
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
'tencent/Hunyuan3D-2',
subfolder='hunyuan3d-dit-v2-0',
variant='fp16'
)
start_time = time.time()
mesh = pipeline(image=image,
num_inference_steps=50,
octree_resolution=380,
num_chunks=20000,
generator=torch.manual_seed(12345),
output_type='trimesh'
)[0]
print("--- %s seconds ---" % (time.time() - start_time))
mesh.export(f'demo.glb')
================================================
FILE: examples/shape_gen_mini.py
================================================
import time
import torch
from PIL import Image
from hy3dgen.rembg import BackgroundRemover
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
image_path = 'assets/demo.png'
image = Image.open(image_path).convert("RGBA")
if image.mode == 'RGB':
rembg = BackgroundRemover()
image = rembg(image)
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
'tencent/Hunyuan3D-2mini',
subfolder='hunyuan3d-dit-v2-mini',
variant='fp16'
)
start_time = time.time()
mesh = pipeline(
image=image,
num_inference_steps=50,
octree_resolution=380,
num_chunks=20000,
generator=torch.manual_seed(12345),
output_type='trimesh'
)[0]
print("--- %s seconds ---" % (time.time() - start_time))
mesh.export(f'demo_mini.glb')
================================================
FILE: examples/shape_gen_multiview.py
================================================
import time
import torch
from PIL import Image
from hy3dgen.rembg import BackgroundRemover
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
images = {
"front": "assets/example_mv_images/1/front.png",
"left": "assets/example_mv_images/1/left.png",
"back": "assets/example_mv_images/1/back.png"
}
for key in images:
image = Image.open(images[key]).convert("RGBA")
if image.mode == 'RGB':
rembg = BackgroundRemover()
image = rembg(image)
images[key] = image
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
'tencent/Hunyuan3D-2mv',
subfolder='hunyuan3d-dit-v2-mv',
variant='fp16'
)
start_time = time.time()
mesh = pipeline(
image=images,
num_inference_steps=50,
octree_resolution=380,
num_chunks=20000,
generator=torch.manual_seed(12345),
output_type='trimesh'
)[0]
print("--- %s seconds ---" % (time.time() - start_time))
mesh.export(f'demo_mv.glb')
================================================
FILE: examples/shape_gen_v2_1.py
================================================
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
# except for the third-party components listed below.
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
# in the repsective licenses of these third-party components.
# Users must comply with all terms and conditions of original licenses of these third-party
# components and must ensure that the usage of the third party components adheres to
# all relevant laws and regulations.
# For avoidance of doubts, Hunyuan 3D means the large language models and
# their software and algorithms, including trained model weights, parameters (including
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
# fine-tuning enabling code and other elements of the foregoing made publicly available
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
from PIL import Image
from hy3dgen.rembg import BackgroundRemover
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
model_path = 'tencent/Hunyuan3D-2.1'
pipeline_shapegen = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
model_path,
subfolder='hunyuan3d-dit-v2-1'
)
image_path = 'assets/demo.png'
image = Image.open(image_path).convert("RGBA")
if image.mode == 'RGB':
rembg = BackgroundRemover()
image = rembg(image)
mesh = pipeline_shapegen(image=image)[0]
mesh.export('demo.glb')
================================================
FILE: examples/textured_shape_gen.py
================================================
from PIL import Image
from hy3dgen.rembg import BackgroundRemover
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
from hy3dgen.texgen import Hunyuan3DPaintPipeline
model_path = 'tencent/Hunyuan3D-2'
pipeline_shapegen = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(model_path)
pipeline_texgen = Hunyuan3DPaintPipeline.from_pretrained(model_path)
image_path = 'assets/demo.png'
image = Image.open(image_path).convert("RGBA")
if image.mode == 'RGB':
rembg = BackgroundRemover()
image = rembg(image)
mesh = pipeline_shapegen(image=image)[0]
mesh = pipeline_texgen(mesh, image=image)
mesh.export('demo.glb')
================================================
FILE: examples/textured_shape_gen_mini.py
================================================
import time
import torch
from PIL import Image
from hy3dgen.rembg import BackgroundRemover
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
from hy3dgen.texgen import Hunyuan3DPaintPipeline
image_path = 'assets/demo.png'
image = Image.open(image_path).convert("RGBA")
if image.mode == 'RGB':
rembg = BackgroundRemover()
image = rembg(image)
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
'tencent/Hunyuan3D-2mini',
subfolder='hunyuan3d-dit-v2-mini',
variant='fp16'
)
pipeline_texgen = Hunyuan3DPaintPipeline.from_pretrained('tencent/Hunyuan3D-2')
start_time = time.time()
mesh = pipeline(
image=image,
num_inference_steps=50,
octree_resolution=380,
num_chunks=20000,
generator=torch.manual_seed(12345),
output_type='trimesh'
)[0]
print("--- %s seconds ---" % (time.time() - start_time))
mesh.export(f'demo_mini.glb')
mesh = pipeline_texgen(mesh, image=image)
mesh.export('demo_textured_mini.glb')
================================================
FILE: examples/textured_shape_gen_multiview.py
================================================
import time
import torch
from PIL import Image
from hy3dgen.rembg import BackgroundRemover
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
from hy3dgen.texgen import Hunyuan3DPaintPipeline
images = {
"front": "assets/example_mv_images/1/front.png",
"left": "assets/example_mv_images/1/left.png",
"back": "assets/example_mv_images/1/back.png"
}
for key in images:
image = Image.open(images[key]).convert("RGBA")
if image.mode == 'RGB':
rembg = BackgroundRemover()
image = rembg(image)
images[key] = image
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
'tencent/Hunyuan3D-2mv',
subfolder='hunyuan3d-dit-v2-mv',
variant='fp16'
)
pipeline_texgen = Hunyuan3DPaintPipeline.from_pretrained('tencent/Hunyuan3D-2')
start_time = time.time()
mesh = pipeline(
image=images,
num_inference_steps=50,
octree_resolution=380,
num_chunks=20000,
generator=torch.manual_seed(12345),
output_type='trimesh'
)[0]
print("--- %s seconds ---" % (time.time() - start_time))
mesh.export(f'demo_white_mesh_mv.glb')
mesh = pipeline_texgen(mesh, image=images["front"])
mesh.export('demo_textured_mv.glb')
================================================
FILE: gradio_app.py
================================================
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
# except for the third-party components listed below.
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
# in the repsective licenses of these third-party components.
# Users must comply with all terms and conditions of original licenses of these third-party
# components and must ensure that the usage of the third party components adheres to
# all relevant laws and regulations.
# For avoidance of doubts, Hunyuan 3D means the large language models and
# their software and algorithms, including trained model weights, parameters (including
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
# fine-tuning enabling code and other elements of the foregoing made publicly available
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
import os
import random
import shutil
import time
from glob import glob
from pathlib import Path
import gradio as gr
import torch
import trimesh
import uvicorn
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
import uuid
from hy3dgen.shapegen.utils import logger
MAX_SEED = int(1e7)
def get_example_img_list():
print('Loading example img list ...')
return sorted(glob('./assets/example_images/**/*.png', recursive=True))
def get_example_txt_list():
print('Loading example txt list ...')
txt_list = list()
for line in open('./assets/example_prompts.txt', encoding='utf-8'):
txt_list.append(line.strip())
return txt_list
def get_example_mv_list():
print('Loading example mv list ...')
mv_list = list()
root = './assets/example_mv_images'
for mv_dir in os.listdir(root):
view_list = []
for view in ['front', 'back', 'left', 'right']:
path = os.path.join(root, mv_dir, f'{view}.png')
if os.path.exists(path):
view_list.append(path)
else:
view_list.append(None)
mv_list.append(view_list)
return mv_list
def gen_save_folder(max_size=200):
os.makedirs(SAVE_DIR, exist_ok=True)
# 获取所有文件夹路径
dirs = [f for f in Path(SAVE_DIR).iterdir() if f.is_dir()]
# 如果文件夹数量超过 max_size,删除创建时间最久的文件夹
if len(dirs) >= max_size:
# 按创建时间排序,最久的排在前面
oldest_dir = min(dirs, key=lambda x: x.stat().st_ctime)
shutil.rmtree(oldest_dir)
print(f"Removed the oldest folder: {oldest_dir}")
# 生成一个新的 uuid 文件夹名称
new_folder = os.path.join(SAVE_DIR, str(uuid.uuid4()))
os.makedirs(new_folder, exist_ok=True)
print(f"Created new folder: {new_folder}")
return new_folder
def export_mesh(mesh, save_folder, textured=False, type='glb'):
if textured:
path = os.path.join(save_folder, f'textured_mesh.{type}')
else:
path = os.path.join(save_folder, f'white_mesh.{type}')
if type not in ['glb', 'obj']:
mesh.export(path)
else:
mesh.export(path, include_normals=textured)
return path
def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
if randomize_seed:
seed = random.randint(0, MAX_SEED)
return seed
def build_model_viewer_html(save_folder, height=660, width=790, textured=False):
# Remove first folder from path to make relative path
if textured:
related_path = f"./textured_mesh.glb"
template_name = './assets/modelviewer-textured-template.html'
output_html_path = os.path.join(save_folder, f'textured_mesh.html')
else:
related_path = f"./white_mesh.glb"
template_name = './assets/modelviewer-template.html'
output_html_path = os.path.join(save_folder, f'white_mesh.html')
offset = 50 if textured else 10
with open(os.path.join(CURRENT_DIR, template_name), 'r', encoding='utf-8') as f:
template_html = f.read()
with open(output_html_path, 'w', encoding='utf-8') as f:
template_html = template_html.replace('#height#', f'{height - offset}')
template_html = template_html.replace('#width#', f'{width}')
template_html = template_html.replace('#src#', f'{related_path}/')
f.write(template_html)
rel_path = os.path.relpath(output_html_path, SAVE_DIR)
iframe_tag = f'<iframe src="/static/{rel_path}" height="{height}" width="100%" frameborder="0"></iframe>'
print(
f'Find html file {output_html_path}, {os.path.exists(output_html_path)}, relative HTML path is /static/{rel_path}')
return f"""
<div style='height: {height}; width: 100%;'>
{iframe_tag}
</div>
"""
def _gen_shape(
caption=None,
image=None,
mv_image_front=None,
mv_image_back=None,
mv_image_left=None,
mv_image_right=None,
steps=50,
guidance_scale=7.5,
seed=1234,
octree_resolution=256,
check_box_rembg=False,
num_chunks=200000,
randomize_seed: bool = False,
):
if not MV_MODE and image is None and caption is None:
raise gr.Error("Please provide either a caption or an image.")
if MV_MODE:
if mv_image_front is None and mv_image_back is None and mv_image_left is None and mv_image_right is None:
raise gr.Error("Please provide at least one view image.")
image = {}
if mv_image_front:
image['front'] = mv_image_front
if mv_image_back:
image['back'] = mv_image_back
if mv_image_left:
image['left'] = mv_image_left
if mv_image_right:
image['right'] = mv_image_right
seed = int(randomize_seed_fn(seed, randomize_seed))
octree_resolution = int(octree_resolution)
if caption: print('prompt is', caption)
save_folder = gen_save_folder()
stats = {
'model': {
'shapegen': f'{args.model_path}/{args.subfolder}',
'texgen': f'{args.texgen_model_path}',
},
'params': {
'caption': caption,
'steps': steps,
'guidance_scale': guidance_scale,
'seed': seed,
'octree_resolution': octree_resolution,
'check_box_rembg': check_box_rembg,
'num_chunks': num_chunks,
}
}
time_meta = {}
if image is None:
start_time = time.time()
try:
image = t2i_worker(caption)
except Exception as e:
raise gr.Error(f"Text to 3D is disable. Please enable it by `python gradio_app.py --enable_t23d`.")
time_meta['text2image'] = time.time() - start_time
# remove disk io to make responding faster, uncomment at your will.
# image.save(os.path.join(save_folder, 'input.png'))
if MV_MODE:
start_time = time.time()
for k, v in image.items():
if check_box_rembg or v.mode == "RGB":
img = rmbg_worker(v.convert('RGB'))
image[k] = img
time_meta['remove background'] = time.time() - start_time
else:
if check_box_rembg or image.mode == "RGB":
start_time = time.time()
image = rmbg_worker(image.convert('RGB'))
time_meta['remove background'] = time.time() - start_time
# remove disk io to make responding faster, uncomment at your will.
# image.save(os.path.join(save_folder, 'rembg.png'))
# image to white model
start_time = time.time()
generator = torch.Generator()
generator = generator.manual_seed(int(seed))
outputs = i23d_worker(
image=image,
num_inference_steps=steps,
guidance_scale=guidance_scale,
generator=generator,
octree_resolution=octree_resolution,
num_chunks=num_chunks,
output_type='mesh'
)
time_meta['shape generation'] = time.time() - start_time
logger.info("---Shape generation takes %s seconds ---" % (time.time() - start_time))
tmp_start = time.time()
mesh = export_to_trimesh(outputs)[0]
time_meta['export to trimesh'] = time.time() - tmp_start
stats['number_of_faces'] = mesh.faces.shape[0]
stats['number_of_vertices'] = mesh.vertices.shape[0]
stats['time'] = time_meta
main_image = image if not MV_MODE else image['front']
return mesh, main_image, save_folder, stats, seed
def generation_all(
caption=None,
image=None,
mv_image_front=None,
mv_image_back=None,
mv_image_left=None,
mv_image_right=None,
steps=50,
guidance_scale=7.5,
seed=1234,
octree_resolution=256,
check_box_rembg=False,
num_chunks=200000,
randomize_seed: bool = False,
):
start_time_0 = time.time()
mesh, image, save_folder, stats, seed = _gen_shape(
caption,
image,
mv_image_front=mv_image_front,
mv_image_back=mv_image_back,
mv_image_left=mv_image_left,
mv_image_right=mv_image_right,
steps=steps,
guidance_scale=guidance_scale,
seed=seed,
octree_resolution=octree_resolution,
check_box_rembg=check_box_rembg,
num_chunks=num_chunks,
randomize_seed=randomize_seed,
)
path = export_mesh(mesh, save_folder, textured=False)
# tmp_time = time.time()
# mesh = floater_remove_worker(mesh)
# mesh = degenerate_face_remove_worker(mesh)
# logger.info("---Postprocessing takes %s seconds ---" % (time.time() - tmp_time))
# stats['time']['postprocessing'] = time.time() - tmp_time
tmp_time = time.time()
mesh = face_reduce_worker(mesh)
logger.info("---Face Reduction takes %s seconds ---" % (time.time() - tmp_time))
stats['time']['face reduction'] = time.time() - tmp_time
tmp_time = time.time()
textured_mesh = texgen_worker(mesh, image)
logger.info("---Texture Generation takes %s seconds ---" % (time.time() - tmp_time))
stats['time']['texture generation'] = time.time() - tmp_time
stats['time']['total'] = time.time() - start_time_0
textured_mesh.metadata['extras'] = stats
path_textured = export_mesh(textured_mesh, save_folder, textured=True)
model_viewer_html_textured = build_model_viewer_html(save_folder, height=HTML_HEIGHT, width=HTML_WIDTH,
textured=True)
if args.low_vram_mode:
torch.cuda.empty_cache()
return (
gr.update(value=path),
gr.update(value=path_textured),
model_viewer_html_textured,
stats,
seed,
)
def shape_generation(
caption=None,
image=None,
mv_image_front=None,
mv_image_back=None,
mv_image_left=None,
mv_image_right=None,
steps=50,
guidance_scale=7.5,
seed=1234,
octree_resolution=256,
check_box_rembg=False,
num_chunks=200000,
randomize_seed: bool = False,
):
start_time_0 = time.time()
mesh, image, save_folder, stats, seed = _gen_shape(
caption,
image,
mv_image_front=mv_image_front,
mv_image_back=mv_image_back,
mv_image_left=mv_image_left,
mv_image_right=mv_image_right,
steps=steps,
guidance_scale=guidance_scale,
seed=seed,
octree_resolution=octree_resolution,
check_box_rembg=check_box_rembg,
num_chunks=num_chunks,
randomize_seed=randomize_seed,
)
stats['time']['total'] = time.time() - start_time_0
mesh.metadata['extras'] = stats
path = export_mesh(mesh, save_folder, textured=False)
model_viewer_html = build_model_viewer_html(save_folder, height=HTML_HEIGHT, width=HTML_WIDTH)
if args.low_vram_mode:
torch.cuda.empty_cache()
return (
gr.update(value=path),
model_viewer_html,
stats,
seed,
)
def build_app():
title = 'Hunyuan3D-2: High Resolution Textured 3D Assets Generation'
if MV_MODE:
title = 'Hunyuan3D-2mv: Image to 3D Generation with 1-4 Views'
if 'mini' in args.subfolder:
title = 'Hunyuan3D-2mini: Strong 0.6B Image to Shape Generator'
if TURBO_MODE:
title = title.replace(':', '-Turbo: Fast ')
title_html = f"""
<div style="font-size: 2em; font-weight: bold; text-align: center; margin-bottom: 5px">
{title}
</div>
<div align="center">
Tencent Hunyuan3D Team
</div>
<div align="center">
<a href="https://github.com/tencent/Hunyuan3D-2">Github</a>  
<a href="http://3d-models.hunyuan.tencent.com">Homepage</a>  
<a href="https://3d.hunyuan.tencent.com">Hunyuan3D Studio</a>  
<a href="#">Technical Report</a>  
<a href="https://huggingface.co/Tencent/Hunyuan3D-2"> Pretrained Models</a>  
</div>
"""
custom_css = """
.app.svelte-wpkpf6.svelte-wpkpf6:not(.fill_width) {
max-width: 1480px;
}
.mv-image button .wrap {
font-size: 10px;
}
.mv-image .icon-wrap {
width: 20px;
}
"""
with gr.Blocks(theme=gr.themes.Base(), title='Hunyuan-3D-2.0', analytics_enabled=False, css=custom_css) as demo:
gr.HTML(title_html)
with gr.Row():
with gr.Column(scale=3):
with gr.Tabs(selected='tab_img_prompt') as tabs_prompt:
with gr.Tab('Image Prompt', id='tab_img_prompt', visible=not MV_MODE) as tab_ip:
image = gr.Image(label='Image', type='pil', image_mode='RGBA', height=290)
with gr.Tab('Text Prompt', id='tab_txt_prompt', visible=HAS_T2I and not MV_MODE) as tab_tp:
caption = gr.Textbox(label='Text Prompt',
placeholder='HunyuanDiT will be used to generate image.',
info='Example: A 3D model of a cute cat, white background')
with gr.Tab('MultiView Prompt', visible=MV_MODE) as tab_mv:
# gr.Label('Please upload at least one front image.')
with gr.Row():
mv_image_front = gr.Image(label='Front', type='pil', image_mode='RGBA', height=140,
min_width=100, elem_classes='mv-image')
mv_image_back = gr.Image(label='Back', type='pil', image_mode='RGBA', height=140,
min_width=100, elem_classes='mv-image')
with gr.Row():
mv_image_left = gr.Image(label='Left', type='pil', image_mode='RGBA', height=140,
min_width=100, elem_classes='mv-image')
mv_image_right = gr.Image(label='Right', type='pil', image_mode='RGBA', height=140,
min_width=100, elem_classes='mv-image')
with gr.Row():
btn = gr.Button(value='Gen Shape', variant='primary', min_width=100)
btn_all = gr.Button(value='Gen Textured Shape',
variant='primary',
visible=HAS_TEXTUREGEN,
min_width=100)
with gr.Group():
file_out = gr.File(label="File", visible=False)
file_out2 = gr.File(label="File", visible=False)
with gr.Tabs(selected='tab_options' if TURBO_MODE else 'tab_export'):
with gr.Tab("Options", id='tab_options', visible=TURBO_MODE):
gen_mode = gr.Radio(label='Generation Mode',
info='Recommendation: Turbo for most cases, Fast for very complex cases, Standard seldom use.',
choices=['Turbo', 'Fast', 'Standard'], value='Turbo')
decode_mode = gr.Radio(label='Decoding Mode',
info='The resolution for exporting mesh from generated vectset',
choices=['Low', 'Standard', 'High'],
value='Standard')
with gr.Tab('Advanced Options', id='tab_advanced_options'):
with gr.Row():
check_box_rembg = gr.Checkbox(value=True, label='Remove Background', min_width=100)
randomize_seed = gr.Checkbox(label="Randomize seed", value=True, min_width=100)
seed = gr.Slider(
label="Seed",
minimum=0,
maximum=MAX_SEED,
step=1,
value=1234,
min_width=100,
)
with gr.Row():
num_steps = gr.Slider(maximum=100,
minimum=1,
value=5 if 'turbo' in args.subfolder else 30,
step=1, label='Inference Steps')
octree_resolution = gr.Slider(maximum=512, minimum=16, value=256, label='Octree Resolution')
with gr.Row():
cfg_scale = gr.Number(value=5.0, label='Guidance Scale', min_width=100)
num_chunks = gr.Slider(maximum=5000000, minimum=1000, value=8000,
label='Number of Chunks', min_width=100)
with gr.Tab("Export", id='tab_export'):
with gr.Row():
file_type = gr.Dropdown(label='File Type', choices=SUPPORTED_FORMATS,
value='glb', min_width=100)
reduce_face = gr.Checkbox(label='Simplify Mesh', value=False, min_width=100)
export_texture = gr.Checkbox(label='Include Texture', value=False,
visible=False, min_width=100)
target_face_num = gr.Slider(maximum=1000000, minimum=100, value=10000,
label='Target Face Number')
with gr.Row():
confirm_export = gr.Button(value="Transform", min_width=100)
file_export = gr.DownloadButton(label="Download", variant='primary',
interactive=False, min_width=100)
with gr.Column(scale=6):
with gr.Tabs(selected='gen_mesh_panel') as tabs_output:
with gr.Tab('Generated Mesh', id='gen_mesh_panel'):
html_gen_mesh = gr.HTML(HTML_OUTPUT_PLACEHOLDER, label='Output')
with gr.Tab('Exporting Mesh', id='export_mesh_panel'):
html_export_mesh = gr.HTML(HTML_OUTPUT_PLACEHOLDER, label='Output')
with gr.Tab('Mesh Statistic', id='stats_panel'):
stats = gr.Json({}, label='Mesh Stats')
with gr.Column(scale=3 if MV_MODE else 2):
with gr.Tabs(selected='tab_img_gallery') as gallery:
with gr.Tab('Image to 3D Gallery', id='tab_img_gallery', visible=not MV_MODE) as tab_gi:
with gr.Row():
gr.Examples(examples=example_is, inputs=[image],
label=None, examples_per_page=18)
with gr.Tab('Text to 3D Gallery', id='tab_txt_gallery', visible=HAS_T2I and not MV_MODE) as tab_gt:
with gr.Row():
gr.Examples(examples=example_ts, inputs=[caption],
label=None, examples_per_page=18)
with gr.Tab('MultiView to 3D Gallery', id='tab_mv_gallery', visible=MV_MODE) as tab_mv:
with gr.Row():
gr.Examples(examples=example_mvs,
inputs=[mv_image_front, mv_image_back, mv_image_left, mv_image_right],
label=None, examples_per_page=6)
gr.HTML(f"""
<div align="center">
Activated Model - Shape Generation ({args.model_path}/{args.subfolder}) ; Texture Generation ({'Hunyuan3D-2' if HAS_TEXTUREGEN else 'Unavailable'})
</div>
""")
if not HAS_TEXTUREGEN:
gr.HTML("""
<div style="margin-top: 5px;" align="center">
<b>Warning: </b>
Texture synthesis is disable due to missing requirements,
please install requirements following <a href="https://github.com/Tencent/Hunyuan3D-2?tab=readme-ov-file#install-requirements">README.md</a>to activate it.
</div>
""")
if not args.enable_t23d:
gr.HTML("""
<div style="margin-top: 5px;" align="center">
<b>Warning: </b>
Text to 3D is disable. To activate it, please run `python gradio_app.py --enable_t23d`.
</div>
""")
tab_ip.select(fn=lambda: gr.update(selected='tab_img_gallery'), outputs=gallery)
if HAS_T2I:
tab_tp.select(fn=lambda: gr.update(selected='tab_txt_gallery'), outputs=gallery)
btn.click(
shape_generation,
inputs=[
caption,
image,
mv_image_front,
mv_image_back,
mv_image_left,
mv_image_right,
num_steps,
cfg_scale,
seed,
octree_resolution,
check_box_rembg,
num_chunks,
randomize_seed,
],
outputs=[file_out, html_gen_mesh, stats, seed]
).then(
lambda: (gr.update(visible=False, value=False), gr.update(interactive=True), gr.update(interactive=True),
gr.update(interactive=False)),
outputs=[export_texture, reduce_face, confirm_export, file_export],
).then(
lambda: gr.update(selected='gen_mesh_panel'),
outputs=[tabs_output],
)
btn_all.click(
generation_all,
inputs=[
caption,
image,
mv_image_front,
mv_image_back,
mv_image_left,
mv_image_right,
num_steps,
cfg_scale,
seed,
octree_resolution,
check_box_rembg,
num_chunks,
randomize_seed,
],
outputs=[file_out, file_out2, html_gen_mesh, stats, seed]
).then(
lambda: (gr.update(visible=True, value=True), gr.update(interactive=False), gr.update(interactive=True),
gr.update(interactive=False)),
outputs=[export_texture, reduce_face, confirm_export, file_export],
).then(
lambda: gr.update(selected='gen_mesh_panel'),
outputs=[tabs_output],
)
def on_gen_mode_change(value):
if value == 'Turbo':
return gr.update(value=5)
elif value == 'Fast':
return gr.update(value=10)
else:
return gr.update(value=30)
gen_mode.change(on_gen_mode_change, inputs=[gen_mode], outputs=[num_steps])
def on_decode_mode_change(value):
if value == 'Low':
return gr.update(value=196)
elif value == 'Standard':
return gr.update(value=256)
else:
return gr.update(value=384)
decode_mode.change(on_decode_mode_change, inputs=[decode_mode], outputs=[octree_resolution])
def on_export_click(file_out, file_out2, file_type, reduce_face, export_texture, target_face_num):
if file_out is None:
raise gr.Error('Please generate a mesh first.')
print(f'exporting {file_out}')
print(f'reduce face to {target_face_num}')
if export_texture:
mesh = trimesh.load(file_out2)
save_folder = gen_save_folder()
path = export_mesh(mesh, save_folder, textured=True, type=file_type)
# for preview
save_folder = gen_save_folder()
_ = export_mesh(mesh, save_folder, textured=True)
model_viewer_html = build_model_viewer_html(save_folder, height=HTML_HEIGHT, width=HTML_WIDTH,
textured=True)
else:
mesh = trimesh.load(file_out)
mesh = floater_remove_worker(mesh)
mesh = degenerate_face_remove_worker(mesh)
if reduce_face:
mesh = face_reduce_worker(mesh, target_face_num)
save_folder = gen_save_folder()
path = export_mesh(mesh, save_folder, textured=False, type=file_type)
# for preview
save_folder = gen_save_folder()
_ = export_mesh(mesh, save_folder, textured=False)
model_viewer_html = build_model_viewer_html(save_folder, height=HTML_HEIGHT, width=HTML_WIDTH,
textured=False)
print(f'export to {path}')
return model_viewer_html, gr.update(value=path, interactive=True)
confirm_export.click(
lambda: gr.update(selected='export_mesh_panel'),
outputs=[tabs_output],
).then(
on_export_click,
inputs=[file_out, file_out2, file_type, reduce_face, export_texture, target_face_num],
outputs=[html_export_mesh, file_export]
)
return demo
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--model_path", type=str, default='tencent/Hunyuan3D-2mini')
parser.add_argument("--subfolder", type=str, default='hunyuan3d-dit-v2-mini-turbo')
parser.add_argument("--texgen_model_path", type=str, default='tencent/Hunyuan3D-2')
parser.add_argument('--port', type=int, default=8080)
parser.add_argument('--host', type=str, default='0.0.0.0')
parser.add_argument('--device', type=str, default='cuda')
parser.add_argument('--mc_algo', type=str, default='mc')
parser.add_argument('--cache-path', type=str, default='gradio_cache')
parser.add_argument('--enable_t23d', action='store_true')
parser.add_argument('--disable_tex', action='store_true')
parser.add_argument('--enable_flashvdm', action='store_true')
parser.add_argument('--compile', action='store_true')
parser.add_argument('--low_vram_mode', action='store_true')
args = parser.parse_args()
SAVE_DIR = args.cache_path
os.makedirs(SAVE_DIR, exist_ok=True)
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
MV_MODE = 'mv' in args.model_path
TURBO_MODE = 'turbo' in args.subfolder
HTML_HEIGHT = 690 if MV_MODE else 650
HTML_WIDTH = 500
HTML_OUTPUT_PLACEHOLDER = f"""
<div style='height: {650}px; width: 100%; border-radius: 8px; border-color: #e5e7eb; border-style: solid; border-width: 1px; display: flex; justify-content: center; align-items: center;'>
<div style='text-align: center; font-size: 16px; color: #6b7280;'>
<p style="color: #8d8d8d;">Welcome to Hunyuan3D!</p>
<p style="color: #8d8d8d;">No mesh here.</p>
</div>
</div>
"""
INPUT_MESH_HTML = """
<div style='height: 490px; width: 100%; border-radius: 8px;
border-color: #e5e7eb; order-style: solid; border-width: 1px;'>
</div>
"""
example_is = get_example_img_list()
example_ts = get_example_txt_list()
example_mvs = get_example_mv_list()
SUPPORTED_FORMATS = ['glb', 'obj', 'ply', 'stl']
HAS_TEXTUREGEN = False
if not args.disable_tex:
try:
from hy3dgen.texgen import Hunyuan3DPaintPipeline
texgen_worker = Hunyuan3DPaintPipeline.from_pretrained(args.texgen_model_path)
if args.low_vram_mode:
texgen_worker.enable_model_cpu_offload()
# Not help much, ignore for now.
# if args.compile:
# texgen_worker.models['delight_model'].pipeline.unet.compile()
# texgen_worker.models['delight_model'].pipeline.vae.compile()
# texgen_worker.models['multiview_model'].pipeline.unet.compile()
# texgen_worker.models['multiview_model'].pipeline.vae.compile()
HAS_TEXTUREGEN = True
except Exception as e:
print(e)
print("Failed to load texture generator.")
print('Please try to install requirements by following README.md')
HAS_TEXTUREGEN = False
HAS_T2I = True
if args.enable_t23d:
from hy3dgen.text2image import HunyuanDiTPipeline
t2i_worker = HunyuanDiTPipeline('Tencent-Hunyuan/HunyuanDiT-v1.1-Diffusers-Distilled', device=args.device)
HAS_T2I = True
from hy3dgen.shapegen import FaceReducer, FloaterRemover, DegenerateFaceRemover, MeshSimplifier, \
Hunyuan3DDiTFlowMatchingPipeline
from hy3dgen.shapegen.pipelines import export_to_trimesh
from hy3dgen.rembg import BackgroundRemover
rmbg_worker = BackgroundRemover()
i23d_worker = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained(
args.model_path,
subfolder=args.subfolder,
use_safetensors=True,
device=args.device,
)
if args.enable_flashvdm:
mc_algo = 'mc' if args.device in ['cpu', 'mps'] else args.mc_algo
i23d_worker.enable_flashvdm(mc_algo=mc_algo)
if args.compile:
i23d_worker.compile()
floater_remove_worker = FloaterRemover()
degenerate_face_remove_worker = DegenerateFaceRemover()
face_reduce_worker = FaceReducer()
# https://discuss.huggingface.co/t/how-to-serve-an-html-file/33921/2
# create a FastAPI app
app = FastAPI()
# create a static directory to store the static files
static_dir = Path(SAVE_DIR).absolute()
static_dir.mkdir(parents=True, exist_ok=True)
app.mount("/static", StaticFiles(directory=static_dir, html=True), name="static")
shutil.copytree('./assets/env_maps', os.path.join(static_dir, 'env_maps'), dirs_exist_ok=True)
if args.low_vram_mode:
torch.cuda.empty_cache()
demo = build_app()
app = gr.mount_gradio_app(app, demo, path="/")
uvicorn.run(app, host=args.host, port=args.port, workers=1)
================================================
FILE: hy3dgen/__init__.py
================================================
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
# except for the third-party components listed below.
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
# in the repsective licenses of these third-party components.
# Users must comply with all terms and conditions of original licenses of these third-party
# components and must ensure that the usage of the third party components adheres to
# all relevant laws and regulations.
# For avoidance of doubts, Hunyuan 3D means the large language models and
# their software and algorithms, including trained model weights, parameters (including
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
# fine-tuning enabling code and other elements of the foregoing made publicly available
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
================================================
FILE: hy3dgen/rembg.py
================================================
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
# except for the third-party components listed below.
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
# in the repsective licenses of these third-party components.
# Users must comply with all terms and conditions of original licenses of these third-party
# components and must ensure that the usage of the third party components adheres to
# all relevant laws and regulations.
# For avoidance of doubts, Hunyuan 3D means the large language models and
# their software and algorithms, including trained model weights, parameters (including
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
# fine-tuning enabling code and other elements of the foregoing made publicly available
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
from PIL import Image
from rembg import remove, new_session
class BackgroundRemover():
def __init__(self):
self.session = new_session()
def __call__(self, image: Image.Image):
output = remove(image, session=self.session, bgcolor=[255, 255, 255, 0])
return output
================================================
FILE: hy3dgen/shapegen/__init__.py
================================================
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
# except for the third-party components listed below.
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
# in the repsective licenses of these third-party components.
# Users must comply with all terms and conditions of original licenses of these third-party
# components and must ensure that the usage of the third party components adheres to
# all relevant laws and regulations.
# For avoidance of doubts, Hunyuan 3D means the large language models and
# their software and algorithms, including trained model weights, parameters (including
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
# fine-tuning enabling code and other elements of the foregoing made publicly available
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
from .pipelines import Hunyuan3DDiTPipeline, Hunyuan3DDiTFlowMatchingPipeline
from .postprocessors import FaceReducer, FloaterRemover, DegenerateFaceRemover, MeshSimplifier
from .preprocessors import ImageProcessorV2, IMAGE_PROCESSORS, DEFAULT_IMAGEPROCESSOR
================================================
FILE: hy3dgen/shapegen/models/__init__.py
================================================
# Open Source Model Licensed under the Apache License Version 2.0
# and Other Licenses of the Third-Party Components therein:
# The below Model in this distribution may have been modified by THL A29 Limited
# ("Tencent Modifications"). All Tencent Modifications are Copyright (C) 2024 THL A29 Limited.
# Copyright (C) 2024 THL A29 Limited, a Tencent company. All rights reserved.
# The below software and/or models in this distribution may have been
# modified by THL A29 Limited ("Tencent Modifications").
# All Tencent Modifications are Copyright (C) THL A29 Limited.
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
# except for the third-party components listed below.
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
# in the repsective licenses of these third-party components.
# Users must comply with all terms and conditions of original licenses of these third-party
# components and must ensure that the usage of the third party components adheres to
# all relevant laws and regulations.
# For avoidance of doubts, Hunyuan 3D means the large language models and
# their software and algorithms, including trained model weights, parameters (including
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
# fine-tuning enabling code and other elements of the foregoing made publicly available
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
from .autoencoders import ShapeVAE
from .conditioner import DualImageEncoder, SingleImageEncoder, DinoImageEncoder, CLIPImageEncoder
from .denoisers import Hunyuan3DDiT
================================================
FILE: hy3dgen/shapegen/models/autoencoders/__init__.py
================================================
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
# except for the third-party components listed below.
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
# in the repsective licenses of these third-party components.
# Users must comply with all terms and conditions of original licenses of these third-party
# components and must ensure that the usage of the third party components adheres to
# all relevant laws and regulations.
# For avoidance of doubts, Hunyuan 3D means the large language models and
# their software and algorithms, including trained model weights, parameters (including
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
# fine-tuning enabling code and other elements of the foregoing made publicly available
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
from .attention_blocks import CrossAttentionDecoder
from .attention_processors import FlashVDMCrossAttentionProcessor, CrossAttentionProcessor, \
FlashVDMTopMCrossAttentionProcessor
from .model import ShapeVAE, VectsetVAE
from .surface_extractors import SurfaceExtractors, MCSurfaceExtractor, DMCSurfaceExtractor, Latent2MeshOutput
from .volume_decoders import HierarchicalVolumeDecoding, FlashVDMVolumeDecoding, VanillaVolumeDecoder
================================================
FILE: hy3dgen/shapegen/models/autoencoders/attention_blocks.py
================================================
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
# except for the third-party components listed below.
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
# in the repsective licenses of these third-party components.
# Users must comply with all terms and conditions of original licenses of these third-party
# components and must ensure that the usage of the third party components adheres to
# all relevant laws and regulations.
# For avoidance of doubts, Hunyuan 3D means the large language models and
# their software and algorithms, including trained model weights, parameters (including
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
# fine-tuning enabling code and other elements of the foregoing made publicly available
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
import os
from typing import Optional, Union, List
import torch
import torch.nn as nn
from einops import rearrange
from torch import Tensor
from .attention_processors import CrossAttentionProcessor
from ...utils import logger
scaled_dot_product_attention = nn.functional.scaled_dot_product_attention
if os.environ.get('USE_SAGEATTN', '0') == '1':
try:
from sageattention import sageattn
except ImportError:
raise ImportError('Please install the package "sageattention" to use this USE_SAGEATTN.')
scaled_dot_product_attention = sageattn
class FourierEmbedder(nn.Module):
"""The sin/cosine positional embedding. Given an input tensor `x` of shape [n_batch, ..., c_dim], it converts
each feature dimension of `x[..., i]` into:
[
sin(x[..., i]),
sin(f_1*x[..., i]),
sin(f_2*x[..., i]),
...
sin(f_N * x[..., i]),
cos(x[..., i]),
cos(f_1*x[..., i]),
cos(f_2*x[..., i]),
...
cos(f_N * x[..., i]),
x[..., i] # only present if include_input is True.
], here f_i is the frequency.
Denote the space is [0 / num_freqs, 1 / num_freqs, 2 / num_freqs, 3 / num_freqs, ..., (num_freqs - 1) / num_freqs].
If logspace is True, then the frequency f_i is [2^(0 / num_freqs), ..., 2^(i / num_freqs), ...];
Otherwise, the frequencies are linearly spaced between [1.0, 2^(num_freqs - 1)].
Args:
num_freqs (int): the number of frequencies, default is 6;
logspace (bool): If logspace is True, then the frequency f_i is [..., 2^(i / num_freqs), ...],
otherwise, the frequencies are linearly spaced between [1.0, 2^(num_freqs - 1)];
input_dim (int): the input dimension, default is 3;
include_input (bool): include the input tensor or not, default is True.
Attributes:
frequencies (torch.Tensor): If logspace is True, then the frequency f_i is [..., 2^(i / num_freqs), ...],
otherwise, the frequencies are linearly spaced between [1.0, 2^(num_freqs - 1);
out_dim (int): the embedding size, if include_input is True, it is input_dim * (num_freqs * 2 + 1),
otherwise, it is input_dim * num_freqs * 2.
"""
def __init__(self,
num_freqs: int = 6,
logspace: bool = True,
input_dim: int = 3,
include_input: bool = True,
include_pi: bool = True) -> None:
"""The initialization"""
super().__init__()
if logspace:
frequencies = 2.0 ** torch.arange(
num_freqs,
dtype=torch.float32
)
else:
frequencies = torch.linspace(
1.0,
2.0 ** (num_freqs - 1),
num_freqs,
dtype=torch.float32
)
if include_pi:
frequencies *= torch.pi
self.register_buffer("frequencies", frequencies, persistent=False)
self.include_input = include_input
self.num_freqs = num_freqs
self.out_dim = self.get_dims(input_dim)
def get_dims(self, input_dim):
temp = 1 if self.include_input or self.num_freqs == 0 else 0
out_dim = input_dim * (self.num_freqs * 2 + temp)
return out_dim
def forward(self, x: torch.Tensor) -> torch.Tensor:
""" Forward process.
Args:
x: tensor of shape [..., dim]
Returns:
embedding: an embedding of `x` of shape [..., dim * (num_freqs * 2 + temp)]
where temp is 1 if include_input is True and 0 otherwise.
"""
if self.num_freqs > 0:
embed = (x[..., None].contiguous() * self.frequencies).view(*x.shape[:-1], -1)
if self.include_input:
return torch.cat((x, embed.sin(), embed.cos()), dim=-1)
else:
return torch.cat((embed.sin(), embed.cos()), dim=-1)
else:
return x
class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
"""
def __init__(self, drop_prob: float = 0., scale_by_keep: bool = True):
super(DropPath, self).__init__()
self.drop_prob = drop_prob
self.scale_by_keep = scale_by_keep
def forward(self, x):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
'survival rate' as the argument.
"""
if self.drop_prob == 0. or not self.training:
return x
keep_prob = 1 - self.drop_prob
shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
if keep_prob > 0.0 and self.scale_by_keep:
random_tensor.div_(keep_prob)
return x * random_tensor
def extra_repr(self):
return f'drop_prob={round(self.drop_prob, 3):0.3f}'
class MLP(nn.Module):
def __init__(
self, *,
width: int,
expand_ratio: int = 4,
output_width: int = None,
drop_path_rate: float = 0.0
):
super().__init__()
self.width = width
self.c_fc = nn.Linear(width, width * expand_ratio)
self.c_proj = nn.Linear(width * expand_ratio, output_width if output_width is not None else width)
self.gelu = nn.GELU()
self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0. else nn.Identity()
def forward(self, x):
return self.drop
gitextract_k0kyt9hn/ ├── .gitignore ├── .readthedocs.yaml ├── LICENSE ├── NOTICE ├── README.md ├── README_ja_jp.md ├── README_zh_cn.md ├── api_server.py ├── assets/ │ ├── 1.glb │ ├── example_prompts.txt │ ├── modelviewer-template.html │ └── modelviewer-textured-template.html ├── blender_addon.py ├── docs/ │ ├── Makefile │ ├── README.md │ ├── make.bat │ ├── requirements.txt │ └── source/ │ ├── _static/ │ │ └── css/ │ │ └── custom.css │ ├── citation.md │ ├── conf.py │ ├── index.md │ ├── installation/ │ │ └── index.md │ ├── modelzoo.md │ └── started/ │ ├── api.md │ ├── blender.md │ ├── code.md │ ├── comfyui.md │ ├── gradio.md │ ├── index.md │ └── studio.md ├── examples/ │ ├── fast_shape_gen_multiview.py │ ├── fast_shape_gen_with_flashvdm.py │ ├── fast_texture_gen_multiview.py │ ├── faster_shape_gen_with_flashvdm_mini_turbo.py │ ├── shape_gen.py │ ├── shape_gen_mini.py │ ├── shape_gen_multiview.py │ ├── shape_gen_v2_1.py │ ├── textured_shape_gen.py │ ├── textured_shape_gen_mini.py │ └── textured_shape_gen_multiview.py ├── gradio_app.py ├── hy3dgen/ │ ├── __init__.py │ ├── rembg.py │ ├── shapegen/ │ │ ├── __init__.py │ │ ├── models/ │ │ │ ├── __init__.py │ │ │ ├── autoencoders/ │ │ │ │ ├── __init__.py │ │ │ │ ├── attention_blocks.py │ │ │ │ ├── attention_processors.py │ │ │ │ ├── model.py │ │ │ │ ├── surface_extractors.py │ │ │ │ └── volume_decoders.py │ │ │ ├── conditioner.py │ │ │ └── denoisers/ │ │ │ ├── __init__.py │ │ │ ├── hunyuan3ddit.py │ │ │ ├── hunyuandit.py │ │ │ └── moe_layers.py │ │ ├── pipelines.py │ │ ├── postprocessors.py │ │ ├── preprocessors.py │ │ ├── schedulers.py │ │ ├── surface_loaders.py │ │ └── utils.py │ ├── texgen/ │ │ ├── __init__.py │ │ ├── custom_rasterizer/ │ │ │ ├── custom_rasterizer/ │ │ │ │ ├── __init__.py │ │ │ │ ├── io_glb.py │ │ │ │ ├── io_obj.py │ │ │ │ └── render.py │ │ │ ├── lib/ │ │ │ │ └── custom_rasterizer_kernel/ │ │ │ │ ├── __init__.py │ │ │ │ ├── grid_neighbor.cpp │ │ │ │ ├── rasterizer.cpp │ │ │ │ ├── rasterizer.h │ │ │ │ └── rasterizer_gpu.cu │ │ │ └── setup.py │ │ ├── differentiable_renderer/ │ │ │ ├── __init__.py │ │ │ ├── camera_utils.py │ │ │ ├── compile_mesh_painter.bat │ │ │ ├── mesh_processor.cpp │ │ │ ├── mesh_processor.py │ │ │ ├── mesh_render.py │ │ │ ├── mesh_utils.py │ │ │ └── setup.py │ │ ├── hunyuanpaint/ │ │ │ ├── __init__.py │ │ │ ├── pipeline.py │ │ │ └── unet/ │ │ │ ├── __init__.py │ │ │ └── modules.py │ │ ├── pipelines.py │ │ └── utils/ │ │ ├── __init__.py │ │ ├── alignImg4Tex_utils.py │ │ ├── counter_utils.py │ │ ├── dehighlight_utils.py │ │ ├── imagesuper_utils.py │ │ ├── multiview_utils.py │ │ ├── simplify_mesh_utils.py │ │ └── uv_warp_utils.py │ └── text2image.py ├── minimal_demo.py ├── minimal_vae_demo.py ├── requirements.txt └── setup.py
SYMBOL INDEX (482 symbols across 44 files)
FILE: api_server.py
function build_logger (line 52) | def build_logger(logger_name, logger_filename):
class StreamToLogger (line 95) | class StreamToLogger(object):
method __init__ (line 100) | def __init__(self, logger, log_level=logging.INFO):
method __getattr__ (line 106) | def __getattr__(self, attr):
method write (line 109) | def write(self, buf):
method flush (line 123) | def flush(self):
function pretty_print_semaphore (line 129) | def pretty_print_semaphore(semaphore):
function load_image_from_base64 (line 142) | def load_image_from_base64(image):
class ModelWorker (line 146) | class ModelWorker:
method __init__ (line 147) | def __init__(self,
method get_queue_length (line 173) | def get_queue_length(self):
method get_status (line 180) | def get_status(self):
method generate (line 187) | def generate(self, uid, params):
function generate (line 245) | async def generate(request: Request):
function generate (line 278) | async def generate(request: Request):
function status (line 288) | async def status(uid: str):
FILE: blender_addon.py
class Hunyuan3DProperties (line 34) | class Hunyuan3DProperties(bpy.types.PropertyGroup):
class Hunyuan3DOperator (line 93) | class Hunyuan3DOperator(bpy.types.Operator):
method modal (line 112) | def modal(self, context, event):
method invoke (line 124) | def invoke(self, context, event):
method generate_model (line 181) | def generate_model(self, context):
class Hunyuan3DPanel (line 299) | class Hunyuan3DPanel(bpy.types.Panel):
method draw (line 305) | def draw(self, context):
function register (line 339) | def register():
function unregister (line 345) | def unregister():
FILE: examples/fast_shape_gen_with_flashvdm.py
function run (line 28) | def run():
FILE: examples/faster_shape_gen_with_flashvdm_mini_turbo.py
function run (line 30) | def run():
FILE: gradio_app.py
function get_example_img_list (line 35) | def get_example_img_list():
function get_example_txt_list (line 40) | def get_example_txt_list():
function get_example_mv_list (line 48) | def get_example_mv_list():
function gen_save_folder (line 64) | def gen_save_folder(max_size=200):
function export_mesh (line 85) | def export_mesh(mesh, save_folder, textured=False, type='glb'):
function randomize_seed_fn (line 97) | def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
function build_model_viewer_html (line 103) | def build_model_viewer_html(save_folder, height=660, width=790, textured...
function _gen_shape (line 135) | def _gen_shape(
function generation_all (line 242) | def generation_all(
function shape_generation (line 307) | def shape_generation(
function build_app (line 353) | def build_app():
FILE: hy3dgen/rembg.py
class BackgroundRemover (line 19) | class BackgroundRemover():
method __init__ (line 20) | def __init__(self):
method __call__ (line 23) | def __call__(self, image: Image.Image):
FILE: hy3dgen/shapegen/models/autoencoders/attention_blocks.py
class FourierEmbedder (line 37) | class FourierEmbedder(nn.Module):
method __init__ (line 74) | def __init__(self,
method get_dims (line 107) | def get_dims(self, input_dim):
method forward (line 113) | def forward(self, x: torch.Tensor) -> torch.Tensor:
class DropPath (line 134) | class DropPath(nn.Module):
method __init__ (line 138) | def __init__(self, drop_prob: float = 0., scale_by_keep: bool = True):
method forward (line 143) | def forward(self, x):
method extra_repr (line 162) | def extra_repr(self):
class MLP (line 166) | class MLP(nn.Module):
method __init__ (line 167) | def __init__(
method forward (line 181) | def forward(self, x):
class QKVMultiheadCrossAttention (line 185) | class QKVMultiheadCrossAttention(nn.Module):
method __init__ (line 186) | def __init__(
method forward (line 203) | def forward(self, q, kv):
class MultiheadCrossAttention (line 219) | class MultiheadCrossAttention(nn.Module):
method __init__ (line 220) | def __init__(
method forward (line 250) | def forward(self, x, data):
class ResidualCrossAttentionBlock (line 264) | class ResidualCrossAttentionBlock(nn.Module):
method __init__ (line 265) | def __init__(
method forward (line 296) | def forward(self, x: torch.Tensor, data: torch.Tensor):
class QKVMultiheadAttention (line 302) | class QKVMultiheadAttention(nn.Module):
method __init__ (line 303) | def __init__(
method forward (line 318) | def forward(self, qkv):
class MultiheadAttention (line 332) | class MultiheadAttention(nn.Module):
method __init__ (line 333) | def __init__(
method forward (line 359) | def forward(self, x):
class ResidualAttentionBlock (line 366) | class ResidualAttentionBlock(nn.Module):
method __init__ (line 367) | def __init__(
method forward (line 392) | def forward(self, x: torch.Tensor):
class Transformer (line 398) | class Transformer(nn.Module):
method __init__ (line 399) | def __init__(
method forward (line 430) | def forward(self, x: torch.Tensor):
class CrossAttentionDecoder (line 436) | class CrossAttentionDecoder(nn.Module):
method __init__ (line 438) | def __init__(
method set_cross_attention_processor (line 478) | def set_cross_attention_processor(self, processor):
method set_default_cross_attention_processor (line 481) | def set_default_cross_attention_processor(self):
method forward (line 484) | def forward(self, queries=None, query_embeddings=None, latents=None):
function fps (line 497) | def fps(
class PointCrossAttentionEncoder (line 511) | class PointCrossAttentionEncoder(nn.Module):
method __init__ (line 513) | def __init__(
method sample_points_and_latents (line 575) | def sample_points_and_latents(self, pc: torch.FloatTensor, feats: Opti...
method forward (line 674) | def forward(self, pc, feats):
FILE: hy3dgen/shapegen/models/autoencoders/attention_processors.py
class CrossAttentionProcessor (line 29) | class CrossAttentionProcessor:
method __call__ (line 30) | def __call__(self, attn, q, k, v):
class FlashVDMCrossAttentionProcessor (line 35) | class FlashVDMCrossAttentionProcessor:
method __init__ (line 36) | def __init__(self, topk=None):
method __call__ (line 39) | def __call__(self, attn, q, k, v):
method select_topkv (line 73) | def select_topkv(self, q_chunk, k, v, topk):
class FlashVDMTopMCrossAttentionProcessor (line 84) | class FlashVDMTopMCrossAttentionProcessor(FlashVDMCrossAttentionProcessor):
method select_topkv (line 85) | def select_topkv(self, q_chunk, k, v, topk):
FILE: hy3dgen/shapegen/models/autoencoders/model.py
class DiagonalGaussianDistribution (line 30) | class DiagonalGaussianDistribution(object):
method __init__ (line 31) | def __init__(self, parameters: Union[torch.Tensor, List[torch.Tensor]]...
method sample (line 48) | def sample(self):
method kl (line 52) | def kl(self, other=None, dims=(1, 2, 3)):
method nll (line 66) | def nll(self, sample, dims=(1, 2, 3)):
method mode (line 74) | def mode(self):
class VectsetVAE (line 78) | class VectsetVAE(nn.Module):
method from_single_file (line 82) | def from_single_file(
method from_pretrained (line 117) | def from_pretrained(
method init_from_ckpt (line 143) | def init_from_ckpt(self, path, ignore_keys=()):
method __init__ (line 158) | def __init__(
method latents2mesh (line 171) | def latents2mesh(self, latents: torch.FloatTensor, **kwargs):
method enable_flashvdm_decoder (line 178) | def enable_flashvdm_decoder(
class ShapeVAE (line 198) | class ShapeVAE(VectsetVAE):
method __init__ (line 199) | def __init__(
method forward (line 279) | def forward(self, latents):
method encode (line 284) | def encode(self, surface, sample_posterior=True):
method decode (line 295) | def decode(self, latents):
FILE: hy3dgen/shapegen/models/autoencoders/surface_extractors.py
class Latent2MeshOutput (line 22) | class Latent2MeshOutput:
method __init__ (line 24) | def __init__(self, mesh_v=None, mesh_f=None):
function center_vertices (line 29) | def center_vertices(vertices):
class SurfaceExtractor (line 37) | class SurfaceExtractor:
method _compute_box_stat (line 38) | def _compute_box_stat(self, bounds: Union[Tuple[float], List[float], f...
method run (line 47) | def run(self, *args, **kwargs):
method __call__ (line 50) | def __call__(self, grid_logits, **kwargs):
class MCSurfaceExtractor (line 67) | class MCSurfaceExtractor(SurfaceExtractor):
method run (line 68) | def run(self, grid_logit, *, mc_level, bounds, octree_resolution, **kw...
class DMCSurfaceExtractor (line 79) | class DMCSurfaceExtractor(SurfaceExtractor):
method run (line 80) | def run(self, grid_logit, *, octree_resolution, **kwargs):
FILE: hy3dgen/shapegen/models/autoencoders/volume_decoders.py
function extract_near_surface_volume_fn (line 29) | def extract_near_surface_volume_fn(input_tensor: torch.Tensor, alpha: fl...
function generate_dense_grid_points (line 122) | def generate_dense_grid_points(
class VanillaVolumeDecoder (line 141) | class VanillaVolumeDecoder:
method __call__ (line 143) | def __call__(
class HierarchicalVolumeDecoding (line 185) | class HierarchicalVolumeDecoding:
method __call__ (line 187) | def __call__(
class FlashVDMVolumeDecoding (line 280) | class FlashVDMVolumeDecoding:
method __init__ (line 281) | def __init__(self, topk_mode='mean'):
method __call__ (line 291) | def __call__(
FILE: hy3dgen/shapegen/models/conditioner.py
function get_1d_sincos_pos_embed_from_grid (line 37) | def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
class ImageEncoder (line 57) | class ImageEncoder(nn.Module):
method __init__ (line 58) | def __init__(
method forward (line 91) | def forward(self, image, mask=None, value_range=(-1, 1), **kwargs):
method unconditional_embedding (line 106) | def unconditional_embedding(self, batch_size, **kwargs):
class CLIPImageEncoder (line 120) | class CLIPImageEncoder(ImageEncoder):
class DinoImageEncoder (line 127) | class DinoImageEncoder(ImageEncoder):
class DinoImageEncoderMV (line 134) | class DinoImageEncoderMV(DinoImageEncoder):
method __init__ (line 135) | def __init__(
method forward (line 154) | def forward(self, image, mask=None, value_range=(-1, 1), view_idxs=None):
method unconditional_embedding (line 190) | def unconditional_embedding(self, batch_size, view_idxs=None, **kwargs):
function build_image_encoder (line 203) | def build_image_encoder(config):
class DualImageEncoder (line 214) | class DualImageEncoder(nn.Module):
method __init__ (line 215) | def __init__(
method forward (line 224) | def forward(self, image, mask=None, **kwargs):
method unconditional_embedding (line 231) | def unconditional_embedding(self, batch_size, **kwargs):
class SingleImageEncoder (line 239) | class SingleImageEncoder(nn.Module):
method __init__ (line 240) | def __init__(
method forward (line 247) | def forward(self, image, mask=None, **kwargs):
method unconditional_embedding (line 253) | def unconditional_embedding(self, batch_size, **kwargs):
FILE: hy3dgen/shapegen/models/denoisers/hunyuan3ddit.py
function attention (line 33) | def attention(q: Tensor, k: Tensor, v: Tensor, **kwargs) -> Tensor:
function timestep_embedding (line 39) | def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: fl...
class GELU (line 63) | class GELU(nn.Module):
method __init__ (line 64) | def __init__(self, approximate='tanh'):
method forward (line 68) | def forward(self, x: Tensor) -> Tensor:
class MLPEmbedder (line 72) | class MLPEmbedder(nn.Module):
method __init__ (line 73) | def __init__(self, in_dim: int, hidden_dim: int):
method forward (line 79) | def forward(self, x: Tensor) -> Tensor:
class RMSNorm (line 83) | class RMSNorm(torch.nn.Module):
method __init__ (line 84) | def __init__(self, dim: int):
method forward (line 88) | def forward(self, x: Tensor):
class QKNorm (line 95) | class QKNorm(torch.nn.Module):
method __init__ (line 96) | def __init__(self, dim: int):
method forward (line 101) | def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tuple[Tensor, Te...
class SelfAttention (line 107) | class SelfAttention(nn.Module):
method __init__ (line 108) | def __init__(
method forward (line 122) | def forward(self, x: Tensor, pe: Tensor) -> Tensor:
class ModulationOut (line 132) | class ModulationOut:
class Modulation (line 138) | class Modulation(nn.Module):
method __init__ (line 139) | def __init__(self, dim: int, double: bool):
method forward (line 145) | def forward(self, vec: Tensor) -> Tuple[ModulationOut, Optional[Modula...
class DoubleStreamBlock (line 155) | class DoubleStreamBlock(nn.Module):
method __init__ (line 156) | def __init__(
method forward (line 189) | def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -...
class SingleStreamBlock (line 220) | class SingleStreamBlock(nn.Module):
method __init__ (line 226) | def __init__(
method forward (line 254) | def forward(self, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:
class LastLayer (line 270) | class LastLayer(nn.Module):
method __init__ (line 271) | def __init__(self, hidden_size: int, patch_size: int, out_channels: int):
method forward (line 277) | def forward(self, x: Tensor, vec: Tensor) -> Tensor:
class Hunyuan3DDiT (line 284) | class Hunyuan3DDiT(nn.Module):
method __init__ (line 285) | def __init__(
method forward (line 381) | def forward(
FILE: hy3dgen/shapegen/models/denoisers/hunyuandit.py
function modulate (line 26) | def modulate(x, shift, scale):
function get_1d_sincos_pos_embed_from_grid (line 30) | def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
class Timesteps (line 50) | class Timesteps(nn.Module):
method __init__ (line 51) | def __init__(self,
method forward (line 63) | def forward(self, timesteps):
class TimestepEmbedder (line 79) | class TimestepEmbedder(nn.Module):
method __init__ (line 84) | def __init__(self, hidden_size, frequency_embedding_size=256, cond_pro...
method forward (line 100) | def forward(self, t, condition):
class MLP (line 113) | class MLP(nn.Module):
method __init__ (line 114) | def __init__(self, *, width: int):
method forward (line 121) | def forward(self, x):
class CrossAttention (line 125) | class CrossAttention(nn.Module):
method __init__ (line 126) | def __init__(
method forward (line 164) | def forward(self, x, y):
class Attention (line 230) | class Attention(nn.Module):
method __init__ (line 235) | def __init__(
method forward (line 260) | def forward(self, x):
class HunYuanDiTBlock (line 291) | class HunYuanDiTBlock(nn.Module):
method __init__ (line 292) | def __init__(
method forward (line 365) | def forward(self, x, c=None, text_states=None, skip_value=None):
class AttentionPool (line 395) | class AttentionPool(nn.Module):
method __init__ (line 396) | def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, o...
method forward (line 405) | def forward(self, x, attention_mask=None):
class FinalLayer (line 437) | class FinalLayer(nn.Module):
method __init__ (line 442) | def __init__(self, final_hidden_size, out_channels):
method forward (line 448) | def forward(self, x):
class HunYuanDiTPlain (line 455) | class HunYuanDiTPlain(nn.Module):
method __init__ (line 457) | def __init__(
method forward (line 555) | def forward(self, x, t, contexts, **kwargs):
FILE: hy3dgen/shapegen/models/denoisers/moe_layers.py
class AddAuxiliaryLoss (line 9) | class AddAuxiliaryLoss(torch.autograd.Function):
method forward (line 16) | def forward(ctx, x, loss):
method backward (line 23) | def backward(ctx, grad_output):
class MoEGate (line 30) | class MoEGate(nn.Module):
method __init__ (line 31) | def __init__(self, embed_dim, num_experts=16, num_experts_per_tok=2, a...
method reset_parameters (line 46) | def reset_parameters(self) -> None:
method forward (line 50) | def forward(self, hidden_states):
class MoEBlock (line 93) | class MoEBlock(nn.Module):
method __init__ (line 94) | def __init__(self, dim, num_experts=8, moe_top_k=2,
method initialize_weight (line 109) | def initialize_weight(self):
method forward (line 112) | def forward(self, hidden_states):
method moe_infer (line 133) | def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
FILE: hy3dgen/shapegen/pipelines.py
function retrieve_timesteps (line 35) | def retrieve_timesteps(
function export_to_trimesh (line 95) | def export_to_trimesh(mesh_output):
function get_obj_from_str (line 112) | def get_obj_from_str(string, reload=False):
function instantiate_from_config (line 120) | def instantiate_from_config(config, **kwargs):
class Hunyuan3DDiTPipeline (line 135) | class Hunyuan3DDiTPipeline:
method from_single_file (line 141) | def from_single_file(
method from_pretrained (line 201) | def from_pretrained(
method __init__ (line 234) | def __init__(
method compile (line 253) | def compile(self):
method enable_flashvdm (line 258) | def enable_flashvdm(
method to (line 300) | def to(self, device=None, dtype=None):
method _execution_device (line 313) | def _execution_device(self):
method enable_model_cpu_offload (line 334) | def enable_model_cpu_offload(self, gpu_id: Optional[int] = None, devic...
method maybe_free_model_hooks (line 404) | def maybe_free_model_hooks(self):
method encode_cond (line 424) | def encode_cond(self, image, additional_cond_inputs, do_classifier_fre...
method prepare_extra_step_kwargs (line 456) | def prepare_extra_step_kwargs(self, generator, eta):
method prepare_latents (line 473) | def prepare_latents(self, batch_size, dtype, device, generator, latent...
method prepare_image (line 490) | def prepare_image(self, image) -> dict:
method get_guidance_scale_embedding (line 512) | def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=tor...
method set_surface_extractor (line 540) | def set_surface_extractor(self, mc_algo):
method __call__ (line 552) | def __call__(
method _export (line 648) | def _export(
class Hunyuan3DDiTFlowMatchingPipeline (line 680) | class Hunyuan3DDiTFlowMatchingPipeline(Hunyuan3DDiTPipeline):
method __call__ (line 683) | def __call__(
FILE: hy3dgen/shapegen/postprocessors.py
function load_mesh (line 28) | def load_mesh(path):
function reduce_face (line 37) | def reduce_face(mesh: pymeshlab.MeshSet, max_facenum: int = 200000):
function remove_floater (line 54) | def remove_floater(mesh: pymeshlab.MeshSet):
function pymeshlab2trimesh (line 62) | def pymeshlab2trimesh(mesh: pymeshlab.MeshSet):
function trimesh2pymeshlab (line 76) | def trimesh2pymeshlab(mesh: trimesh.Trimesh):
function export_mesh (line 91) | def export_mesh(input, output):
function import_mesh (line 104) | def import_mesh(mesh: Union[pymeshlab.MeshSet, trimesh.Trimesh, Latent2M...
class FaceReducer (line 118) | class FaceReducer:
method __call__ (line 120) | def __call__(
class FloaterRemover (line 131) | class FloaterRemover:
method __call__ (line 133) | def __call__(
class DegenerateFaceRemover (line 143) | class DegenerateFaceRemover:
method __call__ (line 145) | def __call__(
function mesh_normalize (line 160) | def mesh_normalize(mesh):
class MeshSimplifier (line 179) | class MeshSimplifier:
method __init__ (line 180) | def __init__(self, executable: str = None):
method __call__ (line 187) | def __call__(
FILE: hy3dgen/shapegen/preprocessors.py
function array_to_tensor (line 22) | def array_to_tensor(np_array):
class ImageProcessorV2 (line 30) | class ImageProcessorV2:
method __init__ (line 31) | def __init__(self, size=512, border_ratio=None):
method recenter (line 36) | def recenter(image, border_ratio: float = 0.2):
method load_image (line 90) | def load_image(self, image, border_ratio=0.15, to_tensor=True):
method __call__ (line 109) | def __call__(self, image, border_ratio=0.15, to_tensor=True, **kwargs):
class MVImageProcessorV2 (line 120) | class MVImageProcessorV2(ImageProcessorV2):
method __init__ (line 126) | def __init__(self, size=512, border_ratio=None):
method __call__ (line 135) | def __call__(self, image_dict, border_ratio=0.15, to_tensor=True, **kw...
FILE: hy3dgen/shapegen/schedulers.py
class FlowMatchEulerDiscreteSchedulerOutput (line 43) | class FlowMatchEulerDiscreteSchedulerOutput(BaseOutput):
class FlowMatchEulerDiscreteScheduler (line 56) | class FlowMatchEulerDiscreteScheduler(SchedulerMixin, ConfigMixin):
method __init__ (line 79) | def __init__(
method step_index (line 103) | def step_index(self):
method begin_index (line 110) | def begin_index(self):
method set_begin_index (line 117) | def set_begin_index(self, begin_index: int = 0):
method scale_noise (line 127) | def scale_noise(
method _sigma_to_t (line 175) | def _sigma_to_t(self, sigma):
method time_shift (line 178) | def time_shift(self, mu: float, sigma: float, t: torch.Tensor):
method set_timesteps (line 181) | def set_timesteps(
method index_for_timestep (line 223) | def index_for_timestep(self, timestep, schedule_timesteps=None):
method _init_step_index (line 237) | def _init_step_index(self, timestep):
method step (line 245) | def step(
method __len__ (line 320) | def __len__(self):
class ConsistencyFlowMatchEulerDiscreteSchedulerOutput (line 325) | class ConsistencyFlowMatchEulerDiscreteSchedulerOutput(BaseOutput):
class ConsistencyFlowMatchEulerDiscreteScheduler (line 330) | class ConsistencyFlowMatchEulerDiscreteScheduler(SchedulerMixin, ConfigM...
method __init__ (line 335) | def __init__(
method step_index (line 355) | def step_index(self):
method begin_index (line 362) | def begin_index(self):
method set_begin_index (line 369) | def set_begin_index(self, begin_index: int = 0):
method _sigma_to_t (line 379) | def _sigma_to_t(self, sigma):
method set_timesteps (line 382) | def set_timesteps(
method index_for_timestep (line 414) | def index_for_timestep(self, timestep, schedule_timesteps=None):
method _init_step_index (line 428) | def _init_step_index(self, timestep):
method step (line 436) | def step(
method __len__ (line 479) | def __len__(self):
FILE: hy3dgen/shapegen/surface_loaders.py
function normalize_mesh (line 7) | def normalize_mesh(mesh, scale=0.9999):
function sample_pointcloud (line 18) | def sample_pointcloud(mesh, num=200000):
function load_surface (line 26) | def load_surface(mesh, num_points=8192):
function sharp_sample_pointcloud (line 40) | def sharp_sample_pointcloud(mesh, num=16384):
function load_surface_sharpegde (line 74) | def load_surface_sharpegde(mesh, num_points=4096, num_sharp_points=4096,...
class SurfaceLoader (line 119) | class SurfaceLoader:
method __init__ (line 120) | def __init__(self, num_points=8192):
method __call__ (line 123) | def __call__(self, mesh_or_mesh_path, num_points=None):
class SharpEdgeSurfaceLoader (line 141) | class SharpEdgeSurfaceLoader:
method __init__ (line 142) | def __init__(self, num_uniform_points=8192, num_sharp_points=8192, **k...
method __call__ (line 147) | def __call__(self, mesh_or_mesh_path, num_uniform_points=None, num_sha...
FILE: hy3dgen/shapegen/utils.py
function get_logger (line 22) | def get_logger(name):
class synchronize_timer (line 38) | class synchronize_timer:
method __init__ (line 57) | def __init__(self, name=None):
method __enter__ (line 60) | def __enter__(self):
method __exit__ (line 68) | def __exit__(self, exc_type, exc_value, exc_tb):
method __call__ (line 77) | def __call__(self, func):
function smart_load_model (line 89) | def smart_load_model(
FILE: hy3dgen/texgen/custom_rasterizer/custom_rasterizer/io_glb.py
function get_buffer_data (line 26) | def get_buffer_data(gltf, buffer_view):
function get_attribute_data (line 35) | def get_attribute_data(gltf, accessor_index):
function get_image_data (line 62) | def get_image_data(gltf, image, folder):
function convert_triangle_strip_to_triangles (line 82) | def convert_triangle_strip_to_triangles(indices):
function convert_triangle_fan_to_triangles (line 93) | def convert_triangle_fan_to_triangles(indices):
function get_node_transform (line 101) | def get_node_transform(node):
function get_world_transform (line 117) | def get_world_transform(gltf, node_index, parents, world_transforms):
function LoadGlb (line 134) | def LoadGlb(path):
function RotatePrimitives (line 233) | def RotatePrimitives(primitives, transform):
FILE: hy3dgen/texgen/custom_rasterizer/custom_rasterizer/io_obj.py
function LoadObj (line 19) | def LoadObj(fn):
function LoadObjWithTexture (line 37) | def LoadObjWithTexture(fn, tex_fn):
FILE: hy3dgen/texgen/custom_rasterizer/custom_rasterizer/render.py
function rasterize (line 19) | def rasterize(pos, tri, resolution, clamp_depth=torch.zeros(0), use_dept...
function interpolate (line 26) | def interpolate(col, findices, barycentric, tri):
FILE: hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/grid_neighbor.cpp
function pos2key (line 4) | inline int pos2key(float* p, int resolution) {
function key2pos (line 11) | inline void key2pos(int key, int resolution, float* p) {
function key2cornerpos (line 20) | inline void key2cornerpos(int key, int resolution, float* p) {
type Grid (line 36) | struct Grid
function pos_from_seq (line 50) | inline void pos_from_seq(Grid& grid, int seq, float* p) {
function fetch_seq (line 55) | inline int fetch_seq(Grid& grid, int l, int i, int j, torch::Tensor pdat...
function fetch_last_seq (line 64) | inline int fetch_last_seq(Grid& grid, int i, int j, torch::Tensor pdata) {
function fetch_nearest_seq (line 78) | inline int fetch_nearest_seq(Grid& grid, int i, int j, int dim, float d,...
function fetch_nearest_seq_layer (line 97) | inline int fetch_nearest_seq_layer(Grid& grid, int i, int j, int dim, fl...
function FetchNeighbor (line 116) | void FetchNeighbor(Grid& grid, int seq, float* pos, int dim, int boundar...
function DownsampleGrid (line 157) | void DownsampleGrid(Grid& src, Grid& tar)
function NeighborGrid (line 192) | void NeighborGrid(Grid& grid, std::vector<torch::Tensor> view_layer_posi...
function PadGrid (line 264) | void PadGrid(Grid& src, Grid& tar, std::vector<torch::Tensor>& view_laye...
function build_hierarchy (line 311) | std::vector<std::vector<torch::Tensor>> build_hierarchy(std::vector<torc...
function build_hierarchy_with_feat (line 435) | std::vector<std::vector<torch::Tensor>> build_hierarchy_with_feat(
FILE: hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/rasterizer.cpp
function rasterizeTriangleCPU (line 3) | void rasterizeTriangleCPU(int idx, float* vt0, float* vt1, float* vt2, i...
function barycentricFromImgcoordCPU (line 41) | void barycentricFromImgcoordCPU(float* V, int* F, int* findices, INT64* ...
function rasterizeImagecoordsKernelCPU (line 81) | void rasterizeImagecoordsKernelCPU(float* V, int* F, float* d, INT64* zb...
function rasterize_image_cpu (line 94) | std::vector<torch::Tensor> rasterize_image_cpu(torch::Tensor V, torch::T...
function rasterize_image (line 125) | std::vector<torch::Tensor> rasterize_image(torch::Tensor V, torch::Tenso...
function PYBIND11_MODULE (line 135) | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
FILE: hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/rasterizer.h
function calculateSignedArea2 (line 12) | inline float calculateSignedArea2(float* a, float* b, float* c) {
function calculateBarycentricCoordinate (line 16) | inline void calculateBarycentricCoordinate(float* a, float* b, float* c,...
function isBarycentricCoordInBounds (line 37) | inline bool isBarycentricCoordInBounds(float* barycentricCoord) {
FILE: hy3dgen/texgen/differentiable_renderer/camera_utils.py
function transform_pos (line 21) | def transform_pos(mtx, pos, keepdim=False):
function get_mv_matrix (line 37) | def get_mv_matrix(elev, azim, camera_distance, center=None):
function get_orthographic_projection_matrix (line 74) | def get_orthographic_projection_matrix(
function get_perspective_projection_matrix (line 100) | def get_perspective_projection_matrix(fovy, aspect_wh, near, far):
FILE: hy3dgen/texgen/differentiable_renderer/mesh_processor.cpp
function meshVerticeInpaint_smooth (line 12) | std::pair<py::array_t<float>,
function meshVerticeInpaint (line 144) | std::pair<py::array_t<float>, py::array_t<uint8_t>> meshVerticeInpaint(p...
function PYBIND11_MODULE (line 155) | PYBIND11_MODULE(mesh_processor, m) {
FILE: hy3dgen/texgen/differentiable_renderer/mesh_processor.py
function meshVerticeInpaint_smooth (line 17) | def meshVerticeInpaint_smooth(texture, mask, vtx_pos, vtx_uv, pos_idx, u...
function meshVerticeInpaint (line 80) | def meshVerticeInpaint(texture, mask, vtx_pos, vtx_uv, pos_idx, uv_idx, ...
FILE: hy3dgen/texgen/differentiable_renderer/mesh_render.py
function stride_from_shape (line 32) | def stride_from_shape(shape):
function scatter_add_nd_with_count (line 39) | def scatter_add_nd_with_count(input, count, indices, values, weights=None):
function linear_grid_put_2d (line 67) | def linear_grid_put_2d(H, W, coords, values, return_count=False):
class MeshRender (line 120) | class MeshRender():
method __init__ (line 121) | def __init__(
method raster_rasterize (line 165) | def raster_rasterize(self, pos, tri, resolution, ranges=None, grad_db=...
method raster_interpolate (line 179) | def raster_interpolate(self, uv, rast_out, uv_idx, rast_db=None, diff_...
method raster_texture (line 193) | def raster_texture(self, tex, uv, uv_da=None, mip_level_bias=None, mip...
method raster_antialias (line 203) | def raster_antialias(self, color, rast, pos, tri, topology_hash=None, ...
method load_mesh (line 213) | def load_mesh(
method save_mesh (line 228) | def save_mesh(self):
method set_mesh (line 233) | def set_mesh(
method set_texture (line 263) | def set_texture(self, tex):
method set_default_render_resolution (line 275) | def set_default_render_resolution(self, default_resolution):
method set_default_texture_resolution (line 280) | def set_default_texture_resolution(self, texture_size):
method get_mesh (line 285) | def get_mesh(self):
method get_texture (line 298) | def get_texture(self):
method to (line 301) | def to(self, device):
method color_rgb_to_srgb (line 309) | def color_rgb_to_srgb(self, image):
method _render (line 338) | def _render(
method render (line 377) | def render(
method render_normal (line 424) | def render_normal(
method convert_normal_map (line 493) | def convert_normal_map(self, image):
method get_pos_from_mvp (line 512) | def get_pos_from_mvp(self, elev, azim, camera_distance, center):
method render_depth (line 525) | def render_depth(
method render_position (line 566) | def render_position(self, elev, azim, camera_distance=None, center=None,
method render_uvpos (line 600) | def render_uvpos(self, return_type='th'):
method uv_feature_map (line 609) | def uv_feature_map(self, vert_feat, bg=None):
method render_sketch_from_geometry (line 624) | def render_sketch_from_geometry(self, normal_image, depth_image):
method render_sketch_from_depth (line 643) | def render_sketch_from_depth(self, depth_image):
method back_project (line 653) | def back_project(self, image, elev, azim,
method bake_texture (line 759) | def bake_texture(self, colors, elevs, azims,
method fast_bake_texture (line 783) | def fast_bake_texture(self, textures, cos_maps):
method uv_inpaint (line 800) | def uv_inpaint(self, texture, mask):
FILE: hy3dgen/texgen/differentiable_renderer/mesh_utils.py
function load_mesh (line 18) | def load_mesh(mesh):
function save_mesh (line 30) | def save_mesh(mesh, texture_data):
FILE: hy3dgen/texgen/differentiable_renderer/setup.py
function get_platform_specific_args (line 20) | def get_platform_specific_args():
FILE: hy3dgen/texgen/hunyuanpaint/pipeline.py
function guidance_scale_embedding (line 47) | def guidance_scale_embedding(w, embedding_dim=512, dtype=torch.float32):
function append_dims (line 76) | def append_dims(x, target_dims):
function scalings_for_boundary_conditions (line 85) | def scalings_for_boundary_conditions(timestep, sigma_data=0.5, timestep_...
function get_predicted_original_sample (line 93) | def get_predicted_original_sample(model_output, timesteps, sample, predi...
function get_predicted_noise (line 113) | def get_predicted_noise(model_output, timesteps, sample, prediction_type...
function extract_into_tensor (line 131) | def extract_into_tensor(a, t, x_shape, N_gen):
class DDIMSolver (line 139) | class DDIMSolver:
method __init__ (line 140) | def __init__(self, alpha_cumprods, timesteps=1000, ddim_timesteps=50):
method to (line 153) | def to(self, device):
method ddim_step (line 159) | def ddim_step(self, pred_x0, pred_noise, timestep_index, N_gen):
function update_ema (line 167) | def update_ema(target_params, source_params, rate=0.99):
function to_rgb_image (line 180) | def to_rgb_image(maybe_rgba: Image.Image):
class HunyuanPaintPipeline (line 193) | class HunyuanPaintPipeline(StableDiffusionPipeline):
method __init__ (line 195) | def __init__(
method set_turbo (line 227) | def set_turbo(self, is_turbo: bool):
method encode_images (line 231) | def encode_images(self, images):
method __call__ (line 244) | def __call__(
method denoise (line 390) | def denoise(
FILE: hy3dgen/texgen/hunyuanpaint/unet/modules.py
function _chunked_feed_forward (line 29) | def _chunked_feed_forward(ff: nn.Module, hidden_states: torch.Tensor, ch...
class Basic2p5DTransformerBlock (line 46) | class Basic2p5DTransformerBlock(torch.nn.Module):
method __init__ (line 47) | def __init__(self, transformer: BasicTransformerBlock,layer_name,use_m...
method _initialize_attn_weights (line 83) | def _initialize_attn_weights(self):
method __getattr__ (line 98) | def __getattr__(self, name: str):
method forward (line 104) | def forward(
function compute_voxel_grid_mask (line 302) | def compute_voxel_grid_mask(position, grid_resolution=8):
function compute_multi_resolution_mask (line 349) | def compute_multi_resolution_mask(position_maps, grid_resolutions=[32, 1...
function compute_discrete_voxel_indice (line 359) | def compute_discrete_voxel_indice(position, grid_resolution=8, voxel_res...
function compute_multi_resolution_discrete_voxel_indice (line 391) | def compute_multi_resolution_discrete_voxel_indice(
class UNet2p5DConditionModel (line 404) | class UNet2p5DConditionModel(torch.nn.Module):
method __init__ (line 405) | def __init__(self, unet: UNet2DConditionModel) -> None:
method from_pretrained (line 423) | def from_pretrained(pretrained_model_name_or_path, **kwargs):
method init_condition (line 436) | def init_condition(self):
method init_camera_embedding (line 450) | def init_camera_embedding(self):
method init_attention (line 458) | def init_attention(self, unet, use_ma=False, use_ra=False, is_turbo=Fa...
method __getattr__ (line 492) | def __getattr__(self, name: str):
method forward (line 498) | def forward(
FILE: hy3dgen/texgen/pipelines.py
class Hunyuan3DTexGenConfig (line 33) | class Hunyuan3DTexGenConfig:
method __init__ (line 35) | def __init__(self, light_remover_ckpt_path, multiview_ckpt_path, subfo...
class Hunyuan3DPaintPipeline (line 53) | class Hunyuan3DPaintPipeline:
method from_pretrained (line 55) | def from_pretrained(cls, model_path, subfolder='hunyuan3d-paint-v2-0-t...
method __init__ (line 89) | def __init__(self, config):
method load_models (line 98) | def load_models(self):
method enable_model_cpu_offload (line 106) | def enable_model_cpu_offload(self, gpu_id: Optional[int] = None, devic...
method render_normal_multiview (line 110) | def render_normal_multiview(self, camera_elevs, camera_azims, use_abs_...
method render_position_multiview (line 119) | def render_position_multiview(self, camera_elevs, camera_azims):
method bake_from_multiview (line 128) | def bake_from_multiview(self, views, camera_elevs,
method texture_inpaint (line 148) | def texture_inpaint(self, texture, mask):
method recenter_image (line 155) | def recenter_image(self, image, border_ratio=0.2):
method __call__ (line 190) | def __call__(self, mesh, image):
FILE: hy3dgen/texgen/utils/alignImg4Tex_utils.py
class Img2img_Control_Ip_adapter (line 21) | class Img2img_Control_Ip_adapter:
method __init__ (line 22) | def __init__(self, device):
method __call__ (line 35) | def __call__(
class HesModel (line 71) | class HesModel:
method __init__ (line 72) | def __init__(self, ):
method __call__ (line 95) | def __call__(self,
FILE: hy3dgen/texgen/utils/counter_utils.py
class RunningStats (line 16) | class RunningStats():
method __init__ (line 17) | def __init__(self) -> None:
method add_value (line 24) | def add_value(self, value):
method get_count (line 35) | def get_count(self):
method get_sum (line 38) | def get_sum(self):
method get_mean (line 41) | def get_mean(self):
method get_min (line 44) | def get_min(self):
method get_max (line 47) | def get_max(self):
FILE: hy3dgen/texgen/utils/dehighlight_utils.py
class Light_Shadow_Remover (line 22) | class Light_Shadow_Remover():
method __init__ (line 23) | def __init__(self, config):
method recorrect_rgb (line 38) | def recorrect_rgb(self, src_image, target_image, alpha_channel, scale=...
method __call__ (line 69) | def __call__(self, image):
FILE: hy3dgen/texgen/utils/imagesuper_utils.py
class Image_Super_Net (line 18) | class Image_Super_Net():
method __init__ (line 19) | def __init__(self, config):
method __call__ (line 26) | def __call__(self, image, prompt=''):
FILE: hy3dgen/texgen/utils/multiview_utils.py
class Multiview_Diffusion_Net (line 25) | class Multiview_Diffusion_Net():
method __init__ (line 26) | def __init__(self, config) -> None:
method seed_everything (line 50) | def seed_everything(self, seed):
method __call__ (line 56) | def __call__(self, input_images, control_images, camera_info):
FILE: hy3dgen/texgen/utils/simplify_mesh_utils.py
function remesh_mesh (line 18) | def remesh_mesh(mesh_path, remesh_path, method='trimesh'):
function mesh_simplify_trimesh (line 25) | def mesh_simplify_trimesh(inputpath, outputpath):
FILE: hy3dgen/texgen/utils/uv_warp_utils.py
function mesh_uv_wrap (line 19) | def mesh_uv_wrap(mesh):
FILE: hy3dgen/text2image.py
function seed_everything (line 23) | def seed_everything(seed):
class HunyuanDiTPipeline (line 30) | class HunyuanDiTPipeline:
method __init__ (line 31) | def __init__(
method compile (line 49) | def compile(self):
method __call__ (line 67) | def __call__(self, prompt, seed=0):
Condensed preview — 100 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (607K chars).
[
{
"path": ".gitignore",
"chars": 3441,
"preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packagi"
},
{
"path": ".readthedocs.yaml",
"chars": 596,
"preview": "# Read the Docs configuration file\n# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details\n\n# Requir"
},
{
"path": "LICENSE",
"chars": 17666,
"preview": "TENCENT HUNYUAN 3D 2.0 COMMUNITY LICENSE AGREEMENT\nTencent Hunyuan 3D 2.0 Release Date: January 21, 2025\nTHIS LICENSE AG"
},
{
"path": "NOTICE",
"chars": 31940,
"preview": "Usage and Legal Notices:\n\nTencent is pleased to support the open source community by making Hunyuan 3D 2.0 available.\n\nC"
},
{
"path": "README.md",
"chars": 18696,
"preview": "[中文阅读](README_zh_cn.md)\n[日本語で読む](README_ja_jp.md)\n\n<p align=\"center\"> \n <img src=\"https://github.com/user-attachments/a"
},
{
"path": "README_ja_jp.md",
"chars": 7261,
"preview": "[Read in English](README.md)\n[中文阅读](README_zh_cn.md)\n\n<p align=\"center\"> \n <img src=\"./assets/images/teaser.jpg\">\n\n\n</p"
},
{
"path": "README_zh_cn.md",
"chars": 9209,
"preview": "[Read in English](README.md)\n[日本語で読む](README_ja_jp.md)\n\n<p align=\"center\">\n <img src=\"./assets/images/teaser.jpg\">\n\n</p"
},
{
"path": "api_server.py",
"chars": 11022,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "assets/example_prompts.txt",
"chars": 159,
"preview": "一片绿色的树叶在白色背景上居中展现,清晰的纹理\n一只棕白相间的仓鼠,站在白色背景前。照片采用居中构图方式,卡通风格\n一盆绿色植物生长在红色花盆中,居中,写实\na pot of green plants grows in a red flow"
},
{
"path": "assets/modelviewer-template.html",
"chars": 3116,
"preview": "<!DOCTYPE html>\n<html>\n\n<head>\n <!-- Import the component -->\n <script src=\"https://cdn.jsdelivr.net/npm/@google/m"
},
{
"path": "assets/modelviewer-textured-template.html",
"chars": 4857,
"preview": "<!DOCTYPE html>\n<html>\n\n<head>\n <!-- Import the component -->\n <script src=\"https://cdn.jsdelivr.net/npm/@google/m"
},
{
"path": "blender_addon.py",
"chars": 13114,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "docs/Makefile",
"chars": 638,
"preview": "# Minimal makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line, and also\n# from the "
},
{
"path": "docs/README.md",
"chars": 123,
"preview": "# Documentation\n\nSource of the documentation.\n\n- Build html.\n\n```bash\nmake html\n```\n\n- Preview at `build/html/index.html"
},
{
"path": "docs/make.bat",
"chars": 769,
"preview": "@ECHO OFF\n\npushd %~dp0\n\nREM Command file for Sphinx documentation\n\nif \"%SPHINXBUILD%\" == \"\" (\n\tset SPHINXBUILD=sphinx-bu"
},
{
"path": "docs/requirements.txt",
"chars": 266,
"preview": "myst-parser\nsphinx-rtd-theme\nfuro\nsphinx-copybutton\nsphinx-inline-tabs\nnbsphinx\nnbsphinx_link\nlinkify-it-py\nlinkify\nipyt"
},
{
"path": "docs/source/_static/css/custom.css",
"chars": 434,
"preview": "\n/*.sidebar-logo {*/\n/* display: block;*/\n/* margin: 0;*/\n/* max-width: 50%;*/\n/*}*/\n\n.nbsphinx-gallery {\n d"
},
{
"path": "docs/source/citation.md",
"chars": 1482,
"preview": "# Citation\n\nThe following publications discuss the ideas behind Hunyuan3D-2:\n\n> **Unleashing Vecset Diffusion Model for "
},
{
"path": "docs/source/conf.py",
"chars": 4230,
"preview": "# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common op"
},
{
"path": "docs/source/index.md",
"chars": 1768,
"preview": "---\nhide-toc: true\n---\n\n# Welcome to Hunyuan3D\n\n```{toctree}\n:maxdepth: 3\n:hidden: \n\nInstallation <installation/index>\nG"
},
{
"path": "docs/source/installation/index.md",
"chars": 861,
"preview": "# Installation\n\n```{toctree}\n:hidden:\n```\n\n∇-Prox works with PyTorch. To install Pytorch, please follow the [PyTorch ins"
},
{
"path": "docs/source/modelzoo.md",
"chars": 3192,
"preview": "# Model Zoo\n\nIt takes 6 GB VRAM for shape generation and 24.5 GB for shape and texture generation in total.\n\n## Hunyuan3"
},
{
"path": "docs/source/started/api.md",
"chars": 481,
"preview": "# API\n\nYou could launch an API server locally, which you could post web request for Image/Text to 3D, Texturing existing"
},
{
"path": "docs/source/started/blender.md",
"chars": 277,
"preview": "# Blender Addon\n\n\nWith an API server launched, you could also directly use Hunyuan3D 2.0 in your blender with\nour [Blend"
},
{
"path": "docs/source/started/code.md",
"chars": 1126,
"preview": "# Code\n\n\nWe designed a diffusers-like API to use our shape generation model - Hunyuan3D-DiT and texture synthesis model "
},
{
"path": "docs/source/started/comfyui.md",
"chars": 18,
"preview": "# Comfyui\n\ncomfyui"
},
{
"path": "docs/source/started/gradio.md",
"chars": 1199,
"preview": "# Gradio APP\n\nYou could also host a [Gradio](https://www.gradio.app/) App in your own computer via:\n\nStandard Version\n\n`"
},
{
"path": "docs/source/started/index.md",
"chars": 563,
"preview": "# Get Started\n\n```{toctree}\n:hidden:\n\ngradio\ncomfyui\napi\nblender\ncode\nstudio\n```\n\n## Installation\n\nTo get started with ∇"
},
{
"path": "docs/source/started/studio.md",
"chars": 137,
"preview": "# Official Website\n\nDon't forget to visit [Hunyuan3D](https://3d.hunyuan.tencent.com) for quick use, if you don't want t"
},
{
"path": "examples/fast_shape_gen_multiview.py",
"chars": 987,
"preview": "import time\n\nimport torch\nfrom PIL import Image\n\nfrom hy3dgen.rembg import BackgroundRemover\nfrom hy3dgen.shapegen impor"
},
{
"path": "examples/fast_shape_gen_with_flashvdm.py",
"chars": 1161,
"preview": "# HY3DGEN_DEBUG=1 USE_SAGEATTN=1 python3 examples/fast_shape_gen_with_flashvdm.py\n# HY3DGEN_DEBUG=1 USE_SAGEATTN=0 pytho"
},
{
"path": "examples/fast_texture_gen_multiview.py",
"chars": 733,
"preview": "import time\n\nimport torch\nfrom PIL import Image\nimport trimesh\n\nfrom hy3dgen.rembg import BackgroundRemover\nfrom hy3dgen"
},
{
"path": "examples/faster_shape_gen_with_flashvdm_mini_turbo.py",
"chars": 1245,
"preview": "# HY3DGEN_DEBUG=1 USE_SAGEATTN=1 python3 examples/faster_shape_gen_with_flashvdm_mini_turbo.py\n# HY3DGEN_DEBUG=1 USE_SAG"
},
{
"path": "examples/shape_gen.py",
"chars": 822,
"preview": "import time\n\nimport torch\nfrom PIL import Image\n\nfrom hy3dgen.rembg import BackgroundRemover\nfrom hy3dgen.shapegen impor"
},
{
"path": "examples/shape_gen_mini.py",
"chars": 763,
"preview": "import time\n\nimport torch\nfrom PIL import Image\n\nfrom hy3dgen.rembg import BackgroundRemover\nfrom hy3dgen.shapegen impor"
},
{
"path": "examples/shape_gen_multiview.py",
"chars": 955,
"preview": "import time\n\nimport torch\nfrom PIL import Image\n\nfrom hy3dgen.rembg import BackgroundRemover\nfrom hy3dgen.shapegen impor"
},
{
"path": "examples/shape_gen_v2_1.py",
"chars": 1438,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "examples/textured_shape_gen.py",
"chars": 633,
"preview": "from PIL import Image\n\nfrom hy3dgen.rembg import BackgroundRemover\nfrom hy3dgen.shapegen import Hunyuan3DDiTFlowMatching"
},
{
"path": "examples/textured_shape_gen_mini.py",
"chars": 974,
"preview": "import time\n\nimport torch\nfrom PIL import Image\n\nfrom hy3dgen.rembg import BackgroundRemover\nfrom hy3dgen.shapegen impor"
},
{
"path": "examples/textured_shape_gen_multiview.py",
"chars": 1185,
"preview": "import time\n\nimport torch\nfrom PIL import Image\n\nfrom hy3dgen.rembg import BackgroundRemover\nfrom hy3dgen.shapegen impor"
},
{
"path": "gradio_app.py",
"chars": 30874,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/__init__.py",
"chars": 920,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/rembg.py",
"chars": 1220,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/shapegen/__init__.py",
"chars": 1181,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/shapegen/models/__init__.py",
"chars": 1665,
"preview": "# Open Source Model Licensed under the Apache License Version 2.0\n# and Other Licenses of the Third-Party Components the"
},
{
"path": "hy3dgen/shapegen/models/autoencoders/__init__.py",
"chars": 1360,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/shapegen/models/autoencoders/attention_blocks.py",
"chars": 26121,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/shapegen/models/autoencoders/attention_processors.py",
"chars": 3913,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/shapegen/models/autoencoders/model.py",
"chars": 10461,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/shapegen/models/autoencoders/surface_extractors.py",
"chars": 3895,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/shapegen/models/autoencoders/volume_decoders.py",
"chars": 17838,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/shapegen/models/conditioner.py",
"chars": 9192,
"preview": "# Open Source Model Licensed under the Apache License Version 2.0\n# and Other Licenses of the Third-Party Components the"
},
{
"path": "hy3dgen/shapegen/models/denoisers/__init__.py",
"chars": 961,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/shapegen/models/denoisers/hunyuan3ddit.py",
"chars": 14984,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/shapegen/models/denoisers/hunyuandit.py",
"chars": 21440,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/shapegen/models/denoisers/moe_layers.py",
"chars": 6352,
"preview": "import math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom diffusers.models.attention import F"
},
{
"path": "hy3dgen/shapegen/pipelines.py",
"chars": 31932,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/shapegen/postprocessors.py",
"chars": 7018,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/shapegen/preprocessors.py",
"chars": 5992,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/shapegen/schedulers.py",
"chars": 18997,
"preview": "# Copyright 2024 Stability AI, Katherine Crowson and The HuggingFace Team. All rights reserved.\n#\n# Licensed under the A"
},
{
"path": "hy3dgen/shapegen/surface_loaders.py",
"chars": 6182,
"preview": "import numpy as np\n\nimport torch\nimport trimesh\n\n\ndef normalize_mesh(mesh, scale=0.9999):\n bbox = mesh.bounds\n cen"
},
{
"path": "hy3dgen/shapegen/utils.py",
"chars": 4464,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/__init__.py",
"chars": 992,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/custom_rasterizer/custom_rasterizer/__init__.py",
"chars": 1150,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/custom_rasterizer/custom_rasterizer/io_glb.py",
"chars": 10279,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/custom_rasterizer/custom_rasterizer/io_obj.py",
"chars": 2663,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/custom_rasterizer/custom_rasterizer/render.py",
"chars": 1613,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/__init__.py",
"chars": 921,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/grid_neighbor.cpp",
"chars": 22599,
"preview": "#include \"rasterizer.h\"\n#include <fstream>\n\ninline int pos2key(float* p, int resolution) {\n int x = (p[0] * 0.5 + 0.5"
},
{
"path": "hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/rasterizer.cpp",
"chars": 6789,
"preview": "#include \"rasterizer.h\"\n\nvoid rasterizeTriangleCPU(int idx, float* vt0, float* vt1, float* vt2, int width, int height, I"
},
{
"path": "hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/rasterizer.h",
"chars": 1972,
"preview": "#ifndef RASTERIZER_H_\n#define RASTERIZER_H_\n\n#include <torch/extension.h>\n#include <vector>\n#include <ATen/ATen.h>\n#incl"
},
{
"path": "hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/rasterizer_gpu.cu",
"chars": 6410,
"preview": "#include \"rasterizer.h\"\n\n__device__ void rasterizeTriangleGPU(int idx, float* vt0, float* vt1, float* vt2, int width, in"
},
{
"path": "hy3dgen/texgen/custom_rasterizer/setup.py",
"chars": 692,
"preview": "from setuptools import setup, find_packages\nfrom torch.utils.cpp_extension import BuildExtension, CUDAExtension\n\n# build"
},
{
"path": "hy3dgen/texgen/differentiable_renderer/__init__.py",
"chars": 920,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/differentiable_renderer/camera_utils.py",
"chars": 3707,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/differentiable_renderer/compile_mesh_painter.bat",
"chars": 204,
"preview": "FOR /F \"tokens=*\" %%i IN ('python -m pybind11 --includes') DO SET PYINCLUDES=%%i\necho %PYINCLUDES%\ng++ -O3 -Wall -shared"
},
{
"path": "hy3dgen/texgen/differentiable_renderer/mesh_processor.cpp",
"chars": 6399,
"preview": "#include <vector>\n#include <queue>\n#include <cmath>\n#include <algorithm>\n#include <pybind11/pybind11.h>\n#include <pybind"
},
{
"path": "hy3dgen/texgen/differentiable_renderer/mesh_processor.py",
"chars": 3834,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/differentiable_renderer/mesh_render.py",
"chars": 31420,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/differentiable_renderer/mesh_utils.py",
"chars": 1596,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/differentiable_renderer/setup.py",
"chars": 2526,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/hunyuanpaint/__init__.py",
"chars": 920,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/hunyuanpaint/pipeline.py",
"chars": 34415,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/hunyuanpaint/unet/__init__.py",
"chars": 920,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/hunyuanpaint/unet/modules.py",
"chars": 26152,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/pipelines.py",
"chars": 10376,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/utils/__init__.py",
"chars": 920,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/utils/alignImg4Tex_utils.py",
"chars": 4764,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/utils/counter_utils.py",
"chars": 1620,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/utils/dehighlight_utils.py",
"chars": 4643,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/utils/imagesuper_utils.py",
"chars": 1628,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/utils/multiview_utils.py",
"chars": 3856,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/utils/simplify_mesh_utils.py",
"chars": 1629,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/texgen/utils/uv_warp_utils.py",
"chars": 1379,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "hy3dgen/text2image.py",
"chars": 3140,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "minimal_demo.py",
"chars": 1555,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
},
{
"path": "minimal_vae_demo.py",
"chars": 1108,
"preview": "import torch\n\nfrom hy3dgen.shapegen.models.autoencoders import ShapeVAE\nfrom hy3dgen.shapegen.surface_loaders import Sha"
},
{
"path": "requirements.txt",
"chars": 387,
"preview": "ninja\npybind11\n\ndiffusers\neinops\nopencv-python\nnumpy\ntorch\ntransformers\ntorchvision\n#taming-transformers-rom1504\n#Config"
},
{
"path": "setup.py",
"chars": 1625,
"preview": "# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT\n# except for the third-party compone"
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the Tencent-Hunyuan/Hunyuan3D-2 GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 100 files (570.5 KB), approximately 147.5k tokens, and a symbol index with 482 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.