From c1237ced7be67866249446ae3be43ffa44fd8bd8 Mon Sep 17 00:00:00 2001 From: Subhrajit Prusty Date: Sat, 28 Oct 2023 23:28:15 +0530 Subject: [PATCH] lint: black --- app.py | 121 ++++++++++++++++++++++++--------------------- setup.py | 70 +++++++++++++------------- tools/gradient.py | 2 +- tools/points.py | 11 +++-- tools/shapes.py | 52 ++++++++++--------- tools/wallpaper.py | 85 ++++++++++++++++++++++--------- wallgen.py | 25 +++------- 7 files changed, 204 insertions(+), 162 deletions(-) diff --git a/app.py b/app.py index 7a14665..9082010 100644 --- a/app.py +++ b/app.py @@ -17,35 +17,35 @@ genTriangle, nGradient, random_gradient, - swirl_image) + swirl_image, +) UPLOAD_FOLDER = os.path.join("static", "upload") -ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg']) +ALLOWED_EXTENSIONS = set(["png", "jpg", "jpeg"]) app = Flask(__name__, static_url_path="/static") -app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER -app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024 +app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER +app.config["MAX_CONTENT_LENGTH"] = 5 * 1024 * 1024 def allowed_file(filename): - return '.' in filename and \ - filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS + return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS -@app.route("/", methods=['GET']) +@app.route("/", methods=["GET"]) def index(): return render_template("home.html") -@app.route("/poly", methods=['GET', 'POST']) +@app.route("/poly", methods=["GET", "POST"]) def poly(): - if request.method == 'POST': + if request.method == "POST": # get data - side = int(request.form.get('side')) - np = int(request.form.get('np')) - outline = request.form.get('outline') - bgtype = request.form.get('bgtype') - swirl = request.form.get('swirl') + side = int(request.form.get("side")) + np = int(request.form.get("np")) + outline = request.form.get("outline") + bgtype = request.form.get("bgtype") + swirl = request.form.get("swirl") error = None @@ -55,7 +55,7 @@ def poly(): error = "WARNING: Too less points OR too many points" fname = "wall-{}.png".format(int(time.time())) - fpath = 'static/images/' + fname + fpath = "static/images/" + fname shift = side // 10 nside = side + shift * 2 # increase size to prevent underflow @@ -65,11 +65,11 @@ def poly(): if bgtype == "nbyn": img = NbyNGradient(nside) elif bgtype == "customColors": - nColors = request.form.get('nColors') + nColors = request.form.get("nColors") colors = [] for i in range(int(nColors)): - colors.append(request.form.get('rgb' + str(i + 1))) + colors.append(request.form.get("rgb" + str(i + 1))) try: colors = [tuple(bytes.fromhex(x[1:])) for x in colors] @@ -81,7 +81,7 @@ def poly(): if error is not None: print(error) - return render_template('error.html', context=error) + return render_template("error.html", context=error) if outline: outline = tuple(bytes.fromhex("#2c2c2c"[1:])) @@ -97,20 +97,20 @@ def poly(): # print(fpath) img.save(fpath) - imgurl = url_for('static', filename='images/' + fname) + imgurl = url_for("static", filename="images/" + fname) return render_template("download.html", context=imgurl, home="poly") else: - return render_template('poly.html') + return render_template("poly.html") -@app.route("/shape", methods=['GET', 'POST']) +@app.route("/shape", methods=["GET", "POST"]) def shape(): - if request.method == 'POST': - side = int(request.form.get('side')) - outline = request.form.get('outline') - bgtype = request.form.get('bgtype') - swirl = request.form.get('swirl') - shape = request.form.get('shape') + if request.method == "POST": + side = int(request.form.get("side")) + outline = request.form.get("outline") + bgtype = request.form.get("bgtype") + swirl = request.form.get("swirl") + shape = request.form.get("shape") error = None @@ -118,18 +118,18 @@ def shape(): error = "WARNING: Image too large OR Image too small" fname = "wall-{}.png".format(int(time.time())) - fpath = 'static/images/' + fname + fpath = "static/images/" + fname img = random_gradient(side) if bgtype == "nbyn": img = NbyNGradient(side) elif bgtype == "customColors": - nColors = request.form.get('nColors') + nColors = request.form.get("nColors") colors = [] for i in range(int(nColors)): - colors.append(request.form.get('rgb' + str(i + 1))) + colors.append(request.form.get("rgb" + str(i + 1))) try: colors = [tuple(bytes.fromhex(x[1:])) for x in colors] @@ -141,7 +141,7 @@ def shape(): if error is not None: print(error) - return render_template('error.html', context=error) + return render_template("error.html", context=error) if outline: outline = tuple(bytes.fromhex("#2c2c2c"[1:])) @@ -151,34 +151,34 @@ def shape(): if swirl: img = swirl_image(img) - if shape == 'hexagon': + if shape == "hexagon": img = genHexagon(side, side, img, outline, per=5) - elif shape == 'squares': + elif shape == "squares": img = genSquares(side, side, img, outline, per=5) - elif shape == 'diamond': + elif shape == "diamond": img = genDiamond(side, side, img, outline, per=5) - elif shape == 'triangle': + elif shape == "triangle": img = genTriangle(side, side, img, outline, per=5) - elif shape == 'isometric': + elif shape == "isometric": img = genIsometric(side, side, img, outline, per=5) # print(fpath) img.save(fpath) - imgurl = url_for('static', filename='images/' + fname) + imgurl = url_for("static", filename="images/" + fname) return render_template("download.html", context=imgurl, home="shape") else: - return render_template('shape.html') + return render_template("shape.html") -@app.route("/pic", methods=['GET', 'POST']) +@app.route("/pic", methods=["GET", "POST"]) def pic(): - if request.method == 'POST': + if request.method == "POST": # print(request.files) # print(request.form) - if 'image' not in request.files: + if "image" not in request.files: error = "No file part" return render_template("error.html", context=error) else: - file = request.files['image'] + file = request.files["image"] # print(file.filename) # print(len(file.filename)) if len(file.filename) < 1: @@ -187,11 +187,11 @@ def pic(): if file and allowed_file(file.filename): filename = secure_filename(file.filename) - ufpath = os.path.join(app.config['UPLOAD_FOLDER'], filename) + ufpath = os.path.join(app.config["UPLOAD_FOLDER"], filename) file.save(ufpath) - np = request.form.get('np') - outline = request.form.get('outline') - smart = request.form.get('smart') + np = request.form.get("np") + outline = request.form.get("outline") + smart = request.form.get("smart") if np or smart: og_img = Image.open(ufpath) @@ -203,8 +203,8 @@ def pic(): else: scale = 1 img = og_img.resize( - (width // scale, height // scale), - resample=Image.BICUBIC) + (width // scale, height // scale), resample=Image.BICUBIC + ) width = img.width height = img.height wshift = width // 100 @@ -225,17 +225,24 @@ def pic(): else: pts = genPoints(int(np), n_width, n_height) - img = genPoly(img.width, img.height, img, pts, - wshift, hshift, outline, pic=True) + img = genPoly( + img.width, + img.height, + img, + pts, + wshift, + hshift, + outline, + pic=True, + ) fname = "wall-{}.png".format(int(time.time())) - fpath = 'static/images/' + fname + fpath = "static/images/" + fname # print(fpath) img.save(fpath) - imgurl = url_for('static', filename='images/' + fname) - return render_template( - "download.html", context=imgurl, home="pic") + imgurl = url_for("static", filename="images/" + fname) + return render_template("download.html", context=imgurl, home="pic") else: error = "Invalid input, try again" return render_template("error.html", context=error) @@ -246,8 +253,8 @@ def pic(): return render_template("pic.html") -if __name__ == '__main__': - port = int(os.environ.get('PORT', 5000)) - http_server = WSGIServer(('', port), app) +if __name__ == "__main__": + port = int(os.environ.get("PORT", 5000)) + http_server = WSGIServer(("", port), app) print("Starting server:") http_server.serve_forever() diff --git a/setup.py b/setup.py index 4d2298e..ec7c5ed 100644 --- a/setup.py +++ b/setup.py @@ -7,46 +7,46 @@ def readme(): try: - with open('README.md') as f: + with open("README.md") as f: return f.read() except BaseException: pass -setup(name='wallgen', - version='1.0', - description='Generate low poly wallpapers', - long_description=readme(), - long_description_content_type='text/markdown', - - author='Subhrajit Prusty', - author_email='subhrajit1997@gmail.com', - url='http://github.com/SubhrajitPrusty/wallgen', - - setup_requires=['setuptools>=40.0.0'], - - classifiers=[ - 'Development Status :: 4 - Beta', - - 'Intended Audience :: Developers', - 'Topic :: Software Development :: Build Tools', - - 'License :: OSI Approved :: MIT License', - - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6', - ], - - keywords='image PIL wallpaper theme', - license='MIT', - packages=find_packages(), - install_requires=['pillow', 'click', 'scipy', - 'numpy', 'Cython', 'scikit-image', - 'loguru'], - entry_points=""" +setup( + name="wallgen", + version="1.0", + description="Generate low poly wallpapers", + long_description=readme(), + long_description_content_type="text/markdown", + author="Subhrajit Prusty", + author_email="subhrajit1997@gmail.com", + url="http://github.com/SubhrajitPrusty/wallgen", + setup_requires=["setuptools>=40.0.0"], + classifiers=[ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Topic :: Software Development :: Build Tools", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", + ], + keywords="image PIL wallpaper theme", + license="MIT", + packages=find_packages(), + install_requires=[ + "pillow", + "click", + "scipy", + "numpy", + "Cython", + "scikit-image", + "loguru", + ], + entry_points=""" [console_scripts] wallgen=wallgen:cli """, - ) +) diff --git a/tools/gradient.py b/tools/gradient.py index b63e4e8..d765378 100644 --- a/tools/gradient.py +++ b/tools/gradient.py @@ -111,7 +111,7 @@ def swirl_image(image, strength=10): w, h = image.shape[:2] sw = swirl(image, rotation=0, strength=strength, radius=max(w, h)) with warnings.catch_warnings(): - warnings.simplefilter('ignore') + warnings.simplefilter("ignore") sw = img_as_ubyte(sw) pil_img = Image.fromarray(sw) diff --git a/tools/points.py b/tools/points.py index 2565545..f6ae718 100644 --- a/tools/points.py +++ b/tools/points.py @@ -12,7 +12,7 @@ def distance(p1, p2): (x1, y1) = p1 (x2, y2) = p2 - d = int((y2 - y1)**2 + (x2 - x1)**2)**0.5 + d = int((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5 return d @@ -46,7 +46,7 @@ def genPoints(qty, width, height): def calcCenter(ps): - """ calculate incenter of a triangle given all vertices""" + """calculate incenter of a triangle given all vertices""" mid1 = ((ps[0][0] + ps[1][0]) / 2, (ps[0][1] + ps[1][1]) / 2) mid = ((mid1[0] + ps[2][0]) / 2, (mid1[1] + ps[2][1]) / 2) return mid @@ -60,7 +60,7 @@ def genSmartPoints(image): # convert to RGB compatible image with warnings.catch_warnings(): - warnings.simplefilter('ignore') + warnings.simplefilter("ignore") rgb_img = img_as_ubyte(color.gray2rgb(edges)) # convert to PIL image @@ -84,8 +84,9 @@ def genSmartPoints(image): raise Exception("EdgeDetectionError") # get a n/5 number of points rather than all of the points - sample = np.random.choice(len(edges_data), len( - edges_data) // 5 if len(edges_data) / 5 < 50000 else 50000) + sample = np.random.choice( + len(edges_data), len(edges_data) // 5 if len(edges_data) / 5 < 50000 else 50000 + ) edges_data = [edges_data[x] for x in sample] # print(len(edges_data)) diff --git a/tools/shapes.py b/tools/shapes.py index 23183f2..fe8a8bc 100644 --- a/tools/shapes.py +++ b/tools/shapes.py @@ -25,8 +25,11 @@ def drawSlants(side, gradient=False, invert=False): else: c = randcolor() draw.line([-adj, y, y, -adj], width=w, fill=c) - draw.line([side - y, side + adj, side + adj, side - y], width=w, - fill=negative(c) if invert else c) + draw.line( + [side - y, side + adj, side + adj, side - y], + width=w, + fill=negative(c) if invert else c, + ) y += w return img @@ -36,10 +39,9 @@ def drawSlants(side, gradient=False, invert=False): # TRIANGULATION # ################# -def genPoly(width, height, img, points, wshift, hshift, outl=None, pic=False): - baseImg = Image.new( - "RGB", (width + (wshift * 2), height + (hshift * 2)), "#000000") +def genPoly(width, height, img, points, wshift, hshift, outl=None, pic=False): + baseImg = Image.new("RGB", (width + (wshift * 2), height + (hshift * 2)), "#000000") baseImg.paste(img, box=(wshift, hshift)) bw = baseImg.width @@ -72,8 +74,9 @@ def genPoly(width, height, img, points, wshift, hshift, outl=None, pic=False): else: draw.polygon(tp, fill=c) # draw one triangle - img = baseImg.crop((wshift, hshift, baseImg.width - wshift, - baseImg.height - hshift)) # crop back to normal size + img = baseImg.crop( + (wshift, hshift, baseImg.width - wshift, baseImg.height - hshift) + ) # crop back to normal size return img @@ -82,8 +85,8 @@ def genPoly(width, height, img, points, wshift, hshift, outl=None, pic=False): # diamond # ########### -def genDiamond(width, height, img, outl=None, pic=False, per=1): +def genDiamond(width, height, img, outl=None, pic=False, per=1): x = y = 0 per = per / 5 # more percentage is too small @@ -100,9 +103,12 @@ def genDiamond(width, height, img, outl=None, pic=False, per=1): for i in range(hboxes - 1): # one extra line for j in range(wboxes // 2 - 1): # ¯\_(ツ)_/¯ - - points = [(x, y), (x + inc, y + inc), (x + 2 * inc, y), - (x + inc, y - inc)] # diamond + points = [ + (x, y), + (x + inc, y + inc), + (x + 2 * inc, y), + (x + inc, y - inc), + ] # diamond a, b = (x + x + 2 * inc) // 2, y @@ -139,8 +145,8 @@ def genDiamond(width, height, img, outl=None, pic=False, per=1): # SQUARES # ########### -def genSquares(width, height, img, outl=None, pic=False, per=1): +def genSquares(width, height, img, outl=None, pic=False, per=1): x = y = 0 per = per / 5 # more percentage is too small @@ -157,8 +163,7 @@ def genSquares(width, height, img, outl=None, pic=False, per=1): for i in range(hboxes): for j in range(wboxes): - points = [(x, y), (x, y + inc), (x + inc, y + inc), - (x + inc, y)] # squares + points = [(x, y), (x, y + inc), (x + inc, y + inc), (x + inc, y)] # squares a, b = (x + x + inc) // 2, (y + y + inc) // 2 # to get pixel data try: # adj to not overflow @@ -193,8 +198,8 @@ def genSquares(width, height, img, outl=None, pic=False, per=1): # HEXAGON # ########### -def genHexagon(width, height, img, outl=None, pic=False, per=1): +def genHexagon(width, height, img, outl=None, pic=False, per=1): per = 11 - per x = y = 0 @@ -218,8 +223,10 @@ def genHexagon(width, height, img, outl=None, pic=False, per=1): for i in range(-1, hboxes + 1): for j in range(-1, wboxes + 2): - points = [((x + radius * math.sin(k * ang)), - (y + radius * math.cos(k * ang))) for k in range(6)] + points = [ + ((x + radius * math.sin(k * ang)), (y + radius * math.cos(k * ang))) + for k in range(6) + ] a, b = x, y try: # adj to not overflow @@ -250,13 +257,13 @@ def genHexagon(width, height, img, outl=None, pic=False, per=1): return img # return final image + ############# # ISOMETRIC # ############# def genIsometric(width, height, img, outl=None, pic=False, per=1): - per = 11 - per x = y = 0 @@ -280,8 +287,10 @@ def genIsometric(width, height, img, outl=None, pic=False, per=1): for i in range(-1, hboxes + 1): for j in range(wboxes + 2): - points = [((x + radius * math.sin(k * ang)), - (y + radius * math.cos(k * ang))) for k in range(6)] + points = [ + ((x + radius * math.sin(k * ang)), (y + radius * math.cos(k * ang))) + for k in range(6) + ] # to store the vertices of the individual equilateral triangles # that make up a hexagon triangle_points = [] @@ -322,13 +331,13 @@ def genIsometric(width, height, img, outl=None, pic=False, per=1): return img # return final image + ############# # TRIANGLES # ############# def genTriangle(width, height, img, outl=None, pic=False, per=1): - x = y = 0 per = per / 5 # more percentage is too small @@ -346,7 +355,6 @@ def genTriangle(width, height, img, outl=None, pic=False, per=1): pair = 0 for i in range(hboxes * 2): for j in range(wboxes): - if i % 2 == 0: # triangle pointing down points = [(x, y), (x + inc * 2, y), (x + inc, y + inc)] diff --git a/tools/wallpaper.py b/tools/wallpaper.py index dde3a63..43f34c0 100644 --- a/tools/wallpaper.py +++ b/tools/wallpaper.py @@ -9,15 +9,17 @@ def get_env(): # Get Current Desktop Environment - def get(name): return os.environ.get( - name) if os.environ.get(name) else None + def get(name): + return os.environ.get(name) if os.environ.get(name) else None + support = [ "XDG_CURRENT_DESKTOP", "DESKTOP_SESSION", "GNOME_DESKTOP_SESSION_ID", "MATE_DESKTOP_SESSION_ID", "SWAYSOCK", - "DESKTOP_STARTUP_ID"] + "DESKTOP_STARTUP_ID", + ] for env in support: out = get(env) if out: @@ -36,7 +38,7 @@ def get(name): return os.environ.get( def is_64bit_windows(): """Check if 64 bit Windows OS""" - return struct.calcsize('P') * 8 == 64 + return struct.calcsize("P") * 8 == 64 def setwallpaper(image_path, relative_path=True): @@ -47,37 +49,73 @@ def setwallpaper(image_path, relative_path=True): if "linux" in host: desktop = str(desktop).lower() - def disown(cmd): return subprocess.Popen( - cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + def disown(cmd): + return subprocess.Popen( + cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL + ) + if desktop in ["xfce", "xubuntu"]: xfconf_re = re.compile( r"^/backdrop/screen\d/monitor(?:0|\w*)/" r"(?:(?:image-path|last-image)|workspace\d/last-image)$", - flags=re.M + flags=re.M, ) xfconf_data = subprocess.check_output( ["xfconf-query", "--channel", "xfce4-desktop", "--list"], - stderr=subprocess.DEVNULL - ).decode('utf8') + stderr=subprocess.DEVNULL, + ).decode("utf8") paths = xfconf_re.findall(xfconf_data) for path in paths: - disown(["xfconf-query", "--channel", "xfce4-desktop", - "--property", path, "--set", image_path]) + disown( + [ + "xfconf-query", + "--channel", + "xfce4-desktop", + "--property", + path, + "--set", + image_path, + ] + ) elif desktop in ["muffin", "cinnamon"]: - disown(["gsettings", "set", "org.cinnamon.desktop.background", - "picture-uri", "file://" + urllib.parse.quote(image_path)]) + disown( + [ + "gsettings", + "set", + "org.cinnamon.desktop.background", + "picture-uri", + "file://" + urllib.parse.quote(image_path), + ] + ) elif desktop in ["gnome", "unity"]: - disown(["gsettings", "set", "org.gnome.desktop.background", - "picture-uri", "file://" + urllib.parse.quote(image_path)]) + disown( + [ + "gsettings", + "set", + "org.gnome.desktop.background", + "picture-uri", + "file://" + urllib.parse.quote(image_path), + ] + ) elif "mate" in desktop: - disown(["gsettings", "set", "org.mate.background", - "picture-filename", image_path]) + disown( + [ + "gsettings", + "set", + "org.mate.background", + "picture-filename", + image_path, + ] + ) elif "sway" in desktop: disown(["swaymsg", "output", "*", "bg", image_path, "fill"]) elif "awesome" in desktop: - disown(["awesome-client", - "require('gears').wallpaper.maximized('" - + image_path + "')"]) + disown( + [ + "awesome-client", + "require('gears').wallpaper.maximized('" + image_path + "')", + ] + ) else: if desktop: msg = f"Sorry, {desktop} is currently not supported." @@ -86,12 +124,11 @@ def disown(cmd): return subprocess.Popen( return msg, False elif "darwin" in host: db_file = "Library/Application Support/Dock/desktoppicture.db" - db_path = os.path.join( - os.getenv("HOME", os.getenv("USERPROFILE")), db_file) + db_path = os.path.join(os.getenv("HOME", os.getenv("USERPROFILE")), db_file) img_dir, _ = os.path.split(image_path) sql = "delete from data; " - sql += "insert into data values(\"%s\"); " % img_dir - sql += "insert into data values(\"%s\"); " % image_path + sql += 'insert into data values("%s"); ' % img_dir + sql += 'insert into data values("%s"); ' % image_path sql += "update preferences set data_id=2 where key=1 or key=2 or key=3; " # noqa: E501 sql += "update preferences set data_id=1 where key=10 or key=20 or key=30;" # noqa: E501 subprocess.call(["sqlite3", db_path, sql]) diff --git a/wallgen.py b/wallgen.py index e73a80a..c8a5acc 100644 --- a/wallgen.py +++ b/wallgen.py @@ -93,9 +93,7 @@ def cli(): @click.option( "--only-color", "-oc", is_flag=True, help="Generate just a gradient image" ) -@click.option( - "--use-nn", "-un", is_flag=True, help="Use NbyNGradient function" -) +@click.option("--use-nn", "-un", is_flag=True, help="Use NbyNGradient function") @click.option( "--swirl", "-sw", @@ -173,9 +171,7 @@ def poly( if swirl: if only_color: - img = img.resize( - (side // scale, side // scale), resample=Image.BICUBIC - ) + img = img.resize((side // scale, side // scale), resample=Image.BICUBIC) img = swirl_image(img, swirl) if not only_color: @@ -199,9 +195,7 @@ def poly( print("\r", end="") print("Making final tweaks", end="") - img = img.resize( - (side // scale, side // scale), resample=Image.BICUBIC - ) + img = img.resize((side // scale, side // scale), resample=Image.BICUBIC) if show: img.show() @@ -271,9 +265,7 @@ def poly( metavar="/path/to/output_file", help="Rename the output file", ) -@click.option( - "--use-nn", "-un", is_flag=True, help="Use NbyNGradient function" -) +@click.option("--use-nn", "-un", is_flag=True, help="Use NbyNGradient function") @click.option( "--swirl", "-sw", @@ -528,7 +520,7 @@ def pic_poly(image, points, show, outline, name, smart, set_wall): # height += hshift*2 if outline: - if isinstance(outline, tuple): + if isinstance(outline, tuple): pass else: try: @@ -622,9 +614,7 @@ def pic_poly(image, points, show, outline, name, smart, set_wall): metavar="#HEXCODE", help="Outline the shapes", ) -@click.option( - "--name", "-n", metavar="/path/to/output_file", help="Rename the output" -) +@click.option("--name", "-n", metavar="/path/to/output_file", help="Rename the output") @click.option( "--set-wall", "-w", @@ -717,8 +707,7 @@ def pic_shape(image, shape, show, outline, name, percent, set_wall): ) @click.pass_context def randomize(ctx, side, name): - """Generate a random config - """ + """Generate a random config""" choice_of_pattern = ["poly", "shape", "slants"] pattern = choice(choice_of_pattern) click.secho(f"Random choice of pattern: {pattern}")