""" VLM captioning: image [+ optional YOLO detections] -> safety observation. This is the LANGUAGE half of the pipeline. It supports MULTIPLE models behind a single interface, and two modes: 1. WITH detector (default): the VLM receives the image AND the deterministic PPE findings (one per person and item, each marked required or advisory). The detector remains AUTHORITATIVE for PPE: the VLM reports its findings in plain words and may FLAG one the image clearly contradicts ("verify_items"), but never overrides one and never decides whether an item is required. 2. IMAGE-ONLY (use_detector=False): the VLM receives the image alone and judges PPE from the image itself. Baseline that shows what the detector adds. Output, hazard first and in the client's own terms: "issue" what is happening that creates the danger ("Worker is working at height at an unguarded slab edge.") "main_hazard" what could happen because of it ("Fall from height") "missing_controls" the controls that are visibly not in place "safety_observation" a short paragraph that stands on its own: the issue and hazard, then the PPE findings, then anything else "severity", "ppe_summary", "verify_items", "detector_disagreement" Every statement must be confirmable from the photo, so "No significant hazard visible." and an empty "missing_controls" list are valid answers. Providers: - Claude models (Anthropic SDK) require ANTHROPIC_API_KEY - Qwen3-VL models (DashScope, OpenAI-compatible) require DASHSCOPE_API_KEY """ from __future__ import annotations import base64 import json import mimetypes import os from pathlib import Path # --------------------------------------------------------------------------- # Model registry # --------------------------------------------------------------------------- MODEL_REGISTRY: dict[str, dict[str, str]] = { # --- Anthropic (Claude) --- "sonnet": {"provider": "anthropic", "id": "claude-sonnet-4-6"}, "opus": {"provider": "anthropic", "id": "claude-opus-4-8"}, "haiku": {"provider": "anthropic", "id": "claude-haiku-4-5"}, # --- Qwen via DashScope (OpenAI-compatible) --- "qwen-8b": {"provider": "dashscope", "id": "qwen3-vl-8b-instruct"}, "qwen-30b": {"provider": "dashscope", "id": "qwen3-vl-30b-a3b-instruct"}, "qwen-32b": {"provider": "dashscope", "id": "qwen3-vl-32b-instruct"}, } DEFAULT_MODEL = "sonnet" DASHSCOPE_BASE_URL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1" NO_HAZARD = "No significant hazard visible." # --------------------------------------------------------------------------- # Prompts # --------------------------------------------------------------------------- # Shared by both modes: how to look at the scene and name the issue. _HAZARD_FIRST = """How to assess the scene: The reader is a client or site manager who wants to know, in one glance, what the problem is. A reader looking at a worker on an unguarded slab edge described the answer they want like this: "The issue is that he is working at height and the risk is of falling. So a potential fall is the main hazard." Your output follows that shape: the ISSUE (what is happening), the MAIN HAZARD (what could happen because of it), then the controls that are missing. This record may also be read later in an audit or an incident review, so every statement in it must be something a second person could confirm by looking at the same photo. That matters more than sounding thorough: an empty field is better than a guess. Step 1 - look before you judge. Note what is actually visible: each person, what that person is doing at this moment, and the surroundings that matter for safety. Describe the action you can see, not what nearby equipment suggests (a worker measuring timber next to an idle saw is measuring, not sawing). Assess the people who are clearly visible; leave out distant background figures too small to assess, unless one of them is exposed to a hazard. Step 2 - name the issue. Think like an experienced site safety supervisor and ask: who in this photo is exposed, right now, to something that could seriously hurt them? - An issue needs both a source of danger and a person exposed to it. A crane, plant, a stockpile, an excavation or tools that are simply present in the scene, with nobody exposed to them, are background and not the issue. - The issue usually comes from the ACTIVITY or the ENVIRONMENT (working at height, an unguarded edge, moving plant or vehicles, an open excavation, machinery or power tools in use, a suspended load, live electrical work, hot work, manual handling), not from a PPE item. Missing PPE is the issue only when nothing more serious is visible. - Name ONE issue. A second one, if there is one, goes in "safety_observation". - Many photos show nothing serious: people walking, talking, or working with everything in order. Then the issue is exactly "No significant hazard visible." That is a correct and useful answer, so do not stretch a minor point to fill the field. Step 3 - name the main hazard. Say in a few words what could happen to the person because of the issue: "Fall from height", "Struck by reversing plant", "Hand injury from the blade". Step 4 - name the missing controls for that issue. - Use only controls that are standard for it: edge protection, a harness connected to an anchor, machine guarding, barriers, an exclusion zone, or the PPE that directly protects against that hazard. - List a control only when the place it would be is visible in the photo and it is not there. Before you list it, check the photo again: if a barrier, guard or rail is in the picture, it is not missing. - You can only judge what the photo shows, so write "no ... visible" or "not connected", never that something does not exist on the site. - If you cannot name a standard control that is visibly absent, return an empty list. Do not make one up. Wording: - Short, direct, plain words, the way a supervisor would say it out loud. Examples of the STYLE wanted (do not reuse them unless they are true of this photo): issue: "Worker is working at height at an unguarded slab edge." main_hazard: "Fall from height" missing_controls: ["No edge protection", "No harness visible"] and issue: "Worker is cutting with a grinder." main_hazard: "Eye or hand injury from the disc" missing_controls: ["No guard on the disc", "No eye protection"] - Describe things as they appear. Do not add a condition the photo cannot show (such as "unstable", "active", "live", "loose" or "heavy"), and do not mention details too small or too blurred to make out. - Being careful means not inventing things. It does not mean hedging what you can plainly see.""" def _schema(with_detector: bool) -> str: """The JSON contract. The PPE parts differ between the two modes.""" if with_detector: ppe_words = """the PPE findings in plain words: name every REQUIRED item that is not worn or could not be confirmed and say whose it is, mention advisory items that are not worn in a few words, and sum up what is worn briefly""" ppe = """ "verify_items": a list with one entry for each detector finding that the image clearly contradicts, each entry an object {"person_id": , "item": "", "seen": ""}. Use [] if nothing is clearly contradicted,""" required = """a REQUIRED PPE item is marked "missing" by the detector (and you have not listed it in "verify_items") for a person who is exposed to the issue""" low_ppe = """a required PPE item marked "missing" for someone not exposed to any hazard, an advisory item marked "missing",""" else: ppe_words = """the PPE findings that matter: name the items that are not worn or could not be seen, and sum up the items that are worn in a few words""" ppe = """ "ppe_summary": object mapping "head", "eyes", "hands", "torso", "feet" (and "fall_arrest" when someone is working at height) to "present"/"missing"/"uncertain". It must agree with "safety_observation",""" required = """a REQUIRED PPE item (helmet or high-visibility vest) is clearly not worn by a person who is exposed to the issue""" low_ppe = """a required PPE item not worn by someone not exposed to any hazard, an advisory item (gloves, eye protection) not worn,""" return f"""Return ONLY a JSON object with these keys, in this order, nothing else: "observations": a list of 3 to 6 short factual phrases from Step 1: who is visible, what each person is doing, and the surroundings that matter. Facts only, no judgement. Everything in the fields below must be supported by something in this list, "issue": ONE short plain sentence, 15 words or fewer, saying what is happening that puts a person in danger, and nothing else (e.g. "Worker is working at height at an unguarded slab edge."). If there is none, write exactly "{NO_HAZARD}" with nothing added. Do not list the missing controls here; they have their own field, "main_hazard": a few words naming what could happen because of the issue (e.g. "Fall from height"), or "" if there is no significant hazard, "missing_controls": a list of at most 3 short phrases from Step 4 (e.g. ["No edge protection", "Harness worn but not connected"]), or [] if there are none or if there is no significant hazard. Controls only: other hazards do not belong in this list, "safety_observation": 2-4 sentences that read as a complete note on their own. Open with the issue and the main hazard in one plain sentence, the way a supervisor would say it out loud ("He is working at height with no edge protection, so the risk is a fall."). Then {ppe_words}. Then a second hazard if there is one, and any readable safety sign that relates to the issue (quote its wording). If there is no significant hazard, say so in a few words and go straight to the PPE findings, {ppe} "severity": one of "none", "low", "medium", "high", chosen by these definitions: "high": a person is exposed right now to something that could kill or permanently injure (fall from height, being struck by plant or a load, collapse of an excavation, contact with a running blade or live conductor) AND a key control for it is visibly missing; "medium": a person is exposed right now to something that could cause an injury needing time off work, with a control visibly missing, OR {required}; "low": only minor issues that are actually visible: housekeeping, a trip hazard, {low_ppe} or a hazard nearby with nobody exposed to it; "none": nothing of concern is visible. PPE that simply could not be seen (out of frame or hidden) does not raise the severity on its own. A worker who is properly equipped and not exposed to an uncontrolled hazard is "low" or "none", whatever tools or plant are nearby. Be concise, factual, and neutral. This is a safety record, not marketing copy.""" # Mode 1: detector is the PPE record. The VLM reports it in plain words and may # flag (never override) a finding the image contradicts. SYSTEM_WITH_DETECTOR = """You are a workplace-safety observation assistant for the AiGiS platform. You are given (1) an image of a work environment and (2) the PPE findings of a deterministic object-detection model, one row per person and PPE item. """ + _HAZARD_FIRST + """ Rules for the detector findings: - Each finding has a status ("present", "missing" or "uncertain") and a level ("required" or "advisory"). "person_id" numbers the people from left to right; a null person_id means the item could not be tied to one person. - The detector is the authoritative record for the PPE it covers. Report its findings in "safety_observation"; do not re-judge them from the image. You do not decide whether an item is required ("level" says that), and you do not drop or play down a finding because you think it does not matter in this scene. - Write the findings in plain words for a reader who has never heard of the detector: "present" is "worn", "missing" is "not worn", "uncertain" is "could not be confirmed". Refer to people by position or appearance ("the worker on the left"), not by number. Never mention "the detector", confidence scores or overlap values in "issue", "main_hazard", "missing_controls" or "safety_observation". - The detector covers only the PPE items in its findings. It knows nothing about the activity, the surroundings, or harnesses and other fall-arrest equipment, so the issue, the main hazard and the missing controls come from what you see in the IMAGE. - "missing_controls" may include a PPE item only when it is the direct control for the issue (a harness for work at height, eye protection for grinding). Do not list an item there that the detector marks "present". - FLAG, DON'T OVERRIDE: the detector can miss an object or mistake one for another. A finding is clearly contradicted when it says "missing" and the item, or an equivalent such as a high-visibility jacket for a vest or a face shield for eye protection, is plainly worn; or when it says "present" and that part of the body is plainly bare. When that happens: * add an entry to "verify_items"; * in "safety_observation", say what the image shows and that it should be verified ("a high-visibility jacket appears to be worn and should be verified"), instead of reporting the item as not worn. Do this only when it is clear. An "uncertain" status that you cannot settle from the image is not a contradiction, so report it as could not be confirmed. - Do not invent objects or people. """ + _schema(True) # Mode 2: image only, no detector. The VLM also reports PPE. # NOTE: "required" here (helmet, high-visibility vest) mirrors the levels in # sh17.yaml. If the required list changes there, change it here too. SYSTEM_IMAGE_ONLY = """You are a workplace-safety observation assistant for the AiGiS platform. You are given an image of a work environment. There is no object-detection input; assess the scene from the image alone. """ + _HAZARD_FIRST + """ Rules for PPE in this mode: - Check the same items every time, so two photos can be compared. Use these keys in "ppe_summary": "head" (helmet), "eyes" (glasses or face shield), "hands" (gloves), "torso" (high-visibility vest or jacket), "feet" (safety footwear), and add "fall_arrest" (harness) only when someone is working at height. If several people are visible, record the worst case for each key and say in "safety_observation" which person it applies to. - Helmet and high-visibility vest are REQUIRED on site. Gloves, eye protection and footwear are advisory. - Give each item one status and use it everywhere in your answer. In words, use one of three plain phrases, matching the three statuses: "worn" (present) - the item is clearly on the person; "not worn" (missing) - that part of the body is clearly in view and the item is not on it, e.g. bare hands; "could not be seen" (uncertain) - that part of the body is out of frame, hidden, or too small to judge. Do not write that PPE is "not visible": it does not tell the reader which of the last two you mean. Bare hands in plain view are an observation, not a guess, so say "gloves not worn" directly. - Do not invent objects or people not clearly visible in the image. """ + _schema(False) # Backwards-compatible alias. SYSTEM_PROMPT = SYSTEM_WITH_DETECTOR # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _encode_image(image_path: str) -> tuple[str, str]: media_type = mimetypes.guess_type(image_path)[0] or "image/jpeg" data = base64.standard_b64encode(Path(image_path).read_bytes()).decode() return media_type, data def _strip_fences(text: str) -> str: return text.replace("```json", "").replace("```", "").strip() def _resolve(model: str) -> tuple[str, str, str]: if model in MODEL_REGISTRY: entry = MODEL_REGISTRY[model] return model, entry["provider"], entry["id"] provider = "anthropic" if model.startswith("claude") else "dashscope" return model, provider, model def _detector_brief(detection_result: dict) -> dict: """ What the VLM needs from the detector: the PPE findings only. Boxes, raw confidences and the detail strings are left out on purpose, because they are what used to leak into the text as "the detector reports ... (0.26)". """ findings = [] for c in detection_result.get("compliance", []): findings.append({ "person_id": c.get("person_id"), "item": c.get("item") or c.get("expected_ppe"), "level": c.get("level", "required"), "status": c.get("status"), }) return {"people": detection_result.get("people"), "ppe_findings": findings} def _build_user_text(detection_result: dict | None) -> str: if detection_result is None: return ( "Write the safety record for this image as specified. " "List what is visible first, then the issue." ) return ( "Detector PPE findings (authoritative for PPE; report them in plain words " "and flag any finding the image clearly contradicts):\n" + json.dumps(_detector_brief(detection_result), indent=2) + "\n\nWrite the safety record for this image as specified. " "List what is visible first, then the issue, which comes from the image." ) def _parse(text: str) -> dict: cleaned = _strip_fences(text) try: return json.loads(cleaned) except json.JSONDecodeError: return {"raw": text, "parse_error": True} _STATUS_RANK = {"present": 0, "uncertain": 1, "missing": 2} def _norm_item(value) -> str: return str(value).strip().lower().replace("-", "_").replace(" ", "_") def _finalise(result: dict, with_detector: bool, detection_result: dict | None = None) -> dict: """ Make the result predictable for the app and the endpoint. Everything here is plain code, so these fields do not depend on the model's wording: - "verify_items" is always a list of {"person_id", "item", "seen"} dicts (empty in image-only mode, where there is no detector to contradict); - "detector_disagreement" (the text line shown in the app) is built from it; - with a detector, "ppe_summary" is built from the DETECTOR's findings: the worst status per item across all people, with any item the model flagged for verification marked "uncertain". """ if not isinstance(result, dict) or result.get("parse_error"): return result raw = result.get("verify_items") if with_detector else [] if isinstance(raw, (str, dict)): raw = [raw] items: list[dict] = [] for it in raw or []: if isinstance(it, dict): item = str(it.get("item", "")).strip() if item: items.append({ "person_id": it.get("person_id"), "item": item, "seen": str(it.get("seen", "")).strip(), }) elif str(it).strip(): items.append({"person_id": None, "item": str(it).strip(), "seen": ""}) result["verify_items"] = items findings = (detection_result or {}).get("compliance", []) if with_detector else [] def detector_status(person_id, item) -> str: for c in findings: name = c.get("item") or c.get("expected_ppe") if _norm_item(name) == _norm_item(item) and ( person_id is None or c.get("person_id") == person_id ): return str(c.get("status", "")) return "" parts = [] for it in items: name = _norm_item(it["item"]).replace("_", " ") who = f" (person {it['person_id']})" if it["person_id"] is not None else "" said = detector_status(it["person_id"], it["item"]) text = f"{name}{who}" if said: text += f": detector says {said}" if it["seen"]: text += f"{', image shows' if said else ': image shows'} {it['seen']}" parts.append(text) result["detector_disagreement"] = "; ".join(parts) if with_detector: flagged = {(it["person_id"], _norm_item(it["item"])) for it in items} summary: dict[str, str] = {} for c in findings: name = _norm_item(c.get("item") or c.get("expected_ppe")) status = str(c.get("status", "")) if (c.get("person_id"), name) in flagged or (None, name) in flagged: status = "uncertain" if _STATUS_RANK.get(status, -1) > _STATUS_RANK.get(summary.get(name), -1): summary[name] = status result["ppe_summary"] = summary return result # --------------------------------------------------------------------------- # Provider back-ends # --------------------------------------------------------------------------- def _caption_anthropic(model_id, system, media_type, b64, user_text) -> dict: import anthropic client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"]) msg = client.messages.create( model=model_id, max_tokens=1024, system=system, messages=[ { "role": "user", "content": [ { "type": "image", "source": { "type": "base64", "media_type": media_type, "data": b64, }, }, {"type": "text", "text": user_text}, ], } ], ) text = "".join(b.text for b in msg.content if b.type == "text") return _parse(text) def _caption_dashscope(model_id, system, media_type, b64, user_text) -> dict: from openai import OpenAI client = OpenAI( api_key=os.environ["DASHSCOPE_API_KEY"], base_url=DASHSCOPE_BASE_URL, ) resp = client.chat.completions.create( model=model_id, max_tokens=1024, messages=[ {"role": "system", "content": system}, { "role": "user", "content": [ { "type": "image_url", "image_url": {"url": f"data:{media_type};base64,{b64}"}, }, {"type": "text", "text": user_text}, ], }, ], ) text = resp.choices[0].message.content or "" return _parse(text) _BACKENDS = { "anthropic": _caption_anthropic, "dashscope": _caption_dashscope, } # --------------------------------------------------------------------------- # Public entry points # --------------------------------------------------------------------------- def caption(image_path, detection_result=None, model=DEFAULT_MODEL, use_detector=True) -> dict: media_type, b64 = _encode_image(image_path) return _caption_from_b64(media_type, b64, detection_result, model, use_detector) def caption_bytes(image_bytes, media_type, detection_result=None, model=DEFAULT_MODEL, use_detector=True) -> dict: b64 = base64.standard_b64encode(image_bytes).decode() return _caption_from_b64(media_type, b64, detection_result, model, use_detector) def _caption_from_b64(media_type, b64, detection_result, model, use_detector) -> dict: key, provider, model_id = _resolve(model) with_detector = use_detector and detection_result is not None system = SYSTEM_WITH_DETECTOR if with_detector else SYSTEM_IMAGE_ONLY user_text = _build_user_text(detection_result if with_detector else None) backend = _BACKENDS.get(provider) if backend is None: raise ValueError(f"Unknown provider '{provider}' for model '{model}'") result = backend(model_id, system, media_type, b64, user_text) result = _finalise(result, with_detector, detection_result) result["_model"] = key result["_use_detector"] = with_detector return result