|
| 1 | +""" |
| 2 | +Script Generator - converts trace into executable code |
| 3 | +""" |
| 4 | + |
| 5 | +import json |
| 6 | +from typing import List, Optional |
| 7 | +from .recorder import Trace, TraceStep |
| 8 | +from .query import find |
| 9 | + |
| 10 | + |
| 11 | +class ScriptGenerator: |
| 12 | + """Generates Python or TypeScript code from a trace""" |
| 13 | + |
| 14 | + def __init__(self, trace: Trace): |
| 15 | + self.trace = trace |
| 16 | + |
| 17 | + def generate_python(self) -> str: |
| 18 | + """Generate Python script from trace""" |
| 19 | + lines = [ |
| 20 | + '"""', |
| 21 | + f'Generated script from trace: {self.trace.start_url}', |
| 22 | + f'Created: {self.trace.created_at}', |
| 23 | + '"""', |
| 24 | + '', |
| 25 | + 'from sentience import SentienceBrowser, snapshot, find, click, type_text, press', |
| 26 | + '', |
| 27 | + 'def main():', |
| 28 | + ' with SentienceBrowser(headless=False) as browser:', |
| 29 | + f' browser.page.goto("{self.trace.start_url}")', |
| 30 | + ' browser.page.wait_for_load_state("networkidle")', |
| 31 | + '', |
| 32 | + ] |
| 33 | + |
| 34 | + for step in self.trace.steps: |
| 35 | + lines.extend(self._generate_python_step(step, indent=' ')) |
| 36 | + |
| 37 | + lines.extend([ |
| 38 | + '', |
| 39 | + 'if __name__ == "__main__":', |
| 40 | + ' main()', |
| 41 | + ]) |
| 42 | + |
| 43 | + return '\n'.join(lines) |
| 44 | + |
| 45 | + def generate_typescript(self) -> str: |
| 46 | + """Generate TypeScript script from trace""" |
| 47 | + lines = [ |
| 48 | + '/**', |
| 49 | + f' * Generated script from trace: {self.trace.start_url}', |
| 50 | + f' * Created: {self.trace.created_at}', |
| 51 | + ' */', |
| 52 | + '', |
| 53 | + "import { SentienceBrowser, snapshot, find, click, typeText, press } from './src';", |
| 54 | + '', |
| 55 | + 'async function main() {', |
| 56 | + ' const browser = new SentienceBrowser(undefined, false);', |
| 57 | + '', |
| 58 | + ' try {', |
| 59 | + ' await browser.start();', |
| 60 | + f' await browser.getPage().goto(\'{self.trace.start_url}\');', |
| 61 | + ' await browser.getPage().waitForLoadState(\'networkidle\');', |
| 62 | + '', |
| 63 | + ] |
| 64 | + |
| 65 | + for step in self.trace.steps: |
| 66 | + lines.extend(self._generate_typescript_step(step, indent=' ')) |
| 67 | + |
| 68 | + lines.extend([ |
| 69 | + ' } finally {', |
| 70 | + ' await browser.close();', |
| 71 | + ' }', |
| 72 | + '}', |
| 73 | + '', |
| 74 | + 'main().catch(console.error);', |
| 75 | + ]) |
| 76 | + |
| 77 | + return '\n'.join(lines) |
| 78 | + |
| 79 | + def _generate_python_step(self, step: TraceStep, indent: str = '') -> List[str]: |
| 80 | + """Generate Python code for a single step""" |
| 81 | + lines = [] |
| 82 | + |
| 83 | + if step.type == 'navigation': |
| 84 | + lines.append(f'{indent}# Navigate to {step.url}') |
| 85 | + lines.append(f'{indent}browser.page.goto("{step.url}")') |
| 86 | + lines.append(f'{indent}browser.page.wait_for_load_state("networkidle")') |
| 87 | + |
| 88 | + elif step.type == 'click': |
| 89 | + if step.selector: |
| 90 | + # Use semantic selector |
| 91 | + lines.append(f'{indent}# Click: {step.selector}') |
| 92 | + lines.append(f'{indent}snap = snapshot(browser)') |
| 93 | + lines.append(f'{indent}element = find(snap, "{step.selector}")') |
| 94 | + lines.append(f'{indent}if element:') |
| 95 | + lines.append(f'{indent} click(browser, element.id)') |
| 96 | + lines.append(f'{indent}else:') |
| 97 | + lines.append(f'{indent} raise Exception("Element not found: {step.selector}")') |
| 98 | + elif step.element_id is not None: |
| 99 | + # Fallback to element ID |
| 100 | + lines.append(f'{indent}# TODO: replace with semantic selector') |
| 101 | + lines.append(f'{indent}click(browser, {step.element_id})') |
| 102 | + lines.append('') |
| 103 | + |
| 104 | + elif step.type == 'type': |
| 105 | + if step.selector: |
| 106 | + lines.append(f'{indent}# Type into: {step.selector}') |
| 107 | + lines.append(f'{indent}snap = snapshot(browser)') |
| 108 | + lines.append(f'{indent}element = find(snap, "{step.selector}")') |
| 109 | + lines.append(f'{indent}if element:') |
| 110 | + lines.append(f'{indent} type_text(browser, element.id, "{step.text}")') |
| 111 | + lines.append(f'{indent}else:') |
| 112 | + lines.append(f'{indent} raise Exception("Element not found: {step.selector}")') |
| 113 | + elif step.element_id is not None: |
| 114 | + lines.append(f'{indent}# TODO: replace with semantic selector') |
| 115 | + lines.append(f'{indent}type_text(browser, {step.element_id}, "{step.text}")') |
| 116 | + lines.append('') |
| 117 | + |
| 118 | + elif step.type == 'press': |
| 119 | + lines.append(f'{indent}# Press key: {step.key}') |
| 120 | + lines.append(f'{indent}press(browser, "{step.key}")') |
| 121 | + lines.append('') |
| 122 | + |
| 123 | + return lines |
| 124 | + |
| 125 | + def _generate_typescript_step(self, step: TraceStep, indent: str = '') -> List[str]: |
| 126 | + """Generate TypeScript code for a single step""" |
| 127 | + lines = [] |
| 128 | + |
| 129 | + if step.type == 'navigation': |
| 130 | + lines.append(f'{indent}// Navigate to {step.url}') |
| 131 | + lines.append(f'{indent}await browser.getPage().goto(\'{step.url}\');') |
| 132 | + lines.append(f'{indent}await browser.getPage().waitForLoadState(\'networkidle\');') |
| 133 | + |
| 134 | + elif step.type == 'click': |
| 135 | + if step.selector: |
| 136 | + lines.append(f'{indent}// Click: {step.selector}') |
| 137 | + lines.append(f'{indent}const snap = await snapshot(browser);') |
| 138 | + lines.append(f'{indent}const element = find(snap, \'{step.selector}\');') |
| 139 | + lines.append(f'{indent}if (element) {{') |
| 140 | + lines.append(f'{indent} await click(browser, element.id);') |
| 141 | + lines.append(f'{indent}}} else {{') |
| 142 | + lines.append(f'{indent} throw new Error(\'Element not found: {step.selector}\');') |
| 143 | + lines.append(f'{indent}}}') |
| 144 | + elif step.element_id is not None: |
| 145 | + lines.append(f'{indent}// TODO: replace with semantic selector') |
| 146 | + lines.append(f'{indent}await click(browser, {step.element_id});') |
| 147 | + lines.append('') |
| 148 | + |
| 149 | + elif step.type == 'type': |
| 150 | + if step.selector: |
| 151 | + lines.append(f'{indent}// Type into: {step.selector}') |
| 152 | + lines.append(f'{indent}const snap = await snapshot(browser);') |
| 153 | + lines.append(f'{indent}const element = find(snap, \'{step.selector}\');') |
| 154 | + lines.append(f'{indent}if (element) {{') |
| 155 | + lines.append(f'{indent} await typeText(browser, element.id, \'{step.text}\');') |
| 156 | + lines.append(f'{indent}}} else {{') |
| 157 | + lines.append(f'{indent} throw new Error(\'Element not found: {step.selector}\');') |
| 158 | + lines.append(f'{indent}}}') |
| 159 | + elif step.element_id is not None: |
| 160 | + lines.append(f'{indent}// TODO: replace with semantic selector') |
| 161 | + lines.append(f'{indent}await typeText(browser, {step.element_id}, \'{step.text}\');') |
| 162 | + lines.append('') |
| 163 | + |
| 164 | + elif step.type == 'press': |
| 165 | + lines.append(f'{indent}// Press key: {step.key}') |
| 166 | + lines.append(f'{indent}await press(browser, \'{step.key}\');') |
| 167 | + lines.append('') |
| 168 | + |
| 169 | + return lines |
| 170 | + |
| 171 | + def save_python(self, filepath: str) -> None: |
| 172 | + """Generate and save Python script""" |
| 173 | + code = self.generate_python() |
| 174 | + with open(filepath, 'w') as f: |
| 175 | + f.write(code) |
| 176 | + |
| 177 | + def save_typescript(self, filepath: str) -> None: |
| 178 | + """Generate and save TypeScript script""" |
| 179 | + code = self.generate_typescript() |
| 180 | + with open(filepath, 'w') as f: |
| 181 | + f.write(code) |
| 182 | + |
| 183 | + |
| 184 | +def generate(trace: Trace, language: str = 'py') -> str: |
| 185 | + """ |
| 186 | + Generate script from trace |
| 187 | + |
| 188 | + Args: |
| 189 | + trace: Trace object |
| 190 | + language: 'py' or 'ts' |
| 191 | + |
| 192 | + Returns: |
| 193 | + Generated code as string |
| 194 | + """ |
| 195 | + generator = ScriptGenerator(trace) |
| 196 | + if language == 'py': |
| 197 | + return generator.generate_python() |
| 198 | + elif language == 'ts': |
| 199 | + return generator.generate_typescript() |
| 200 | + else: |
| 201 | + raise ValueError(f"Unsupported language: {language}. Use 'py' or 'ts'") |
| 202 | + |
0 commit comments