Duplicate from Tetrabot2026/InspecSafe-V1
Browse filesCo-authored-by: tetrabot <tetrabot@users.noreply.huggingface.co>
Files changed (7)
- README.mdAdded+135
- dataset_loader.pyAdded+387
- model_api_generate_results.pyAdded+208
- model_benchmark_evaluation.pyAdded+140
- model_confusion_matrix.pyAdded+138
- test.tar.gzAdded+3
- train.tar.gzAdded+3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135---language:- enlicense: cc-by-4.0tags:- multiple-modality- industrial-scene- custom-datasetsize_categories:- 10G<n<100Gsource_datasets:- original---
# InspecSafe-V1
## Overview
**InspecSafe-V1** is a high-quality, multimodal annotated dataset designed for **world model construction and analysis in industrial environments**. The data was collected from real-world inspection robots deployed across industrial sites and has been carefully cleaned and standardized for research and applications in predictive world modeling for industrial scenarios.
The dataset covers five representative industrial settings: tunnels, power facilities, sintering equipment, oil/gas/chemical plants, and coal conveyor galleries. It was constructed using data from 41 wheeled or rail-mounted inspection robots operating at 2,239 valid inspection waypoints. Across the dataset, multimodal records may include visible-light video, infrared video, audio, depth or LiDAR point clouds, gas concentration readings, temperature, and humidity. Depending on the inspection robot, sensing configuration, and waypoint conditions, each inspection waypoint is associated with the available subset of these modalities rather than necessarily containing all modality types.The available modality types include:
- Visible-light video - Infrared video - Audio - Depth or LiDAR point clouds - Gas concentration readings - Temperature - Humidity
Additionally, pixel-level polygonal segmentation annotations are provided for industrial objects in visible-light images. To support downstream tasks, each sample is also accompanied by a semantic scene description and a corresponding safety-level label based on real inspection protocols.
## Dataset Format
The dataset is divided into a training set and a test set, both of which are organized in a structured directory layout with aligned multimodal streams and annotations. An overview of the data structure is shown below:
```DATA_PATH├── train│ ├── Annotations│ │ ├── Normal_data│ │ │ ├── coal_conveyor-Level04-SuspendedRail-000560│ │ │ │ ├── coal_conveyor-Level04-SuspendedRail-000560-001.jpg│ │ │ │ ├── coal_conveyor-Level04-SuspendedRail-000560-001.json│ │ │ │ └── coal_conveyor-Level04-SuspendedRail-000560-001.txt│ │ │ └── ...│ │ └── Anomaly_data│ │ ├── coal_conveyor-Level01-SuspendedRail-002486│ │ │ ├── coal_conveyor-Level01-SuspendedRail-002486-001.jpg│ │ │ ├── coal_conveyor-Level01-SuspendedRail-002486-001.json│ │ │ └── coal_conveyor-Level01-SuspendedRail-002486-001.txt│ │ └── ...│ ├── Other_modalities│ │ ├── coal_conveyor-Level04-SuspendedRail-000560│ │ │ ├── coal_conveyor-Level04-SuspendedRail-000560-visible.mp4│ │ │ ├── coal_conveyor-Level04-SuspendedRail-000560-infrared.mp4│ │ │ ├── coal_conveyor-Level04-SuspendedRail-000560-sensor.txt│ │ │ ├── coal_conveyor-Level04-SuspendedRail-000560-point_cloud.bag│ │ │ └── coal_conveyor-Level04-SuspendedRail-000560-audio.wav│ │ └── ...│ └── Parameters│ ├── Hardware│ ├── Device_A.json│ ├── Device_B.json│ └── ...└── test ├── Annotations │ ├── Normal_data │ │ ├── coal_conveyor-Level04-SuspendedRail-000001 │ │ │ ├── coal_conveyor-Level04-SuspendedRail-000001-001.jpg │ │ │ ├── coal_conveyor-Level04-SuspendedRail-000001-001.json │ │ │ └── coal_conveyor-Level04-SuspendedRail-000001-001.txt │ │ └── ... │ └── Anomaly_data │ ├── coal_conveyor-Level01-SuspendedRail-002235 │ │ ├── coal_conveyor-Level01-SuspendedRail-002235-001.jpg │ │ ├── coal_conveyor-Level01-SuspendedRail-002235-001.json │ │ └── coal_conveyor-Level01-SuspendedRail-002235-001.txt │ └── ... ├── Other_modalities │ ├── coal_conveyor-Level04-SuspendedRail-000001 │ │ ├── coal_conveyor-Level04-SuspendedRail-000001-visible.mp4 │ │ ├── coal_conveyor-Level04-SuspendedRail-000001-infrared.mp4 │ │ ├── coal_conveyor-Level04-SuspendedRail-000001-sensor.txt │ │ ├── coal_conveyor-Level04-SuspendedRail-000001-point_cloud.bag │ │ └── coal_conveyor-Level04-SuspendedRail-000001-audio.wav │ └── ... └── Parameters ├── Hardware ├── Device_A.json ├── Device_B.json └── ...```
### Notes:- **Inspection point identifier**: Each folder name represents an inspection point, such as `coal_conveyor-Level04-SuspendedRail-000560`. The same identifier is used in both the `Annotations` and `Other_modalities` folders to enable cross-modal correspondence.- **Inspection instances**: A single inspection point may contain multiple inspection instances. In the `Annotations` folder, these instances are distinguished by numerical suffixes appended to the filenames, such as `-001`, `-002`, and `-003`.- **Annotations**: - `.jpg`: Visible-light image frame for the corresponding inspection instance. - `.json`: Pixel-level polygonal segmentation annotations and related metadata. - `.txt`: Human-readable semantic description of the scene.- **Other modalities**: - `.mp4`: Visible-light and infrared videos. - `.txt`: Sensor logs, including gas concentration, temperature, and humidity. - `.bag`: Point-cloud data in ROS bag format. - `.wav`: Audio recordings.- **Parameters**: The `Parameters` folder contains hardware specifications, software settings, and calibration-related files used to support multimodal interpretation and fusion.> This structure ensures synchronized access across all modalities and supports both supervised learning and world modeling tasks. Each sample metadata (e.g., robot ID, location, timestamp, safety label) is stored in JSON format. Segmentation masks are provided as PNG images with instance IDs matching the annotation JSON.
The shared inspection point identifier allows the multimodal and sensory records in `Other_modalities` to be linked to one or more annotated inspection instances in `Annotations`.
## Data Splits
| Split | Number of Samples ||---------|-------------------|| train | 3,763 || test | 1,250 |
> Note: The dataset does not include a separate validation split; users are encouraged to create one from the training set as needed.
## License
This dataset is released under the [CC-BY-4.0 License](https://creativecommons.org/licenses/by/4.0/).
## Acknowledgements
We thank the multimodal recognition algorithm team who contributed to data collection and annotation. This work was supported by TetraBOT.
---
For questions or contributions, please open an issue in the repository.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387"""
Multimodal Robot Anomaly Detection Dataset Loader
Data Path Structure:
DATA_PATH/
├── train/
│ ├── Annotations/
│ │ ├── Normal_data/
│ │ │ └── {point_name}/
│ │ │ ├── {point_name}_visible_{timestamp}_frame_{frame_id}.jpg
│ │ │ ├── {point_name}_visible_{timestamp}_frame_{frame_id}.json
│ │ │ └── {point_name}_visible_{timestamp}_frame_{frame_id}.txt
│ │ └── Anomaly_data/
│ │ └── {anomaly_name}/
│ │ ├── {anomaly_name}.jpg
│ │ ├── {anomaly_name}.json
│ │ └── {anomaly_name}.txt
│ ├── Other_modalities/
│ │ └── {point_name}/
│ │ ├── {point_name}_visible_{timestamp}.mp4
│ │ ├── {point_name}_infrared_{timestamp}.mp4
│ │ ├── {point_name}_sensor_{timestamp}.txt
│ │ ├── {point_name}_point_cloud_{timestamp}.bag
│ │ └── {point_name}_audio_{timestamp}.wav
│ └── Parameters/
│ ├── Hardware/
│ └── Device_*.json
└── test/
└── (same structure as train)
"""
import os
import json
from pathlib import Path
from dataclasses import dataclass, field
from typing import Optional, List, Dict, Any, Tuple, Literal
from enum import Enum
import torch
from torch.utils.data import Dataset
import cv2
import numpy as np
class DataSplit(Enum):
TRAIN = "train"
TEST = "test"
class DataType(Enum):
NORMAL = "Normal_data"
ANOMALY = "Anomaly_data"
@dataclass
class ImageAnnotation:
"""Image annotation data structure."""
image_path: str
json_path: str
txt_path: str
label: int # 0 for normal, 1 for anomaly
data_type: DataType
point_name: str
frame_id: Optional[str] = None
metadata: Dict[str, Any] = field(default_factory=dict)
@dataclass
class MultimodalData:
"""Multimodal data for a collection point."""
point_name: str
rgb_video_path: Optional[str] = None
infrared_video_path: Optional[str] = None
sensor_data_path: Optional[str] = None
point_cloud_path: Optional[str] = None
audio_path: Optional[str] = None
class MultimodalRobotDataset(Dataset):
"""
Multimodal Robot Anomaly Detection Dataset.
Supports:
- Loading normal and anomaly images with annotations
- Loading multimodal data (RGB, infrared, sensor, point cloud, audio)
- Loading device parameters
"""
def __init__(
self,
root_path: str,
split: DataSplit = DataSplit.TRAIN,
data_type: Optional[DataType] = None, # None means both
transform=None,
load_multimodal: bool = False,
load_parameters: bool = False,
):
"""
Initialize the dataset.
Args:
root_path: Root path to DATA_PATH directory
split: DataSplit.TRAIN or DataSplit.TEST
data_type: Filter by DataType, None means load all
transform: Optional transform to apply to images
load_multimodal: Whether to load multimodal data paths
load_parameters: Whether to load device parameters
"""
self.root_path = Path(root_path)
self.split = split
self.data_type = data_type
self.transform = transform
self.load_multimodal = load_multimodal
self.load_parameters = load_parameters
self.annotations: List[ImageAnnotation] = []
self.multimodal_data: Dict[str, MultimodalData] = {}
self.device_parameters: Dict[str, Any] = {}
self._scan_dataset()
if self.load_parameters:
self._load_parameters()
def _scan_dataset(self):
"""Scan and collect all annotation files."""
split_path = self.root_path / self.split.value
annotation_path = split_path / "Annotations"
data_types = [self.data_type] if self.data_type else [DataType.NORMAL, DataType.ANOMALY]
for dtype in data_types:
dtype_path = annotation_path / dtype.value
if not dtype_path.exists():
continue
for point_dir in dtype_path.iterdir():
if not point_dir.is_dir():
continue
point_name = point_dir.name
# Find all image files
for img_file in point_dir.glob("*.jpg"):
json_file = img_file.with_suffix(".json")
txt_file = img_file.with_suffix(".txt")
# Extract frame_id from filename
frame_id = self._extract_frame_id(img_file.name)
annotation = ImageAnnotation(
image_path=str(img_file),
json_path=str(json_file) if json_file.exists() else "",
txt_path=str(txt_file) if txt_file.exists() else "",
label=0 if dtype == DataType.NORMAL else 1,
data_type=dtype,
point_name=point_name,
frame_id=frame_id,
)
self.annotations.append(annotation)
# Sort by point name for consistent ordering
self.annotations.sort(key=lambda x: (x.data_type.value, x.point_name, x.frame_id or ""))
# Load multimodal data if requested
if self.load_multimodal:
self._scan_multimodal_data()
def _extract_frame_id(self, filename: str) -> Optional[str]:
"""Extract frame ID from filename."""
# Pattern: *_frame_000001.jpg or frame_000001.jpg
if "_frame_" in filename:
parts = filename.replace(".jpg", "").split("_frame_")
return parts[-1] if len(parts) > 1 else None
elif filename.startswith("frame_"):
return filename.replace(".jpg", "").replace("frame_", "")
return None
def _scan_multimodal_data(self):
"""Scan and collect multimodal data paths."""
split_path = self.root_path / self.split.value
multimodal_path = split_path / "Other_modalities"
if not multimodal_path.exists():
return
for point_dir in multimodal_path.iterdir():
if not point_dir.is_dir():
continue
point_name = point_dir.name
mm_data = MultimodalData(point_name=point_name)
for file in point_dir.iterdir():
if "_visible_" in file.name and file.suffix == ".mp4":
mm_data.rgb_video_path = str(file)
elif "_infrared_" in file.name and file.suffix == ".mp4":
mm_data.infrared_video_path = str(file)
elif "_sensor_" in file.name and file.suffix == ".txt":
mm_data.sensor_data_path = str(file)
elif "_point_cloud_" in file.name and file.suffix == ".bag":
mm_data.point_cloud_path = str(file)
elif "_audio_" in file.name and file.suffix == ".wav":
mm_data.audio_path = str(file)
self.multimodal_data[point_name] = mm_data
def _load_parameters(self):
"""Load device parameters."""
split_path = self.root_path / self.split.value
params_path = split_path / "Parameters"
if not params_path.exists():
return
# Load Device_*.json files
for param_file in params_path.glob("*.json"):
device_name = param_file.stem
with open(param_file, 'r', encoding='utf-8') as f:
self.device_parameters[device_name] = json.load(f)
def __len__(self) -> int:
return len(self.annotations)
def __getitem__(self, idx: int) -> Dict[str, Any]:
"""
Get a single sample.
Returns:
Dictionary containing:
- image: RGB image tensor (C, H, W)
- label: 0 for normal, 1 for anomaly
- json_data: annotation from json file
- txt_data: semantic description from txt file
- metadata: additional metadata
"""
ann = self.annotations[idx]
# Load image
image = cv2.imread(ann.image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
if self.transform:
image = self.transform(image)
# Load json annotation
json_data = None
if ann.json_path and os.path.exists(ann.json_path):
with open(ann.json_path, 'r', encoding='utf-8') as f:
json_data = json.load(f)
# Load txt description
txt_data = None
if ann.txt_path and os.path.exists(ann.txt_path):
with open(ann.txt_path, 'r', encoding='utf-8') as f:
txt_data = f.read().strip()
return {
"image": image,
"label": ann.label,
"json_data": json_data,
"txt_data": txt_data,
"metadata": {
"image_path": ann.image_path,
"point_name": ann.point_name,
"frame_id": ann.frame_id,
"data_type": ann.data_type.value,
}
}
def get_multimodal_data(self, point_name: str) -> Optional[MultimodalData]:
"""Get multimodal data for a specific point."""
return self.multimodal_data.get(point_name)
def get_parameter(self, device_name: str) -> Optional[Dict[str, Any]]:
"""Get device parameter by name."""
return self.device_parameters.get(device_name)
def get_stats(self) -> Dict[str, int]:
"""Get dataset statistics."""
normal_count = sum(1 for a in self.annotations if a.data_type == DataType.NORMAL)
anomaly_count = sum(1 for a in self.annotations if a.data_type == DataType.ANOMALY)
return {
"total": len(self.annotations),
"normal": normal_count,
"anomaly": anomaly_count,
"points": len(set(a.point_name for a in self.annotations)),
"multimodal_collections": len(self.multimodal_data),
"device_parameters": len(self.device_parameters),
}
def create_train_test_split(
root_path: str,
transform=None,
load_multimodal: bool = False,
load_parameters: bool = False,
) -> Tuple[MultimodalRobotDataset, MultimodalRobotDataset]:
"""
Create train and test datasets.
Args:
root_path: Root path to DATA_PATH directory
transform: Optional transform to apply to images
load_multimodal: Whether to load multimodal data paths
load_parameters: Whether to load device parameters
Returns:
Tuple of (train_dataset, test_dataset)
"""
train_dataset = MultimodalRobotDataset(
root_path=root_path,
split=DataSplit.TRAIN,
transform=transform,
load_multimodal=load_multimodal,
load_parameters=load_parameters,
)
test_dataset = MultimodalRobotDataset(
root_path=root_path,
split=DataSplit.TEST,
transform=transform,
load_multimodal=load_multimodal,
load_parameters=load_parameters,
)
return train_dataset, test_dataset
# Example usage
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Multimodal Robot Anomaly Dataset Loader")
parser.add_argument("--root", type=str, default="/home/tc/trainData/multimodal_data_process/split1/DATA_PATH",
help="Root path to DATA_PATH directory")
parser.add_argument("--split", type=str, choices=["train", "test", "all"], default="all",
help="Which split to load")
parser.add_argument("--stats", action="store_true", help="Print dataset statistics")
args = parser.parse_args()
if args.split == "all":
train_ds, test_ds = create_train_test_split(
root_path=args.root,
load_multimodal=True,
load_parameters=True,
)
print("=" * 50)
print("TRAIN Dataset Statistics:")
print("=" * 50)
for k, v in train_ds.get_stats().items():
print(f" {k}: {v}")
print("\n" + "=" * 50)
print("TEST Dataset Statistics:")
print("=" * 50)
for k, v in test_ds.get_stats().items():
print(f" {k}: {v}")
else:
split = DataSplit.TRAIN if args.split == "train" else DataSplit.TEST
dataset = MultimodalRobotDataset(
root_path=args.root,
split=split,
load_multimodal=True,
load_parameters=True,
)
print("=" * 50)
print(f"{args.split.upper()} Dataset Statistics:")
print("=" * 50)
for k, v in dataset.get_stats().items():
print(f" {k}: {v}")
# Test loading a sample
if args.stats and args.split == "all":
print("\n" + "=" * 50)
print("Sample Data (first 3):")
print("=" * 50)
for i, sample in enumerate(train_ds):
if i >= 3:
break
print(f"\nSample {i + 1}:")
print(f" Label: {sample['label']} ({'Normal' if sample['label'] == 0 else 'Anomaly'})")
print(f" Point: {sample['metadata']['point_name']}")
print(f" Frame: {sample['metadata']['frame_id']}")
print(f" Image shape: {sample['image'].shape if hasattr(sample['image'], 'shape') else 'N/A'}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208"""
================================================================================
DMX API Batch Image Analysis Script (with Progress & ETA)
================================================================================
Description:
Batch analyzes local images using specified multimodal model via DMX API,
and saves results as .txt files named after each image.
================================================================================
"""
import base64
import json
import os
import time
import glob
from pathlib import Path
from datetime import datetime, timedelta
import requests
# ============================================================================
# Utility Functions
# ============================================================================
def encode_image(image_path):
"""Encode local image file to Base64 string"""
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
def get_image_files(annotations_dir):
"""
Recursively find all image files from Annotations directory
(assumes images share the same name as annotations but with common image extensions)
Note: Actual images may not be in Annotations directory, but in sibling directories like JPEGImages or images.
This assumes images are in the same level as Annotations, or Annotations contains images (adjust based on your needs)
"""
# Common image extensions
image_extensions = ['*.jpg', '*.jpeg', '*.png', '*.bmp', '*.tiff', '*.webp']
image_paths = []
for ext in image_extensions:
image_paths.extend(glob.glob(os.path.join(annotations_dir, '**', ext), recursive=True))
# If images are in another directory (e.g., ../JPEGImages), add paths here
# For example:
# image_dir = os.path.join(annotations_dir, '..', 'JPEGImages')
# image_paths.extend(glob.glob(os.path.join(image_dir, '**', ext), recursive=True))
return sorted(image_paths)
# ============================================================================
# API Configuration
# ============================================================================
BASE_URL = "https://www.dmxapi.cn/"
API_ENDPOINT = BASE_URL + "v1/chat/completions"
API_KEY = "sk-***"
# Model name (used to create results folder)
MODEL_NAME = "claude-opus-4-5-20251101"
# Path Configuration
ANNOTATIONS_ROOT = "/path/to/your/DATA_PATH/test/Annotations"
MODEL_RESULTS_PATH = "/path/to/your/model_generate_results_dir/%s" % MODEL_NAME
os.makedirs(MODEL_RESULTS_PATH, exist_ok=True)
OUTPUT_DIR = os.path.join(MODEL_RESULTS_PATH, MODEL_NAME)
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Get all image paths
image_paths = get_image_files(ANNOTATIONS_ROOT)
total_images = len(image_paths)
if total_images == 0:
print(f"[!] No image files found in {ANNOTATIONS_ROOT} and its subdirectories.")
exit(1)
print(f"[INFO] Found {total_images} images, results will be saved to: {OUTPUT_DIR}")
# Build prompt (unchanged)
prompt = (
"Please analyze the input industrial scene image according to the following criteria:\n\n"
"Task Objectives:\n"
"1. Describe key visual elements in the image (e.g., personnel behavior, environmental conditions, object distribution, hazard sources, etc.).\n"
"2. Assess the safety level of the scene into one of four categories:\n"
" - Level one: High-risk hazards present that could lead to severe incidents (e.g., open flame, smoke, personnel collapse, oil leakage, etc.);\n"
" - Level two: Moderate risks present that may cause safety issues or violations (e.g., using a mobile phone, oil accumulation, foreign objects, missing required PPE, etc.);\n"
" - Level three: Minor hazards present that require attention but are not urgent (e.g., water pooling, small foreign objects, missing face mask, etc.);\n"
" - no abnormalities observed: No obvious abnormalities or risk factors.\n\n"
"Assessment Criteria (by industry):\n"
"| Safety Level | Oil & Gas / Chemical | Coal Conveyor Gallery | Tunnel | Power | Metallurgy |\n"
"|--------------|----------------------|------------------------|--------|-------|------------|\n"
"| Level one | Open flame, smoke, no hard hat, no gloves, no mask, smoking, personnel collapse, oil leakage | Open flame, smoke, no hard hat, smoking, personnel collapse | Open flame, smoke, non-motorized vehicles in fast lane, wood, metal, personnel collapse | Open flame, smoke, smoking, personnel collapse | Open flame, smoke, no hard hat, personnel collapse |\n"
"| Level two | Water pooling, using mobile phone | Using mobile phone, no gloves, no mask, foreign objects (plastic bags, bottles, foam, metal, paper) | Foam, plastic bags, plastic bottles, no hard hat, cabinet door open | Water pooling, oil accumulation, using mobile phone, foreign objects (plastic bags, bottles, foam, metal, paper), no hard hat, no gloves, cabinet door open | No gloves, no mask, smoking |\n"
"| Level three | Foreign objects | Water pooling | Water pooling, oil accumulation, using mobile phone, no gloves, no mask, smoking | No mask | Water pooling, oil accumulation, using mobile phone, foreign objects (plastic bags, bottles, foam, metal, paper) |\n\n"
"Notes:\n"
"- If the image cannot be clearly recognized, output 'Unrecognizable' and explain the reason in the [Image Description].\n"
"- If the scene exhibits characteristics of multiple industries, prioritize the most relevant industry category.\n"
"- If no risk factors are present, assign the safety level as 'no abnormalities observed'."
"Output Format Requirements:\n"
"Strictly follow the structure below (do not add extra content,only include Image Description and Safety Level):\n\n"
"[Image Description]\n"
"[Detailed description of the scene, human actions, environmental features, visible objects, etc.]\n\n"
"[Safety Level]\n"
"[Level one / Level two / Level three / no abnormalities observed]\n\n"
)
headers = {
"Content-Type": "application/json",
"Authorization": f"{API_KEY}"
}
# ============================================================================
# Main Batch Processing Loop
# ============================================================================
processed = 0
total_time = 0.0
start_all = time.time()
for img_path in image_paths:
img_name = os.path.splitext(os.path.basename(img_path))[0]
output_file = os.path.join(OUTPUT_DIR, f"{img_name}.txt")
# Skip already processed images
if os.path.exists(output_file):
print(f"[SKIP] Already exists: {img_name}")
processed += 1
continue
try:
# Encode image
image_data = encode_image(img_path)
except FileNotFoundError:
print(f"[ERROR] Image not found: {img_path}")
continue
except Exception as e:
print(f"[ERROR] Encoding failed {img_path}: {e}")
continue
payload = {
"model": MODEL_NAME,
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_data}"}}
]
}
],
"temperature": 0.1
}
start = time.time()
try:
response = requests.post(API_ENDPOINT, headers=headers, json=payload, timeout=60)
elapsed = time.time() - start
total_time += elapsed
processed += 1
if response.status_code != 200:
error_msg = f"HTTP {response.status_code}: {response.text}"
print(f"[FAIL] {img_name} - {error_msg}")
# Optional: save error info to file
with open(output_file, 'w') as f:
f.write(f"[API ERROR] {error_msg}\n")
continue
result = response.json()
if "choices" in result and len(result["choices"]) > 0:
content = result["choices"][0]["message"]["content"]
with open(output_file, 'w', encoding='utf-8') as f:
f.write(content)
print(f"[OK] {img_name} ({elapsed:.2f}s)")
else:
error_detail = result.get("error", "Unknown error")
print(f"[FAIL] {img_name} - No valid response: {error_detail}")
with open(output_file, 'w') as f:
f.write(f"[NO RESPONSE] {error_detail}\n")
except Exception as e:
elapsed = time.time() - start
total_time += elapsed
processed += 1
print(f"[EXCEPTION] {img_name}: {e}")
with open(output_file, 'w') as f:
f.write(f"[EXCEPTION] {str(e)}\n")
continue
# Calculate ETA
if processed > 0:
avg_time = total_time / processed
remaining = total_images - processed
eta_seconds = avg_time * remaining
eta_str = str(timedelta(seconds=int(eta_seconds)))
print(f" -> Progress: {processed}/{total_images} | Avg time: {avg_time:.2f}s | ETA: {eta_str}")
# ============================================================================
# Final Statistics
# ============================================================================
total_elapsed = time.time() - start_all
print("\n" + "=" * 80)
print(f"Batch processing completed!")
print(f"Total images: {total_images}")
print(f"Processed/Skipped: {processed}")
print(f"Total time: {timedelta(seconds=int(total_elapsed))}")
print(f"Results saved to: {OUTPUT_DIR}")
print("=" * 80)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Benchmark Evaluation Script for Model Text Similarity
=========================================================
Compares generated results with reference texts using text embeddings.
"""
import numpy as np
import requests
import subprocess
import os
from pathlib import Path
from typing import List
MODEL_NAME = "grok-4.1-fast"
MODEL_RESULTS_PATH = "/path/to/your/model_generate_results_dir/%s/" % MODEL_NAME
TEST_DATA_PATH = "/path/to/your/DATA_PATH/test/"
class TextSimilarityCalculator:
def __init__(self, model_name="bge-m3", ollama_host="http://localhost:11434"):
self.model_name = model_name
self.ollama_host = ollama_host
def get_embedding(self, text: str) -> List[float]:
try:
response = requests.get(f"{self.ollama_host}/api/tags")
if response.status_code != 200:
return None
payload = {"model": self.model_name, "prompt": text, "stream": False}
response = requests.post(f"{self.ollama_host}/api/embeddings", json=payload, timeout=30)
if response.status_code == 200:
return response.json().get("embedding", [])
return None
except:
return None
def cosine_similarity(self, vec1: List[float], vec2: List[float]) -> float:
if not vec1 or not vec2:
return 0.0
vec1, vec2 = np.array(vec1), np.array(vec2)
norm1, norm2 = np.linalg.norm(vec1), np.linalg.norm(vec2)
if norm1 == 0 or norm2 == 0:
return 0.0
return np.dot(vec1, vec2) / (norm1 * norm2)
def calculate_similarity(self, text1: str, text2: str) -> float:
embedding1, embedding2 = self.get_embedding(text1), self.get_embedding(text2)
if embedding1 is None or embedding2 is None:
return 0.0
return float(self.cosine_similarity(embedding1, embedding2))
def check_ollama_installation(self):
try:
result = subprocess.run(["ollama", "--version"], capture_output=True, text=True)
if result.returncode == 0:
result = subprocess.run(["ollama", "list"], capture_output=True, text=True)
return self.model_name in result.stdout
return False
except:
return False
def find_matching_txt_files(ref_dir, test_dir):
matches = []
ref_txt_files = list(Path(ref_dir).glob("*.txt"))
for txt_path in Path(test_dir).rglob("*.txt"):
txt_name = txt_path.name
matching_ref = [ref for ref in ref_txt_files if ref.name == txt_name]
if matching_ref:
for ref_file in matching_ref:
matches.append((ref_file, txt_path))
return matches
def read_file_content(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as f:
return f.read().strip()
except:
return ""
def main():
matches = find_matching_txt_files(MODEL_RESULTS_PATH, TEST_DATA_PATH)
if not matches:
print("No matching txt files found")
return
print(f"Found {len(matches)} matching txt file pairs")
print("-" * 50)
calculator = TextSimilarityCalculator()
if not calculator.check_ollama_installation():
print("Ollama environment check failed")
return
similarities = []
for i, (ref_path, test_path) in enumerate(matches, 1):
ref_content = read_file_content(ref_path)
test_content = read_file_content(test_path)
if not ref_content or not test_content:
print(f"File {ref_path.name}: Skipped (empty content)")
continue
similarity = calculator.calculate_similarity(ref_content, test_content)
similarities.append(similarity)
print(f"Pair {i}: {ref_path.name}")
print(f" Reference file: {ref_path}")
print(f" Target file: {test_path}")
print(f" Similarity: {similarity:.4f}")
print("-" * 30)
if similarities:
avg_similarity = np.mean(similarities)
print("=" * 50)
print(f"Total file pairs: {len(similarities)}")
print(f"Average similarity: {avg_similarity:.4f}")
else:
print("No valid file pairs for similarity calculation")
if __name__ == "__main__":
main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138import os
import re
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from collections import defaultdict
MODEL_NAME = "grok-4.1-fast"
MODEL_RESULTS_PATH = "/path/to/your/model_generate_results_dir/%s/" % MODEL_NAME
GT_ROOT_ANOMALY = "/path/to/your/DATA_PATH/test/Annotations/Anomaly_data"
GT_ROOT_NORMAL = "/path/to/your/DATA_PATH/test/Annotations/Normal_data"
# Define class order
classes = ["level one", "level two", "level three", "no abnormalities observed", "unrecognizable"]
tick_label_classes = ["level Ⅰ", "level Ⅱ", "level Ⅲ", "level Ⅳ", "unrecognizable"]
# Ground truth label mapping
label_map = {
"observed": "no abnormalities observed",
"one": "level one",
"two": "level two",
"ii": "level two",
"2": "level two",
"three": "level three",
"unrecognizable": "unrecognizable",
}
def extract_prediction(file_path):
"""Extract the last word from prediction file and map to standard class"""
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
if not lines:
return label_map["unrecognizable"]
last_line = lines[-1].strip()
if '(' in last_line:
last_line = last_line.split('(')[0]
words = last_line.split()
if not words:
return label_map["unrecognizable"]
last_word = words[-1]
# Remove possible punctuation (e.g., period)
last_word = last_word.rstrip('.').strip().lower().replace('level]', '').replace(']', '')
if last_word in label_map:
return label_map[last_word]
else:
print(f"Warning: Unknown prediction label keyword: '{last_word}' in {file_path}")
return label_map["unrecognizable"]
def extract_ground_truth(file_path):
"""Extract the last word from ground truth file and map to standard class"""
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
if not lines:
return None
last_line = lines[-1].strip()
words = last_line.split()
if not words:
return None
last_word = words[-1]
# Remove possible punctuation (e.g., period)
last_word = last_word.rstrip('.').strip().lower()
if last_word in label_map:
return label_map[last_word]
else:
print(f"Warning: Unknown ground truth label keyword: '{last_word}' in {file_path}")
return None
def collect_files(root_dir):
"""Recursively collect all .txt files in directory, return {filename: full_path} dict"""
file_dict = {}
for dirpath, _, filenames in os.walk(root_dir):
for f in filenames:
if f.endswith('.txt'):
file_dict[f] = os.path.join(dirpath, f)
return file_dict
def main():
# Collect prediction and ground truth files
pred_files = collect_files(MODEL_RESULTS_PATH)
gt_files1 = collect_files(GT_ROOT_ANOMALY)
gt_files2 = collect_files(GT_ROOT_NORMAL)
gt_files = {**gt_files1, **gt_files2}
# Match filenames
common_files = set(pred_files.keys()) & set(gt_files.keys())
print(f"Found {len(common_files)} matching samples")
# Initialize confusion matrix
cm = np.zeros((len(classes), len(classes)), dtype=int)
class_to_index = {cls: i for i, cls in enumerate(classes)}
count_valid = 0
for fname in common_files:
pred_path = pred_files[fname]
gt_path = gt_files[fname]
pred = extract_prediction(pred_path)
gt = extract_ground_truth(gt_path)
if pred is None or gt is None:
continue
if pred not in class_to_index or gt not in class_to_index:
print(f"Skip invalid class: pred={pred}, gt={gt}")
continue
i = class_to_index[gt] # Ground truth -> row
j = class_to_index[pred] # Prediction -> column
cm[i, j] += 1
count_valid += 1
print(f"Valid samples: {count_valid}")
# Plot confusion matrix
plt.figure(figsize=(8, 6))
sns.set(font_scale=1.2)
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
xticklabels=tick_label_classes,
yticklabels=tick_label_classes)
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.title(MODEL_NAME)
plt.xticks(rotation=45, ha='right')
plt.yticks(rotation=0)
plt.tight_layout()
plt.savefig(f"{MODEL_NAME}.png", dpi=300)
plt.show()
if __name__ == "__main__":
main()123version https://git-lfs.github.com/spec/v1oid sha256:818086e696f970e036bf6a76758e4fb851fa26f771fe4eac56f8dc073b44358dsize 5748799871123version https://git-lfs.github.com/spec/v1oid sha256:ef03b9eb2f9bd91b03f203a8e6cfcc3464cb0d9f0215349a80ad95281fa88cd6size 17886855594README.mdAdded+135
dataset_loader.pyAdded+387
model_api_generate_results.pyAdded+208
model_benchmark_evaluation.pyAdded+140
model_confusion_matrix.pyAdded+138
test.tar.gzAdded+3
train.tar.gzAdded+3