Monday, July 13, 2026

 Sample code to query Qwen2.5VL-7B VLM model in chat mode


#! /usr/bin/python

# filename: vlm_scene_query.py

"""

Download an aerial image from an Azure SAS URL, extract XFIF/GPS metadata,

and query a vision-language model (e.g., Qwen2.5VL-7B VLM) to answer a

scene-level question such as estimating area based on parking spot counts.


Usage:

    export MODEL_ID="your-qwen-model-id-or-hf-repo"

    export HF_API_TOKEN="..." # if required by the model host

    python vlm_scene_query.py --sas-url "<SAS_URL>" --question "Estimate area in square meters"


Notes:

- This script uses the Hugging Face transformers pipeline as a generic interface.

  Qwen VLM may require a provider-specific SDK or a different pipeline name.

  Replace the model loading section with the provider-specific code if needed.

- The script extracts GPS EXIF if present and returns it with the model response.

"""


import os

import sys

import argparse

import tempfile

import json

import math

import logging

from typing import Optional, Dict, Any, Tuple


import requests

from PIL import Image

import exifread


# Optional: transformers pipeline for vision-language models

try:

    from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM

    HF_AVAILABLE = True

except Exception:

    HF_AVAILABLE = False


logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")

logger = logging.getLogger("vlm_scene_query")



def download_image_from_sas(sas_url: str, dest_path: str, timeout: int = 30) -> None:

    """Download an image from an Azure SAS URL to dest_path."""

    logger.info("Downloading image from SAS URL")

    resp = requests.get(sas_url, stream=True, timeout=timeout)

    resp.raise_for_status()

    with open(dest_path, "wb") as f:

        for chunk in resp.iter_content(chunk_size=8192):

            if chunk:

                f.write(chunk)

    logger.info("Downloaded image to %s", dest_path)



def extract_gps_from_exif(image_path: str) -> Dict[str, Any]:

    """Extract GPS EXIF data (if present) using exifread and return a dict."""

    logger.info("Extracting EXIF metadata")

    with open(image_path, "rb") as f:

        tags = exifread.process_file(f, details=False)

    gps = {}

    def _get(tag):

        return tags.get(tag)

    # Common EXIF GPS tags

    lat_ref = _get("GPS GPSLatitudeRef")

    lat = _get("GPS GPSLatitude")

    lon_ref = _get("GPS GPSLongitudeRef")

    lon = _get("GPS GPSLongitude")

    alt = _get("GPS GPSAltitude")

    if lat and lon and lat_ref and lon_ref:

        def _to_deg(value):

            # value is like [Rational(37,1), Rational(46,1), Rational(0,1)]

            try:

                parts = [float(x.num) / float(x.den) for x in value.values]

                deg = parts[0] + parts[1] / 60.0 + parts[2] / 3600.0

                return deg

            except Exception:

                return None

        lat_deg = _to_deg(lat)

        lon_deg = _to_deg(lon)

        if lat_deg is not None and lon_deg is not None:

            if str(lat_ref).upper().startswith("S"):

                lat_deg = -lat_deg

            if str(lon_ref).upper().startswith("W"):

                lon_deg = -lon_deg

            gps["latitude"] = lat_deg

            gps["longitude"] = lon_deg

    if alt:

        try:

            gps["altitude"] = float(alt.values[0].num) / float(alt.values[0].den)

        except Exception:

            pass

    # XFIF or other tags may be present; include raw tags for inspection

    gps["raw_tags"] = {k: str(v) for k, v in tags.items() if k.startswith("GPS")}

    return gps



def default_area_estimate_from_parking_count(parking_count: int,

                                             spot_length_m: float = 4.5,

                                             spot_width_m: float = 1.8,

                                             spacing_factor: float = 1.2) -> Tuple[float, float]:

    """

    Estimate area in square meters and square feet given a count of parking spots.

    Default sedan footprint: 4.5m x 1.8m = 8.1 m^2. spacing_factor accounts for drive lanes and spacing.

    Returns (area_m2, area_ft2).

    """

    single_spot_area = spot_length_m * spot_width_m * spacing_factor

    total_m2 = parking_count * single_spot_area

    total_ft2 = total_m2 * 10.7639

    return total_m2, total_ft2



def build_prompt_for_vlm(question: str, guidance: Optional[str] = None) -> str:

    """

    Build a clear prompt for the vision-language model. Guidance can include

    assumptions to make (e.g., sedan footprint).

    """

    base = (

        "You are given an aerial image. Answer the user's question precisely. "

        "If you need to make reasonable assumptions, state them explicitly. "

        "Return a JSON object with keys: 'answer_text', 'parking_spot_count' (int or null), "

        "'assumptions' (list of strings), and 'computed' (object with numeric fields). "

    )

    if guidance:

        base += guidance + " "

    base += "User question: " + question

    return base



def query_vlm_with_image(model_id: str, image_path: str, prompt: str, hf_token: Optional[str] = None) -> Dict[str, Any]:

    """

    Query a vision-language model with the image and prompt.

    This uses the Hugging Face pipeline interface as a generic example.

    Replace with provider-specific SDK if required by the model.

    """

    if not HF_AVAILABLE:

        raise RuntimeError("transformers not available in this environment; cannot load VLM pipeline")


    # If the model requires authentication, set the token in the environment for HF

    if hf_token:

        os.environ["HUGGINGFACEHUB_API_TOKEN"] = hf_token


    # Attempt to use a generic image-to-text pipeline. Some VLMs require custom loading.

    logger.info("Loading VLM model pipeline (model_id=%s)", model_id)

    try:

        # Many VLMs use a "vision-text" or "image-to-text" pipeline; this is a best-effort example.

        vlm = pipeline(task="image-to-text", model=model_id, device=0 if torch_cuda_available() else -1)

    except Exception:

        # Fallback: try seq2seq with processor + model (provider-specific)

        # Provide a helpful error message to the user

        raise RuntimeError(

            "Failed to instantiate a generic image-to-text pipeline for model_id=%s. "

            "Qwen VLMs often require provider-specific SDKs or a custom pipeline. "

            "Replace this function with the provider's recommended loading code." % model_id

        )


    logger.info("Running VLM inference")

    # Many pipelines accept a list of images and optional prompt; adapt as needed

    with open(image_path, "rb") as f:

        image_bytes = f.read()

    # The pipeline may accept a PIL Image or bytes; try PIL first

    pil_img = Image.open(image_path).convert("RGB")

    # Some pipelines accept a 'prompt' kwarg; others require concatenating prompt to input.

    try:

        result = vlm(pil_img, prompt=prompt, max_new_tokens=512)

    except TypeError:

        # If pipeline doesn't accept prompt kwarg, pass prompt as first argument

        result = vlm(prompt + "\n", pil_img, max_new_tokens=512)

    # result is often a list of dicts or a string

    logger.debug("Raw VLM result: %s", result)

    # Normalize to dict

    if isinstance(result, list) and len(result) > 0:

        raw_text = result[0].get("generated_text") or result[0].get("text") or str(result[0])

    elif isinstance(result, dict):

        raw_text = result.get("generated_text") or result.get("text") or json.dumps(result)

    else:

        raw_text = str(result)

    # Try to parse JSON from the model output; if not JSON, return text in answer_text

    try:

        parsed = json.loads(raw_text)

        return parsed

    except Exception:

        return {"answer_text": raw_text, "raw": raw_text}



def torch_cuda_available() -> bool:

    try:

        import torch

        return torch.cuda.is_available()

    except Exception:

        return False



def parse_parking_count_from_vlm_response(vlm_resp: Dict[str, Any]) -> Optional[int]:

    """

    Extract parking_spot_count if present in the VLM response dict.

    """

    try:

        count = vlm_resp.get("parking_spot_count")

        if count is None:

            # Try to parse from answer_text heuristically

            text = vlm_resp.get("answer_text", "")

            # naive heuristic: find first integer in text

            import re

            m = re.search(r"\b(\d{1,4})\b", text)

            if m:

                return int(m.group(1))

            return None

        return int(count)

    except Exception:

        return None



def main():

    parser = argparse.ArgumentParser(description="Query a VLM about an aerial image from an Azure SAS URL")

    parser.add_argument("--sas-url", required=True, help="Azure SAS URL to the JPEG image")

    parser.add_argument("--question", required=True, help="Natural language question to ask the VLM")

    parser.add_argument("--model-id", default=os.environ.get("MODEL_ID", "Qwen/Qwen-2.5V-L-7B"), help="VLM model id or repo")

    parser.add_argument("--hf-token", default=os.environ.get("HF_API_TOKEN"), help="Hugging Face API token if required")

    parser.add_argument("--assume-spot-length-m", type=float, default=4.5, help="Assumed parking spot length in meters")

    parser.add_argument("--assume-spot-width-m", type=float, default=1.8, help="Assumed parking spot width in meters")

    parser.add_argument("--spacing-factor", type=float, default=1.2, help="Factor to account for drive lanes and spacing")

    parser.add_argument("--no-vlm", action="store_true", help="Skip VLM and use deterministic heuristic only")

    args = parser.parse_args()


    with tempfile.TemporaryDirectory() as tmpdir:

        img_path = os.path.join(tmpdir, "scene.jpg")

        try:

            download_image_from_sas(args.sas_url, img_path)

        except Exception as e:

            logger.error("Failed to download image: %s", e)

            sys.exit(1)


        gps = extract_gps_from_exif(img_path)

        logger.info("Extracted GPS metadata: %s", gps)


        # Build prompt

        guidance = (

            f"Assume a typical U.S. sedan footprint of {args.assume_spot_length_m}m x {args.assume_spot_width_m}m "

            f"and a spacing factor of {args.spacing_factor} to account for drive lanes. "

            "Count visible parking spots if possible and compute total area in square meters and square feet."

        )

        prompt = build_prompt_for_vlm(args.question, guidance=guidance)


        vlm_response = None

        parking_count = None

        if not args.no_vlm:

            try:

                vlm_response = query_vlm_with_image(args.model_id, img_path, prompt, hf_token=args.hf_token)

                logger.info("VLM response received")

                parking_count = parse_parking_count_from_vlm_response(vlm_response)

            except Exception as e:

                logger.warning("VLM query failed or not available: %s", e)

                vlm_response = {"error": str(e)}

                parking_count = None


        # If VLM didn't provide a parking count, fall back to asking user assumption or using a heuristic

        if parking_count is None:

            # Heuristic fallback: try to detect cars using a very small, dependency-free heuristic is not reliable.

            # Instead, we will ask the model's textual output for a number if available; otherwise, default to 10 spots.

            if vlm_response and isinstance(vlm_response, dict):

                parking_count = parse_parking_count_from_vlm_response(vlm_response)

            if parking_count is None:

                logger.info("No parking count from VLM; using fallback default of 10 spots for estimation")

                parking_count = 10 # conservative default; in production, prefer human-in-the-loop


        area_m2, area_ft2 = default_area_estimate_from_parking_count(

            parking_count,

            spot_length_m=args.assume_spot_length_m,

            spot_width_m=args.assume_spot_width_m,

            spacing_factor=args.spacing_factor

        )


        # Build final structured response

        response = {

            "run_id": f"run-{os.urandom(6).hex()}",

            "agent_id": "qwen-vlm-estimator",

            "start_time": None,

            "end_time": None,

            "model_version": args.model_id,

            "gps": gps,

            "question": args.question,

            "vlm_raw_response": vlm_response,

            "parking_spot_count_used": parking_count,

            "assumptions": [

                f"sedan footprint {args.assume_spot_length_m}m x {args.assume_spot_width_m}m",

                f"spacing factor {args.spacing_factor}"

            ],

            "computed": {

                "area_m2": round(area_m2, 2),

                "area_ft2": round(area_ft2, 2),

                "spot_area_m2": round(args.assume_spot_length_m * args.assume_spot_width_m * args.spacing_factor, 2)

            },

            "answer_text": (

                f"Estimated total area ≈ {round(area_m2,2)} m² ({round(area_ft2,2)} ft²) "

                f"based on {parking_count} parking spots and assumed sedan footprint "

                f"{args.assume_spot_length_m}m x {args.assume_spot_width_m}m with spacing factor {args.spacing_factor}."

            )

        }


        # Print JSON response

        print(json.dumps(response, indent=2))



if __name__ == "__main__":

    main()


"""

Sample output:

 python Qwen.py --sas-url "https://tinyurl.com/carlot01" --question "what is the size of the parking lot shown in terms of square feet assuming usual size of a sedan in the united states and counting at most 1 occupancy per parking spot" --hf-token "<your-token>"

2026-07-12 19:16:35,444 INFO Downloading image from SAS URL

2026-07-12 19:16:36,468 INFO Downloaded image to C:\Users\ravib\AppData\Local\Temp\tmp6sle4o5d\scene.jpg

2026-07-12 19:16:36,470 INFO Extracting EXIF metadata

2026-07-12 19:16:36,491 INFO Extracted GPS metadata: {'raw_tags': {}}

2026-07-12 19:16:36,492 INFO Loading VLM model pipeline (model_id=Qwen/Qwen-2.5V-L-7B)

2026-07-12 19:16:37,065 INFO HTTP Request: GET https://huggingface.co/api/agent-harnesses "HTTP/1.1 200 OK"

2026-07-12 19:16:37,176 INFO HTTP Request: HEAD https://huggingface.co/Qwen/Qwen-2.5V-L-7B/resolve/main/config.json "HTTP/1.1 401 Unauthorized"

2026-07-12 19:16:37,178 WARNING VLM query failed or not available: Failed to instantiate a generic image-to-text pipeline for model_id=Qwen/Qwen-2.5V-L-7B. Qwen VLMs often require provider-specific SDKs or a custom pipeline. Replace this function with the provider's recommended loading code.

2026-07-12 19:16:37,179 INFO No parking count from VLM; using fallback default of 10 spots for estimation

{

  "run_id": "run-70391241b7e3",

  "agent_id": "qwen-vlm-estimator",

  "start_time": null,

  "end_time": null,

  "model_version": "Qwen/Qwen-2.5V-L-7B",

  "gps": {

    "raw_tags": {}

  },

  "question": "what is the size of the parking lot shown in terms of square feet assuming usual size of a sedan in the united states and counting at most 1 occupancy per parking spot",

  "vlm_raw_response": {

    "error": "Failed to instantiate a generic image-to-text pipeline for model_id=Qwen/Qwen-2.5V-L-7B. Qwen VLMs often require provider-specific SDKs or a custom pipeline. Replace this function with the provider's recommended loading code."

  },

  "parking_spot_count_used": 10,

  "assumptions": [

    "sedan footprint 4.5m x 1.8m",

    "spacing factor 1.2"

  ],

  "computed": {

    "area_m2": 97.2,

    "area_ft2": 1046.25,

    "spot_area_m2": 9.72

  },

  "answer_text": "Estimated total area \u2248 97.2 m\u00b2 (1046.25 ft\u00b2) based on 10 parking spots and assumed sedan footprint 4.5m x 1.8m with spacing factor 1.2."

}

"""


 


Sunday, July 12, 2026

 Generative Artificial Intelligence and the Importance of Data

Generative artificial intelligence is one of the most important developments in modern technology because it changes what computers can do. Traditional artificial intelligence usually focuses on recognizing patterns, classifying information, or predicting outcomes. Generative artificial intelligence goes further by creating new content, such as text, images, computer code, audio, and summaries. This shift from prediction to creation gives people and organizations new ways to solve problems, communicate ideas, and make work more efficient.

Large language models are a major part of this change. These models are trained on enormous amounts of text so they can understand language patterns and produce responses that sound natural. They can answer questions, translate languages, summarize long documents, write first drafts, assist with coding, and help people search for information. Some models are general-purpose, meaning they can help with many different kinds of tasks. Others are designed for a specific subject or job, such as medicine, law, cybersecurity, research, or software development. The most useful model depends on the problem being solved, the kind of data available, and the level of accuracy, speed, and cost required.

Data is the foundation of successful artificial intelligence projects. A model is only as useful as the information it can learn from or retrieve. Public information can help a model understand language and general knowledge, but many real-world tasks require private, specialized, or up-to-date information. Organizations often have valuable data stored in documents, databases, emails, images, audio files, and other sources. To make generative artificial intelligence more accurate and useful, that information needs to be organized, protected, and made available in responsible ways.

There are several ways to adapt language models for particular needs. Prompt engineering means writing clear instructions so the model produces a better answer. In-context learning gives the model helpful background information during a task. Retrieval-augmented generation allows a system to search trusted information sources and bring relevant facts into the model’s response. Fine-tuning changes a pretrained model so it performs better for a specific subject or task. Human feedback can also be used to guide a model toward more helpful, honest, and safe responses. These techniques show that artificial intelligence is not simply a tool that works automatically; it must be carefully guided and improved.

Generative artificial intelligence applications require strong technical support. Data pipelines are needed to collect, clean, organize, and deliver information to models. Vector representations help computers compare meaning rather than only matching exact words, which makes search and retrieval faster and more useful. Specialized hardware can speed up training and inference, especially for large models. User interfaces, such as web apps, chat windows, mobile apps, and developer tools, make these systems easier for people to use. In production settings, teams must also think about latency, cost, scalability, and how different systems will connect to each other.

Security, governance, and ethics are just as important as technical performance. Generative artificial intelligence systems may handle sensitive information, so organizations need clear rules about who can access data, how data is stored, and how it is used. There are also risks involving bias, privacy, misinformation, hallucinations, and copyright. A model can produce incorrect information with confidence, repeat unfair patterns found in training data, or create content that raises legal and ethical concerns. Because of these risks, human oversight, regular monitoring, careful data management, and responsible policies are necessary.

This is a practical path for using generative artificial intelligence successfully. Organizations should begin by identifying meaningful problems rather than adopting the technology just because it is popular. They should build a strong data foundation, choose appropriate models, encourage collaboration among technical and nontechnical workers, and measure results over time. Starting small, learning from experiments, and sharing best practices can help people use these tools wisely. Overall, the main message is that generative artificial intelligence can be powerful, but its value depends on high-quality data, thoughtful design, secure systems, and responsible human judgment.


 Nine Ten Drones has built its reputation on helping organizations unlock the promise of UAVs through training, consulting, and operational deployment. Yet as the industry shifts from experimentation to scaled autonomy, the next frontier is not simply flying drones—it’s making sense of the data they capture in real time. This is where our drone vision analytics, can transform Nine Ten Drones’ mission from enabling flight to enabling intelligence.

Nine Ten Drones is about empowering operators to use UAVs safely and effectively across industries like public safety, infrastructure, and agriculture. A contextual DVSA adds a new dimension: it becomes the bridge between raw aerial footage and actionable insight. By fusing centimeter-level geolocation from networks like GEODNET with semantic video analytics, the DVSA can annotate every frame with meaning. A drone surveying a highway isn’t just recording asphalt—it’s identifying lane markings, traffic density, and potential hazards. A drone flying over farmland isn’t just capturing crops—it detects stress zones, irrigation anomalies, and pest activity. For Nine Ten Drones’ clients, this means training programs and operational workflows can evolve from “how to fly” into “how to interpret and act.”

The synergy with Nine Ten Drones’ consulting practice is particularly powerful. Their teams already advise municipalities, utilities, and enterprises on how to integrate UAVs into daily operations. With a contextual DVSA, those recommendations can be backed by live, annotated datasets. A police department could review drone footage not just for situational awareness but for automated detection of crowd movement patterns. A utility company could receive alerts when vegetation encroaches on power lines, flagged directly in the video stream. The DVSA becomes a trusted assistant, guiding operators toward decisions that are faster, safer, and more defensible.

Training is another area where the DVSA amplifies Nine Ten Drones’ impact. Instead of teaching students to interpret raw imagery, instructors can use the DVSA to demonstrate how analytics enrich the picture. A trainee flying a mission over a construction site could see real-time overlays of equipment usage, safety compliance, or material stockpiles. This accelerates learning curves and prepares operators for data-driven workflows that modern autonomy demands. It also positions Nine Ten Drones as not just a training provider but a gateway to advanced geospatial intelligence.

Operationally, the contextual DVSA enhances resilience. Nine Ten Drones emphasizes safe, repeatable missions, but GNSS signals and coverage can be inconsistent. By combining GEODNET’s decentralized RTK corrections with our analytics, the DVSA can validate positional accuracy against visual cues, flagging anomalies when signals drift. This feedback loop strengthens trust in the data, ensuring that every mission produces results that are both precise and reliable. For industries like emergency response or environmental monitoring, reliability is not optional—it’s mission-critical.

Most importantly, the DVSA aligns with Nine Ten Drones’ philosophy of democratizing UAV adoption. Their vision is to make drones accessible to organizations that may lack deep technical expertise. A contextual DVSA embodies that ethos by lowering the barrier to insight. Operators don’t need to be data scientists to benefit from semantic overlays, predictive alerts, or geospatial indexing. They simply fly their missions, and the DVSA translates video into meaning. This accessibility expands use cases—from small-town public works departments to large-scale agricultural cooperatives—without requiring specialized analytics teams.

Nine Ten Drones equips people to fly drones; our contextual DVSA equips those drones to think. Together, they create an ecosystem where UAVs are not just airborne cameras but intelligent agents of autonomy. The result is a future where every mission—whether for safety, infrastructure, or agriculture—produces not just imagery but insight, not just data but decisions. And that is how Nine Ten Drones, with the help of our analytics, can lead the industry into the autonomy era.


Saturday, July 11, 2026

 Authenticity in the age of artificial intelligence is no longer a simple question of whether something was produced by a person or by a machine. It is becoming a question of agency, transparency, context, and intent. As generative systems increasingly assist with writing, image creation, speech, decision support, and interpersonal communication, the boundary between human expression and machine-mediated expression has become technically and socially ambiguous. A message may originate from a human idea but be refined by an algorithm; an image may depict a real event but be enhanced, compressed, or reconstructed by software; a profile, résumé, or professional statement may be truthful in substance while optimized in tone by an automated assistant. In this environment, authenticity should not be defined solely by the absence of automation. A more useful standard is whether the final artifact remains meaningfully connected to the human judgment, values, and accountability behind it.

From a technical perspective, AI challenges authenticity because it separates surface form from originating effort. Earlier digital tools changed how people edited, distributed, and formatted communication, but they did not usually generate the substance of expression at scale. Contemporary AI systems can produce fluent language, realistic media, and persuasive interaction patterns with minimal prompting. This creates a verification problem: the observable output may no longer reveal the process that produced it. A polished response may reflect careful human thought, automated pattern completion, or a hybrid of both. The same ambiguity applies to images, audio, video, and synthetic personas. As a result, audiences increasingly need process signals rather than relying only on content signals. Metadata, provenance standards, disclosure norms, and audit trails become important not because every automated contribution is deceptive, but because trust depends on understanding the relationship between representation and reality.

The professional risk is not that AI assistance exists, but that it can obscure responsibility. In business, education, research, design, and public communication, authenticity has traditionally carried an assumption of accountable authorship. Readers, customers, colleagues, and institutions evaluate not only what is said, but who stands behind it and how it was produced. When AI-generated or AI-shaped content is presented without appropriate context, accountability can become diffuse. A leader may appear more empathetic than their actual engagement supports. A candidate may seem more articulate than their underlying competence demonstrates. A brand may sound personal while operating through automated segmentation. These examples do not make AI inherently inauthentic; they show that authenticity depends on whether the use of AI amplifies genuine intention or substitutes for it in a way that misleads the audience.

A strong authenticity framework should therefore distinguish between assistance, augmentation, simulation, and deception. Assistance occurs when AI helps improve clarity, accessibility, translation, structure, or recall while the human remains the source of intent and final judgment. Augmentation occurs when AI expands a person’s expressive range, enabling communication that might otherwise be limited by language barriers, cognitive load, disability, time pressure, or lack of specialized production skills. Simulation occurs when AI creates the appearance of human presence, personality, expertise, or experience without the corresponding human basis. Deception occurs when that simulation is deliberately or negligently presented as something it is not. These categories are more practical than a binary distinction between human-made and machine-made content, because real workflows increasingly involve mixtures of human and computational contribution.

For organizations, the technical challenge is to design systems that preserve human agency rather than merely optimize engagement. Many AI tools are tuned to produce outputs that attract attention, increase response rates, or conform to statistically successful patterns. Those goals can be useful, but they can also flatten individuality and encourage formulaic communication. When optimization becomes the dominant design objective, authenticity erodes because people begin to communicate in the style most likely to perform well rather than in the style that best reflects their actual judgment. Responsible implementation requires explicit choices about when optimization is appropriate, when disclosure is necessary, and when human review is mandatory. It also requires recognizing that measurable engagement is not the same as trust, understanding, or meaningful connection.

Authenticity in 2025 should be treated as a socio-technical property rather than a nostalgic preference for unassisted creation. It emerges when people understand the role of AI in a communication, when the output remains aligned with the human values and decisions behind it, and when accountability is not hidden behind automation. The most credible future is not one in which AI is excluded from expression, but one in which AI is used with disciplined transparency and human control. A technically mature definition of being real must account for hybrid authorship while still protecting trust. In practice, this means that the question is not simply whether AI was used. The better question is whether the human remained meaningfully present in the choices, commitments, and consequences carried by the final work.


Friday, July 10, 2026

 Anomaly detection for drone video sensing analytics:

Effective systems combine fast, robust low‑level motion extraction with mid‑ and high‑level learning that models normal scene dynamics and interactions, and they must address the unique challenges introduced by an aerial, moving platform. Drones change the problem in three fundamental ways: the camera is not fixed, objects are often small and seen from oblique angles, and scene appearance changes rapidly with altitude, speed, and viewpoint. These constraints make many techniques developed for static surveillance cameras less effective out of the box and force a hybrid approach that leverages both classical computer vision for real‑time proposals and modern learning methods for semantic anomaly scoring. 


At the lowest level, background subtraction and motion‑based proposals remain valuable because they are computationally inexpensive and provide immediate cues about moving regions. Algorithms such as Gaussian mixture models (MOG variants), pixel‑history methods, and sample‑based background models are useful for generating candidate foreground masks and motion blobs that downstream modules can analyze. Their principal weakness in UAV video is sensitivity to ego‑motion and parallax; without compensation they produce many false positives as the background itself moves relative to the sensor. Because of that, practical pipelines almost always include a stabilization or motion‑compensation stage before applying background models. 


Motion compensation can be as simple as global frame registration using feature matches and homography estimation for near‑planar scenes, or as involved as dense optical flow‑based warping when parallax and depth variation are significant. Once motion proposals are available, they serve two roles: they reduce the search space for heavier models and they provide short‑term motion cues for tracking and association. Tracking and multi‑object association are important because many anomalies are defined by trajectories and interactions rather than by single‑frame appearance: sudden dispersal, counter‑flow in a crowd, loitering, or an object entering a restricted area are temporal phenomena that require consistent identity or motion history. For crowd behavior and multi‑agent anomalies, trajectory‑centric models are the dominant paradigm. Recurrent architectures, social pooling mechanisms, graph neural networks, and attention‑based transformers have all been applied to model interactions among agents and to learn typical motion patterns. These models can detect deviations such as abrupt changes in velocity, unusual relative positions, or coordinated motion that differs from learned norms. The aerial viewpoint complicates trajectory extraction because detections are smaller and occlusions differ from ground cameras, so robust detection and tracklet stitching are prerequisites for reliable interaction modeling. 


At a higher semantic level, unsupervised and self‑supervised deep learning methods are now the state of the art for anomaly scoring when the goal is to detect semantic deviations rather than simply motion. Autoencoders, variational autoencoders, predictive networks that forecast future frames or features, and spatio‑temporal encoders (including 3D CNNs and transformer variants) are used to learn a model of “normal” scene dynamics; anomalies are then flagged by reconstruction or prediction error, or by low likelihood under a learned latent distribution. These approaches are powerful because they can capture complex appearance and motion patterns, but they require representative normal data and careful domain adaptation for aerial contexts. In practice, teams combine fast foreground/motion proposals with a lightweight deep model that scores candidate regions or short clips; this hybrid reduces compute and improves precision by focusing learning‑based scoring on the most relevant pixels. Data considerations are central to any deployment. Because anomalies are rare and varied, the most reliable approach is to collect a substantial corpus of normal aerial footage that matches the intended operational envelope (altitudes, speeds, camera gimbals, lighting, seasons). Synthetic augmentation and simulation can help cover rare events and viewpoint variations, and transfer learning from larger ground‑camera datasets can provide useful priors, but domain shift must be explicitly addressed through fine‑tuning, adversarial domain adaptation, or self‑supervised pretraining on unlabeled aerial video. 


Evaluation should be multi‑faceted: frame‑level and pixel‑level metrics (AUC, precision/recall) are useful for measuring detection quality, while event‑level metrics that consider temporal continuity and false alarm rates per hour are more meaningful for operational use. The most common failure modes are false positives caused by ego‑motion and dynamic backgrounds, and false negatives caused by small object size or occlusion. Mitigations include better motion compensation, multi‑scale detection, temporal aggregation of scores, and conservative post‑processing that fuses motion, appearance, and track consistency. 


From an engineering perspective, a recommended pipeline for adding custom models to a drone video sensing analytics repository is sequential: first stabilize or compensate for camera motion; second, run a fast background subtraction or motion saliency stage to produce candidate regions; third, perform detection and short‑term tracking to produce tracklets and trajectories; fourth, apply a learned anomaly scorer that operates on either the candidate region, the tracklet history, or a short clip; and finally fuse scores across modalities and time to produce robust alerts. Lightweight autoencoders or small spatio‑temporal transformers are good starting points for the learned scorer because they balance expressivity and deployability on edge hardware. Operational constraints—compute, latency, and bandwidth—often dictate that heavy models run offboard while simpler motion‑based filters run on the drone. 


There are practical tradeoffs: classical methods are fast and interpretable but brittle under camera motion; deep methods are expressive but data‑hungry and sensitive to domain shift. Combining them yields the best practical performance for UAV analytics. 


Finally, code samples to help implement the hybrid approach is in the references. This includes a short OpenCV example showing MOG2 background subtraction for motion proposals, a minimal PyTorch autoencoder inference pattern where reconstruction error becomes an anomaly score, and a sketch of motion compensation using optical flow to warp frames before background modeling. These sketches are intended as starting points for integration and experimentation rather than production‑ready modules; they demonstrate how to connect fast foreground extraction to a learned anomaly scorer and how to incorporate motion compensation to reduce false alarms. 


Together, these findings form a coherent, implementable strategy for anomaly detection in drone video sensing analytics: stabilize and propose with classical vision, model semantics and interactions with learning, collect representative normal data, and evaluate with both frame‑level and event‑level metrics while explicitly addressing domain shift and operational constraints.  


References: 

1. https://github.com/ravibeta/dvsa-api

2. Previous articles 

3. Sample 1: OpenCV MOG2 background subtraction (motion proposals)

import cv2

cap = cv2.VideoCapture('uav_video.mp4')

bg = cv2.createBackgroundSubtractorMOG2(history=500, varThreshold=16, detectShadows=True)

while True:

    ret, frame = cap.read()

    if not ret: break

    fg = bg.apply(frame)

    _, fg = cv2.threshold(fg, 200, 255, cv2.THRESH_BINARY)

    # optional morphological cleanup

    print(fg.sum()) # simple motion cue

4. Sample 2: Simple PyTorch convolutional autoencoder for frame anomaly scoring

# encoder/decoder omitted for brevity; train on normal frames

# inference: reconstruction error -> anomaly score 

recon = model(frame_tensor)

score = ((frame_tensor - recon)**2).mean().item()

5. Sample 3: Motion compensation sketch using optical flow for background subtraction

# compute flow between frames, warp previous background model, then apply MOG2

flow = cv2.calcOpticalFlowFarneback(prev_gray, gray, None, 0.5,3,15,3,5,1.2,0)

# warp prev frame by flow (implementation detail) then update bg model



Thursday, July 9, 2026

 Authenticity in the age of artificial intelligence is no longer a simple question of whether something was produced by a person or by a machine. It is becoming a question of agency, transparency, context, and intent. As generative systems increasingly assist with writing, image creation, speech, decision support, and interpersonal communication, the boundary between human expression and machine-mediated expression has become technically and socially ambiguous. A message may originate from a human idea but be refined by an algorithm; an image may depict a real event but be enhanced, compressed, or reconstructed by software; a profile, résumé, or professional statement may be truthful in substance while optimized in tone by an automated assistant. In this environment, authenticity should not be defined solely by the absence of automation. A more useful standard is whether the final artifact remains meaningfully connected to the human judgment, values, and accountability behind it.

From a technical perspective, AI challenges authenticity because it separates surface form from originating effort. Earlier digital tools changed how people edited, distributed, and formatted communication, but they did not usually generate the substance of expression at scale. Contemporary AI systems can produce fluent language, realistic media, and persuasive interaction patterns with minimal prompting. This creates a verification problem: the observable output may no longer reveal the process that produced it. A polished response may reflect careful human thought, automated pattern completion, or a hybrid of both. The same ambiguity applies to images, audio, video, and synthetic personas. As a result, audiences increasingly need process signals rather than relying only on content signals. Metadata, provenance standards, disclosure norms, and audit trails become important not because every automated contribution is deceptive, but because trust depends on understanding the relationship between representation and reality.

The professional risk is not that AI assistance exists, but that it can obscure responsibility. In business, education, research, design, and public communication, authenticity has traditionally carried an assumption of accountable authorship. Readers, customers, colleagues, and institutions evaluate not only what is said, but who stands behind it and how it was produced. When AI-generated or AI-shaped content is presented without appropriate context, accountability can become diffuse. A leader may appear more empathetic than their actual engagement supports. A candidate may seem more articulate than their underlying competence demonstrates. A brand may sound personal while operating through automated segmentation. These examples do not make AI inherently inauthentic; they show that authenticity depends on whether the use of AI amplifies genuine intention or substitutes for it in a way that misleads the audience.

A strong authenticity framework should therefore distinguish between assistance, augmentation, simulation, and deception. Assistance occurs when AI helps improve clarity, accessibility, translation, structure, or recall while the human remains the source of intent and final judgment. Augmentation occurs when AI expands a person’s expressive range, enabling communication that might otherwise be limited by language barriers, cognitive load, disability, time pressure, or lack of specialized production skills. Simulation occurs when AI creates the appearance of human presence, personality, expertise, or experience without the corresponding human basis. Deception occurs when that simulation is deliberately or negligently presented as something it is not. These categories are more practical than a binary distinction between human-made and machine-made content, because real workflows increasingly involve mixtures of human and computational contribution.

For organizations, the technical challenge is to design systems that preserve human agency rather than merely optimize engagement. Many AI tools are tuned to produce outputs that attract attention, increase response rates, or conform to statistically successful patterns. Those goals can be useful, but they can also flatten individuality and encourage formulaic communication. When optimization becomes the dominant design objective, authenticity erodes because people begin to communicate in the style most likely to perform well rather than in the style that best reflects their actual judgment. Responsible implementation requires explicit choices about when optimization is appropriate, when disclosure is necessary, and when human review is mandatory. It also requires recognizing that measurable engagement is not the same as trust, understanding, or meaningful connection.

Authenticity in 2025 should be treated as a socio-technical property rather than a nostalgic preference for unassisted creation. It emerges when people understand the role of AI in a communication, when the output remains aligned with the human values and decisions behind it, and when accountability is not hidden behind automation. The most credible future is not one in which AI is excluded from expression, but one in which AI is used with disciplined transparency and human control. A technically mature definition of being real must account for hybrid authorship while still protecting trust. In practice, this means that the question is not simply whether AI was used. The better question is whether the human remained meaningfully present in the choices, commitments, and consequences carried by the final work.

References: 

1. “AI & Authenticity: What Does It Mean to Be ‘Real’ in 2025?” written by Ben Szuhaj at Kungfu.ai in 2025

#codingexercise: CodingExercise-07-09-2026.docx

Wednesday, July 8, 2026

 

DVSA  retention schedule

Retention schedule template (concise, operational): retain each record type only as long as necessary for the stated purpose and to meet legal or contractual obligations; document the legal basis and review date for each entry.

 

Training datasets (raw labeled images used to train models):

purpose—model development and improvement;

retention—retain for up to 3 years unless a shorter business justification applies; controls—hashed identifiers, access limited to ML engineers, versioned snapshots, and deletion workflow that removes source files and associated embeddings.

 

Raw flight video and full-resolution frames:

purpose—safety investigations and mission replay;

retention—retain for 90 days by default; extend to 1–7 years only when required by contract, insurance, or sector rules;

controls—tiered storage, encrypted at rest, and legal‑hold flagging.

 

Promoted catalog records (indexed frames, object metadata, embeddings):

purpose—analytics, search, and copilot responses;

retention—retain 1–5 years depending on reuse value and regulatory needs;

controls—immutable audit log of promotions, ability to redact or unlink personal identifiers, and periodic re‑evaluation.

 

System logs and audit trails (access logs, model versioning, tamper‑evident traces): purpose—security, compliance, and incident response;

retention—retain 1–7 years per enterprise risk policy;

controls—WORM storage, cryptographic integrity checks, and exportable audit packages.

 

Deletion and propagation: when erasure is requested, remove primary records and propagate deletions to indexes, vector stores, backups, and third‑party processors within a documented SLA; provide deletion confirmation and a verifiable deletion receipt.

 

Notes: Retention enforcement is automated, a searchable data inventory is maintained, retention clauses are included in vendor contracts, and all retention and deletion actions are logged for auditability.

 

Userfacing privacy notice (U.S. tailored, plain language):

we collect video, telemetry (GPS, timestamps), derived object metadata, and analytics outputs to provide drone sensing, mapping, and analytics services;

we may use selected data to improve models unless you opt out;

we retain raw flight video for 90 days by default and promoted catalog records for up to 3 years unless law or contract requires otherwise;

you may request access, correction, or deletion of personal data via [support channel], and deletion requests will be executed and propagated within our documented SLA;

we will honor lawful requests and preserve records under legal hold when required by law or litigation.

For enterprise customers we offer contractual controls (DPA, SOC 2, encryption, and notraining options) and will comply with sectoral retention rules (e.g., financial, healthcare) that may require longer retention.

 

Disclosure: Prompts, responses, and logs can be subject to legal preservation in investigations; AI logs are treated as enterprise records and legalhold processes are applied when needed.