sridharKikkeri commited on
Commit
1b288b8
·
verified ·
1 Parent(s): 3a64849

Create SelfHealing.py

Browse files
Files changed (1) hide show
  1. SelfHealing.py +61 -0
SelfHealing.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import LlamaForCausalLM, LlamaTokenizer
2
+ import torch
3
+ from playwright.sync_api import sync_playwright
4
+
5
+ # Load LLaMA 2 model and tokenizer
6
+ model_name = "meta-llama/Llama-2-7b-hf" # Use appropriate LLaMA 2 model variant
7
+ tokenizer = LlamaTokenizer.from_pretrained(model_name)
8
+ model = LlamaForCausalLM.from_pretrained(model_name)
9
+
10
+ # Example function to generate alternative locators using LLaMA 2
11
+ def generate_alternative_locators(html_content, failed_locator):
12
+ prompt = f"""
13
+ The following HTML structure contains a failing locator: "{failed_locator}".
14
+ Suggest alternative XPaths or CSS selectors that could identify the same element.
15
+
16
+ HTML:
17
+ {html_content}
18
+ """
19
+
20
+ inputs = tokenizer(prompt, return_tensors="pt")
21
+ outputs = model.generate(inputs["input_ids"], max_length=500)
22
+
23
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
24
+ suggestions = response.split("\n") # Assuming each suggestion is on a new line
25
+
26
+ return suggestions
27
+
28
+ # Example of self-healing process using Playwright and LLaMA 2 suggestions
29
+ def attempt_self_healing(page, failed_locator: str):
30
+ # Retrieve HTML of the page
31
+ html = page.content()
32
+
33
+ # Get alternative locators from LLaMA 2
34
+ suggestions = generate_alternative_locators(html, failed_locator)
35
+ print("Suggested alternatives:", suggestions)
36
+
37
+ # Attempt to click with alternative locators
38
+ for locator in suggestions:
39
+ try:
40
+ page.locator(locator.strip()).click()
41
+ print(f"Self-healing successful with locator: {locator}")
42
+ return
43
+ except Exception as e:
44
+ print(f"Locator failed: {locator}, Error: {e}")
45
+
46
+ print("Self-healing failed. No valid locator found.")
47
+
48
+ # Main Playwright script
49
+ with sync_playwright() as p:
50
+ browser = p.chromium.launch()
51
+ page = browser.new_page()
52
+
53
+ page.goto("https://example.com")
54
+
55
+ # Assume we know the failed locator
56
+ failed_locator = "//button[@id='non-existent-button']"
57
+
58
+ # Try to heal the test
59
+ attempt_self_healing(page, failed_locator)
60
+
61
+ browser.close()