fixing bugs
Browse files
app.py
CHANGED
|
@@ -23,19 +23,14 @@ class CustomLogger:
|
|
| 23 |
self.logger.addHandler(handler)
|
| 24 |
self.logger.setLevel(logging.INFO)
|
| 25 |
|
| 26 |
-
|
| 27 |
def divider(self, text=None, length=60):
|
| 28 |
if text:
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
if available_space < 1:
|
| 32 |
-
available_space = 1 # Garante pelo menos 1 '='
|
| 33 |
-
msg = f"\n{'=' * 10} {text.upper()} {'=' * available_space}"
|
| 34 |
else:
|
| 35 |
-
msg = "
|
| 36 |
self.logger.info(msg)
|
| 37 |
|
| 38 |
-
|
| 39 |
def etapa(self, text):
|
| 40 |
self.logger.info(f"▶ {text}")
|
| 41 |
|
|
@@ -53,118 +48,116 @@ logger = CustomLogger(__name__)
|
|
| 53 |
|
| 54 |
# ================== CONFIGURAÇÃO DE HARDWARE ==================
|
| 55 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 56 |
-
torch_dtype = torch.
|
| 57 |
-
logger.divider("
|
| 58 |
logger.success(f"Dispositivo detectado: {device.upper()}")
|
| 59 |
-
logger.success(f"
|
| 60 |
|
| 61 |
|
| 62 |
# ================== CARREGAMENTO DE MODELOS ==================
|
| 63 |
def carregar_modelo_thera(repo_id):
|
|
|
|
| 64 |
try:
|
| 65 |
-
logger.divider(f"Carregando
|
| 66 |
model_path = hf_hub_download(repo_id=repo_id, filename="model.pkl")
|
| 67 |
with open(model_path, 'rb') as f:
|
| 68 |
check = pickle.load(f)
|
| 69 |
model = build_thera(3, check['backbone'], check['size'])
|
| 70 |
params = check['model']
|
| 71 |
-
logger.success(f"
|
| 72 |
return model, params
|
| 73 |
except Exception as e:
|
| 74 |
logger.error(f"Falha ao carregar {repo_id}: {str(e)}")
|
| 75 |
return None, None
|
| 76 |
|
| 77 |
|
| 78 |
-
# Carregar modelos
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
modelo_rdn, params_rdn = carregar_modelo_thera("prs-eth/thera-rdn-pro")
|
| 82 |
-
except Exception as e:
|
| 83 |
-
logger.error("Falha crítica no carregamento dos modelos Thera")
|
| 84 |
-
raise
|
| 85 |
|
| 86 |
-
# ==================
|
| 87 |
pipe = None
|
| 88 |
modelo_profundidade = None
|
|
|
|
| 89 |
|
| 90 |
try:
|
| 91 |
-
logger.divider("
|
|
|
|
|
|
|
| 92 |
pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
|
| 93 |
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 94 |
torch_dtype=torch_dtype,
|
| 95 |
-
variant="fp16",
|
| 96 |
use_safetensors=True
|
| 97 |
).to(device)
|
| 98 |
|
|
|
|
| 99 |
pipe.load_lora_weights(
|
| 100 |
"KappaNeuro/bas-relief",
|
| 101 |
weight_name="BAS-RELIEF.safetensors"
|
| 102 |
)
|
| 103 |
-
logger.success("Pipeline SDXL configurado")
|
| 104 |
|
| 105 |
-
|
| 106 |
processador_profundidade = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 107 |
modelo_profundidade = DPTForDepthEstimation.from_pretrained("Intel/dpt-large").to(device)
|
| 108 |
-
logger.success("Modelo de profundidade pronto")
|
| 109 |
|
|
|
|
| 110 |
except Exception as e:
|
| 111 |
-
logger.
|
| 112 |
pipe = None
|
| 113 |
modelo_profundidade = None
|
| 114 |
|
| 115 |
|
| 116 |
-
# ==================
|
| 117 |
-
def
|
|
|
|
| 118 |
try:
|
| 119 |
logger.divider("Novo Processamento")
|
| 120 |
|
| 121 |
-
# Converter entrada
|
| 122 |
if not isinstance(imagem, Image.Image):
|
| 123 |
imagem = Image.fromarray(imagem)
|
| 124 |
|
| 125 |
-
# ========= SUPER-RESOLUÇÃO =========
|
| 126 |
-
logger.etapa("
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
np.array(imagem) / 255
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
(
|
| 135 |
-
|
| 136 |
True
|
| 137 |
)
|
| 138 |
|
| 139 |
-
sr_pil = Image.fromarray(np.array(
|
| 140 |
-
logger.success(f"
|
| 141 |
|
| 142 |
-
# ========= ESTILO BAIXO-RELEVO =========
|
| 143 |
-
arte_pil =
|
| 144 |
-
if pipe
|
| 145 |
try:
|
| 146 |
-
logger.etapa("Aplicando Estilo
|
| 147 |
-
|
| 148 |
-
prompt=f"BAS-RELIEF {
|
| 149 |
image=sr_pil,
|
| 150 |
-
strength=0.
|
| 151 |
-
num_inference_steps=
|
| 152 |
-
guidance_scale=7.
|
| 153 |
-
)
|
| 154 |
-
|
| 155 |
-
logger.success(f"Arte gerada: {arte_pil.size[0]}x{arte_pil.size[1]}")
|
| 156 |
except Exception as e:
|
| 157 |
-
logger.error(f"
|
| 158 |
|
| 159 |
-
# ========= MAPA DE PROFUNDIDADE =========
|
| 160 |
-
mapa_pil =
|
| 161 |
-
if
|
| 162 |
try:
|
| 163 |
logger.etapa("Calculando Profundidade")
|
| 164 |
-
inputs = processador_profundidade(
|
| 165 |
with torch.no_grad():
|
| 166 |
-
|
| 167 |
-
depth = outputs.predicted_depth
|
| 168 |
|
| 169 |
depth = torch.nn.functional.interpolate(
|
| 170 |
depth.unsqueeze(1).float(),
|
|
@@ -172,47 +165,45 @@ def pipeline_completo(imagem, fator_escala, modelo_escolhido, prompt_estilo):
|
|
| 172 |
mode="bicubic"
|
| 173 |
).squeeze().cpu().numpy()
|
| 174 |
|
| 175 |
-
|
| 176 |
-
mapa_pil = Image.fromarray((
|
| 177 |
-
logger.success("
|
| 178 |
except Exception as e:
|
| 179 |
-
logger.error(f"
|
| 180 |
|
| 181 |
-
return sr_pil, arte_pil
|
| 182 |
|
| 183 |
except Exception as e:
|
| 184 |
-
logger.error(f"Erro
|
| 185 |
return None, None, None
|
| 186 |
|
| 187 |
|
| 188 |
# ================== INTERFACE GRADIO ==================
|
| 189 |
-
with gr.Blocks(title="TheraSR
|
| 190 |
-
gr.Markdown("#
|
| 191 |
|
| 192 |
with gr.Row():
|
| 193 |
with gr.Column():
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
label="Prompt de Estilo",
|
| 203 |
-
value="insanely detailed ancient greek marble浮雕, 8k cinematic lighting"
|
| 204 |
)
|
| 205 |
-
|
| 206 |
|
| 207 |
with gr.Column():
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
inputs=[
|
| 215 |
-
outputs=[
|
| 216 |
)
|
| 217 |
|
| 218 |
if __name__ == "__main__":
|
|
|
|
| 23 |
self.logger.addHandler(handler)
|
| 24 |
self.logger.setLevel(logging.INFO)
|
| 25 |
|
|
|
|
| 26 |
def divider(self, text=None, length=60):
|
| 27 |
if text:
|
| 28 |
+
available_space = max(length - len(text) - 12, 1)
|
| 29 |
+
msg = f"{'=' * 10} {text.upper()} {'=' * available_space}"
|
|
|
|
|
|
|
|
|
|
| 30 |
else:
|
| 31 |
+
msg = "=" * length
|
| 32 |
self.logger.info(msg)
|
| 33 |
|
|
|
|
| 34 |
def etapa(self, text):
|
| 35 |
self.logger.info(f"▶ {text}")
|
| 36 |
|
|
|
|
| 48 |
|
| 49 |
# ================== CONFIGURAÇÃO DE HARDWARE ==================
|
| 50 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 51 |
+
torch_dtype = torch.float32 # Forçar precisão única para compatibilidade
|
| 52 |
+
logger.divider("Inicialização do Sistema")
|
| 53 |
logger.success(f"Dispositivo detectado: {device.upper()}")
|
| 54 |
+
logger.success(f"Modo de precisão: float32")
|
| 55 |
|
| 56 |
|
| 57 |
# ================== CARREGAMENTO DE MODELOS ==================
|
| 58 |
def carregar_modelo_thera(repo_id):
|
| 59 |
+
"""Carrega modelos Thera com tratamento de erros robusto"""
|
| 60 |
try:
|
| 61 |
+
logger.divider(f"Carregando {repo_id}")
|
| 62 |
model_path = hf_hub_download(repo_id=repo_id, filename="model.pkl")
|
| 63 |
with open(model_path, 'rb') as f:
|
| 64 |
check = pickle.load(f)
|
| 65 |
model = build_thera(3, check['backbone'], check['size'])
|
| 66 |
params = check['model']
|
| 67 |
+
logger.success(f"{repo_id} carregado")
|
| 68 |
return model, params
|
| 69 |
except Exception as e:
|
| 70 |
logger.error(f"Falha ao carregar {repo_id}: {str(e)}")
|
| 71 |
return None, None
|
| 72 |
|
| 73 |
|
| 74 |
+
# Carregar modelos principais
|
| 75 |
+
modelo_edsr, params_edsr = carregar_modelo_thera("prs-eth/thera-edsr-pro")
|
| 76 |
+
modelo_rdn, params_rdn = carregar_modelo_thera("prs-eth/thera-rdn-pro")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
+
# ================== MODELOS DE ARTE (CARREGAMENTO CONDICIONAL) ==================
|
| 79 |
pipe = None
|
| 80 |
modelo_profundidade = None
|
| 81 |
+
processador_profundidade = None
|
| 82 |
|
| 83 |
try:
|
| 84 |
+
logger.divider("Inicializando Componentes Artísticos")
|
| 85 |
+
|
| 86 |
+
# Pipeline de estilo
|
| 87 |
pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
|
| 88 |
"stabilityai/stable-diffusion-xl-base-1.0",
|
| 89 |
torch_dtype=torch_dtype,
|
|
|
|
| 90 |
use_safetensors=True
|
| 91 |
).to(device)
|
| 92 |
|
| 93 |
+
# Adapter LoRA
|
| 94 |
pipe.load_lora_weights(
|
| 95 |
"KappaNeuro/bas-relief",
|
| 96 |
weight_name="BAS-RELIEF.safetensors"
|
| 97 |
)
|
|
|
|
| 98 |
|
| 99 |
+
# Modelo de profundidade
|
| 100 |
processador_profundidade = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
|
| 101 |
modelo_profundidade = DPTForDepthEstimation.from_pretrained("Intel/dpt-large").to(device)
|
|
|
|
| 102 |
|
| 103 |
+
logger.success("Componentes artísticos prontos")
|
| 104 |
except Exception as e:
|
| 105 |
+
logger.warning(f"Recursos artísticos desativados: {str(e)}")
|
| 106 |
pipe = None
|
| 107 |
modelo_profundidade = None
|
| 108 |
|
| 109 |
|
| 110 |
+
# ================== PIPELINE PRINCIPAL ==================
|
| 111 |
+
def processar_imagem(imagem, escala, modelo, prompt):
|
| 112 |
+
"""Fluxo completo de processamento com fallbacks"""
|
| 113 |
try:
|
| 114 |
logger.divider("Novo Processamento")
|
| 115 |
|
| 116 |
+
# Converter entrada para PIL
|
| 117 |
if not isinstance(imagem, Image.Image):
|
| 118 |
imagem = Image.fromarray(imagem)
|
| 119 |
|
| 120 |
+
# ========= 1. SUPER-RESOLUÇÃO =========
|
| 121 |
+
logger.etapa("Super-Resolução Thera")
|
| 122 |
+
modelo_sr = modelo_edsr if modelo == "EDSR" else modelo_rdn
|
| 123 |
+
params_sr = params_edsr if modelo == "EDSR" else params_rdn
|
| 124 |
+
|
| 125 |
+
sr_jax = process(
|
| 126 |
+
np.array(imagem) / 255.0,
|
| 127 |
+
modelo_sr,
|
| 128 |
+
params_sr,
|
| 129 |
+
(int(imagem.height * escala),
|
| 130 |
+
int(imagem.width * escala)),
|
| 131 |
True
|
| 132 |
)
|
| 133 |
|
| 134 |
+
sr_pil = Image.fromarray(np.array(sr_jax)).convert("RGB")
|
| 135 |
+
logger.success(f"Resolução: {sr_pil.size[0]}x{sr_pil.size[1]}")
|
| 136 |
|
| 137 |
+
# ========= 2. ESTILO BAIXO-RELEVO =========
|
| 138 |
+
arte_pil = sr_pil # Fallback padrão
|
| 139 |
+
if pipe:
|
| 140 |
try:
|
| 141 |
+
logger.etapa("Aplicando Estilo")
|
| 142 |
+
arte_pil = pipe(
|
| 143 |
+
prompt=f"BAS-RELIEF {prompt}, marble texture, cinematic lighting",
|
| 144 |
image=sr_pil,
|
| 145 |
+
strength=0.6,
|
| 146 |
+
num_inference_steps=25,
|
| 147 |
+
guidance_scale=7.0
|
| 148 |
+
).images[0]
|
| 149 |
+
logger.success("Estilo aplicado")
|
|
|
|
| 150 |
except Exception as e:
|
| 151 |
+
logger.error(f"Erro no estilo: {str(e)}")
|
| 152 |
|
| 153 |
+
# ========= 3. MAPA DE PROFUNDIDADE =========
|
| 154 |
+
mapa_pil = arte_pil # Fallback padrão
|
| 155 |
+
if modelo_profundidade and arte_pil:
|
| 156 |
try:
|
| 157 |
logger.etapa("Calculando Profundidade")
|
| 158 |
+
inputs = processador_profundidade(arte_pil, return_tensors="pt").to(device)
|
| 159 |
with torch.no_grad():
|
| 160 |
+
depth = modelo_profundidade(**inputs).predicted_depth
|
|
|
|
| 161 |
|
| 162 |
depth = torch.nn.functional.interpolate(
|
| 163 |
depth.unsqueeze(1).float(),
|
|
|
|
| 165 |
mode="bicubic"
|
| 166 |
).squeeze().cpu().numpy()
|
| 167 |
|
| 168 |
+
depth_normalized = (depth - depth.min()) / (depth.max() - depth.min())
|
| 169 |
+
mapa_pil = Image.fromarray((depth_normalized * 255).astype(np.uint8))
|
| 170 |
+
logger.success("Profundidade calculada")
|
| 171 |
except Exception as e:
|
| 172 |
+
logger.error(f"Erro na profundidade: {str(e)}")
|
| 173 |
|
| 174 |
+
return sr_pil, arte_pil, mapa_pil
|
| 175 |
|
| 176 |
except Exception as e:
|
| 177 |
+
logger.error(f"Erro fatal: {str(e)}")
|
| 178 |
return None, None, None
|
| 179 |
|
| 180 |
|
| 181 |
# ================== INTERFACE GRADIO ==================
|
| 182 |
+
with gr.Blocks(title="TheraSR Universal", theme=gr.themes.Soft()) as app:
|
| 183 |
+
gr.Markdown("# 🏛 TheraSR - Super Resolução & Arte")
|
| 184 |
|
| 185 |
with gr.Row():
|
| 186 |
with gr.Column():
|
| 187 |
+
input_image = gr.Image(label="Imagem de Entrada", type="pil")
|
| 188 |
+
scale = gr.Slider(1.0, 4.0, value=2.0,
|
| 189 |
+
label="Fator de Escala", step=0.1)
|
| 190 |
+
model_select = gr.Radio(["EDSR", "RDN"],
|
| 191 |
+
value="EDSR", label="Modelo")
|
| 192 |
+
style_prompt = gr.Textbox(
|
| 193 |
+
label="Descrição do Estilo",
|
| 194 |
+
value="ancient greek marble浮雕, ultra detailed, 8k"
|
|
|
|
|
|
|
| 195 |
)
|
| 196 |
+
btn_process = gr.Button("Processar", variant="primary")
|
| 197 |
|
| 198 |
with gr.Column():
|
| 199 |
+
output_sr = gr.Image(label="Super-Resolução", interactive=False)
|
| 200 |
+
output_art = gr.Image(label="Arte em Relevo", interactive=False)
|
| 201 |
+
output_depth = gr.Image(label="Mapa de Profundidade", interactive=False)
|
| 202 |
+
|
| 203 |
+
btn_process.click(
|
| 204 |
+
processar_imagem,
|
| 205 |
+
inputs=[input_image, scale, model_select, style_prompt],
|
| 206 |
+
outputs=[output_sr, output_art, output_depth]
|
| 207 |
)
|
| 208 |
|
| 209 |
if __name__ == "__main__":
|