Metadata-Version: 2.4
Name: self-healing-elements
Version: 0.1.0
Summary: AI-powered self-healing Selenium locator engine
Author: LIKITH
Project-URL: Homepage, https://github.com/LIKITH/self-healing-elements
Keywords: selenium,self-healing,test-automation,ai,ml
Requires-Python: >=3.12
Description-Content-Type: text/markdown
Requires-Dist: selenium
Requires-Dist: pytest
Requires-Dist: fastapi
Requires-Dist: uvicorn
Requires-Dist: pydantic
Requires-Dist: beautifulsoup4
Requires-Dist: httpx
Requires-Dist: xgboost
Requires-Dist: pandas
Requires-Dist: scikit-learn
Requires-Dist: litellm

# Self-Healing Elements

```bash
pip install self-healing-elements
```

```python
from selenium import webdriver
from selenium.webdriver.common.by import By
from self_healing import SelfHealingDriver

driver = SelfHealingDriver(webdriver.Chrome())
heading = driver.find_element(By.TAG_NAME, "h1", logical_id="page_heading")
```

![Python](https://img.shields.io/badge/Python-3.11-3776AB?logo=python&logoColor=white)
![Tests](https://img.shields.io/badge/Tests-41%20Passing-brightgreen)
![License](https://img.shields.io/badge/License-MIT-blue.svg)

An AI-powered and heuristic-driven self-healing locator framework for web automation. It dynamically detects, heals, and updates broken web element locators (like XPaths and CSS Selectors) using historical attribute metadata and DOM structure analysis.

## Demo

### Quick start (local)

```powershell
# 1) From the project root
.venv\Scripts\activate

# 2) Install dependencies
pip install -r requirements.txt

# 3) Start the API locally
uvicorn src.self_healing.api:app --host 0.0.0.0 --port 8000 --reload
```

Then open:

```text
http://localhost:8000/
```

The root route displays the live dashboard with the summary panel, healing event table, and registry viewer.

### How it works

The healing flow is:

1. A locator fails or becomes stale.
2. The engine loads the stored element profile from SQLite.
3. It scans the page and measures similarity across candidate elements.
4. It blends a rule-based score with XGBoost, PyTorch, and semantic similarity scores.
5. It picks the best candidate and returns a structured explainability payload.
6. It writes the updated registry + healing history, and logs the event.

#### Example: POST /heal

Request payload:

```json
{
  "logical_id": "id:submit-btn",
  "by": "id",
  "value": "submit-btn",
  "page_source": "<html><body><button id='new-submit-btn' class='btn btn-primary' type='submit'>Submit Form</button></body></html>"
}
```

Example response:

```json
{
  "status": "HEALED",
  "logical_id": "id:submit-btn",
  "original_locator": {"type": "id", "value": "submit-btn"},
  "healed_locator": {"type": "id", "value": "new-submit-btn"},
  "confidence_score": 0.875,
  "explanation": "Successfully healed locator for 'id:submit-btn'. Matched candidate <button> with confidence score 87.50%. Generated new locator: id='new-submit-btn'.",
  "xai_breakdown": {
    "features": {
      "tag_score": 1.0,
      "text_score": 1.0,
      "class_score": 1.0,
      "attributes_score": 0.5,
      "parent_score": 1.0
    },
    "feature_importance": {
      "tag": 0.1,
      "text": 0.3,
      "class": 0.2,
      "parent": 0.15,
      "attributes": 0.125
    },
    "decision_breakdown": {
      "rule_score": 0.875,
      "xgboost_score": 0.91,
      "neural_score": 0.88,
      "semantic_score": 0.82,
      "final_blended_score": 0.875
    },
    "scores": {
      "rule_score": 0.875,
      "ml_score": 0.91,
      "nn_score": 0.88,
      "semantic_score": 0.82,
      "final_score": 0.875
    },
    "confidence_tier": "HIGH",
    "reasoning": "Final score of 87.5% exceeds the auto-healing threshold."
  }
}
```

This gives both a human-readable explanation and a machine-readable XAI payload for downstream dashboards, tooling, or analytics.

### Tech stack

| Layer | Technology | Purpose |
| --- | --- | --- |
| Rules | Heuristic matcher | Fast weighted similarity scoring for tag, text, class, attributes, and parent context |
| XGBoost | `xgboost` | Learned ranking signal for candidate prioritization |
| PyTorch | `torch` / custom neural ranker | Secondary learned model signal for confidence scoring |
| Sentence Transformers | `sentence-transformers` | Semantic similarity for text- and structure-aware matching |
| LLM | Ollama + LiteLLM | Natural-language explanation generation for healed candidates |
| API | FastAPI + Uvicorn | REST JSON API and dashboard endpoints |
| Storage | SQLite | Persistent registry of element profiles and healing history |
| Containerization | Docker + Docker Compose | Production-style deployment, persistence, and orchestration |

## Features

- **Dynamic Locator Healing**: Seamlessly falls back to backup strategies when a primary locator fails.
- **Smart DOM Similarity Matching**: Uses weighted attributes (IDs, classes, text content, tags) to find the best match for the changed element.
- **Auto-Update & Persistence**: Stores healed locators back into a local registry to make future runs faster.
- **Detailed Healing Logs**: Outputs diagnostic reports explaining why a locator was healed and the confidence score.

## Directory Structure

```text
self-healing-elements/
├── docs/               # Architecture, roadmap, problem statements
├── src/self_healing/   # Package source code
│   └── __init__.py
├── tests/              # Automated test suites
├── .gitignore          # Git exclusion rules
├── README.md           # Project overview
└── requirements.txt    # Project dependencies
```

## Getting Started

1. Activate your virtual environment:
   ```powershell
   .venv\Scripts\activate
   ```
2. Install dependencies:
   ```powershell
   pip install -r requirements.txt
   ```
3. Run tests:
   ```powershell
   pytest
   ```

## Docker / Compose

This repository includes a production-style Docker stack with a FastAPI API, background retraining worker, Nginx reverse proxy, and local Ollama service.

### Production stack

```bash
cp .env.example .env
make build
make up
```

Then open the app through Nginx:

```text
http://localhost/
```

### Local development override

```bash
cp .env.example .env
docker compose -f docker-compose.yml -f docker-compose.override.yml up --build
```

This runs the dev stack with the app surfaced on:

```text
http://localhost:8000/
```

### Useful commands

```bash
make logs
make test
make train
docker compose down -v
```

> Note: `make down` and `docker compose down -v` remove the named volumes, so use them carefully if you want to preserve registry or model state.

### TLS certificate note for HTTPS

The HTTPS-enabled Nginx config expects a certificate pair in `./certs`:

```bash
mkdir -p certs
openssl req -x509 -nodes -newkey rsa:2048 \
  -keyout certs/server.key \
  -out certs/server.crt \
  -days 365 \
  -subj "/CN=localhost"
```

Then start the stack with the TLS config mounted by `docker-compose.override.yml`.

---

## Docker notes

- Named volumes persist the registry, healing event log, and trained model artifacts across restarts.
- The API reads/writes SQLite state from `/data/registry` and logs from `/data/logs`.
- The worker retrains from stored healing history and writes model artifacts to `/data/models`.
- The local LLM service is exposed internally at `http://ollama:11434` for explanation generation.

## Features

- **Dynamic Locator Healing**: Seamlessly falls back to backup strategies when a primary locator fails.
- **Smart DOM Similarity Matching**: Uses weighted attributes (IDs, classes, text content, tags) to find the best match for the changed element.
- **Auto-Update & Persistence**: Stores healed locators back into a local registry to make future runs faster.
- **Detailed Healing Logs**: Outputs diagnostic reports explaining why a locator was healed and the confidence score.

## Directory Structure

```text
self-healing-elements/
├── docs/               # Architecture, roadmap, problem statements
├── src/self_healing/   # Package source code
│   └── __init__.py
├── tests/              # Automated test suites
├── .gitignore          # Git exclusion rules
├── README.md           # Project overview
└── requirements.txt    # Project dependencies
```

## Getting Started

1. Activate your virtual environment:
   ```powershell
   .venv\Scripts\activate
   ```
2. Install dependencies:
   ```powershell
   pip install -r requirements.txt
   ```
3. Run tests:
   ```powershell
   pytest
   ```

## Docker / Compose

This repository includes a production-style Docker stack with a FastAPI API, background retraining worker, Nginx reverse proxy, and local Ollama service.

### Production stack

```bash
cp .env.example .env
make build
make up
```

Then open the app through Nginx:

```text
http://localhost/
```

### Local development override

```bash
cp .env.example .env
docker compose -f docker-compose.yml -f docker-compose.override.yml up --build
```

This runs the dev stack with the app surfaced on:

```text
http://localhost:8000/
```

### Useful commands

```bash
make logs
make test
make train
t docker compose down -v
```

> Note: `make down` and `docker compose down -v` remove the named volumes, so use them carefully if you want to preserve registry or model state.

### TLS certificate note for HTTPS

The HTTPS-enabled Nginx config expects a certificate pair in `./certs`:

```bash
mkdir -p certs
openssl req -x509 -nodes -newkey rsa:2048 \
  -keyout certs/server.key \
  -out certs/server.crt \
  -days 365 \
  -subj "/CN=localhost"
```

Then start the stack with the TLS config mounted by `docker-compose.override.yml`.

---

## Docker notes

- Named volumes persist the registry, healing event log, and trained model artifacts across restarts.
- The API reads/writes SQLite state from `/data/registry` and logs from `/data/logs`.
- The worker retrains from stored healing history and writes model artifacts to `/data/models`.
- The local LLM service is exposed internally at `http://ollama:11434` for explanation generation.
