Switched compose to be class-based
All checks were successful
All checks were successful
This commit is contained in:
parent
fc80fc9b84
commit
27d7598f81
8 changed files with 102 additions and 97 deletions
|
@ -46,9 +46,8 @@ This would generate the expressions for Scathach (Servant Id 70) in the folder o
|
||||||
`skyeweave` can also be used in other Python scripts.
|
`skyeweave` can also be used in other Python scripts.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from skyeweave import compose
|
from skyeweave import SkyeWeave
|
||||||
|
SkyeWeave().compose(70)
|
||||||
compose(70)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
This feature will be expanded upon in future releases.
|
This feature will be expanded upon in future releases.
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
[project]
|
[project]
|
||||||
name = "skyeweave"
|
name = "skyeweave"
|
||||||
version = "1.0.0-c.2"
|
version = "1.0.0-c.3"
|
||||||
requires-python = ">= 3.10"
|
requires-python = ">= 3.10"
|
||||||
authors = [{name = "Firq", email = "firelp42@gmail.com"}]
|
authors = [{name = "Firq", email = "firelp42@gmail.com"}]
|
||||||
maintainers = [{name = "Firq", email = "firelp42@gmail.com"}]
|
maintainers = [{name = "Firq", email = "firelp42@gmail.com"}]
|
||||||
|
|
|
@ -2,4 +2,4 @@ import importlib.metadata
|
||||||
|
|
||||||
__version__ = importlib.metadata.version(__package__ or "skyeweave")
|
__version__ = importlib.metadata.version(__package__ or "skyeweave")
|
||||||
|
|
||||||
from .service import compose
|
from .service import SkyeWeave
|
||||||
|
|
|
@ -5,7 +5,7 @@ import sys
|
||||||
from typing import List
|
from typing import List
|
||||||
|
|
||||||
from .. import __version__
|
from .. import __version__
|
||||||
from ..service import compose
|
from ..service import SkyeWeave
|
||||||
from ..config import AtlasAPIConfig, LoggingConfig, PathConfig
|
from ..config import AtlasAPIConfig, LoggingConfig, PathConfig
|
||||||
from ..utils import rmdir, disable_tqdm
|
from ..utils import rmdir, disable_tqdm
|
||||||
|
|
||||||
|
@ -91,4 +91,4 @@ def run():
|
||||||
rmdir(PathConfig.IMAGES)
|
rmdir(PathConfig.IMAGES)
|
||||||
LOGGER.info("Successfully reset local storage")
|
LOGGER.info("Successfully reset local storage")
|
||||||
|
|
||||||
compose(input_id, args.filter)
|
SkyeWeave().compose(input_id, args.filter)
|
||||||
|
|
|
@ -1 +1 @@
|
||||||
from .compose import compose
|
from .compose import SkyeWeave
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
import logging
|
import logging
|
||||||
|
import pathlib
|
||||||
from typing import Annotated, List, NotRequired, Tuple, TypedDict
|
from typing import Annotated, List, NotRequired, Tuple, TypedDict
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
|
@ -61,12 +62,11 @@ def fetch_mstsvtjson():
|
||||||
break
|
break
|
||||||
handle.write(block)
|
handle.write(block)
|
||||||
|
|
||||||
def fetch_expression_sheets(basefolder: str, imageid: str):
|
def fetch_expression_sheets(tempfolder: pathlib.Path, imageid: str):
|
||||||
atlasurl_base = f"https://static.atlasacademy.io/{AtlasAPIConfig.REGION}/CharaFigure/{imageid}"
|
atlasurl_base = f"https://static.atlasacademy.io/{AtlasAPIConfig.REGION}/CharaFigure/{imageid}"
|
||||||
|
|
||||||
savefolder = PathConfig.IMAGES / basefolder / str(imageid)
|
savefolder = tempfolder / str(imageid)
|
||||||
if not savefolder.is_dir():
|
savefolder.mkdir(exist_ok=True, parents=True)
|
||||||
savefolder.mkdir(exist_ok=True, parents=True)
|
|
||||||
|
|
||||||
idx, status = 0, 200
|
idx, status = 0, 200
|
||||||
|
|
||||||
|
|
|
@ -11,106 +11,115 @@ from .atlas import SpritesheetData, fetch_data, fetch_expression_sheets, fetch_c
|
||||||
|
|
||||||
LOGGER = logging.getLogger(LoggingConfig.NAME)
|
LOGGER = logging.getLogger(LoggingConfig.NAME)
|
||||||
|
|
||||||
def compose(input_id: int, filters: Optional[List[str]] = None):
|
class SkyeWeave:
|
||||||
PathConfig.IMAGES.mkdir(exist_ok=True)
|
output_folder: pathlib.Path
|
||||||
PathConfig.OUTPUT.mkdir(exist_ok=True)
|
image_folder: pathlib.Path
|
||||||
|
|
||||||
if input_id < 10000:
|
def __init__(self, output: Optional[pathlib.Path] = None, assets: Optional[pathlib.Path] = None):
|
||||||
chara_ids = fetch_data(input_id)
|
self.output_folder = output or PathConfig.OUTPUT
|
||||||
savefolder = PathConfig.OUTPUT / str(input_id)
|
self.image_folder = assets or PathConfig.IMAGES
|
||||||
else:
|
|
||||||
LOGGER.info(f"Processing manually uploaded charaId {input_id}")
|
self.output_folder.mkdir(exist_ok=True)
|
||||||
savefolder = PathConfig.OUTPUT / "manual"
|
self.image_folder.mkdir(exist_ok=True)
|
||||||
chara_ids = [str(input_id)]
|
|
||||||
|
def compose(self, input_id: int, filters: Optional[List[str]] = None):
|
||||||
|
if input_id < 10000:
|
||||||
|
chara_ids = fetch_data(input_id)
|
||||||
|
savefolder, tempfolder = self.output_folder / str(input_id), self.image_folder / str(input_id)
|
||||||
|
else:
|
||||||
|
LOGGER.info(f"Processing manually uploaded charaId {input_id}")
|
||||||
|
savefolder, tempfolder = self.output_folder / "manual", self.image_folder / "manual"
|
||||||
|
chara_ids = [str(input_id)]
|
||||||
|
|
||||||
if not savefolder.is_dir():
|
|
||||||
savefolder.mkdir(parents=True, exist_ok=True)
|
savefolder.mkdir(parents=True, exist_ok=True)
|
||||||
|
tempfolder.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
if filters is not None:
|
chara_ids = [ v for v in chara_ids if v in filters ] if filters else chara_ids
|
||||||
chara_ids = [ v for v in chara_ids if v in filters ]
|
LOGGER.debug(chara_ids)
|
||||||
LOGGER.debug(chara_ids)
|
|
||||||
|
|
||||||
for char_id in chara_ids:
|
for char_id in chara_ids:
|
||||||
expfolder = fetch_expression_sheets(savefolder.stem, char_id)
|
expfolder = fetch_expression_sheets(tempfolder, char_id)
|
||||||
config = fetch_config(char_id)
|
config = fetch_config(char_id)
|
||||||
process_sprite(expfolder, config, savefolder)
|
self.process_sprite(expfolder, config, savefolder)
|
||||||
|
|
||||||
LOGGER.info(f"Files have been saved at: {savefolder.absolute()}")
|
LOGGER.info(f"Files have been saved at: {savefolder.absolute()}")
|
||||||
|
|
||||||
|
def process_sprite(self, images_folder: pathlib.Path, configdata: SpritesheetData, outputfolder: pathlib.Path):
|
||||||
|
main_sprite = self._gen_main_sprite(images_folder / "0.png")
|
||||||
|
image_idx = self._save_sprite(main_sprite, outputfolder, f"{images_folder.stem}")
|
||||||
|
|
||||||
def calculate_counts(width: int, height: int, facesize: tuple[int, int]):
|
for i in images_folder.iterdir():
|
||||||
rowcount, colcount = height // facesize[1], width // facesize[0]
|
LOGGER.debug(f"Idx: {image_idx}")
|
||||||
LOGGER.debug(f"{height} | {facesize[1]} --> {rowcount}")
|
initial_row = 0
|
||||||
LOGGER.debug(f"{width} | {facesize[0]} --> {colcount}")
|
expressions = Image.open(i)
|
||||||
return rowcount, colcount
|
|
||||||
|
|
||||||
def gen_main_sprite(folder: pathlib.Path):
|
rowcount, colcount = self._calculate_counts(*expressions.size, configdata["facesize"])
|
||||||
image = Image.open(folder / "0.png")
|
|
||||||
width, height = image.size
|
|
||||||
LOGGER.debug(f"Main sprite ({folder}): {width}:{height}")
|
|
||||||
return image.crop((0, 0, width, height - 256))
|
|
||||||
|
|
||||||
def process_sprite(images_folder: pathlib.Path, configdata: SpritesheetData, outputfolder: pathlib.Path):
|
if i.name == "0.png" and 256 < configdata["facesize"][1]:
|
||||||
main_sprite = gen_main_sprite(images_folder)
|
continue
|
||||||
image_idx = save_sprite(main_sprite, outputfolder, f"{images_folder.stem}")
|
|
||||||
|
|
||||||
for i in images_folder.iterdir():
|
if i.name == "0.png":
|
||||||
LOGGER.debug(f"Idx: {image_idx}")
|
initial_row = rowcount - 1
|
||||||
initial_row = 0
|
|
||||||
expressions = Image.open(i)
|
|
||||||
|
|
||||||
rowcount, colcount = calculate_counts(*expressions.size, configdata["facesize"])
|
for x, y in tqdm_itertools.product(range(initial_row, rowcount), range(0, colcount), ascii="-=", desc=f"[PROG] [{LoggingConfig.NAME}]", bar_format="{desc} {percentage:3.0f}% |{bar}|"):
|
||||||
|
img = self._generate_sprite(main_sprite, expressions, x, y, configdata)
|
||||||
|
if img is not None:
|
||||||
|
image_idx = self._save_sprite(img, outputfolder, f"{images_folder.stem}", image_idx)
|
||||||
|
LOGGER.debug(f"{x}/{y} - {'Invalid' if img is None else 'Valid'} image")
|
||||||
|
|
||||||
if i.name == "0.png" and 256 < configdata["facesize"][1]:
|
@staticmethod
|
||||||
continue
|
def _calculate_counts(width: int, height: int, facesize: tuple[int, int]):
|
||||||
|
rowcount, colcount = height // facesize[1], width // facesize[0]
|
||||||
|
LOGGER.debug(f"{height} | {facesize[1]} --> {rowcount}")
|
||||||
|
LOGGER.debug(f"{width} | {facesize[0]} --> {colcount}")
|
||||||
|
return rowcount, colcount
|
||||||
|
|
||||||
if i.name == "0.png":
|
@staticmethod
|
||||||
initial_row = rowcount - 1
|
def _gen_main_sprite(imagepath: pathlib.Path):
|
||||||
|
image = Image.open(imagepath)
|
||||||
|
width, height = image.size
|
||||||
|
LOGGER.debug(f"Main sprite ({imagepath}): {width}:{height}")
|
||||||
|
return image.crop((0, 0, width, height - 256))
|
||||||
|
|
||||||
for x, y in tqdm_itertools.product(range(initial_row, rowcount), range(0, colcount), ascii="-=", desc=f"[PROG] [{LoggingConfig.NAME}]", bar_format="{desc} {percentage:3.0f}% |{bar}|"):
|
@staticmethod
|
||||||
img = generate_sprite(main_sprite, expressions, x, y, configdata)
|
def _generate_sprite(main_sprite: Image.Image, expressions: Image.Image, row: int, col: int, configdata: SpritesheetData) -> Image.Image | None:
|
||||||
if img is not None:
|
position, facesize = configdata["position"], configdata["facesize"]
|
||||||
image_idx = save_sprite(img, outputfolder, f"{images_folder.stem}", image_idx)
|
roi = (
|
||||||
LOGGER.debug(f"{x}/{y} - {'Invalid' if img is None else 'Valid'} image")
|
col * facesize[0],
|
||||||
|
row * facesize[1],
|
||||||
|
(col + 1) * facesize[0],
|
||||||
|
(row + 1) * facesize[1]
|
||||||
|
)
|
||||||
|
LOGGER.debug(roi)
|
||||||
|
expression = expressions.crop(roi)
|
||||||
|
|
||||||
|
if SkyeWeave._is_empty(expression):
|
||||||
|
LOGGER.debug("Image empty")
|
||||||
|
return None
|
||||||
|
|
||||||
def generate_sprite(main_sprite: Image.Image, expressions: Image.Image, row: int, col: int, configdata: SpritesheetData) -> Image.Image | None:
|
mask = Image.new("RGBA", (facesize[0], facesize[1]), (255,255,255,255))
|
||||||
position, facesize = configdata["position"], configdata["facesize"]
|
composition = main_sprite.copy()
|
||||||
roi = (
|
composition.paste(expression, position, mask)
|
||||||
col * facesize[0],
|
return composition
|
||||||
row * facesize[1],
|
|
||||||
(col + 1) * facesize[0],
|
|
||||||
(row + 1) * facesize[1]
|
|
||||||
)
|
|
||||||
LOGGER.debug(roi)
|
|
||||||
expression = expressions.crop(roi)
|
|
||||||
|
|
||||||
if is_empty(expression):
|
@staticmethod
|
||||||
LOGGER.debug("Image empty")
|
def _save_sprite(image: Image.Image, outputfolder: pathlib.Path, name: str, idx: int = 0) -> int:
|
||||||
return None
|
savefolder = outputfolder / name
|
||||||
|
if not savefolder.is_dir():
|
||||||
|
savefolder.mkdir()
|
||||||
|
outfile = savefolder / f"{idx}.png"
|
||||||
|
|
||||||
mask = Image.new("RGBA", (facesize[0], facesize[1]), (255,255,255,255))
|
with open(outfile, 'wb') as file:
|
||||||
composition = main_sprite.copy()
|
image.save(file)
|
||||||
composition.paste(expression, position, mask)
|
|
||||||
return composition
|
|
||||||
|
|
||||||
|
return idx + 1
|
||||||
|
|
||||||
def save_sprite(image: Image.Image, outputfolder: pathlib.Path, name: str, idx: int = 0) -> int:
|
@staticmethod
|
||||||
savefolder = outputfolder / name
|
def _is_empty(img: Image.Image):
|
||||||
if not savefolder.is_dir():
|
w, h = img.size
|
||||||
savefolder.mkdir()
|
croparea = (w * 0.375, h * 0.375, w * 0.625, h * 0.625 )
|
||||||
outfile = savefolder / f"{idx}.png"
|
data = Counter(img.crop(croparea).convert('LA').getdata())
|
||||||
|
LOGGER.debug(f"Counts: {len(data)}")
|
||||||
with open(outfile, 'wb') as file:
|
if len(data) < 6:
|
||||||
image.save(file)
|
return True
|
||||||
|
return False
|
||||||
return idx + 1
|
|
||||||
|
|
||||||
def is_empty(img: Image.Image):
|
|
||||||
w, h = img.size
|
|
||||||
croparea = (w * 0.375, h * 0.375, w * 0.625, h * 0.625 )
|
|
||||||
data = Counter(img.crop(croparea).convert('LA').getdata())
|
|
||||||
LOGGER.debug(f"Counts: {len(data)}")
|
|
||||||
if len(data) < 6:
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
3
test.py
3
test.py
|
@ -1,3 +0,0 @@
|
||||||
from skyeweave import compose
|
|
||||||
|
|
||||||
compose(70)
|
|
Loading…
Reference in a new issue