Datasets:

ArXiv:
ea-dev-pjlab-results / fix_model_output.py
shulin16's picture
Upload folder using huggingface_hub
9f3bc09 verified
#!/usr/bin/env python3
"""
Output fixer for the evaluation agent model.
This script provides utilities to fix malformed structured output from the model.
"""
import re
import json
from typing import Dict, Optional, Tuple
class ModelOutputFixer:
"""Fixes malformed structured output from the evaluation agent model."""
def __init__(self):
"""Initialize the output fixer."""
self.common_tools = [
"Object Class", "Scene", "Color", "Spatial Relationship",
"Human Action", "Dynamic Degree", "Multiple Objects",
"Overall Consistency", "Aesthetic Quality", "Imaging Quality",
"Motion Smoothness", "Subject Consistency", "Background Consistency"
]
self.common_subaspects = [
"Basic object class generation", "Intermediate object class generation",
"Complex object class generation", "Advanced object class generation",
"Simple color accuracy", "Complex color combinations",
"Basic spatial relationships", "Complex spatial arrangements",
"Single object generation", "Multiple object generation"
]
def parse_malformed_output(self, output: str) -> Dict[str, Optional[str]]:
"""
Parse malformed output and extract components.
Args:
output: Malformed model output
Returns:
Dictionary with think, subaspect, and tool components
"""
result = {"think": None, "subaspect": None, "tool": None}
# Try to extract think content (various patterns)
think_patterns = [
r'<think>(.*?)</think>',
r'<think>(.*?)(?:<subaspect>|<tool>|$)',
r'(?:^|>)(.*?)<think>', # Content before <think>
]
for pattern in think_patterns:
match = re.search(pattern, output, re.DOTALL)
if match and match.group(1).strip():
result["think"] = match.group(1).strip()
break
# Try to extract subaspect content
subaspect_patterns = [
r'<subaspect>(.*?)</subaspect>',
r'<subaspect>(.*?)(?:<tool>|</tool>|$)',
r'([A-Z][^<]*(?:generation|accuracy|relationships?|evaluation))[^<]*</tool>', # Content ending with </tool>
]
for pattern in subaspect_patterns:
match = re.search(pattern, output, re.DOTALL | re.IGNORECASE)
if match and match.group(1).strip():
candidate = match.group(1).strip()
# Check if it looks like a subaspect
if any(keyword in candidate.lower() for keyword in ["generation", "accuracy", "evaluation", "assessment", "analysis"]):
result["subaspect"] = candidate
break
# Try to extract tool content
tool_patterns = [
r'<tool>(.*?)</tool>',
r'<tool>(.*?)$',
r'<think>([^<]*(?:Object Class|Scene|Color|Human Action|Dynamic Degree)[^<]*)</tool>', # Tool name in wrong tag
]
for pattern in tool_patterns:
match = re.search(pattern, output, re.DOTALL)
if match and match.group(1).strip():
candidate = match.group(1).strip()
# Check if it's a known tool
if any(tool.lower() in candidate.lower() for tool in self.common_tools):
result["tool"] = candidate
break
return result
def fix_output(self, malformed_output: str) -> str:
"""
Fix malformed output and return properly structured format.
Args:
malformed_output: The malformed model output
Returns:
Fixed output in correct format
"""
parsed = self.parse_malformed_output(malformed_output)
# Fix missing components with reasonable defaults
if not parsed["think"]:
parsed["think"] = "To evaluate this aspect, I will analyze the model's capabilities systematically."
if not parsed["subaspect"]:
# Try to infer from context or use a generic one
if "object" in malformed_output.lower():
parsed["subaspect"] = "Object generation capability"
elif "color" in malformed_output.lower():
parsed["subaspect"] = "Color accuracy assessment"
else:
parsed["subaspect"] = "Basic capability evaluation"
if not parsed["tool"]:
# Try to infer tool from context
for tool in self.common_tools:
if tool.lower().replace(" ", "") in malformed_output.lower().replace(" ", ""):
parsed["tool"] = tool
break
if not parsed["tool"]:
parsed["tool"] = "Object Class" # Default tool
# Construct proper output
fixed_output = f"<think>{parsed['think']}</think> <subaspect>{parsed['subaspect']}</subaspect> <tool>{parsed['tool']}</tool>"
return fixed_output
def validate_output(self, output: str) -> Tuple[bool, str]:
"""
Validate if output has correct structure.
Args:
output: Output to validate
Returns:
Tuple of (is_valid, error_message)
"""
required_patterns = [
(r'<think>.*?</think>', "Missing or malformed <think> tags"),
(r'<subaspect>.*?</subaspect>', "Missing or malformed <subaspect> tags"),
(r'<tool>.*?</tool>', "Missing or malformed <tool> tags")
]
for pattern, error_msg in required_patterns:
if not re.search(pattern, output, re.DOTALL):
return False, error_msg
return True, "Valid structure"
def interactive_fix(self):
"""Interactive mode for fixing outputs."""
print("🔧 MODEL OUTPUT FIXER - Interactive Mode")
print("="*50)
print("Paste your malformed model output below (press Enter twice to finish):")
lines = []
while True:
try:
line = input()
if line.strip() == "" and lines:
break
lines.append(line)
except (EOFError, KeyboardInterrupt):
break
if not lines:
print("No input provided.")
return
malformed_output = "\n".join(lines)
print(f"\n📥 Input: {malformed_output}")
# Parse components
parsed = self.parse_malformed_output(malformed_output)
print(f"\n🔍 Parsed Components:")
print(f" Think: {parsed['think'][:50]}..." if parsed['think'] else " Think: ❌ Not found")
print(f" Subaspect: {parsed['subaspect']}" if parsed['subaspect'] else " Subaspect: ❌ Not found")
print(f" Tool: {parsed['tool']}" if parsed['tool'] else " Tool: ❌ Not found")
# Fix output
fixed = self.fix_output(malformed_output)
print(f"\n✅ Fixed Output:\n{fixed}")
# Validate
is_valid, msg = self.validate_output(fixed)
print(f"\n✓ Validation: {msg}")
def main():
"""Main function for command line usage."""
import argparse
parser = argparse.ArgumentParser(description="Fix malformed model output")
parser.add_argument("--input", "-i", help="Input malformed output string")
parser.add_argument("--file", "-f", help="Input file with malformed output")
parser.add_argument("--interactive", "-I", action="store_true", help="Interactive mode")
parser.add_argument("--output", "-o", help="Output file for fixed result")
args = parser.parse_args()
fixer = ModelOutputFixer()
if args.interactive:
fixer.interactive_fix()
return
# Get input
malformed_output = ""
if args.input:
malformed_output = args.input
elif args.file:
try:
with open(args.file, 'r') as f:
malformed_output = f.read().strip()
except Exception as e:
print(f"Error reading file: {e}")
return
else:
print("Please provide input via --input, --file, or --interactive")
return
if not malformed_output:
print("No input provided")
return
# Fix output
print(f"Input: {malformed_output}")
parsed = fixer.parse_malformed_output(malformed_output)
print(f"\nParsed components:")
for key, value in parsed.items():
print(f" {key}: {value}")
fixed = fixer.fix_output(malformed_output)
print(f"\nFixed output: {fixed}")
# Save to file if requested
if args.output:
try:
with open(args.output, 'w') as f:
f.write(fixed)
print(f"Fixed output saved to {args.output}")
except Exception as e:
print(f"Error saving file: {e}")
if __name__ == "__main__":
main()
# Example usage as a module:
# from fix_model_output import ModelOutputFixer
# fixer = ModelOutputFixer()
# fixed = fixer.fix_output("Advanced Object Class Generation</tool> <think>Object Class</tool>")
# print(fixed)