tmutton commited on
Commit
e0cfb62
·
1 Parent(s): 6363c9c

Add WCAG classification training pipeline

Browse files
Files changed (9) hide show
  1. .gitignore +15 -0
  2. load_dataset.py +15 -0
  3. load_model.py +25 -0
  4. predict.py +49 -0
  5. test.csv +11 -0
  6. tokenize_dataset.py +52 -0
  7. train.csv +81 -0
  8. train_model.py +136 -0
  9. validation.csv +11 -0
.gitignore ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python virtual environment
2
+ .venv/
3
+
4
+ # Python cache
5
+ __pycache__/
6
+ *.pyc
7
+
8
+ # Hugging Face training output
9
+ results/
10
+
11
+ # Generated trained model
12
+ wcag-classifier/
13
+
14
+ # Hugging Face / dataset caches
15
+ .cache/
load_dataset.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset
2
+
3
+ dataset = load_dataset(
4
+ "csv",
5
+ data_files={
6
+ "train": "train.csv",
7
+ "validation": "validation.csv",
8
+ "test": "test.csv",
9
+ }
10
+ )
11
+
12
+ print(dataset)
13
+
14
+ print("\nFirst training example:")
15
+ print(dataset["train"][0])
load_model.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForSequenceClassification
2
+
3
+ MODEL_NAME = "distilbert-base-uncased"
4
+
5
+ id2label = {
6
+ 0: "1.3.1 Info and Relationships",
7
+ 1: "2.1.1 Keyboard",
8
+ 2: "2.4.3 Focus Order",
9
+ 3: "2.4.7 Focus Visible",
10
+ 4: "4.1.2 Name, Role, Value",
11
+ }
12
+
13
+ label2id = {
14
+ label: id
15
+ for id, label in id2label.items()
16
+ }
17
+
18
+ model = AutoModelForSequenceClassification.from_pretrained(
19
+ MODEL_NAME,
20
+ num_labels=5,
21
+ id2label=id2label,
22
+ label2id=label2id,
23
+ )
24
+
25
+ print(model.config)
predict.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from transformers import (
4
+ AutoModelForSequenceClassification,
5
+ AutoTokenizer,
6
+ )
7
+
8
+ MODEL_PATH = Path(__file__).resolve().parent / "wcag-classifier"
9
+
10
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
11
+
12
+ model = AutoModelForSequenceClassification.from_pretrained(
13
+ MODEL_PATH
14
+ )
15
+
16
+
17
+ def predict(text):
18
+ inputs = tokenizer(
19
+ text,
20
+ return_tensors="pt",
21
+ truncation=True,
22
+ )
23
+
24
+ with torch.no_grad():
25
+ outputs = model(**inputs)
26
+
27
+ probabilities = torch.softmax(
28
+ outputs.logits,
29
+ dim=-1
30
+ )[0]
31
+
32
+ predicted_id = torch.argmax(probabilities).item()
33
+
34
+ predicted_label = model.config.id2label[predicted_id]
35
+ confidence = probabilities[predicted_id].item()
36
+
37
+ return predicted_label, confidence
38
+
39
+
40
+ while True:
41
+ text = input("\nDescribe an accessibility issue (or 'quit'): ")
42
+
43
+ if text.lower() == "quit":
44
+ break
45
+
46
+ label, confidence = predict(text)
47
+
48
+ print(f"\nPrediction: {label}")
49
+ print(f"Confidence: {confidence:.1%}")
test.csv ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ text,label
2
+ Focus jumps from the navigation directly to the footer,2.4.3 Focus Order
3
+ Dropdown options cannot be selected using the keyboard,2.1.1 Keyboard
4
+ Users navigating with Tab cannot see which link is currently active,2.4.7 Focus Visible
5
+ The focus indicator disappears against the control background,2.4.7 Focus Visible
6
+ Custom switch does not expose its on or off state,"4.1.2 Name, Role, Value"
7
+ Image button has no programmatically determinable name,"4.1.2 Name, Role, Value"
8
+ Custom slider cannot be adjusted using the arrow keys,2.1.1 Keyboard
9
+ Section titles are presented using bold text instead of heading markup,1.3.1 Info and Relationships
10
+ After deleting an item focus moves to the page header instead of the next relevant control,2.4.3 Focus Order
11
+ A list of navigation links is visually presented as a list but is not marked up as one,1.3.1 Info and Relationships
tokenize_dataset.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import load_dataset
2
+ from transformers import AutoTokenizer
3
+
4
+ MODEL_NAME = "distilbert-base-uncased"
5
+
6
+ LABELS = [
7
+ "1.3.1 Info and Relationships",
8
+ "2.1.1 Keyboard",
9
+ "2.4.3 Focus Order",
10
+ "2.4.7 Focus Visible",
11
+ "4.1.2 Name, Role, Value",
12
+ ]
13
+
14
+ label2id = {label: index for index, label in enumerate(LABELS)}
15
+ id2label = {index: label for index, label in enumerate(LABELS)}
16
+
17
+ dataset = load_dataset(
18
+ "csv",
19
+ data_files={
20
+ "train": "train.csv",
21
+ "validation": "validation.csv",
22
+ "test": "test.csv",
23
+ }
24
+ )
25
+
26
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
27
+
28
+
29
+ def preprocess(example):
30
+ encoded = tokenizer(
31
+ example["text"],
32
+ truncation=True
33
+ )
34
+
35
+ encoded["label"] = label2id[example["label"]]
36
+
37
+ return encoded
38
+
39
+
40
+ tokenized_dataset = dataset.map(preprocess)
41
+
42
+ print(tokenized_dataset)
43
+
44
+ print("\nOriginal example:")
45
+ print(dataset["train"][0])
46
+
47
+ print("\nTokenized example:")
48
+ print(tokenized_dataset["train"][0])
49
+
50
+ print("\nLabels:")
51
+ for label, id in label2id.items():
52
+ print(f"{id}: {label}")
train.csv ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ text,label
2
+ Custom radio control does not expose its selected state,"4.1.2 Name, Role, Value"
3
+ Navigation items show no visual change when they receive keyboard focus,2.4.7 Focus Visible
4
+ Tabbing from the search field moves focus to an unrelated control further down the page,2.4.3 Focus Order
5
+ The custom checkbox has no visible focus styling,2.4.7 Focus Visible
6
+ The submit button does not display an outline when focused,2.4.7 Focus Visible
7
+ Keyboard users cannot operate the carousel controls,2.1.1 Keyboard
8
+ Keyboard focus on the accordion header is not visually apparent,2.4.7 Focus Visible
9
+ Keyboard focus on the menu trigger is visually indistinguishable from its default state,2.4.7 Focus Visible
10
+ Tab order does not follow the visual order of the page,2.4.3 Focus Order
11
+ Keyboard users cannot close the dialog,2.1.1 Keyboard
12
+ Table header relationships are lost when the content is accessed with a screen reader,1.3.1 Info and Relationships
13
+ Form controls are visually grouped under a heading but have no programmatic group relationship,1.3.1 Info and Relationships
14
+ Opening the menu places focus on content outside the menu,2.4.3 Focus Order
15
+ Close button is announced without an accessible name,"4.1.2 Name, Role, Value"
16
+ Keyboard focus is not visible,2.4.7 Focus Visible
17
+ The relationship between a form section heading and its controls is only conveyed visually,1.3.1 Info and Relationships
18
+ Custom control does not respond to keyboard input,2.1.1 Keyboard
19
+ Menu cannot be opened without using a mouse,2.1.1 Keyboard
20
+ Custom slider does not expose its current value to assistive technology,"4.1.2 Name, Role, Value"
21
+ The focus outline has been removed from links,2.4.7 Focus Visible
22
+ User must use a mouse to activate the control,2.1.1 Keyboard
23
+ Drag and drop control provides no keyboard method of operation,2.1.1 Keyboard
24
+ When tabbing through the form there is no indication of the active field,2.4.7 Focus Visible
25
+ The selected navigation item and the keyboard-focused navigation item look identical,2.4.7 Focus Visible
26
+ Table headers are not programmatically associated with their cells,1.3.1 Info and Relationships
27
+ Date picker can only be operated using a mouse,2.1.1 Keyboard
28
+ Navigation control can be clicked with a mouse but cannot be activated from the keyboard,2.1.1 Keyboard
29
+ Combobox does not communicate its role to screen reader users,"4.1.2 Name, Role, Value"
30
+ Interactive icon cannot receive keyboard input,2.1.1 Keyboard
31
+ Content that appears as a numbered list is not programmatically identified as a list,1.3.1 Info and Relationships
32
+ Tabbing to the search button produces no visible focus indicator,2.4.7 Focus Visible
33
+ Text is styled to look like a heading but assistive technology identifies it as ordinary text,1.3.1 Info and Relationships
34
+ Keyboard navigation moves between controls in an illogical sequence,2.4.3 Focus Order
35
+ Toggle button does not communicate whether it is pressed,"4.1.2 Name, Role, Value"
36
+ Menu button does not expose whether the menu is currently open,"4.1.2 Name, Role, Value"
37
+ The currently focused control cannot be distinguished from surrounding controls,2.4.7 Focus Visible
38
+ Interactive icons provide no visible indication when they receive focus,2.4.7 Focus Visible
39
+ Focus unexpectedly jumps back to the top of the page,2.4.3 Focus Order
40
+ User cannot select an item from the list using the keyboard,2.1.1 Keyboard
41
+ Custom dropdown does not expose whether it is expanded or collapsed,"4.1.2 Name, Role, Value"
42
+ Tab sequence does not match the logical reading order,2.4.3 Focus Order
43
+ Visually grouped checkboxes are not contained within a programmatically identified group,1.3.1 Info and Relationships
44
+ Related form fields are positioned together visually but their relationship cannot be determined programmatically,1.3.1 Info and Relationships
45
+ The carousel controls receive keyboard focus without displaying a focus indicator,2.4.7 Focus Visible
46
+ Keyboard users encounter footer links before completing the form,2.4.3 Focus Order
47
+ Custom checkbox does not expose its checked state to assistive technology,"4.1.2 Name, Role, Value"
48
+ Focus styling is missing from the custom dropdown,2.4.7 Focus Visible
49
+ Button cannot be activated using the Enter or Space key,2.1.1 Keyboard
50
+ Tooltip trigger cannot be activated from the keyboard,2.1.1 Keyboard
51
+ Focus moves to controls that are visually positioned later in the interface,2.4.3 Focus Order
52
+ Focus moves outside the modal while the dialog is still open,2.4.3 Focus Order
53
+ Interactive icon is announced without its purpose being identified,"4.1.2 Name, Role, Value"
54
+ After closing the dialog focus does not return to the control that opened it,2.4.3 Focus Order
55
+ Interactive chart controls cannot be operated without a pointing device,2.1.1 Keyboard
56
+ Items in the custom listbox cannot be selected without a mouse,2.1.1 Keyboard
57
+ Keyboard users cannot visually identify which form field currently has focus,2.4.7 Focus Visible
58
+ Focus reaches background page controls before the active dialog controls,2.4.3 Focus Order
59
+ Search icon is exposed as a button but has no accessible name,"4.1.2 Name, Role, Value"
60
+ Focus moves through form fields in an unexpected sequence,2.4.3 Focus Order
61
+ Form fields are visually grouped but the relationship is not available to assistive technology,1.3.1 Info and Relationships
62
+ Screen reader identifies the interactive element as plain text instead of a button,"4.1.2 Name, Role, Value"
63
+ Screen reader does not announce the current value of the custom range control,"4.1.2 Name, Role, Value"
64
+ Radio buttons are visually grouped but are not programmatically associated with their group label,1.3.1 Info and Relationships
65
+ Navigation submenu cannot be expanded using the keyboard,2.1.1 Keyboard
66
+ Opening the modal does not move focus into the dialog,2.4.3 Focus Order
67
+ Table cells are not associated with the appropriate row headers,1.3.1 Info and Relationships
68
+ After submitting the form focus moves to an unrelated navigation item,2.4.3 Focus Order
69
+ Button has no accessible name,"4.1.2 Name, Role, Value"
70
+ Focus moves to the footer before reaching the main content,2.4.3 Focus Order
71
+ Screen reader does not announce the state of the checkbox,"4.1.2 Name, Role, Value"
72
+ Data is arranged visually in rows and columns but no table semantics are provided,1.3.1 Info and Relationships
73
+ There is no visual indication when a navigation link receives keyboard focus,2.4.7 Focus Visible
74
+ Headings are visually styled but are not marked up as headings,1.3.1 Info and Relationships
75
+ Heading structure does not reflect the page hierarchy,1.3.1 Info and Relationships
76
+ The visual hierarchy of the content is not represented in the page markup,1.3.1 Info and Relationships
77
+ Expandable navigation control does not communicate its expanded state,"4.1.2 Name, Role, Value"
78
+ Screen reader does not identify the custom control as a button,"4.1.2 Name, Role, Value"
79
+ Keyboard focus moves behind the open dialog,2.4.3 Focus Order
80
+ A data table does not identify its column headers programmatically,1.3.1 Info and Relationships
81
+ Accordion sections cannot be expanded using keyboard controls,2.1.1 Keyboard
train_model.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from datasets import load_dataset
4
+ from sklearn.metrics import accuracy_score, precision_recall_fscore_support
5
+ from transformers import (
6
+ AutoModelForSequenceClassification,
7
+ AutoTokenizer,
8
+ DataCollatorWithPadding,
9
+ Trainer,
10
+ TrainingArguments,
11
+ )
12
+
13
+ MODEL_NAME = "distilbert-base-uncased"
14
+
15
+ LABELS = [
16
+ "1.3.1 Info and Relationships",
17
+ "2.1.1 Keyboard",
18
+ "2.4.3 Focus Order",
19
+ "2.4.7 Focus Visible",
20
+ "4.1.2 Name, Role, Value",
21
+ ]
22
+
23
+ label2id = {label: i for i, label in enumerate(LABELS)}
24
+ id2label = {i: label for i, label in enumerate(LABELS)}
25
+
26
+ # Load our CSV files
27
+ dataset = load_dataset(
28
+ "csv",
29
+ data_files={
30
+ "train": "train.csv",
31
+ "validation": "validation.csv",
32
+ "test": "test.csv",
33
+ },
34
+ )
35
+
36
+ # Load DistilBERT's tokenizer
37
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
38
+
39
+
40
+ def preprocess(example):
41
+ encoded = tokenizer(
42
+ example["text"],
43
+ truncation=True,
44
+ )
45
+
46
+ encoded["label_id"] = label2id[example["label"]]
47
+
48
+ return encoded
49
+
50
+
51
+ tokenized_dataset = dataset.map(
52
+ preprocess,
53
+ remove_columns=["text", "label"],
54
+ )
55
+
56
+ tokenized_dataset = tokenized_dataset.rename_column(
57
+ "label_id",
58
+ "labels",
59
+ )
60
+
61
+ # Pads each batch to the longest sentence in that batch
62
+ data_collator = DataCollatorWithPadding(
63
+ tokenizer=tokenizer
64
+ )
65
+
66
+ # Load pretrained DistilBERT with our new 5-class head
67
+ model = AutoModelForSequenceClassification.from_pretrained(
68
+ MODEL_NAME,
69
+ num_labels=len(LABELS),
70
+ id2label=id2label,
71
+ label2id=label2id,
72
+ )
73
+
74
+
75
+ def compute_metrics(eval_pred):
76
+ logits, labels = eval_pred
77
+
78
+ predictions = np.argmax(logits, axis=-1)
79
+
80
+ precision, recall, f1, _ = precision_recall_fscore_support(
81
+ labels,
82
+ predictions,
83
+ average="weighted",
84
+ zero_division=0,
85
+ )
86
+
87
+ accuracy = accuracy_score(
88
+ labels,
89
+ predictions,
90
+ )
91
+
92
+ return {
93
+ "accuracy": accuracy,
94
+ "precision": precision,
95
+ "recall": recall,
96
+ "f1": f1,
97
+ }
98
+
99
+
100
+ training_args = TrainingArguments(
101
+ output_dir="./results",
102
+ num_train_epochs=5,
103
+ per_device_train_batch_size=8,
104
+ per_device_eval_batch_size=8,
105
+ learning_rate=2e-5,
106
+ eval_strategy="epoch",
107
+ save_strategy="epoch",
108
+ logging_strategy="epoch",
109
+ load_best_model_at_end=True,
110
+ metric_for_best_model="f1",
111
+ )
112
+
113
+ trainer = Trainer(
114
+ model=model,
115
+ args=training_args,
116
+ train_dataset=tokenized_dataset["train"],
117
+ eval_dataset=tokenized_dataset["validation"],
118
+ data_collator=data_collator,
119
+ compute_metrics=compute_metrics,
120
+ )
121
+
122
+ print("\nStarting training...\n")
123
+
124
+ trainer.train()
125
+
126
+ print("\nEvaluating final model on test data...\n")
127
+
128
+ test_results = trainer.evaluate(
129
+ tokenized_dataset["test"]
130
+ )
131
+
132
+ print(test_results)
133
+
134
+ # Save our finished model locally
135
+ trainer.save_model("./wcag-classifier")
136
+ tokenizer.save_pretrained("./wcag-classifier")
validation.csv ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ text,label
2
+ Nested headings do not represent the structure shown visually on the page,1.3.1 Info and Relationships
3
+ Icon button does not provide an accessible name,"4.1.2 Name, Role, Value"
4
+ Focus is programmatically moved to the close button but there is no visual indication,2.4.7 Focus Visible
5
+ Modal cannot be opened using the keyboard,2.1.1 Keyboard
6
+ Required fields are indicated by visual formatting that is not programmatically available,1.3.1 Info and Relationships
7
+ Keyboard navigation reaches hidden content before visible controls,2.4.3 Focus Order
8
+ Tabbing through the page skips to the sidebar before the main content,2.4.3 Focus Order
9
+ Custom toggle responds to mouse clicks but not keyboard activation,2.1.1 Keyboard
10
+ Accordion header does not communicate whether its panel is expanded or collapsed,"4.1.2 Name, Role, Value"
11
+ Focused buttons cannot be visually distinguished from unfocused buttons,2.4.7 Focus Visible