staswrs
🔥 Clean redeploy with updated app.py
b2a27a7
raw
history blame
7.59 kB
# import os
# import subprocess
# # 🧹 Убираем pyenv, если вдруг остался .python-version
# os.environ.pop("PYENV_VERSION", None)
# # ⚙️ Устанавливаем torch и diso
# subprocess.run(["pip", "install", "torch", "wheel"], check=True)
# subprocess.run([
# "pip", "install", "--no-build-isolation",
# "diso@git+https://github.com/SarahWeiii/diso.git"
# ], check=True)
# # ✅ Только теперь импортируем всё остальное
# import gradio as gr
# import uuid
# import torch
# import zipfile
# import requests
# from inference_triposg import run_triposg
# from triposg.pipelines.pipeline_triposg import TripoSGPipeline
# from briarmbg import BriaRMBG
# # === Настройки устройства ===
# # device = "cuda" if torch.cuda.is_available() else "cpu"
# # dtype = torch.float16 if torch.cuda.is_available() else torch.float32
# # dtype = torch.float32
# device = "cuda" if torch.cuda.is_available() else "cpu"
# dtype = torch.float16 if device == "cuda" else torch.float32
# # === Проверка и загрузка весов ===
# weights_dir = "pretrained_weights"
# triposg_path = os.path.join(weights_dir, "TripoSG")
# rmbg_path = os.path.join(weights_dir, "RMBG-1.4")
# if not (os.path.exists(triposg_path) and os.path.exists(rmbg_path)):
# print("📦 Downloading pretrained weights from Hugging Face Dataset...")
# url = "https://huggingface.co/datasets/endlesstools/pretrained-assets/resolve/main/pretrained_models.zip"
# zip_path = "pretrained_models.zip"
# with requests.get(url, stream=True) as r:
# r.raise_for_status()
# with open(zip_path, "wb") as f:
# for chunk in r.iter_content(chunk_size=8192):
# f.write(chunk)
# print("📦 Extracting weights...")
# with zipfile.ZipFile(zip_path, "r") as zip_ref:
# zip_ref.extractall(weights_dir)
# os.remove(zip_path)
# print("✅ Weights ready.")
# # === Загрузка моделей ===
# pipe = TripoSGPipeline.from_pretrained(triposg_path).to(device, dtype)
# rmbg_net = BriaRMBG.from_pretrained(rmbg_path).to(device)
# rmbg_net.eval()
# # === Функция генерации ===
# def generate(file):
# temp_id = str(uuid.uuid4())
# input_path = f"/tmp/{temp_id}.png"
# output_path = f"/tmp/{temp_id}.glb"
# with open(input_path, "wb") as f:
# f.write(file)
# print("[DEBUG] Generating mesh...")
# try:
# mesh = run_triposg(
# pipe=pipe,
# image_input=input_path,
# rmbg_net=rmbg_net,
# seed=42,
# num_inference_steps=25,
# guidance_scale=5.0,
# faces=-1,
# )
# # mesh.export(output_path)
# if mesh is None:
# raise ValueError("Mesh generation failed")
# mesh.export(output_path)
# print(f"[DEBUG] Mesh saved to {output_path}")
# # return output_path
# if os.path.exists(output_path):
# return output_path
# else:
# return "Error: mesh export failed or file not found"
# except Exception as e:
# print("[ERROR]", e)
# return f"Error: {e}"
# # === Gradio-интерфейс ===
# demo = gr.Interface(
# fn=generate,
# inputs=gr.File(type="binary", label="Upload image"),
# outputs=gr.File(label="Generated .glb model"),
# title="TripoSG Image-to-3D",
# description="Upload an image and get back a 3D GLB model.",
# )
# # # === ВАЖНО: переменная должна называться `app` ===
# # app = demo.launch(inline=True, share=False, prevent_thread_lock=True)
# demo.launch()
import os
import subprocess
# Убираем pyenv, если вдруг остался .python-version
os.environ.pop("PYENV_VERSION", None)
# Установка зависимостей
subprocess.run(["pip", "install", "torch", "wheel"], check=True)
subprocess.run([
"pip", "install", "--no-build-isolation",
"diso@git+https://github.com/SarahWeiii/diso.git"
], check=True)
# Импорты
import gradio as gr
import uuid
import torch
import zipfile
import requests
import traceback
from inference_triposg import run_triposg
from triposg.pipelines.pipeline_triposg import TripoSGPipeline
from briarmbg import BriaRMBG
# Настройки устройства
device = "cuda" if torch.cuda.is_available() else "cpu"
dtype = torch.float16 if device == "cuda" else torch.float32
# Загрузка весов
weights_dir = "pretrained_weights"
triposg_path = os.path.join(weights_dir, "TripoSG")
rmbg_path = os.path.join(weights_dir, "RMBG-1.4")
if not (os.path.exists(triposg_path) and os.path.exists(rmbg_path)):
print("📦 Downloading pretrained weights...")
url = "https://huggingface.co/datasets/endlesstools/pretrained-assets/resolve/main/pretrained_models.zip"
zip_path = "pretrained_models.zip"
with requests.get(url, stream=True) as r:
r.raise_for_status()
with open(zip_path, "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
print("📦 Extracting weights...")
with zipfile.ZipFile(zip_path, "r") as zip_ref:
zip_ref.extractall(weights_dir)
os.remove(zip_path)
print("✅ Weights ready.")
# Загрузка моделей
pipe = TripoSGPipeline.from_pretrained(triposg_path).to(device, dtype)
rmbg_net = BriaRMBG.from_pretrained(rmbg_path).to(device)
rmbg_net.eval()
# Генерация .glb
def generate(image_path):
print("[API CALL] image_path received:", image_path)
print("[API CALL] File exists:", os.path.exists(image_path))
temp_id = str(uuid.uuid4())
output_path = f"/tmp/{temp_id}.glb"
print("[DEBUG] Generating mesh from:", image_path)
try:
mesh = run_triposg(
pipe=pipe,
image_input=image_path,
rmbg_net=rmbg_net,
seed=42,
num_inference_steps=25,
guidance_scale=5.0,
faces=-1,
)
if mesh is None:
raise ValueError("Mesh generation failed")
mesh.export(output_path)
print(f"[DEBUG] Mesh saved to {output_path}")
return output_path if os.path.exists(output_path) else "Error: output file not found"
# except Exception as e:
# print("[ERROR]", e)
# return f"Error: {e}"
except Exception as e:
import traceback
print("[ERROR]", e)
traceback.print_exc() # ← выведет полную трассировку в логи
return f"Error: {e}"
# Интерфейс Gradio
demo = gr.Interface(
fn=generate,
inputs=gr.Image(type="filepath", label="Upload image"),
outputs=gr.File(label="Download .glb"),
title="TripoSG Image to 3D",
description="Upload an image to generate a 3D model (.glb)",
)
# Запуск
demo.launch()
# import gradio as gr
# import uuid
# import os
# import traceback
# def generate(image_path):
# try:
# print("[DEBUG] got image path:", image_path)
# print("[DEBUG] file exists:", os.path.exists(image_path))
# out_path = f"/tmp/{uuid.uuid4()}.txt"
# with open(out_path, "w") as f:
# f.write(f"Received: {image_path}")
# return out_path
# except Exception as e:
# print("[ERROR]", e)
# traceback.print_exc()
# return f"Error: {e}"
# demo = gr.Interface(
# fn=generate,
# inputs=gr.Image(type="filepath"),
# outputs=gr.File()
# )
# demo.launch()