MIPR / construction /intent_analysis.py
leequeue's picture
Upload folder using huggingface_hub
49654fc verified
Raw History Blame Contribute Delete
6.43 kB
#!/usr/bin/env python3
"""图片与原始 query → scene(content、intent、note);使用原始 Claude CLI prompt。"""
import argparse
import json
import os
import subprocess
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
STAGE1_PROMPT = """请观察图片并结合用户的问题,以 JSON 格式回答以下三点:
1. "content":图中是什么东西或什么场景?如果物品的具体类型会影响解决方案,请说清楚(例如螺丝是内六角还是十字的,因为这决定需要什么工具)。若某个关键特征看不清或不确定,明确写出"疑似"或"无法确定",不要臆断。
2. "intent":结合图片和提问,用户想解决什么问题?尽量往搜索商品上靠(如"寻找清洗白色运动鞋的用品");但如果靠不上(比如用户只是想了解、评价、比较、询问某属性),就别硬靠,直接输出原始意图,如"想了解这款衣服的评价如何"。
3. "note":根据识别出的物品/场景和用户意图,指出一句解决该问题时的注意事项,重点是会影响"该选什么商品"的地方。如果没有特别需要注意的,就留空 ""。
示例:
- 菜刀图 + "生锈了怎么处理" →
{"content": "菜刀,刀面有锈斑", "intent": "寻找给菜刀除锈的工具或用品", "note": "菜刀直接接触食物,除锈处理需满足食品安全要求,不能用工业除锈剂"}
- 内六角螺丝图 + "怎么拧下来" →
{"content": "内六角螺丝", "intent": "寻找拧下内六角螺丝的工具", "note": "内六角螺丝需要特定规格的工具,规格不匹配无法使用"}
- 免打孔挂杆图 + "厨房墙上挂东西用啥" →
{"content": "厨房墙面收纳挂杆", "intent": "寻找厨房墙面免打孔收纳挂杆", "note": "需免打孔安装;厨房环境需考虑承重和防油污"}
- 针织衫图 + "这种容易起球吗" →
{"content": "针织上衣", "intent": "想了解这款衣服是否容易起球", "note": ""}
请直接输出 JSON 对象,不要输出任何其他内容。"""
SYSTEM_PROMPT = "你是一个多模态场景分析助手。用户会提供一张图片的文件路径和一个搜索查询。请先用 Read 工具读取图片,然后根据图片内容和查询回答。只输出 JSON 对象,不要输出任何解释或其他内容。"
def load_input_jsonl(path):
with open(path, encoding="utf-8") as f:
rows = [json.loads(line) for line in f if line.strip()]
return [dict(row, idx=str(row["idx"])) for row in rows]
def load_done_jsonl(path):
done = set()
if os.path.exists(path):
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
done.add(str(json.loads(line)["idx"]))
except (json.JSONDecodeError, KeyError):
continue
return done
_write_lock = threading.Lock()
def append_jsonl(path, obj):
with _write_lock:
with open(path, "a", encoding="utf-8") as f:
f.write(json.dumps(obj, ensure_ascii=False) + "\n")
f.flush()
def extract_json_obj(text):
import re
try:
match = re.search(r"\{.*\}", text, re.DOTALL)
if match:
parsed = json.loads(match.group())
if isinstance(parsed, dict):
return parsed
except (json.JSONDecodeError, ValueError):
pass
return {"content": "未知", "intent": "未知", "note": "未知", "_raw": text}
def call_claude(image_path, query, model, timeout_seconds):
user_prompt = f"请先用 Read 工具读取这张图片: {image_path}\n\n用户搜索查询:{query}\n\n{STAGE1_PROMPT}"
result = subprocess.run(
[
"claude", "-p", user_prompt,
"--system-prompt", SYSTEM_PROMPT,
"--model", model,
"--output-format", "text",
"--allowedTools", "Read",
"--no-session-persistence",
"--bare",
],
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
timeout=timeout_seconds,
)
if result.returncode != 0:
stderr = (result.stderr or "").strip()
raise RuntimeError(f"claude -p exit {result.returncode}: {stderr}")
return result.stdout.strip()
def call_claude_with_retry(image_path, query, model, max_retries, timeout_seconds):
for attempt in range(1, max_retries + 1):
try:
raw = call_claude(image_path, query, model, timeout_seconds)
return raw, None
except Exception as exc:
if attempt == max_retries:
return None, str(exc)
time.sleep(min(2 ** attempt, 10))
return None, "max retries exceeded"
def run_stage1(args):
rows = load_input_jsonl(args.input)
done = load_done_jsonl(args.output)
os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True)
def process_one(row):
image_path = os.path.abspath(os.path.join(args.image_dir, row["image_url"]))
if not os.path.isfile(image_path):
raise FileNotFoundError(image_path)
raw, error = call_claude_with_retry(
image_path, row["query"], args.model, args.max_retries, args.timeout)
if error:
raise RuntimeError(f"idx={row['idx']}: {error}")
append_jsonl(args.output, {
**row, "scene": extract_json_obj(raw), "raw_response_s1": raw,
})
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
futures = [pool.submit(process_one, row) for row in rows if row["idx"] not in done]
for future in as_completed(futures):
future.result()
print(f"意图分析完成:{args.output}")
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--input", required=True, help="JSONL: idx, query, image_url(本地图片文件名)")
p.add_argument("--output", required=True)
p.add_argument("--image-dir", required=True)
p.add_argument("--model", default="claude-sonnet-4-6")
p.add_argument("--concurrency", type=int, default=8)
p.add_argument("--max-retries", type=int, default=3)
p.add_argument("--timeout", type=int, default=120)
run_stage1(p.parse_args())
if __name__ == "__main__":
main()