Text-to-Image
Diffusers
Safetensors
English
Chinese
flow-matching
qwen-image
ascend
lora
recursive-self-improvement
Instructions to use DALabCommunity/Haidass-Image-Instruct with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Diffusers
How to use DALabCommunity/Haidass-Image-Instruct with Diffusers:
pip install -U diffusers transformers accelerate
import torch from diffusers import DiffusionPipeline # switch to "mps" for apple devices pipe = DiffusionPipeline.from_pretrained("DALabCommunity/Haidass-Image-Base-v1_0.6B_512px", dtype=torch.bfloat16, device_map="cuda") pipe.load_lora_weights("DALabCommunity/Haidass-Image-Instruct") prompt = "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k" image = pipe(prompt).images[0] - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- Draw Things
- DiffusionBee
Download inference.py from DALabCommunity/Haidass-Image-Instruct: direct link, hf CLI and curl.
- Browser
- Download file 24 kB
-
https://huggingface.co/DALabCommunity/Haidass-Image-Instruct/resolve/main/inference.py
- Command line
-
hf download hf://DALabCommunity/Haidass-Image-Instruct/inference.py
-
curl -L -o inference.py https://huggingface.co/DALabCommunity/Haidass-Image-Instruct/resolve/main/inference.py
24 kB
| """Generate with Haidass-Image-Instruct's default prompt-only routing.""" | |
| import argparse | |
| from contextlib import nullcontext | |
| import json | |
| import os | |
| from tempfile import NamedTemporaryFile | |
| from pathlib import Path | |
| import re | |
| import time | |
| import warnings | |
| import torch | |
| from PIL import Image | |
| from safetensors.torch import load_file | |
| from transformers import AutoModel, AutoTokenizer | |
| from runtime.model import DiTConfig, PackedSingleStreamDiT | |
| from runtime.prompt_routing import preprocess_and_route_text_prompt | |
| from runtime.qwenimage21_vae import AutoencoderKLQwenImage21 | |
| from runtime.spelling import augment_caption | |
| MAX_SEED = 2**31 - 1 | |
| def select_device(name): | |
| name = str(name) | |
| if re.fullmatch(r'auto|cpu|(?:cuda|npu)(?::\d+)?', name) is None: | |
| raise ValueError('Device must be auto, cpu, cuda[:N], or npu[:N]') | |
| if name == 'auto' and torch.cuda.is_available(): | |
| return torch.device('cuda:0') | |
| if name == 'auto' or name.startswith('npu'): | |
| try: | |
| import torch_npu | |
| except ImportError as exc: | |
| if name != 'auto': | |
| raise RuntimeError('NPU inference requires torch_npu installed for the current PyTorch and Ascend runtime.') from exc | |
| else: | |
| if torch_npu.npu.is_available(): | |
| device = torch.device('npu:0' if name in ('auto', 'npu') else name) | |
| torch.npu.set_device(device) | |
| return device | |
| if name != 'auto': | |
| raise RuntimeError('No Ascend NPU is available to torch_npu.') | |
| if name.startswith('cuda') and not torch.cuda.is_available(): | |
| raise RuntimeError('No CUDA device is available to PyTorch.') | |
| return torch.device('cpu' if name == 'auto' else name) | |
| def route_prompt(prompt, raw_prompt=None, *, mode='routed', apply_spelling=True): | |
| """Return (prepared prompt, writing route enabled), including for the legacy Space.""" | |
| result = preprocess_and_route_text_prompt( | |
| prompt, raw_prompt, apply_spelling=apply_spelling, canonical_spelling=augment_caption | |
| ) | |
| triggered = bool(result['load_writing_lora']) | |
| if mode == 'none': | |
| active = False | |
| elif mode == 'routed': | |
| active = triggered | |
| elif mode == 'always': | |
| active = True | |
| else: | |
| raise ValueError(f'Unknown writing routing mode: {mode}') | |
| return (result['final_prompt'] if active and triggered else result['normalized_prompt']), active | |
| def validate_seed(seed): | |
| if type(seed) is not int or not 0 <= seed <= MAX_SEED: | |
| raise ValueError(f'seed must be an integer between 0 and {MAX_SEED}') | |
| def validate_pool(seed, pool): | |
| if not isinstance(pool, (tuple, list)) or len(pool) != 8: | |
| raise ValueError('candidate_seeds must contain exactly eight seeds') | |
| for value in pool: | |
| validate_seed(value) | |
| if pool[0] != seed or len(set(pool)) != 8: | |
| raise ValueError('candidate_seeds must be distinct and begin with the row seed') | |
| class Generator: | |
| """Load one released model. `generate` and `generate_batch` use all default routes.""" | |
| def __init__(self, directory=None, device='auto', text_encoder=None, memory_fraction=None): | |
| self.directory = Path(directory) if directory is not None else Path(__file__).resolve().parent | |
| if text_encoder is not None and not Path(text_encoder).is_dir(): | |
| raise FileNotFoundError(f'Local text encoder directory does not exist: {text_encoder}') | |
| self.device = select_device(device) | |
| self.torch = torch | |
| if memory_fraction is not None and self.device.type == 'npu': | |
| torch.npu.set_per_process_memory_fraction(memory_fraction, self.device) | |
| self.config = json.loads((self.directory/'config.json').read_text(encoding='utf-8')) | |
| self.settings = self.config['inference'] | |
| self.text = self.config['text_encoder'] | |
| text_path = str(text_encoder or self.text['repository']) | |
| self.dtype = torch.bfloat16 | |
| if self.device.type == 'cuda' and not torch.cuda.is_bf16_supported(): | |
| self.dtype = torch.float16 | |
| component_dtype = torch.float32 if self.device.type == 'cpu' else self.dtype | |
| self.encoder = AutoModel.from_pretrained(text_path, torch_dtype=component_dtype, attn_implementation='sdpa') | |
| self.encoder.to(self.device).eval().requires_grad_(False) | |
| self.tokenizer = AutoTokenizer.from_pretrained(text_path) | |
| self.tokenizer.padding_side = 'right' | |
| if self.tokenizer.pad_token_id is None: | |
| self.tokenizer.pad_token = self.tokenizer.eos_token | |
| vae_dir = self.directory/'vae' | |
| vae_config = json.loads((vae_dir/'config.json').read_text(encoding='utf-8')) | |
| self.vae = AutoencoderKLQwenImage21.from_pretrained(str(vae_dir), torch_dtype=component_dtype, | |
| local_files_only=True) | |
| self.vae.to(self.device).eval().requires_grad_(False) | |
| self.latent_mean = torch.tensor(vae_config['latents_mean'], device=self.device).view(1, -1, 1, 1) | |
| self.latent_std = torch.tensor(vae_config['latents_std'], device=self.device).view(1, -1, 1, 1) | |
| self.latent_channels = vae_config['z_dim'] | |
| self.latent_size = self.settings['resolution'] // vae_config['scale_factor_spatial'] | |
| self.base = self._load_backbone().to(self.device).eval().requires_grad_(False) | |
| self.adapter = None # Legacy Space can provide its own PEFT wrapper. | |
| self._adapter_load_failed = False | |
| self.count_head = self._parse_count = self._choose_count = self._candidate_seeds = None | |
| path = self.directory/'counting_head'/'head.npz' | |
| if path.is_file(): | |
| from counting_head.count_n_rank import CountRanker | |
| from counting_head.count_parser import parse_prompt | |
| from counting_head.sampling import candidate_seeds, choose_and_finish | |
| self.count_head = CountRanker(path) | |
| if self.count_head.step != 5 or self.count_head.layer != 25: | |
| raise ValueError('The packaged counting head must use step 5 and layer 25') | |
| self._parse_count = parse_prompt | |
| self._choose_count = choose_and_finish | |
| self._candidate_seeds = candidate_seeds | |
| else: | |
| warnings.warn('counting_head/head.npz is missing. Counting requests use a single backbone draw.', stacklevel=2) | |
| def _load_backbone(self): | |
| with torch.device('cpu'): | |
| model = PackedSingleStreamDiT(DiTConfig(**self.config['dit']), | |
| backend='ascend' if self.device.type == 'npu' else 'reference') | |
| state = load_file(str(self.directory/'dit.safetensors'), device='cpu') | |
| model.load_state_dict(state, strict=True) | |
| return model | |
| def _model(self, routed): | |
| if self._adapter_load_failed: | |
| raise RuntimeError('Writing adapter loading failed. Create a new Generator before running inference.') | |
| if routed and self.adapter is None: | |
| from peft import PeftModel | |
| adapter_dir = self.directory/self.config['routing']['writing_adapter'] | |
| for name in ('adapter_config.json', 'adapter_model.safetensors'): | |
| path = adapter_dir/name | |
| if not path.is_file(): | |
| raise FileNotFoundError(f'Missing writing adapter file: {path}') | |
| # PEFT can change modules before finishing an adapter load. | |
| self._adapter_load_failed = True | |
| try: | |
| with torch.inference_mode(False), torch.no_grad(): | |
| adapter = PeftModel.from_pretrained( | |
| self.base, adapter_dir, is_trainable=False, torch_device='cpu' | |
| ).to(self.device).eval() | |
| assert adapter.get_base_model() is self.base | |
| except Exception as exc: | |
| raise RuntimeError('Writing adapter loading failed. Create a new Generator before running inference.') from exc | |
| self.adapter = adapter | |
| self._adapter_load_failed = False | |
| if self.adapter is not None: | |
| return (self.adapter, nullcontext()) if routed else (self.base, self.adapter.disable_adapter()) | |
| return self.base, nullcontext() | |
| def _branch_guidance(self, routed): | |
| if routed: | |
| return (float(self.settings.get('writing_cfg', self.settings['cfg'])), | |
| self.settings.get('writing_cfg_norm', self.settings.get('cfg_norm', 'none'))) | |
| return float(self.settings['cfg']), self.settings.get('cfg_norm', 'none') | |
| def _contexts(self, caption): | |
| tokenized = self.tokenizer([caption, self.tokenizer.eos_token], padding=True, truncation=True, | |
| max_length=self.text['max_length'], return_tensors='pt') | |
| ids = tokenized.input_ids.to(self.device) | |
| mask = tokenized.attention_mask.to(self.device) | |
| features = self.encoder(input_ids=ids, attention_mask=mask, use_cache=False).last_hidden_state | |
| return [value[row.bool()] for value, row in zip(features, mask)] | |
| def _noise(self, seed): | |
| shape = self.latent_channels, self.latent_size, self.latent_size | |
| if self.device.type == 'npu': | |
| torch.npu.manual_seed(seed) | |
| return torch.randn(shape, device=self.device, dtype=torch.float32) | |
| rng = torch.Generator(device=self.device).manual_seed(seed) | |
| return torch.randn(shape, device=self.device, generator=rng, dtype=torch.float32) | |
| def _image(self, latent): | |
| raw = (latent[None].float()*self.latent_std + self.latent_mean)[:, :, None] | |
| pixels = self.vae.decode(raw.to(next(self.vae.parameters()).dtype)).sample[0, :3, 0].float() | |
| if not bool(torch.isfinite(pixels).all()): | |
| raise FloatingPointError('The VAE returned non-finite pixels') | |
| return Image.fromarray(((pixels.clamp(-1, 1)+1)*127.5).byte().permute(1, 2, 0).cpu().numpy()) | |
| def _render(self, captions, seeds, routed, steps, *, start_step=0, stop_step=None, resume=None, | |
| capture=None, progress=None): | |
| model, context = self._model(routed) | |
| cfg, cfg_norm = self._branch_guidance(routed) | |
| if resume is None: | |
| contexts, latents = [], [] | |
| for caption, seed in zip(captions, seeds): | |
| contexts.extend(self._contexts(caption)) | |
| latents.append(self._noise(seed)) | |
| else: | |
| latents, contexts = resume | |
| shift = self.settings['timestep_shift'] | |
| lower, upper = self.settings['cfg_lower'], self.settings['cfg_upper'] | |
| grid = torch.linspace(self.settings['start'], self.settings['end'], steps+1, device=self.device) | |
| if shift != 1: | |
| grid = shift * grid / (1 + (shift - 1) * grid) | |
| mask = ((grid > lower) & (grid <= upper)).tolist() if (lower, upper) != (0, 1) else [True]*len(grid) | |
| cells = self.latent_size**2 | |
| if capture is not None: | |
| capture.begin(self.base, contexts, latents[0].shape[-2:]) | |
| with context: | |
| for step, (active, (timestep, following)) in enumerate(zip(mask, zip(grid[:-1], grid[1:])), 1): | |
| if step <= start_step: | |
| continue | |
| if stop_step is not None and step > stop_step: | |
| break | |
| if capture is not None: | |
| capture.step = step | |
| inputs = [latent for latent in latents for _ in range(2)] | |
| with torch.autocast(self.device.type, dtype=self.dtype): | |
| predictions = model(inputs, contexts, timestep.expand(len(inputs))).split(cells) | |
| updated = [] | |
| for i, latent in enumerate(latents): | |
| conditional, unconditional = predictions[2*i:2*i+2] | |
| vc_f, vu_f = conditional.float(), unconditional.float() | |
| if active: | |
| velocity = vu_f + cfg * (vc_f-vu_f) | |
| if cfg_norm == 'qwen': | |
| velocity = velocity * (torch.norm(vc_f, dim=-1, keepdim=True) / | |
| torch.norm(velocity, dim=-1, keepdim=True).clamp(min=1e-8)) | |
| else: | |
| velocity = vc_f | |
| updated.append(latent + (following-timestep) * velocity.T.reshape_as(latent)) | |
| latents = updated | |
| if progress is not None: | |
| progress(step) | |
| return latents, contexts | |
| def generate(self, prompt, seed=0, *, steps=None, candidate_seeds=None, count_head=True, | |
| writing_lora=True, routing='auto', progress=None, raw_prompt=None): | |
| """Return `(PIL.Image, record)` using writing, count, or single backbone routing.""" | |
| if not isinstance(prompt, str) or not prompt.strip(): | |
| raise ValueError('prompt must be non-empty text') | |
| validate_seed(seed) | |
| if candidate_seeds is not None: | |
| validate_pool(seed, candidate_seeds) | |
| steps = self.settings['steps'] if steps is None else steps | |
| if type(steps) is not int or steps < 1: | |
| raise ValueError('steps must be a positive integer') | |
| if routing not in ('auto', 'none'): | |
| raise ValueError('routing must be auto or none') | |
| active = routing != 'none' | |
| final_prompt, writing = route_prompt(prompt, raw_prompt, mode='routed' if active and writing_lora else 'none') | |
| parsed = self._parse_count(prompt) if active and self._parse_count is not None else None | |
| wants_count = not writing and count_head and parsed is not None | |
| use_count = wants_count and steps == 50 | |
| route = 'writing_lora' if writing else 'count_head' if use_count else 'backbone' | |
| def emit(event, **data): | |
| if progress is not None: | |
| progress(dict(event=event, route=route, **data)) | |
| notes = [] | |
| if wants_count and not use_count: | |
| notes.append(f'Counting uses the 50-step schedule; steps={steps} falls back to one backbone draw.') | |
| truncated = writing and len(self.tokenizer(final_prompt, truncation=False, verbose=False).input_ids) > self.text['max_length'] | |
| if truncated: | |
| notes.append(f'Spelled prompt exceeds {self.text["max_length"]} tokens and will be truncated.') | |
| emit('route', parsed_count=None if parsed is None else parsed['count'], steps=steps) | |
| for note in notes: | |
| if progress is None: | |
| warnings.warn(note, stacklevel=2) | |
| else: | |
| emit('notice', message=note) | |
| if self.device.type == 'npu': | |
| torch.npu.synchronize(self.device) | |
| started = time.monotonic() | |
| seeds, selected, scores = [seed], 0, None | |
| if use_count: | |
| seeds = list(candidate_seeds) if candidate_seeds is not None else self._candidate_seeds(seed) | |
| latent, selected, scores = self._choose_count(self, final_prompt, seeds, parsed['count'], emit) | |
| else: | |
| latents, _ = self._render([final_prompt], seeds, writing, steps, | |
| progress=lambda step: emit('step', step=step, steps=steps)) | |
| latent = latents[0] | |
| image = self._image(latent) | |
| if self.device.type == 'npu': | |
| torch.npu.synchronize(self.device) | |
| return image, dict(route=route, writing_triggered=writing, parsed=parsed, | |
| parsed_count=None if parsed is None else parsed['count'], head_used=use_count, | |
| selected=selected, candidates=seeds, seed=seeds[selected], input_seed=seed, | |
| log_probabilities_target=scores, truncated=bool(truncated), final_prompt=final_prompt, | |
| steps=steps, seconds=time.monotonic()-started, notices=notes) | |
| def generate_batch(self, prompts, seeds, *, steps=None, candidate_seeds=None, count_head=True, | |
| writing_lora=True, routing='auto', progress=None, return_records=False, raw_prompts=None): | |
| """Route mixed prompts in input order. Set `return_records=True` for `(PIL, record)` pairs.""" | |
| if not prompts or len(prompts) != len(seeds): | |
| raise ValueError('Supply the same nonzero number of prompts and seeds') | |
| if candidate_seeds is None: | |
| candidate_seeds = [None] * len(prompts) | |
| if raw_prompts is None: | |
| raw_prompts = [None] * len(prompts) | |
| if len(candidate_seeds) != len(prompts) or len(raw_prompts) != len(prompts): | |
| raise ValueError('Supply one candidate-pool and raw-prompt entry per image') | |
| results = [self.generate(prompt, seed, steps=steps, candidate_seeds=pool, count_head=count_head, | |
| writing_lora=writing_lora, routing=routing, progress=progress, raw_prompt=raw) | |
| for prompt, seed, pool, raw in zip(prompts, seeds, candidate_seeds, raw_prompts)] | |
| return results if return_records else [image for image, _ in results] | |
| def read_cases(path): | |
| rows = json.loads(path.read_text(encoding='utf-8-sig')) | |
| if not isinstance(rows, list) or not rows: | |
| raise ValueError('Batch JSON must be a non-empty list of objects') | |
| errors, identifiers = [], {} | |
| reserved = {'CON', 'PRN', 'AUX', 'NUL'} | {f'{prefix}{n}' for prefix in ('COM', 'LPT') for n in range(1, 10)} | |
| for number, row in enumerate(rows, 1): | |
| if not isinstance(row, dict): | |
| errors.append(f'row {number}: expected an object') | |
| continue | |
| missing = {'id', 'caption', 'seed'} - row.keys() | |
| if missing: | |
| errors.append(f'row {number}: missing {", ".join(sorted(missing))}') | |
| identifier = str(row.get('id')) | |
| if 'id' in row: | |
| if (type(row['id']) not in (int, str) or re.fullmatch(r'[A-Za-z0-9_-][A-Za-z0-9_.-]{0,127}', identifier) is None | |
| or identifier.endswith('.') or identifier.split('.')[0].upper() in reserved): | |
| errors.append(f'row {number}: id must be a portable file-name component') | |
| elif identifier.casefold() in identifiers: | |
| errors.append(f'row {number}: duplicate id {identifier!r} from row {identifiers[identifier.casefold()]}') | |
| else: | |
| identifiers[identifier.casefold()] = number | |
| if 'caption' in row and (not isinstance(row['caption'], str) or not row['caption'].strip()): | |
| errors.append(f'row {number}: caption must be non-empty text') | |
| if 'seed' in row: | |
| try: | |
| validate_seed(row['seed']) | |
| except ValueError as exc: | |
| errors.append(f'row {number}: {exc}') | |
| if 'candidate_seeds' in row: | |
| try: | |
| validate_pool(row.get('seed'), row['candidate_seeds']) | |
| except ValueError as exc: | |
| errors.append(f'row {number}: {exc}') | |
| if errors: | |
| raise ValueError('Invalid batch input:\n' + '\n'.join(errors)) | |
| return rows | |
| def output_sidecar(path, *, overwrite): | |
| sidecar = path.with_suffix('.json') | |
| if sidecar == path: | |
| raise ValueError(f'Image output and JSON sidecar would use the same path: {path}') | |
| if path.is_symlink() or (path.exists() and (not overwrite or not path.is_file())): | |
| raise FileExistsError(f'Invalid image output path: {path}') | |
| if sidecar.is_symlink() or (sidecar.exists() and (not overwrite or not sidecar.is_file())): | |
| raise FileExistsError(f'Refusing to replace an existing JSON record: {sidecar}') | |
| return sidecar | |
| def _write_record(stream, record): | |
| json.dump(record, stream, ensure_ascii=False, allow_nan=False, indent=2) | |
| stream.write('\n') | |
| def write_image(image, record, path, *, overwrite=False): | |
| sidecar = output_sidecar(path, overwrite=overwrite) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| if overwrite: | |
| temporary = [] | |
| try: | |
| with NamedTemporaryFile(dir=path.parent, delete=False) as stream: | |
| temporary.append(Path(stream.name)) | |
| image.save(stream, format='PNG') | |
| with NamedTemporaryFile(mode='w', encoding='utf-8', dir=path.parent, delete=False) as stream: | |
| temporary.append(Path(stream.name)) | |
| _write_record(stream, record) | |
| os.replace(temporary[0], path) | |
| os.replace(temporary[1], sidecar) | |
| finally: | |
| for item in temporary: | |
| item.unlink(missing_ok=True) | |
| return | |
| with path.open('xb') as output: | |
| try: | |
| image.save(output, format='PNG') | |
| with sidecar.open('x', encoding='utf-8') as stream: | |
| _write_record(stream, record) | |
| except BaseException: | |
| output.close() | |
| path.unlink() | |
| raise | |
| def console_progress(event): | |
| if event['event'] == 'prefix': | |
| event['message'] = f'prefix {event["candidate"]}/{event["candidates_total"]}' | |
| elif event['event'] in ('step', 'prefix_step'): | |
| event['message'] = f'{event["event"]} {event["step"]}/{event["steps"]}' | |
| print(json.dumps(event, ensure_ascii=False), flush=True) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('prompt', nargs='?') | |
| parser.add_argument('--cases', type=Path, help='JSON list with id, caption, seed, and optional candidate_seeds') | |
| parser.add_argument('--output', type=Path, help='PNG path, or output directory with --cases') | |
| parser.add_argument('--seed', type=int, default=0) | |
| parser.add_argument('--steps', type=int) | |
| parser.add_argument('--model', type=Path, default=Path(__file__).resolve().parent) | |
| parser.add_argument('--device', default='auto') | |
| parser.add_argument('--text-encoder', type=Path, help='Local Qwen3-0.6B directory') | |
| parser.add_argument('--count-head', choices=('on', 'off'), default='on') | |
| parser.add_argument('--writing-lora', choices=('on', 'off'), default='on') | |
| parser.add_argument('--routing', choices=('auto', 'none'), default='auto') | |
| args = parser.parse_args() | |
| if (args.prompt is None) == (args.cases is None): | |
| parser.error('Supply one prompt or --cases') | |
| try: | |
| rows = read_cases(args.cases) if args.cases else [dict(id=0, caption=args.prompt, seed=args.seed)] | |
| validate_seed(args.seed) | |
| if args.steps is not None and args.steps < 1: | |
| raise ValueError('steps must be a positive integer') | |
| if args.text_encoder is not None and not args.text_encoder.is_dir(): | |
| raise ValueError(f'Local text encoder directory does not exist: {args.text_encoder}') | |
| except (ValueError, OSError) as exc: | |
| parser.error(str(exc)) | |
| batch = args.cases is not None | |
| base = args.output or Path('outputs' if batch else 'output.png') | |
| pending = [] | |
| for number, row in enumerate(rows, 1): | |
| output = base/str(row['id'])/'image.png' if batch else base | |
| if batch and output.is_file(): | |
| print(json.dumps(dict(event='skipped', id=row['id'], image=str(output)), ensure_ascii=False), flush=True) | |
| continue | |
| try: | |
| output_sidecar(output, overwrite=not batch) | |
| except (ValueError, OSError) as exc: | |
| parser.error(f'row {number}: {exc}') | |
| pending.append((row, output)) | |
| if not pending: | |
| return | |
| generator = Generator(args.model, args.device, args.text_encoder) | |
| for row, output in pending: | |
| image, record = generator.generate(row['caption'], row['seed'], steps=args.steps, | |
| candidate_seeds=row.get('candidate_seeds'), count_head=args.count_head == 'on', | |
| writing_lora=args.writing_lora == 'on', routing=args.routing, progress=console_progress) | |
| record.update(id=row['id']) | |
| write_image(image, record, output, overwrite=not batch) | |
| print(json.dumps(record, ensure_ascii=False, allow_nan=False), flush=True) | |
| if __name__ == '__main__': | |
| main() | |