Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.
Python adbadblockandroid-tvandroid-tv-launcherapple-tvbloatware-removalclaude-codedebloatfire-tvgoogle-tvlauncherprivacysmart-tvsony-braviatclvibe-codingxiaomi
tools: the card scripts name the pictures they read before Pillow opens them
xbshengea445e35cb32
diff --git a/tests/test_card_input_pictures.py b/tests/test_card_input_pictures.pynew file mode 100644index 000000000..5935ee8ea--- /dev/null+++ b/tests/test_card_input_pictures.py@@ -0,0 +1,207 @@+"""The pictures the README card scripts read are not arguments, and Pillow answered them last.++`docs/workflows/press.md` step 2 sends a contributor to `tools/readme_featured.py ... docs/featured.png`+and `tools/readme_card.py ... docs/card.jpg`, and the card's own docstring says to run+`tools/readme_stats.py` first. The font and the written picture were judged before Pillow was imported+(#1929, #2069), but the pictures the scripts *read* were not: they are opened by name relative to the+directory the reader stands in, so++ readme_card.py run from tools/ -> FileNotFoundError: 'docs/stock-home.jpg'+ card.jpg run before readme_stats.py -> FileNotFoundError: 'docs/stats.png'+ a logo renamed without its picture -> FileNotFoundError: 'docs/press/xda.png'+ a truncated stats.png -> UnidentifiedImageError: cannot identify image file++were each a traceback out of the middle of the draw with exit 1 - the code a run that wrote nothing+returns - naming neither the sibling script that draws `docs/stats.png` / `docs/featured.png` nor+whether anything reached the disk, while the font and the output got a sentence instead.++Both scripts judge their pictures now, with the path named, the sibling that draws it where there is+one, and 'Nothing was written.', before the Pillow import (so CI, whose tools/venv has no Pillow, runs+these tests); each open still catches a file that is there and is not a picture, in the same words. The+two pictures the repository ships, the four the card stacks and the logos in LOGOS are read out of the+sources so a rename fails here rather than in a maintainer's run.++Run from the repository root: python3 -m unittest discover -s tests -v+"""+import ast+import importlib.util+import os+import shutil+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+TOOLS = ROOT / "tools"+DOCS = ROOT / "docs"+CARD = TOOLS / "readme_card.py"+FEATURED = TOOLS / "readme_featured.py"++# The launcher's own font: one vertical weight axis, so it is the variable TTF these scripts ask for.+LAUNCHER_FONT = ROOT / "launcher" / "app" / "src" / "main" / "res" / "font" / "outfit.ttf"++HAVE_PIL = importlib.util.find_spec("PIL") is not None+++def source(script):+ return script.read_text(encoding="utf-8")+++def read_paths(script):+ """The picture paths a script checks before Pillow: INPUTS' names, or LOGOS' docs/press/<name>.png."""+ tree = ast.parse(source(script))+ for node in tree.body:+ if not isinstance(node, ast.Assign) or not isinstance(node.value, (ast.List, ast.Tuple)):+ continue+ name = getattr(node.targets[0], "id", "")+ items = [elt.value for elt in node.value.elts+ if isinstance(elt, ast.Constant) and isinstance(elt.value, str)]+ if name == "INPUTS":+ return items+ if name == "LOGOS":+ return [f"docs/press/{n}.png" for n in items]+ raise AssertionError(f"{script.name} has no INPUTS or LOGOS list")+++def run_without_pillow(argv, cwd, shadow):+ """A run whose PIL import cannot succeed, the way CI's tools/venv runs: the refusal must not need it."""+ pkg = Path(shadow) / "PIL"+ pkg.mkdir(parents=True, exist_ok=True)+ (pkg / "__init__.py").write_text('raise ImportError("No module named \'PIL\'")\n', encoding="utf-8")+ env = dict(os.environ)+ env["PYTHONPATH"] = str(shadow)+ return subprocess.run([sys.executable, *argv], cwd=cwd, env=env, capture_output=True, text=True)+++def run_plain(argv, cwd):+ """The same command with the Pillow this machine has, so a real picture is drawn."""+ env = dict(os.environ)+ env.pop("PYTHONPATH", None)+ return subprocess.run([sys.executable, *argv], cwd=cwd, env=env, capture_output=True, text=True)+++class CardPicturesTest(unittest.TestCase):+ def setUp(self):+ self._tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self._tmp.cleanup)+ self.cwd = Path(self._tmp.name) / "checkout" # a stand-in for a clone seen from somewhere else+ (self.cwd / "docs").mkdir(parents=True)+ self.out = Path(self._tmp.name) / "out.jpg"+ self.shadow = Path(self._tmp.name) / "shadow"++ def touch(self, *names):+ for name in names:+ path = self.cwd / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(b"not a picture yet\n")++ def assert_refused(self, done, *wanted):+ self.assertEqual(done.returncode, 1, done.stderr)+ self.assertNotIn("Traceback", done.stderr)+ self.assertIn("Nothing was written", done.stderr)+ for text in wanted:+ self.assertIn(text, done.stderr)++ def card(self, out=None):+ return run_without_pillow([str(CARD), str(LAUNCHER_FONT), str(out or self.out)], self.cwd, self.shadow)++ def featured(self, out=None):+ out = out or Path(self._tmp.name) / "out.png"+ return run_without_pillow([str(FEATURED), str(LAUNCHER_FONT), str(out)], self.cwd, self.shadow)++ def test_a_missing_screenshot_is_named(self):+ """The two the repository ships, read before either sibling has drawn anything."""+ done = self.card()+ self.assert_refused(done, "docs/stock-home.jpg", "repository root")++ def test_a_missing_stats_picture_names_the_script_that_draws_it(self):+ """The card stacks docs/stats.png, which tools/readme_stats.py draws - not a file the card ships."""+ self.touch("docs/stock-home.jpg", "docs/new-home.jpg", "docs/featured.png")+ done = self.card()+ self.assert_refused(done, "docs/stats.png", "tools/readme_stats.py")++ def test_a_missing_featured_picture_names_its_script(self):+ self.touch("docs/stock-home.jpg", "docs/new-home.jpg", "docs/stats.png")+ done = self.card()+ self.assert_refused(done, "docs/featured.png", "tools/readme_featured.py")++ def test_a_picture_that_is_a_folder_is_named_as_one(self):+ self.touch("docs/stock-home.jpg", "docs/new-home.jpg", "docs/featured.png")+ (self.cwd / "docs" / "stats.png").mkdir()+ done = self.card()+ self.assert_refused(done, "docs/stats.png", "is a folder")++ def test_a_folder_where_the_logos_go_is_named(self):+ (self.cwd / "docs" / "press").mkdir()+ done = self.featured()+ self.assert_refused(done, "docs/press/techcrunch.png", "LOGOS")++ def test_a_missing_logo_is_named_with_the_repository_root(self):+ done = self.featured()+ self.assert_refused(done, "docs/press/techcrunch.png", "repository root")++ def test_the_refusal_comes_before_the_pillow_message(self):+ """No Pillow, as in CI's tools/venv: the picture is judged first, so that is the answer given."""+ self.touch("docs/stock-home.jpg", "docs/new-home.jpg", "docs/featured.png")+ done = self.card()+ self.assertNotIn("needs Pillow", done.stderr)+ done = self.featured()+ self.assertNotIn("needs Pillow", done.stderr)++ @unittest.skipUnless(HAVE_PIL, "reads a picture with Pillow, which tools/venv has not")+ def test_a_picture_that_is_not_a_picture_is_named(self):+ for name in ("docs/stock-home.jpg", "docs/new-home.jpg", "docs/featured.png"):+ shutil.copy(DOCS / Path(name).name, self.cwd / name)+ (self.cwd / "docs" / "stats.png").write_bytes(b"not a picture")+ done = run_plain([str(CARD), str(LAUNCHER_FONT), str(self.out)], self.cwd)+ self.assert_refused(done, "docs/stats.png")++ @unittest.skipUnless(HAVE_PIL, "reads a picture with Pillow, which tools/venv has not")+ def test_a_logo_that_is_not_a_picture_is_named(self):+ press = self.cwd / "docs" / "press"+ press.mkdir()+ for name in read_paths(FEATURED):+ (self.cwd / name).write_bytes(b"not a picture")+ done = run_plain([str(FEATURED), str(LAUNCHER_FONT), str(Path(self._tmp.name) / "o.png")], self.cwd)+ self.assert_refused(done, "docs/press/techcrunch.png")++ @unittest.skipUnless(HAVE_PIL, "draws the card with Pillow, which tools/venv has not")+ def test_the_card_still_writes_with_its_pictures_there(self):+ for name in ("docs/stock-home.jpg", "docs/new-home.jpg", "docs/stats.png", "docs/featured.png"):+ shutil.copy(DOCS / Path(name).name, self.cwd / name)+ done = run_plain([str(CARD), str(LAUNCHER_FONT), str(self.out)], self.cwd)+ self.assertEqual(done.returncode, 0, done.stderr)+ self.assertGreater(self.out.stat().st_size, 50_000, "the card came out empty")++ @unittest.skipUnless(HAVE_PIL, "draws the panel with Pillow, which tools/venv has not")+ def test_the_panel_still_writes_with_its_logos_there(self):+ press = self.cwd / "docs" / "press"+ press.mkdir()+ for name in read_paths(FEATURED):+ shutil.copy(DOCS / "press" / Path(name).name, self.cwd / name)+ out = Path(self._tmp.name) / "featured.png"+ done = run_plain([str(FEATURED), str(LAUNCHER_FONT), str(out)], self.cwd)+ self.assertEqual(done.returncode, 0, done.stderr)+ self.assertGreater(out.stat().st_size, 20_000, "the panel came out empty")++ def test_the_judgement_sits_above_the_pillow_import(self):+ for script, call in ((CARD, "inputs_problem()"), (FEATURED, "logo_problem()")):+ with self.subTest(script=script.name):+ text = source(script)+ self.assertIn(call, text, f"{script.name} does not judge its pictures")+ self.assertLess(text.index(call), text.index("from PIL import"),+ f"{script.name} judges its pictures after Pillow is imported")++ def test_every_picture_named_is_in_this_checkout(self):+ """A renamed file fails here, where the scripts would have named it in a maintainer's run."""+ for script in (CARD, FEATURED):+ for path in read_paths(script):+ with self.subTest(script=script.name, picture=path):+ self.assertTrue((ROOT / path).is_file(), f"{script.name} reads {path}, which is not here")+ self.assertGreaterEqual(len(read_paths(FEATURED)), 10, "the LOGOS read found almost nothing")+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/readme_card.py b/tools/readme_card.pyindex dfa6091b7..cb70b5611 100644--- a/tools/readme_card.py+++ b/tools/readme_card.py@@ -4,7 +4,8 @@ the file the front page displays.Run tools/readme_stats.py and tools/readme_featured.py first, then:python3 tools/readme_card.py Fredoka.ttf docs/card.jpgFredoka is the variable TTF from Google Fonts, and its file is not in this repo: pass the path of the-copy you downloaded.+copy you downloaded. The four pictures it stacks are this checkout's own - docs/stock-home.jpg,+docs/new-home.jpg and the two its siblings draw - so run it from the repository root."""import osimport sys@@ -62,12 +63,59 @@ OUT_PROBLEM = out_problem(OUT)if OUT_PROBLEM:sys.exit(f"{OUT_PROBLEM}. Nothing was written.")+# The pictures the card stacks are the input this script does not take as arguments: two screenshots the+# repository ships, and the two pictures its siblings draw. They are read at names relative to the+# repository root, so a run from another directory, or a sibling's picture not drawn yet, reached+# `Image.open()` in the middle of the draw and came back as `FileNotFoundError: [Errno 2] ...+# 'docs/stats.png'` - a traceback naming neither the script that draws it nor whether a picture was+# written. Judged before the Pillow import, so a machine without it answers the same way.+INPUTS = (+ ("docs/stock-home.jpg", None),+ ("docs/new-home.jpg", None),+ ("docs/stats.png", "tools/readme_stats.py draws it"),+ ("docs/featured.png", "tools/readme_featured.py draws it"),+)+++def inputs_problem():+ """Why a picture the card stacks cannot be read, or None."""+ for path, drawn_by in INPUTS:+ if os.path.isdir(path):+ return (f"{path} is a folder, and the card reads one picture from it: pass this checkout's "+ f"file, run from the repository root")+ if not os.path.isfile(path):+ if drawn_by:+ return (f"cannot read {path}: there is no such file. {drawn_by}, and the card reads it "+ f"from the repository root, so run that first")+ return (f"cannot read {path}: there is no such file. The card stacks this checkout's own "+ f"pictures, so run this from the repository root")+ return None+++INPUTS_PROBLEM = inputs_problem()+if INPUTS_PROBLEM:+ sys.exit(f"{INPUTS_PROBLEM}. Nothing was written.")+# See readme_stats.py: Pillow lives in the optional requirements file, so name it rather than crash.try:from PIL import Image, ImageDraw, ImageFilter, ImageFontexcept ImportError:sys.exit("readme_card.py needs Pillow: tools/venv/bin/pip install -r tools/requirements-perf.txt")++def load(path):+ """One picture the card stacks, or a sentence naming the file Pillow could not read.++ `inputs_problem()` has already answered whether the file is there; a file that is there and is not a+ picture - a truncated PNG from an interrupted pull, an HTML error page saved under the name - is+ Pillow's `UnidentifiedImageError` out of the open, in the middle of the draw.+ """+ try:+ return Image.open(path).convert("RGB")+ except (OSError, ValueError) as error:+ sys.exit(f"cannot read {path}: {error}. Nothing was written.")++BG, LINE, DIM, GREEN = "#15181e", "#2c313a", "#aab3bd", "#cfffcf"W = 1600def f(size, wt):@@ -90,8 +138,8 @@ def spaced(d, cx, y, t, font, sp, fill):for c in t: d.text((x, y), c, font=font, fill=fill); x += d.textlength(c, font=font) + sp# the TV screens, cropped to the bezel; the Wi-Fi name on the after shot is blurred-before = Image.open("docs/stock-home.jpg").convert("RGB").crop((130, 216, 1317, 864))-after = Image.open("docs/new-home.jpg").convert("RGB")+before = load("docs/stock-home.jpg").crop((130, 216, 1317, 864))+after = load("docs/new-home.jpg")box = (1150, 236, 1240, 280); after.paste(after.crop(box).filter(ImageFilter.GaussianBlur(9)), box)after = after.crop((203, 138, 1467, 792))PAD, ARROW = 70, 90@@ -108,7 +156,7 @@ ax, ay = W / 2, 90 + th / 2d.line([(ax - 26, ay), (ax + 26, ay)], fill=GREEN, width=5)d.line([(ax + 8, ay - 16), (ax + 27, ay), (ax + 8, ay + 16)], fill=GREEN, width=5, joint="curve")-parts = [Image.open("docs/stats.png").convert("RGB"), Image.open("docs/featured.png").convert("RGB"), tv]+parts = [load("docs/stats.png"), load("docs/featured.png"), tv]SEP = 24 # extra air on each side of a dividerH = sum(p.height for p in parts) + 2 * SEP * (len(parts) - 1)card = Image.new("RGB", (W, H), BG); d = ImageDraw.Draw(card); y = 0diff --git a/tools/readme_featured.py b/tools/readme_featured.pyindex 62a76abdc..964ab6bb6 100644--- a/tools/readme_featured.py+++ b/tools/readme_featured.py@@ -1,8 +1,9 @@"""Renders the Featured in panel (docs/featured.png), the middle part of the README card.Update LOGOS / MORE, then: python3 tools/readme_featured.py Fredoka.ttf docs/featured.png-and rebuild the card with tools/readme_card.py. Logos come from docs/press/. Fredoka is the variable TTF-from Google Fonts, and its file is not in this repo: pass the path of the copy you downloaded.+and rebuild the card with tools/readme_card.py. Logos come from docs/press/, at names relative to the+repository root, so run it from there. Fredoka is the variable TTF from Google Fonts, and its file is not+in this repo: pass the path of the copy you downloaded."""import osimport sys@@ -60,15 +61,42 @@ OUT_PROBLEM = out_problem(OUT)if OUT_PROBLEM:sys.exit(f"{OUT_PROBLEM}. Nothing was written.")+LOGOS = ["techcrunch", "techradar", "tomsguide", "mashable", "androidauthority", "xda", "flatpanelshd", "itsfoss",+ "phandroid", "gigazine", "xataka", "winfuture", "frandroid", "macitynet", "techaeris", "techpp"]+MORE = "+297 more · 313 articles from 44 countries"+++def logo_problem():+ """Why a logo this panel draws cannot be read, or None.++ The pictures are the input this script does not take as arguments: `docs/press/<name>.png` for each+ name in LOGOS, read from wherever the reader stands, so a run from another directory, or a logo named+ in LOGOS whose picture was renamed, reached `Image.open()` in the middle of the draw and came back as+ `FileNotFoundError: [Errno 2] ... 'docs/press/xda.png'` - a traceback naming neither LOGOS nor this+ checkout, and saying nothing about whether the panel was written. Judged before the Pillow import, so+ a machine without it answers the same way.+ """+ for name in LOGOS:+ path = f"docs/press/{name}.png"+ if os.path.isdir(path):+ return (f"{path} is a folder, and the panel draws one picture from it: pass this checkout's "+ f"file, run from the repository root")+ if not os.path.isfile(path):+ return (f"cannot read {path}: there is no such file. The logos the panel draws are the names "+ f"in LOGOS here, read from docs/press/ in this checkout, so run this from the "+ f"repository root and give a renamed logo its picture")+ return None+++LOGO_PROBLEM = logo_problem()+if LOGO_PROBLEM:+ sys.exit(f"{LOGO_PROBLEM}. Nothing was written.")+# See readme_stats.py: Pillow lives in the optional requirements file, so name it rather than crash.try:from PIL import Image, ImageDraw, ImageFontexcept ImportError:sys.exit("readme_featured.py needs Pillow: tools/venv/bin/pip install -r tools/requirements-perf.txt")--LOGOS = ["techcrunch", "techradar", "tomsguide", "mashable", "androidauthority", "xda", "flatpanelshd", "itsfoss",- "phandroid", "gigazine", "xataka", "winfuture", "frandroid", "macitynet", "techaeris", "techpp"]-MORE = "+297 more · 313 articles from 44 countries"W, LH, GAP, ROWGAP, PAD = 1600, 54, 40, 36, 80def f(size, wt):# A path that exists is not yet a font: Google Fonts serves Fredoka as a zip holding the variable@@ -86,7 +114,12 @@ def f(size, wt):f(12, 400) # the font is the argument the reader brings, so a wrong one is named before any drawinglogos = []for n in LOGOS:- im = Image.open(f"docs/press/{n}.png").convert("RGBA")+ try:+ im = Image.open(f"docs/press/{n}.png").convert("RGBA")+ except (OSError, ValueError) as error:+ # A picture that is there and is not one: a truncated PNG, a file an interrupted copy left, an+ # HTML error page saved under the logo's name. Found at the open, after the font was loaded.+ sys.exit(f"cannot read docs/press/{n}.png: {error}. Nothing was written.")logos.append(im.resize((round(im.width * LH / im.height), LH), Image.LANCZOS))half = (len(logos) + 1) // 2rows = [logos[:half], logos[half:]]