Datasets:

ArXiv:
File size: 9,417 Bytes
9f3bc09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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)