📦 EqualifyEverything / equalify-uic-analysis

📄 equalify-uic-analysis.py · 184 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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184# === 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, "flags": "scanAsPdf"} if mode == "verapdf" else {"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
                if status == "failed":
                    logging.info(f"Job {job_id} status is failed")
                    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():
    from collections import defaultdict

    def chunked(iterable, size):
        for i in range(0, len(iterable), size):
            yield iterable[i:i + size]

    input_rows = read_input_csv()
    processed_urls = set()
    file_exists = os.path.exists(OUTPUT_CSV)
    if file_exists:
        with open(OUTPUT_CSV, newline='', encoding='utf-8') as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                if row.get("Equalify Scan Results") or row.get("Notes"):
                    processed_urls.add(row["URL"])
        logging.info(f"Skipping {len(processed_urls)} previously processed URLs")

    url_to_row = {}
    pdf_urls = []
    html_urls = []

    with open(OUTPUT_CSV, mode='a', newline='', encoding='utf-8') as csvfile:
        fieldnames = list(input_rows[0].keys()) + ["Equalify Scan Results", "Notes"]
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        if not file_exists or os.stat(OUTPUT_CSV).st_size == 0:
            writer.writeheader()

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

            if url in processed_urls:
                logging.info(f"Skipping already processed URL: {url}")
                continue

            if not url:
                row["Notes"] = "Missing URL"

            elif url_type == "box":
                row["Notes"] = "Box links aren't accessible."

            else:
                if url_type == "pdf":
                    pdf_urls.append(url)
                else:
                    html_urls.append(url)
            url_to_row[url] = row

        for url_list, mode in [(pdf_urls, "verapdf"), (html_urls, None)]:
            for chunk in chunked(url_list, 100):
                jobs = send_scan_request(chunk, mode=mode)
                if isinstance(jobs, dict) and "error" in jobs:
                    for url in chunk:
                        row = url_to_row[url]
                        row["Notes"] = f"Error during scan request: {jobs['error']}"
                        writer.writerow(row)
                    continue
                if not jobs:
                    for url in chunk:
                        row = url_to_row[url]
                        row["Notes"] = "No job returned from scan"
                        writer.writerow(row)
                    continue
                for job in jobs:
                    url = job.get("url")
                    job_id = job.get("jobId")
                    row = url_to_row[url]
                    if not job_id:
                        row["Notes"] = "No jobId found"
                        writer.writerow(row)
                        continue
                    result = poll_job_result(job_id)
                    if result:
                        if result.get("status") == "completed":
                            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.info(f"Scan job {job_id} returned status: {result.get('status')}")
                            row["Notes"] = f"Scan {result.get('status')}"
                    else:
                        logging.error(f"Failed to get results for job {job_id}")
                        row["Notes"] = "Scan timed out or failed"
                    writer.writerow(row) 

if __name__ == "__main__":
    main()