"""Auto-Describe: write a prompt from an uploaded image with the pipeline's own Qwen-VL. Qwen Image's text encoder is a complete Qwen-VL chat model (lm_head included), so captioning reuses weights that are already on the GPU: no extra download or memory. Everything except `describe` is pure Python and runs on CPU in the tests. """ import contextlib import re from PIL import Image, ImageOps MAX_EDGE = 1024 MAX_NEW_TOKENS = 220 RECREATE_INSTRUCTION = ( "Write one prompt for an image generation model that would recreate this image. " "Cover the main subject and their appearance, clothing, pose and expression; the setting " "and background; the lighting and colours; the camera framing and angle; and the visual " "style or medium. Write one flowing paragraph of 60 to 120 words with concrete visual " "facts only. No preamble, no lists, no headings, no quotation marks." ) SCENE_INSTRUCTION = ( "Describe the scene in this image so it can be extended seamlessly beyond its borders: " "the setting, background, ground, sky or walls, lighting direction, colours and visual style. " "Write one paragraph of 30 to 60 words with concrete visual facts only. " "No preamble, no lists, no quotation marks." ) _LABEL = re.compile(r"^\s*(?:\*\*)?(?:prompt|description|image prompt|scene)(?:\*\*)?\s*[:\-–]\s*", re.I) _PREAMBLE = re.compile(r"^\s*(?:here is|here's|sure[,!.]?)[^:\n]{0,80}:\s*", re.I) def source_image(image1, image2=None): """Image 1 first, then Image 2; returns (image, label).""" if image1 is not None: return image1, "Image 1" if image2 is not None: return image2, "Image 2" raise ValueError("Upload an image first. Auto-Describe writes the prompt from Image 1.") def prepare_image(image): """Upright, flattened RGB no larger than MAX_EDGE, which keeps the vision token count small.""" if not isinstance(image, Image.Image): image = Image.fromarray(image) image = ImageOps.exif_transpose(image).copy() if image.mode in ("RGBA", "LA") or (image.mode == "P" and "transparency" in image.info): rgba = image.convert("RGBA") flat = Image.new("RGB", rgba.size, (255, 255, 255)) flat.paste(rgba, mask=rgba.getchannel("A")) image = flat else: image = image.convert("RGB") image.thumbnail((MAX_EDGE, MAX_EDGE), Image.Resampling.LANCZOS) return image def instruction(scene_only=False): return SCENE_INSTRUCTION if scene_only else RECREATE_INSTRUCTION def clean(text): """Strip reasoning, labels, Markdown and quotes; reject an empty caption.""" text = re.sub(r".*?", " ", str(text or ""), flags=re.S | re.I) text = re.sub(r"^.*?", " ", text, flags=re.S | re.I) text = _LABEL.sub("", _PREAMBLE.sub("", text.strip())) text = re.sub(r"[*_#`]+", "", text) text = " ".join(text.split()).strip().strip("\"'“”‘’").strip() if len(text) < 15: raise ValueError("Qwen-VL returned no usable description. Your prompt is unchanged.") return text def compose(description, preset=None): """Outpaint keeps its fill instruction and gains the scene; other modes use the description.""" if not preset: return description return f"{str(preset).strip()} The scene: {description}" @contextlib.contextmanager def adapters_disabled(model): """Turn off PEFT LoRA layers on this model only, restoring each layer's own state afterwards.""" layers = [module for module in model.modules() if isinstance(getattr(module, "_disable_adapters", None), bool)] states = [layer._disable_adapters for layer in layers] try: for layer in layers: layer._disable_adapters = True yield finally: for layer, state in zip(layers, states): layer._disable_adapters = state def describe(model, processor, image, scene_only=False, max_new_tokens=MAX_NEW_TOKENS): """Caption `image` with a Qwen-VL ForConditionalGeneration model and its processor.""" import torch messages = [{"role": "user", "content": [ {"type": "image", "image": prepare_image(image)}, {"type": "text", "text": instruction(scene_only)}, ]}] inputs = processor.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt") device = next(model.parameters()).device inputs = inputs.to(device) tokenizer = getattr(processor, "tokenizer", processor) with torch.inference_mode(), adapters_disabled(model): output = model.generate( **inputs, max_new_tokens=int(max_new_tokens), do_sample=False, repetition_penalty=1.05, pad_token_id=tokenizer.pad_token_id or tokenizer.eos_token_id) reply = processor.batch_decode(output[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)[0] return clean(reply)