<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Guo Tiantian on Medium]]></title>
        <description><![CDATA[Stories by Guo Tiantian on Medium]]></description>
        <link>https://medium.com/@guo.tiantian3002?source=rss-5114011df30------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rphcAxdiDtxXnjfkmA7lQQ.jpeg</url>
            <title>Stories by Guo Tiantian on Medium</title>
            <link>https://medium.com/@guo.tiantian3002?source=rss-5114011df30------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:53:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guo.tiantian3002/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Trustable AI for Utility Monitoring: A Multi-Agent, LLM-Driven Approach]]></title>
            <link>https://medium.com/@guo.tiantian3002/building-trustable-ai-for-utility-monitoring-a-multi-agent-llm-driven-approach-b3a7724eae50?source=rss-5114011df30------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3a7724eae50</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Guo Tiantian]]></dc:creator>
            <pubDate>Tue, 29 Jul 2025 16:01:36 GMT</pubDate>
            <atom:updated>2025-07-30T04:59:44.990Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern utility systems are growing increasingly complex. As our infrastructure digitizes, the demand for intelligent, explainable, and scalable meter monitoring is reaching new heights. While traditional machine learning (ML) models like XGBoost offer solid performance, they often lack transparency and adaptability — two crucial factors in operational environments where stakes are high.<br>In this post, we introduce a hybrid AI framework that uses large language models (LLMs) and a modular multi-agent system to deliver reliable, explainable, and efficient meter anomaly detection.</p><h3>The Problem: Complex Infrastructure, Opaque Models</h3><p>Typical anomaly detection pipelines rely on fixed-rule logic or monolithic ML models. While effective in controlled scenarios, these systems struggle in dynamic utility environments. Policies change, data structures evolve, and faults don’t always look the same.<br>Moreover, explainability has become a key concern. Tools like SHAP or LIME offer post-hoc explanations but require technical expertise. That’s where LLMs shine: they can turn complex decisions into natural language explanations.</p><h3>The Solution: A Multi-Agent Architecture</h3><p>Inspired by human workflows, we break down the system into four specialized agents:<br><strong>Query Agent</strong> — fetches, preprocesses, and generates features from meter data.<br><strong>Text-to-SQL Agent</strong> — translates user prompts or internal agent queries into executable SQL.<br><strong>Rule-Based Agent </strong>— applies domain-specific rules to validate or adjust AI outputs.<br><strong>Explainability Agent</strong> — powered by LLMs to generate plain-language reports and diagnostics.</p><p>These agents communicate through a shared coordination layer, which manages task flow and data handoff. Think of it like CrewAI, but tuned for infrastructure reliability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*9rjHhYQnOx02gV4sQ9n0CQ.png" /><figcaption>Fig.1. System Overview</figcaption></figure><h3>How It Works</h3><ul><li>The<strong> Query Agent</strong> pulls structured data and generates features like trends or statistical anomalies.</li><li>The <strong>Text-to-SQL Agent</strong>, enhanced with Retrieval-Augmented Generation (RAG), builds contextual SQL queries from natural language prompts.</li><li>The <strong>Rule-Based Agent</strong> adds human-understandable policy logic. For example: “flag a case if six months of zero readings are recorded”.</li><li>Finally, the <strong>Explainability Agent</strong> pulls everything together and answers questions like, “Why was this meter flagged?”</li></ul><h3><strong>Text-to-SQL Agent with RAG: Under the Hood</strong></h3><p>Retrieving the right data starts with asking the right question. Our Text-to-SQL agent converts user input or downstream task instructions into SQL queries, enabling flexible interaction with utility databases.<br>But SQL generation in isolation can be brittle. That’s why we augment it with Retrieval-Augmented Generation (RAG). Before forming a query, the agent pulls relevant information such as schema structure, column descriptions, and recent query logs. This context dramatically improves query accuracy and reduces token waste.<br>Using RAG, our system:</p><ul><li>Adapts to schema changes</li><li>Produces more accurate and interpretable queries</li><li>Reduces hallucination of table or field names</li></ul><p>The result is a robust querying layer that speaks the language of both humans and machines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*ITCPHU1lYREiULdpHMivsg.png" /><figcaption>Fig.2. Text-to-SQL Agent architecture enhanced with RAG.</figcaption></figure><h3>Experiments</h3><p>We ran a series of experiments to assess the real-world value of our hybrid system. Here are the key findings:</p><ol><li><strong>Text-to-SQL Gets Smarter with RAG</strong></li></ol><p>RAG enhances the Text-to-SQL agent by injecting schema metadata, business rules, and examples into each query prompt. In our evaluation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5vLrvD63mu4WIAjOekJJBQ.png" /></figure><p>That’s not just smarter — it’s faster and cheaper.</p><p><strong>2. Rule-Based Logic Still Catches What AI Misses</strong></p><p>In our 3-month evaluation (Jan–Mar 2025), we monitored thousands of utility meter cases. Some were flagged by AI, others by rule-based logic. Interestingly, a growing number of cases were only caught by rules, not by the AI model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qsw23mb9-FB0hfm8mDn07A.png" /></figure><p><strong>Takeaway</strong>: Domain rules still play a critical role in catching anomalies that the model misses. This highlights the importance of hybrid AI + rule systems in sensitive domains like energy management.</p><p><strong>3. Optimizing Report Generation with Batching</strong></p><p>We also tested batch sizes for report generation to balance clarity and speed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s201WCr1CFkaW7Z23qYllg.png" /></figure><p>Recommendation: Batch size 3 hits the sweet spot for efficient, high-quality generation. Thanks to <a href="https://medium.com/u/b3e16e0c968d">Leongjunhoe</a></p><p><strong>4. Chatbot Interface For Engineers</strong></p><p>To make the insights more accessible, we built a chatbot interface that lets engineers generate natural-language reports with a simple prompt. This tool, developed by <a href="https://medium.com/u/b3e16e0c968d">Leongjunhoe</a>, integrates with the agent system and enables rapid diagnosis without SQL or code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2bQgYRWnddri-EgCGdfDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uKHEI6AQpjSZlSTMiozUrw.png" /></figure><h3>Why It Matters</h3><p>Utility companies need more than accurate models; they need models that explain themselves, adapt to policy, and scale across use cases. This multi-agent framework:</p><ul><li>Enables natural language access to structured data</li><li>Preserves rule-based governance</li><li>Provides reliable, explainable insights for human operators</li></ul><h3>What’s Next</h3><p>We’re exploring:</p><ul><li>Reinforcement learning to improve agent collaboration</li><li>Extending the system to gas leak detection and predictive maintenance</li><li>Integrating governance controls and traceability</li></ul><p>If you’re interested in explainable AI, infrastructure automation, or building LLM-powered agent systems, let’s connect!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3a7724eae50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object-relation Detection YOLOv8 Model trained by large model generated&auto-labeled images]]></title>
            <link>https://medium.com/@guo.tiantian3002/object-relation-detection-yolov8-model-trained-by-large-model-generated-auto-labeled-images-0bcb2d4d4143?source=rss-5114011df30------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bcb2d4d4143</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Guo Tiantian]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 08:06:45 GMT</pubDate>
            <atom:updated>2024-03-26T14:33:45.727Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkLw6xxygc4w&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkLw6xxygc4w&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FkLw6xxygc4w%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb2ee0af0ccb5ff4c7e227cf4582a605/href">https://medium.com/media/cb2ee0af0ccb5ff4c7e227cf4582a605/href</a></iframe><h3>Object</h3><p>Industrial safety is a critical concern, prompting significant research efforts in AI aimed at devising intelligent tools to mitigate potential hazards. Helmet detection stands out as a prominent area of focus within these endeavors.</p><h3>Survey</h3><p>There are some of the object detection tools that can</p><ul><li>Detect helmet: such as <a href="https://github.com/yihong1120/Construction-Hazard-Detection/blob/main/README-zh-tw.md">Construction-Hazard-Detection</a>, <a href="https://github.com/singhamal001/SafeSite">SAFESITE</a>, <a href="https://www.sensetime.com/hk/solution-revision?categoryId=41132746">a platform from SENSETIME</a> and <a href="https://www.kaggle.com/code/plasticglass/yolov8-safety-helmet-detection">other helmet detection tries from kaggle</a></li><li>Detect human wearing helmet: such as <a href="https://github.com/AnshulSood11/PPE-Detection-YOLO-Deep_SORT">PPE-Detection-YOLO-Deep_SORT</a></li></ul><p>However, these detections have certain limitations:</p><ul><li>Several tools solely detect the presence of a helmet without assessing whether it is properly worn by the worker;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukUkCkeqBRsJBxiXd9_Maw.png" /></figure><ul><li>The training images utilized are of low quality, sourced from the internet;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dx3QLfIlZTwSaXKj9Z5DFQ.png" /></figure><ul><li>The dataset employed for training the detection model requires manual labeling, a process that is both time-consuming and costly;</li><li>The dataset contains thousands of images, potentially exceeding the necessary volume for effective training.</li></ul><h3>Solution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aw9nXZpQxT2vFWb7kEu6tg.png" /><figcaption>Solution overview</figcaption></figure><p>The solution outlined in the following blog post will adhere to these steps:</p><ol><li>Prompt Generation: GPT-4 will be employed to generate diverse prompts for text-to-image generation</li><li>Image Generation: Stable Diffusion, Dall-e-3, GroundingDino will be employed to generate images from prompts (text)</li><li>Auto Label Image Dataset: GroundingDino, GPT4V will be employed to auto label images in Yolo dataset format.</li><li>Model Training: YOLOv8 will be employed as framework to train new Helmet-on-head Detector AI model.</li></ol><h3>Preparation</h3><p>Install dependencies on GPU enabled PC or cloud compute. Below are some examples, need to install torch or other packages dependent on python version.</p><pre>%pip install torch==1.11.0+cu102 torchvision==0.12.0+cu102 torchaudio==0.11.0 --extra-index-url https://download.pytorch.org/whl/cu102<br><br>!git clone https://github.com/IDEA-Research/GroundingDINO.git<br>%cd GroundingDINO<br>%pip install -e .<br><br>%mkdir weights<br>%cd weights<br>!wget -q https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth</pre><h3>Prompt Generation</h3><p>The concept of using ChatGPT as a prompt generator for Stable Diffusion, and Dall-e-3 is interesting. It spares us from the need to extensively contemplate the myriad situations our images should cover, enabling the creation of a dataset that better captures the essence of person, helmet, and person with helmet, regardless of the scenario.</p><p>A sample request to generate positive images:</p><pre>input_request = &quot;&quot;&quot;<br>I have to generate an image dataset for a human wear safety helmet detection model <br>with stable diffusion. Give me 30 different prompts to obtain images <br>of different situations like construction site, High voltage electricity site that <br>helmet correctly worn by workers in different environments and poses. Your response <br>must be only in the form of a python list of strings.  <br>Add the string &quot;,  photo , 4k, high resolution&quot; at the end of each string<br>&quot;&quot;&quot;</pre><p>ChatGPT response:</p><pre>response = &quot;&quot;&quot; [<br>    &quot;Construction worker wearing safety helmet at a construction site, photo, 4k, high resolution&quot;,<br>    &quot;Electrician wearing safety helmet at a high voltage electricity site, photo, 4k, high resolution&quot;,<br>    &quot;Factory worker wearing safety helmet on the production floor, photo, 4k, high resolution&quot;,<br>    &quot;Miner wearing safety helmet in a mine shaft, photo, 4k, high resolution&quot;,<br>    &quot;Firefighter wearing safety helmet at the scene of a fire, photo, 4k, high resolution&quot;,<br>    &quot;Forestry worker wearing safety helmet in a forest, photo, 4k, high resolution&quot;,<br>    &quot;Scaffolder wearing safety helmet on scaffolding, photo, 4k, high resolution&quot;,<br>    &quot;Oil rig worker wearing safety helmet on an offshore platform, photo, 4k, high resolution&quot;,<br>    &quot;Railway worker wearing safety helmet on railroad tracks, photo, 4k, high resolution&quot;,<br>    &quot;Road construction worker wearing safety helmet on a highway, photo, 4k, high resolution&quot;,<br>    &quot;Dock worker wearing safety helmet in a shipping yard, photo, 4k, high resolution&quot;,<br>    &quot;Agricultural worker wearing safety helmet on a farm, photo, 4k, high resolution&quot;,<br>    &quot;Warehouse worker wearing safety helmet in a warehouse, photo, 4k, high resolution&quot;,<br>    &quot;Airport ground crew wearing safety helmet on the tarmac, photo, 4k, high resolution&quot;,<br>    &quot;Mechanic wearing safety helmet in an auto repair shop, photo, 4k, high resolution&quot;,<br>    &quot;Plumber wearing safety helmet in a utility tunnel, photo, 4k, high resolution&quot;,<br>    &quot;Construction inspector wearing safety helmet at a construction site, photo, 4k, high resolution&quot;,<br>    &quot;Crane operator wearing safety helmet on a construction site, photo, 4k, high resolution&quot;,<br>    &quot;High-rise window washer wearing safety helmet on a skyscraper, photo, 4k, high resolution&quot;,<br>    &quot;Bridge inspector wearing safety helmet under a bridge, photo, 4k, high resolution&quot;,<br>    &quot;Demolition worker wearing safety helmet at a demolition site, photo, 4k, high resolution&quot;,<br>    &quot;Highway patrol officer wearing safety helmet on duty, photo, 4k, high resolution&quot;,<br>    &quot;HVAC technician wearing safety helmet in an industrial facility, photo, 4k, high resolution&quot;,<br>    &quot;Security guard wearing safety helmet on patrol, photo, 4k, high resolution&quot;,<br>    &quot;Painter wearing safety helmet on a construction site, photo, 4k, high resolution&quot;,<br>    &quot;Electric utility worker wearing safety helmet on a power line, photo, 4k, high resolution&quot;,<br>    &quot;Roofer wearing safety helmet on a roof under construction, photo, 4k, high resolution&quot;,<br>    &quot;Tower climber wearing safety helmet on a communication tower, photo, 4k, high resolution&quot;,<br>    &quot;Rescue worker wearing safety helmet during a rescue operation, photo, 4k, high resolution&quot;,<br>    &quot;Welder wearing safety helmet in a welding workshop, photo, 4k, high resolution&quot;<br>]&quot;&quot;&quot;<br></pre><p>A sample request to generate negative images:</p><pre>input_request = &quot;&quot;&quot;<br>I have to generate an image dataset for human detection model <br>with stable diffusion. Give me 30 different prompts to obtain images <br>of different situations that human in different environments and poses. <br>Your response must be only in the form of a python list of strings.  <br>Add the string &quot;,  photo , 4k, high resolution&quot; at the end of each string<br>&quot;&quot;&quot;<br></pre><p>ChatGPT response:</p><pre>response = &quot;&quot;&quot;[<br>    &quot;Construction worker without helmet at a construction site, photo, 4k, high resolution&quot;,<br>    &quot;Electrician without helmet at a high voltage electricity site, photo, 4k, high resolution&quot;,<br>    &quot;Factory worker without helmet on the production floor, photo, 4k, high resolution&quot;,<br>    &quot;Miner without helmet in a mine shaft, photo, 4k, high resolution&quot;,<br>    &quot;Firefighter without helmet at the scene of a fire, photo, 4k, high resolution&quot;,<br>    &quot;Forestry worker without helmet in a forest, photo, 4k, high resolution&quot;,<br>    &quot;Scaffolder without helmet on scaffolding, photo, 4k, high resolution&quot;,<br>    &quot;Oil rig worker without helmet on an offshore platform, photo, 4k, high resolution&quot;,<br>    &quot;Railway worker without helmet on railroad tracks, photo, 4k, high resolution&quot;,<br>    &quot;Road construction worker without helmet on a highway, photo, 4k, high resolution&quot;,<br>    &quot;Dock worker without helmet in a shipping yard, photo, 4k, high resolution&quot;,<br>    &quot;Agricultural worker without helmet on a farm, photo, 4k, high resolution&quot;,<br>    &quot;Warehouse worker without helmet in a warehouse, photo, 4k, high resolution&quot;,<br>    &quot;Airport ground crew without helmet on the tarmac, photo, 4k, high resolution&quot;,<br>    &quot;Mechanic without helmet in an auto repair shop, photo, 4k, high resolution&quot;,<br>    &quot;Plumber without helmet in a utility tunnel, photo, 4k, high resolution&quot;,<br>    &quot;Construction inspector without helmet at a construction site, photo, 4k, high resolution&quot;,<br>    &quot;Crane operator without helmet on a construction site, photo, 4k, high resolution&quot;,<br>    &quot;High-rise window washer without helmet on a skyscraper, photo, 4k, high resolution&quot;,<br>    &quot;Bridge inspector without helmet under a bridge, photo, 4k, high resolution&quot;,<br>    &quot;Demolition worker without helmet at a demolition site, photo, 4k, high resolution&quot;,<br>    &quot;Highway patrol officer without helmet on duty, photo, 4k, high resolution&quot;,<br>    &quot;HVAC technician without helmet in an industrial facility, photo, 4k, high resolution&quot;,<br>    &quot;Security guard without helmet on patrol, photo, 4k, high resolution&quot;,<br>    &quot;Painter without helmet on a construction site, photo, 4k, high resolution&quot;,<br>    &quot;Electric utility worker without helmet on a power line, photo, 4k, high resolution&quot;,<br>    &quot;Roofer without helmet on a roof under construction, photo, 4k, high resolution&quot;,<br>    &quot;Tower climber without helmet on a communication tower, photo, 4k, high resolution&quot;,<br>    &quot;Rescue worker without helmet during a rescue operation, photo, 4k, high resolution&quot;,<br>    &quot;Welder without helmet in a welding workshop, photo, 4k, high resolution&quot;]<br>&quot;&quot;&quot;</pre><p>You can randomly check the prompts.</p><h3>Image Generation</h3><p>Now that we have the prompts in the form of a Python list, we can proceed with the creation of images using the Diffusers library from Hugging Face​. It is possible to choose from various pretrained models in the text-to-image category, which can be run locally, ensuring access to a GPU with sufficient memory. In this specific case, we are using the “dreamlike-photoreal-2.0” model from dreamlike-art, but it’s just an example; we can also use “stable-diffusion-2–1” from stabilityai, among many others, we also tried Dall-e-3 model.</p><p>Code to generate images by Stable Diffusion:</p><pre>from diffusers import DiffusionPipeline<br>import torch<br>import numpy as np<br>from PIL import Image<br><br>device = torch.device(&#39;cuda&#39; if torch.cuda.is_available() else &#39;cpu&#39;)<br>sd_pipe = DiffusionPipeline.from_pretrained(<br>    &quot;dreamlike-art/dreamlike-photoreal-2.0&quot;,<br>    torch_dtype=torch.float16,<br>    use_safetensors=True<br>).to(device)<br><br>negative_prompt=&quot;low resolution, ugly, naked, nude&quot;<br>num_batches = len(chatgpt_prompts)<br>num_images_per_batch = 8<br><br>generated_images = []<br><br>j = 0<br>for i in range(num_batches):<br>    batch = sd_pipe(prompt=chatgpt_prompts[i],<br>                  negative_prompt=negative_prompt,<br>                  num_images_per_prompt=num_images_per_batch,<br>                    height=416,<br>                    width=416)<br>    for batch_image in batch.images:<br>        generated_images.append(np.array(batch_image))<br>        <br>        image_name = &quot;data/generated_image/img_&quot; + str(j) + &quot;.png&quot;<br>        im = Image.fromarray(np.array(batch_image))<br>        im.save(image_name)<br>        j = j + 1</pre><p>show images generated:</p><pre>def mosaic_sample(list_of_arrays, nrows=5, ncols=8):<br>    random_choose = np.arange(0,len(list_of_arrays), 1)<br>    np.random.shuffle(random_choose)<br>    random_choose = random_choose[:nrows*ncols]<br>    out_w, out_h = 540, 720<br>    d_w, d_h = out_w//ncols, out_h//nrows<br>    out = np.zeros((out_h, out_w, 3), dtype=np.uint8)<br>    row = 0<br>    col = 0<br>    for choose in random_choose:<br>        choosen_image = Image.fromarray(list_of_arrays[choose]<br>                                        ).resize((d_w, d_h))<br>        out[row*d_h:row*d_h + d_h, <br>            col*d_w:col*d_w + d_w, <br>            :] = np.array(choosen_image)<br>        row += 1<br>        if row == nrows:<br>            row = 0<br>            col += 1<br>    return out<br><br>Image.fromarray(mosaic_sample(generated_images, nrows=5, ncols=3))</pre><p>Positive images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*aS4U-PUKT28amcBftKWaAw.png" /></figure><p>Negative images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*C5C8zwYe3_8-Vcbueyk6Yw.png" /></figure><p>By the way, the text-2-images generation tools sometimes are not so clever. The model is unable to generate images without helmet. In order to generate more negative case images, use Grounded-SAM to locate and mask the helmet in the image, then use stable diffusion to inpainting the masked area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O6BZgB8wCuCuttusXNyapw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LGX5DiTFAotHi4Mx63VHRA.png" /></figure><h3>Auto Label Image Dataset</h3><p>However, to train a supervised learning model like the detection model, in addition to images, we need annotations, i.e., the bounding boxes of person wearing helmet for each image. Labeling a dataset is often the operation that requires the most effort in terms of time and human resources: you have to go through all the images and manually draw rectangles around the target class in each image. In order to make this operation completely automatic, we can leverage the power and versatility of GroundingDINO and GPT4V. It takes as input the image we want to label and a text describing what we want to annotate — in our case, we need to crop out “person” (“person” better than “human” or “men” here).</p><pre>import os, sys<br>sys.path.append(os.path.join(os.getcwd(), &quot;GroundingDINO&quot;))<br>from torchvision.ops import box_convert<br>import GroundingDINO.groundingdino.datasets.transforms as T<br>from GroundingDINO.groundingdino.models import build_model<br>from GroundingDINO.groundingdino.util import box_ops<br>from GroundingDINO.groundingdino.util.slconfig import SLConfig<br>from GroundingDINO.groundingdino.util.utils import (clean_state_dict, <br>                                                  get_phrases_from_posmap)<br>from GroundingDINO.groundingdino.util.inference import (annotate, <br>                                                        load_image, <br>                                                         predict)<br>from huggingface_hub import hf_hub_download<br><br>import base64, os<br>import requests<br>import io</pre><pre>def load_model_hf(repo_id, filename, ckpt_config_filename, device=&#39;cpu&#39;):<br>    cache_config_file = hf_hub_download(repo_id=repo_id, <br>                                    filename=ckpt_config_filename)<br><br>    args = SLConfig.fromfile(cache_config_file)<br>    args.device = device<br>    model = build_model(args)<br><br>    cache_file = hf_hub_download(repo_id=repo_id, filename=filename)<br>    checkpoint = torch.load(cache_file, map_location=device)<br>    log = model.load_state_dict(clean_state_dict(checkpoint[&#39;model&#39;]), <br>                                                        strict=False)<br>    print(&quot;Model loaded from {} \n =&gt; {}&quot;.format(cache_file, log))<br>    _ = model.eval()<br>    return model</pre><p>From the detection function</p><pre>boxes, logits, phrases = predict(model=model, image=image_preprocessed, caption=text_prompt, box_threshold=box_threshold, text_threshold=text_threshold)</pre><p>we got the bounding box of “person” and further input the bounding box of “person” to GPT4V to further label the relationship of “person wearing helmet” by</p><pre>if person wear helmet, return yes, else return no&quot;</pre><pre>def gpt_label(img, boxes, logits, phrases):<br>    img_width = np.array(img).shape[0]<br>    img_height = np.array(img).shape[1]<br>    <br>    if len(np.array(boxes)) &gt; 0:<br>        for i in range(len(np.array(boxes))):<br>            x_center, y_center, width, height = np.array(boxes)[i][0], np.array(boxes)[i][1], np.array(boxes)[i][2], np.array(boxes)[i][3]<br>            # Convert normalized coordinates [0, 1] back to pixel values.<br>            x_center = x_center * img_width<br>            y_center = y_center * img_height<br>            width = width * img_width<br>            height = height * img_height<br><br>            # Calculate the top-left (x1, y1) and bottom-right (x2, y2) coordinates of the box.<br>            x1 = x_center - (width / 2)<br>            y1 = y_center - (height / 2)<br>            x2 = x_center + (width / 2)<br>            y2 = y_center + (height / 2)<br><br>            b = io.BytesIO()<br>            cropImg=Image.fromarray(img).crop((x1, y1, x2, y2))<br>            cropImg.save(b, &#39;jpeg&#39;)<br>            base64_cropImg = base64.b64encode(b.getvalue()).decode(&#39;utf-8&#39;)<br><br>            headers = {<br>              &quot;Content-Type&quot;: &quot;application/json&quot;,<br>              &quot;Authorization&quot;: f&quot;Bearer {api_key}&quot;<br>            }<br><br>            payload = {<br>              &quot;model&quot;: &quot;gpt-4-vision-preview&quot;,<br>              &quot;messages&quot;: [<br>                {<br>                  &quot;role&quot;: &quot;user&quot;,<br>                  &quot;content&quot;: [<br>                    {<br>                      &quot;type&quot;: &quot;text&quot;,<br>                      &quot;text&quot;: &quot;if person wear helmet, return yes, else return no&quot;<br>                    },<br>                    {<br>                      &quot;type&quot;: &quot;image_url&quot;,<br>                      &quot;image_url&quot;: {<br>                        &quot;url&quot;: f&quot;data:image/jpeg;base64,{base64_cropImg}&quot;<br>                      }<br>                    }<br>                  ]<br>                }<br>              ],<br>              &quot;max_tokens&quot;: 300<br>            }<br><br>            response = requests.post(&quot;https://api.openai.com/v1/chat/completions&quot;, headers=headers, json=payload)<br>            if len(response.json()) &gt; 1:<br>                output = response.json()[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;]<br>                if output == &quot;Yes&quot;:<br>                    phrases[i] = &quot;Positive&quot;<br>                else:<br>                    phrases[i] = &quot;Negative&quot;<br>            else:<br>                phrases[i] = &quot;Negative&quot;<br>    return phrases</pre><pre><br>def detect(img, image_source, image_preprocessed, text_prompt, model, <br>                    box_threshold = 0.35, text_threshold = 0.25):<br>    boxes, logits, phrases = predict(model=model, image=image_preprocessed, caption=text_prompt, box_threshold=box_threshold, text_threshold=text_threshold)<br>    <br>    phrases = gpt_label(img, boxes, logits, phrases)<br>    <br>    annotated_frame = annotate(image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)<br>    annotated_frame = annotated_frame[...,::-1] # BGR to RGB<br>    return annotated_frame, boxes, phrases</pre><h3>Model Training</h3><p>After dataset of images prepared, we can future prepared those images to fit YOLOv8 training format. To find out, let’s use one of the most commonly used architectures for detection, namely YOLOv8 in the “Small” version. Utilizing the Ultralytics library, we need to save our dataset to disk in a specific format: the dataset root must already contain the split into train, val, and test sets. Each set must have two subfolders, “images” and “labels”: the former containing all images in .jpg format, and the latter containing all bounding box annotation files in YOLO format (text files .txt with one bounding box per line containing class_id, x, y, w, h as a percentage of the image and separated by tabs). Moreover, we need a dataset.yaml file containing the paths to images and some other parameters. Let’s do the refactor:</p><pre>!mkdir yolo_dataset<br>!mkdir yolo_dataset/train<br>!mkdir yolo_dataset/train/images<br>!mkdir yolo_dataset/train/labels<br>!mkdir yolo_dataset/valid<br>!mkdir yolo_dataset/valid/images<br>!mkdir yolo_dataset/valid/labels<br>!mkdir yolo_dataset/test<br>!mkdir yolo_dataset/test/images<br>!mkdir yolo_dataset/test/labels</pre><pre>path:  yolo_dataset<br>train: yolo_dataset/train/<br>test: yolo_dataset/test/<br>val: yolo_dataset/valid/<br><br>#Classes<br>nc: 2<br><br>#classes names<br>names: <br>    0: &#39;Negative&#39;<br>    1: &#39;Positive&#39;</pre><pre>annotated_images = []<br>source_images = []<br>preprocessed_images = []<br>annotations = []<br>annnotated_frames = []<br><br># mark negative images: this prevents from making boxes<br># man_in_helmet = np.ones(len(generated_images))<br># man_in_helmet[913:] = 0<br><br>no_of_images = len(generated_images)<br><br># train/valid/test split (random choose) 80% / 10% / 10%<br><br>images_ids = np.arange(0,len(generated_images), 1)<br>np.random.shuffle(images_ids)<br>train_ids = images_ids[:int(len(images_ids)*0.8)]<br>valid_ids = images_ids[int(len(images_ids)*0.8):int(len(images_ids)*0.9)]<br>test_ids = images_ids[int(len(images_ids)*0.9):]</pre><pre>for i, pil_image in enumerate(generated_images):<br>    image_source, image_preprocessed = preprocess_image(pil_image)<br>    # source_images.append(image_source)<br>    # preprocessed_images.append(image_preprocessed)<br><br>    # detect person with helmet and save as yolo dataset format<br>    annotated_frame, detected_boxes, phrases = detect(pil_image,image_source,image_preprocessed,text_prompt=&quot;person&quot;, model=groundingdino_model, box_threshold = 0.3, text_threshold = 0.25)<br>    print(i)<br>    if len(phrases) == 0:<br>        # negative images does not have bounding boxes<br>        annotated_images = image_source<br>        annotations = torch.empty((0,4))<br>    else:<br>        # positive images<br>        annotated_images = annotated_frame<br>        annotations = detected_boxes<br><br>    if i in train_ids:<br>        original_image = pil_image<br>        # saving to train/images folder<br>        Image.fromarray(original_image).save(<br>                  f&quot;./data/yolo_dataset/train/images/{i}.png&quot;)<br>        # saving boxes annotations in yolo format (class x y width height) <br>        # to train/labels<br>        boxes = annotations.numpy().tolist()<br><br>        with open(f&quot;./data/yolo_dataset/train/labels/{i}.txt&quot;, &quot;w+&quot;) as file:<br>            for b in range(len(boxes)):<br>                if phrases[b] == &quot;Negative&quot;:<br>                    body = &quot;\n&quot;.join([&quot;0\t&quot;+&quot;\t&quot;.join([str(coord) for coord in boxes[b]])]) + &quot;\n&quot;<br>                elif phrases[b] == &quot;Positive&quot;:<br>                    body = &quot;\n&quot;.join([&quot;1\t&quot;+&quot;\t&quot;.join([str(coord) for coord in boxes[b]])]) + &quot;\n&quot;<br>                else:<br>                    body = &quot;\n&quot;.join([&quot;0\t&quot;+&quot;\t&quot;.join([str(coord) for coord in boxes[b]])]) + &quot;\n&quot;<br>                file.write(body)<br>        file.close()<br><br>    if i in valid_ids:<br>        original_image = pil_image<br>        # saving to valid/images folder<br>        Image.fromarray(original_image).save(<br>                    f&quot;./data/yolo_dataset/valid/images/{i}.png&quot;)<br>        # saving boxes annotations in yolo format (class x y width height) <br>        # to train/labels<br>        boxes = annotations.numpy().tolist()<br><br>        with open(f&quot;./data/yolo_dataset/valid/labels/{i}.txt&quot;, &quot;w+&quot;) as file:<br>            for b in range(len(boxes)):<br>                if phrases[b] == &quot;Negative&quot;:<br>                    body = &quot;\n&quot;.join([&quot;0\t&quot;+&quot;\t&quot;.join([str(coord) for coord in boxes[b]])]) + &quot;\n&quot;<br>                elif phrases[b] == &quot;Positive&quot;:<br>                    body = &quot;\n&quot;.join([&quot;1\t&quot;+&quot;\t&quot;.join([str(coord) for coord in boxes[b]])]) + &quot;\n&quot;<br>                else:<br>                    body = &quot;\n&quot;.join([&quot;0\t&quot;+&quot;\t&quot;.join([str(coord) for coord in boxes[b]])]) + &quot;\n&quot;<br>                file.write(body)<br>        file.close()<br><br>    if i in test_ids:<br>        original_image = pil_image<br>        # saving to train/images folder<br>        Image.fromarray(original_image).save(<br>                     f&quot;./data/yolo_dataset/test/images/{i}.png&quot;)<br>        # saving boxes annotations in yolo format (class x y width height) <br>        # to train/labels<br>        boxes = annotations.numpy().tolist()<br>        with open(f&quot;./data/yolo_dataset/test/labels/{i}.txt&quot;, &quot;w+&quot;) as file:<br>            for b in range(len(boxes)):<br>                if phrases[b] == &quot;Negative&quot;:<br>                    body = &quot;\n&quot;.join([&quot;0\t&quot;+&quot;\t&quot;.join([str(coord) for coord in boxes[b]])]) + &quot;\n&quot;<br>                elif phrases[b] == &quot;Positive&quot;:<br>                    body = &quot;\n&quot;.join([&quot;1\t&quot;+&quot;\t&quot;.join([str(coord) for coord in boxes[b]])]) + &quot;\n&quot;<br>                else:<br>                    body = &quot;\n&quot;.join([&quot;0\t&quot;+&quot;\t&quot;.join([str(coord) for coord in boxes[b]])]) + &quot;\n&quot;<br>                file.write(body)<br>        file.close()</pre><p>Auto label images one by one and distributed to the train/test/validate folder.</p><p>Training code is simple:</p><pre>from ultralytics import YOLO<br><br>detection_model = YOLO(&quot;yolov8n.pt&quot;)<br><br>training_results = detection_model.train(data=&quot;data/yolo_dataset.yaml&quot;, <br>                                         imgsz=416, <br>                                         batch=128,<br>                                         epochs=120)</pre><p>Then we got the model to detect if work wear helmet or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*Jn35yG12ufdCo-JoxUTg-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*DzPuz4ScvzmEY8nkWqdXtA.png" /></figure><p>Complete code please refer to the <a href="https://github.com/guo-tt/safety_cheers/tree/master">Github</a>.</p><h3>Conclusion</h3><p>In this article, we have demonstrated a potential fully automated approach for training computer vision models, object-object relation detection models even in the absence of data and annotations. However, while it may appear to be a revolutionary breakthrough, there are some observations I’ve made during the development of the pipeline:</p><ol><li>The images generation mostly dependent on the accurate descriptions of prompt, sometimes the images are not generated exactly like prompt. Hope in the future, the text-2-images foundation models will be more “clever”;</li><li>GPT4V cannot always tell the truth of “person-in-helmet”, especially it only see the back or side of human or human didn’t show face well;</li><li>Perhaps the best strategy is a hybrid approach involving both synthetic and real data: the former aids the latter in increasing both quantity and quality.</li></ol><p>If you’ve tried other approaches or have ideas to overcome the limitations of this pipeline, feel free to share with me and express your thoughts 🙂​. I believe there’s a significant opportunity in this area to enhance our work as AI engineers.</p><h3>References</h3><p>🙏A special thanks to the reference from which I get inspired for the code:</p><p><a href="https://medium.com/@deepGio/fully-automated-image-dataset-generation-and-labeling-with-chatgpt-sd-groundingdino-and-sam-7b9c39995305">https://medium.com/@deepGio/fully-automated-image-dataset-generation-and-labeling-with-chatgpt-sd-groundingdino-and-sam-7b9c39995305</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bcb2d4d4143" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>