ds1david commited on
Commit
58eaf7f
·
1 Parent(s): e87f39a

Trying fix variants

Browse files
Files changed (1) hide show
  1. app.py +30 -57
app.py CHANGED
@@ -5,98 +5,71 @@ from diffusers import StableDiffusionXLImg2ImgPipeline
5
  from transformers import DPTFeatureExtractor, DPTForDepthEstimation
6
  from PIL import Image, ImageEnhance, ImageOps
7
 
8
- # Configuração de dispositivo e tipos de dados
9
  device = "cuda" if torch.cuda.is_available() else "cpu"
10
- torch_dtype = torch.float16 if device == "cuda" else torch.float32
11
 
12
  print("Carregando modelo SDXL Img2Img...")
13
  pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
14
  "stabilityai/stable-diffusion-xl-base-1.0",
15
  torch_dtype=torch_dtype,
16
- variant="fp32",
17
  use_safetensors=True
18
  ).to(device)
19
 
20
- print("Carregando pesos LoRA para baixo-relevo...")
21
  pipe.load_lora_weights(
22
  "KappaNeuro/bas-relief",
23
  weight_name="BAS-RELIEF.safetensors",
24
- adapter_name="bas_relief",
25
- peft_backend="peft"
26
  )
27
 
28
- print("Carregando modelo de profundidade DPT...")
29
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
30
  depth_model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large").to(device)
31
 
32
 
33
- def melhorar_mapa_profundidade(depth_arr: np.ndarray) -> Image.Image:
34
- d_min, d_max = depth_arr.min(), depth_arr.max()
35
- depth_stretched = (depth_arr - d_min) / (d_max - d_min + 1e-8)
36
- depth_stretched = (depth_stretched * 255).astype(np.uint8)
37
 
38
- depth_pil = Image.fromarray(depth_stretched)
39
- depth_pil = ImageOps.autocontrast(depth_pil)
40
 
41
- enhancer = ImageEnhance.Sharpness(depth_pil)
42
- depth_pil = enhancer.enhance(2.0)
43
-
44
- return depth_pil
45
-
46
-
47
- def gerar_baixo_relevo_e_profundidade(imagem: Image.Image):
48
- # Pré-processamento da imagem
49
  imagem = imagem.convert("RGB").resize((512, 512))
50
 
51
- # Geração da imagem em baixo-relevo
52
- with torch.autocast(device, dtype=torch_dtype):
53
  resultado = pipe(
54
  prompt="BAS-RELIEF",
55
  image=imagem,
56
  strength=0.7,
57
- num_inference_steps=15,
58
- guidance_scale=7.5,
59
- generator=torch.Generator(device=device).manual_seed(0)
60
  )
61
 
62
- imagem_gerada = resultado.images[0]
63
-
64
- # Cálculo do mapa de profundidade
65
- inputs = feature_extractor(imagem_gerada, return_tensors="pt").to(device)
66
  with torch.no_grad():
67
- outputs = depth_model(**inputs)
68
- predicted_depth = outputs.predicted_depth
69
 
70
- prediction = torch.nn.functional.interpolate(
71
- predicted_depth.unsqueeze(1),
72
- size=imagem_gerada.size[::-1],
73
- mode="bicubic",
74
- align_corners=False
75
- ).squeeze()
76
 
77
- mapa_profundidade = melhorar_mapa_profundidade(prediction.cpu().numpy())
78
-
79
- return imagem_gerada, mapa_profundidade
80
 
81
 
82
  # Interface Gradio
83
- titulo = "Conversor para Baixo-relevo com Mapa de Profundidade"
84
- descricao = (
85
- "Carrega uma imagem para transformar em estilo baixo-relevo usando SDXL + LoRA "
86
- "e gera o mapa de profundidade correspondente."
87
- )
88
-
89
  interface = gr.Interface(
90
- fn=gerar_baixo_relevo_e_profundidade,
91
- inputs=gr.Image(label="Imagem de Entrada", type="pil"),
92
- outputs=[
93
- gr.Image(label="Baixo-relevo Gerado"),
94
- gr.Image(label="Mapa de Profundidade")
95
- ],
96
- title=titulo,
97
- description=descricao,
98
- allow_flagging="never"
99
  )
100
 
101
  if __name__ == "__main__":
102
- interface.launch(server_name="0.0.0.0" if torch.cuda.is_available() else None)
 
5
  from transformers import DPTFeatureExtractor, DPTForDepthEstimation
6
  from PIL import Image, ImageEnhance, ImageOps
7
 
8
+ # Configuração de dispositivo
9
  device = "cuda" if torch.cuda.is_available() else "cpu"
10
+ torch_dtype = torch.float32 if device == "cpu" else torch.float16
11
 
12
  print("Carregando modelo SDXL Img2Img...")
13
  pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
14
  "stabilityai/stable-diffusion-xl-base-1.0",
15
  torch_dtype=torch_dtype,
 
16
  use_safetensors=True
17
  ).to(device)
18
 
19
+ print("Carregando pesos LoRA...")
20
  pipe.load_lora_weights(
21
  "KappaNeuro/bas-relief",
22
  weight_name="BAS-RELIEF.safetensors",
23
+ adapter_name="bas_relief"
 
24
  )
25
 
26
+ print("Carregando modelo de profundidade...")
27
  feature_extractor = DPTFeatureExtractor.from_pretrained("Intel/dpt-large")
28
  depth_model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large").to(device)
29
 
30
 
31
+ def processar_profundidade(depth_arr: np.ndarray) -> Image.Image:
32
+ depth_normalized = (depth_arr - depth_arr.min()) / (depth_arr.max() - depth_arr.min() + 1e-8)
33
+ depth_img = Image.fromarray((depth_normalized * 255).astype(np.uint8))
34
+ return ImageOps.autocontrast(depth_img)
35
 
 
 
36
 
37
+ def processar_imagem(imagem: Image.Image):
38
+ # Pré-processamento
 
 
 
 
 
 
39
  imagem = imagem.convert("RGB").resize((512, 512))
40
 
41
+ # Gerar baixo-relevo
42
+ with torch.inference_mode():
43
  resultado = pipe(
44
  prompt="BAS-RELIEF",
45
  image=imagem,
46
  strength=0.7,
47
+ num_inference_steps=20,
48
+ guidance_scale=7.5
 
49
  )
50
 
51
+ # Calcular profundidade
52
+ inputs = feature_extractor(resultado.images[0], return_tensors="pt").to(device)
 
 
53
  with torch.no_grad():
54
+ depth = depth_model(**inputs).predicted_depth
 
55
 
56
+ depth_map = torch.nn.functional.interpolate(
57
+ depth.unsqueeze(1),
58
+ size=imagem.size[::-1],
59
+ mode="bicubic"
60
+ ).squeeze().cpu().numpy()
 
61
 
62
+ return resultado.images[0], processar_profundidade(depth_map)
 
 
63
 
64
 
65
  # Interface Gradio
 
 
 
 
 
 
66
  interface = gr.Interface(
67
+ fn=processar_imagem,
68
+ inputs=gr.Image(type="pil"),
69
+ outputs=[gr.Image(label="Resultado"), gr.Image(label="Profundidade")],
70
+ title="Conversor para Baixo-relevo",
71
+ description="Transforme imagens em baixo-relevo com mapa de profundidade"
 
 
 
 
72
  )
73
 
74
  if __name__ == "__main__":
75
+ interface.launch()