Spaces:
Running on Zero

moss-reverse / app.py
jing96963's picture
reverse_dev: actually pass dev prompt to infer
89f2307 verified
Raw History Blame Contribute Delete
18.4 kB
"""Private ZeroGPU poster -> MOSS layout API. No remote-code model loading."""
import gc
import os
import re
import threading
import time
import spaces # Must precede torch for ZeroGPU CUDA emulation.
import torch
import gradio as gr
import transformers
from PIL import ImageOps
from transformers import AutoProcessor
from layout_convert import convert_layout, parse_output
MODEL_IDS = ("huihui-ai/Huihui-Qwen3.5-9B-abliterated",
"huihui-ai/Huihui-Qwen3-VL-8B-Instruct-abliterated")
DEFAULT_MODEL = os.getenv("REVERSE_MODEL", MODEL_IDS[1]) # Qwen3-VL-8B bf16: best boxes + fastest in the 10-24 test
if DEFAULT_MODEL not in MODEL_IDS:
raise ValueError("REVERSE_MODEL must be one of MODEL_IDS")
CHOICES = [f"{model} | {mode}" for model in MODEL_IDS for mode in ("bf16", "fp8")]
DEFAULT_CHOICE = f"{DEFAULT_MODEL} | {'fp8' if os.getenv('REVERSE_FP8') == '1' else 'bf16'}"
CACHE = {}
LOCK = threading.Lock()
PROMPT = '''把这张海报拆成可编辑图层,只输出严格 JSON(desc 和 caption 用中文)。格式:
{"caption":"整体描述,必须依次写出:①画风/质感(写实摄影、写实 CG、3D 卡通、厚涂插画、扁平插画等,人物和动物分别是什么质感);②镜头视角(平视、俯拍、仰拍、鱼眼广角、自拍视角等);③主体之间的动作和互动(谁在对谁做什么,例如:巨大的白猫用前爪捏着小女孩的毛线帽把她提起来);④主体的相对大小(例如:猫占右侧大半画面,女孩约画面三分之一高);⑤背景和前景",
"items":[{"kind":"subject|shape|text","label":"object|text","text":"文字原文(仅 text)",
"desc":"是什么 + 外观(颜色、材质、描边);文字项写成具体的字体设计语言,例如:粉紫色霓虹灯泡字,边缘一圈发光小灯泡 / 3D 立体圆润软糖字,有厚度和高光,带发光描边 / 毛笔书法字,笔锋拉丝飞白","bbox_2d":[x1,y1,x2,y2],"rotation":0}]}
kind 含义:subject = 人物、动物、产品等主体;shape = 装饰图形:文字下面的色块/底衬、毛笔笔刷/笔触、色带、徽章底、贴纸、线条;text = 文字。
拆分规则(最重要):
1. 每个人物/主体单独一项,几个人就写几项;主体的 desc 必须写出它的质感(写实/卡通等)、动作姿态、和其他主体的互动、在画面中的大小;同一个物体只写一项,不要重复,也不要输出覆盖整张图的框。框按物体在画面中的真实大小标,主体之间的大小比例要如实。
2. 文字下面如果有色块、笔刷笔触、色带等底衬,必须单独写成一项 shape,不能合并进文字的描述;画面里画出来的物件(如一支毛笔)也单独一项。
3. 多行文字按行拆:每一行单独一项 text,单独的大号符号(如末尾的感叹号「!」)也单独一项 text。
4. desc 第一短句必须是简短名称(如「左侧戴墨镜的女子」「紫色笔触底衬」),然后用逗号接外观描述。
5. 文字下方或背后的彩色笔触/横条(哪怕只是一道刷痕)要单独一项 shape,和画出来的毛笔物件是两项。
6. 不输出背景本身,背景写进 caption;忽略界面元素(关闭按钮、水印)。
7. items 按从底到顶的绘制顺序:主体 → 文字下面的底衬/笔刷 → 文字。
8. bbox_2d 用 0–1000 相对坐标 [左,上,右,下],紧贴该元素的可见范围。
9. rotation:元素明显倾斜时填角度(负数=逆时针、左低右高;正数=顺时针),水平写 0。
示例(另一张图):{"caption":"…","items":[
{"kind":"subject","label":"object","desc":"穿红色卫衣的男孩,站立微笑","bbox_2d":[120,200,480,980],"rotation":0},
{"kind":"shape","label":"object","desc":"黄色毛笔笔触底衬","bbox_2d":[520,60,960,170],"rotation":-5},
{"kind":"text","label":"text","text":"新品上市","desc":"黑色粗体毛笔字","bbox_2d":[560,70,920,160],"rotation":-5},
{"kind":"text","label":"text","text":"限时五折","desc":"白色粗黑体,红色描边","bbox_2d":[540,700,940,800],"rotation":0}]}
只返回 JSON,不要 Markdown 或思考过程。'''
def load_variant(choice):
"""Runs in the CPU handler BEFORE entering @spaces.GPU; one variant only.
Default is also loaded at module scope. ZeroGPU intercepts .to('cuda')
outside GPU functions; do not query torch.cuda here.
"""
if choice not in CHOICES:
raise ValueError("未知 model 变体")
if choice in CACHE:
return CACHE[choice]
model_id, requested = choice.split(" | ")
processor = AutoProcessor.from_pretrained(model_id)
factory = getattr(transformers, "AutoModelForMultimodalLM", None) or transformers.AutoModelForImageTextToText
mode, warning = requested, None
kwargs = {"dtype": torch.bfloat16, "low_cpu_mem_usage": True}
def build(fp8):
options = dict(kwargs)
if fp8:
# On-the-fly quantization of BF16 source weights, not an FP8 checkpoint.
options.update(quantization_config=transformers.FineGrainedFP8Config(), device_map={"": "cuda"})
loaded = factory.from_pretrained(model_id, **options)
return loaded.eval().to("cuda")
# No silent bf16 fallback here: all variants stay resident, so a failed FP8
# load is reported via LOAD_ERRORS instead of duplicating the bf16 weights.
model = build(requested == "fp8")
if requested == "fp8":
gc.collect()
CACHE[choice] = (model, processor, model_id, mode, warning)
return CACHE[choice]
MAX_SIDE = int(os.getenv("REVERSE_MAX_SIDE", "1024"))
def shrink(image):
"""Vision tokens grow with pixel count; a 1760x2346 poster costs ~4x a 1024 one.
Layout coordinates are relative (0-1000), so downscaling does not move boxes."""
image = ImageOps.exif_transpose(image).convert("RGB")
if max(image.size) > MAX_SIDE:
image = image.copy()
image.thumbnail((MAX_SIDE, MAX_SIDE))
return image
@spaces.GPU(duration=int(os.getenv("REVERSE_GPU_SECONDS", "90")))
def infer(image, choice, prompt=None):
model, processor, _, _, _ = CACHE[choice]
torch.cuda.reset_peak_memory_stats()
t0 = time.perf_counter()
raw = ""
for attempt in range(2):
messages = [{"role": "user", "content": [{"type": "image", "image": image},
{"type": "text", "text": (prompt or PROMPT) + ("\n只输出 JSON。上一次输出无效,请重新完整输出。" if attempt else "")}]}]
inputs = processor.apply_chat_template(messages, tokenize=True, add_generation_prompt=True,
enable_thinking=False, return_dict=True, return_tensors="pt")
inputs = inputs.to("cuda")
with torch.inference_mode():
generated = model.generate(**inputs, max_new_tokens=4096, do_sample=False)
raw = processor.batch_decode(generated[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)[0]
try:
parsed = parse_output(raw)
result = convert_layout(parsed, image.width, image.height)
result["gpu_seconds"] = round(time.perf_counter() - t0, 3)
return result, raw, torch.cuda.max_memory_allocated() / 1024**3
except ValueError:
if attempt:
raise gr.Error("模型两次未返回有效的排版 JSON:" + raw[:1500]) from None
finally:
del inputs, generated
def reverse(image, model=DEFAULT_CHOICE, _prompt=None):
if image is None:
raise gr.Error("请上传图片")
started = time.perf_counter()
image = shrink(image)
# Serialize loading + GPU invocation, preventing eviction during inference.
with LOCK:
choice = model or DEFAULT_CHOICE
if choice not in CACHE:
raise gr.Error(f"该变体未加载:{LOAD_ERRORS.get(choice, '未知原因')}")
result, raw, memory = infer(image, choice, _prompt)
_, _, model_id, mode, warning = CACHE[choice]
result.update(raw=raw, model=model_id, mode=mode, seconds=round(time.perf_counter()-started, 3), gpu_mem_gb=memory)
if warning:
result["warning"] = warning
return result
# Test-only prompt version, reachable only through api_name="reverse_dev"; the
# live /reverse used by the website keeps PROMPT until a release is approved.
PROMPT_DEV = PROMPT.replace("只返回 JSON,不要 Markdown 或思考过程。", """补充要求(画风判断很重要):
- 先判断质感:写实照片(真实皮肤毛孔、真实毛发、相机景深)/ 写实 CG(接近真实但更干净完美)/ 3D 卡通(皮克斯式夸张大眼、塑料或黏土质感)/ 2D 插画。人物和动物分别判断,不要因为画面有发光字或装饰就判成卡通;判断依据写进 caption。
- 主体 desc 里写清姿态:是否悬空、被谁提起或抱着、四肢朝向;有肢体伸向镜头、近大远小、鱼眼广角、自拍视角时要写明。
只返回 JSON,不要 Markdown 或思考过程。""")
def reverse_dev(image, model=DEFAULT_CHOICE):
return reverse(image, model, PROMPT_DEV)
CAPTION_PROMPTS = {
("zh", "详细"): """看这张图,写一段可以直接用于 AI 生图的中文提示词。只输出提示词本身,不要标题、编号、解释或 Markdown。
按顺序覆盖:画面主体;每个人物的性别年龄感、外貌发型、服装配饰、表情、姿势和动作,以及他们在画面里的位置;场景和背景;构图和镜头(景别、视角);光线和色调;画风/摄影风格。
画面里如果有文字,按原文写出,用「」括起来,并说明字体风格、颜色和位置。画面里没有文字就不要写「」。写成连贯的一段话,约 150–300 字。""",
("zh", "简短"): """看这张图,写一句可以直接用于 AI 生图的中文提示词(40–80 字):主体、关键外观、场景、风格;画面里真有文字时才用「」写出原文,没有文字就不要出现「」。只输出提示词本身。""",
("en", "详细"): """Look at this image and write a ready-to-use English text-to-image prompt. Output only the prompt, no title, list, explanation or Markdown.
Cover in order: main subject; for each person their apparent gender/age, looks and hair, clothing and accessories, expression, pose and position in the frame; setting and background; composition and camera (shot size, angle); lighting and colour palette; art/photo style.
If the image contains text, quote it verbatim in double quotes with its font style, colour and position. One flowing paragraph, about 80–160 words.""",
("en", "简短"): """Write one short ready-to-use English text-to-image prompt (20–40 words) for this image: subject, key looks, setting, style; quote visible text verbatim only if the image really contains text. Output only the prompt.""",
}
@spaces.GPU(duration=int(os.getenv("REVERSE_GPU_SECONDS", "90")))
def infer_caption(image, choice, instruction):
model, processor, _, _, _ = CACHE[choice]
t0 = time.perf_counter()
messages = [{"role": "user", "content": [{"type": "image", "image": image}, {"type": "text", "text": instruction}]}]
inputs = processor.apply_chat_template(messages, tokenize=True, add_generation_prompt=True,
enable_thinking=False, return_dict=True, return_tensors="pt").to("cuda")
with torch.inference_mode():
generated = model.generate(**inputs, max_new_tokens=1024, do_sample=False, repetition_penalty=1.05)
text = processor.batch_decode(generated[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)[0]
return text, round(time.perf_counter() - t0, 3)
def clean_caption(text):
text = re.sub(r"<think>.*?</think>", "", text, flags=re.S | re.I)
text = re.sub(r"```\w*|```", "", text).strip()
text = re.sub(r"^(?:提示词|生图提示词|prompt)\s*[::]\s*", "", text, flags=re.I)
text = re.sub(r"^#+\s*", "", text, flags=re.M).replace("**", "")
return text.strip().strip('"“”').strip()
def caption(image, lang="zh", detail="详细", model=DEFAULT_CHOICE):
"""Plain text-to-image prompt (no JSON). lang: zh|en; detail: 详细|简短."""
if image is None:
raise gr.Error("请上传图片")
lang = lang if lang in ("zh", "en") else "zh"
detail = detail if detail in ("详细", "简短") else "详细"
started = time.perf_counter()
image = shrink(image)
with LOCK:
choice = model or DEFAULT_CHOICE
if choice not in CACHE:
raise gr.Error(f"该变体未加载:{LOAD_ERRORS.get(choice, '未知原因')}")
text, gpu_seconds = infer_caption(image, choice, CAPTION_PROMPTS[(lang, detail)])
_, _, model_id, mode, _ = CACHE[choice]
prompt = clean_caption(text)
if not prompt:
raise gr.Error("模型没有返回提示词,请重试")
return {"prompt": prompt, "lang": lang, "detail": detail, "model": model_id, "mode": mode,
"gpu_seconds": gpu_seconds, "seconds": round(time.perf_counter() - started, 3)}
ENHANCE_PROMPT = """你是 AI 生图提示词专家。把用户的想法扩写成一段可以直接用于生图模型的中文提示词。
规则:
1. 保留用户写到的每一个要素,不改变、不删减;用户给出的文字内容(引号或「」里的字)必须原样保留,并用「」括起来,说明字体风格、颜色、位置。
2. 补全用户没写的细节:主体外貌/服装/动作、场景与背景、构图与镜头、光线、色调、材质质感、画风;补的细节要和用户意图一致,不加用户没要求的文字。
3. 用户提到的风格(如 C4D、3D、厚涂、胶片)要展开成具体视觉特征(例如 3D 立体字:有厚度、倒角、高光、投影)。
4. 只输出提示词本身,一段话,150–300 字,不要标题、解释或 Markdown。
用户的想法:"""
@spaces.GPU(duration=int(os.getenv("REVERSE_GPU_SECONDS", "90")))
def infer_text(choice, instruction):
model, processor, _, _, _ = CACHE[choice]
t0 = time.perf_counter()
messages = [{"role": "user", "content": [{"type": "text", "text": instruction}]}]
inputs = processor.apply_chat_template(messages, tokenize=True, add_generation_prompt=True,
enable_thinking=False, return_dict=True, return_tensors="pt").to("cuda")
with torch.inference_mode():
generated = model.generate(**inputs, max_new_tokens=768, do_sample=False, repetition_penalty=1.05)
text = processor.batch_decode(generated[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)[0]
return text, round(time.perf_counter() - t0, 3)
def enhance(prompt, model=DEFAULT_CHOICE):
"""Expand a short user idea into a detailed MOSS-friendly Chinese prompt."""
prompt = (prompt or "").strip()
if not prompt:
raise gr.Error("请输入提示词")
if len(prompt) > 2000:
raise gr.Error("提示词太长")
started = time.perf_counter()
with LOCK:
choice = model or DEFAULT_CHOICE
if choice not in CACHE:
raise gr.Error(f"该变体未加载:{LOAD_ERRORS.get(choice, '未知原因')}")
text, gpu_seconds = infer_text(choice, ENHANCE_PROMPT + prompt)
out = clean_caption(text)
if not out:
raise gr.Error("模型没有返回提示词,请重试")
return {"prompt": out, "source": prompt, "gpu_seconds": gpu_seconds, "seconds": round(time.perf_counter() - started, 3)}
# ZeroGPU only intercepts .to('cuda') at module level, so every variant is loaded
# at startup (2 x bf16 ~37 GB). FP8 variants are attempted too; if on-the-fly
# quantisation needs a real GPU at load time they fall back and report it.
# The ZeroGPU slice has ~50 GB, so not all four fit: REVERSE_LOAD picks which
# variants are resident ("all-bf16", "all-fp8", or comma-separated choices).
LOAD_ERRORS = {}
_load = os.getenv("REVERSE_LOAD", "")
_wanted = ([c for c in CHOICES if c.endswith("| bf16")] if _load == "all-bf16" else
[c for c in CHOICES if c.endswith("| fp8")] if _load == "all-fp8" else
[c.strip() for c in _load.split(",") if c.strip()] or [DEFAULT_CHOICE])
for _choice in CHOICES:
if _choice not in _wanted:
LOAD_ERRORS[_choice] = "not loaded in this Space (REVERSE_LOAD)"
continue
try:
load_variant(_choice)
except Exception as exc: # keep the Space up with whatever loaded
LOAD_ERRORS[_choice] = f"{type(exc).__name__}: {str(exc)[:300]}"
print("load failed", _choice, LOAD_ERRORS[_choice], flush=True)
with gr.Blocks() as demo:
gr.Markdown("# 从图片反推 MOSS 排版\n私有使用;选择模型和精度后上传海报。切换模型会卸载上一个。")
image = gr.Image(type="pil", label="海报")
model = gr.Dropdown(CHOICES, value=DEFAULT_CHOICE, label="model")
button = gr.Button("反推排版")
output = gr.JSON(label="MOSS layout")
button.click(reverse, [image, model], output, api_name="reverse", concurrency_limit=1)
dev_button = gr.Button("反推排版(测试版提示词)", visible=False)
dev_button.click(reverse_dev, [image, model], output, api_name="reverse_dev", concurrency_limit=1)
with gr.Row():
lang = gr.Radio(["zh", "en"], value="zh", label="lang")
detail = gr.Radio(["详细", "简短"], value="详细", label="detail")
cap_button = gr.Button("反推提示词")
cap_output = gr.JSON(label="提示词")
cap_button.click(caption, [image, lang, detail, model], cap_output, api_name="caption", concurrency_limit=1)
idea = gr.Textbox(label="提示词增强:输入想法")
enh_button = gr.Button("增强提示词")
enh_output = gr.JSON(label="增强结果")
enh_button.click(enhance, [idea, model], enh_output, api_name="enhance", concurrency_limit=1)
demo.queue(default_concurrency_limit=1, max_size=8)
if __name__ == "__main__":
demo.launch(show_error=True)