📦 EqualifyEverything / equalify-uic-analysis

📄 equalify-uic-analysis.py · 139 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139# === Open Source Software ===
# This program is maintained by the University of Illinois Chicago Accessibility
# Engineering Team (https://uic.edu/accessibility/engineering).
# Copyright (C) 2025  University of Illinois Chicago.

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program. 

# Basin Imports
import csv
import json
import os
import time
import requests
import logging

# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

INPUT_CSV = "input.csv"
OUTPUT_CSV = "output.csv"
RESULTS_DIR = "results"
SCAN_URL = "https://scan-dev.equalify.app/generate/urls"
JOB_URL_BASE = "https://scan-dev.equalify.app/"

os.makedirs(RESULTS_DIR, exist_ok=True)

def read_input_csv():
    with open(INPUT_CSV, newline='', encoding='utf-8') as csvfile:
        reader = list(csv.DictReader(csvfile))
    logging.info(f"Read {len(reader)} rows from {INPUT_CSV}")
    return reader

def write_output_csv(rows, fieldnames):
    with open(OUTPUT_CSV, mode='w', newline='', encoding='utf-8') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)
    logging.info(f"Wrote results to {OUTPUT_CSV}")

def send_scan_request(urls, mode=None):
    logging.info(f"Sending scan request for {len(urls)} URLs with mode={mode}")
    body = {"urls": [{"url": url} for url in urls]}
    if mode:
        body["mode"] = mode
    try:
        response = requests.post(SCAN_URL, json=body)
        response.raise_for_status()
        jobs = response.json().get("jobs", [])
        logging.info(f"Received response with {len(jobs)} jobs")
        return jobs
    except Exception as e:
        return {"error": str(e)}

def poll_job_result(job_id):
    result_url = f"{JOB_URL_BASE}results/axe/{job_id}"
    logging.info(f"Requesting scan result from {result_url}")
    logging.info(f"Polling job result for job_id={job_id}")
    for attempt in range(6):
        try:
            response = requests.get(result_url)
            if response.ok:
                logging.info(f"Received {len(response.text)} characters in response")
                result = response.json()
                status = result.get("status")
                if status == "completed":
                    logging.info(f"Job {job_id} status is completed at attempt {attempt+1}")
                    return result
                else:
                    logging.info(f"Job {job_id} status is {status}")
        except Exception as e:
            logging.warning(f"Attempt {attempt+1} failed for job {job_id}: {e}")
        logging.info(f"Checked job {job_id}, attempt {attempt+1}")
        time.sleep(10)
    return None

def main():
    input_rows = read_input_csv()
    output_rows = []

    for idx, row in enumerate(input_rows):
        url_type = row["Link Type"].strip().lower()
        url = row["URL"].strip()
        logging.info(f"Processing row {idx+1}/{len(input_rows)}: {url}")
        row["Equalify Scan Results"] = ""
        row["Notes"] = ""

        if not url:
            row["Notes"] = "Missing URL"
            output_rows.append(row)
            continue

        mode = "verapdf" if url_type == "pdf" else None
        jobs = send_scan_request([url], mode=mode)

        if isinstance(jobs, dict) and "error" in jobs:
            row["Notes"] = f"Error during scan request: {jobs['error']}"
            output_rows.append(row)
            continue

        if not jobs:
            row["Notes"] = "No job returned from scan"
            output_rows.append(row)
            continue

        job_id = jobs[0].get("jobId")
        if not job_id:
            row["Notes"] = "No jobId found"
            output_rows.append(row)
            continue

        result = poll_job_result(job_id)
        if result:
            filename = f"{job_id}.json"
            filepath = os.path.join(RESULTS_DIR, filename)
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(result, f, indent=2)
            logging.info(f"Saved scan result to {filepath}")
            row["Equalify Scan Results"] = filename
        else:
            logging.error(f"Failed to get results for job {job_id}")
            row["Notes"] = "Scan timed out or failed"

        output_rows.append(row)

    write_output_csv(output_rows, input_rows[0].keys())

if __name__ == "__main__":
    main()