rtietz commited on
Commit
6f0197c
·
verified ·
1 Parent(s): 7315abd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -41
app.py CHANGED
@@ -12,24 +12,13 @@ from transformers import (
12
  Qwen2VLForConditionalGeneration
13
  )
14
 
15
- # ------------------------------------------------------------------------
16
- # RADAR DE HARDWARE (MÁGICA DE ADAPTAÇÃO)
17
- # Detecta automaticamente se o servidor atual possui GPU (cuda) ou CPU.
18
- # ------------------------------------------------------------------------
19
- DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
20
-
21
- # Se estivermos na CPU, usamos o formato 'bfloat16' para encolher os
22
- # modelos modernos pela metade, evitando que estoure a RAM de 16GB.
23
- DTYPE_MODERNOS = torch.float16 if DEVICE == "cuda" else torch.bfloat16
24
-
25
  def traduzir_para_pt(texto):
26
  try:
27
  return GoogleTranslator(source='en', target='pt').translate(texto)
28
  except Exception as e:
29
  return f"{texto} (Erro na tradução: {str(e)})"
30
 
31
- # O decorador @spaces.GPU é inteligente: se estivermos na CPU, ele
32
- # simplesmente se desativa sozinho, sem causar erros.
33
  @spaces.GPU(duration=120)
34
  def analisar_imagem(imagem, tamanho):
35
  if imagem is None:
@@ -38,6 +27,11 @@ def analisar_imagem(imagem, tamanho):
38
  resultados = []
39
  hf_token = os.environ.get("HF_TOKEN")
40
 
 
 
 
 
 
41
  if "Pequeno" in tamanho:
42
  max_tok = 40
43
  prompt_vlms = "Describe this image briefly in one or two sentences."
@@ -50,46 +44,44 @@ def analisar_imagem(imagem, tamanho):
50
 
51
  def limpar_memoria():
52
  gc.collect()
53
- if DEVICE == "cuda":
54
  torch.cuda.empty_cache()
55
 
56
- limpar_memoria() # Limpeza preventiva antes de começar
57
 
58
  # =========================================================
59
  # GERAÇÃO CLÁSSICA (2021 - 2022)
60
  # =========================================================
61
 
62
- # 1. BLIP (Salesforce)
63
  try:
64
- print(f"Carregando BLIP no dispositivo: {DEVICE}...")
 
65
  processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
66
- model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(DEVICE)
67
- inputs = processor(imagem, return_tensors="pt").to(DEVICE)
68
  out = model.generate(**inputs, max_new_tokens=max_tok)
69
  resultados.append(traduzir_para_pt(processor.decode(out[0], skip_special_tokens=True)))
70
  del processor, model, inputs, out
71
  limpar_memoria()
72
  except Exception as e: resultados.append(f"Erro BLIP: {str(e)}")
73
 
74
- # 2. ViT-GPT2 (NLP Connect)
75
  try:
76
- print(f"Carregando ViT-GPT2 no dispositivo: {DEVICE}...")
77
- model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning").to(DEVICE)
78
  feature_extractor = ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
79
  tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
80
- pixel_values = feature_extractor(images=imagem, return_tensors="pt").pixel_values.to(DEVICE)
81
  out = model.generate(pixel_values, max_new_tokens=max_tok, num_beams=4)
82
  resultados.append(traduzir_para_pt(tokenizer.decode(out[0], skip_special_tokens=True)))
83
  del model, feature_extractor, tokenizer, pixel_values, out
84
  limpar_memoria()
85
  except Exception as e: resultados.append(f"Erro ViT-GPT2: {str(e)}")
86
 
87
- # 3. GIT (Microsoft)
88
  try:
89
- print(f"Carregando GIT no dispositivo: {DEVICE}...")
90
  processor = AutoProcessor.from_pretrained("microsoft/git-base-coco")
91
- model = AutoModelForCausalLM.from_pretrained("microsoft/git-base-coco").to(DEVICE)
92
- pixel_values = processor(images=imagem, return_tensors="pt").pixel_values.to(DEVICE)
93
  out = model.generate(pixel_values=pixel_values, max_new_tokens=max_tok)
94
  resultados.append(traduzir_para_pt(processor.decode(out[0], skip_special_tokens=True)))
95
  del processor, model, pixel_values, out
@@ -100,16 +92,15 @@ def analisar_imagem(imagem, tamanho):
100
  # GERAÇÃO MODERNA (VLMs de 2023 - 2024)
101
  # =========================================================
102
 
103
- # 4. Qwen2-VL 2B (Alibaba)
104
  try:
105
- print(f"Carregando Qwen2-VL no dispositivo: {DEVICE}...")
106
  model_id = "Qwen/Qwen2-VL-2B-Instruct"
107
- model = Qwen2VLForConditionalGeneration.from_pretrained(model_id, torch_dtype=DTYPE_MODERNOS).to(DEVICE)
108
  processor = AutoProcessor.from_pretrained(model_id)
109
 
110
  messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": prompt_vlms}]}]
111
  text_prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
112
- inputs = processor(text=[text_prompt], images=[imagem], padding=True, return_tensors="pt").to(DEVICE)
113
 
114
  out = model.generate(**inputs, max_new_tokens=max_tok)
115
  generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, out)]
@@ -120,27 +111,25 @@ def analisar_imagem(imagem, tamanho):
120
  limpar_memoria()
121
  except Exception as e: resultados.append(f"Erro Qwen2-VL: {str(e)}")
122
 
123
- # 5. PaliGemma 3B (Google)
124
  try:
125
- print(f"Carregando PaliGemma no dispositivo: {DEVICE}...")
126
  model_id = "google/paligemma-3b-mix-224"
127
  processor = AutoProcessor.from_pretrained(model_id, token=hf_token)
128
- model = PaliGemmaForConditionalGeneration.from_pretrained(model_id, torch_dtype=DTYPE_MODERNOS, token=hf_token).to(DEVICE)
129
- inputs = processor(text="caption", images=imagem, return_tensors="pt").to(DEVICE)
130
  out = model.generate(**inputs, max_new_tokens=max_tok)
131
  resultados.append(traduzir_para_pt(processor.decode(out[0], skip_special_tokens=True)))
132
  del processor, model, inputs, out
133
  limpar_memoria()
134
  except Exception as e: resultados.append(f"Erro PaliGemma: {str(e)}")
135
 
136
- # 6. LLaVA 1.5 7B
137
  try:
138
- print(f"Carregando LLaVA no dispositivo: {DEVICE}...")
139
  model_id = "llava-hf/llava-1.5-7b-hf"
140
  processor = AutoProcessor.from_pretrained(model_id)
141
- model = LlavaForConditionalGeneration.from_pretrained(model_id, torch_dtype=DTYPE_MODERNOS).to(DEVICE)
142
  prompt = f"USER: <image>\n{prompt_vlms}\nASSISTANT:"
143
- inputs = processor(images=imagem, text=prompt, return_tensors="pt").to(DEVICE)
144
  out = model.generate(**inputs, max_new_tokens=max_tok)
145
  texto_gerado = processor.decode(out[0], skip_special_tokens=True)
146
  texto_en = texto_gerado.split("ASSISTANT:")[-1].strip()
@@ -151,8 +140,9 @@ def analisar_imagem(imagem, tamanho):
151
 
152
  return tuple(resultados)
153
 
154
- # Construindo a Interface Gráfica com 3 Colunas
155
- with gr.Blocks(theme=gr.themes.Base()) as demo:
 
156
  gr.Markdown("# 👁️ Linha do Tempo: Modelos Visuais")
157
  gr.Markdown("Faça o upload de uma imagem, selecione a complexidade da análise e observe o salto tecnológico. **Sistema Híbrido:** Adapta-se automaticamente entre CPU gratuita ou aceleração de GPU.")
158
 
@@ -185,4 +175,5 @@ with gr.Blocks(theme=gr.themes.Base()) as demo:
185
  )
186
 
187
  if __name__ == "__main__":
188
- demo.launch()
 
 
12
  Qwen2VLForConditionalGeneration
13
  )
14
 
 
 
 
 
 
 
 
 
 
 
15
  def traduzir_para_pt(texto):
16
  try:
17
  return GoogleTranslator(source='en', target='pt').translate(texto)
18
  except Exception as e:
19
  return f"{texto} (Erro na tradução: {str(e)})"
20
 
21
+ # O decorador @spaces.GPU liga a GPU dinamicamente (se aplicável)
 
22
  @spaces.GPU(duration=120)
23
  def analisar_imagem(imagem, tamanho):
24
  if imagem is None:
 
27
  resultados = []
28
  hf_token = os.environ.get("HF_TOKEN")
29
 
30
+ # RADAR DE HARDWARE MOVIDO PARA DENTRO DA FUNÇÃO
31
+ # Agora ele detecta a GPU no momento exato da execução!
32
+ device = "cuda" if torch.cuda.is_available() else "cpu"
33
+ dtype_modernos = torch.float16 if device == "cuda" else torch.bfloat16
34
+
35
  if "Pequeno" in tamanho:
36
  max_tok = 40
37
  prompt_vlms = "Describe this image briefly in one or two sentences."
 
44
 
45
  def limpar_memoria():
46
  gc.collect()
47
+ if device == "cuda":
48
  torch.cuda.empty_cache()
49
 
50
+ limpar_memoria()
51
 
52
  # =========================================================
53
  # GERAÇÃO CLÁSSICA (2021 - 2022)
54
  # =========================================================
55
 
 
56
  try:
57
+ print(f"\n[ HARDWARE ATIVO: {device.upper()} ]")
58
+ print("Carregando BLIP...")
59
  processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
60
+ model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(device)
61
+ inputs = processor(imagem, return_tensors="pt").to(device)
62
  out = model.generate(**inputs, max_new_tokens=max_tok)
63
  resultados.append(traduzir_para_pt(processor.decode(out[0], skip_special_tokens=True)))
64
  del processor, model, inputs, out
65
  limpar_memoria()
66
  except Exception as e: resultados.append(f"Erro BLIP: {str(e)}")
67
 
 
68
  try:
69
+ print("Carregando ViT-GPT2...")
70
+ model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning").to(device)
71
  feature_extractor = ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
72
  tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
73
+ pixel_values = feature_extractor(images=imagem, return_tensors="pt").pixel_values.to(device)
74
  out = model.generate(pixel_values, max_new_tokens=max_tok, num_beams=4)
75
  resultados.append(traduzir_para_pt(tokenizer.decode(out[0], skip_special_tokens=True)))
76
  del model, feature_extractor, tokenizer, pixel_values, out
77
  limpar_memoria()
78
  except Exception as e: resultados.append(f"Erro ViT-GPT2: {str(e)}")
79
 
 
80
  try:
81
+ print("Carregando GIT...")
82
  processor = AutoProcessor.from_pretrained("microsoft/git-base-coco")
83
+ model = AutoModelForCausalLM.from_pretrained("microsoft/git-base-coco").to(device)
84
+ pixel_values = processor(images=imagem, return_tensors="pt").pixel_values.to(device)
85
  out = model.generate(pixel_values=pixel_values, max_new_tokens=max_tok)
86
  resultados.append(traduzir_para_pt(processor.decode(out[0], skip_special_tokens=True)))
87
  del processor, model, pixel_values, out
 
92
  # GERAÇÃO MODERNA (VLMs de 2023 - 2024)
93
  # =========================================================
94
 
 
95
  try:
96
+ print("Carregando Qwen2-VL...")
97
  model_id = "Qwen/Qwen2-VL-2B-Instruct"
98
+ model = Qwen2VLForConditionalGeneration.from_pretrained(model_id, torch_dtype=dtype_modernos).to(device)
99
  processor = AutoProcessor.from_pretrained(model_id)
100
 
101
  messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": prompt_vlms}]}]
102
  text_prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
103
+ inputs = processor(text=[text_prompt], images=[imagem], padding=True, return_tensors="pt").to(device)
104
 
105
  out = model.generate(**inputs, max_new_tokens=max_tok)
106
  generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, out)]
 
111
  limpar_memoria()
112
  except Exception as e: resultados.append(f"Erro Qwen2-VL: {str(e)}")
113
 
 
114
  try:
115
+ print("Carregando PaliGemma...")
116
  model_id = "google/paligemma-3b-mix-224"
117
  processor = AutoProcessor.from_pretrained(model_id, token=hf_token)
118
+ model = PaliGemmaForConditionalGeneration.from_pretrained(model_id, torch_dtype=dtype_modernos, token=hf_token).to(device)
119
+ inputs = processor(text="caption", images=imagem, return_tensors="pt").to(device)
120
  out = model.generate(**inputs, max_new_tokens=max_tok)
121
  resultados.append(traduzir_para_pt(processor.decode(out[0], skip_special_tokens=True)))
122
  del processor, model, inputs, out
123
  limpar_memoria()
124
  except Exception as e: resultados.append(f"Erro PaliGemma: {str(e)}")
125
 
 
126
  try:
127
+ print("Carregando LLaVA...")
128
  model_id = "llava-hf/llava-1.5-7b-hf"
129
  processor = AutoProcessor.from_pretrained(model_id)
130
+ model = LlavaForConditionalGeneration.from_pretrained(model_id, torch_dtype=dtype_modernos).to(device)
131
  prompt = f"USER: <image>\n{prompt_vlms}\nASSISTANT:"
132
+ inputs = processor(images=imagem, text=prompt, return_tensors="pt").to(device)
133
  out = model.generate(**inputs, max_new_tokens=max_tok)
134
  texto_gerado = processor.decode(out[0], skip_special_tokens=True)
135
  texto_en = texto_gerado.split("ASSISTANT:")[-1].strip()
 
140
 
141
  return tuple(resultados)
142
 
143
+ # Construindo a Interface Gráfica
144
+ # O aviso do Gradio sumiu pois retiramos o 'theme' daqui...
145
+ with gr.Blocks() as demo:
146
  gr.Markdown("# 👁️ Linha do Tempo: Modelos Visuais")
147
  gr.Markdown("Faça o upload de uma imagem, selecione a complexidade da análise e observe o salto tecnológico. **Sistema Híbrido:** Adapta-se automaticamente entre CPU gratuita ou aceleração de GPU.")
148
 
 
175
  )
176
 
177
  if __name__ == "__main__":
178
+ # ... e passamos o 'theme' para a etapa de inicialização (launch), como manda a nova regra!
179
+ demo.launch(theme=gr.themes.Base())