| 588 | |
| 589 | @staticmethod |
| 590 | def load_json(data: str | bytes | TextIOWrapper | BinaryIO, load_assets: bool = True, _name: Optional[str] = None): # noqa: C901 |
| 591 | _dir_for_name = None |
| 592 | |
| 593 | if _name is None: |
| 594 | if hasattr(data, "name"): |
| 595 | _dir_for_name = data.name |
| 596 | |
| 597 | if not isinstance(_name, str) and _name is not None: |
| 598 | _name = str(_name) |
| 599 | |
| 600 | if isinstance(data, bytes): |
| 601 | data = BytesIO(data) |
| 602 | |
| 603 | elif isinstance(data, str): |
| 604 | _dir_for_name = data |
| 605 | data = open(data, "rb") |
| 606 | |
| 607 | if _name is None and _dir_for_name is not None: |
| 608 | # Remove any directory names and the file extension |
| 609 | _name = _dir_for_name.split("/")[-1] |
| 610 | _name = ".".join(_name.split(".")[:-1]) |
| 611 | |
| 612 | asset_data = [] |
| 613 | with data: |
| 614 | # For if the sprite3 is just JSON (e.g. if it's exported from scratchattach) |
| 615 | if commons.is_valid_json(data): |
| 616 | json_str = data |
| 617 | |
| 618 | else: |
| 619 | with ZipFile(data) as archive: |
| 620 | json_str = archive.read("sprite.json") |
| 621 | |
| 622 | # Also load assets |
| 623 | if load_assets: |
| 624 | for filename in archive.namelist(): |
| 625 | if filename != "sprite.json": |
| 626 | md5_hash = filename.split(".")[0] |
| 627 | |
| 628 | asset_data.append(asset.AssetFile(filename, archive.read(filename), md5_hash)) |
| 629 | else: |
| 630 | warnings.warn( |
| 631 | "Loading sb3 without loading assets. When exporting the project, there may be errors due to assets not being uploaded to the Scratch website" |
| 632 | ) |
| 633 | |
| 634 | return _name, asset_data, json_str |
| 635 | |
| 636 | @classmethod |
| 637 | def from_sprite3(cls, data: str | bytes | TextIOWrapper | BinaryIO, load_assets: bool = True, _name: Optional[str] = None): |