Spaces:
Sleeping
Sleeping
Update vlm_caption.py
Browse files12345678910111213141516171819202122232424 unmodified lines49505152535455565758596061626 unmodified lines697071727374757677787980818283848586878889909192939495969798991001011 unmodified line1031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132148 unmodified lines22322422522622722822923023123223323423520 unmodified lines2562572582592602612622632642652662672682692702712722732745 unmodified lines28028128228328428586 unmodified lines372373374375376377"""VLM captioning: image [+ optional YOLO detections] -> safety-aware observation.This is the LANGUAGE half of the pipeline. It supports MULTIPLE models behind asingle interface, and two modes:1. WITH detector (default): the VLM receives the image AND the deterministicdetections + compliance findings. The detector remains AUTHORITATIVE for thecompliance verdict, but the VLM is allowed to FLAG when the image visiblydisagrees with a finding (see Case-2 handling below).2. IMAGE-ONLY (use_detector=False): the VLM receives the image alone and judgesPPE from the image itself. Baseline that shows what the detector adds.In both modes the output is HAZARD-FIRST and GROUNDED:- the model first lists what is visible ("observations"), then names the singlemost serious hazard someone is exposed to, the risk, and the controls thatare visibly missing, before it reports PPE findings;- every statement must be confirmable from the photo, so "No significant hazardvisible." and an empty "missing_controls" list are valid answers;- "severity" follows fixed definitions (see _SYSTEM_COMMON).Providers:- Claude models (Anthropic SDK) require ANTHROPIC_API_KEY24 unmodified linesDEFAULT_MODEL = "sonnet"DASHSCOPE_BASE_URL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"# ---------------------------------------------------------------------------# Prompts# ---------------------------------------------------------------------------# Shared by both modes: how to look at the scene and pick the main hazard._HAZARD_FIRST = """How to assess the scene:This record may be read later in an audit or an incident review, so everystatement in it must be something a second person could confirm by looking atthe same photo. That matters more than sounding thorough: an empty field isbetter than a guess.6 unmodified linesleave out distant background figures too small to assess, unless one of them isexposed to a hazard.Step 2 - pick the main hazard.Think like an experienced site safety supervisor and ask: who in this photo isexposed, right now, to something that could seriously hurt them?- A hazard needs both a source and a person exposed to it. A crane, plant, astockpile, an excavation or tools that are simply present in the scene, withnobody exposed to them, are background and not the main hazard.- The main hazard usually comes from the ACTIVITY or the ENVIRONMENT (working atheight, an unguarded edge, moving plant or vehicles, an open excavation,machinery or power tools in use, a suspended load, live electrical work, hotwork, manual handling), not from a PPE item. Missing PPE is the main hazardonly when nothing more serious is visible.- Name ONE hazard. A second hazard, if there is one, goes in"safety_observation".- Many photos show nothing serious: people walking, talking, or working witheverything in order. Then the main hazard is exactly "No significant hazardvisible." That is a correct and useful answer, so do not stretch a minorissue to fill the field.Step 3 - name the missing controls for that hazard.- Use only controls that are standard for that hazard: edge protection, aharness 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 itis not there. Before you list it, check the photo again: if a barrier, guardor rail is in the picture, it is not missing.- You can only judge what the photo shows, so write "not visible" or "nonevisible", never that something does not exist.- If you cannot name a standard control that is visibly absent, return an emptylist. Do not make one up.1 unmodified line- 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 thisphoto):"Worker is working at height. No edge protection and no harness visible.""The issue here is that he is working at height and the risk is of falling.""Worker is cutting with a grinder. No guard on the disc and 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 mentiondetails too small or too blurred to make out.- Do not open with a list of PPE items. PPE findings come after the main hazard.- Give each PPE item one status and use it everywhere in your answer. Never callthe same item missing in one field and unconfirmed in another.- When you report PPE in words, use one of three plain phrases, matching thethree statuses:"worn" (present) - the item is clearly on the person;"not worn" (missing) - that part of the body is clearly in viewand the item is not on it, e.g. bare handsor bare eyes;"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 ofthe last two you mean. Bare hands in plain view are an observation, not aguess, so say "gloves not worn" directly. Being careful means not inventingthings; it does not mean hedging what you can plainly see."""_SYSTEM_COMMON = """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 isvisible, what each person is doing, and the surroundings that matter. Factsonly, no judgement. Everything in the fields below must be supported bysomething in this list,"main_hazard": ONE short plain sentence, 15 words or fewer, naming the singlemost serious hazard a person is exposed to and nothing else (e.g. "Workeris working at height at an unguarded slab edge."). If there is none, writeexactly "No significant hazard visible." with nothing added. Do not listthe missing controls here; they have their own field,"risk": a few words naming what could happen because of that hazard (e.g."Fall from height"), or "" if there is no significant hazard,"missing_controls": a list of at most 3 short phrases from Step 3 (e.g. ["Noedge protection", "Harness worn but not connected"]), or [] if there arenone or if there is no significant hazard. Controls only: other hazards donot belong in this list,"safety_observation": 1-3 sentences covering ONLY what the fields above do notalready say: the PPE findings that matter (name the items that are missingor uncertain, and sum up the items that are present in a few words), asecond hazard if there is one, and any readable safety sign that relatesto the hazard (quote its wording). Do NOT restate the main hazard, the risk or the missingcontrols, and do NOT add a reminder that findings need on-siteverification (the app adds that line itself),"ppe_summary": object mapping each assessed body part to "present"/"missing"/"uncertain".It must agree with what "safety_observation" says,"severity": one of "none", "low", "medium", "high", chosen by these definitions:"high": a person is exposed right now to a hazard that could kill orpermanently injure (fall from height, being struck by plant or aload, collapse of an excavation, contact with a running blade orlive conductor) AND a key control for it is visibly missing;"medium": a person is exposed right now to a hazard that could cause aninjury needing time off work, with a control visibly missing, ORPPE that the task in progress clearly requires is clearly missing;"low": only minor issues that are actually visible: housekeeping, atrip hazard, a PPE item not worn that the task does not strictlyneed, 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 hazardis "low" or "none", whatever tools or plant are nearby,"detector_disagreement": a short string, used ONLY when the image clearlycontradicts a specific detector finding (e.g. the detector says the helmetis missing but one is plainly worn). A low-confidence detection is not adisagreement, and neither is anything the detector does not detect at all(such as a harness): put those in "safety_observation" or"missing_controls". Use "" (empty) if there is no contradiction.Say each thing once. Be concise, factual, and neutral. This is a safety record,not marketing copy."""# Mode 1: detector authoritative, BUT the VLM may flag visible disagreement.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) structured detectionsfrom a deterministic object-detection model, including PPE-compliance findings.""" + _HAZARD_FIRST + """Rules for the detector input:- The detector only covers PPE items and people. It knows nothing about theactivity or the surroundings, so the main hazard, the risk and the missingcontrols come from what you see in the IMAGE.- The DETECTOR's compliance findings are the authoritative record for PPE. Baseyour "ppe_summary" on them, not on your own re-reading of the image, andreport every item the detector marks "missing" in "safety_observation".- IMPORTANT EXCEPTION (flag, don't override): the detector can MISS objects. If afinding says a PPE item is "missing" but you can CLEARLY see that item isactually present in the image (e.g. a worker is plainly wearing a helmet thedetector did not register), do NOT silently trust the finding and do NOTsilently overrule it. Instead:* in "safety_observation", note that the detector did not register the itembut it appears present in the image and should be verified;* record it in "detector_disagreement";* in "ppe_summary", mark that body part "uncertain" (not "missing").This keeps the deterministic layer in charge while preventing a misseddetection from becoming a false "worker unprotected" claim.- If a finding is "missing" and the image does NOT clearly show the item, keep itas missing and state it as a potential safety issue.- If a finding is "uncertain", say it could not be confirmed and should be verified.- Do not invent objects or people.""" + _SYSTEM_COMMON# Mode 2: image only, no detector.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;8 unmodified linesfootwear), and add "fall_arrest" (harness) only when someone is working atheight. If several people are visible, record the worst case for each key andsay in "safety_observation" which person it applies to.- Status for each item: "present" when it is clearly worn; "missing" when thatpart of the body is clearly visible and the item is clearly not on it;"uncertain" when you cannot tell (hidden, out of frame, or too small to see).- Do not invent objects or people not clearly visible in the image.- Leave "detector_disagreement" as "" (there is no detector in this mode).""" + _SYSTEM_COMMON# Backwards-compatible alias.SYSTEM_PROMPT = SYSTEM_WITH_DETECTOR20 unmodified linesreturn model, provider, modeldef _build_user_text(detection_result: dict | None) -> str:if detection_result is None:return ("Write the safety observation for this image as specified. ""List what is visible first, then the main hazard.")return ("Structured detector output (authoritative for PPE claims, but flag any ""finding the image clearly contradicts):\n"+ json.dumps(detection_result, indent=2)+ "\n\nWrite the safety observation for this image as specified. ""List what is visible first, then the main hazard, which comes from the ""image, not the detector.")5 unmodified linesreturn {"raw": text, "parse_error": True}# ---------------------------------------------------------------------------# Provider back-ends# ---------------------------------------------------------------------------86 unmodified linesraise ValueError(f"Unknown provider '{provider}' for model '{model}'")result = backend(model_id, system, media_type, b64, user_text)result["_model"] = keyresult["_use_detector"] = with_detectorreturn result1234567891011121314151617181920212223242526272824 unmodified lines53545556575859606162636465666768697071727374756 unmodified lines8283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171 unmodified line1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482498 unmodified lines25825926026126226326426526626726826927027127227327427527627727820 unmodified lines2993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323335 unmodified lines33934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038186 unmodified lines468469470471472473474"""VLM captioning: image [+ optional YOLO detections] -> hazard statement.This is the LANGUAGE half of the pipeline. It supports MULTIPLE models behind asingle interface, and two modes:1. WITH detector (default): the VLM writes the hazard statement from the image.PPE compliance is NOT narrated by the VLM: it comes from the deterministicdetector and the app renders it as a table. The VLM only receives thedetector's findings so that it can FLAG a finding the image clearlycontradicts ("verify_items"). It never overrides one and never decideswhether an item is required.2. IMAGE-ONLY (use_detector=False): the VLM receives the image alone and alsoreports PPE from the image itself. Baseline that shows what the detector adds.Output, 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(["No edge protection", "Harness worn but not connected"])Every statement must be confirmable from the photo, so "No significant hazardvisible." and an empty "missing_controls" list are valid answers.Providers:- Claude models (Anthropic SDK) require ANTHROPIC_API_KEY24 unmodified linesDEFAULT_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 theproblem is. A reader looking at a worker on an unguarded slab edge described theanswer they want like this: "The issue is that he is working at height and therisk is of falling. So a potential fall is the main hazard." Your output followsthat shape: the ISSUE (what is happening), the MAIN HAZARD (what could happenbecause of it), then the controls that are missing.This record may also be read later in an audit or an incident review, so everystatement in it must be something a second person could confirm by looking atthe same photo. That matters more than sounding thorough: an empty field isbetter than a guess.6 unmodified linesleave out distant background figures too small to assess, unless one of them isexposed to a hazard.Step 2 - name the issue.Think like an experienced site safety supervisor and ask: who in this photo isexposed, 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 thescene, with nobody exposed to them, are background and not the issue.- The issue usually comes from the ACTIVITY or the ENVIRONMENT (working atheight, an unguarded edge, moving plant or vehicles, an open excavation,machinery or power tools in use, a suspended load, live electrical work, hotwork, manual handling), not from a PPE item. Missing PPE is the issue onlywhen 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 witheverything in order. Then the issue is exactly "No significant hazardvisible." That is a correct and useful answer, so do not stretch a minorpoint 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: "Fallfrom 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 harnessconnected to an anchor, machine guarding, barriers, an exclusion zone, or thePPE that directly protects against that hazard.- List a control only when the place it would be is visible in the photo and itis not there. Before you list it, check the photo again: if a barrier, guardor rail is in the picture, it is not missing.- You can only judge what the photo shows, so write "no ... visible" or "notconnected", never that something does not exist on the site.- If you cannot name a standard control that is visibly absent, return an emptylist. Do not make one up.1 unmodified line- 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 thisphoto):issue: "Worker is working at height at an unguarded slab edge."main_hazard: "Fall from height"missing_controls: ["No edge protection", "No harness visible"]andissue: "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 mentiondetails too small or too blurred to make out.- Being careful means not inventing things. It does not mean hedging what youcan plainly see."""def _schema(with_detector: bool) -> str:"""The JSON contract. Two fields differ between the modes."""if with_detector:observation = """ "safety_observation": 0-2 sentences covering ONLY what the fields above do notalready say: a second hazard if there is one, and any readable safety signthat relates to the issue (quote its wording). No PPE inventory, since thePPE record is shown separately. Use "" if there is nothing to add,"""ppe = """ "verify_items": a list with one entry for each detector finding that the imageclearly contradicts, each entry an object{"person_id": <number or null>, "item": "<item name exactly as the detectorgives it>", "seen": "<a few words on what the image shows>"}.Use [] if nothing is clearly contradicted,"""required = """a REQUIRED PPE item is marked "missing" by the detector (andyou have not listed it in "verify_items") for a person who isexposed to the issue"""low_ppe = """a required PPE item marked "missing" for someone not exposedto any hazard, an advisory item marked "missing","""else:observation = """ "safety_observation": 1-3 sentences covering ONLY what the fields above do notalready say: the PPE findings that matter (name the items that are notworn or could not be seen, and sum up the items that are worn in a fewwords), a second hazard if there is one, and any readable safety signthat relates to the issue (quote its wording),"""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) isclearly not worn by a person who is exposed to the issue"""low_ppe = """a required PPE item not worn by someone not exposed to anyhazard, 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 isvisible, what each person is doing, and the surroundings that matter. Factsonly, no judgement. Everything in the fields below must be supported bysomething in this list,"issue": ONE short plain sentence, 15 words or fewer, saying what is happeningthat puts a person in danger, and nothing else (e.g. "Worker is working atheight at an unguarded slab edge."). If there is none, write exactly"{NO_HAZARD}" with nothing added. Do not list the missingcontrols 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. ["Noedge protection", "Harness worn but not connected"]), or [] if there arenone or if there is no significant hazard. Controls only: other hazards donot belong in this list,{observation}{ppe}"severity": one of "none", "low", "medium", "high", chosen by these definitions:"high": a person is exposed right now to something that could kill orpermanently injure (fall from height, being struck by plant or aload, collapse of an excavation, contact with a running blade orlive conductor) AND a key control for it is visibly missing;"medium": a person is exposed right now to something that could cause aninjury needing time off work, with a control visibly missing, OR{required};"low": only minor issues that are actually visible: housekeeping, atrip 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 hazardis "low" or "none", whatever tools or plant are nearby.Say each thing once. Be concise, factual, and neutral. This is a safety record,not marketing copy."""# Mode 1: detector is the PPE record. The VLM writes the hazard statement 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 adeterministic object-detection model, one row per person and PPE item.""" + _HAZARD_FIRST + """Rules for the detector findings:- The app shows the detector's PPE record to the reader as a table, builtdirectly from the detector. Your text must not repeat it, so write no PPEinventory, and never mention "the detector", confidence scores or overlapvalues in "issue", "main_hazard", "missing_controls" or"safety_observation". The reader of those fields has never heard of thedetector.- The detector covers only the PPE items in its findings. It knows nothing aboutthe activity, the surroundings, or harnesses and other fall-arrest equipment,so the issue, the main hazard and the missing controls come from what you seein the IMAGE.- The detector is the authoritative record for the PPE it covers. You do notdecide whether an item is required ("level" says that), and you do not drop orplay down a finding because you think it does not matter in this scene.- "missing_controls" may include a PPE item only when it is the direct controlfor the issue (a harness for work at height, eye protection for grinding). Donot list an item there that the detector marks "present".- FLAG, DON'T OVERRIDE: the detector can miss an object or mistake one foranother. When its status for an item is clearly contradicted by the image, addan entry to "verify_items". That means: it says "missing" and the item, or anequivalent such as a face shield for eye protection, is plainly worn; or itsays "present" and that part of the body is plainly bare. Do this only when itis clear. An "uncertain" status that you cannot settle from the image is not acontradiction, so leave it alone.- "person_id" numbers the people from left to right. A null person_id means thedetector could not tie the item to one person.- 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;8 unmodified linesfootwear), and add "fall_arrest" (harness) only when someone is working atheight. If several people are visible, record the worst case for each key andsay in "safety_observation" which person it applies to.- Helmet and high-visibility vest are REQUIRED on site. Gloves, eye protectionand footwear are advisory.- Give each item one status and use it everywhere in your answer. In words, useone 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 viewand 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 ofthe last two you mean. Bare hands in plain view are an observation, not aguess, 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_DETECTOR20 unmodified linesreturn model, provider, modeldef _detector_brief(detection_result: dict) -> dict:"""What the VLM needs from the detector: the PPE findings only. Boxes, rawconfidences and the detail strings are left out on purpose, because they arewhat 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 (the reader already sees these in a table; use them ""only to flag a 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.")5 unmodified linesreturn {"raw": text, "parse_error": True}def _finalise(result: dict, with_detector: bool) -> dict:"""Make the result predictable for the app and the endpoint:- "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 older text field) is derived from it in code,so existing consumers still get a string."""if not isinstance(result, dict) or result.get("parse_error"):return resultraw = 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"] = itemsparts = []for it in items:who = f"person {it['person_id']}: " if it["person_id"] is not None else ""seen = f" - {it['seen']}" if it["seen"] else ""parts.append(f"{who}{it['item']}{seen}")result["detector_disagreement"] = "; ".join(parts)return result# ---------------------------------------------------------------------------# Provider back-ends# ---------------------------------------------------------------------------86 unmodified linesraise ValueError(f"Unknown provider '{provider}' for model '{model}'")result = backend(model_id, system, media_type, b64, user_text)result = _finalise(result, with_detector)result["_model"] = keyresult["_use_detector"] = with_detectorreturn result
vlm_caption.py+217-120