Coverage for src/bioimageio/spec/_hf_card.py: 81%

305 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 16:20 +0000

1from __future__ import annotations 

2 

3import collections.abc 

4import warnings 

5from collections.abc import Sequence 

6from functools import partial 

7from pathlib import PurePosixPath 

8from typing import Any 

9 

10import numpy as np 

11from imageio.v3 import imwrite # pyright: ignore[reportUnknownVariableType] 

12from loguru import logger 

13from numpy.typing import NDArray 

14from typing_extensions import assert_never 

15 

16from bioimageio.spec._internal.validation_context import get_validation_context 

17from bioimageio.spec.model.v0_5 import ( 

18 FileDescr, 

19 IntervalOrRatioDataDescr, 

20 KerasHdf5WeightsDescr, 

21 KerasV3WeightsDescr, 

22 NominalOrOrdinalDataDescr, 

23 OnnxWeightsDescr, 

24 PytorchStateDictWeightsDescr, 

25 TensorflowJsWeightsDescr, 

26 TensorflowSavedModelBundleWeightsDescr, 

27 TensorId, 

28 TorchscriptWeightsDescr, 

29) 

30 

31from ._internal.io import RelativeFilePath, get_reader 

32from ._internal.io_utils import load_array 

33from ._version import VERSION 

34from .model import ModelDescr 

35from .utils import get_spdx_licenses, load_image 

36 

37HF_KNOWN_LICENSES = ( 

38 "apache-2.0", 

39 "mit", 

40 "openrail", 

41 "bigscience-openrail-m", 

42 "creativeml-openrail-m", 

43 "bigscience-bloom-rail-1.0", 

44 "bigcode-openrail-m", 

45 "afl-3.0", 

46 "artistic-2.0", 

47 "bsl-1.0", 

48 "bsd", 

49 "bsd-2-clause", 

50 "bsd-3-clause", 

51 "bsd-3-clause-clear", 

52 "c-uda", 

53 "cc", 

54 "cc0-1.0", 

55 "cc-by-2.0", 

56 "cc-by-2.5", 

57 "cc-by-3.0", 

58 "cc-by-4.0", 

59 "cc-by-sa-3.0", 

60 "cc-by-sa-4.0", 

61 "cc-by-nc-2.0", 

62 "cc-by-nc-3.0", 

63 "cc-by-nc-4.0", 

64 "cc-by-nd-4.0", 

65 "cc-by-nc-nd-3.0", 

66 "cc-by-nc-nd-4.0", 

67 "cc-by-nc-sa-2.0", 

68 "cc-by-nc-sa-3.0", 

69 "cc-by-nc-sa-4.0", 

70 "cdla-sharing-1.0", 

71 "cdla-permissive-1.0", 

72 "cdla-permissive-2.0", 

73 "wtfpl", 

74 "ecl-2.0", 

75 "epl-1.0", 

76 "epl-2.0", 

77 "etalab-2.0", 

78 "eupl-1.1", 

79 "eupl-1.2", 

80 "agpl-3.0", 

81 "gfdl", 

82 "gpl", 

83 "gpl-2.0", 

84 "gpl-3.0", 

85 "lgpl", 

86 "lgpl-2.1", 

87 "lgpl-3.0", 

88 "isc", 

89 "h-research", 

90 "intel-research", 

91 "lppl-1.3c", 

92 "ms-pl", 

93 "apple-ascl", 

94 "apple-amlr", 

95 "mpl-2.0", 

96 "odc-by", 

97 "odbl", 

98 "openmdw-1.0", 

99 "openrail++", 

100 "osl-3.0", 

101 "postgresql", 

102 "ofl-1.1", 

103 "ncsa", 

104 "unlicense", 

105 "zlib", 

106 "pddl", 

107 "lgpl-lr", 

108 "deepfloyd-if-license", 

109 "fair-noncommercial-research-license", 

110 "llama2", 

111 "llama3", 

112 "llama3.1", 

113 "llama3.2", 

114 "llama3.3", 

115 "llama4", 

116 "grok2-community", 

117 "gemma", 

118) 

119 

120 

121def _generate_png_from_tensor(tensor: NDArray[np.generic]) -> bytes | None: 

122 """Generate PNG bytes from a sample tensor. 

123 

124 Prefers 2D slices from multi-dimensional arrays. 

125 Returns PNG bytes or None if generation fails. 

126 """ 

127 try: 

128 # Squeeze out singleton dimensions 

129 arr = np.squeeze(tensor) 

130 

131 # Handle different dimensionalities 

132 if arr.ndim == 2: 

133 img_data = arr 

134 elif arr.ndim == 3: 

135 # Could be (H, W, C) or (Z, H, W) 

136 if arr.shape[-1] in [1, 3, 4]: # Likely channels last 

137 img_data = arr 

138 else: # Take middle slice 

139 img_data = arr[arr.shape[0] // 2] 

140 elif arr.ndim == 4: 

141 # Take middle slices (e.g., batch, z, y, x) 

142 img_data = ( 

143 arr[0, arr.shape[1] // 2] 

144 if arr.shape[0] == 1 

145 else arr[arr.shape[0] // 2, arr.shape[1] // 2] 

146 ) 

147 elif arr.ndim > 4: 

148 # Take middle slices of all extra dimensions 

149 slices = tuple(s // 2 for s in arr.shape[:-2]) 

150 img_data = arr[slices] 

151 else: 

152 return None 

153 

154 # Normalize to 0-255 uint8 

155 img_data = np.squeeze(img_data) 

156 if img_data.dtype != np.uint8: 

157 img_min, img_max = img_data.min(), img_data.max() 

158 if img_max > img_min: 

159 img_data: NDArray[Any] = (img_data - img_min) / (img_max - img_min) 

160 else: 

161 img_data = np.zeros_like(img_data) 

162 img_data = (img_data * 255).astype(np.uint8) 

163 return imwrite("<bytes>", img_data, extension=".png") 

164 except Exception: 

165 return None 

166 

167 

168def _get_io_description( 

169 model: ModelDescr, 

170) -> tuple[str, dict[str, bytes], list[TensorId], list[TensorId]]: 

171 """Generate a description of model inputs and outputs with sample images. 

172 

173 Returns: 

174 A tuple of (markdown_string, referenced_files_dict, input_ids, output_ids) where referenced_files_dict maps 

175 filenames to file bytes. 

176 """ 

177 markdown_string = "" 

178 referenced_files: dict[str, bytes] = {} 

179 input_ids: list[TensorId] = [] 

180 output_ids: list[TensorId] = [] 

181 

182 def format_data_descr( 

183 d: NominalOrOrdinalDataDescr 

184 | IntervalOrRatioDataDescr 

185 | Sequence[NominalOrOrdinalDataDescr | IntervalOrRatioDataDescr], 

186 ) -> str: 

187 ret = "" 

188 if isinstance(d, NominalOrOrdinalDataDescr): 

189 ret += f" - Values: {d.values}\n" 

190 elif isinstance(d, IntervalOrRatioDataDescr): 

191 ret += f" - Value unit: {d.unit}\n" 

192 ret += f" - Value scale factor: {d.scale}\n" 

193 if d.offset is not None: 

194 ret += f" - Value offset: {d.offset}\n" 

195 elif d.range[0] is not None: 

196 ret += f" - Value minimum: {d.range[0]}\n" 

197 elif d.range[1] is not None: 

198 ret += f" - Value maximum: {d.range[1]}\n" 

199 elif isinstance(d, collections.abc.Sequence): 

200 for dd in d: 

201 ret += format_data_descr(dd) 

202 else: 

203 assert_never(d) 

204 

205 return ret 

206 

207 # Input descriptions 

208 if model.inputs: 

209 markdown_string += "\n- **Input specifications:**\n" 

210 

211 for inp in model.inputs: 

212 input_ids.append(inp.id) 

213 axes_str = ", ".join(str(a.id) for a in inp.axes) 

214 shape_str = " × ".join(str(a.size) for a in inp.axes) 

215 

216 markdown_string += f" `{inp.id}`: {inp.description or ''}\n\n" 

217 markdown_string += f" - Axes: `{axes_str}`\n" 

218 markdown_string += f" - Shape: `{shape_str}`\n" 

219 markdown_string += f" - Data type: `{inp.dtype}`\n" 

220 markdown_string += format_data_descr(inp.data) 

221 

222 # Try to load and display sample_tensor (preferred) or test_tensor 

223 img_bytes = None 

224 if inp.sample_tensor is not None: 

225 try: 

226 arr = np.asarray(load_image(inp.sample_tensor)) 

227 img_bytes = _generate_png_from_tensor(arr) 

228 except Exception as e: 

229 logger.error("failed to generate input sample image: {}", e) 

230 

231 if img_bytes is None and inp.test_tensor is not None: 

232 try: 

233 arr = load_array(inp.test_tensor) 

234 img_bytes = _generate_png_from_tensor(arr) 

235 except Exception as e: 

236 logger.error( 

237 "failed to generate input sample image from test data: {}", e 

238 ) 

239 

240 if img_bytes: 

241 filename = f"images/input_{inp.id}_sample.png" 

242 referenced_files[filename] = img_bytes 

243 markdown_string += f" - example\n ![{inp.id} sample]({filename})\n" 

244 

245 # Output descriptions 

246 if model.outputs: 

247 markdown_string += "\n- **Output specifications:**\n" 

248 for out in model.outputs: 

249 output_ids.append(out.id) 

250 axes_str = ", ".join(str(a.id) for a in out.axes) 

251 shape_str = " × ".join(str(a.size) for a in out.axes) 

252 

253 markdown_string += f" `{out.id}`: {out.description or ''}\n" 

254 markdown_string += f" - Axes: `{axes_str}`\n" 

255 markdown_string += f" - Shape: `{shape_str}`\n" 

256 markdown_string += f" - Data type: `{out.dtype}`\n" 

257 markdown_string += format_data_descr(out.data) 

258 

259 # Try to load and display sample_tensor (preferred) or test_tensor 

260 img_bytes = None 

261 if out.sample_tensor is not None: 

262 try: 

263 arr = np.asarray(load_image(out.sample_tensor)) 

264 img_bytes = _generate_png_from_tensor(arr) 

265 except Exception as e: 

266 logger.error("failed to generate output sample image: {}", e) 

267 

268 if img_bytes is None and out.test_tensor is not None: 

269 try: 

270 arr = load_array(out.test_tensor) 

271 img_bytes = _generate_png_from_tensor(arr) 

272 except Exception as e: 

273 logger.error( 

274 "failed to generate output sample image from test data: {}", e 

275 ) 

276 

277 if img_bytes: 

278 filename = f"images/output_{out.id}_sample.png" 

279 referenced_files[filename] = img_bytes 

280 markdown_string += f" - example\n {out.id} sample]({filename})\n" 

281 

282 return markdown_string, referenced_files, input_ids, output_ids 

283 

284 

285def create_huggingface_model_card( 

286 model: ModelDescr, *, repo_id: str 

287) -> tuple[str, dict[str, bytes]]: 

288 """Create a Hugging Face model card for a BioImage.IO model. 

289 

290 Returns: 

291 A tuple of (markdown_string, images_dict) where images_dict maps 

292 filenames to PNG bytes that should be saved alongside the markdown. 

293 """ 

294 model = model.model_copy() 

295 

296 if model.version is None: 

297 model_version = "" 

298 else: 

299 model_version = f"\n- **model version:** {model.version}" 

300 

301 if model.documentation is None: 

302 additional_model_doc = "" 

303 else: 

304 doc_reader = get_reader(model.documentation) 

305 local_doc_path = f"package/{doc_reader.original_file_name}" 

306 with get_validation_context().replace(perform_io_checks=False): 

307 model.documentation = FileDescr( 

308 source=RelativeFilePath(PurePosixPath(local_doc_path)) 

309 ) 

310 

311 additional_model_doc = f"\n- **Additional model documentation:** [{local_doc_path}]({local_doc_path})" 

312 

313 if model.cite: 

314 developed_by = "\n- **Developed by:** " + ( 

315 "".join( 

316 ( 

317 f"\n - {c.text}: " 

318 + (f"https://www.doi.org/{c.doi}" if c.doi else str(c.url)) 

319 ) 

320 for c in model.cite 

321 ) 

322 ) 

323 else: 

324 developed_by = "" 

325 

326 if model.config.bioimageio.funded_by: 

327 funded_by = f"\n- **Funded by:** {model.config.bioimageio.funded_by}" 

328 else: 

329 funded_by = "" 

330 

331 if model.authors: 

332 shared_by = "\n- **Shared by:** " + ( 

333 "".join( 

334 f"\n - {a.name}" 

335 + (f", {a.affiliation}" if a.affiliation else "") 

336 + ( 

337 f", [https://orcid.org/{a.orcid}](https://orcid.org/{a.orcid})" 

338 if a.orcid 

339 else "" 

340 ) 

341 + ( 

342 f", [https://github.com/{a.github_user}](https://github.com/{a.github_user})" 

343 if a.github_user 

344 else "" 

345 ) 

346 for a in model.authors 

347 ) 

348 ) 

349 else: 

350 shared_by = "" 

351 

352 if model.config.bioimageio.architecture_type: 

353 model_type = f"\n- **Model type:** {model.config.bioimageio.architecture_type}" 

354 else: 

355 model_type = "" 

356 

357 if model.config.bioimageio.modality: 

358 model_modality = f"\n- **Modality:** {model.config.bioimageio.modality}" 

359 else: 

360 model_modality = "" 

361 

362 if model.config.bioimageio.target_structure: 

363 target_structures = "\n- **Target structures:** " + ", ".join( 

364 model.config.bioimageio.target_structure 

365 ) 

366 else: 

367 target_structures = "" 

368 

369 if model.config.bioimageio.task: 

370 task_type = f"\n- **Task type:** {model.config.bioimageio.task}" 

371 else: 

372 task_type = "" 

373 

374 if model.parent: 

375 finetuned_from = f"\n- **Finetuned from model:** {model.parent.id}" 

376 else: 

377 finetuned_from = "" 

378 

379 repository = ( 

380 f"[{model.git_repo}]({model.git_repo})" if model.git_repo else "missing" 

381 ) 

382 

383 dl_framework_parts: list[str] = [] 

384 training_frameworks: list[str] = [] 

385 model_size: str | None = None 

386 for weights in model.weights.available_formats.values(): 

387 if isinstance(weights, (PytorchStateDictWeightsDescr, TorchscriptWeightsDescr)): 

388 dl_framework_version = weights.pytorch_version 

389 elif isinstance( 

390 weights, 

391 ( 

392 TensorflowSavedModelBundleWeightsDescr, 

393 TensorflowJsWeightsDescr, 

394 KerasHdf5WeightsDescr, 

395 ), 

396 ): 

397 dl_framework_version = weights.tensorflow_version 

398 elif isinstance(weights, KerasV3WeightsDescr): 

399 dl_framework_version = weights.keras_version 

400 elif isinstance(weights, OnnxWeightsDescr): 

401 dl_framework_version = f"opset version: {weights.opset_version}" 

402 else: 

403 assert_never(weights) 

404 

405 if weights.parent is None: 

406 training_frameworks.append(weights.weights_format_name) 

407 

408 dl_framework_parts.append( 

409 f"\n - {weights.weights_format_name}: {dl_framework_version}" 

410 ) 

411 

412 if model_size is None: 

413 s = 0 

414 r = weights.get_reader() 

415 for chunk in iter(partial(r.read, 128 * 1024), b""): 

416 s += len(chunk) 

417 

418 if model.config.bioimageio.model_parameter_count is not None: 

419 if model.config.bioimageio.model_parameter_count < 1e9: 

420 model_size = f"{model.config.bioimageio.model_parameter_count / 1e6:.2f} million parameters, " 

421 else: 

422 model_size = f"{model.config.bioimageio.model_parameter_count / 1e9:.2f} billion parameters, " 

423 else: 

424 model_size = "" 

425 

426 if s < 1e9: 

427 model_size += f"{s / 1e6:.2f} MB" 

428 else: 

429 model_size += f"{s / 1e9:.2f} GB" 

430 

431 dl_frameworks = "".join(dl_framework_parts) 

432 if len(training_frameworks) > 1: 

433 warnings.warn( 

434 "Multiple training frameworks detected. (Some weight formats are probably missing a `parent` reference.)" 

435 ) 

436 

437 if ( 

438 model.weights.pytorch_state_dict is not None 

439 and model.weights.pytorch_state_dict.dependencies is not None 

440 ): 

441 env_reader = model.weights.pytorch_state_dict.dependencies.get_reader() 

442 dependencies = f"Dependencies for Pytorch State dict weights are listed in [{env_reader.original_file_name}](package/{env_reader.original_file_name})." 

443 else: 

444 dependencies = "None beyond the respective framework library." 

445 

446 out_of_scope_use = ( 

447 model.config.bioimageio.out_of_scope_use 

448 if model.config.bioimageio.out_of_scope_use 

449 else """missing; therefore these typical limitations should be considered: 

450 

451- *Likely not suitable for diagnostic purposes.* 

452- *Likely not validated for different imaging modalities than present in the training data.* 

453- *Should not be used without proper validation on user's specific datasets.* 

454 

455""" 

456 ) 

457 

458 environmental_impact = model.config.bioimageio.environmental_impact.format_md() 

459 if environmental_impact: 

460 environmental_impact_toc_entry = ( 

461 "\n- [Environmental Impact](#environmental-impact)" 

462 ) 

463 else: 

464 environmental_impact_toc_entry = "" 

465 

466 evaluation_parts: list[str] = [] 

467 n_evals = 0 

468 for e in model.config.bioimageio.evaluations: 

469 if e.dataset_role == "independent": 

470 continue # treated separately below 

471 

472 n_evals += 1 

473 n_evals_str = "" if n_evals == 1 else f" {n_evals}" 

474 evaluation_parts.append(f"\n# Evaluation{n_evals_str}\n") 

475 evaluation_parts.append(e.format_md()) 

476 

477 n_evals = 0 

478 for e in model.config.bioimageio.evaluations: 

479 if e.dataset_role != "independent": 

480 continue # treated separately above 

481 

482 n_evals += 1 

483 n_evals_str = "" if n_evals == 1 else f" {n_evals}" 

484 

485 evaluation_parts.append(f"### Validation on External Data{n_evals_str}\n") 

486 evaluation_parts.append(e.format_md()) 

487 

488 if evaluation_parts: 

489 evaluation = "\n".join(evaluation_parts) 

490 evaluation_toc_entry = "\n- [Evaluation](#evaluation)" 

491 else: 

492 evaluation = "" 

493 evaluation_toc_entry = "" 

494 

495 training_details = "" 

496 if model.config.bioimageio.training.training_preprocessing: 

497 training_details += f"### Preprocessing\n\n{model.config.bioimageio.training.training_preprocessing}\n\n" 

498 

499 training_details += "### Training Hyperparameters\n\n" 

500 training_details += f"- **Framework:** {' / '.join(training_frameworks)}" 

501 if model.config.bioimageio.training.training_epochs is not None: 

502 training_details += ( 

503 f"- **Epochs:** {model.config.bioimageio.training.training_epochs}\n" 

504 ) 

505 

506 if model.config.bioimageio.training.training_batch_size is not None: 

507 training_details += f"- **Batch size:** {model.config.bioimageio.training.training_batch_size}\n" 

508 

509 if model.config.bioimageio.training.initial_learning_rate is not None: 

510 training_details += f"- **Initial learning rate:** {model.config.bioimageio.training.initial_learning_rate}\n" 

511 

512 if model.config.bioimageio.training.learning_rate_schedule is not None: 

513 training_details += f"- **Learning rate schedule:** {model.config.bioimageio.training.learning_rate_schedule}\n" 

514 

515 if model.config.bioimageio.training.loss_function is not None: 

516 training_details += ( 

517 f"- **Loss function:** {model.config.bioimageio.training.loss_function}" 

518 ) 

519 if model.config.bioimageio.training.loss_function_kwargs: 

520 training_details += ( 

521 f" with {model.config.bioimageio.training.loss_function_kwargs}" 

522 ) 

523 training_details += "\n" 

524 

525 if model.config.bioimageio.training.optimizer is not None: 

526 training_details += ( 

527 f"- **Optimizer:** {model.config.bioimageio.training.optimizer}" 

528 ) 

529 if model.config.bioimageio.training.optimizer_kwargs: 

530 training_details += ( 

531 f" with {model.config.bioimageio.training.optimizer_kwargs}" 

532 ) 

533 training_details += "\n" 

534 

535 if model.config.bioimageio.training.regularization is not None: 

536 training_details += ( 

537 f"- **Regularization:** {model.config.bioimageio.training.regularization}\n" 

538 ) 

539 

540 speeds_sizes_times = "### Speeds, Sizes, Times\n\n" 

541 if model.config.bioimageio.training.training_duration is not None: 

542 speeds_sizes_times += f"- **Training time:** {f'{model.config.bioimageio.training.training_duration:.2f}'}\n" 

543 

544 speeds_sizes_times += f"- **Model size:** {model_size}\n" 

545 if model.config.bioimageio.inference_time: 

546 speeds_sizes_times += ( 

547 f"- **Inference time:** {model.config.bioimageio.inference_time}\n" 

548 ) 

549 

550 if model.config.bioimageio.memory_requirements_inference: 

551 speeds_sizes_times += f"- **Memory requirements:** {model.config.bioimageio.memory_requirements_inference}\n" 

552 

553 model_arch_and_objective = "## Model Architecture and Objective\n\n" 

554 if ( 

555 model.config.bioimageio.architecture_type 

556 or model.config.bioimageio.architecture_description 

557 ): 

558 model_arch_and_objective += ( 

559 f"- **Architecture:** {model.config.bioimageio.architecture_type or ''}" 

560 + ( 

561 " --- " 

562 if model.config.bioimageio.architecture_type 

563 and model.config.bioimageio.architecture_description 

564 else "" 

565 ) 

566 + ( 

567 model.config.bioimageio.architecture_description 

568 if model.config.bioimageio.architecture_description is not None 

569 else "" 

570 ) 

571 + "\n" 

572 ) 

573 

574 io_desc, referenced_files, input_ids, output_ids = _get_io_description(model) 

575 predict_snippet_inputs = str( 

576 {input_id: "<path or tensor>" for input_id in input_ids} 

577 ) 

578 model_arch_and_objective += io_desc 

579 

580 hardware_requirements = "\n### Hardware Requirements\n" 

581 if model.config.bioimageio.memory_requirements_training is not None: 

582 hardware_requirements += f"- **Training:** GPU memory: {model.config.bioimageio.memory_requirements_training}\n" 

583 

584 if model.config.bioimageio.memory_requirements_inference is not None: 

585 hardware_requirements += f"- **Inference:** GPU memory: {model.config.bioimageio.memory_requirements_inference}\n" 

586 

587 hardware_requirements += f"- **Storage:** Model size: {model_size}\n" 

588 

589 if model.license is None: 

590 license = "unknown" 

591 license_meta = "unknown" 

592 elif isinstance(model.license, FileDescr): 

593 license_reader = get_reader(model.license) 

594 local_license_path = f"package/{license_reader.original_file_name}" 

595 with get_validation_context().replace(perform_io_checks=False): 

596 model.license.source = RelativeFilePath(PurePosixPath(local_license_path)) 

597 

598 license = f"[{local_license_path}]({local_license_path})" 

599 license_meta = "unknown" 

600 else: 

601 spdx_licenses = get_spdx_licenses() 

602 matches = [ 

603 (entry["name"], entry["reference"]) 

604 for entry in spdx_licenses["licenses"] 

605 if entry["licenseId"].lower() == model.license.lower() 

606 ] 

607 if matches: 

608 if len(matches) > 1: 

609 logger.warning( 

610 "Multiple SPDX license matches found for '{}', using the first one.", 

611 model.license, 

612 ) 

613 name, reference = matches[0] 

614 license = f"[{name}]({reference})" 

615 if model.license.lower() in HF_KNOWN_LICENSES: 

616 license_meta = model.license.lower() 

617 else: 

618 license_meta = f"other\nlicense_name: {model.license.lower()}\nlicense_link: {reference}" 

619 else: 

620 if model.license.lower() in HF_KNOWN_LICENSES: 

621 license_meta = model.license.lower() 

622 else: 

623 license_meta = "unknown" 

624 

625 license = model.license.lower() 

626 

627 base_model = ( 

628 f"\nbase_model: {model.parent.id[len('huggingface/') :]}" 

629 if model.parent is not None and model.parent.id.startswith("huggingface/") 

630 else "" 

631 ) 

632 dataset_meta = ( 

633 f"\ndataset: {model.training_data.id[len('huggingface/') :]}" 

634 if model.training_data is not None 

635 and model.training_data.id is not None 

636 and model.training_data.id.startswith("huggingface/") 

637 else "" 

638 ) 

639 if model.covers: 

640 cover_image_reader = get_reader(model.covers[0]) 

641 cover_image_bytes = cover_image_reader.read() 

642 cover_image_filename = f"images/{cover_image_reader.original_file_name}" 

643 referenced_files[cover_image_filename] = cover_image_bytes 

644 cover_image_md = f"\n![cover image]({cover_image_filename})\n\n" 

645 thumbnail_meta = ( 

646 f"\nthumbnail: {cover_image_filename}" # TODO: fix this to be a proper URL 

647 ) 

648 

649 else: 

650 cover_image_md = "" 

651 thumbnail_meta = "" 

652 

653 # TODO: add pipeline_tag to metadata 

654 readme = f"""--- 

655license: {license_meta}{thumbnail_meta} 

656tags: {list({"biology"}.union(set(model.tags)))} 

657language: [en] 

658library_name: bioimageio{base_model}{dataset_meta} 

659--- 

660# {model.name}{cover_image_md} 

661 

662{model.description or ""} 

663 

664 

665# Table of Contents 

666 

667- [Model Details](#model-details) 

668- [Uses](#uses) 

669- [Bias, Risks, and Limitations](#bias-risks-and-limitations) 

670- [How to Get Started with the Model](#how-to-get-started-with-the-model) 

671- [Training Details](#training-details){evaluation_toc_entry}{ 

672 environmental_impact_toc_entry 

673 } 

674- [Technical Specifications](#technical-specifications) 

675 

676 

677# Model Details 

678 

679## Model Description 

680{model_version}{additional_model_doc}{developed_by}{funded_by}{shared_by}{model_type}{ 

681 model_modality 

682 }{target_structures}{task_type} 

683- **License:** {license}{finetuned_from} 

684 

685## Model Sources 

686 

687- **Repository:** {repository} 

688- **Paper:** see [**Developed by**](#model-description) 

689 

690# Uses 

691 

692## Direct Use 

693 

694This model is compatible with the bioimageio.spec Python package (version >= { 

695 VERSION 

696 }) and the bioimageio.core Python package supporting model inference in Python code or via the `bioimageio` CLI. 

697 

698```python 

699from bioimageio.core import predict 

700 

701output_sample = predict( 

702 "huggingface/{repo_id}/{model.version or "draft"}", 

703 inputs={predict_snippet_inputs}, 

704) 

705 

706output_tensor = output_sample.members["{ 

707 output_ids[0] if output_ids else "<output_id>" 

708 }"] 

709xarray_dataarray = output_tensor.data 

710numpy_ndarray = output_tensor.data.to_numpy() 

711``` 

712 

713## Downstream Use 

714 

715Specific bioimage.io partner tool compatibilities may be reported at [Compatibility Reports](https://bioimage-io.github.io/collection/latest/compatibility/#compatibility-by-resource). 

716{ 

717 "Training (and fine-tuning) code may be available at " + model.git_repo + "." 

718 if model.git_repo 

719 else "" 

720 } 

721 

722## Out-of-Scope Use 

723 

724{out_of_scope_use} 

725 

726 

727{model.config.bioimageio.bias_risks_limitations.format_md()} 

728 

729# How to Get Started with the Model 

730 

731You can use "huggingface/{repo_id}/{ 

732 model.version or "draft" 

733 }" as the resource identifier to load this model directly from the Hugging Face Hub using bioimageio.spec or bioimageio.core. 

734 

735See [bioimageio.core documentation: Get started](https://bioimage-io.github.io/core-bioimage-io-python/latest/get-started) for instructions on how to load and run this model using the `bioimageio.core` Python package or the bioimageio CLI. 

736 

737# Training Details 

738 

739## Training Data 

740 

741{ 

742 "This model was trained on `" + str(model.training_data.id) + "`." 

743 if model.training_data is not None 

744 else "missing" 

745 } 

746 

747## Training Procedure 

748 

749{training_details} 

750 

751{speeds_sizes_times} 

752{evaluation} 

753{environmental_impact} 

754 

755# Technical Specifications 

756 

757{model_arch_and_objective} 

758 

759## Compute Infrastructure 

760 

761{hardware_requirements} 

762 

763### Software 

764 

765- **Framework:** {dl_frameworks} 

766- **Libraries:** {dependencies} 

767- **BioImage.IO partner compatibility:** [Compatibility Reports](https://bioimage-io.github.io/collection/latest/compatibility/#compatibility-by-resource) 

768 

769--- 

770 

771*This model card was created using the template of the bioimageio.spec Python Package, which intern is based on the BioImage Model Zoo template, incorporating best practices from the Hugging Face Model Card Template. For more information on contributing models, visit [bioimage.io](https://bioimage.io).* 

772 

773--- 

774 

775**References:** 

776 

777- [Hugging Face Model Card Template](https://huggingface.co/docs/hub/en/model-card-annotated) 

778- [Hugging Face modelcard_template.md](https://github.com/huggingface/huggingface_hub/blob/b9decfdf9b9a162012bc52f260fd64fc37db660e/src/huggingface_hub/templates/modelcard_template.md) 

779- [BioImage Model Zoo Documentation](https://bioimage.io/docs/) 

780- [Model Cards for Model Reporting](https://arxiv.org/abs/1810.03993) 

781- [bioimageio.spec Python Package](https://bioimage-io.github.io/spec-bioimage-io) 

782""" 

783 

784 return readme, referenced_files