Blacken the code base.

This commit is contained in:
yrriban 2025-12-24 18:35:43 -05:00
parent d585c1529d
commit 07d079f204
19 changed files with 138 additions and 168 deletions

View file

@ -1,5 +1,5 @@
import sys
from dcc.main import main
if __name__ == '__main__':
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))

View file

@ -34,12 +34,10 @@ class Concat(dcc.doom_base.Wad):
+ f"to{parsed_args.end_map}"
)
output = av.open(
self.fabricate.joinpath(parsed_args.wad).joinpath(
f"{fn_base}.mp4"), "w"
self.fabricate.joinpath(parsed_args.wad).joinpath(f"{fn_base}.mp4"), "w"
)
summary_file = open(
self.fabricate.joinpath(parsed_args.wad).joinpath(
f"{fn_base}.txt"), "w"
self.fabricate.joinpath(parsed_args.wad).joinpath(f"{fn_base}.txt"), "w"
)
self._offset = 0
@ -66,11 +64,13 @@ class Concat(dcc.doom_base.Wad):
start_time = self._offset / 1000000
text = self._add_chunk(
videodir.joinpath(f"{parsed_args.wad}_map{idx}.mp4"),
output, not parsed_args.nooverlay
output,
not parsed_args.nooverlay,
)
list.append(
summary, f"{text} {math.floor(start_time / 60):02}:"
+ f"{math.floor(start_time % 60):02}"
summary,
f"{text} {math.floor(start_time / 60):02}:"
+ f"{math.floor(start_time % 60):02}",
)
if state == State.DONE:
break
@ -82,8 +82,7 @@ class Concat(dcc.doom_base.Wad):
def _add_chunk(self, v, output, overlay):
chunk = av.open(v)
if not (len(chunk.streams.video) == 1
and len(chunk.streams.audio) == 1):
if not (len(chunk.streams.video) == 1 and len(chunk.streams.audio) == 1):
raise Exception(
f"irregular chunk {v}: streams {chunk.streams} "
+ f"(expected 1 video & 1 audio)"
@ -96,16 +95,11 @@ class Concat(dcc.doom_base.Wad):
text = ""
if overlay:
img = wand.image.Image(
height=chunk.streams[0].height,
width=chunk.streams[0].width
height=chunk.streams[0].height, width=chunk.streams[0].width
)
mapstring = v.name[-6:-4]
text = self._config["map_names"][f"map{mapstring}"]
self.draw_text(
img,
f"MAP{mapstring}: {text}",
font_size=120
)
self.draw_text(img, f"MAP{mapstring}: {text}", font_size=120)
img.trim(reset_coords=True)
img.border("graya(25%, 25%)", 10, 10)
img.border(self.thumbnail_text_stroke, 16, 16)
@ -113,10 +107,7 @@ class Concat(dcc.doom_base.Wad):
# multiple of 8. dude whyyyyyyy
padfactor = 8
img.border("transparent", padfactor, 0)
img.crop(
width=img.width - img.width % padfactor,
height=img.height
)
img.crop(width=img.width - img.width % padfactor, height=img.height)
if len(output.streams.get()) == 0:
# We can't use the input stream as a template here; it doesn't
@ -145,12 +136,10 @@ class Concat(dcc.doom_base.Wad):
oas.bit_rate = astr.bit_rate
src = ograph.add_buffer(
template=chunk.streams.video[0],
time_base=chunk.streams.video[0].time_base
template=chunk.streams.video[0], time_base=chunk.streams.video[0].time_base
)
asrc = ograph.add_abuffer(
template=chunk.streams.audio[0],
time_base=chunk.streams.audio[0].time_base
template=chunk.streams.audio[0], time_base=chunk.streams.audio[0].time_base
)
# TODO: video fades are absolute relative to the input video; audio
# fades need to have their timestamps offset by the position in the
@ -163,19 +152,18 @@ class Concat(dcc.doom_base.Wad):
iafade_start = self._offset * sample_rate / 1000000
iafade = ograph.add("afade", args=f"in:{iafade_start}:{sample_rate}")
oafade_start = (
(self._offset + chunk.duration) * sample_rate / 1000000
- sample_rate
)
self._offset + chunk.duration
) * sample_rate / 1000000 - sample_rate
oafade = ograph.add("afade", args=f"out:{oafade_start}:{sample_rate}")
if overlay:
overlay = ograph.add_buffer(
width=img.width, height=img.height,
format="rgba", time_base=chunk.streams.video[0].time_base
)
overlay_fo = ograph.add(
"fade", args=f"out:{4 * frame_rate}:{frame_rate}"
width=img.width,
height=img.height,
format="rgba",
time_base=chunk.streams.video[0].time_base,
)
overlay_fo = ograph.add("fade", args=f"out:{4 * frame_rate}:{frame_rate}")
overlay.link_to(overlay_fo, 0, 0)
composite = ograph.add("overlay", args="x=4:y=4")
src.link_to(composite, 0, 0)
@ -194,9 +182,8 @@ class Concat(dcc.doom_base.Wad):
for packet in chunk.demux():
if packet.dts is None:
continue
pof = (
(self._offset * packet.time_base.denominator)
/ (packet.time_base.numerator * 1000000)
pof = (self._offset * packet.time_base.denominator) / (
packet.time_base.numerator * 1000000
)
packet.dts += pof
packet.pts += pof
@ -221,9 +208,7 @@ class Concat(dcc.doom_base.Wad):
def _make_text_frame(self, img, ifr):
# We need to give each frame its own memory it can own.
text_frame = av.video.frame.VideoFrame(
img.width, img.height, format="rgba"
)
text_frame = av.video.frame.VideoFrame(img.width, img.height, format="rgba")
text_frame.planes[0].update(img.make_blob(format="rgba"))
text_frame.pts = ifr.pts
text_frame.dts = ifr.dts

View file

@ -12,13 +12,15 @@ class ConfigBase(object):
self._doom = pathlib.Path(parsed_args.doom)
self._config_name = parsed_args.config_name
self._config = tomlkit.toml_file.TOMLFile(
self.doom.joinpath(self.config_name)).read()
self.doom.joinpath(self.config_name)
).read()
self._dsda = self._config.get("dsda")
if self._dsda is None:
raise Exception(
"required key 'dsda' not set in config "
+ f"{self.doom.joinpath(self.config_name)}.")
+ f"{self.doom.joinpath(self.config_name)}."
)
for d in ("iwads", "pwads", "demos", "fabricate"):
self._init_attr([d], d, fn=self.doom.joinpath)
@ -29,10 +31,7 @@ class ConfigBase(object):
self._init_attr(["thumbnail", "text_fill"], "white")
self._init_attr(["thumbnail", "text_stroke"], "red")
self._init_attr(["thumbnail", "overlay_name"], "M_DOOM_scaled.png")
self._init_attr(
["fetch", "mirror"],
"https://youfailit.net/pub/idgames"
)
self._init_attr(["fetch", "mirror"], "https://youfailit.net/pub/idgames")
def _init_attr(self, what, default, fn=lambda x: x):
propname = "_".join(what)
@ -45,8 +44,7 @@ class ConfigBase(object):
setattr(self, f"_{propname}", fn(val))
setattr(
type(self), propname,
property(lambda self: getattr(self, f"_{propname}"))
type(self), propname, property(lambda self: getattr(self, f"_{propname}"))
)
@property
@ -65,10 +63,10 @@ class ConfigBase(object):
def get_parser_func(toc):
def add_common_args(self, prog_name):
parser = super(toc, self).get_parser(prog_name)
parser.add_argument(
"--doom", default=pathlib.Path.home().joinpath("doom"))
parser.add_argument("--doom", default=pathlib.Path.home().joinpath("doom"))
parser.add_argument("--config-name", default="config.toml")
return parser
return add_common_args

View file

@ -22,12 +22,10 @@ class Configure(dcc.doom_base.Wad):
wad = omg.WadIO(w)
complevel = wad.read("COMPLVL").decode("ascii").strip()
except Exception as e:
print(
f"Wad {w} likely has no lump COMPLVL (exception {e})")
print(f"Wad {w} likely has no lump COMPLVL (exception {e})")
if complevel is None:
complevel = input("Complevel? ")
doc = tomlkit.document()
doc.add("complevel", complevel)
if parsed_args.iwad is not None:

View file

@ -70,9 +70,8 @@ class Wad(dcc.config.Base):
return []
def thumb_overlay_path(self):
return (
self._ensure(self.fabricate.joinpath(self.wad))
.joinpath(self.thumbnail_overlay_name)
return self._ensure(self.fabricate.joinpath(self.wad)).joinpath(
self.thumbnail_overlay_name
)
@ -129,55 +128,49 @@ class WadMap(Wad):
def demo_in_path(self):
candidates = [
x for x in self.demos.joinpath(self.wad)
.glob(self._file_base("*.lmp"))
x for x in self.demos.joinpath(self.wad).glob(self._file_base("*.lmp"))
]
if len(candidates) == 0:
raise Exception(
"no suitable demo candidates for WAD {} MAP {} name {}."
.format(self.wad, self.map, self.name_string)
"no suitable demo candidates for WAD {} MAP {} name {}.".format(
self.wad, self.map, self.name_string
)
)
if len(candidates) == 1:
return candidates[0]
return sorted(filter(lambda s: re.search("-", str(s)), candidates))[-1]
def dsda_text_path(self):
return (
self._ensure(self.demos.joinpath(self.wad))
.joinpath(self._file_base(".txt"))
return self._ensure(self.demos.joinpath(self.wad)).joinpath(
self._file_base(".txt")
)
def video_path(self):
return (
self._ensure(self.fabricate.joinpath(self.wad))
.joinpath(self._file_base(".mp4"))
return self._ensure(self.fabricate.joinpath(self.wad)).joinpath(
self._file_base(".mp4")
)
def demo_out_path(self):
return (
self._ensure(self.demos.joinpath(self.wad))
.joinpath(self._file_base(".lmp"))
return self._ensure(self.demos.joinpath(self.wad)).joinpath(
self._file_base(".lmp")
)
def target_bucket(self):
return "doom/" + self._file_base(".lmp")
def base_thumb_path(self):
return (
self._ensure(self.fabricate.joinpath(self.wad))
.joinpath(self._file_base("_base.png"))
return self._ensure(self.fabricate.joinpath(self.wad)).joinpath(
self._file_base("_base.png")
)
def text_thumb_path(self):
return (
self._ensure(self.fabricate.joinpath(self.wad))
.joinpath(self._file_base("_text.png"))
return self._ensure(self.fabricate.joinpath(self.wad)).joinpath(
self._file_base("_text.png")
)
def thumb_path(self):
return (
self._ensure(self.fabricate.joinpath(self.wad))
.joinpath(self._file_base("_thumb.png"))
return self._ensure(self.fabricate.joinpath(self.wad)).joinpath(
self._file_base("_thumb.png")
)
def _file_base(self, ext):

View file

@ -22,10 +22,9 @@ class DSDA(dcc.doom_base.WadMap):
if shutil.which("xvfb-run") is not None:
command = ["xvfb-run"] + command
subprocess.run(
command + self.dsda_preamble(warp=False) + [
"-fastdemo", dip, "-nosound",
"-skiptic", "-1", "-export_text_file"
]
command
+ self.dsda_preamble(warp=False)
+ ["-fastdemo", dip, "-nosound", "-skiptic", "-1", "-export_text_file"]
)
editor = "nano"
if "EDITOR" in os.environ:

View file

@ -24,7 +24,11 @@ class Eureka(dcc.doom_base.WadMap):
if complevel == "11" or complevel == "21":
port = "mbf"
os.execvp("eureka",
["eureka"] + ["-iwad", iwad] + ["-w", parsed_args.map]
+ ["-p", port] + [mw]
os.execvp(
"eureka",
["eureka"]
+ ["-iwad", iwad]
+ ["-w", parsed_args.map]
+ ["-p", port]
+ [mw],
)

View file

@ -8,7 +8,7 @@ import wand.image
class Extract(dcc.doom_base.Wad):
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
parser.add_argument('lump')
parser.add_argument("lump")
return parser
def take_action(self, parsed_args):
@ -24,8 +24,9 @@ class Extract(dcc.doom_base.Wad):
) as img:
img.transparent_color(wand.color.Color("#ff00ff"), 0.0)
img.save(
filename=self.fabricate.joinpath(parsed_args.wad)
.joinpath(parsed_args.lump + ".png")
filename=self.fabricate.joinpath(parsed_args.wad).joinpath(
parsed_args.lump + ".png"
)
)
return
except Exception as e:
@ -35,6 +36,5 @@ class Extract(dcc.doom_base.Wad):
)
print(
f"Lump {parsed_args.lump} not found in any wad in "
+ f"{parsed_args.wad}"
f"Lump {parsed_args.lump} not found in any wad in " + f"{parsed_args.wad}"
)

View file

@ -18,10 +18,12 @@ class Fabricate(dcc.doom_base.WadMap):
command = [self.dsda]
if not parsed_args.fg and shutil.which("xvfb-run") is not None:
command = ["xvfb-run"] + command
os.execvp(command[0],
command + self.dsda_preamble()
os.execvp(
command[0],
command
+ self.dsda_preamble()
+ ["-timedemo", self.demo_in_path()]
+ ["-viddump", self.video_path()]
+ ["-viddump", self.video_path()],
)
def options_dict(self):

View file

@ -21,14 +21,12 @@ class Fetch(dcc.config.Base):
idgames_id = self.search_idgames(parsed_args.id_or_name)
reply = self.fetch_url(
"https://www.doomworld.com/idgames/api/" +
"api.php?action=get&id={}&out=json".format(idgames_id)
"https://www.doomworld.com/idgames/api/"
+ "api.php?action=get&id={}&out=json".format(idgames_id)
)
rpath = "/".join(
[self.fetch_mirror, reply["content"]["dir"], reply["content"]["filename"]]
)
rpath = "/".join([
self.fetch_mirror,
reply["content"]["dir"],
reply["content"]["filename"]
])
wad = reply["content"]["filename"][0:-4]
with urllib.request.urlopen(rpath) as response:
@ -38,8 +36,8 @@ class Fetch(dcc.config.Base):
# TODO: explicit error handling. Let users choose when >1 result.
def search_idgames(self, wad):
reply = self.fetch_url(
"https://www.doomworld.com/idgames/api/" +
"api.php?action=search&query={}&out=json".format(wad)
"https://www.doomworld.com/idgames/api/"
+ "api.php?action=search&query={}&out=json".format(wad)
)
if "content" not in reply:
sys.exit(f"No WAD named {wad} found on idgames.")
@ -62,8 +60,5 @@ class Fetch(dcc.config.Base):
if fetcher_path is None:
raise Exception(f"Fetch util {fetcher} not found on PATH.")
proc = subprocess.run(
[fetcher_path, url],
capture_output=True, check=True
)
proc = subprocess.run([fetcher_path, url], capture_output=True, check=True)
return json.loads(proc.stdout)

View file

@ -12,16 +12,13 @@ class List(dcc.config.ListerBase):
match parsed_args.target:
case "pwads":
return (
("pwads",), sorted(
(x.name,) for x in os.scandir(self.pwads) if x.is_dir()
)
("pwads",),
sorted((x.name,) for x in os.scandir(self.pwads) if x.is_dir()),
)
case "iwads":
return (
("iwads",), sorted(
(x.name,) for x in
os.scandir(self.iwads) if x.is_file()
)
("iwads",),
sorted((x.name,) for x in os.scandir(self.iwads) if x.is_file()),
)
case _:
raise Exception(f"unknown target {parsed_args.target}")
@ -35,11 +32,12 @@ class WadList(dcc.config.ListerBase):
def _get_results(self, name, base, wad, ext):
return (
(name,), sorted(
(x.name,) for x in
os.scandir(base.joinpath(wad))
(name,),
sorted(
(x.name,)
for x in os.scandir(base.joinpath(wad))
if x.name.endswith(ext)
)
),
)
@ -50,6 +48,4 @@ class ListDemos(WadList):
class ListVideos(WadList):
def take_action(self, parsed_args):
return self._get_results(
"videos", self.fabricate, parsed_args.wad, ".mp4"
)
return self._get_results("videos", self.fabricate, parsed_args.wad, ".mp4")

View file

@ -68,5 +68,5 @@ def main(argv=sys.argv[1:]):
return dcc.run(argv)
if __name__ == '__main__':
if __name__ == "__main__":
sys.exit(main())

View file

@ -10,14 +10,13 @@ class Put(dcc.doom_base.WadMap):
# TODO: accept configuration for bucket name
def take_action(self, parsed_args):
s3_client = boto3.client('s3')
s3_client = boto3.client("s3")
demo = self.demo_in_path()
bucket = self.target_bucket()
print("Uploading {} to bucket {}.".format(demo, bucket))
s3_client.upload_file(
demo, 'yrriban', bucket,
ExtraArgs={
'ContentType': 'binary/octet-stream',
'ACL': 'public-read'
}
demo,
"yrriban",
bucket,
ExtraArgs={"ContentType": "binary/octet-stream", "ACL": "public-read"},
)

View file

@ -5,9 +5,9 @@ import os
class Record(dcc.doom_base.WadMap):
def take_action(self, parsed_args):
os.execv(self.dsda,
[self.dsda] + self.dsda_preamble() +
["-record", self.demo_out_path()]
os.execv(
self.dsda,
[self.dsda] + self.dsda_preamble() + ["-record", self.demo_out_path()],
)
def options_dict(self):

View file

@ -16,10 +16,10 @@ class RIB(dcc.doom_base.WadMap):
demo = ""
dt = 0
demodir = (
pathlib.Path.home() /
".dsda-doom" /
"dsda_doom_data" /
self.iwad_path.stem.lower()
pathlib.Path.home()
/ ".dsda-doom"
/ "dsda_doom_data"
/ self.iwad_path.stem.lower()
)
for w in self.load_order():
demodir = demodir.joinpath(w.stem.lower())
@ -41,8 +41,10 @@ class RIB(dcc.doom_base.WadMap):
+ f"and map {parsed_args.map} (tried to look in {demodir})"
)
os.execv(self.dsda,
[self.dsda] + self.dsda_preamble(warp=False)
os.execv(
self.dsda,
[self.dsda]
+ self.dsda_preamble(warp=False)
+ ["-playdemo", demo]
+ ["-skiptic", str(-35 * parsed_args.secs_before)]
+ ["-skiptic", str(-35 * parsed_args.secs_before)],
)

View file

@ -22,11 +22,11 @@ class SS(dcc.doom_base.WadMap):
height = self.thumbnail_height
with wand.image.Image(width=width, height=height, pseudo="x:") as img:
img.reset_coords()
if (img.width < width or img.height < height):
if img.width < width or img.height < height:
if not messagebox.askretrycancel(
title="DCC",
message=f"Image too small ({img.width}x{img.height})." +
"Try again?"
message=f"Image too small ({img.width}x{img.height})."
+ "Try again?",
):
sys.exit("Gave up trying to select an image.")
return False

View file

@ -30,9 +30,7 @@ def draw_text(self, img, text, font_size=64, wrap_dist=0.75):
columns = len(wrapped_text)
while columns > 0:
columns -= 1
wrapped_text = '\n'.join(
textwrap.wrap(wrapped_text, columns)
)
wrapped_text = "\n".join(textwrap.wrap(wrapped_text, columns))
wrapped_width, _ = eval_metrics(wrapped_text)
if wrapped_width <= target_width:
break
@ -43,7 +41,7 @@ def draw_text(self, img, text, font_size=64, wrap_dist=0.75):
)
textlines[idx] = wrapped_text
wrapped_text = '\n'.join(textlines)
wrapped_text = "\n".join(textlines)
draw.text(5, int(draw.font_size) + 5, wrapped_text)
draw(img)
@ -74,12 +72,9 @@ class Text(dcc.doom_base.WadMap):
text += "\n"
text = "{}{}".format(text, parsed_args.demotype)
with wand.image.Image(
height=self.thumbnail_height,
width=self.thumbnail_width
height=self.thumbnail_height, width=self.thumbnail_width
) as img:
self.draw_text(
img, text, wrap_dist=0.95
)
self.draw_text(img, text, wrap_dist=0.95)
img.trim()
img.reset_coords()
img.save(filename=self.text_thumb_path())

View file

@ -17,7 +17,7 @@ class Thumb(dcc.doom_base.WadMap):
overlay = self.thumb_overlay_path()
with (
wand.image.Image(filename=base) as bi,
wand.color.Color("transparent") as tc
wand.color.Color("transparent") as tc,
):
with wand.image.Image(filename=text) as ti:
ti.border(tc, 5, 5)

View file

@ -32,7 +32,9 @@ def test_play(expect):
rig._hooks = []
parser = rig.get_parser("test_play")
parsed_args = parser.parse_args(args=["--doom", td, "scythe", "01"])
with expect(os, times=1).execv(
with (
expect(os, times=1)
.execv(
tdp.joinpath("dsda-doom").joinpath("exe"),
[
tdp.joinpath("dsda-doom").joinpath("exe"),
@ -46,6 +48,8 @@ def test_play(expect):
"4",
"-warp",
"01",
]
).thenReturn(None):
],
)
.thenReturn(None)
):
assert rig.run(parsed_args) is None