Add WCAG classification training pipeline
Browse filesFiles changed (9)
- .gitignoreAdded+15
- load_dataset.pyAdded+15
- load_model.pyAdded+25
- predict.pyAdded+49
- test.csvAdded+11
- tokenize_dataset.pyAdded+52
- train.csvAdded+81
- train_model.pyAdded+136
- validation.csvAdded+11
123456789101112131415# Python virtual environment.venv/
# Python cache__pycache__/*.pyc
# Hugging Face training outputresults/
# Generated trained modelwcag-classifier/
# Hugging Face / dataset caches.cache/123456789101112131415from datasets import load_dataset
dataset = load_dataset( "csv", data_files={ "train": "train.csv", "validation": "validation.csv", "test": "test.csv", })
print(dataset)
print("\nFirst training example:")print(dataset["train"][0])12345678910111213141516171819202122232425from transformers import AutoModelForSequenceClassification
MODEL_NAME = "distilbert-base-uncased"
id2label = { 0: "1.3.1 Info and Relationships", 1: "2.1.1 Keyboard", 2: "2.4.3 Focus Order", 3: "2.4.7 Focus Visible", 4: "4.1.2 Name, Role, Value",}
label2id = { label: id for id, label in id2label.items()}
model = AutoModelForSequenceClassification.from_pretrained( MODEL_NAME, num_labels=5, id2label=id2label, label2id=label2id,)
print(model.config)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import torch
from transformers import ( AutoModelForSequenceClassification, AutoTokenizer,)
MODEL_PATH = Path(__file__).resolve().parent / "wcag-classifier"
tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
model = AutoModelForSequenceClassification.from_pretrained( MODEL_PATH)
def predict(text): inputs = tokenizer( text, return_tensors="pt", truncation=True, )
with torch.no_grad(): outputs = model(**inputs)
probabilities = torch.softmax( outputs.logits, dim=-1 )[0]
predicted_id = torch.argmax(probabilities).item()
predicted_label = model.config.id2label[predicted_id] confidence = probabilities[predicted_id].item()
return predicted_label, confidence
while True: text = input("\nDescribe an accessibility issue (or 'quit'): ")
if text.lower() == "quit": break
label, confidence = predict(text)
print(f"\nPrediction: {label}") print(f"Confidence: {confidence:.1%}")1234567891011text,labelFocus jumps from the navigation directly to the footer,2.4.3 Focus OrderDropdown options cannot be selected using the keyboard,2.1.1 KeyboardUsers navigating with Tab cannot see which link is currently active,2.4.7 Focus VisibleThe focus indicator disappears against the control background,2.4.7 Focus VisibleCustom switch does not expose its on or off state,"4.1.2 Name, Role, Value"Image button has no programmatically determinable name,"4.1.2 Name, Role, Value"Custom slider cannot be adjusted using the arrow keys,2.1.1 KeyboardSection titles are presented using bold text instead of heading markup,1.3.1 Info and RelationshipsAfter deleting an item focus moves to the page header instead of the next relevant control,2.4.3 Focus OrderA list of navigation links is visually presented as a list but is not marked up as one,1.3.1 Info and Relationships12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152from datasets import load_datasetfrom transformers import AutoTokenizer
MODEL_NAME = "distilbert-base-uncased"
LABELS = [ "1.3.1 Info and Relationships", "2.1.1 Keyboard", "2.4.3 Focus Order", "2.4.7 Focus Visible", "4.1.2 Name, Role, Value",]
label2id = {label: index for index, label in enumerate(LABELS)}id2label = {index: label for index, label in enumerate(LABELS)}
dataset = load_dataset( "csv", data_files={ "train": "train.csv", "validation": "validation.csv", "test": "test.csv", })
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
def preprocess(example): encoded = tokenizer( example["text"], truncation=True )
encoded["label"] = label2id[example["label"]]
return encoded
tokenized_dataset = dataset.map(preprocess)
print(tokenized_dataset)
print("\nOriginal example:")print(dataset["train"][0])
print("\nTokenized example:")print(tokenized_dataset["train"][0])
print("\nLabels:")for label, id in label2id.items(): print(f"{id}: {label}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081text,labelCustom radio control does not expose its selected state,"4.1.2 Name, Role, Value"Navigation items show no visual change when they receive keyboard focus,2.4.7 Focus VisibleTabbing from the search field moves focus to an unrelated control further down the page,2.4.3 Focus OrderThe custom checkbox has no visible focus styling,2.4.7 Focus VisibleThe submit button does not display an outline when focused,2.4.7 Focus VisibleKeyboard users cannot operate the carousel controls,2.1.1 KeyboardKeyboard focus on the accordion header is not visually apparent,2.4.7 Focus VisibleKeyboard focus on the menu trigger is visually indistinguishable from its default state,2.4.7 Focus VisibleTab order does not follow the visual order of the page,2.4.3 Focus OrderKeyboard users cannot close the dialog,2.1.1 KeyboardTable header relationships are lost when the content is accessed with a screen reader,1.3.1 Info and RelationshipsForm controls are visually grouped under a heading but have no programmatic group relationship,1.3.1 Info and RelationshipsOpening the menu places focus on content outside the menu,2.4.3 Focus OrderClose button is announced without an accessible name,"4.1.2 Name, Role, Value"Keyboard focus is not visible,2.4.7 Focus VisibleThe relationship between a form section heading and its controls is only conveyed visually,1.3.1 Info and RelationshipsCustom control does not respond to keyboard input,2.1.1 KeyboardMenu cannot be opened without using a mouse,2.1.1 KeyboardCustom slider does not expose its current value to assistive technology,"4.1.2 Name, Role, Value"The focus outline has been removed from links,2.4.7 Focus VisibleUser must use a mouse to activate the control,2.1.1 KeyboardDrag and drop control provides no keyboard method of operation,2.1.1 KeyboardWhen tabbing through the form there is no indication of the active field,2.4.7 Focus VisibleThe selected navigation item and the keyboard-focused navigation item look identical,2.4.7 Focus VisibleTable headers are not programmatically associated with their cells,1.3.1 Info and RelationshipsDate picker can only be operated using a mouse,2.1.1 KeyboardNavigation control can be clicked with a mouse but cannot be activated from the keyboard,2.1.1 KeyboardCombobox does not communicate its role to screen reader users,"4.1.2 Name, Role, Value"Interactive icon cannot receive keyboard input,2.1.1 KeyboardContent that appears as a numbered list is not programmatically identified as a list,1.3.1 Info and RelationshipsTabbing to the search button produces no visible focus indicator,2.4.7 Focus VisibleText is styled to look like a heading but assistive technology identifies it as ordinary text,1.3.1 Info and RelationshipsKeyboard navigation moves between controls in an illogical sequence,2.4.3 Focus OrderToggle button does not communicate whether it is pressed,"4.1.2 Name, Role, Value"Menu button does not expose whether the menu is currently open,"4.1.2 Name, Role, Value"The currently focused control cannot be distinguished from surrounding controls,2.4.7 Focus VisibleInteractive icons provide no visible indication when they receive focus,2.4.7 Focus VisibleFocus unexpectedly jumps back to the top of the page,2.4.3 Focus OrderUser cannot select an item from the list using the keyboard,2.1.1 KeyboardCustom dropdown does not expose whether it is expanded or collapsed,"4.1.2 Name, Role, Value"Tab sequence does not match the logical reading order,2.4.3 Focus OrderVisually grouped checkboxes are not contained within a programmatically identified group,1.3.1 Info and RelationshipsRelated form fields are positioned together visually but their relationship cannot be determined programmatically,1.3.1 Info and RelationshipsThe carousel controls receive keyboard focus without displaying a focus indicator,2.4.7 Focus VisibleKeyboard users encounter footer links before completing the form,2.4.3 Focus OrderCustom checkbox does not expose its checked state to assistive technology,"4.1.2 Name, Role, Value"Focus styling is missing from the custom dropdown,2.4.7 Focus VisibleButton cannot be activated using the Enter or Space key,2.1.1 KeyboardTooltip trigger cannot be activated from the keyboard,2.1.1 KeyboardFocus moves to controls that are visually positioned later in the interface,2.4.3 Focus OrderFocus moves outside the modal while the dialog is still open,2.4.3 Focus OrderInteractive icon is announced without its purpose being identified,"4.1.2 Name, Role, Value"After closing the dialog focus does not return to the control that opened it,2.4.3 Focus OrderInteractive chart controls cannot be operated without a pointing device,2.1.1 KeyboardItems in the custom listbox cannot be selected without a mouse,2.1.1 KeyboardKeyboard users cannot visually identify which form field currently has focus,2.4.7 Focus VisibleFocus reaches background page controls before the active dialog controls,2.4.3 Focus OrderSearch icon is exposed as a button but has no accessible name,"4.1.2 Name, Role, Value"Focus moves through form fields in an unexpected sequence,2.4.3 Focus OrderForm fields are visually grouped but the relationship is not available to assistive technology,1.3.1 Info and RelationshipsScreen reader identifies the interactive element as plain text instead of a button,"4.1.2 Name, Role, Value"Screen reader does not announce the current value of the custom range control,"4.1.2 Name, Role, Value"Radio buttons are visually grouped but are not programmatically associated with their group label,1.3.1 Info and RelationshipsNavigation submenu cannot be expanded using the keyboard,2.1.1 KeyboardOpening the modal does not move focus into the dialog,2.4.3 Focus OrderTable cells are not associated with the appropriate row headers,1.3.1 Info and RelationshipsAfter submitting the form focus moves to an unrelated navigation item,2.4.3 Focus OrderButton has no accessible name,"4.1.2 Name, Role, Value"Focus moves to the footer before reaching the main content,2.4.3 Focus OrderScreen reader does not announce the state of the checkbox,"4.1.2 Name, Role, Value"Data is arranged visually in rows and columns but no table semantics are provided,1.3.1 Info and RelationshipsThere is no visual indication when a navigation link receives keyboard focus,2.4.7 Focus VisibleHeadings are visually styled but are not marked up as headings,1.3.1 Info and RelationshipsHeading structure does not reflect the page hierarchy,1.3.1 Info and RelationshipsThe visual hierarchy of the content is not represented in the page markup,1.3.1 Info and RelationshipsExpandable navigation control does not communicate its expanded state,"4.1.2 Name, Role, Value"Screen reader does not identify the custom control as a button,"4.1.2 Name, Role, Value"Keyboard focus moves behind the open dialog,2.4.3 Focus OrderA data table does not identify its column headers programmatically,1.3.1 Info and RelationshipsAccordion sections cannot be expanded using keyboard controls,2.1.1 Keyboard123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136import numpy as np
from datasets import load_datasetfrom sklearn.metrics import accuracy_score, precision_recall_fscore_supportfrom transformers import ( AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, Trainer, TrainingArguments,)
MODEL_NAME = "distilbert-base-uncased"
LABELS = [ "1.3.1 Info and Relationships", "2.1.1 Keyboard", "2.4.3 Focus Order", "2.4.7 Focus Visible", "4.1.2 Name, Role, Value",]
label2id = {label: i for i, label in enumerate(LABELS)}id2label = {i: label for i, label in enumerate(LABELS)}
# Load our CSV filesdataset = load_dataset( "csv", data_files={ "train": "train.csv", "validation": "validation.csv", "test": "test.csv", },)
# Load DistilBERT's tokenizertokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
def preprocess(example): encoded = tokenizer( example["text"], truncation=True, )
encoded["label_id"] = label2id[example["label"]]
return encoded
tokenized_dataset = dataset.map( preprocess, remove_columns=["text", "label"],)
tokenized_dataset = tokenized_dataset.rename_column( "label_id", "labels",)
# Pads each batch to the longest sentence in that batchdata_collator = DataCollatorWithPadding( tokenizer=tokenizer)
# Load pretrained DistilBERT with our new 5-class headmodel = AutoModelForSequenceClassification.from_pretrained( MODEL_NAME, num_labels=len(LABELS), id2label=id2label, label2id=label2id,)
def compute_metrics(eval_pred): logits, labels = eval_pred
predictions = np.argmax(logits, axis=-1)
precision, recall, f1, _ = precision_recall_fscore_support( labels, predictions, average="weighted", zero_division=0, )
accuracy = accuracy_score( labels, predictions, )
return { "accuracy": accuracy, "precision": precision, "recall": recall, "f1": f1, }
training_args = TrainingArguments( output_dir="./results", num_train_epochs=5, per_device_train_batch_size=8, per_device_eval_batch_size=8, learning_rate=2e-5, eval_strategy="epoch", save_strategy="epoch", logging_strategy="epoch", load_best_model_at_end=True, metric_for_best_model="f1",)
trainer = Trainer( model=model, args=training_args, train_dataset=tokenized_dataset["train"], eval_dataset=tokenized_dataset["validation"], data_collator=data_collator, compute_metrics=compute_metrics,)
print("\nStarting training...\n")
trainer.train()
print("\nEvaluating final model on test data...\n")
test_results = trainer.evaluate( tokenized_dataset["test"])
print(test_results)
# Save our finished model locallytrainer.save_model("./wcag-classifier")tokenizer.save_pretrained("./wcag-classifier")1234567891011text,labelNested headings do not represent the structure shown visually on the page,1.3.1 Info and RelationshipsIcon button does not provide an accessible name,"4.1.2 Name, Role, Value"Focus is programmatically moved to the close button but there is no visual indication,2.4.7 Focus VisibleModal cannot be opened using the keyboard,2.1.1 KeyboardRequired fields are indicated by visual formatting that is not programmatically available,1.3.1 Info and RelationshipsKeyboard navigation reaches hidden content before visible controls,2.4.3 Focus OrderTabbing through the page skips to the sidebar before the main content,2.4.3 Focus OrderCustom toggle responds to mouse clicks but not keyboard activation,2.1.1 KeyboardAccordion header does not communicate whether its panel is expanded or collapsed,"4.1.2 Name, Role, Value"Focused buttons cannot be visually distinguished from unfocused buttons,2.4.7 Focus Visible.gitignoreAdded+15
load_dataset.pyAdded+15
load_model.pyAdded+25
predict.pyAdded+49
test.csvAdded+11
tokenize_dataset.pyAdded+52
train.csvAdded+81
train_model.pyAdded+136
validation.csvAdded+11