Load project JSON and assets from an .sb3 file/bytes/file path :return: Project name, asset data, json string
(data: str | bytes | TextIOWrapper | BinaryIO, load_assets: bool = True, _name: Optional[str] = None)
| 153 | |
| 154 | @staticmethod |
| 155 | def load_json(data: str | bytes | TextIOWrapper | BinaryIO, load_assets: bool = True, _name: Optional[str] = None): # noqa: C901 |
| 156 | """ |
| 157 | Load project JSON and assets from an .sb3 file/bytes/file path |
| 158 | :return: Project name, asset data, json string |
| 159 | """ |
| 160 | _dir_for_name = None |
| 161 | |
| 162 | if _name is None: |
| 163 | if hasattr(data, "name"): |
| 164 | _dir_for_name = data.name |
| 165 | |
| 166 | if not isinstance(_name, str) and _name is not None: |
| 167 | _name = str(_name) |
| 168 | |
| 169 | if isinstance(data, bytes): |
| 170 | data = BytesIO(data) |
| 171 | |
| 172 | elif isinstance(data, str): |
| 173 | _dir_for_name = data |
| 174 | data = open(data, "rb") |
| 175 | |
| 176 | if _name is None and _dir_for_name is not None: |
| 177 | # Remove any directory names and the file extension |
| 178 | _name = _dir_for_name.split("/")[-1] |
| 179 | _name = ".".join(_name.split(".")[:-1]) |
| 180 | |
| 181 | asset_data = [] |
| 182 | with data: |
| 183 | # For if the sb3 is just JSON (e.g. if it's exported from scratchattach) |
| 184 | if commons.is_valid_json(data): |
| 185 | json_str = data |
| 186 | |
| 187 | else: |
| 188 | with ZipFile(data) as archive: |
| 189 | json_str = archive.read("project.json") |
| 190 | |
| 191 | # Also load assets |
| 192 | if load_assets: |
| 193 | for filename in archive.namelist(): |
| 194 | if filename != "project.json": |
| 195 | md5_hash = filename.split(".")[0] |
| 196 | |
| 197 | asset_data.append(asset.AssetFile(filename, archive.read(filename), md5_hash)) |
| 198 | |
| 199 | else: |
| 200 | warnings.warn( |
| 201 | "Loading sb3 without loading assets. When exporting the project, there may be errors due to assets not being uploaded to the Scratch website" |
| 202 | ) |
| 203 | |
| 204 | return _name, asset_data, json_str |
| 205 | |
| 206 | @classmethod |
| 207 | def from_sb3(cls, data: str | bytes | TextIOWrapper | BinaryIO, load_assets: bool = True, _name: Optional[str] = None): |