Spaces:
Sleeping
Sleeping
File size: 9,918 Bytes
cacd4d0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 |
"""
Index Caching Dataset Loader
Loads index caching dataset from JSON file (note2_debug.json format) and converts to GEPA-compatible format.
"""
import os
import json
import base64
import logging
from typing import List, Dict, Any, Optional
from pathlib import Path
logger = logging.getLogger(__name__)
class IndexCachingDatasetLoader:
"""
Loads index caching dataset from JSON file.
Expected JSON format:
[
{
"command": "Tap on first option from the suggestion",
"image": "element_images/QMxgc_14_0_tap_IkALe_element.png",
"xml": "xml/IkALe__debug.xml",
"expected": {
"is_index_based": true,
"index_value": 1,
"parent_element_id": "aaaabf",
"element_id_of_nth_child_of_parent": "aaaabg",
"selected_element_is_correct": true
}
},
...
]
Converts to GEPA format:
- input: command text (seed prompt will be provided in test script)
- output: JSON string with expected values
- image_base64: base64 encoded image (TOP LEVEL for UniversalConverter)
- input: Command + XML content (combined in user prompt)
- metadata: All original fields plus converted values
"""
def __init__(self, json_path: Optional[str] = None, base_dir: Optional[str] = None):
"""
Initialize index caching dataset loader.
Args:
json_path: Path to JSON file. Default: "./note2_debug.json" or from env var
base_dir: Base directory for resolving relative paths in JSON.
Default: Directory containing JSON file
Raises:
FileNotFoundError: If JSON file doesn't exist
json.JSONDecodeError: If JSON file is invalid
"""
# Get JSON path from env or use default
if json_path is None:
json_path = os.getenv("INDEX_CACHING_DATASET_PATH", "./note2_debug.json")
self.json_path = Path(json_path).resolve()
if not self.json_path.exists():
raise FileNotFoundError(
f"Dataset file not found: {self.json_path}\n"
f"Make sure note2_debug.json exists in the project root."
)
# Base directory for resolving relative paths
if base_dir is None:
base_dir = self.json_path.parent
self.base_dir = Path(base_dir).resolve()
def load_dataset(self) -> List[Dict[str, Any]]:
"""
Load dataset from JSON file and convert to GEPA format.
Returns:
List of dataset items in GEPA format:
[
{
"input": "Tap on first option from the suggestion", # Command only
"output": '{"is_index_based": true, "index_value": 1, ...}', # Expected JSON
"image_base64": "<base64_encoded_image>", # TOP LEVEL
"metadata": {
"command": "...",
"image_path": "...",
"xml_path": "...",
"expected": {...}
}
},
...
]
Raises:
FileNotFoundError: If image or XML file doesn't exist
json.JSONDecodeError: If JSON file is invalid
"""
# Load JSON file
with open(self.json_path, "r", encoding="utf-8") as f:
dataset = json.load(f)
gepa_dataset = []
for idx, entry in enumerate(dataset):
command = entry.get("command", "")
image_path = entry.get("image", "")
xml_path = entry.get("xml", "")
expected = entry.get("expected", {})
# Resolve paths relative to base_dir
abs_image_path = (self.base_dir / image_path).resolve()
abs_xml_path = (self.base_dir / xml_path).resolve()
# Validate paths
if not abs_image_path.exists():
raise FileNotFoundError(
f"Image file not found: {abs_image_path}\n"
f"Entry {idx + 1}: {command}"
)
if not abs_xml_path.exists():
raise FileNotFoundError(
f"XML file not found: {abs_xml_path}\n"
f"Entry {idx + 1}: {command}"
)
# Load and encode image
with open(abs_image_path, "rb") as f:
image_data = f.read()
image_base64 = base64.b64encode(image_data).decode("utf-8")
# Load XML content
with open(abs_xml_path, "r", encoding="utf-8") as f:
xml_content = f.read()
# Convert expected to JSON string
expected_json = json.dumps(expected, ensure_ascii=False)
# Create user prompt with command + XML content
# The XML will be included in the user prompt text (as the agent does)
user_prompt = f"{command}\n\nXML Content:\n\n```xml\n{xml_content}\n```"
# For reflection, we don't need full XML - just the command is enough
# Reflection is about improving the prompt based on evaluation feedback,
# not analyzing specific XML structures
reflection_input = command # Just the command, no XML
# Create GEPA format item
gepa_item = {
"input": user_prompt, # Command + XML content (for evaluation)
"reflection_input": reflection_input, # Just command (for reflection)
"output": expected_json, # Expected output as JSON string
"image_base64": image_base64, # TOP LEVEL for UniversalConverter
"metadata": {
"command": command,
"image_path": str(image_path),
"xml_path": str(xml_path),
"abs_image_path": str(abs_image_path),
"abs_xml_path": str(abs_xml_path),
"xml_content": xml_content, # Store XML separately in metadata
"expected": expected,
"dataset_index": idx
}
}
gepa_dataset.append(gepa_item)
return gepa_dataset
def load_split(
self,
train_ratio: float = 0.6,
val_ratio: float = 0.4
) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
"""
Load dataset and split into train/val sets (no test set).
Args:
train_ratio: Ratio for training set (default: 0.6)
val_ratio: Ratio for validation set (default: 0.4)
Returns:
Tuple of (train_set, val_set)
Raises:
ValueError: If ratios don't sum to 1.0
"""
if abs(train_ratio + val_ratio - 1.0) > 0.01:
raise ValueError(
f"Split ratios must sum to 1.0, got {train_ratio + val_ratio:.3f}"
)
dataset = self.load_dataset()
total = len(dataset)
train_end = int(total * train_ratio)
train_set = dataset[:train_end]
val_set = dataset[train_end:]
return train_set, val_set
def load_index_caching_dataset(
json_path: Optional[str] = None,
base_dir: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
Convenience function to load index caching dataset.
Args:
json_path: Path to JSON file
base_dir: Base directory for resolving relative paths
Returns:
List of dataset items in GEPA format
"""
loader = IndexCachingDatasetLoader(json_path=json_path, base_dir=base_dir)
return loader.load_dataset()
def load_index_caching_split(
json_path: Optional[str] = None,
base_dir: Optional[str] = None,
train_ratio: float = 0.6,
val_ratio: float = 0.4
) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
"""
Convenience function to load and split index caching dataset.
Args:
json_path: Path to JSON file
base_dir: Base directory for resolving relative paths
train_ratio: Ratio for training set
val_ratio: Ratio for validation set
Returns:
Tuple of (train_set, val_set) - no test set
"""
loader = IndexCachingDatasetLoader(json_path=json_path, base_dir=base_dir)
return loader.load_split(train_ratio=train_ratio, val_ratio=val_ratio)
# Example usage
if __name__ == "__main__":
print("🚀 Testing Index Caching Dataset Loader...")
# Test loading
try:
loader = IndexCachingDatasetLoader(json_path="./note2_debug.json")
dataset = loader.load_dataset()
print(f"\n✅ Loaded {len(dataset)} items")
# Show sample
if dataset:
sample = dataset[0]
print(f"\n📝 Sample Item:")
print(f" Command: {sample['input']}")
print(f" Image path: {sample['metadata']['image_path']}")
print(f" XML path: {sample['metadata']['xml_path']}")
print(f" Expected: {sample['output'][:100]}...")
print(f" Image base64 length: {len(sample['image_base64'])}")
print(f" XML content length: {len(sample['metadata'].get('xml_content', ''))}")
# Test split
train, val = loader.load_split()
print(f"\n📊 Dataset Split:")
print(f" Training: {len(train)} samples")
print(f" Validation: {len(val)} samples")
print(f" Test: Not used (no test set)")
except Exception as e:
print(f"❌ Error: {e}")
|