File size: 13,620 Bytes
5e4510c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
"""
Evaluator for web scraper evolution.

This evaluator tests the scraper against real documentation pages,
providing feedback on accuracy and robustness. It includes URLs
that will be fetched by optillm's readurls plugin during evolution.
"""

import sys
import os
import traceback
from typing import Dict, List, Any

# Add the program directory to the path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))


def evaluate(program_path: str) -> Dict:
    """
    Evaluate the web scraper program.

    Args:
        program_path: Path to the program to evaluate

    Returns:
        Dictionary with metrics and artifacts for OpenEvolve compatibility
    """
    try:
        # Import the program
        sys.path.insert(0, os.path.dirname(program_path))
        program_name = os.path.basename(program_path).replace(".py", "")
        program = __import__(program_name)

        # Test data: HTML content from various documentation sources
        test_cases = get_test_cases()

        # Evaluate each test case
        metrics = {
            "accuracy": 0.0,
            "completeness": 0.0,
            "robustness": 0.0,
            "parsing_errors": 0.0,
            "total_score": 0.0,
        }

        artifacts = {}

        total_correct = 0
        total_expected = 0
        parsing_errors = 0

        for i, test_case in enumerate(test_cases):
            try:
                # Run the scraper
                docs = program.scrape_api_docs(test_case["html"])

                # Evaluate accuracy
                correct, expected = evaluate_extraction(docs, test_case["expected"])
                total_correct += correct
                total_expected += expected

                # Test parameter extraction
                for doc in docs:
                    if "parameters" not in doc:
                        doc["parameters"] = program.extract_parameters(doc.get("signature", ""))

                # Test formatting
                formatted = program.format_documentation(docs)

                # Store results for debugging
                artifacts[f"test_case_{i}"] = {
                    "expected_count": expected,
                    "found_count": correct,
                    "extracted_functions": [doc.get("name", "unknown") for doc in docs],
                    "formatted_length": len(formatted),
                }

            except Exception as e:
                parsing_errors += 1
                artifacts[f"test_case_{i}_error"] = str(e)

        # Calculate metrics
        if total_expected > 0:
            metrics["accuracy"] = total_correct / total_expected

        metrics["completeness"] = min(1.0, total_correct / 20)  # Expect ~20 functions total
        metrics["robustness"] = max(0.0, 1.0 - (parsing_errors / len(test_cases)))
        metrics["parsing_errors"] = parsing_errors / len(test_cases)

        # Overall score - use 'combined_score' as primary metric for evolution
        metrics["combined_score"] = (
            metrics["accuracy"] * 0.4 + metrics["completeness"] * 0.3 + metrics["robustness"] * 0.3
        )

        # Add detailed feedback for the LLM
        artifacts["evaluation_feedback"] = generate_feedback(metrics, artifacts)

        # Return dictionary format for OpenEvolve compatibility
        return metrics

    except Exception as e:
        return {
            "accuracy": 0.0,
            "completeness": 0.0,
            "robustness": 0.0,
            "parsing_errors": 1.0,
            "combined_score": 0.0,
            "error": str(e),
            "traceback": traceback.format_exc(),
            "stage": "program_import",
        }


def get_test_cases() -> List[Dict[str, Any]]:
    """
    Get test cases with HTML content and expected results.

    These test cases include URLs that will be fetched by optillm's
    readurls plugin during evolution, providing the LLM with actual
    documentation structure.

    Returns:
        List of test cases with HTML content and expected results
    """
    return [
        {
            "name": "json_module_docs",
            "html": """
            <html>
            <body>
                <div class="section">
                    <h1>json — JSON encoder and decoder</h1>
                    <p>Source: https://docs.python.org/3/library/json.html</p>
                    
                    <dl class="function">
                        <dt class="sig sig-object py">
                            <span class="sig-name descname">dumps</span>
                            <span class="sig-paren">(</span>
                            <em class="sig-param">obj</em>,
                            <em class="sig-param">indent=None</em>
                            <span class="sig-paren">)</span>
                        </dt>
                        <dd>
                            <p>Serialize obj to a JSON formatted string.</p>
                        </dd>
                    </dl>
                    
                    <dl class="function">
                        <dt class="sig sig-object py">
                            <span class="sig-name descname">loads</span>
                            <span class="sig-paren">(</span>
                            <em class="sig-param">s</em>
                            <span class="sig-paren">)</span>
                        </dt>
                        <dd>
                            <p>Deserialize s to a Python object.</p>
                        </dd>
                    </dl>
                </div>
            </body>
            </html>
            """,
            "expected": [
                {"name": "dumps", "params": ["obj", "indent"]},
                {"name": "loads", "params": ["s"]},
            ],
        },
        {
            "name": "requests_docs",
            "html": """
            <html>
            <body>
                <div class="document">
                    <h1>Requests Documentation</h1>
                    <p>Refer to https://requests.readthedocs.io/en/latest/api/ for full API</p>
                    
                    <div class="function">
                        <h3>requests.get(url, params=None, **kwargs)</h3>
                        <p>Sends a GET request.</p>
                    </div>
                    
                    <div class="function">
                        <h3>requests.post(url, data=None, json=None, **kwargs)</h3>
                        <p>Sends a POST request.</p>
                    </div>
                </div>
            </body>
            </html>
            """,
            "expected": [
                {"name": "requests.get", "params": ["url", "params"]},
                {"name": "requests.post", "params": ["url", "data", "json"]},
            ],
        },
        {
            "name": "beautifulsoup_docs",
            "html": """
            <html>
            <body>
                <div class="section">
                    <h1>BeautifulSoup Documentation</h1>
                    <p>Documentation at https://www.crummy.com/software/BeautifulSoup/bs4/doc/</p>
                    
                    <code class="python">
                        <span class="name">BeautifulSoup</span>(<span class="param">markup</span>, <span class="param">parser</span>)
                    </code>
                    <p>Parse a string using a specified parser.</p>
                    
                    <code class="python">
                        <span class="name">find</span>(<span class="param">name</span>, <span class="param">attrs</span>=<span class="default">None</span>)
                    </code>
                    <p>Find the first matching tag.</p>
                    
                    <code class="python">
                        <span class="name">find_all</span>(<span class="param">name</span>, <span class="param">attrs</span>=<span class="default">None</span>, <span class="param">limit</span>=<span class="default">None</span>)
                    </code>
                    <p>Find all matching tags.</p>
                </div>
            </body>
            </html>
            """,
            "expected": [
                {"name": "BeautifulSoup", "params": ["markup", "parser"]},
                {"name": "find", "params": ["name", "attrs"]},
                {"name": "find_all", "params": ["name", "attrs", "limit"]},
            ],
        },
        {
            "name": "edge_case_malformed",
            "html": """
            <html>
            <body>
                <div class="weird-format">
                    <h2>Unusual Documentation Format</h2>
                    <p>This tests robustness - check https://example.com/weird-api-docs</p>
                    
                    <pre>
                    function_name(arg1, arg2=default_value)
                    Another description here
                    </pre>
                    
                    <table>
                        <tr>
                            <td>another_func()</td>
                            <td>Does something</td>
                        </tr>
                    </table>
                </div>
            </body>
            </html>
            """,
            "expected": [
                {"name": "function_name", "params": ["arg1", "arg2"]},
                {"name": "another_func", "params": []},
            ],
        },
    ]


def evaluate_extraction(
    docs: List[Dict[str, Any]], expected: List[Dict[str, Any]]
) -> tuple[int, int]:
    """
    Evaluate the accuracy of extracted documentation.

    Args:
        docs: Extracted documentation
        expected: Expected results

    Returns:
        Tuple of (correct_count, expected_count)
    """
    correct = 0
    expected_count = len(expected)

    for exp in expected:
        # Check if we found this function
        found = False
        for doc in docs:
            doc_name = doc.get("name", "").lower()
            exp_name = exp["name"].lower()

            if exp_name in doc_name or doc_name in exp_name:
                found = True
                # Check parameter extraction
                doc_params = doc.get("parameters", [])
                exp_params = exp.get("params", [])

                if len(doc_params) >= len(exp_params):
                    correct += 1
                else:
                    correct += 0.5  # Partial credit
                break

        if not found and docs:  # Only penalize if we extracted something
            pass  # No additional penalty

    return correct, expected_count


def generate_feedback(metrics: Dict[str, float], artifacts: Dict[str, Any]) -> str:
    """
    Generate detailed feedback for the LLM to improve the scraper.

    This feedback will be included in the evolution prompt to guide
    the LLM toward better solutions.

    Args:
        metrics: Evaluation metrics
        artifacts: Evaluation artifacts

    Returns:
        Detailed feedback string
    """
    feedback = []

    feedback.append("## Evaluation Feedback")
    feedback.append(f"Overall Score: {metrics['combined_score']:.2f}/1.0")
    feedback.append("")

    # Accuracy feedback
    if metrics["accuracy"] < 0.5:
        feedback.append("⚠️ **Low Accuracy**: The scraper is missing many expected functions.")
        feedback.append(
            "Consider improving the HTML parsing logic to handle different documentation formats."
        )
        feedback.append(
            "Look for patterns like <dl class='function'>, <div class='function'>, and <code> tags."
        )
    elif metrics["accuracy"] < 0.8:
        feedback.append("✅ **Good Accuracy**: Most functions are found, but some are missed.")
        feedback.append("Fine-tune the extraction logic for edge cases.")
    else:
        feedback.append("🎉 **Excellent Accuracy**: Function extraction is working well!")

    feedback.append("")

    # Completeness feedback
    if metrics["completeness"] < 0.5:
        feedback.append("⚠️ **Low Completeness**: Not extracting enough functions overall.")
        feedback.append("Increase the limit or improve the search scope.")

    # Robustness feedback
    if metrics["robustness"] < 0.8:
        feedback.append("⚠️ **Low Robustness**: The scraper fails on some HTML formats.")
        feedback.append("Add try-catch blocks and handle different documentation structures.")
        feedback.append("Consider multiple parsing strategies and fallback methods.")

    # Specific improvements
    feedback.append("")
    feedback.append("## Specific Improvements:")

    # Analyze test case results
    for key, value in artifacts.items():
        if key.startswith("test_case_") and isinstance(value, dict):
            if "error" in key:
                feedback.append(f"- Fix error in {key}: {value}")
            elif value.get("found_count", 0) < value.get("expected_count", 0):
                feedback.append(
                    f"- Improve extraction for {key}: found {value.get('found_count', 0)}/{value.get('expected_count', 0)} functions"
                )

    # Documentation URL hints (these will be fetched by readurls plugin)
    feedback.append("")
    feedback.append("## Documentation References:")
    feedback.append("For improving parsing, refer to these documentation structures:")
    feedback.append("- Python docs: https://docs.python.org/3/library/json.html")
    feedback.append("- Requests docs: https://requests.readthedocs.io/en/latest/api/")
    feedback.append("- BeautifulSoup docs: https://www.crummy.com/software/BeautifulSoup/bs4/doc/")

    return "\n".join(feedback)