Download source/codedesk/families/mediatools.py from rca-umb/five-desks-code: direct link, hf CLI and curl.
- Browser
- Download file 17.7 kB
-
https://huggingface.co/datasets/rca-umb/five-desks-code/resolve/main/source/codedesk/families/mediatools.py
- Command line
-
hf download hf://datasets/rca-umb/five-desks-code/source/codedesk/families/mediatools.py
-
curl -L -o mediatools.py https://huggingface.co/datasets/rca-umb/five-desks-code/resolve/main/source/codedesk/families/mediatools.py
17.7 kB
| """Media production with real tools: ffmpeg, ImageMagick and Pillow. | |
| Each instance generates its own input media and a client spec (spec.md) plus production notes (notes.md) that add | |
| one requirement the spec does not mention. The policy uses the shell to produce the deliverable. Grading measures | |
| the output files (stream properties with ffprobe; picture content against references computed from a private copy | |
| of the inputs) and never trusts anything the policy wrote except the deliverables themselves. | |
| Variants: a trimmed and scaled video clip, square thumbnails from photos (some rotated by EXIF), a contact sheet | |
| ordered by capture time, and a loudness-normalised audio delivery. | |
| """ | |
| import json | |
| import math | |
| import shutil | |
| import tempfile | |
| from pathlib import Path | |
| from .. import runner | |
| from ..base import CodingTask, Tool | |
| ANALYZE = r''' | |
| import json, subprocess, sys | |
| from PIL import Image, ImageOps | |
| kind, path = sys.argv[1], sys.argv[2] | |
| def tiny(img, size): | |
| return list(ImageOps.fit(img.convert("L"), size).getdata()) | |
| if kind == "image": | |
| try: | |
| img = Image.open(path); img.load() | |
| print(json.dumps({"size": img.size, "format": img.format, "tiny": tiny(img, (8, 8))})) | |
| except Exception as e: | |
| print(json.dumps({"error": str(e)[:200]})) | |
| elif kind == "tiles": | |
| cols, rows, tw, th = map(int, sys.argv[3:7]) | |
| img = Image.open(path).convert("L") | |
| out = [] | |
| for r in range(rows): | |
| for c in range(cols): | |
| box = img.crop((c * tw + tw // 4, r * th + th // 4, c * tw + 3 * tw // 4, r * th + 3 * th // 4)) | |
| px = list(box.getdata()); out.append(sum(px) / len(px)) | |
| print(json.dumps({"size": img.size, "tiles": out})) | |
| ''' | |
| def ffprobe(path: Path, cwd: Path) -> dict: | |
| code, out = runner.run(f"ffprobe -v error -show_streams -show_format -of json '{path}'", cwd, timeout=30) | |
| try: | |
| return json.loads(out) | |
| except json.JSONDecodeError: | |
| return {} | |
| def frame_tiny(path: Path, t: float, cwd: Path) -> list[int] | None: | |
| """A 16x9 grayscale thumbnail of the frame at time t (seconds).""" | |
| code, out = runner.run(f"ffmpeg -v error -ss {t:.3f} -i '{path}' -frames:v 1 -vf scale=16:9,format=gray " | |
| "-f rawvideo - | od -An -v -tu1", cwd, timeout=30) | |
| vals = [int(v) for v in out.split() if v.isdigit()] | |
| return vals if len(vals) == 144 else None | |
| def mad(a, b) -> float: | |
| return sum(abs(x - y) for x, y in zip(a, b)) / max(1, len(a)) | |
| class MediaTools(CodingTask): | |
| family = "media" | |
| levels = (1, 2) | |
| max_steps = 24 | |
| def groups(): | |
| return ["production"] | |
| def setup(self): | |
| self.domain = "media-content-production" | |
| self.private = Path(tempfile.mkdtemp(prefix="media-ref-")) # root-only copy of the inputs | |
| self.variant = self.rng.randrange(4) | |
| for attempt in range(20): # generators assert their own invariants; redraw until they hold | |
| try: | |
| getattr(self, f"_v{self.variant}")() | |
| break | |
| except AssertionError: | |
| for d in (self.ws, self.private): | |
| for p in d.iterdir(): | |
| shutil.rmtree(p) if p.is_dir() else p.unlink() | |
| else: | |
| raise RuntimeError("could not generate a media task") | |
| (self.ws / "spec.md").write_text(self.spec) | |
| (self.ws / "notes.md").write_text("# Production notes\n\n" + "\n".join(f"- {n}" for n in self.notes) + "\n") | |
| def close(self): | |
| super().close() | |
| if getattr(self, "private", None): | |
| shutil.rmtree(self.private, ignore_errors=True) | |
| def _sh(self, cmd: str, cwd: Path, timeout: int = 60): | |
| code, out = runner.run(cmd, cwd, timeout=timeout) | |
| assert code == 0, out[-500:] | |
| # -- variant 0: trimmed, scaled clip --------------------------------------------------------------- | |
| def _v0(self): | |
| r = self.rng | |
| dur = r.choice([12, 14, 16]) | |
| self.a = r.randint(2, dur - 7) | |
| self.b = self.a + r.randint(3, 5) | |
| self.w = r.choice([320, 426, 480]) | |
| self.fps = r.choice([12, 15, 24]) | |
| self.mono = r.random() < 0.5 | |
| self._sh(f"ffmpeg -v error -f lavfi -i testsrc2=size=640x360:rate=30:duration={dur} -f lavfi " | |
| f"-i sine=frequency={r.choice([330, 440, 550])}:duration={dur} -ac 2 -c:v libx264 -preset ultrafast " | |
| "-pix_fmt yuv420p -c:a aac -shortest input.mp4", self.ws, 120) | |
| shutil.copy(self.ws / "input.mp4", self.private / "input.mp4") | |
| self.ref = [frame_tiny(self.ws / "input.mp4", t + 0.05, self.ws) for t in (self.a, self.a - 1, self.a + 1)] | |
| assert all(self.ref) | |
| self.out = "deliver/clip.mp4" | |
| self.spec = (f"# Clip delivery\n\nFrom input.mp4, deliver the segment from {self.a} s to {self.b} s as " | |
| f"{self.out}: H.264 video, {self.w} pixels wide with the aspect ratio kept (even height), " | |
| f"{self.fps} frames per second.\n") | |
| self.notes = ["The client's player needs the audio track kept, downmixed to mono (one channel)." | |
| if self.mono else "The client will add their own music: deliver the clip with no audio track."] | |
| def _g0(self, path: Path) -> bool: | |
| info = ffprobe(path, self.ws) | |
| streams = info.get("streams", []) | |
| video = [s for s in streams if s.get("codec_type") == "video"] | |
| audio = [s for s in streams if s.get("codec_type") == "audio"] | |
| if len(video) != 1 or video[0].get("codec_name") != "h264": | |
| return False | |
| v = video[0] | |
| h = round(self.w * 360 / 640 / 2) * 2 | |
| if v.get("width") != self.w or abs(int(v.get("height", 0)) - h) > 2: | |
| return False | |
| num, _, den = str(v.get("avg_frame_rate", "0/1")).partition("/") | |
| try: | |
| fps = float(num) / float(den or 1) | |
| except (ValueError, ZeroDivisionError): | |
| return False | |
| if abs(fps - self.fps) > 0.5: | |
| return False | |
| try: | |
| duration = float(info.get("format", {}).get("duration", 0)) | |
| except ValueError: | |
| return False | |
| if abs(duration - (self.b - self.a)) > 0.25: | |
| return False | |
| if self.mono != (len(audio) == 1 and audio[0].get("channels") == 1) or (not self.mono and audio): | |
| return False | |
| first = frame_tiny(path, 0.05, self.ws) | |
| if first is None: | |
| return False | |
| right, before, after = (mad(first, ref) for ref in self.ref) | |
| return right < 12 and right < before and right < after | |
| # -- variant 1: thumbnails ------------------------------------------------------------------------- | |
| def _photos(self, n): | |
| from PIL import Image, ImageDraw | |
| r = self.rng | |
| self.photos = [] | |
| (self.ws / "photos").mkdir() | |
| for i in range(n): | |
| w, h = r.choice([(640, 480), (800, 600), (480, 640), (1024, 768), (240, 180), (200, 260)]) | |
| img = Image.new("RGB", (w, h), tuple(r.randint(30, 220) for _ in range(3))) | |
| d = ImageDraw.Draw(img) | |
| d.rectangle([0, 0, w // 3, h // 3], fill=(250, 250, 250)) # a bright corner shows orientation | |
| d.ellipse([w // 3, h // 3, 2 * w // 3, 2 * h // 3], fill=tuple(r.randint(0, 255) for _ in range(3))) | |
| orient = r.choice([1, 1, 3, 6, 8]) | |
| exif = Image.Exif() | |
| exif[0x0112] = orient | |
| exif[0x9003] = f"2026:0{r.randint(1, 9)}:{r.randint(10, 28)} {r.randint(10, 19)}:{r.randint(10, 59)}:00" | |
| stem = f"IMG_{r.randint(1000, 9999)}" | |
| while any(p[0] == stem for p in self.photos): | |
| stem = f"IMG_{r.randint(1000, 9999)}" | |
| img.save(self.private / f"{stem}.jpg", quality=92, exif=exif) | |
| shutil.copy(self.private / f"{stem}.jpg", self.ws / "photos" / f"{stem}.jpg") | |
| self.photos.append((stem, img.size, orient, exif[0x9003])) | |
| def _v1(self): | |
| from PIL import Image, ImageOps | |
| r = self.rng | |
| self._photos(r.randint(5, 8)) | |
| self.size = r.choice([128, 160, 200]) | |
| self.min_side = 300 | |
| self.expected = {} | |
| for stem, (w, h), _, _ in self.photos: | |
| if min(w, h) < self.min_side: | |
| continue | |
| img = ImageOps.exif_transpose(Image.open(self.private / f"{stem}.jpg")) | |
| thumb = ImageOps.fit(img, (self.size, self.size)) | |
| self.expected[stem] = list(ImageOps.fit(thumb.convert("L"), (8, 8)).getdata()) | |
| assert 2 <= len(self.expected) < len(self.photos) | |
| self.spec = (f"# Thumbnails\n\nFor every photo in photos/, make a square {self.size}x{self.size} thumbnail: " | |
| "the photo shown upright (as a phone would display it), scaled to cover the square and " | |
| "centre-cropped. Save each as PNG in thumbs/ with the photo's name, e.g. thumbs/IMG_1234.png.\n") | |
| self.notes = [f"Skip photos smaller than {self.min_side} pixels on their short side; no thumbnails for " | |
| "those (they are placeholders)."] | |
| def _g1(self) -> bool: | |
| thumbs = self.ws / "thumbs" | |
| if not thumbs.is_dir(): | |
| return False | |
| got = {p.stem: p for p in thumbs.iterdir() if p.suffix.lower() == ".png"} | |
| if set(got) != set(self.expected): | |
| return False | |
| for stem, ref in self.expected.items(): | |
| stats = self._analyze("image", got[stem]) | |
| if stats.get("format") != "PNG" or tuple(stats.get("size", ())) != (self.size, self.size): | |
| return False | |
| if mad(stats["tiny"], ref) > 14: | |
| return False | |
| return True | |
| # -- variant 2: contact sheet ---------------------------------------------------------------------- | |
| def _v2(self): | |
| from PIL import Image, ImageOps | |
| r = self.rng | |
| self._photos(6) | |
| assert len({p[3] for p in self.photos}) == 6 and sorted(self.photos, key=lambda p: p[3]) != sorted(self.photos) | |
| self.cols, self.rows = (3, 2) if r.random() < 0.5 else (2, 3) | |
| self.tw, self.th = r.choice([(160, 120), (200, 150)]) | |
| order = sorted(self.photos, key=lambda p: p[3]) | |
| self.expected = [] | |
| for stem, *_ in order: | |
| img = ImageOps.exif_transpose(Image.open(self.private / f"{stem}.jpg")) | |
| tile = ImageOps.fit(img, (self.tw, self.th)).convert("L") | |
| box = tile.crop((self.tw // 4, self.th // 4, 3 * self.tw // 4, 3 * self.th // 4)) | |
| px = list(box.getdata()) | |
| self.expected.append(sum(px) / len(px)) | |
| self.out = "sheet.png" | |
| self.spec = (f"# Contact sheet\n\nMake a contact sheet of the six photos in photos/ as {self.out}: a grid " | |
| f"{self.cols} tiles wide and {self.rows} tall, each tile exactly {self.tw}x{self.th} pixels " | |
| "(photo upright, scaled to cover and centre-cropped), no borders or gaps, filled left to right " | |
| "then top to bottom.\n") | |
| self.notes = ["Order the photos by when they were taken (EXIF DateTimeOriginal), earliest first, not by " | |
| "file name."] | |
| def _g2(self) -> bool: | |
| path = self.ws / self.out | |
| if not path.is_file(): | |
| return False | |
| stats = self._analyze("tiles", path, self.cols, self.rows, self.tw, self.th) | |
| if tuple(stats.get("size", ())) != (self.cols * self.tw, self.rows * self.th): | |
| return False | |
| return all(abs(a - b) <= 12 for a, b in zip(stats["tiles"], self.expected)) | |
| # -- variant 3: audio delivery --------------------------------------------------------------------- | |
| def _v3(self): | |
| r = self.rng | |
| self.lead = r.choice([1.0, 1.5, 2.0]) | |
| self.rate = r.choice([16000, 22050, 24000]) | |
| self.peak = r.choice([-1.0, -2.0, -3.0]) | |
| self.trim = r.random() < 0.5 | |
| self._sh(f"ffmpeg -v error -f lavfi -i anullsrc=r=44100:cl=stereo:d={self.lead} -f lavfi " | |
| f"-i sine=frequency={r.choice([300, 500, 700])}:duration=4:sample_rate=44100 " | |
| "-filter_complex '[1]volume=-14dB,aformat=channel_layouts=stereo[t];[0][t]concat=n=2:v=0:a=1' " | |
| "-c:a pcm_s16le take.wav", self.ws, 60) | |
| shutil.copy(self.ws / "take.wav", self.private / "take.wav") | |
| self.out = "deliver/voice.flac" | |
| self.spec = (f"# Audio delivery\n\nDeliver take.wav as {self.out}: FLAC, mono, {self.rate} Hz, normalised so " | |
| f"the peak sample is at {self.peak:g} dBFS (within 0.5 dB).\n") | |
| self.notes = ["Cut the silence at the start: the delivery must begin within 0.1 s of the first sound." | |
| if self.trim else "Keep the timing exactly as recorded, including the silence at the start."] | |
| def _g3(self) -> bool: | |
| path = self.ws / self.out | |
| info = ffprobe(path, self.ws) | |
| audio = [s for s in info.get("streams", []) if s.get("codec_type") == "audio"] | |
| if len(audio) != 1 or audio[0].get("codec_name") != "flac" or audio[0].get("channels") != 1: | |
| return False | |
| if int(audio[0].get("sample_rate", 0)) != self.rate: | |
| return False | |
| code, out = runner.run(f"ffmpeg -v error -i '{path}' -f s16le -ac 1 - | od -An -v -td2", self.ws, timeout=30) | |
| samples = [int(v) for v in out.split() if v.lstrip("-").isdigit()] | |
| if not samples: | |
| return False | |
| peak = max(abs(s) for s in samples) | |
| if peak == 0 or abs(20 * math.log10(peak / 32768) - self.peak) > 0.5: | |
| return False | |
| first = next(i for i, s in enumerate(samples) if abs(s) > peak * 0.05) / self.rate | |
| return first <= 0.1 if self.trim else abs(first - self.lead) <= 0.1 | |
| # -- shared ---------------------------------------------------------------------------------------- | |
| def _analyze(self, *args) -> dict: | |
| script = self.private / "analyze.py" | |
| script.write_text(ANALYZE) | |
| # copy the script where nobody can read it but the policy cannot have changed it | |
| tmp = runner.new_workspace("an-") | |
| try: | |
| shutil.copy(script, tmp / "analyze.py") | |
| target = Path(args[1]) | |
| shutil.copy(target, tmp / ("in" + target.suffix)) | |
| runner.give_to_nobody(tmp) | |
| extra = " ".join(str(a) for a in args[2:]) | |
| code, out = runner.run(f"python -I analyze.py {args[0]} in{target.suffix} {extra}", tmp, timeout=30) | |
| finally: | |
| runner.remove(tmp) | |
| try: | |
| return json.loads(out.strip().splitlines()[-1]) | |
| except (json.JSONDecodeError, IndexError): | |
| return {} | |
| def brief(self): | |
| pointer = " Read spec.md and notes.md first." if self.level == 1 else " The brief is in spec.md." | |
| return ("MEDIA. Production desk. Produce the deliverable described in this workspace with the tools on this " | |
| f"machine (ffmpeg, ffprobe, ImageMagick's magick/convert, Python with Pillow).{pointer} Submit when " | |
| "the files are in place.") | |
| def tools(self): | |
| return self.coding_tools(tests=False) + [Tool("submit", "submit the deliverable (ends the episode)", | |
| self.grade, final=True)] | |
| def grade(self, a=None) -> float: | |
| try: | |
| if self.variant == 0: | |
| return float(self._g0(self.ws / self.out)) | |
| return float(getattr(self, f"_g{self.variant}")()) | |
| except Exception: | |
| return 0.0 | |
| def oracle(self): | |
| """Produce a correct deliverable with the tools (used by tests).""" | |
| if self.variant == 0: | |
| audio = "-ac 1 -c:a aac" if self.mono else "-an" | |
| cmd = (f"mkdir -p deliver && ffmpeg -v error -y -ss {self.a} -i input.mp4 -t {self.b - self.a} " | |
| f"-vf scale={self.w}:-2,fps={self.fps} -c:v libx264 -preset ultrafast {audio} {self.out}") | |
| elif self.variant == 1: | |
| keep = " ".join(f"'{s}'" for s in self.expected) | |
| cmd = ("mkdir -p thumbs && python -c \"import sys\nfrom PIL import Image, ImageOps\nfor s in sys.argv[1:]:\n" | |
| f" ImageOps.fit(ImageOps.exif_transpose(Image.open(f'photos/{{s}}.jpg')), ({self.size},{self.size}))" | |
| f".save(f'thumbs/{{s}}.png')\" {keep}") | |
| elif self.variant == 2: | |
| order = " ".join(p[0] for p in sorted(self.photos, key=lambda p: p[3])) | |
| cmd = ("python -c \"import sys\nfrom PIL import Image, ImageOps\n" | |
| f"sheet = Image.new('RGB', ({self.cols * self.tw}, {self.rows * self.th}))\n" | |
| "for i, s in enumerate(sys.argv[1:]):\n" | |
| f" t = ImageOps.fit(ImageOps.exif_transpose(Image.open(f'photos/{{s}}.jpg')), ({self.tw},{self.th}))\n" | |
| f" sheet.paste(t, ((i % {self.cols}) * {self.tw}, (i // {self.cols}) * {self.th}))\n" | |
| f"sheet.save('{self.out}')\" {order}") | |
| else: | |
| trim = "silenceremove=start_periods=1:start_threshold=-50dB," if self.trim else "" | |
| cmd = (f"mkdir -p deliver && ffmpeg -v error -y -i take.wav -af {trim}aresample={self.rate} -ac 1 tmp.wav " | |
| f"&& G=$(ffmpeg -i tmp.wav -af volumedetect -f null - 2>&1 | sed -n 's/.*max_volume: \\(.*\\) dB/\\1/p') " | |
| f"&& ffmpeg -v error -y -i tmp.wav -af volume=$(python -c \"print({self.peak} - ($G))\")dB " | |
| f"-ar {self.rate} -ac 1 {self.out} && rm tmp.wav") | |
| code, out = runner.run(cmd, self.ws, timeout=120) | |
| assert code == 0, out[-800:] | |