20251119_temp1 / inference7.py
xcll's picture
Upload inference7.py with huggingface_hub
8f5674d verified
import numpy as np
import torch
import torchvision.transforms as T
from decord import VideoReader, cpu
from PIL import Image
from torchvision.transforms.functional import InterpolationMode
from transformers import AutoModel, AutoTokenizer
import json
import os
import random
IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD = (0.229, 0.224, 0.225)
def build_transform(input_size):
MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
transform = T.Compose([
T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
T.ToTensor(),
T.Normalize(mean=MEAN, std=STD)
])
return transform
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
best_ratio_diff = float('inf')
best_ratio = (1, 1)
area = width * height
for ratio in target_ratios:
target_aspect_ratio = ratio[0] / ratio[1]
ratio_diff = abs(aspect_ratio - target_aspect_ratio)
if ratio_diff < best_ratio_diff:
best_ratio_diff = ratio_diff
best_ratio = ratio
elif ratio_diff == best_ratio_diff:
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
best_ratio = ratio
return best_ratio
def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
orig_width, orig_height = image.size
aspect_ratio = orig_width / orig_height
target_ratios = set(
(i, j) for n in range(min_num, max_num + 1)
for i in range(1, n + 1)
for j in range(1, n + 1)
if i * j <= max_num and i * j >= min_num
)
target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
target_aspect_ratio = find_closest_aspect_ratio(
aspect_ratio, target_ratios, orig_width, orig_height, image_size)
target_width = image_size * target_aspect_ratio[0]
target_height = image_size * target_aspect_ratio[1]
blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
resized_img = image.resize((target_width, target_height))
processed_images = []
for i in range(blocks):
box = (
(i % (target_width // image_size)) * image_size,
(i // (target_width // image_size)) * image_size,
((i % (target_width // image_size)) + 1) * image_size,
((i // (target_width // image_size)) + 1) * image_size
)
split_img = resized_img.crop(box)
processed_images.append(split_img)
assert len(processed_images) == blocks
if use_thumbnail and len(processed_images) != 1:
thumbnail_img = image.resize((image_size, image_size))
processed_images.append(thumbnail_img)
return processed_images
def load_image(image_file, input_size=448, max_num=12):
image = Image.open(image_file).convert('RGB')
transform = build_transform(input_size=input_size)
images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
pixel_values = [transform(image) for image in images]
pixel_values = torch.stack(pixel_values)
return pixel_values
# def load_image(image_file, input_size=448, max_num=12):
# image = Image.open(image_file).convert('RGB')
# original_width, original_height = image.size
# if original_width > original_height:
# new_width = 448
# new_height = int(original_height * 448 / original_width)
# else:
# new_height = 448
# new_width = int(original_width * 448 / original_height)
# image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
# transform = build_transform(input_size=input_size)
# images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
# pixel_values = [transform(image) for image in images]
# pixel_values = torch.stack(pixel_values)
# return pixel_values
# ================== 模型加载部分 ==================
path = '/data/yyf/model/InternVL3-8B'
# path = '/data/yyf/model/InternVL2_5-8B'
model = AutoModel.from_pretrained(
path,
torch_dtype=torch.bfloat16,
low_cpu_mem_usage=True,
use_flash_attn=True,
trust_remote_code=True
).eval().cuda()
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
# generation_config = dict(max_new_tokens=1024, do_sample=False)
generation_config = dict(max_new_tokens=1024, do_sample=True, temperature=0.9)
q = """
You are an expert in visual consistency and image logic. You will receive only one edited image. Your task is to determine whether the edited image is valid according to all of the following criteria:
Counterfactual validity: The image should not contain elements that violate real-world common sense.
(Example: a ship flying in the sky, objects appearing in impossible locations.)
Physical consistency: The image should obey basic physical laws, including proper lighting, shadows, proportions, perspective, object interactions, and absence of impossible overlaps or collisions.
Edit-intent plausibility: Even without knowing the instruction, the edited content must appear visually plausible and coherent, without unnatural modifications or logically inconsistent alterations.
Scene and semantic coherence: All objects should logically belong in the scene with consistent style, material, color, and perspective.
Any other violations of visual logic: No impossible structures, contradictory geometry, or incoherent scene composition.
After evaluating all criteria above, output only one word:
"yes" — if the edited image satisfies all requirements
"no" — if the image fails any of the criteria
Do not include explanations, reasoning, or additional text. Output only "yes" or "no".
"""
# ================== 批量评估部分 ==================
image_dir = '/data/xcl/dataSet/images_entity'
output_json = '/data/xcl/dataSet/RSICD_1/acc/results.json'
# 支持的图片后缀
IMG_EXTS = ('.png', '.jpg', '.jpeg', '.bmp', '.webp')
results = {}
with torch.no_grad():
for fname in os.listdir(image_dir):
if not fname.lower().endswith(IMG_EXTS):
continue
fpath = os.path.join(image_dir, fname)
try:
pixel_values = load_image(fpath).to(torch.bfloat16).cuda()
question = '<image>\n' + q
response = model.chat(tokenizer, pixel_values, question, generation_config)
response_single_line = response.strip().replace('\n', ' ').replace('\r', ' ')
# 只保留 yes/no(保险起见转小写)
answer = response_single_line.strip().lower()
if 'yes' in answer and 'no' not in answer:
answer = 'yes'
elif 'no' in answer and 'yes' not in answer:
answer = 'no'
else:
# 如果模型输出不干净,就直接用原始(你也可以自定义默认值)
answer = 'no'
results[fname] = answer
print(f'Processed {fname}: {answer}')
except Exception as e:
print(f'Error processing {fpath}: {e}')
results[fname] = 'error'
# 保存为 JSON 文件
with open(output_json, 'w', encoding='utf-8') as f:
json.dump(results, f, ensure_ascii=False, indent=2)
print(f'Results saved to {output_json}')