Tuesday, November 24, 2026

 DVSA-API should evolve toward a queryable visual evidence system, unlimited by a larger graph of objects mentioned in captions. The bridge to a Kusto-like experience is a semantic query layer in which users express what they want to retrieve, compare, measure, or inspect, while the system decides which combination of video decoding, visual retrieval, graph traversal, geometric computation, and model inference can answer it. In that design, “retrieve the best shot of this bell tower” and “measure the angular sweep of its shadow” are queries over the same underlying evidence, but they require different execution plans and different standards of proof. The graph supplies identity, relationships, dependencies, and provenance; image-processing and geometry operators establish what the imagery supports. This extends, rather than replaces, the continuity-aware architecture.

The earlier discussion was too restrictive if it suggested that knowledge graphs apply exclusively to text. Microsoft’s published LazyGraphRAG implementation and evaluation concern text, but that is a property of that particular method while graphs are not limited by it. Kusto’s graph semantics operate on nodes and edges constructed from tabular data, support property-constrained pattern matching, and return tabular results that can participate in further analysis. A right conceptual move is that a graph represents a domain’s meaningful entities and dependencies, while the query language hides much of the underlying storage organization. For DVSA, the equivalent domain is not “captions connected to captions.” It is the relationship among physical places, visual observations, surfaces, events, measurements, and the computations that connect them.

There is nevertheless an important distinction between the public-cloud analogy and the proposed implementation. Azure Resource Graph provides familiar KQL-style queries over cloud-resource inventory; Kusto’s graph operators provide a broader graph-analysis facility. Neither automatically interprets pixels or establishes a physical relationship simply because a query can express it. What DVSA should borrow is the separation between a stable logical interface and a changing physical execution strategy. A user should not need to know whether a candidate was discovered through a caption, an embedding, a tracked image region, or a reconstructed surface. The system must know, however, because those sources have different evidentiary strength. Source independence should simplify the interface without erasing the distinction between a model’s description and a measured result


Monday, November 23, 2026

Continued from previous post

 

Where vector search is preferred

Vectors are most valuable when the user cannot name the object, the archive was not tagged for the condition, or resemblance itself is the goal.  “Find other roof defects that look like this crop,”  would search region embeddings across flights, deduplicate results from the same roof or pass, and show a shortlist of original crops for review. NVIDIA’s example-image search documents this general workflow: select a box on a paused frame and search for visually similar indexed objects. The benefit is that an analyst can begin with a visual example without first deciding whether the defect is blistering, staining, or membrane separation. The drawback is that a similarity score may reward roof material, lighting, or viewpoint rather than the defect. A full-frame embedding can miss a tiny defect altogether, and a region index that only embeds detector proposals cannot retrieve a defect the detector never proposed. This workflow should use multiscale tiles alongside object crops and verify candidates at native resolution.

Vector retrieval is also a good way to find plausible clips, but it is weaker as the final test of a precise relationship. “Panels beside a skylight” and “panels beneath a skylight in the image” may retrieve the same rooftop footage even though they ask different questions. Research on contrastive VLMs has documented errors in binding attributes to the right object and distinguishing changes in relationships or word order; it has also shown that training on near-miss examples improves those capabilities. That argues for better embeddings, not for treating every embedding model as incapable of relational search. DVSA-API should allow a vector result to say “these are likely matches,” but use a crop, track, or geometry check to establish which object had the attribute or which side of a boundary it occupied. Similarly, the top 20 matches are not a count of all occurrences. An inventory needs a defined survey scope, deduplication, and an accounting of areas that were not observed well enough to judge.

What to precompute and what to leave for the query

The storage-versus-compute intuition is useful, but it is better framed as what to compute once versus what to compute on demand. A vector index already pays up front to encode and store observations. Indexing every tile or every short clip can become expensive, while indexing too sparsely saves storage at the cost of missed evidence. A graph built from an existing asset registry and survey footprints may be cheap. A graph that tries to interpret every clip, resolve identities across flights, and infer every relationship can cost more to build and maintain than the vector index. Conversely, a sparse graph can defer uncertain relationships until a query needs them. Microsoft demonstrates this timing choice for text with LazyGraphRAG, which defers generative interpretation rather than precomputing all summaries; its cost results are not aerial-video estimates.

There is also a direct video study of when to use each route. AdaVideoRAG routes questions among direct VLM inference, simpler retrieval, and graph-enhanced retrieval rather than applying the most elaborate method to every question. In its fixed-routing comparison on VideoMME, adaptive routing scored 68.5, versus 67.5 for always using simple retrieval and 67.1 for always using the graph-enhanced route. That is not an aerial result or a clean test of one database against another. It does show, within a single video system, that forcing the richer route on every query did not improve overall answers. DVSA-API could route by what evidence the answer requires, not by how complicated the wording sounds. “Is that tag legible?” might need one crop. “Is it the same cabinet as last month?” might need two flights and a verified asset link.

We could have three evidence paths in DVSA-API: inspect a known view directly, use vectors to discover candidate evidence, and use specific relationships to join or constrain evidence. Give them shared IDs for source frames, clips, crops, tracks, and places so one path can hand off to another. A known asset could start with the registry and retrieve the views. An unfamiliar appearance could start with vectors and attach confirmed matches to the relevant places or assets. If the evidence is too coarse, fetch a better crop or another recorded view; if no adequate view exists, say what is missing. DVSA-API need not control the aircraft to tell an operator whether the next useful observation is already in the archive or still needs to be captured.

Sunday, November 22, 2026

 Graph search versus vector search for drone vision

DVSA-API could benefit with a distinction: vector search finds observations that resemble a request; graph search connects observations that jointly satisfy it. “Find footage that looks like this patch of eroded riverbank” is a discovery problem. “Show the same riverbank segment before and after the storm, from views that cover the affected area” is a problem of place identity, time, and coverage. Neither search method, by itself, verifies what the pixels show. That is a separate job for a detector, a VLM inspecting the original imagery, a geometric measurement, or a reviewer.

The two systems from the earlier essay make this distinction clear. V* (SEAL) does not query an external knowledge graph. When its initial view is inconclusive, the model uses learned world knowledge and image context to suggest where a target might be, turns that cue into a heatmap, and uses it to prioritize finer crops. The search operates on subdivisions of the image, not on stored facts about the world. Its published search is designed to find a target, not exhaustively enumerate every instance. NVIDIA’s VSS 3.3 Search workflow, meanwhile, does not use vector lookup as a substitute for detection. It indexes video/action embeddings separately from object-level embeddings produced through its computer-vision and behavior-analysis pipeline. At query time, it routes among event, attribute, combined, and example-image search; a VLM critic checks retrieved clips. NVIDIA also documents graph and vector retrieval for caption-based Q&A elsewhere in the blueprint. These are ways of choosing and connecting evidence not two mutually exclusive systems.

Where a graph is merited

An external knowledge graph can improve where to look when it contains site-specific facts that are better than generic visual priors or have connections and relationships that are determined before the search. Fact-based Visual Question Answering offers a documented precedent: it detects concepts in an image, links them to an external knowledge base, and retrieves a supporting fact. A follow-on study, Straight to the Facts, uses learned embeddings to rank those facts rather than relying entirely on an exact query. This is an early example of a graph defining the available facts while vectors help find the right one. DVSA-API could consider “Read the asset tag on the controller cabinet for Pump 4” in this way. A site registry can connect Pump 4 to its cabinet and the cabinet’s mapped position to archived views. A SEAL-style crop search can then inspect the best views, and OCR can return the tag with the source crop. The registry tells the system which cabinet to inspect; it does not tell the system what the camera actually captured. If the registry is stale or the cabinet is not where expected, the graph should prioritize those views, not rule out the rest.

A graph built from observations solves a different problem: it can preserve a relationship across frames and cameras instead of inferring it again from every new view. ConceptGraphs shows how to associate regions across posed RGB-D images, fuse multiple views into 3D object nodes, and attach both visual embeddings and specific relationships. Its demonstration is a robotics workflow, not a validated aerial pipeline; transferring it requires reliable aerial registration and object association. An aerial version could answer, “Which roofs had panels inside the surveyed boundary on both passes?” The system would join observations to persistent roof IDs, test containment in map coordinates, then retrieve dated evidence for each match. That is more defensible than asking a VLM whether a panel is “inside” based on an oblique frame. But the graph can also make a bad assumption durable: merge two similar roofs, and every downstream count or comparison inherits the mistake. Measured relations such as distance, direction, or containment could be computed from geometry and record the coordinate frame and uncertainty. Model-inferred relation could be labeled differently from a measured one.

Time and coverage make the strongest case for defined structure. MIT’s Khronos demonstrates why revisits matter: a robot observes a cooler appear and later disappear as it reobserves the same place. Spatialyze demonstrates a complementary database pattern: use camera and map metadata to skip footage that cannot satisfy a geographic predicate before running more expensive perception. Neither requires that all relationships be extracted by a VLM or stored in a dedicated graph database. “Was the drainage grate cleared between the two surveys?”, DVSA-API should first establish that the same grate was visible in both passes, at sufficient resolution and without material occlusion. Only then should it compare the views. Typed links such as same asset, observed during, and covered by are more useful than another similarity score. The trade-off is maintenance: placements, IDs, camera poses, and visibility estimates can all change or be corrected, so the links need timestamps and source evidence.


Saturday, November 21, 2026

 

Degla AI and DVSA-API compete most directly over the semantic interpretation of drone imagery: turning an operator’s question or objective into visual evidence, interpreting that evidence in context, and producing a response useful to a mission. Their principal difference is where that response leads. Degla positions its onboard intelligence as part of a continuous mission-decision loop, whereas DVSA-API’s documented query pipeline organizes selected aerial imagery and analytical tools around answering questions. Degla AI brings visual question answering closer to the aircraft’s next observation; DVSA provides an architecture for interrogating the observations already available. This distinction shows there is overlap: both must determine what is visible, what the operator means, which evidence matters, and whether that evidence is sufficient to support a conclusion. Degla relies on the onboard mission interpretation while DVSA-API is a curated-frame grounding and agent-based question-answering workflow

Degla’s software is described as a coordinated reasoning-and-perception stack, not a single model whose internal architecture has been disclosed. That said, it does use an onboard vision-language model to interpret imagery, understand intent, and guide mission planning and adaptation. It’s website separates “LLM reasoning,” which interprets objectives and connects them to decisions and responses, from “VLM perception,” which interprets camera scenes in the mission’s context, and from detection and tracking. These descriptions are compatible with several implementations: a shared multimodal model serving multiple roles, a VLM coupled to a separate language-model planner, or an orchestrated collection of models and tools.

Consider the instruction, “Find the missing hiker wearing a red sweater.” This is language grounding: connecting a linguistic description to a particular visual candidate. The instruction supplies a conjunction of conditions—human subject, relevant clothing attribute, and a mission-specific identity hypothesis. A useful response must separate what the image supports from what the mission presumes. “A person wearing red is visible beside the trail” is an observational claim; “the missing hiker has been found” adds an identity conclusion that red clothing alone cannot establish. This makes no claim on precision or recall.

The query-response process could be a conditional multimodal inference: the response depends on the instruction, the visual observations, and whatever mission state or history the application supplies. Degla’s website specifically describes separate reasoning, perception, and tracking functions; a model-generated description need not itself perform localization or maintain identity across frames.

The connection to flight planning indicators imply possibility for a match. The next observation can then confirm, weaken, or reject the hypothesis. This is active perception: selecting observations to reduce uncertainty about a task. Within the scope of VLM analytics, Degla AI drone make progress towards goal by maximizing matches as new information emerges and with continued observation of people and vehicles. There is no reference to information-gain optimization or model generated subgoals or refinement of queries with human intervention during flight.

Temporal understanding is equally consequential. An aircraft changes viewpoint while the subject may also move, so successive images do not offer interchangeable evidence. A useful analytical system must distinguish a newly observed person from a previously considered candidate, preserve the basis for earlier conclusions, and recognize when a changing viewpoint resolves an ambiguity. Degla advertises detection, tracking, and maintaining visual contact, but its materials do not establish that these functions reside inside the VLM itself.  This could mean that mission reasoning consumes both visual interpretations and persistent tracking outputs, with the precise division of responsibility undisclosed. This prevents an exaggerated comparison in which a VLM is credited with all the capabilities of the surrounding autonomy software.

Degla’s reported fine-tuning on expert pilots’ decisions is especially relevant to the quality of these query-response transitions. If the training examples associate observations and mission context with expert judgments, the model can potentially learn not only what an image contains but which interpretation matters next: continue searching, inspect an ambiguous candidate, or maintain observation of a likely match. That would make the learned behavior more task-specific than generic image captioning.

Running inference locally changes the deployment characteristics of that analytical loop. Degla states that its reasoning, perception, and mission execution remain onboard, including offline missions; its launch announcement specifically says mission decisions do not depend on cloud inference.

DVSA-API approaches the same semantic problem from a different software boundary. Its extraction workflow persists curated ImageEntity frames, and its chat path grounds responses through curated_frame_urls. Questions are handled by a three-agent arrangement involving knowledge search, a connected function agent, and a computer-vision tool agent within a shared time budget. Multiple Qwen execution options, including local alternatives. Accordingly, the comparison should not be simplified to “Degla is local, DVSA is cloud.” DVSA’s documented distinction is its API-mediated, curated-evidence workflow and tool composition; Degla’s is an onboard workflow specifically coupled to mission adaptation. DVSA could reprocess curated frames in full on each query and identifies motion-aware change detection and spatiotemporal enrichment  but they are not completed capabilities.

Degla’s VLM proposition is compelling because it changes the purpose of a visual answer: the answer helps determine what evidence to gather next. DVSA-API’s opportunity is to make that decision-support process declared, inspectable, and accessible through an analytical interface. Degla competes with DVSA at the boundary between semantic interpretation and mission-directed questioning, while DVSA can differentiate through evidence-centered query orchestration.

References: previous article: https://1drv.ms/w/c/d609fb70e39b65c8/IQDY7oMfVzQgQYxyQK8fwYu3AVZBtGKteJnZNmS49fUFcEQ?e=uetVbZ

Friday, November 20, 2026

 When should a system stop answering from the evidence it has and go get better evidence? Degla and DVSA-API are two answers to it. Degla's onboard model gets better evidence by changing what the aircraft looks at next. DVSA-API's curated-frame, multi-agent pipeline organizes the evidence already captured so it can answer questions about it. The six workflows below are publicly available cases on what the loop does.

The first pattern is iterative evidence gathering over a long video, and VideoAgent from Stanford, published at ECCV 2024, documents it clearly. The system doesn't caption every frame and then answer. A language model acts as the central agent. It looks at a handful of evenly spaced frames, drafts an answer, and judges whether it is confident. If it isn't, it states what information is missing. A vision-language retrieval model then fetches the frames most likely to contain that information. Those frames are captioned and added to what the agent knows, and the loop repeats until the agent is confident or runs out of budget. The authors report competitive accuracy on long-video question answering while using only about eight frames per question on average. Selective sampling is a property of the reasoning loop instead of a fixed sampling rate. For DVSA-API, this could mean a VideoAgent-style loop would start with a small set of frames and pull in more only when the agent's confidence is low.

The second pattern is guided search inside a single high-resolution image, documented by V* (SEAL). The problem it targets is that a multimodal model shrinks a large image down to its input size, so small objects vanish. In V*, when the model can't answer because the needed detail isn't visible, it names the objects it needs to find. A search model then uses the model's world knowledge as a guide. For example, if it is looking for a small sign, it checks near roads and storefronts before open sky. It works through regions of the full-resolution image, and the crops it finds are kept in a visual working memory used to produce the final answer. The model asks itself where something like this would plausibly be and zooms there. This matters for aerial imagery, because the objects in bounding-box and color queries are often a few dozen pixels in a large frame. The workflow is a digital version of Degla's "take another look"

The third pattern is turning a query into a distinct program, documented by ViperGPT from Columbia. Here the language model doesn't answer the question. It writes a short Python program that calls a fixed set of vision functions, such as finding objects, checking a property of an image patch, comparing positions, or answering a simple visual question. The program then runs, and its output is the answer. A question like "how many cars are parked to the left of the building with the circular roof" becomes a few readable steps: find the building, find the cars, filter by position, count. What this offers a product is inspection. When an answer is wrong, you can see whether the plan or a particular perception step failed, and the steps can be reused across many images. For DVSA-API, this is a design for the computer-vision tool agent. It would make counting, spatial-relation, and multi-step questions auditable, rather than leaving them inside one opaque VLM call.

The fourth pattern is the continuous video-analytics agent, documented by NVIDIA's Video Search and Summarization (VSS) Blueprint. NVIDIA describes it as a reference architecture for video analytics agents that combines VLMs, LLMs and retrieval-augmented generation to deliver verified real-time alerts, visual question answering and automated reports. In plain language, the workflow has two speeds. As video comes in, it is cut into chunks, a VLM writes dense descriptions of each chunk, and those descriptions are stored in a searchable form. Later questions and summaries draw on that store instead of re-watching the video. Meanwhile, standing conditions such as "alert me if X happens" are checked as the video arrives, and a candidate alert is confirmed before it is raised. The business value is that one ingestion pass serves several products: search, Q&A, alerting, and reporting. DVSA-API already has ingestion and Q&A. What this pattern adds is standing queries: an operator registers a question once, and every new flight is checked against it, which reuses your existing evidence instead of repeating questions per flight.

The fifth pattern is fleet-wide content search to mine rare events, documented by Waymo's Content Search. Waymo describes indexing its driving logs so engineers can search what amounted to billions of observed objects from about 20 million miles of driving. It supports searching by similarity to an example as well as by text or category. The stated purpose is to find training data for rare situations quickly and turn data mining into a search problem. The workflow runs across videos rather than within one. An engineer notices a weakness, searches the whole fleet's history for similar cases, gathers them, and uses them to retrain models, so what one vehicle encounters improves the whole fleet. For a business, the archive becomes a training asset instead of a storage cost. For DVSA-API, this suggests a cross-flight query mode, such as "show me every flight where something like this frame appears." Its results would feed evaluation sets and fine-tuning, much as Degla turns expert decisions into training data.

The sixth pattern is natural-language investigation across many fixed cameras, documented by Verkada's AI-powered search. Users of its Command platform can type free-text descriptions such as "person holding a mop" or "white Tesla model Y with tinted windows." Search is no longer limited to a fixed menu of person and vehicle attributes, and results come from people and vehicle detections across the organization's cameras. Two parts of the documented workflow are worth noting beyond the search itself. First, it only searches over people and vehicle detections the system has already indexed; the guide says results won't appear if those analytics are disabled. Second, it pairs the search with guidance on how to phrase queries, stated limitations, query moderation and role-based permissions. A broad description narrows a large camera fleet to a short list of candidates for a person to review, inside a governed workflow. This is a suggestion for DVSA-API to index entities first, let language query those entities, and publish what the system can't reliably answer and who is allowed to ask

Each pattern answers the opening question differently:

• VideoAgent: gathers more frames from the same video.

• V*: looks closer at pixels already captured.

• ViperGPT: breaks the question into explicit, checkable steps.

• NVIDIA VSS: does the expensive interpretation once at ingestion and keeps watching with standing queries.

• Waymo: widens the search to the whole fleet's history.

• Verkada: narrows a fleet to candidates and hands the final judgment to a person under governance.

The thread connecting them is the one the earlier essay ended on: a good system knows when its answer isn't good enough and can state the next useful question to ask of the evidence.


Thursday, November 19, 2026

 Degla AI and DVSA-API compete most directly over the semantic interpretation of drone imagery: turning an operator’s question or objective into visual evidence, interpreting that evidence in context, and producing a response useful to a mission. Their principal difference is where that response leads. Degla positions its onboard intelligence as part of a continuous mission-decision loop, whereas DVSA-API’s documented query pipeline organizes selected aerial imagery and analytical tools around answering questions. Degla AI brings visual question answering closer to the aircraft’s next observation; DVSA provides an architecture for interrogating the observations already available. This distinction shows there is overlap: both must determine what is visible, what the operator means, which evidence matters, and whether that evidence is sufficient to support a conclusion. Degla relies on the onboard mission interpretation while DVSA-API is a curated-frame grounding and agent-based question-answering workflow

Degla’s software is described as a coordinated reasoning-and-perception stack, not a single model whose internal architecture has been disclosed. That said, it does use an onboard vision-language model to interpret imagery, understand intent, and guide mission planning and adaptation. It’s website separates “LLM reasoning,” which interprets objectives and connects them to decisions and responses, from “VLM perception,” which interprets camera scenes in the mission’s context, and from detection and tracking. These descriptions are compatible with several implementations: a shared multimodal model serving multiple roles, a VLM coupled to a separate language-model planner, or an orchestrated collection of models and tools. 

Consider the instruction, “Find the missing hiker wearing a red sweater.” This is language grounding: connecting a linguistic description to a particular visual candidate. The instruction supplies a conjunction of conditions—human subject, relevant clothing attribute, and a mission-specific identity hypothesis. A useful response must separate what the image supports from what the mission presumes. “A person wearing red is visible beside the trail” is an observational claim; “the missing hiker has been found” adds an identity conclusion that red clothing alone cannot establish. This makes no claim on precision or recall.

The query-response process could be a conditional multimodal inference: the response depends on the instruction, the visual observations, and whatever mission state or history the application supplies. Degla’s website specifically describes separate reasoning, perception, and tracking functions; a model-generated description need not itself perform localization or maintain identity across frames.

The connection to flight planning indicators imply possibility for a match. The next observation can then confirm, weaken, or reject the hypothesis. This is active perception: selecting observations to reduce uncertainty about a task. Within the scope of VLM analytics, Degla AI drone make progress towards goal by maximizing matches as new information emerges and with continued observation of people and vehicles. There is no reference to information-gain optimization or model generated subgoals or refinement of queries with human intervention during flight.

Temporal understanding is equally consequential. An aircraft changes viewpoint while the subject may also move, so successive images do not offer interchangeable evidence. A useful analytical system must distinguish a newly observed person from a previously considered candidate, preserve the basis for earlier conclusions, and recognize when a changing viewpoint resolves an ambiguity. Degla advertises detection, tracking, and maintaining visual contact, but its materials do not establish that these functions reside inside the VLM itself. This could mean that mission reasoning consumes both visual interpretations and persistent tracking outputs, with the precise division of responsibility undisclosed. This prevents an exaggerated comparison in which a VLM is credited with all the capabilities of the surrounding autonomy software.

Degla’s reported fine-tuning on expert pilots’ decisions is especially relevant to the quality of these query-response transitions. If the training examples associate observations and mission context with expert judgments, the model can potentially learn not only what an image contains but which interpretation matters next: continue searching, inspect an ambiguous candidate, or maintain observation of a likely match. That would make the learned behavior more task-specific than generic image captioning. 

Running inference locally changes the deployment characteristics of that analytical loop. Degla states that its reasoning, perception, and mission execution remain onboard, including offline missions; its launch announcement specifically says mission decisions do not depend on cloud inference. 

DVSA-API approaches the same semantic problem from a different software boundary. Its extraction workflow persists curated ImageEntity frames, and its chat path grounds responses through curated_frame_urls. Questions are handled by a three-agent arrangement involving knowledge search, a connected function agent, and a computer-vision tool agent within a shared time budget. Multiple Qwen execution options, including local alternatives. Accordingly, the comparison should not be simplified to “Degla is local, DVSA is cloud.” DVSA’s documented distinction is its API-mediated, curated-evidence workflow and tool composition; Degla’s is an onboard workflow specifically coupled to mission adaptation. DVSA could reprocess curated frames in full on each query and identifies motion-aware change detection and spatiotemporal enrichment but they are not completed capabilities.

Degla’s VLM proposition is compelling because it changes the purpose of a visual answer: the answer helps determine what evidence to gather next. DVSA-API’s opportunity is to make that decision-support process declared, inspectable, and accessible through an analytical interface. Degla competes with DVSA at the boundary between semantic interpretation and mission-directed questioning, while DVSA can differentiate through evidence-centered query orchestration. 



Wednesday, November 18, 2026

 Aerial drone video footage to knowledge.

For initiatives such as DVSA, governance at scale becomes economically viable only when video can be managed as knowledge rather than simply stored as footage. The following sample explains how:

index_to_graph.py reads the frame documents in an Azure AI Search index (schema: core/azure/index_schema.py) and builds a spatio-temporal knowledge graph with networkx.

Node From index field

Account, Video account_id, video_id (or the <account>/images/<video>/ blob path)

Frame id, frame_number (or frame<N> in path), timestamp, caption

Object objects plus description.objects from Azure AI Vision

Concept tags, labels, description.tags

Place location

Cell geotags, snapped to a lat/lon grid (default ~110 m)

index_to_graph.py: 


from __future__ import annotations


import argparse

import json

import math

import os

import re

from collections import Counter, defaultdict

from datetime import datetime, timezone

from itertools import combinations

from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple


import networkx as nx


# Fields to pull from the index. ``vector`` is deliberately left out: the graph

# needs semantics and coordinates, not 1536 floats per frame.

SELECT_FIELDS = [

    "id", "account_id", "video_id", "title", "section", "frame_number",

    "prev_id", "next_id", "path", "imageurl", "created", "timestamp",

    "caption", "description", "labels", "tags", "objects", "annotations",

    "boundingbox", "geotags", "location", "user", "session", "version",

    "acl_users", "acl_groups",

]


# 3 decimal places of lat/lon is roughly a 110 m cell: a sensible "same place"

# for low-altitude drone frames. Raise it for tighter neighbourhoods.

DEFAULT_CELL_PRECISION = 3


# A later frame in the same cell counts as a revisit when it belongs to another

# video, or comes this many seconds (or frames, without timestamps) later.

REVISIT_MIN_GAP = 60


_PATH_RE = re.compile(r"(?:^|/)([^/?]+)/images/([^/?]+)/frame(\d+)\.\w+")

_ID_RE = re.compile(r"-(\d+)$")

_NUM_RE = re.compile(r"-?\d+(?:\.\d+)?")



# --------------------------------------------------------------------------

# 1. Fetch documents from Azure AI Search

# --------------------------------------------------------------------------

def fetch_index_documents(search_client, account_id: Optional[str] = None,

                          video_id: Optional[str] = None,

                          user: Optional[str] = None) -> List[Dict[str, Any]]:

    """Page through every frame document for an account (and optionally a video).


    Uses the same scoping the connected search agent uses in

    ``core/azure/agents.py``: ``account_id eq '<id>'`` plus a ``startswith``

    on the blob path for one video. ``user`` adds an ACL check.

    """

    clauses = []

    if account_id:

        clauses.append(f"account_id eq '{_odata(account_id)}'")

        if video_id:

            clauses.append(

                f"startswith(path, '{_odata(account_id)}/images/{_odata(video_id)}/')"

                f" or video_id eq '{_odata(video_id)}'")

    if user:

        clauses.append(f"acl_users/any(u: u eq '{_odata(user)}')")

    flt = " and ".join(f"({c})" for c in clauses) or None

    results = search_client.search(search_text="*", filter=flt,

                                   select=SELECT_FIELDS, top=100000)

    return [dict(r) for r in results] # the SDK pages transparently



def _odata(value: str) -> str:

    return str(value).replace("'", "''")



def search_client_from_env(index_name: str):

    """A ``SearchClient`` from the same env vars ``AzureEnvironmentConfig`` reads."""

    from azure.core.credentials import AzureKeyCredential # noqa: PLC0415

    from azure.search.documents import SearchClient # noqa: PLC0415


    return SearchClient(endpoint=os.environ["AZURE_SEARCH_ENDPOINT"],

                        index_name=index_name,

                        credential=AzureKeyCredential(os.environ["AZURE_SEARCH_ADMIN_KEY"]))



# --------------------------------------------------------------------------

# 2. Normalize one index document into a frame record

# --------------------------------------------------------------------------

def normalize(doc: Dict[str, Any]) -> Dict[str, Any]:

    """Flatten a raw index document into the fields the graph needs."""

    path = doc.get("path") or doc.get("imageurl") or ""

    m = _PATH_RE.search(path.split("?")[0])

    path_account, path_video, path_frame = (m.groups() if m else (None, None, None))


    # Prefer the blob path's frame<N>: the id is <account>-<N:04d> with no video

    # in it, so it is only a fallback.

    frame_number = doc.get("frame_number")

    if frame_number is None:

        idm = _ID_RE.search(doc.get("id", ""))

        frame_number = int(path_frame) if path_frame else (int(idm.group(1)) if idm else None)


    desc = _parse_json(doc.get("description"))

    caption = doc.get("caption") or desc.get("caption") or ""

    tags = _clean(list(doc.get("tags") or []) + list(desc.get("tags") or []))

    labels = _clean(doc.get("labels") or [])

    objects = _clean(_split_objects(doc.get("objects")) + list(desc.get("objects") or []),

                     keep_dupes=True)


    return {

        "id": doc["id"],

        "account_id": str(doc.get("account_id") or path_account or ""),

        "video_id": str(doc.get("video_id") or path_video or "unknown"),

        "title": doc.get("title") or "",

        "section": doc.get("section") or "",

        "frame_number": frame_number,

        "prev_id": doc.get("prev_id"),

        "next_id": doc.get("next_id"),

        "time": _parse_time(doc.get("timestamp")),

        "created": doc.get("created"),

        "caption": caption,

        "dense_captions": list(desc.get("dense_captions") or []),

        "tags": tags,

        "labels": labels,

        "objects": objects, # duplicates kept = instance counts

        "annotations": doc.get("annotations") or "",

        "boundingbox": doc.get("boundingbox") or "",

        "latlon": _parse_latlon(doc.get("geotags")),

        "location": (doc.get("location") or "").strip(),

        "path": path.split("?")[0], # never store SAS tokens in a graph

        "user": doc.get("user") or "",

        "acl_users": list(doc.get("acl_users") or []),

    }



def _parse_json(text: Any) -> Dict[str, Any]:

    if isinstance(text, dict):

        return text

    try:

        value = json.loads(text) if text else {}

        return value if isinstance(value, dict) else {}

    except (TypeError, ValueError):

        return {}



def _split_objects(value: Any) -> List[str]:

    if not value:

        return []

    if isinstance(value, list):

        return value

    parsed = _parse_json(value) if value.strip().startswith("{") else None

    if parsed:

        return list(parsed.get("objects") or [])

    try:

        as_list = json.loads(value)

        if isinstance(as_list, list):

            return [str(v) for v in as_list]

    except ValueError:

        pass

    return re.split(r"[,;|]", value)



def _clean(items: Iterable[Any], keep_dupes: bool = False) -> List[str]:

    out = [str(i).strip().lower() for i in items if str(i).strip()]

    return out if keep_dupes else sorted(set(out))



def _parse_time(value: Any) -> Optional[float]:

    if not value:

        return None

    if isinstance(value, datetime):

        return value.timestamp()

    try:

        return datetime.fromisoformat(str(value).replace("Z", "+00:00")).timestamp()

    except ValueError:

        return None



def _parse_latlon(value: Any) -> Optional[Tuple[float, float]]:

    """``"('47.6', '-122.1')"``, ``"47.6,-122.1"`` or ``"('', '')"`` -> (lat, lon)."""

    nums = _NUM_RE.findall(str(value or ""))

    if len(nums) < 2:

        return None

    lat, lon = float(nums[0]), float(nums[1])

    return (lat, lon) if -90 <= lat <= 90 and -180 <= lon <= 180 else None



# --------------------------------------------------------------------------

# 3. Build the graph

# --------------------------------------------------------------------------

def cell_id(lat: float, lon: float, precision: int = DEFAULT_CELL_PRECISION) -> str:

    f = 10 ** precision

    return f"cell:{math.floor(lat * f)}_{math.floor(lon * f)}@{precision}"



def build_graph(docs: Sequence[Dict[str, Any]],

                precision: int = DEFAULT_CELL_PRECISION) -> nx.MultiDiGraph:

    """Build the knowledge graph from raw index documents.


    Node kinds: Account, Video, Frame, Object, Concept, Place, Cell.

    Edge relations: HAS_VIDEO, HAS_FRAME, NEXT, CONTAINS, DEPICTS, AT_PLACE,

    IN_CELL, ADJACENT, CO_OCCURS, REVISITS.

    """

    G = nx.MultiDiGraph(precision=precision)

    frames = [normalize(d) for d in docs]

    by_video: Dict[str, List[Dict[str, Any]]] = defaultdict(list)


    for f in frames:

        acc = f"account:{f['account_id']}"

        vid = f"video:{f['account_id']}/{f['video_id']}"

        fid = f"frame:{f['id']}"

        G.add_node(acc, kind="Account", name=f["account_id"])

        G.add_node(vid, kind="Video", name=f["video_id"], title=f["title"])

        G.add_node(fid, kind="Frame", name=f["id"], video=f["video_id"],

                   frame_number=f["frame_number"], time=f["time"], caption=f["caption"],

                   dense_captions=f["dense_captions"], boundingbox=f["boundingbox"],

                   path=f["path"], lat=(f["latlon"] or (None, None))[0],

                   lon=(f["latlon"] or (None, None))[1], acl_users=f["acl_users"])

        _edge(G, acc, vid, "HAS_VIDEO")

        _edge(G, vid, fid, "HAS_FRAME")

        by_video[vid].append(f)


        for name, count in Counter(f["objects"]).items():

            _edge(G, fid, _entity(G, "Object", name), "CONTAINS", count=count)

        for name in set(f["tags"]) | set(f["labels"]):

            src = "label" if name in f["labels"] else "tag"

            _edge(G, fid, _entity(G, "Concept", name), "DEPICTS", source=src)

        if f["location"]:

            _edge(G, fid, _entity(G, "Place", f["location"]), "AT_PLACE")

        if f["latlon"]:

            cid = cell_id(*f["latlon"], precision)

            G.add_node(cid, kind="Cell", name=cid, lat=f["latlon"][0], lon=f["latlon"][1])

            _edge(G, fid, cid, "IN_CELL")


        for a, b in combinations(sorted(set(f["objects"])), 2):

            _bump(G, _entity(G, "Object", a), _entity(G, "Object", b), "CO_OCCURS")


    _link_sequences(G, by_video)

    _link_adjacent_cells(G, precision)

    _link_revisits(G)

    return G



def _entity(G: nx.MultiDiGraph, kind: str, name: str) -> str:

    node = f"{kind.lower()}:{name}"

    if node not in G:

        G.add_node(node, kind=kind, name=name)

    return node



def _edge(G: nx.MultiDiGraph, u: str, v: str, rel: str, **attrs: Any) -> None:

    G.add_edge(u, v, key=rel, rel=rel, **attrs)



def _bump(G: nx.MultiDiGraph, u: str, v: str, rel: str) -> None:

    if G.has_edge(u, v, key=rel):

        G[u][v][rel]["weight"] += 1

    else:

        _edge(G, u, v, rel, weight=1)



def _order_key(f: Dict[str, Any]) -> Tuple[float, float]:

    return (f["time"] if f["time"] is not None else math.inf,

            f["frame_number"] if f["frame_number"] is not None else math.inf)



def _link_sequences(G: nx.MultiDiGraph, by_video: Dict[str, List[Dict[str, Any]]]) -> None:

    """NEXT edges: stored ``next_id`` when present, else frame/time order."""

    for frames in by_video.values():

        ids = {f["id"] for f in frames}

        ordered = sorted(frames, key=_order_key)

        for i, f in enumerate(ordered):

            nxt = f["next_id"] if f["next_id"] in ids else (

                ordered[i + 1]["id"] if i + 1 < len(ordered) else None)

            if nxt:

                g = next(x for x in frames if x["id"] == nxt)

                gap = (g["time"] - f["time"]) if None not in (f["time"], g["time"]) else None

                _edge(G, f"frame:{f['id']}", f"frame:{nxt}", "NEXT",

                      seconds=gap, frames=(g["frame_number"] or 0) - (f["frame_number"] or 0))



def _link_adjacent_cells(G: nx.MultiDiGraph, precision: int) -> None:

    cells = {n for n, k in G.nodes(data="kind") if k == "Cell"}

    for c in cells:

        lat_i, lon_i = map(int, c[5:].split("@")[0].split("_"))

        for dlat in (-1, 0, 1):

            for dlon in (-1, 0, 1):

                other = f"cell:{lat_i + dlat}_{lon_i + dlon}@{precision}"

                if other != c and other in cells:

                    _edge(G, c, other, "ADJACENT")



def _link_revisits(G: nx.MultiDiGraph) -> None:

    """REVISITS: a later frame of the same cell, from another flight or after a gap."""

    for cell in [n for n, k in G.nodes(data="kind") if k == "Cell"]:

        visits = sorted((G.nodes[u] for u, _, r in G.in_edges(cell, keys=True) if r == "IN_CELL"),

                        key=lambda n: (n["time"] if n["time"] is not None else math.inf,

                                       n["frame_number"] or 0))

        for first, later in zip(visits, visits[1:]):

            other_flight = first["video"] != later["video"]

            if first["time"] is not None and later["time"] is not None:

                gap = later["time"] - first["time"]

            else:

                gap = (later["frame_number"] or 0) - (first["frame_number"] or 0)

            if other_flight or gap >= REVISIT_MIN_GAP:

                unit = "s" if first["time"] is not None and later["time"] is not None else "frames"

                _edge(G, f"frame:{later['name']}", f"frame:{first['name']}", "REVISITS",

                      cell=cell, gap=gap, gap_unit=unit, other_flight=other_flight)



# --------------------------------------------------------------------------

# 4. Graph-explorer style queries

# --------------------------------------------------------------------------

def _frames_with(G: nx.MultiDiGraph, node: str, rel: str) -> List[str]:

    return [u for u, _, r in G.in_edges(node, keys=True) if r == rel] if node in G else []



def _sort_frames(G: nx.MultiDiGraph, frames: Iterable[str]) -> List[str]:

    return sorted(frames, key=lambda f: (G.nodes[f]["time"] or math.inf,

                                         G.nodes[f]["video"], G.nodes[f]["frame_number"] or 0))



def object_timeline(G: nx.MultiDiGraph, name: str) -> List[Dict[str, Any]]:

    """Every frame where an object (or a concept, as a fallback) appears, in order."""

    name = name.lower()

    hits = _frames_with(G, f"object:{name}", "CONTAINS") or _frames_with(G, f"concept:{name}", "DEPICTS")

    rows = []

    for f in _sort_frames(G, hits):

        n = G.nodes[f]

        count = G.get_edge_data(f, f"object:{name}", "CONTAINS", {}).get("count", 1)

        rows.append({"frame": n["name"], "video": n["video"], "frame_number": n["frame_number"],

                     "time": n["time"], "lat": n["lat"], "lon": n["lon"], "count": count,

                     "caption": n["caption"]})

    return rows



def frames_near(G: nx.MultiDiGraph, lat: float, lon: float, rings: int = 1,

                start: Optional[float] = None, end: Optional[float] = None) -> List[str]:

    """Frames within ``rings`` cells of a point, optionally inside a time window."""

    p = G.graph["precision"]

    f = 10 ** p

    lat_i, lon_i = math.floor(lat * f), math.floor(lon * f)

    hits = set()

    for dlat in range(-rings, rings + 1):

        for dlon in range(-rings, rings + 1):

            hits.update(_frames_with(G, f"cell:{lat_i + dlat}_{lon_i + dlon}@{p}", "IN_CELL"))


    def in_window(fr: str) -> bool:

        t = G.nodes[fr]["time"]

        return t is None or ((start is None or t >= start) and (end is None or t <= end))

    return _sort_frames(G, (h for h in hits if in_window(h)))



def revisited_places(G: nx.MultiDiGraph, min_visits: int = 2) -> List[Dict[str, Any]]:

    """Cells seen by several frames, with which videos saw them."""

    rows = []

    for c, kind in G.nodes(data="kind"):

        if kind != "Cell":

            continue

        frames = _frames_with(G, c, "IN_CELL")

        if len(frames) >= min_visits:

            rows.append({"cell": c, "lat": G.nodes[c]["lat"], "lon": G.nodes[c]["lon"],

                         "frames": len(frames),

                         "videos": sorted({G.nodes[f]["video"] for f in frames})})

    return sorted(rows, key=lambda r: (-len(r["videos"]), -r["frames"]))



def co_occurring(G: nx.MultiDiGraph, name: str, top: int = 5) -> List[Tuple[str, int]]:

    """Objects most often seen in the same frame as ``name``."""

    node = f"object:{name.lower()}"

    if node not in G:

        return []

    counts: Counter = Counter()

    for u, v, r, d in list(G.out_edges(node, keys=True, data=True)) + \

            list(G.in_edges(node, keys=True, data=True)):

        if r == "CO_OCCURS":

            counts[G.nodes[v if u == node else u]["name"]] += d["weight"]

    return counts.most_common(top)



def spatiotemporal_context(G: nx.MultiDiGraph, frame_ids: Sequence[str],

                           max_lines: int = 40) -> str:

    """Context block for the chat agents, grown from frames search already found.


    For each retrieved frame it adds: what it contains, the frames just before

    and after it, and earlier frames of the same place (revisits). Pass the

    ids the connected search agent returned; prepend the result to the prompt

    alongside the ``[Context: account_id=..., video_id=...]`` line.

    """

    lines: List[str] = []

    for raw in frame_ids:

        f = raw if raw.startswith("frame:") else f"frame:{raw}"

        if f not in G:

            continue

        n = G.nodes[f]

        objs = [f"{G.nodes[v]['name']} x{d.get('count', 1)}"

                for _, v, r, d in G.out_edges(f, keys=True, data=True) if r == "CONTAINS"]

        where = f" at ({n['lat']:.5f}, {n['lon']:.5f})" if n["lat"] is not None else ""

        lines.append(f"Frame {n['name']} (video {n['video']}, #{n['frame_number']}"

                     f"{_when(n)}){where}: {n['caption']}"

                     + (f" | objects: {', '.join(objs)}" if objs else ""))

        before, after, revisits = [], [], []

        for u, v, r, d in list(G.in_edges(f, keys=True, data=True)) + \

                list(G.out_edges(f, keys=True, data=True)):

            if r == "NEXT":

                other = G.nodes[u if v == f else v]

                (before if v == f else after).append(

                    f" {'before' if v == f else 'after'}: #{other['frame_number']}"

                    f"{_when(other)} {other['caption']}")

            elif r == "REVISITS":

                other = G.nodes[v if u == f else u]

                kind = "another flight" if d["other_flight"] else f"{d['gap']:.0f} {d['gap_unit']} apart"

                revisits.append(f" same place, {'earlier' if u == f else 'later'} ({kind}): "

                                f"{other['name']}{_when(other)} {other['caption']}")

        lines.extend(before + after + revisits)

        if len(lines) >= max_lines:

            break

    return "\n".join(lines[:max_lines])



def _when(n: Dict[str, Any]) -> str:

    return (", " + datetime.fromtimestamp(n["time"], timezone.utc).strftime("%Y-%m-%d %H:%M:%SZ")

            if n.get("time") is not None else "")



# --------------------------------------------------------------------------

# 5. Exports for graph explorers

# --------------------------------------------------------------------------

def _flat(attrs: Dict[str, Any]) -> Dict[str, Any]:

    """GraphML/Cypher-safe attributes: drop None, join lists."""

    out = {}

    for k, v in attrs.items():

        if v is None:

            continue

        out[k] = "; ".join(map(str, v)) if isinstance(v, (list, tuple)) else v

    return out



def export_graph(G: nx.MultiDiGraph, out_dir: str) -> Dict[str, str]:

    os.makedirs(out_dir, exist_ok=True)

    flat = nx.MultiDiGraph()

    flat.add_nodes_from((n, _flat(d)) for n, d in G.nodes(data=True))

    flat.add_edges_from((u, v, k, _flat(d)) for u, v, k, d in G.edges(keys=True, data=True))


    paths = {"graphml": os.path.join(out_dir, "dvsa_kg.graphml"),

             "json": os.path.join(out_dir, "dvsa_kg.json"),

             "cypher": os.path.join(out_dir, "dvsa_kg.cypher")}

    nx.write_graphml(flat, paths["graphml"])

    with open(paths["json"], "w", encoding="utf-8") as fh:

        json.dump(nx.node_link_data(flat, edges="edges"), fh, indent=1)

    with open(paths["cypher"], "w", encoding="utf-8") as fh:

        fh.write(to_cypher(flat))

    return paths



def to_cypher(G: nx.MultiDiGraph) -> str:

    """openCypher MERGE script (Neo4j Browser; Apache AGE wraps it in cypher())."""

    def lit(v: Any) -> str:

        if isinstance(v, bool):

            return "true" if v else "false"

        if isinstance(v, (int, float)):

            return repr(v)

        return "'" + str(v).replace("\\", "\\\\").replace("'", "\\'") + "'"


    def props(d: Dict[str, Any]) -> str:

        return ", ".join(f"{k}: {lit(v)}" for k, v in d.items() if k != "kind")


    out = []

    for n, d in G.nodes(data=True):

        out.append(f"MERGE (n:{d['kind']} {{key: {lit(n)}}}) SET n += {{{props(d)}}};")

    for u, v, k, d in G.edges(keys=True, data=True):

        extra = {x: y for x, y in d.items() if x != "rel"}

        out.append(f"MATCH (a {{key: {lit(u)}}}), (b {{key: {lit(v)}}}) "

                   f"MERGE (a)-[r:{k}]->(b)" + (f" SET r += {{{props(extra)}}}" if extra else "") + ";")

    return "\n".join(out) + "\n"



# --------------------------------------------------------------------------

# Demo data shaped exactly like build_document() output

# --------------------------------------------------------------------------

def demo_documents() -> List[Dict[str, Any]]:

    """Two short flights over the same parking lot, as the indexer stores them."""

    base = "https://sadronevideo.blob.core.windows.net/input/2/images/{v}/frame{n}.jpg?sv=redacted"

    shots = [ # video, frame, minute, lat, lon, caption, objects, tags

        ("17", 0, 0, 47.67412, -122.12105, "a parking lot with cars",

         ["car", "car", "tree"], ["parking", "outdoor"]),

        ("17", 30, 1, 47.67431, -122.12088, "cars parked near a building",

         ["car", "building"], ["parking", "building"]),

        ("17", 60, 2, 47.67502, -122.12011, "a truck on a road",

         ["truck", "road"], ["road", "outdoor"]),

        ("17", 90, 3, 47.67588, -122.11940, "an empty field next to trees",

         ["tree"], ["field", "grass"]),

        ("21", 0, 120, 47.67415, -122.12101, "a nearly empty parking lot",

         ["car", "tree"], ["parking", "outdoor"]),

        ("21", 30, 121, 47.67505, -122.12015, "a truck and a person on a road",

         ["truck", "person", "road"], ["road"]),

    ]

    docs = []

    for v, n, minute, lat, lon, cap, objs, tags in shots:

        docs.append({

            "id": f"2-{n:04d}" if v == "17" else f"2-{1000 + n:04d}",

            "account_id": "2",

            "description": json.dumps({"caption": cap, "tags": tags, "objects": objs,

                                       "dense_captions": []}),

            "caption": cap, "labels": [], "tags": [], "objects": "",

            "boundingbox": "0,0,1280,720",

            "geotags": str((str(lat), str(lon))),

            "path": base.format(v=v, n=n),

            "timestamp": f"2026-11-01T10:{minute % 60:02d}:00+00:00" if minute < 60

            else f"2026-11-01T12:{minute % 60:02d}:00+00:00",

            "user": "ravi", "session": "demo",

        })

    return docs



# --------------------------------------------------------------------------

# CLI

# --------------------------------------------------------------------------

def main(argv: Optional[Sequence[str]] = None) -> None:

    p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])

    src = p.add_mutually_exclusive_group(required=True)

    src.add_argument("--demo", action="store_true", help="use built-in sample documents")

    src.add_argument("--from-json", help="JSON file with a list of index documents")

    src.add_argument("--index", help="Azure AI Search index name, e.g. dvsa-index-s-2")

    p.add_argument("--account-id")

    p.add_argument("--video-id")

    p.add_argument("--precision", type=int, default=DEFAULT_CELL_PRECISION)

    p.add_argument("--object", default="car", help="object for the timeline query")

    p.add_argument("--out", default="out/kg")

    a = p.parse_args(argv)


    if a.demo:

        docs = demo_documents()

    elif a.from_json:

        with open(a.from_json, encoding="utf-8") as fh:

            docs = json.load(fh)

    else:

        docs = fetch_index_documents(search_client_from_env(a.index), a.account_id, a.video_id)


    G = build_graph(docs, precision=a.precision)

    kinds = Counter(k for _, k in G.nodes(data="kind"))

    rels = Counter(k for _, _, k in G.edges(keys=True))

    print(f"{len(docs)} documents -> {G.number_of_nodes()} nodes, {G.number_of_edges()} edges")

    print(" nodes:", dict(kinds))

    print(" edges:", dict(rels))


    print(f"\nTimeline of '{a.object}':")

    for r in object_timeline(G, a.object):

        print(f" video {r['video']} #{r['frame_number']} x{r['count']}: {r['caption']}")

    print(f"\nCo-occurs with '{a.object}':", co_occurring(G, a.object))

    print("\nRevisited places:")

    for r in revisited_places(G)[:5]:

        print(f" {r['cell']} seen in {r['frames']} frames by videos {r['videos']}")


    first = object_timeline(G, a.object)

    if first:

        print("\nAgent context for", first[0]["frame"] + ":")

        print(spatiotemporal_context(G, [first[0]["frame"]]))


    print("\nWrote:", export_graph(G, a.out))



if __name__ == "__main__":

    main()