Update app.py
Browse files
app.py
CHANGED
|
@@ -7,7 +7,7 @@ from deep_translator import GoogleTranslator
|
|
| 7 |
from transformers import (
|
| 8 |
BlipProcessor, BlipForConditionalGeneration,
|
| 9 |
VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer,
|
| 10 |
-
AutoProcessor, AutoModelForCausalLM, AutoConfig,
|
| 11 |
LlavaForConditionalGeneration, PaliGemmaForConditionalGeneration
|
| 12 |
)
|
| 13 |
|
|
@@ -19,12 +19,23 @@ def traduzir_para_pt(texto):
|
|
| 19 |
return f"{texto} (Erro na tradução: {str(e)})"
|
| 20 |
|
| 21 |
@spaces.GPU(duration=120)
|
| 22 |
-
def analisar_imagem(imagem):
|
| 23 |
if imagem is None:
|
| 24 |
return ["Nenhuma imagem carregada."] * 6
|
| 25 |
|
| 26 |
resultados = []
|
| 27 |
hf_token = os.environ.get("HF_TOKEN")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
# =========================================================
|
| 30 |
# GERAÇÃO CLÁSSICA (2021 - 2022)
|
|
@@ -36,7 +47,8 @@ def analisar_imagem(imagem):
|
|
| 36 |
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 37 |
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to("cuda")
|
| 38 |
inputs = processor(imagem, return_tensors="pt").to("cuda")
|
| 39 |
-
|
|
|
|
| 40 |
resultados.append(traduzir_para_pt(processor.decode(out[0], skip_special_tokens=True)))
|
| 41 |
del processor, model, inputs, out
|
| 42 |
gc.collect(); torch.cuda.empty_cache()
|
|
@@ -49,7 +61,7 @@ def analisar_imagem(imagem):
|
|
| 49 |
feature_extractor = ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
| 50 |
tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
| 51 |
pixel_values = feature_extractor(images=imagem, return_tensors="pt").pixel_values.to("cuda")
|
| 52 |
-
out = model.generate(pixel_values,
|
| 53 |
resultados.append(traduzir_para_pt(tokenizer.decode(out[0], skip_special_tokens=True)))
|
| 54 |
del model, feature_extractor, tokenizer, pixel_values, out
|
| 55 |
gc.collect(); torch.cuda.empty_cache()
|
|
@@ -61,7 +73,7 @@ def analisar_imagem(imagem):
|
|
| 61 |
processor = AutoProcessor.from_pretrained("microsoft/git-base-coco")
|
| 62 |
model = AutoModelForCausalLM.from_pretrained("microsoft/git-base-coco").to("cuda")
|
| 63 |
pixel_values = processor(images=imagem, return_tensors="pt").pixel_values.to("cuda")
|
| 64 |
-
out = model.generate(pixel_values=pixel_values,
|
| 65 |
resultados.append(traduzir_para_pt(processor.decode(out[0], skip_special_tokens=True)))
|
| 66 |
del processor, model, pixel_values, out
|
| 67 |
gc.collect(); torch.cuda.empty_cache()
|
|
@@ -75,26 +87,19 @@ def analisar_imagem(imagem):
|
|
| 75 |
try:
|
| 76 |
print("Carregando Moondream2...")
|
| 77 |
model_id = "vikhyatk/moondream2"
|
| 78 |
-
|
| 79 |
-
# O CURATIVO: Baixamos a configuração e injetamos o token ausente
|
| 80 |
config = AutoConfig.from_pretrained(model_id, trust_remote_code=True, revision="2024-08-26")
|
| 81 |
if not hasattr(config, "pad_token_id"):
|
| 82 |
-
config.pad_token_id = 50256
|
| 83 |
|
| 84 |
-
# Agora carregamos o modelo passando a configuração corrigida
|
| 85 |
model = AutoModelForCausalLM.from_pretrained(
|
| 86 |
-
model_id,
|
| 87 |
-
|
| 88 |
-
trust_remote_code=True,
|
| 89 |
-
revision="2024-08-26",
|
| 90 |
-
torch_dtype=torch.float16
|
| 91 |
).to("cuda")
|
| 92 |
-
|
| 93 |
tokenizer = AutoTokenizer.from_pretrained(model_id, revision="2024-08-26")
|
| 94 |
enc_image = model.encode_image(imagem)
|
| 95 |
-
|
|
|
|
| 96 |
resultados.append(traduzir_para_pt(texto_en))
|
| 97 |
-
|
| 98 |
del config, model, tokenizer, enc_image
|
| 99 |
gc.collect(); torch.cuda.empty_cache()
|
| 100 |
except Exception as e: resultados.append(f"Erro Moondream2: {str(e)}")
|
|
@@ -105,8 +110,9 @@ def analisar_imagem(imagem):
|
|
| 105 |
model_id = "google/paligemma-3b-mix-224"
|
| 106 |
processor = AutoProcessor.from_pretrained(model_id, token=hf_token)
|
| 107 |
model = PaliGemmaForConditionalGeneration.from_pretrained(model_id, torch_dtype=torch.float16, token=hf_token).to("cuda")
|
|
|
|
| 108 |
inputs = processor(text="caption", images=imagem, return_tensors="pt").to("cuda")
|
| 109 |
-
out = model.generate(**inputs, max_new_tokens=
|
| 110 |
resultados.append(traduzir_para_pt(processor.decode(out[0], skip_special_tokens=True)))
|
| 111 |
del processor, model, inputs, out
|
| 112 |
gc.collect(); torch.cuda.empty_cache()
|
|
@@ -118,9 +124,10 @@ def analisar_imagem(imagem):
|
|
| 118 |
model_id = "llava-hf/llava-1.5-7b-hf"
|
| 119 |
processor = AutoProcessor.from_pretrained(model_id)
|
| 120 |
model = LlavaForConditionalGeneration.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
|
| 121 |
-
|
|
|
|
| 122 |
inputs = processor(images=imagem, text=prompt, return_tensors="pt").to("cuda")
|
| 123 |
-
out = model.generate(**inputs, max_new_tokens=
|
| 124 |
texto_gerado = processor.decode(out[0], skip_special_tokens=True)
|
| 125 |
texto_en = texto_gerado.split("ASSISTANT:")[-1].strip()
|
| 126 |
resultados.append(traduzir_para_pt(texto_en))
|
|
@@ -133,18 +140,24 @@ def analisar_imagem(imagem):
|
|
| 133 |
# Construindo a Interface Gráfica com 3 Colunas
|
| 134 |
with gr.Blocks(theme=gr.themes.Base()) as demo:
|
| 135 |
gr.Markdown("# 👁️ Linha do Tempo: Modelos Visuais")
|
| 136 |
-
gr.Markdown("Faça o upload de uma imagem
|
| 137 |
|
| 138 |
with gr.Row():
|
| 139 |
with gr.Column(scale=1):
|
| 140 |
entrada_imagem = gr.Image(type="pil", label="Imagem de Entrada")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
botao_analisar = gr.Button("Processar nos 6 Modelos", variant="primary")
|
| 142 |
|
| 143 |
with gr.Column(scale=1):
|
| 144 |
gr.Markdown("### Geração Clássica")
|
| 145 |
-
saida_blip = gr.Textbox(label="BLIP (Salesforce - Fev/2022)", lines=
|
| 146 |
-
saida_vit = gr.Textbox(label="ViT-GPT2 (NLP Connect - 2021)", lines=
|
| 147 |
-
saida_git = gr.Textbox(label="GIT (Microsoft - Mai/2022)", lines=
|
| 148 |
|
| 149 |
with gr.Column(scale=1):
|
| 150 |
gr.Markdown("### Geração Moderna (VLMs)")
|
|
@@ -154,7 +167,8 @@ with gr.Blocks(theme=gr.themes.Base()) as demo:
|
|
| 154 |
|
| 155 |
botao_analisar.click(
|
| 156 |
fn=analisar_imagem,
|
| 157 |
-
inputs
|
|
|
|
| 158 |
outputs=[saida_blip, saida_vit, saida_git, saida_moon, saida_pali, saida_llava]
|
| 159 |
)
|
| 160 |
|
|
|
|
| 7 |
from transformers import (
|
| 8 |
BlipProcessor, BlipForConditionalGeneration,
|
| 9 |
VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer,
|
| 10 |
+
AutoProcessor, AutoModelForCausalLM, AutoConfig,
|
| 11 |
LlavaForConditionalGeneration, PaliGemmaForConditionalGeneration
|
| 12 |
)
|
| 13 |
|
|
|
|
| 19 |
return f"{texto} (Erro na tradução: {str(e)})"
|
| 20 |
|
| 21 |
@spaces.GPU(duration=120)
|
| 22 |
+
def analisar_imagem(imagem, tamanho):
|
| 23 |
if imagem is None:
|
| 24 |
return ["Nenhuma imagem carregada."] * 6
|
| 25 |
|
| 26 |
resultados = []
|
| 27 |
hf_token = os.environ.get("HF_TOKEN")
|
| 28 |
+
|
| 29 |
+
# Mapeando a escolha do usuário para limites técnicos e prompts semânticos
|
| 30 |
+
if "Pequeno" in tamanho:
|
| 31 |
+
max_tok = 40
|
| 32 |
+
prompt_vlms = "Describe this image briefly in one or two sentences."
|
| 33 |
+
elif "Médio" in tamanho:
|
| 34 |
+
max_tok = 120
|
| 35 |
+
prompt_vlms = "Describe this image in detail."
|
| 36 |
+
else: # Grande
|
| 37 |
+
max_tok = 300
|
| 38 |
+
prompt_vlms = "Describe every element of this image in extensive and exhaustive detail."
|
| 39 |
|
| 40 |
# =========================================================
|
| 41 |
# GERAÇÃO CLÁSSICA (2021 - 2022)
|
|
|
|
| 47 |
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
|
| 48 |
model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to("cuda")
|
| 49 |
inputs = processor(imagem, return_tensors="pt").to("cuda")
|
| 50 |
+
# Força o modelo a tentar gerar o tamanho solicitado
|
| 51 |
+
out = model.generate(**inputs, max_new_tokens=max_tok)
|
| 52 |
resultados.append(traduzir_para_pt(processor.decode(out[0], skip_special_tokens=True)))
|
| 53 |
del processor, model, inputs, out
|
| 54 |
gc.collect(); torch.cuda.empty_cache()
|
|
|
|
| 61 |
feature_extractor = ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
| 62 |
tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
| 63 |
pixel_values = feature_extractor(images=imagem, return_tensors="pt").pixel_values.to("cuda")
|
| 64 |
+
out = model.generate(pixel_values, max_new_tokens=max_tok, num_beams=4)
|
| 65 |
resultados.append(traduzir_para_pt(tokenizer.decode(out[0], skip_special_tokens=True)))
|
| 66 |
del model, feature_extractor, tokenizer, pixel_values, out
|
| 67 |
gc.collect(); torch.cuda.empty_cache()
|
|
|
|
| 73 |
processor = AutoProcessor.from_pretrained("microsoft/git-base-coco")
|
| 74 |
model = AutoModelForCausalLM.from_pretrained("microsoft/git-base-coco").to("cuda")
|
| 75 |
pixel_values = processor(images=imagem, return_tensors="pt").pixel_values.to("cuda")
|
| 76 |
+
out = model.generate(pixel_values=pixel_values, max_new_tokens=max_tok)
|
| 77 |
resultados.append(traduzir_para_pt(processor.decode(out[0], skip_special_tokens=True)))
|
| 78 |
del processor, model, pixel_values, out
|
| 79 |
gc.collect(); torch.cuda.empty_cache()
|
|
|
|
| 87 |
try:
|
| 88 |
print("Carregando Moondream2...")
|
| 89 |
model_id = "vikhyatk/moondream2"
|
|
|
|
|
|
|
| 90 |
config = AutoConfig.from_pretrained(model_id, trust_remote_code=True, revision="2024-08-26")
|
| 91 |
if not hasattr(config, "pad_token_id"):
|
| 92 |
+
config.pad_token_id = 50256
|
| 93 |
|
|
|
|
| 94 |
model = AutoModelForCausalLM.from_pretrained(
|
| 95 |
+
model_id, config=config, trust_remote_code=True,
|
| 96 |
+
revision="2024-08-26", torch_dtype=torch.float16
|
|
|
|
|
|
|
|
|
|
| 97 |
).to("cuda")
|
|
|
|
| 98 |
tokenizer = AutoTokenizer.from_pretrained(model_id, revision="2024-08-26")
|
| 99 |
enc_image = model.encode_image(imagem)
|
| 100 |
+
# O Moondream2 reage muito bem a mudanças no prompt
|
| 101 |
+
texto_en = model.answer_question(enc_image, prompt_vlms, tokenizer)
|
| 102 |
resultados.append(traduzir_para_pt(texto_en))
|
|
|
|
| 103 |
del config, model, tokenizer, enc_image
|
| 104 |
gc.collect(); torch.cuda.empty_cache()
|
| 105 |
except Exception as e: resultados.append(f"Erro Moondream2: {str(e)}")
|
|
|
|
| 110 |
model_id = "google/paligemma-3b-mix-224"
|
| 111 |
processor = AutoProcessor.from_pretrained(model_id, token=hf_token)
|
| 112 |
model = PaliGemmaForConditionalGeneration.from_pretrained(model_id, torch_dtype=torch.float16, token=hf_token).to("cuda")
|
| 113 |
+
# PaliGemma usa a string "caption" base, mas limitamos sua saída com max_new_tokens
|
| 114 |
inputs = processor(text="caption", images=imagem, return_tensors="pt").to("cuda")
|
| 115 |
+
out = model.generate(**inputs, max_new_tokens=max_tok)
|
| 116 |
resultados.append(traduzir_para_pt(processor.decode(out[0], skip_special_tokens=True)))
|
| 117 |
del processor, model, inputs, out
|
| 118 |
gc.collect(); torch.cuda.empty_cache()
|
|
|
|
| 124 |
model_id = "llava-hf/llava-1.5-7b-hf"
|
| 125 |
processor = AutoProcessor.from_pretrained(model_id)
|
| 126 |
model = LlavaForConditionalGeneration.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
|
| 127 |
+
# Ajustamos o prompt de acordo com o tamanho desejado
|
| 128 |
+
prompt = f"USER: <image>\n{prompt_vlms}\nASSISTANT:"
|
| 129 |
inputs = processor(images=imagem, text=prompt, return_tensors="pt").to("cuda")
|
| 130 |
+
out = model.generate(**inputs, max_new_tokens=max_tok)
|
| 131 |
texto_gerado = processor.decode(out[0], skip_special_tokens=True)
|
| 132 |
texto_en = texto_gerado.split("ASSISTANT:")[-1].strip()
|
| 133 |
resultados.append(traduzir_para_pt(texto_en))
|
|
|
|
| 140 |
# Construindo a Interface Gráfica com 3 Colunas
|
| 141 |
with gr.Blocks(theme=gr.themes.Base()) as demo:
|
| 142 |
gr.Markdown("# 👁️ Linha do Tempo: Modelos Visuais")
|
| 143 |
+
gr.Markdown("Faça o upload de uma imagem, selecione a complexidade da análise e observe o salto tecnológico.")
|
| 144 |
|
| 145 |
with gr.Row():
|
| 146 |
with gr.Column(scale=1):
|
| 147 |
entrada_imagem = gr.Image(type="pil", label="Imagem de Entrada")
|
| 148 |
+
# Adicionado o seletor de tamanho logo abaixo da imagem
|
| 149 |
+
seletor_tamanho = gr.Radio(
|
| 150 |
+
choices=["Pequeno (aprox. 3 linhas)", "Médio (aprox. 6 linhas)", "Grande (aprox. 10 linhas)"],
|
| 151 |
+
value="Médio (aprox. 6 linhas)",
|
| 152 |
+
label="Extensão da Descrição"
|
| 153 |
+
)
|
| 154 |
botao_analisar = gr.Button("Processar nos 6 Modelos", variant="primary")
|
| 155 |
|
| 156 |
with gr.Column(scale=1):
|
| 157 |
gr.Markdown("### Geração Clássica")
|
| 158 |
+
saida_blip = gr.Textbox(label="BLIP (Salesforce - Fev/2022)", lines=4)
|
| 159 |
+
saida_vit = gr.Textbox(label="ViT-GPT2 (NLP Connect - 2021)", lines=4)
|
| 160 |
+
saida_git = gr.Textbox(label="GIT (Microsoft - Mai/2022)", lines=4)
|
| 161 |
|
| 162 |
with gr.Column(scale=1):
|
| 163 |
gr.Markdown("### Geração Moderna (VLMs)")
|
|
|
|
| 167 |
|
| 168 |
botao_analisar.click(
|
| 169 |
fn=analisar_imagem,
|
| 170 |
+
# Atualizamos os inputs para enviar a imagem e a escolha de tamanho
|
| 171 |
+
inputs=[entrada_imagem, seletor_tamanho],
|
| 172 |
outputs=[saida_blip, saida_vit, saida_git, saida_moon, saida_pali, saida_llava]
|
| 173 |
)
|
| 174 |
|