20251119_temp1 / inference.py
xcll's picture
Upload inference.py with huggingface_hub
70299db verified
# import torch
# from diffusers import FluxKontextPipeline, FluxPipeline
# from diffusers.utils import load_image
# pipe = FluxKontextPipeline.from_pretrained("/data/xcl/Flux-Kontext/model/FLUX-Kontext-dev", torch_dtype=torch.bfloat16)
# # pipe.to("cuda")
# pipe.enable_model_cpu_offload()
# pipe.image_processor
# input_image = load_image("/data/xcl/dataSet/RSICD_1/test_png/7.png")
# image = pipe(
# image=input_image,
# # prompt="Make the paper in the image appear wrinkled and crumpled.",
# # prompt="Make the handwriting appear messy and wobbly, as if written by a student in a hurry or with uneven hand pressure. Keep the same content and layout.",
# # prompt="Make the text in the image look like it was handwritten perfunctorily on paper.",
# # prompt="Reduce overall brightness, add mild shadows, and lower contrast slightly while keeping the handwriting readable.",
# # prompt="Change the background to look like aged, yellowed paper with slight stains or discoloration.",
# # prompt="Add a few natural-looking coffee stains or water rings to the background",
# prompt="Replace planes with trucks.",
# guidance_scale=2.5,
# height=512,
# width=512,
# ).images[0]
# image.save("junshi.png")
# import faulthandler
# # 在import之后直接添加以下启用代码即可
# faulthandler.enable()
# import torch
# from diffusers import FluxKontextPipeline
# from diffusers.utils import load_image
# pipe = FluxKontextPipeline.from_pretrained("/data/xcl/Flux-Kontext/model/FLUX-Kontext-dev", torch_dtype=torch.bfloat16, device_map="balanced")
# # pipe = FluxKontextPipeline.from_pretrained("/data/xcl/model/flux-kontext", torch_dtype=torch.bfloat16)
# # pipe.to("cuda")
# # pipe.enable_model_cpu_offload()
# input_image = load_image("/data/xcl/dataSet/images/8.png")
# # input_image = input_image.resize((512, 512))
# image = pipe(
# image=input_image,
# prompt="Replace the ships with airplanes.",
# guidance_scale=2.5,
# ).images[0]
# image.save("8.png")
# import os
# import json
# from PIL import Image
# import torch
# from diffusers import FluxKontextPipeline
# def process_images():
# # 初始化管道 - 使用 FluxKontextPipeline
# pipeline = FluxKontextPipeline.from_pretrained(
# "/data/xcl/Flux-Kontext/model/FLUX-Kontext-dev",
# torch_dtype=torch.bfloat16,
# device_map="balanced"
# )
# # 启用 CPU offload 以节省显存
# # pipeline.enable_model_cpu_offload()
# print("FluxKontextPipeline loaded with automatic device mapping and CPU offload.")
# pipeline.set_progress_bar_config(disable=None)
# # 路径配置
# input_dir = "/data/xcl/dataSet/images"
# output_dir = "/data/xcl/dataSet/images_entity_kontext"
# json_file = "/data/xcl/dataSet/junshi_images_entity.json"
# # 创建输出目录
# os.makedirs(output_dir, exist_ok=True)
# # 加载JSON文件
# with open(json_file, 'r') as f:
# prompt_dict = json.load(f)
# print(f"Loaded {len(prompt_dict)} image prompts from JSON file.")
# # 处理每张图片
# processed_count = 0
# for filename, prompt in prompt_dict.items():
# input_path = os.path.join(input_dir, filename)
# output_path = os.path.join(output_dir, filename)
# # 检查输入图片是否存在
# if not os.path.exists(input_path):
# print(f"Warning: Image {input_path} not found, skipping...")
# continue
# # 检查输出是否已存在(避免重复处理)
# if os.path.exists(output_path):
# print(f"Warning: Output {output_path} already exists, skipping...")
# continue
# try:
# # 加载并处理图片
# image = Image.open(input_path).convert("RGB")
# width, height = image.size
# # 准备输入参数 - 根据新模型的API调整
# inputs = {
# "image": image,
# "prompt": prompt,
# "guidance_scale": 2.5, # 新模型使用 guidance_scale 而不是 true_cfg_scale
# "height": height, # 使用输入图像的高度
# "width": width, # 使用输入图像的宽度
# # "generator": torch.manual_seed(0), # 新模型可能不需要这个参数
# # "negative_prompt": " ", # 新模型可能不需要negative_prompt
# # "num_inference_steps": 50, # 新模型可能使用默认步数
# }
# # 执行图像编辑
# with torch.inference_mode():
# output = pipeline(**inputs)
# output_image = output.images[0]
# output_image.save(output_path)
# # 清理GPU缓存
# if torch.cuda.is_available():
# torch.cuda.empty_cache()
# processed_count += 1
# print(f"Processed {filename} -> {output_path}")
# except Exception as e:
# print(f"Error processing {filename}: {str(e)}")
# # 出错时也清理GPU缓存
# if torch.cuda.is_available():
# torch.cuda.empty_cache()
# continue
# print(f"Processing completed! Successfully processed {processed_count} images.")
# if __name__ == "__main__":
# process_images()
import os
import json
from PIL import Image
import torch
from diffusers import FluxKontextPipeline
def resize_image_if_needed(image, max_size=1024):
"""
如果图片的最长边超过max_size,则按比例调整大小
"""
width, height = image.size
max_dimension = max(width, height)
if max_dimension <= max_size:
return image
# 计算新的尺寸,保持宽高比
if width > height:
new_width = max_size
new_height = int(height * (max_size / width))
else:
new_height = max_size
new_width = int(width * (max_size / height))
# 使用LANCZOS重采样以获得更好的质量
resized_image = image.resize((new_width, new_height), Image.LANCZOS)
print(f"Resized image from {width}x{height} to {new_width}x{new_height}")
return resized_image
def process_images():
# 初始化管道 - 使用 FluxKontextPipeline
pipeline = FluxKontextPipeline.from_pretrained(
"/data/xcl/Flux-Kontext/model/FLUX-Kontext-dev",
torch_dtype=torch.bfloat16,
device_map="balanced"
)
# 启用 CPU offload 以节省显存
# pipeline.enable_model_cpu_offload()
print("FluxKontextPipeline loaded with automatic device mapping and CPU offload.")
pipeline.set_progress_bar_config(disable=None)
# 路径配置
input_dir = "/data/xcl/dataSet/images"
output_dir = "/data/xcl/dataSet/images_entity_background_kontext"
json_file = "/data/xcl/dataSet/junshi_images_entity_background.json"
# 创建输出目录
os.makedirs(output_dir, exist_ok=True)
# 加载JSON文件
with open(json_file, 'r') as f:
prompt_dict = json.load(f)
print(f"Loaded {len(prompt_dict)} image prompts from JSON file.")
# 处理每张图片
processed_count = 0
for filename, prompt in prompt_dict.items():
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
# 检查输入图片是否存在
if not os.path.exists(input_path):
print(f"Warning: Image {input_path} not found, skipping...")
continue
# 检查输出是否已存在(避免重复处理)
if os.path.exists(output_path):
print(f"Warning: Output {output_path} already exists, skipping...")
continue
try:
# 加载图片
image = Image.open(input_path).convert("RGB")
original_width, original_height = image.size
# 检查并调整图片尺寸
image = resize_image_if_needed(image, max_size=1024)
new_width, new_height = image.size
# 准备输入参数 - 根据新模型的API调整
inputs = {
"image": image,
"prompt": prompt,
"guidance_scale": 2.5, # 新模型使用 guidance_scale 而不是 true_cfg_scale
"height": new_height, # 使用调整后的高度
"width": new_width, # 使用调整后的宽度
# "generator": torch.manual_seed(0), # 新模型可能不需要这个参数
# "negative_prompt": " ", # 新模型可能不需要negative_prompt
# "num_inference_steps": 50, # 新模型可能使用默认步数
}
# 执行图像编辑
with torch.inference_mode():
output = pipeline(**inputs)
output_image = output.images[0]
output_image.save(output_path)
# 清理GPU缓存
if torch.cuda.is_available():
torch.cuda.empty_cache()
processed_count += 1
print(f"Processed {filename} (original: {original_width}x{original_height}, processed: {new_width}x{new_height}) -> {output_path}")
except Exception as e:
print(f"Error processing {filename}: {str(e)}")
# 出错时也清理GPU缓存
if torch.cuda.is_available():
torch.cuda.empty_cache()
continue
print(f"Processing completed! Successfully processed {processed_count} images.")
if __name__ == "__main__":
process_images()