|
| 1 | +import cs50 |
| 2 | +import re |
| 3 | +from flask import Flask, abort, redirect, render_template, request |
| 4 | +from html import escape |
| 5 | +from werkzeug.exceptions import default_exceptions, HTTPException |
| 6 | + |
| 7 | +from helpers import lines, sentences, substrings |
| 8 | + |
| 9 | +# Configure application |
| 10 | +app = Flask(__name__) |
| 11 | + |
| 12 | +# Reload templates when they are changed |
| 13 | +app.config["TEMPLATES_AUTO_RELOAD"] = True |
| 14 | + |
| 15 | + |
| 16 | +@app.after_request |
| 17 | +def after_request(response): |
| 18 | + """Disable caching""" |
| 19 | + response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" |
| 20 | + response.headers["Expires"] = 0 |
| 21 | + response.headers["Pragma"] = "no-cache" |
| 22 | + return response |
| 23 | + |
| 24 | + |
| 25 | +@app.route("/") |
| 26 | +def index(): |
| 27 | + """Handle requests for / via GET (and POST)""" |
| 28 | + return render_template("index.html") |
| 29 | + |
| 30 | + |
| 31 | +@app.route("/compare", methods=["POST"]) |
| 32 | +def compare(): |
| 33 | + """Handle requests for /compare via POST""" |
| 34 | + |
| 35 | + # Read files |
| 36 | + if not request.files["file1"] or not request.files["file2"]: |
| 37 | + abort(400, "missing file") |
| 38 | + try: |
| 39 | + file1 = request.files["file1"].read().decode("utf-8") |
| 40 | + file2 = request.files["file2"].read().decode("utf-8") |
| 41 | + except Exception: |
| 42 | + abort(400, "invalid file") |
| 43 | + |
| 44 | + # Compare files |
| 45 | + if not request.form.get("algorithm"): |
| 46 | + abort(400, "missing algorithm") |
| 47 | + elif request.form.get("algorithm") == "lines": |
| 48 | + regexes = [f"^{re.escape(match)}$" for match in lines(file1, file2)] |
| 49 | + elif request.form.get("algorithm") == "sentences": |
| 50 | + regexes = [re.escape(match) for match in sentences(file1, file2)] |
| 51 | + elif request.form.get("algorithm") == "substrings": |
| 52 | + if not request.form.get("length"): |
| 53 | + abort(400, "missing length") |
| 54 | + elif not int(request.form.get("length")) > 0: |
| 55 | + abort(400, "invalid length") |
| 56 | + regexes = [re.escape(match) for match in substrings( |
| 57 | + file1, file2, int(request.form.get("length")))] |
| 58 | + else: |
| 59 | + abort(400, "invalid algorithm") |
| 60 | + |
| 61 | + # Highlight files |
| 62 | + highlights1 = highlight(file1, regexes) |
| 63 | + highlights2 = highlight(file2, regexes) |
| 64 | + |
| 65 | + # Output comparison |
| 66 | + return render_template("compare.html", file1=highlights1, file2=highlights2) |
| 67 | + |
| 68 | + |
| 69 | +def highlight(s, regexes): |
| 70 | + """Highlight all instances of regexes in s.""" |
| 71 | + |
| 72 | + # Get intervals for which strings match |
| 73 | + intervals = [] |
| 74 | + for regex in regexes: |
| 75 | + if not regex: |
| 76 | + continue |
| 77 | + matches = re.finditer(regex, s, re.MULTILINE) |
| 78 | + for match in matches: |
| 79 | + intervals.append((match.start(), match.end())) |
| 80 | + intervals.sort(key=lambda x: x[0]) |
| 81 | + |
| 82 | + # Combine intervals to get highlighted areas |
| 83 | + highlights = [] |
| 84 | + for interval in intervals: |
| 85 | + if not highlights: |
| 86 | + highlights.append(interval) |
| 87 | + continue |
| 88 | + last = highlights[-1] |
| 89 | + |
| 90 | + # If intervals overlap, then merge them |
| 91 | + if interval[0] <= last[1]: |
| 92 | + new_interval = (last[0], interval[1]) |
| 93 | + highlights[-1] = new_interval |
| 94 | + |
| 95 | + # Else, start a new highlight |
| 96 | + else: |
| 97 | + highlights.append(interval) |
| 98 | + |
| 99 | + # Maintain list of regions: each is a start index, end index, highlight |
| 100 | + regions = [] |
| 101 | + |
| 102 | + # If no highlights at all, then keep nothing highlighted |
| 103 | + if not highlights: |
| 104 | + regions = [(0, len(s), False)] |
| 105 | + |
| 106 | + # If first region is not highlighted, designate it as such |
| 107 | + elif highlights[0][0] != 0: |
| 108 | + regions = [(0, highlights[0][0], False)] |
| 109 | + |
| 110 | + # Loop through all highlights and add regions |
| 111 | + for start, end in highlights: |
| 112 | + if start != 0: |
| 113 | + prev_end = regions[-1][1] |
| 114 | + if start != prev_end: |
| 115 | + regions.append((prev_end, start, False)) |
| 116 | + regions.append((start, end, True)) |
| 117 | + |
| 118 | + # Add final unhighlighted region if necessary |
| 119 | + if regions[-1][1] != len(s): |
| 120 | + regions.append((regions[-1][1], len(s), False)) |
| 121 | + |
| 122 | + # Combine regions into final result |
| 123 | + result = "" |
| 124 | + for start, end, highlighted in regions: |
| 125 | + escaped = escape(s[start:end]) |
| 126 | + if highlighted: |
| 127 | + result += f"<span>{escaped}</span>" |
| 128 | + else: |
| 129 | + result += escaped |
| 130 | + return result |
| 131 | + |
| 132 | + |
| 133 | +@app.errorhandler(HTTPException) |
| 134 | +def errorhandler(error): |
| 135 | + """Handle errors""" |
| 136 | + return render_template("error.html", error=error), error.code |
| 137 | + |
| 138 | + |
| 139 | +# https://github.com/pallets/flask/pull/2314 |
| 140 | +for code in default_exceptions: |
| 141 | + app.errorhandler(code)(errorhandler) |
0 commit comments