dejanseo commited on
Commit
7d5fa87
Β·
verified Β·
1 Parent(s): 109edc7

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +128 -121
README.md CHANGED
@@ -1,121 +1,128 @@
1
- # Link Anchor Detection Model
2
-
3
- A fine-tuned DeBERTa v3 model that predicts which words in text should be hyperlinks. Trained on 10,273 pages scraped from [The Keyword](https://blog.google/) (Google's official blog), where editorial linking decisions serve as ground truth labels.
4
-
5
- ## How It Works
6
-
7
- Given raw text, the model performs token-level binary classification β€” each token is labeled `LINK` or `O` (not a link). This identifies anchor text candidates: words that a human editor would likely hyperlink.
8
-
9
- ## Pipeline
10
-
11
- ```
12
- sitemap.xml (10,274 URLs from blog.google)
13
- β”‚
14
- β–Ό
15
- scrape.py ──► scraped.db (SQLite, 10,273 pages with markdown + inline links)
16
- β”‚
17
- β–Ό
18
- _prep.py ──► train_windows.jsonl / val_windows.jsonl
19
- β”‚ β€’ Strip markdown, annotate link spans as [LINK_START]...[LINK_END]
20
- β”‚ β€’ Tokenize with DeBERTa, align labels to tokens
21
- β”‚ β€’ Sliding windows (512 tokens, stride 128)
22
- β”‚ β€’ 90/10 doc-level split
23
- β–Ό
24
- train.py ──► model_link_token_cls/
25
- β”‚ β€’ Fine-tune microsoft/mdeberta-v3-base
26
- β”‚ β€’ Weighted cross-entropy (~25x for minority class)
27
- β”‚ β€’ 3 epochs, lr 2e-5, batch 16
28
- β–Ό
29
- app.py ──► Streamlit UI
30
- β€’ Sliding-window inference (handles any text length)
31
- β€’ Word-level highlighting with confidence scores
32
- ```
33
-
34
- ## Data
35
-
36
- Source: [blog.google](https://blog.google/) sitemap (The Keyword β€” Google's product and technology blog).
37
-
38
- | Metric | Value |
39
- |---|---|
40
- | Pages scraped | 10,273 |
41
- | Total tokens | 8.2M |
42
- | Link tokens | 286,799 (3.48%) |
43
- | Training windows | 21,264 |
44
- | Validation windows | 2,402 |
45
-
46
- The class imbalance (96.5% non-link vs 3.5% link) is handled with weighted cross-entropy loss during training.
47
-
48
- ## Model
49
-
50
- - **Base**: `microsoft/mdeberta-v3-base` (DebertaV2ForTokenClassification)
51
- - **Labels**: `O` (0), `LINK` (1)
52
- - **Max position**: 512 tokens
53
- - **Parameters**: 12 layers, 768 hidden, 12 attention heads
54
-
55
- ### Evaluation Results
56
-
57
- | Metric | Value |
58
- |---|---|
59
- | Accuracy | 95.6% |
60
- | Precision | 42.4% |
61
- | Recall | 79.5% |
62
- | F1 | 0.553 |
63
-
64
- High recall means the model catches most link-worthy text. Lower precision reflects the inherent ambiguity β€” many words *could* be linked, so "false positives" are often reasonable candidates.
65
-
66
- ## Usage
67
-
68
- ### Streamlit App
69
-
70
- ```bash
71
- streamlit run app.py
72
- ```
73
-
74
- Paste text, adjust the confidence threshold, and see predicted link anchors highlighted in green.
75
-
76
- ### Python
77
-
78
- ```python
79
- from transformers import AutoTokenizer, AutoModelForTokenClassification
80
- import torch
81
- import torch.nn.functional as F
82
-
83
- tokenizer = AutoTokenizer.from_pretrained("model_link_token_cls")
84
- model = AutoModelForTokenClassification.from_pretrained("model_link_token_cls")
85
- model.eval()
86
-
87
- text = "Google announced new features for Search and Gmail today."
88
- enc = tokenizer(text, return_tensors="pt", return_offsets_mapping=True)
89
- with torch.no_grad():
90
- logits = model(input_ids=enc["input_ids"], attention_mask=enc["attention_mask"]).logits
91
- probs = F.softmax(logits, dim=-1)[0, :, 1] # P(LINK) per token
92
-
93
- for token, offset, p in zip(
94
- tokenizer.convert_ids_to_tokens(enc["input_ids"][0]),
95
- enc["offset_mapping"][0],
96
- probs
97
- ):
98
- if offset[0] == offset[1]:
99
- continue # skip special tokens
100
- if p > 0.5:
101
- print(f" LINK: {text[offset[0]:offset[1]]} ({p:.2%})")
102
- ```
103
-
104
- ## Scripts
105
-
106
- | File | Purpose |
107
- |---|---|
108
- | `scrape.py` | Async Playwright scraper; reads sitemap.xml, saves to SQLite + markdown files |
109
- | `_prep.py` | Cleans markdown, annotates link spans, tokenizes, creates sliding windows |
110
- | `train.py` | Fine-tunes DeBERTa with weighted loss, W&B tracking |
111
- | `app.py` | Streamlit inference app with sliding-window support |
112
- | `_count.py` | Token length analysis utility |
113
- | `_detok.py` | Token ID decoder (Streamlit) |
114
-
115
- ## Requirements
116
-
117
- - Python 3.8+
118
- - PyTorch
119
- - Transformers
120
- - Playwright (for scraping)
121
- - Streamlit (for inference app)
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model:
3
+ - microsoft/deberta-v3-base
4
+ pipeline_tag: token-classification
5
+ tags:
6
+ - links
7
+ ---
8
+ # Link Anchor Detection Model
9
+
10
+ A fine-tuned DeBERTa v3 model that predicts which words in text should be hyperlinks. Trained on 10,273 pages scraped from [The Keyword](https://blog.google/) (Google's official blog), where editorial linking decisions serve as ground truth labels.
11
+
12
+ ## How It Works
13
+
14
+ Given raw text, the model performs token-level binary classification β€” each token is labeled `LINK` or `O` (not a link). This identifies anchor text candidates: words that a human editor would likely hyperlink.
15
+
16
+ ## Pipeline
17
+
18
+ ```
19
+ sitemap.xml (10,274 URLs from blog.google)
20
+ β”‚
21
+ β–Ό
22
+ scrape.py ──► scraped.db (SQLite, 10,273 pages with markdown + inline links)
23
+ β”‚
24
+ β–Ό
25
+ _prep.py ──► train_windows.jsonl / val_windows.jsonl
26
+ β”‚ β€’ Strip markdown, annotate link spans as [LINK_START]...[LINK_END]
27
+ β”‚ β€’ Tokenize with DeBERTa, align labels to tokens
28
+ β”‚ β€’ Sliding windows (512 tokens, stride 128)
29
+ β”‚ β€’ 90/10 doc-level split
30
+ β–Ό
31
+ train.py ──► model_link_token_cls/
32
+ β”‚ β€’ Fine-tune microsoft/mdeberta-v3-base
33
+ β”‚ β€’ Weighted cross-entropy (~25x for minority class)
34
+ β”‚ β€’ 3 epochs, lr 2e-5, batch 16
35
+ β–Ό
36
+ app.py ──► Streamlit UI
37
+ β€’ Sliding-window inference (handles any text length)
38
+ β€’ Word-level highlighting with confidence scores
39
+ ```
40
+
41
+ ## Data
42
+
43
+ Source: [blog.google](https://blog.google/) sitemap (The Keyword β€” Google's product and technology blog).
44
+
45
+ | Metric | Value |
46
+ |---|---|
47
+ | Pages scraped | 10,273 |
48
+ | Total tokens | 8.2M |
49
+ | Link tokens | 286,799 (3.48%) |
50
+ | Training windows | 21,264 |
51
+ | Validation windows | 2,402 |
52
+
53
+ The class imbalance (96.5% non-link vs 3.5% link) is handled with weighted cross-entropy loss during training.
54
+
55
+ ## Model
56
+
57
+ - **Base**: `microsoft/mdeberta-v3-base` (DebertaV2ForTokenClassification)
58
+ - **Labels**: `O` (0), `LINK` (1)
59
+ - **Max position**: 512 tokens
60
+ - **Parameters**: 12 layers, 768 hidden, 12 attention heads
61
+
62
+ ### Evaluation Results
63
+
64
+ | Metric | Value |
65
+ |---|---|
66
+ | Accuracy | 95.6% |
67
+ | Precision | 42.4% |
68
+ | Recall | 79.5% |
69
+ | F1 | 0.553 |
70
+
71
+ High recall means the model catches most link-worthy text. Lower precision reflects the inherent ambiguity β€” many words *could* be linked, so "false positives" are often reasonable candidates.
72
+
73
+ ## Usage
74
+
75
+ ### Streamlit App
76
+
77
+ ```bash
78
+ streamlit run app.py
79
+ ```
80
+
81
+ Paste text, adjust the confidence threshold, and see predicted link anchors highlighted in green.
82
+
83
+ ### Python
84
+
85
+ ```python
86
+ from transformers import AutoTokenizer, AutoModelForTokenClassification
87
+ import torch
88
+ import torch.nn.functional as F
89
+
90
+ tokenizer = AutoTokenizer.from_pretrained("model_link_token_cls")
91
+ model = AutoModelForTokenClassification.from_pretrained("model_link_token_cls")
92
+ model.eval()
93
+
94
+ text = "Google announced new features for Search and Gmail today."
95
+ enc = tokenizer(text, return_tensors="pt", return_offsets_mapping=True)
96
+ with torch.no_grad():
97
+ logits = model(input_ids=enc["input_ids"], attention_mask=enc["attention_mask"]).logits
98
+ probs = F.softmax(logits, dim=-1)[0, :, 1] # P(LINK) per token
99
+
100
+ for token, offset, p in zip(
101
+ tokenizer.convert_ids_to_tokens(enc["input_ids"][0]),
102
+ enc["offset_mapping"][0],
103
+ probs
104
+ ):
105
+ if offset[0] == offset[1]:
106
+ continue # skip special tokens
107
+ if p > 0.5:
108
+ print(f" LINK: {text[offset[0]:offset[1]]} ({p:.2%})")
109
+ ```
110
+
111
+ ## Scripts
112
+
113
+ | File | Purpose |
114
+ |---|---|
115
+ | `scrape.py` | Async Playwright scraper; reads sitemap.xml, saves to SQLite + markdown files |
116
+ | `_prep.py` | Cleans markdown, annotates link spans, tokenizes, creates sliding windows |
117
+ | `train.py` | Fine-tunes DeBERTa with weighted loss, W&B tracking |
118
+ | `app.py` | Streamlit inference app with sliding-window support |
119
+ | `_count.py` | Token length analysis utility |
120
+ | `_detok.py` | Token ID decoder (Streamlit) |
121
+
122
+ ## Requirements
123
+
124
+ - Python 3.8+
125
+ - PyTorch
126
+ - Transformers
127
+ - Playwright (for scraping)
128
+ - Streamlit (for inference app)