instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Write docstrings that follow conventions
import torch import math import tqdm class NoiseScheduleVP: def __init__( self, schedule='discrete', betas=None, alphas_cumprod=None, continuous_beta_0=0.1, continuous_beta_1=20., ): if schedule not in ['discrete', 'linear', 'cosine']: raise ValueError(f"Unsupported noise schedule {schedule}. The schedule needs to be 'discrete' or 'linear' or 'cosine'") self.schedule = schedule if schedule == 'discrete': if betas is not None: log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0) else: assert alphas_cumprod is not None log_alphas = 0.5 * torch.log(alphas_cumprod) self.total_N = len(log_alphas) self.T = 1. self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1)) self.log_alpha_array = log_alphas.reshape((1, -1,)) else: self.total_N = 1000 self.beta_0 = continuous_beta_0 self.beta_1 = continuous_beta_1 self.cosine_s = 0.008 self.cosine_beta_max = 999. self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.)) self.schedule = schedule if schedule == 'cosine': # For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T. # Note that T = 0.9946 may be not the optimal setting. However, we find it works well. self.T = 0.9946 else: self.T = 1. def marginal_log_mean_coeff(self, t): if self.schedule == 'discrete': return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device), self.log_alpha_array.to(t.device)).reshape((-1)) elif self.schedule == 'linear': return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0 elif self.schedule == 'cosine': log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.)) log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0 return log_alpha_t def marginal_alpha(self, t): return torch.exp(self.marginal_log_mean_coeff(t)) def marginal_std(self, t): return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t))) def marginal_lambda(self, t): log_mean_coeff = self.marginal_log_mean_coeff(t) log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff)) return log_mean_coeff - log_std def inverse_lambda(self, lamb): if self.schedule == 'linear': tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb)) Delta = self.beta_0**2 + tmp return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0) elif self.schedule == 'discrete': log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb) t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]), torch.flip(self.t_array.to(lamb.device), [1])) return t.reshape((-1,)) else: log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb)) t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * (1. + self.cosine_s) / math.pi - self.cosine_s t = t_fn(log_alpha) return t def model_wrapper( model, noise_schedule, model_type="noise", model_kwargs=None, guidance_type="uncond", #condition=None, #unconditional_condition=None, guidance_scale=1., classifier_fn=None, classifier_kwargs=None, ): model_kwargs = model_kwargs or {} classifier_kwargs = classifier_kwargs or {} def get_model_input_time(t_continuous): if noise_schedule.schedule == 'discrete': return (t_continuous - 1. / noise_schedule.total_N) * 1000. else: return t_continuous def noise_pred_fn(x, t_continuous, cond=None): if t_continuous.reshape((-1,)).shape[0] == 1: t_continuous = t_continuous.expand((x.shape[0])) t_input = get_model_input_time(t_continuous) if cond is None: output = model(x, t_input, None, **model_kwargs) else: output = model(x, t_input, cond, **model_kwargs) if model_type == "noise": return output elif model_type == "x_start": alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous) dims = x.dim() return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims) elif model_type == "v": alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous) dims = x.dim() return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x elif model_type == "score": sigma_t = noise_schedule.marginal_std(t_continuous) dims = x.dim() return -expand_dims(sigma_t, dims) * output def cond_grad_fn(x, t_input, condition): with torch.enable_grad(): x_in = x.detach().requires_grad_(True) log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs) return torch.autograd.grad(log_prob.sum(), x_in)[0] def model_fn(x, t_continuous, condition, unconditional_condition): if t_continuous.reshape((-1,)).shape[0] == 1: t_continuous = t_continuous.expand((x.shape[0])) if guidance_type == "uncond": return noise_pred_fn(x, t_continuous) elif guidance_type == "classifier": assert classifier_fn is not None t_input = get_model_input_time(t_continuous) cond_grad = cond_grad_fn(x, t_input, condition) sigma_t = noise_schedule.marginal_std(t_continuous) noise = noise_pred_fn(x, t_continuous) return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad elif guidance_type == "classifier-free": if guidance_scale == 1. or unconditional_condition is None: return noise_pred_fn(x, t_continuous, cond=condition) else: x_in = torch.cat([x] * 2) t_in = torch.cat([t_continuous] * 2) if isinstance(condition, dict): assert isinstance(unconditional_condition, dict) c_in = {} for k in condition: if isinstance(condition[k], list): c_in[k] = [torch.cat([ unconditional_condition[k][i], condition[k][i]]) for i in range(len(condition[k]))] else: c_in[k] = torch.cat([ unconditional_condition[k], condition[k]]) elif isinstance(condition, list): c_in = [] assert isinstance(unconditional_condition, list) for i in range(len(condition)): c_in.append(torch.cat([unconditional_condition[i], condition[i]])) else: c_in = torch.cat([unconditional_condition, condition]) noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2) return noise_uncond + guidance_scale * (noise - noise_uncond) assert model_type in ["noise", "x_start", "v"] assert guidance_type in ["uncond", "classifier", "classifier-free"] return model_fn class UniPC: def __init__( self, model_fn, noise_schedule, predict_x0=True, thresholding=False, max_val=1., variant='bh1', condition=None, unconditional_condition=None, before_sample=None, after_sample=None, after_update=None ): self.model_fn_ = model_fn self.noise_schedule = noise_schedule self.variant = variant self.predict_x0 = predict_x0 self.thresholding = thresholding self.max_val = max_val self.condition = condition self.unconditional_condition = unconditional_condition self.before_sample = before_sample self.after_sample = after_sample self.after_update = after_update def dynamic_thresholding_fn(self, x0, t=None): dims = x0.dim() p = self.dynamic_thresholding_ratio s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1) s = expand_dims(torch.maximum(s, self.thresholding_max_val * torch.ones_like(s).to(s.device)), dims) x0 = torch.clamp(x0, -s, s) / s return x0 def model(self, x, t): cond = self.condition uncond = self.unconditional_condition if self.before_sample is not None: x, t, cond, uncond = self.before_sample(x, t, cond, uncond) res = self.model_fn_(x, t, cond, uncond) if self.after_sample is not None: x, t, cond, uncond, res = self.after_sample(x, t, cond, uncond, res) if isinstance(res, tuple): # (None, pred_x0) res = res[1] return res def noise_prediction_fn(self, x, t): return self.model(x, t) def data_prediction_fn(self, x, t): noise = self.noise_prediction_fn(x, t) dims = x.dim() alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t) x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims) if self.thresholding: p = 0.995 # A hyperparameter in the paper of "Imagen" [1]. s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1) s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims) x0 = torch.clamp(x0, -s, s) / s return x0 def model_fn(self, x, t): if self.predict_x0: return self.data_prediction_fn(x, t) else: return self.noise_prediction_fn(x, t) def get_time_steps(self, skip_type, t_T, t_0, N, device): if skip_type == 'logSNR': lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device)) lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device)) logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device) return self.noise_schedule.inverse_lambda(logSNR_steps) elif skip_type == 'time_uniform': return torch.linspace(t_T, t_0, N + 1).to(device) elif skip_type == 'time_quadratic': t_order = 2 t = torch.linspace(t_T**(1. / t_order), t_0**(1. / t_order), N + 1).pow(t_order).to(device) return t else: raise ValueError(f"Unsupported skip_type {skip_type}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'") def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device): if order == 3: K = steps // 3 + 1 if steps % 3 == 0: orders = [3,] * (K - 2) + [2, 1] elif steps % 3 == 1: orders = [3,] * (K - 1) + [1] else: orders = [3,] * (K - 1) + [2] elif order == 2: if steps % 2 == 0: K = steps // 2 orders = [2,] * K else: K = steps // 2 + 1 orders = [2,] * (K - 1) + [1] elif order == 1: K = steps orders = [1,] * steps else: raise ValueError("'order' must be '1' or '2' or '3'.") if skip_type == 'logSNR': # To reproduce the results in DPM-Solver paper timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device) else: timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[torch.cumsum(torch.tensor([0,] + orders), 0).to(device)] return timesteps_outer, orders def denoise_to_zero_fn(self, x, s): return self.data_prediction_fn(x, s) def multistep_uni_pc_update(self, x, model_prev_list, t_prev_list, t, order, **kwargs): if len(t.shape) == 0: t = t.view(-1) if 'bh' in self.variant: return self.multistep_uni_pc_bh_update(x, model_prev_list, t_prev_list, t, order, **kwargs) else: assert self.variant == 'vary_coeff' return self.multistep_uni_pc_vary_update(x, model_prev_list, t_prev_list, t, order, **kwargs) def multistep_uni_pc_vary_update(self, x, model_prev_list, t_prev_list, t, order, use_corrector=True): #print(f'using unified predictor-corrector with order {order} (solver type: vary coeff)') ns = self.noise_schedule assert order <= len(model_prev_list) # first compute rks t_prev_0 = t_prev_list[-1] lambda_prev_0 = ns.marginal_lambda(t_prev_0) lambda_t = ns.marginal_lambda(t) model_prev_0 = model_prev_list[-1] sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t) log_alpha_t = ns.marginal_log_mean_coeff(t) alpha_t = torch.exp(log_alpha_t) h = lambda_t - lambda_prev_0 rks = [] D1s = [] for i in range(1, order): t_prev_i = t_prev_list[-(i + 1)] model_prev_i = model_prev_list[-(i + 1)] lambda_prev_i = ns.marginal_lambda(t_prev_i) rk = (lambda_prev_i - lambda_prev_0) / h rks.append(rk) D1s.append((model_prev_i - model_prev_0) / rk) rks.append(1.) rks = torch.tensor(rks, device=x.device) K = len(rks) # build C matrix C = [] col = torch.ones_like(rks) for k in range(1, K + 1): C.append(col) col = col * rks / (k + 1) C = torch.stack(C, dim=1) if len(D1s) > 0: D1s = torch.stack(D1s, dim=1) # (B, K) C_inv_p = torch.linalg.inv(C[:-1, :-1]) A_p = C_inv_p if use_corrector: #print('using corrector') C_inv = torch.linalg.inv(C) A_c = C_inv hh = -h if self.predict_x0 else h h_phi_1 = torch.expm1(hh) h_phi_ks = [] factorial_k = 1 h_phi_k = h_phi_1 for k in range(1, K + 2): h_phi_ks.append(h_phi_k) h_phi_k = h_phi_k / hh - 1 / factorial_k factorial_k *= (k + 1) model_t = None if self.predict_x0: x_t_ = ( sigma_t / sigma_prev_0 * x - alpha_t * h_phi_1 * model_prev_0 ) # now predictor x_t = x_t_ if len(D1s) > 0: # compute the residuals for predictor for k in range(K - 1): x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k]) # now corrector if use_corrector: model_t = self.model_fn(x_t, t) D1_t = (model_t - model_prev_0) x_t = x_t_ k = 0 for k in range(K - 1): x_t = x_t - alpha_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1]) x_t = x_t - alpha_t * h_phi_ks[K] * (D1_t * A_c[k][-1]) else: log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t) x_t_ = ( (torch.exp(log_alpha_t - log_alpha_prev_0)) * x - (sigma_t * h_phi_1) * model_prev_0 ) # now predictor x_t = x_t_ if len(D1s) > 0: # compute the residuals for predictor for k in range(K - 1): x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_p[k]) # now corrector if use_corrector: model_t = self.model_fn(x_t, t) D1_t = (model_t - model_prev_0) x_t = x_t_ k = 0 for k in range(K - 1): x_t = x_t - sigma_t * h_phi_ks[k + 1] * torch.einsum('bkchw,k->bchw', D1s, A_c[k][:-1]) x_t = x_t - sigma_t * h_phi_ks[K] * (D1_t * A_c[k][-1]) return x_t, model_t def multistep_uni_pc_bh_update(self, x, model_prev_list, t_prev_list, t, order, x_t=None, use_corrector=True): #print(f'using unified predictor-corrector with order {order} (solver type: B(h))') ns = self.noise_schedule assert order <= len(model_prev_list) dims = x.dim() # first compute rks t_prev_0 = t_prev_list[-1] lambda_prev_0 = ns.marginal_lambda(t_prev_0) lambda_t = ns.marginal_lambda(t) model_prev_0 = model_prev_list[-1] sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t) log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t) alpha_t = torch.exp(log_alpha_t) h = lambda_t - lambda_prev_0 rks = [] D1s = [] for i in range(1, order): t_prev_i = t_prev_list[-(i + 1)] model_prev_i = model_prev_list[-(i + 1)] lambda_prev_i = ns.marginal_lambda(t_prev_i) rk = ((lambda_prev_i - lambda_prev_0) / h)[0] rks.append(rk) D1s.append((model_prev_i - model_prev_0) / rk) rks.append(1.) rks = torch.tensor(rks, device=x.device) R = [] b = [] hh = -h[0] if self.predict_x0 else h[0] h_phi_1 = torch.expm1(hh) # h\phi_1(h) = e^h - 1 h_phi_k = h_phi_1 / hh - 1 factorial_i = 1 if self.variant == 'bh1': B_h = hh elif self.variant == 'bh2': B_h = torch.expm1(hh) else: raise NotImplementedError() for i in range(1, order + 1): R.append(torch.pow(rks, i - 1)) b.append(h_phi_k * factorial_i / B_h) factorial_i *= (i + 1) h_phi_k = h_phi_k / hh - 1 / factorial_i R = torch.stack(R) b = torch.tensor(b, device=x.device) # now predictor use_predictor = len(D1s) > 0 and x_t is None if len(D1s) > 0: D1s = torch.stack(D1s, dim=1) # (B, K) if x_t is None: # for order 2, we use a simplified version if order == 2: rhos_p = torch.tensor([0.5], device=b.device) else: rhos_p = torch.linalg.solve(R[:-1, :-1], b[:-1]) else: D1s = None if use_corrector: #print('using corrector') # for order 1, we use a simplified version if order == 1: rhos_c = torch.tensor([0.5], device=b.device) else: rhos_c = torch.linalg.solve(R, b) model_t = None if self.predict_x0: x_t_ = ( expand_dims(sigma_t / sigma_prev_0, dims) * x - expand_dims(alpha_t * h_phi_1, dims)* model_prev_0 ) if x_t is None: if use_predictor: pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s) else: pred_res = 0 x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * pred_res if use_corrector: model_t = self.model_fn(x_t, t) if D1s is not None: corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s) else: corr_res = 0 D1_t = (model_t - model_prev_0) x_t = x_t_ - expand_dims(alpha_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t) else: x_t_ = ( expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x - expand_dims(sigma_t * h_phi_1, dims) * model_prev_0 ) if x_t is None: if use_predictor: pred_res = torch.einsum('k,bkchw->bchw', rhos_p, D1s) else: pred_res = 0 x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * pred_res if use_corrector: model_t = self.model_fn(x_t, t) if D1s is not None: corr_res = torch.einsum('k,bkchw->bchw', rhos_c[:-1], D1s) else: corr_res = 0 D1_t = (model_t - model_prev_0) x_t = x_t_ - expand_dims(sigma_t * B_h, dims) * (corr_res + rhos_c[-1] * D1_t) return x_t, model_t def sample(self, x, steps=20, t_start=None, t_end=None, order=3, skip_type='time_uniform', method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver', atol=0.0078, rtol=0.05, corrector=False, ): t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end t_T = self.noise_schedule.T if t_start is None else t_start device = x.device if method == 'multistep': assert steps >= order, "UniPC order must be < sampling steps" timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device) #print(f"Running UniPC Sampling with {timesteps.shape[0]} timesteps, order {order}") assert timesteps.shape[0] - 1 == steps with torch.no_grad(): vec_t = timesteps[0].expand((x.shape[0])) model_prev_list = [self.model_fn(x, vec_t)] t_prev_list = [vec_t] with tqdm.tqdm(total=steps) as pbar: # Init the first `order` values by lower order multistep DPM-Solver. for init_order in range(1, order): vec_t = timesteps[init_order].expand(x.shape[0]) x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, init_order, use_corrector=True) if model_x is None: model_x = self.model_fn(x, vec_t) if self.after_update is not None: self.after_update(x, model_x) model_prev_list.append(model_x) t_prev_list.append(vec_t) pbar.update() for step in range(order, steps + 1): vec_t = timesteps[step].expand(x.shape[0]) if lower_order_final: step_order = min(order, steps + 1 - step) else: step_order = order #print('this step order:', step_order) if step == steps: #print('do not run corrector at the last step') use_corrector = False else: use_corrector = True x, model_x = self.multistep_uni_pc_update(x, model_prev_list, t_prev_list, vec_t, step_order, use_corrector=use_corrector) if self.after_update is not None: self.after_update(x, model_x) for i in range(order - 1): t_prev_list[i] = t_prev_list[i + 1] model_prev_list[i] = model_prev_list[i + 1] t_prev_list[-1] = vec_t # We do not need to evaluate the final model value. if step < steps: if model_x is None: model_x = self.model_fn(x, vec_t) model_prev_list[-1] = model_x pbar.update() else: raise NotImplementedError() if denoise_to_zero: x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0) return x ############################################################# # other utility functions ############################################################# def interpolate_fn(x, xp, yp): N, K = x.shape[0], xp.shape[1] all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2) sorted_all_x, x_indices = torch.sort(all_x, dim=2) x_idx = torch.argmin(x_indices, dim=2) cand_start_idx = x_idx - 1 start_idx = torch.where( torch.eq(x_idx, 0), torch.tensor(1, device=x.device), torch.where( torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx, ), ) end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1) start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2) end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2) start_idx2 = torch.where( torch.eq(x_idx, 0), torch.tensor(0, device=x.device), torch.where( torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx, ), ) y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1) start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2) end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2) cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x) return cand def expand_dims(v, dims): return v[(...,) + (None,)*(dims - 1)]
--- +++ @@ -12,6 +12,85 @@ continuous_beta_0=0.1, continuous_beta_1=20., ): + """Create a wrapper class for the forward SDE (VP type). + + *** + Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t. + We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images. + *** + + The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ). + We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper). + Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have: + + log_alpha_t = self.marginal_log_mean_coeff(t) + sigma_t = self.marginal_std(t) + lambda_t = self.marginal_lambda(t) + + Moreover, as lambda(t) is an invertible function, we also support its inverse function: + + t = self.inverse_lambda(lambda_t) + + =============================================================== + + We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]). + + 1. For discrete-time DPMs: + + For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by: + t_i = (i + 1) / N + e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1. + We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3. + + Args: + betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details) + alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details) + + Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`. + + **Important**: Please pay special attention for the args for `alphas_cumprod`: + The `alphas_cumprod` is the \hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that + q_{t_n | 0}(x_{t_n} | x_0) = N ( \sqrt{\hat{alpha_n}} * x_0, (1 - \hat{alpha_n}) * I ). + Therefore, the notation \hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have + alpha_{t_n} = \sqrt{\hat{alpha_n}}, + and + log(alpha_{t_n}) = 0.5 * log(\hat{alpha_n}). + + + 2. For continuous-time DPMs: + + We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise + schedule are the default settings in DDPM and improved-DDPM: + + Args: + beta_min: A `float` number. The smallest beta for the linear schedule. + beta_max: A `float` number. The largest beta for the linear schedule. + cosine_s: A `float` number. The hyperparameter in the cosine schedule. + cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule. + T: A `float` number. The ending time of the forward process. + + =============================================================== + + Args: + schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs, + 'linear' or 'cosine' for continuous-time DPMs. + Returns: + A wrapper object of the forward SDE (VP type). + + =============================================================== + + Example: + + # For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1): + >>> ns = NoiseScheduleVP('discrete', betas=betas) + + # For discrete-time DPMs, given alphas_cumprod (the \hat{alpha_n} array for n = 0, 1, ..., N - 1): + >>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod) + + # For continuous-time DPMs (VPSDE), linear schedule: + >>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.) + + """ if schedule not in ['discrete', 'linear', 'cosine']: raise ValueError(f"Unsupported noise schedule {schedule}. The schedule needs to be 'discrete' or 'linear' or 'cosine'") @@ -44,6 +123,9 @@ self.T = 1. def marginal_log_mean_coeff(self, t): + """ + Compute log(alpha_t) of a given continuous-time label t in [0, T]. + """ if self.schedule == 'discrete': return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device), self.log_alpha_array.to(t.device)).reshape((-1)) elif self.schedule == 'linear': @@ -54,17 +136,29 @@ return log_alpha_t def marginal_alpha(self, t): + """ + Compute alpha_t of a given continuous-time label t in [0, T]. + """ return torch.exp(self.marginal_log_mean_coeff(t)) def marginal_std(self, t): + """ + Compute sigma_t of a given continuous-time label t in [0, T]. + """ return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t))) def marginal_lambda(self, t): + """ + Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T]. + """ log_mean_coeff = self.marginal_log_mean_coeff(t) log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff)) return log_mean_coeff - log_std def inverse_lambda(self, lamb): + """ + Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t. + """ if self.schedule == 'linear': tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb)) Delta = self.beta_0**2 + tmp @@ -92,11 +186,104 @@ classifier_fn=None, classifier_kwargs=None, ): + """Create a wrapper function for the noise prediction model. + + DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to + firstly wrap the model function to a noise prediction model that accepts the continuous time as the input. + + We support four types of the diffusion model by setting `model_type`: + + 1. "noise": noise prediction model. (Trained by predicting noise). + + 2. "x_start": data prediction model. (Trained by predicting the data x_0 at time 0). + + 3. "v": velocity prediction model. (Trained by predicting the velocity). + The "v" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2]. + + [1] Salimans, Tim, and Jonathan Ho. "Progressive distillation for fast sampling of diffusion models." + arXiv preprint arXiv:2202.00512 (2022). + [2] Ho, Jonathan, et al. "Imagen Video: High Definition Video Generation with Diffusion Models." + arXiv preprint arXiv:2210.02303 (2022). + + 4. "score": marginal score function. (Trained by denoising score matching). + Note that the score function and the noise prediction model follows a simple relationship: + ``` + noise(x_t, t) = -sigma_t * score(x_t, t) + ``` + + We support three types of guided sampling by DPMs by setting `guidance_type`: + 1. "uncond": unconditional sampling by DPMs. + The input `model` has the following format: + `` + model(x, t_input, **model_kwargs) -> noise | x_start | v | score + `` + + 2. "classifier": classifier guidance sampling [3] by DPMs and another classifier. + The input `model` has the following format: + `` + model(x, t_input, **model_kwargs) -> noise | x_start | v | score + `` + + The input `classifier_fn` has the following format: + `` + classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond) + `` + + [3] P. Dhariwal and A. Q. Nichol, "Diffusion models beat GANs on image synthesis," + in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794. + + 3. "classifier-free": classifier-free guidance sampling by conditional DPMs. + The input `model` has the following format: + `` + model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score + `` + And if cond == `unconditional_condition`, the model output is the unconditional DPM output. + + [4] Ho, Jonathan, and Tim Salimans. "Classifier-free diffusion guidance." + arXiv preprint arXiv:2207.12598 (2022). + + + The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999) + or continuous-time labels (i.e. epsilon to T). + + We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise: + `` + def model_fn(x, t_continuous) -> noise: + t_input = get_model_input_time(t_continuous) + return noise_pred(model, x, t_input, **model_kwargs) + `` + where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver. + + =============================================================== + + Args: + model: A diffusion model with the corresponding format described above. + noise_schedule: A noise schedule object, such as NoiseScheduleVP. + model_type: A `str`. The parameterization type of the diffusion model. + "noise" or "x_start" or "v" or "score". + model_kwargs: A `dict`. A dict for the other inputs of the model function. + guidance_type: A `str`. The type of the guidance for sampling. + "uncond" or "classifier" or "classifier-free". + condition: A pytorch tensor. The condition for the guided sampling. + Only used for "classifier" or "classifier-free" guidance type. + unconditional_condition: A pytorch tensor. The condition for the unconditional sampling. + Only used for "classifier-free" guidance type. + guidance_scale: A `float`. The scale for the guided sampling. + classifier_fn: A classifier function. Only used for the classifier guidance. + classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function. + Returns: + A noise prediction model that accepts the noised data and the continuous time as the inputs. + """ model_kwargs = model_kwargs or {} classifier_kwargs = classifier_kwargs or {} def get_model_input_time(t_continuous): + """ + Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time. + For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N]. + For continuous-time DPMs, we just use `t_continuous`. + """ if noise_schedule.schedule == 'discrete': return (t_continuous - 1. / noise_schedule.total_N) * 1000. else: @@ -126,12 +313,18 @@ return -expand_dims(sigma_t, dims) * output def cond_grad_fn(x, t_input, condition): + """ + Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t). + """ with torch.enable_grad(): x_in = x.detach().requires_grad_(True) log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs) return torch.autograd.grad(log_prob.sum(), x_in)[0] def model_fn(x, t_continuous, condition, unconditional_condition): + """ + The noise prediction model function that is used for DPM-Solver. + """ if t_continuous.reshape((-1,)).shape[0] == 1: t_continuous = t_continuous.expand((x.shape[0])) if guidance_type == "uncond": @@ -191,6 +384,10 @@ after_sample=None, after_update=None ): + """Construct a UniPC. + + We support both data_prediction and noise_prediction. + """ self.model_fn_ = model_fn self.noise_schedule = noise_schedule self.variant = variant @@ -204,6 +401,9 @@ self.after_update = after_update def dynamic_thresholding_fn(self, x0, t=None): + """ + The dynamic thresholding method. + """ dims = x0.dim() p = self.dynamic_thresholding_ratio s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1) @@ -227,9 +427,15 @@ return res def noise_prediction_fn(self, x, t): + """ + Return the noise prediction model. + """ return self.model(x, t) def data_prediction_fn(self, x, t): + """ + Return the data prediction model (with thresholding). + """ noise = self.noise_prediction_fn(x, t) dims = x.dim() alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t) @@ -242,12 +448,17 @@ return x0 def model_fn(self, x, t): + """ + Convert the model to the noise prediction model or the data prediction model. + """ if self.predict_x0: return self.data_prediction_fn(x, t) else: return self.noise_prediction_fn(x, t) def get_time_steps(self, skip_type, t_T, t_0, N, device): + """Compute the intermediate time steps for sampling. + """ if skip_type == 'logSNR': lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device)) lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device)) @@ -263,6 +474,9 @@ raise ValueError(f"Unsupported skip_type {skip_type}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'") def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device): + """ + Get the order of each step for sampling by the singlestep DPM-Solver. + """ if order == 3: K = steps // 3 + 1 if steps % 3 == 0: @@ -291,6 +505,9 @@ return timesteps_outer, orders def denoise_to_zero_fn(self, x, s): + """ + Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization. + """ return self.data_prediction_fn(x, s) def multistep_uni_pc_update(self, x, model_prev_list, t_prev_list, t, order, **kwargs): @@ -592,6 +809,18 @@ ############################################################# def interpolate_fn(x, xp, yp): + """ + A piecewise linear function y = f(x), using xp and yp as keypoints. + We implement f(x) in a differentiable way (i.e. applicable for autograd). + The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.) + + Args: + x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver). + xp: PyTorch tensor with shape [C, K], where K is the number of keypoints. + yp: PyTorch tensor with shape [C, K]. + Returns: + The function values f(x), with shape [N, C]. + """ N, K = x.shape[0], xp.shape[1] all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2) sorted_all_x, x_indices = torch.sort(all_x, dim=2) @@ -622,4 +851,13 @@ def expand_dims(v, dims): - return v[(...,) + (None,)*(dims - 1)]+ """ + Expand the tensor `v` to the dim `dims`. + + Args: + `v`: a PyTorch tensor with shape [N]. + `dim`: a `int`. + Returns: + a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`. + """ + return v[(...,) + (None,)*(dims - 1)]
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/models/diffusion/uni_pc/uni_pc.py
Create documentation strings for testing functions
from __future__ import annotations import dataclasses import inspect import os from typing import Optional, Any from fastapi import FastAPI from gradio import Blocks from modules import errors, timer, extensions, shared, util def report_exception(c, job): errors.report(f"Error executing callback {job} for {c.script}", exc_info=True) class ImageSaveParams: def __init__(self, image, p, filename, pnginfo): self.image = image """the PIL image itself""" self.p = p """p object with processing parameters; either StableDiffusionProcessing or an object with same fields""" self.filename = filename """name of file that the image would be saved to""" self.pnginfo = pnginfo """dictionary with parameters for image's PNG info data; infotext will have the key 'parameters'""" class ExtraNoiseParams: def __init__(self, noise, x, xi): self.noise = noise """Random noise generated by the seed""" self.x = x """Latent representation of the image""" self.xi = xi """Noisy latent representation of the image""" class CFGDenoiserParams: def __init__(self, x, image_cond, sigma, sampling_step, total_sampling_steps, text_cond, text_uncond, denoiser=None): self.x = x """Latent image representation in the process of being denoised""" self.image_cond = image_cond """Conditioning image""" self.sigma = sigma """Current sigma noise step value""" self.sampling_step = sampling_step """Current Sampling step number""" self.total_sampling_steps = total_sampling_steps """Total number of sampling steps planned""" self.text_cond = text_cond """ Encoder hidden states of text conditioning from prompt""" self.text_uncond = text_uncond """ Encoder hidden states of text conditioning from negative prompt""" self.denoiser = denoiser """Current CFGDenoiser object with processing parameters""" class CFGDenoisedParams: def __init__(self, x, sampling_step, total_sampling_steps, inner_model): self.x = x """Latent image representation in the process of being denoised""" self.sampling_step = sampling_step """Current Sampling step number""" self.total_sampling_steps = total_sampling_steps """Total number of sampling steps planned""" self.inner_model = inner_model """Inner model reference used for denoising""" class AfterCFGCallbackParams: def __init__(self, x, sampling_step, total_sampling_steps): self.x = x """Latent image representation in the process of being denoised""" self.sampling_step = sampling_step """Current Sampling step number""" self.total_sampling_steps = total_sampling_steps """Total number of sampling steps planned""" class UiTrainTabParams: def __init__(self, txt2img_preview_params): self.txt2img_preview_params = txt2img_preview_params class ImageGridLoopParams: def __init__(self, imgs, cols, rows): self.imgs = imgs self.cols = cols self.rows = rows @dataclasses.dataclass class BeforeTokenCounterParams: prompt: str steps: int styles: list is_positive: bool = True @dataclasses.dataclass class ScriptCallback: script: str callback: any name: str = "unnamed" def add_callback(callbacks, fun, *, name=None, category='unknown', filename=None): if filename is None: stack = [x for x in inspect.stack() if x.filename != __file__] filename = stack[0].filename if stack else 'unknown file' extension = extensions.find_extension(filename) extension_name = extension.canonical_name if extension else 'base' callback_name = f"{extension_name}/{os.path.basename(filename)}/{category}" if name is not None: callback_name += f'/{name}' unique_callback_name = callback_name for index in range(1000): existing = any(x.name == unique_callback_name for x in callbacks) if not existing: break unique_callback_name = f'{callback_name}-{index+1}' callbacks.append(ScriptCallback(filename, fun, unique_callback_name)) def sort_callbacks(category, unordered_callbacks, *, enable_user_sort=True): callbacks = unordered_callbacks.copy() callback_lookup = {x.name: x for x in callbacks} dependencies = {} order_instructions = {} for extension in extensions.extensions: for order_instruction in extension.metadata.list_callback_order_instructions(): if order_instruction.name in callback_lookup: if order_instruction.name not in order_instructions: order_instructions[order_instruction.name] = [] order_instructions[order_instruction.name].append(order_instruction) if order_instructions: for callback in callbacks: dependencies[callback.name] = [] for callback in callbacks: for order_instruction in order_instructions.get(callback.name, []): for after in order_instruction.after: if after not in callback_lookup: continue dependencies[callback.name].append(after) for before in order_instruction.before: if before not in callback_lookup: continue dependencies[before].append(callback.name) sorted_names = util.topological_sort(dependencies) callbacks = [callback_lookup[x] for x in sorted_names] if enable_user_sort: for name in reversed(getattr(shared.opts, 'prioritized_callbacks_' + category, [])): index = next((i for i, callback in enumerate(callbacks) if callback.name == name), None) if index is not None: callbacks.insert(0, callbacks.pop(index)) return callbacks def ordered_callbacks(category, unordered_callbacks=None, *, enable_user_sort=True): if unordered_callbacks is None: unordered_callbacks = callback_map.get('callbacks_' + category, []) if not enable_user_sort: return sort_callbacks(category, unordered_callbacks, enable_user_sort=False) callbacks = ordered_callbacks_map.get(category) if callbacks is not None and len(callbacks) == len(unordered_callbacks): return callbacks callbacks = sort_callbacks(category, unordered_callbacks) ordered_callbacks_map[category] = callbacks return callbacks def enumerate_callbacks(): for category, callbacks in callback_map.items(): if category.startswith('callbacks_'): category = category[10:] yield category, callbacks callback_map = dict( callbacks_app_started=[], callbacks_model_loaded=[], callbacks_ui_tabs=[], callbacks_ui_train_tabs=[], callbacks_ui_settings=[], callbacks_before_image_saved=[], callbacks_image_saved=[], callbacks_extra_noise=[], callbacks_cfg_denoiser=[], callbacks_cfg_denoised=[], callbacks_cfg_after_cfg=[], callbacks_before_component=[], callbacks_after_component=[], callbacks_image_grid=[], callbacks_infotext_pasted=[], callbacks_script_unloaded=[], callbacks_before_ui=[], callbacks_on_reload=[], callbacks_list_optimizers=[], callbacks_list_unets=[], callbacks_before_token_counter=[], ) ordered_callbacks_map = {} def clear_callbacks(): for callback_list in callback_map.values(): callback_list.clear() ordered_callbacks_map.clear() def app_started_callback(demo: Optional[Blocks], app: FastAPI): for c in ordered_callbacks('app_started'): try: c.callback(demo, app) timer.startup_timer.record(os.path.basename(c.script)) except Exception: report_exception(c, 'app_started_callback') def app_reload_callback(): for c in ordered_callbacks('on_reload'): try: c.callback() except Exception: report_exception(c, 'callbacks_on_reload') def model_loaded_callback(sd_model): for c in ordered_callbacks('model_loaded'): try: c.callback(sd_model) except Exception: report_exception(c, 'model_loaded_callback') def ui_tabs_callback(): res = [] for c in ordered_callbacks('ui_tabs'): try: res += c.callback() or [] except Exception: report_exception(c, 'ui_tabs_callback') return res def ui_train_tabs_callback(params: UiTrainTabParams): for c in ordered_callbacks('ui_train_tabs'): try: c.callback(params) except Exception: report_exception(c, 'callbacks_ui_train_tabs') def ui_settings_callback(): for c in ordered_callbacks('ui_settings'): try: c.callback() except Exception: report_exception(c, 'ui_settings_callback') def before_image_saved_callback(params: ImageSaveParams): for c in ordered_callbacks('before_image_saved'): try: c.callback(params) except Exception: report_exception(c, 'before_image_saved_callback') def image_saved_callback(params: ImageSaveParams): for c in ordered_callbacks('image_saved'): try: c.callback(params) except Exception: report_exception(c, 'image_saved_callback') def extra_noise_callback(params: ExtraNoiseParams): for c in ordered_callbacks('extra_noise'): try: c.callback(params) except Exception: report_exception(c, 'callbacks_extra_noise') def cfg_denoiser_callback(params: CFGDenoiserParams): for c in ordered_callbacks('cfg_denoiser'): try: c.callback(params) except Exception: report_exception(c, 'cfg_denoiser_callback') def cfg_denoised_callback(params: CFGDenoisedParams): for c in ordered_callbacks('cfg_denoised'): try: c.callback(params) except Exception: report_exception(c, 'cfg_denoised_callback') def cfg_after_cfg_callback(params: AfterCFGCallbackParams): for c in ordered_callbacks('cfg_after_cfg'): try: c.callback(params) except Exception: report_exception(c, 'cfg_after_cfg_callback') def before_component_callback(component, **kwargs): for c in ordered_callbacks('before_component'): try: c.callback(component, **kwargs) except Exception: report_exception(c, 'before_component_callback') def after_component_callback(component, **kwargs): for c in ordered_callbacks('after_component'): try: c.callback(component, **kwargs) except Exception: report_exception(c, 'after_component_callback') def image_grid_callback(params: ImageGridLoopParams): for c in ordered_callbacks('image_grid'): try: c.callback(params) except Exception: report_exception(c, 'image_grid') def infotext_pasted_callback(infotext: str, params: dict[str, Any]): for c in ordered_callbacks('infotext_pasted'): try: c.callback(infotext, params) except Exception: report_exception(c, 'infotext_pasted') def script_unloaded_callback(): for c in reversed(ordered_callbacks('script_unloaded')): try: c.callback() except Exception: report_exception(c, 'script_unloaded') def before_ui_callback(): for c in reversed(ordered_callbacks('before_ui')): try: c.callback() except Exception: report_exception(c, 'before_ui') def list_optimizers_callback(): res = [] for c in ordered_callbacks('list_optimizers'): try: c.callback(res) except Exception: report_exception(c, 'list_optimizers') return res def list_unets_callback(): res = [] for c in ordered_callbacks('list_unets'): try: c.callback(res) except Exception: report_exception(c, 'list_unets') return res def before_token_counter_callback(params: BeforeTokenCounterParams): for c in ordered_callbacks('before_token_counter'): try: c.callback(params) except Exception: report_exception(c, 'before_token_counter') def remove_current_script_callbacks(): stack = [x for x in inspect.stack() if x.filename != __file__] filename = stack[0].filename if stack else 'unknown file' if filename == 'unknown file': return for callback_list in callback_map.values(): for callback_to_remove in [cb for cb in callback_list if cb.script == filename]: callback_list.remove(callback_to_remove) for ordered_callbacks_list in ordered_callbacks_map.values(): for callback_to_remove in [cb for cb in ordered_callbacks_list if cb.script == filename]: ordered_callbacks_list.remove(callback_to_remove) def remove_callbacks_for_function(callback_func): for callback_list in callback_map.values(): for callback_to_remove in [cb for cb in callback_list if cb.callback == callback_func]: callback_list.remove(callback_to_remove) for ordered_callback_list in ordered_callbacks_map.values(): for callback_to_remove in [cb for cb in ordered_callback_list if cb.callback == callback_func]: ordered_callback_list.remove(callback_to_remove) def on_app_started(callback, *, name=None): add_callback(callback_map['callbacks_app_started'], callback, name=name, category='app_started') def on_before_reload(callback, *, name=None): add_callback(callback_map['callbacks_on_reload'], callback, name=name, category='on_reload') def on_model_loaded(callback, *, name=None): add_callback(callback_map['callbacks_model_loaded'], callback, name=name, category='model_loaded') def on_ui_tabs(callback, *, name=None): add_callback(callback_map['callbacks_ui_tabs'], callback, name=name, category='ui_tabs') def on_ui_train_tabs(callback, *, name=None): add_callback(callback_map['callbacks_ui_train_tabs'], callback, name=name, category='ui_train_tabs') def on_ui_settings(callback, *, name=None): add_callback(callback_map['callbacks_ui_settings'], callback, name=name, category='ui_settings') def on_before_image_saved(callback, *, name=None): add_callback(callback_map['callbacks_before_image_saved'], callback, name=name, category='before_image_saved') def on_image_saved(callback, *, name=None): add_callback(callback_map['callbacks_image_saved'], callback, name=name, category='image_saved') def on_extra_noise(callback, *, name=None): add_callback(callback_map['callbacks_extra_noise'], callback, name=name, category='extra_noise') def on_cfg_denoiser(callback, *, name=None): add_callback(callback_map['callbacks_cfg_denoiser'], callback, name=name, category='cfg_denoiser') def on_cfg_denoised(callback, *, name=None): add_callback(callback_map['callbacks_cfg_denoised'], callback, name=name, category='cfg_denoised') def on_cfg_after_cfg(callback, *, name=None): add_callback(callback_map['callbacks_cfg_after_cfg'], callback, name=name, category='cfg_after_cfg') def on_before_component(callback, *, name=None): add_callback(callback_map['callbacks_before_component'], callback, name=name, category='before_component') def on_after_component(callback, *, name=None): add_callback(callback_map['callbacks_after_component'], callback, name=name, category='after_component') def on_image_grid(callback, *, name=None): add_callback(callback_map['callbacks_image_grid'], callback, name=name, category='image_grid') def on_infotext_pasted(callback, *, name=None): add_callback(callback_map['callbacks_infotext_pasted'], callback, name=name, category='infotext_pasted') def on_script_unloaded(callback, *, name=None): add_callback(callback_map['callbacks_script_unloaded'], callback, name=name, category='script_unloaded') def on_before_ui(callback, *, name=None): add_callback(callback_map['callbacks_before_ui'], callback, name=name, category='before_ui') def on_list_optimizers(callback, *, name=None): add_callback(callback_map['callbacks_list_optimizers'], callback, name=name, category='list_optimizers') def on_list_unets(callback, *, name=None): add_callback(callback_map['callbacks_list_unets'], callback, name=name, category='list_unets') def on_before_token_counter(callback, *, name=None): add_callback(callback_map['callbacks_before_token_counter'], callback, name=name, category='before_token_counter')
--- +++ @@ -1,542 +1,613 @@-from __future__ import annotations - -import dataclasses -import inspect -import os -from typing import Optional, Any - -from fastapi import FastAPI -from gradio import Blocks - -from modules import errors, timer, extensions, shared, util - - -def report_exception(c, job): - errors.report(f"Error executing callback {job} for {c.script}", exc_info=True) - - -class ImageSaveParams: - def __init__(self, image, p, filename, pnginfo): - self.image = image - """the PIL image itself""" - - self.p = p - """p object with processing parameters; either StableDiffusionProcessing or an object with same fields""" - - self.filename = filename - """name of file that the image would be saved to""" - - self.pnginfo = pnginfo - """dictionary with parameters for image's PNG info data; infotext will have the key 'parameters'""" - - -class ExtraNoiseParams: - def __init__(self, noise, x, xi): - self.noise = noise - """Random noise generated by the seed""" - - self.x = x - """Latent representation of the image""" - - self.xi = xi - """Noisy latent representation of the image""" - - -class CFGDenoiserParams: - def __init__(self, x, image_cond, sigma, sampling_step, total_sampling_steps, text_cond, text_uncond, denoiser=None): - self.x = x - """Latent image representation in the process of being denoised""" - - self.image_cond = image_cond - """Conditioning image""" - - self.sigma = sigma - """Current sigma noise step value""" - - self.sampling_step = sampling_step - """Current Sampling step number""" - - self.total_sampling_steps = total_sampling_steps - """Total number of sampling steps planned""" - - self.text_cond = text_cond - """ Encoder hidden states of text conditioning from prompt""" - - self.text_uncond = text_uncond - """ Encoder hidden states of text conditioning from negative prompt""" - - self.denoiser = denoiser - """Current CFGDenoiser object with processing parameters""" - - -class CFGDenoisedParams: - def __init__(self, x, sampling_step, total_sampling_steps, inner_model): - self.x = x - """Latent image representation in the process of being denoised""" - - self.sampling_step = sampling_step - """Current Sampling step number""" - - self.total_sampling_steps = total_sampling_steps - """Total number of sampling steps planned""" - - self.inner_model = inner_model - """Inner model reference used for denoising""" - - -class AfterCFGCallbackParams: - def __init__(self, x, sampling_step, total_sampling_steps): - self.x = x - """Latent image representation in the process of being denoised""" - - self.sampling_step = sampling_step - """Current Sampling step number""" - - self.total_sampling_steps = total_sampling_steps - """Total number of sampling steps planned""" - - -class UiTrainTabParams: - def __init__(self, txt2img_preview_params): - self.txt2img_preview_params = txt2img_preview_params - - -class ImageGridLoopParams: - def __init__(self, imgs, cols, rows): - self.imgs = imgs - self.cols = cols - self.rows = rows - - -@dataclasses.dataclass -class BeforeTokenCounterParams: - prompt: str - steps: int - styles: list - - is_positive: bool = True - - -@dataclasses.dataclass -class ScriptCallback: - script: str - callback: any - name: str = "unnamed" - - -def add_callback(callbacks, fun, *, name=None, category='unknown', filename=None): - if filename is None: - stack = [x for x in inspect.stack() if x.filename != __file__] - filename = stack[0].filename if stack else 'unknown file' - - extension = extensions.find_extension(filename) - extension_name = extension.canonical_name if extension else 'base' - - callback_name = f"{extension_name}/{os.path.basename(filename)}/{category}" - if name is not None: - callback_name += f'/{name}' - - unique_callback_name = callback_name - for index in range(1000): - existing = any(x.name == unique_callback_name for x in callbacks) - if not existing: - break - - unique_callback_name = f'{callback_name}-{index+1}' - - callbacks.append(ScriptCallback(filename, fun, unique_callback_name)) - - -def sort_callbacks(category, unordered_callbacks, *, enable_user_sort=True): - callbacks = unordered_callbacks.copy() - callback_lookup = {x.name: x for x in callbacks} - dependencies = {} - - order_instructions = {} - for extension in extensions.extensions: - for order_instruction in extension.metadata.list_callback_order_instructions(): - if order_instruction.name in callback_lookup: - if order_instruction.name not in order_instructions: - order_instructions[order_instruction.name] = [] - - order_instructions[order_instruction.name].append(order_instruction) - - if order_instructions: - for callback in callbacks: - dependencies[callback.name] = [] - - for callback in callbacks: - for order_instruction in order_instructions.get(callback.name, []): - for after in order_instruction.after: - if after not in callback_lookup: - continue - - dependencies[callback.name].append(after) - - for before in order_instruction.before: - if before not in callback_lookup: - continue - - dependencies[before].append(callback.name) - - sorted_names = util.topological_sort(dependencies) - callbacks = [callback_lookup[x] for x in sorted_names] - - if enable_user_sort: - for name in reversed(getattr(shared.opts, 'prioritized_callbacks_' + category, [])): - index = next((i for i, callback in enumerate(callbacks) if callback.name == name), None) - if index is not None: - callbacks.insert(0, callbacks.pop(index)) - - return callbacks - - -def ordered_callbacks(category, unordered_callbacks=None, *, enable_user_sort=True): - if unordered_callbacks is None: - unordered_callbacks = callback_map.get('callbacks_' + category, []) - - if not enable_user_sort: - return sort_callbacks(category, unordered_callbacks, enable_user_sort=False) - - callbacks = ordered_callbacks_map.get(category) - if callbacks is not None and len(callbacks) == len(unordered_callbacks): - return callbacks - - callbacks = sort_callbacks(category, unordered_callbacks) - - ordered_callbacks_map[category] = callbacks - return callbacks - - -def enumerate_callbacks(): - for category, callbacks in callback_map.items(): - if category.startswith('callbacks_'): - category = category[10:] - - yield category, callbacks - - -callback_map = dict( - callbacks_app_started=[], - callbacks_model_loaded=[], - callbacks_ui_tabs=[], - callbacks_ui_train_tabs=[], - callbacks_ui_settings=[], - callbacks_before_image_saved=[], - callbacks_image_saved=[], - callbacks_extra_noise=[], - callbacks_cfg_denoiser=[], - callbacks_cfg_denoised=[], - callbacks_cfg_after_cfg=[], - callbacks_before_component=[], - callbacks_after_component=[], - callbacks_image_grid=[], - callbacks_infotext_pasted=[], - callbacks_script_unloaded=[], - callbacks_before_ui=[], - callbacks_on_reload=[], - callbacks_list_optimizers=[], - callbacks_list_unets=[], - callbacks_before_token_counter=[], -) - -ordered_callbacks_map = {} - - -def clear_callbacks(): - for callback_list in callback_map.values(): - callback_list.clear() - - ordered_callbacks_map.clear() - - -def app_started_callback(demo: Optional[Blocks], app: FastAPI): - for c in ordered_callbacks('app_started'): - try: - c.callback(demo, app) - timer.startup_timer.record(os.path.basename(c.script)) - except Exception: - report_exception(c, 'app_started_callback') - - -def app_reload_callback(): - for c in ordered_callbacks('on_reload'): - try: - c.callback() - except Exception: - report_exception(c, 'callbacks_on_reload') - - -def model_loaded_callback(sd_model): - for c in ordered_callbacks('model_loaded'): - try: - c.callback(sd_model) - except Exception: - report_exception(c, 'model_loaded_callback') - - -def ui_tabs_callback(): - res = [] - - for c in ordered_callbacks('ui_tabs'): - try: - res += c.callback() or [] - except Exception: - report_exception(c, 'ui_tabs_callback') - - return res - - -def ui_train_tabs_callback(params: UiTrainTabParams): - for c in ordered_callbacks('ui_train_tabs'): - try: - c.callback(params) - except Exception: - report_exception(c, 'callbacks_ui_train_tabs') - - -def ui_settings_callback(): - for c in ordered_callbacks('ui_settings'): - try: - c.callback() - except Exception: - report_exception(c, 'ui_settings_callback') - - -def before_image_saved_callback(params: ImageSaveParams): - for c in ordered_callbacks('before_image_saved'): - try: - c.callback(params) - except Exception: - report_exception(c, 'before_image_saved_callback') - - -def image_saved_callback(params: ImageSaveParams): - for c in ordered_callbacks('image_saved'): - try: - c.callback(params) - except Exception: - report_exception(c, 'image_saved_callback') - - -def extra_noise_callback(params: ExtraNoiseParams): - for c in ordered_callbacks('extra_noise'): - try: - c.callback(params) - except Exception: - report_exception(c, 'callbacks_extra_noise') - - -def cfg_denoiser_callback(params: CFGDenoiserParams): - for c in ordered_callbacks('cfg_denoiser'): - try: - c.callback(params) - except Exception: - report_exception(c, 'cfg_denoiser_callback') - - -def cfg_denoised_callback(params: CFGDenoisedParams): - for c in ordered_callbacks('cfg_denoised'): - try: - c.callback(params) - except Exception: - report_exception(c, 'cfg_denoised_callback') - - -def cfg_after_cfg_callback(params: AfterCFGCallbackParams): - for c in ordered_callbacks('cfg_after_cfg'): - try: - c.callback(params) - except Exception: - report_exception(c, 'cfg_after_cfg_callback') - - -def before_component_callback(component, **kwargs): - for c in ordered_callbacks('before_component'): - try: - c.callback(component, **kwargs) - except Exception: - report_exception(c, 'before_component_callback') - - -def after_component_callback(component, **kwargs): - for c in ordered_callbacks('after_component'): - try: - c.callback(component, **kwargs) - except Exception: - report_exception(c, 'after_component_callback') - - -def image_grid_callback(params: ImageGridLoopParams): - for c in ordered_callbacks('image_grid'): - try: - c.callback(params) - except Exception: - report_exception(c, 'image_grid') - - -def infotext_pasted_callback(infotext: str, params: dict[str, Any]): - for c in ordered_callbacks('infotext_pasted'): - try: - c.callback(infotext, params) - except Exception: - report_exception(c, 'infotext_pasted') - - -def script_unloaded_callback(): - for c in reversed(ordered_callbacks('script_unloaded')): - try: - c.callback() - except Exception: - report_exception(c, 'script_unloaded') - - -def before_ui_callback(): - for c in reversed(ordered_callbacks('before_ui')): - try: - c.callback() - except Exception: - report_exception(c, 'before_ui') - - -def list_optimizers_callback(): - res = [] - - for c in ordered_callbacks('list_optimizers'): - try: - c.callback(res) - except Exception: - report_exception(c, 'list_optimizers') - - return res - - -def list_unets_callback(): - res = [] - - for c in ordered_callbacks('list_unets'): - try: - c.callback(res) - except Exception: - report_exception(c, 'list_unets') - - return res - - -def before_token_counter_callback(params: BeforeTokenCounterParams): - for c in ordered_callbacks('before_token_counter'): - try: - c.callback(params) - except Exception: - report_exception(c, 'before_token_counter') - - -def remove_current_script_callbacks(): - stack = [x for x in inspect.stack() if x.filename != __file__] - filename = stack[0].filename if stack else 'unknown file' - if filename == 'unknown file': - return - for callback_list in callback_map.values(): - for callback_to_remove in [cb for cb in callback_list if cb.script == filename]: - callback_list.remove(callback_to_remove) - for ordered_callbacks_list in ordered_callbacks_map.values(): - for callback_to_remove in [cb for cb in ordered_callbacks_list if cb.script == filename]: - ordered_callbacks_list.remove(callback_to_remove) - - -def remove_callbacks_for_function(callback_func): - for callback_list in callback_map.values(): - for callback_to_remove in [cb for cb in callback_list if cb.callback == callback_func]: - callback_list.remove(callback_to_remove) - for ordered_callback_list in ordered_callbacks_map.values(): - for callback_to_remove in [cb for cb in ordered_callback_list if cb.callback == callback_func]: - ordered_callback_list.remove(callback_to_remove) - - -def on_app_started(callback, *, name=None): - add_callback(callback_map['callbacks_app_started'], callback, name=name, category='app_started') - - -def on_before_reload(callback, *, name=None): - add_callback(callback_map['callbacks_on_reload'], callback, name=name, category='on_reload') - - -def on_model_loaded(callback, *, name=None): - add_callback(callback_map['callbacks_model_loaded'], callback, name=name, category='model_loaded') - - -def on_ui_tabs(callback, *, name=None): - add_callback(callback_map['callbacks_ui_tabs'], callback, name=name, category='ui_tabs') - - -def on_ui_train_tabs(callback, *, name=None): - add_callback(callback_map['callbacks_ui_train_tabs'], callback, name=name, category='ui_train_tabs') - - -def on_ui_settings(callback, *, name=None): - add_callback(callback_map['callbacks_ui_settings'], callback, name=name, category='ui_settings') - - -def on_before_image_saved(callback, *, name=None): - add_callback(callback_map['callbacks_before_image_saved'], callback, name=name, category='before_image_saved') - - -def on_image_saved(callback, *, name=None): - add_callback(callback_map['callbacks_image_saved'], callback, name=name, category='image_saved') - - -def on_extra_noise(callback, *, name=None): - add_callback(callback_map['callbacks_extra_noise'], callback, name=name, category='extra_noise') - - -def on_cfg_denoiser(callback, *, name=None): - add_callback(callback_map['callbacks_cfg_denoiser'], callback, name=name, category='cfg_denoiser') - - -def on_cfg_denoised(callback, *, name=None): - add_callback(callback_map['callbacks_cfg_denoised'], callback, name=name, category='cfg_denoised') - - -def on_cfg_after_cfg(callback, *, name=None): - add_callback(callback_map['callbacks_cfg_after_cfg'], callback, name=name, category='cfg_after_cfg') - - -def on_before_component(callback, *, name=None): - add_callback(callback_map['callbacks_before_component'], callback, name=name, category='before_component') - - -def on_after_component(callback, *, name=None): - add_callback(callback_map['callbacks_after_component'], callback, name=name, category='after_component') - - -def on_image_grid(callback, *, name=None): - add_callback(callback_map['callbacks_image_grid'], callback, name=name, category='image_grid') - - -def on_infotext_pasted(callback, *, name=None): - add_callback(callback_map['callbacks_infotext_pasted'], callback, name=name, category='infotext_pasted') - - -def on_script_unloaded(callback, *, name=None): - - add_callback(callback_map['callbacks_script_unloaded'], callback, name=name, category='script_unloaded') - - -def on_before_ui(callback, *, name=None): - - add_callback(callback_map['callbacks_before_ui'], callback, name=name, category='before_ui') - - -def on_list_optimizers(callback, *, name=None): - - add_callback(callback_map['callbacks_list_optimizers'], callback, name=name, category='list_optimizers') - - -def on_list_unets(callback, *, name=None): - - add_callback(callback_map['callbacks_list_unets'], callback, name=name, category='list_unets') - - -def on_before_token_counter(callback, *, name=None): - - add_callback(callback_map['callbacks_before_token_counter'], callback, name=name, category='before_token_counter')+from __future__ import annotations + +import dataclasses +import inspect +import os +from typing import Optional, Any + +from fastapi import FastAPI +from gradio import Blocks + +from modules import errors, timer, extensions, shared, util + + +def report_exception(c, job): + errors.report(f"Error executing callback {job} for {c.script}", exc_info=True) + + +class ImageSaveParams: + def __init__(self, image, p, filename, pnginfo): + self.image = image + """the PIL image itself""" + + self.p = p + """p object with processing parameters; either StableDiffusionProcessing or an object with same fields""" + + self.filename = filename + """name of file that the image would be saved to""" + + self.pnginfo = pnginfo + """dictionary with parameters for image's PNG info data; infotext will have the key 'parameters'""" + + +class ExtraNoiseParams: + def __init__(self, noise, x, xi): + self.noise = noise + """Random noise generated by the seed""" + + self.x = x + """Latent representation of the image""" + + self.xi = xi + """Noisy latent representation of the image""" + + +class CFGDenoiserParams: + def __init__(self, x, image_cond, sigma, sampling_step, total_sampling_steps, text_cond, text_uncond, denoiser=None): + self.x = x + """Latent image representation in the process of being denoised""" + + self.image_cond = image_cond + """Conditioning image""" + + self.sigma = sigma + """Current sigma noise step value""" + + self.sampling_step = sampling_step + """Current Sampling step number""" + + self.total_sampling_steps = total_sampling_steps + """Total number of sampling steps planned""" + + self.text_cond = text_cond + """ Encoder hidden states of text conditioning from prompt""" + + self.text_uncond = text_uncond + """ Encoder hidden states of text conditioning from negative prompt""" + + self.denoiser = denoiser + """Current CFGDenoiser object with processing parameters""" + + +class CFGDenoisedParams: + def __init__(self, x, sampling_step, total_sampling_steps, inner_model): + self.x = x + """Latent image representation in the process of being denoised""" + + self.sampling_step = sampling_step + """Current Sampling step number""" + + self.total_sampling_steps = total_sampling_steps + """Total number of sampling steps planned""" + + self.inner_model = inner_model + """Inner model reference used for denoising""" + + +class AfterCFGCallbackParams: + def __init__(self, x, sampling_step, total_sampling_steps): + self.x = x + """Latent image representation in the process of being denoised""" + + self.sampling_step = sampling_step + """Current Sampling step number""" + + self.total_sampling_steps = total_sampling_steps + """Total number of sampling steps planned""" + + +class UiTrainTabParams: + def __init__(self, txt2img_preview_params): + self.txt2img_preview_params = txt2img_preview_params + + +class ImageGridLoopParams: + def __init__(self, imgs, cols, rows): + self.imgs = imgs + self.cols = cols + self.rows = rows + + +@dataclasses.dataclass +class BeforeTokenCounterParams: + prompt: str + steps: int + styles: list + + is_positive: bool = True + + +@dataclasses.dataclass +class ScriptCallback: + script: str + callback: any + name: str = "unnamed" + + +def add_callback(callbacks, fun, *, name=None, category='unknown', filename=None): + if filename is None: + stack = [x for x in inspect.stack() if x.filename != __file__] + filename = stack[0].filename if stack else 'unknown file' + + extension = extensions.find_extension(filename) + extension_name = extension.canonical_name if extension else 'base' + + callback_name = f"{extension_name}/{os.path.basename(filename)}/{category}" + if name is not None: + callback_name += f'/{name}' + + unique_callback_name = callback_name + for index in range(1000): + existing = any(x.name == unique_callback_name for x in callbacks) + if not existing: + break + + unique_callback_name = f'{callback_name}-{index+1}' + + callbacks.append(ScriptCallback(filename, fun, unique_callback_name)) + + +def sort_callbacks(category, unordered_callbacks, *, enable_user_sort=True): + callbacks = unordered_callbacks.copy() + callback_lookup = {x.name: x for x in callbacks} + dependencies = {} + + order_instructions = {} + for extension in extensions.extensions: + for order_instruction in extension.metadata.list_callback_order_instructions(): + if order_instruction.name in callback_lookup: + if order_instruction.name not in order_instructions: + order_instructions[order_instruction.name] = [] + + order_instructions[order_instruction.name].append(order_instruction) + + if order_instructions: + for callback in callbacks: + dependencies[callback.name] = [] + + for callback in callbacks: + for order_instruction in order_instructions.get(callback.name, []): + for after in order_instruction.after: + if after not in callback_lookup: + continue + + dependencies[callback.name].append(after) + + for before in order_instruction.before: + if before not in callback_lookup: + continue + + dependencies[before].append(callback.name) + + sorted_names = util.topological_sort(dependencies) + callbacks = [callback_lookup[x] for x in sorted_names] + + if enable_user_sort: + for name in reversed(getattr(shared.opts, 'prioritized_callbacks_' + category, [])): + index = next((i for i, callback in enumerate(callbacks) if callback.name == name), None) + if index is not None: + callbacks.insert(0, callbacks.pop(index)) + + return callbacks + + +def ordered_callbacks(category, unordered_callbacks=None, *, enable_user_sort=True): + if unordered_callbacks is None: + unordered_callbacks = callback_map.get('callbacks_' + category, []) + + if not enable_user_sort: + return sort_callbacks(category, unordered_callbacks, enable_user_sort=False) + + callbacks = ordered_callbacks_map.get(category) + if callbacks is not None and len(callbacks) == len(unordered_callbacks): + return callbacks + + callbacks = sort_callbacks(category, unordered_callbacks) + + ordered_callbacks_map[category] = callbacks + return callbacks + + +def enumerate_callbacks(): + for category, callbacks in callback_map.items(): + if category.startswith('callbacks_'): + category = category[10:] + + yield category, callbacks + + +callback_map = dict( + callbacks_app_started=[], + callbacks_model_loaded=[], + callbacks_ui_tabs=[], + callbacks_ui_train_tabs=[], + callbacks_ui_settings=[], + callbacks_before_image_saved=[], + callbacks_image_saved=[], + callbacks_extra_noise=[], + callbacks_cfg_denoiser=[], + callbacks_cfg_denoised=[], + callbacks_cfg_after_cfg=[], + callbacks_before_component=[], + callbacks_after_component=[], + callbacks_image_grid=[], + callbacks_infotext_pasted=[], + callbacks_script_unloaded=[], + callbacks_before_ui=[], + callbacks_on_reload=[], + callbacks_list_optimizers=[], + callbacks_list_unets=[], + callbacks_before_token_counter=[], +) + +ordered_callbacks_map = {} + + +def clear_callbacks(): + for callback_list in callback_map.values(): + callback_list.clear() + + ordered_callbacks_map.clear() + + +def app_started_callback(demo: Optional[Blocks], app: FastAPI): + for c in ordered_callbacks('app_started'): + try: + c.callback(demo, app) + timer.startup_timer.record(os.path.basename(c.script)) + except Exception: + report_exception(c, 'app_started_callback') + + +def app_reload_callback(): + for c in ordered_callbacks('on_reload'): + try: + c.callback() + except Exception: + report_exception(c, 'callbacks_on_reload') + + +def model_loaded_callback(sd_model): + for c in ordered_callbacks('model_loaded'): + try: + c.callback(sd_model) + except Exception: + report_exception(c, 'model_loaded_callback') + + +def ui_tabs_callback(): + res = [] + + for c in ordered_callbacks('ui_tabs'): + try: + res += c.callback() or [] + except Exception: + report_exception(c, 'ui_tabs_callback') + + return res + + +def ui_train_tabs_callback(params: UiTrainTabParams): + for c in ordered_callbacks('ui_train_tabs'): + try: + c.callback(params) + except Exception: + report_exception(c, 'callbacks_ui_train_tabs') + + +def ui_settings_callback(): + for c in ordered_callbacks('ui_settings'): + try: + c.callback() + except Exception: + report_exception(c, 'ui_settings_callback') + + +def before_image_saved_callback(params: ImageSaveParams): + for c in ordered_callbacks('before_image_saved'): + try: + c.callback(params) + except Exception: + report_exception(c, 'before_image_saved_callback') + + +def image_saved_callback(params: ImageSaveParams): + for c in ordered_callbacks('image_saved'): + try: + c.callback(params) + except Exception: + report_exception(c, 'image_saved_callback') + + +def extra_noise_callback(params: ExtraNoiseParams): + for c in ordered_callbacks('extra_noise'): + try: + c.callback(params) + except Exception: + report_exception(c, 'callbacks_extra_noise') + + +def cfg_denoiser_callback(params: CFGDenoiserParams): + for c in ordered_callbacks('cfg_denoiser'): + try: + c.callback(params) + except Exception: + report_exception(c, 'cfg_denoiser_callback') + + +def cfg_denoised_callback(params: CFGDenoisedParams): + for c in ordered_callbacks('cfg_denoised'): + try: + c.callback(params) + except Exception: + report_exception(c, 'cfg_denoised_callback') + + +def cfg_after_cfg_callback(params: AfterCFGCallbackParams): + for c in ordered_callbacks('cfg_after_cfg'): + try: + c.callback(params) + except Exception: + report_exception(c, 'cfg_after_cfg_callback') + + +def before_component_callback(component, **kwargs): + for c in ordered_callbacks('before_component'): + try: + c.callback(component, **kwargs) + except Exception: + report_exception(c, 'before_component_callback') + + +def after_component_callback(component, **kwargs): + for c in ordered_callbacks('after_component'): + try: + c.callback(component, **kwargs) + except Exception: + report_exception(c, 'after_component_callback') + + +def image_grid_callback(params: ImageGridLoopParams): + for c in ordered_callbacks('image_grid'): + try: + c.callback(params) + except Exception: + report_exception(c, 'image_grid') + + +def infotext_pasted_callback(infotext: str, params: dict[str, Any]): + for c in ordered_callbacks('infotext_pasted'): + try: + c.callback(infotext, params) + except Exception: + report_exception(c, 'infotext_pasted') + + +def script_unloaded_callback(): + for c in reversed(ordered_callbacks('script_unloaded')): + try: + c.callback() + except Exception: + report_exception(c, 'script_unloaded') + + +def before_ui_callback(): + for c in reversed(ordered_callbacks('before_ui')): + try: + c.callback() + except Exception: + report_exception(c, 'before_ui') + + +def list_optimizers_callback(): + res = [] + + for c in ordered_callbacks('list_optimizers'): + try: + c.callback(res) + except Exception: + report_exception(c, 'list_optimizers') + + return res + + +def list_unets_callback(): + res = [] + + for c in ordered_callbacks('list_unets'): + try: + c.callback(res) + except Exception: + report_exception(c, 'list_unets') + + return res + + +def before_token_counter_callback(params: BeforeTokenCounterParams): + for c in ordered_callbacks('before_token_counter'): + try: + c.callback(params) + except Exception: + report_exception(c, 'before_token_counter') + + +def remove_current_script_callbacks(): + stack = [x for x in inspect.stack() if x.filename != __file__] + filename = stack[0].filename if stack else 'unknown file' + if filename == 'unknown file': + return + for callback_list in callback_map.values(): + for callback_to_remove in [cb for cb in callback_list if cb.script == filename]: + callback_list.remove(callback_to_remove) + for ordered_callbacks_list in ordered_callbacks_map.values(): + for callback_to_remove in [cb for cb in ordered_callbacks_list if cb.script == filename]: + ordered_callbacks_list.remove(callback_to_remove) + + +def remove_callbacks_for_function(callback_func): + for callback_list in callback_map.values(): + for callback_to_remove in [cb for cb in callback_list if cb.callback == callback_func]: + callback_list.remove(callback_to_remove) + for ordered_callback_list in ordered_callbacks_map.values(): + for callback_to_remove in [cb for cb in ordered_callback_list if cb.callback == callback_func]: + ordered_callback_list.remove(callback_to_remove) + + +def on_app_started(callback, *, name=None): + """register a function to be called when the webui started, the gradio `Block` component and + fastapi `FastAPI` object are passed as the arguments""" + add_callback(callback_map['callbacks_app_started'], callback, name=name, category='app_started') + + +def on_before_reload(callback, *, name=None): + """register a function to be called just before the server reloads.""" + add_callback(callback_map['callbacks_on_reload'], callback, name=name, category='on_reload') + + +def on_model_loaded(callback, *, name=None): + """register a function to be called when the stable diffusion model is created; the model is + passed as an argument; this function is also called when the script is reloaded. """ + add_callback(callback_map['callbacks_model_loaded'], callback, name=name, category='model_loaded') + + +def on_ui_tabs(callback, *, name=None): + """register a function to be called when the UI is creating new tabs. + The function must either return a None, which means no new tabs to be added, or a list, where + each element is a tuple: + (gradio_component, title, elem_id) + + gradio_component is a gradio component to be used for contents of the tab (usually gr.Blocks) + title is tab text displayed to user in the UI + elem_id is HTML id for the tab + """ + add_callback(callback_map['callbacks_ui_tabs'], callback, name=name, category='ui_tabs') + + +def on_ui_train_tabs(callback, *, name=None): + """register a function to be called when the UI is creating new tabs for the train tab. + Create your new tabs with gr.Tab. + """ + add_callback(callback_map['callbacks_ui_train_tabs'], callback, name=name, category='ui_train_tabs') + + +def on_ui_settings(callback, *, name=None): + """register a function to be called before UI settings are populated; add your settings + by using shared.opts.add_option(shared.OptionInfo(...)) """ + add_callback(callback_map['callbacks_ui_settings'], callback, name=name, category='ui_settings') + + +def on_before_image_saved(callback, *, name=None): + """register a function to be called before an image is saved to a file. + The callback is called with one argument: + - params: ImageSaveParams - parameters the image is to be saved with. You can change fields in this object. + """ + add_callback(callback_map['callbacks_before_image_saved'], callback, name=name, category='before_image_saved') + + +def on_image_saved(callback, *, name=None): + """register a function to be called after an image is saved to a file. + The callback is called with one argument: + - params: ImageSaveParams - parameters the image was saved with. Changing fields in this object does nothing. + """ + add_callback(callback_map['callbacks_image_saved'], callback, name=name, category='image_saved') + + +def on_extra_noise(callback, *, name=None): + """register a function to be called before adding extra noise in img2img or hires fix; + The callback is called with one argument: + - params: ExtraNoiseParams - contains noise determined by seed and latent representation of image + """ + add_callback(callback_map['callbacks_extra_noise'], callback, name=name, category='extra_noise') + + +def on_cfg_denoiser(callback, *, name=None): + """register a function to be called in the kdiffussion cfg_denoiser method after building the inner model inputs. + The callback is called with one argument: + - params: CFGDenoiserParams - parameters to be passed to the inner model and sampling state details. + """ + add_callback(callback_map['callbacks_cfg_denoiser'], callback, name=name, category='cfg_denoiser') + + +def on_cfg_denoised(callback, *, name=None): + """register a function to be called in the kdiffussion cfg_denoiser method after building the inner model inputs. + The callback is called with one argument: + - params: CFGDenoisedParams - parameters to be passed to the inner model and sampling state details. + """ + add_callback(callback_map['callbacks_cfg_denoised'], callback, name=name, category='cfg_denoised') + + +def on_cfg_after_cfg(callback, *, name=None): + """register a function to be called in the kdiffussion cfg_denoiser method after cfg calculations are completed. + The callback is called with one argument: + - params: AfterCFGCallbackParams - parameters to be passed to the script for post-processing after cfg calculation. + """ + add_callback(callback_map['callbacks_cfg_after_cfg'], callback, name=name, category='cfg_after_cfg') + + +def on_before_component(callback, *, name=None): + """register a function to be called before a component is created. + The callback is called with arguments: + - component - gradio component that is about to be created. + - **kwargs - args to gradio.components.IOComponent.__init__ function + + Use elem_id/label fields of kwargs to figure out which component it is. + This can be useful to inject your own components somewhere in the middle of vanilla UI. + """ + add_callback(callback_map['callbacks_before_component'], callback, name=name, category='before_component') + + +def on_after_component(callback, *, name=None): + """register a function to be called after a component is created. See on_before_component for more.""" + add_callback(callback_map['callbacks_after_component'], callback, name=name, category='after_component') + + +def on_image_grid(callback, *, name=None): + """register a function to be called before making an image grid. + The callback is called with one argument: + - params: ImageGridLoopParams - parameters to be used for grid creation. Can be modified. + """ + add_callback(callback_map['callbacks_image_grid'], callback, name=name, category='image_grid') + + +def on_infotext_pasted(callback, *, name=None): + """register a function to be called before applying an infotext. + The callback is called with two arguments: + - infotext: str - raw infotext. + - result: dict[str, any] - parsed infotext parameters. + """ + add_callback(callback_map['callbacks_infotext_pasted'], callback, name=name, category='infotext_pasted') + + +def on_script_unloaded(callback, *, name=None): + """register a function to be called before the script is unloaded. Any hooks/hijacks/monkeying about that + the script did should be reverted here""" + + add_callback(callback_map['callbacks_script_unloaded'], callback, name=name, category='script_unloaded') + + +def on_before_ui(callback, *, name=None): + """register a function to be called before the UI is created.""" + + add_callback(callback_map['callbacks_before_ui'], callback, name=name, category='before_ui') + + +def on_list_optimizers(callback, *, name=None): + """register a function to be called when UI is making a list of cross attention optimization options. + The function will be called with one argument, a list, and shall add objects of type modules.sd_hijack_optimizations.SdOptimization + to it.""" + + add_callback(callback_map['callbacks_list_optimizers'], callback, name=name, category='list_optimizers') + + +def on_list_unets(callback, *, name=None): + """register a function to be called when UI is making a list of alternative options for unet. + The function will be called with one argument, a list, and shall add objects of type modules.sd_unet.SdUnetOption to it.""" + + add_callback(callback_map['callbacks_list_unets'], callback, name=name, category='list_unets') + + +def on_before_token_counter(callback, *, name=None): + """register a function to be called when UI is counting tokens for a prompt. + The function will be called with one argument of type BeforeTokenCounterParams, and should modify its fields if necessary.""" + + add_callback(callback_map['callbacks_before_token_counter'], callback, name=name, category='before_token_counter')
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/script_callbacks.py
Help me write clear docstrings
from __future__ import annotations import json import logging import math import os import sys import hashlib from dataclasses import dataclass, field import torch import numpy as np from PIL import Image, ImageOps import random import cv2 from skimage import exposure from typing import Any import modules.sd_hijack from modules import devices, prompt_parser, masking, sd_samplers, lowvram, infotext_utils, extra_networks, sd_vae_approx, scripts, sd_samplers_common, sd_unet, errors, rng, profiling from modules.rng import slerp # noqa: F401 from modules.sd_hijack import model_hijack from modules.sd_samplers_common import images_tensor_to_samples, decode_first_stage, approximation_indexes from modules.shared import opts, cmd_opts, state import modules.shared as shared import modules.paths as paths import modules.face_restoration import modules.images as images import modules.styles import modules.sd_models as sd_models import modules.sd_vae as sd_vae from ldm.data.util import AddMiDaS from ldm.models.diffusion.ddpm import LatentDepth2ImageDiffusion from einops import repeat, rearrange from blendmodes.blend import blendLayers, BlendType # some of those options should not be changed at all because they would break the model, so I removed them from options. opt_C = 4 opt_f = 8 def setup_color_correction(image): logging.info("Calibrating color correction.") correction_target = cv2.cvtColor(np.asarray(image.copy()), cv2.COLOR_RGB2LAB) return correction_target def apply_color_correction(correction, original_image): logging.info("Applying color correction.") image = Image.fromarray(cv2.cvtColor(exposure.match_histograms( cv2.cvtColor( np.asarray(original_image), cv2.COLOR_RGB2LAB ), correction, channel_axis=2 ), cv2.COLOR_LAB2RGB).astype("uint8")) image = blendLayers(image, original_image, BlendType.LUMINOSITY) return image.convert('RGB') def uncrop(image, dest_size, paste_loc): x, y, w, h = paste_loc base_image = Image.new('RGBA', dest_size) image = images.resize_image(1, image, w, h) base_image.paste(image, (x, y)) image = base_image return image def apply_overlay(image, paste_loc, overlay): if overlay is None: return image, image.copy() if paste_loc is not None: image = uncrop(image, (overlay.width, overlay.height), paste_loc) original_denoised_image = image.copy() image = image.convert('RGBA') image.alpha_composite(overlay) image = image.convert('RGB') return image, original_denoised_image def create_binary_mask(image, round=True): if image.mode == 'RGBA' and image.getextrema()[-1] != (255, 255): if round: image = image.split()[-1].convert("L").point(lambda x: 255 if x > 128 else 0) else: image = image.split()[-1].convert("L") else: image = image.convert('L') return image def txt2img_image_conditioning(sd_model, x, width, height): if sd_model.model.conditioning_key in {'hybrid', 'concat'}: # Inpainting models # The "masked-image" in this case will just be all 0.5 since the entire image is masked. image_conditioning = torch.ones(x.shape[0], 3, height, width, device=x.device) * 0.5 image_conditioning = images_tensor_to_samples(image_conditioning, approximation_indexes.get(opts.sd_vae_encode_method)) # Add the fake full 1s mask to the first dimension. image_conditioning = torch.nn.functional.pad(image_conditioning, (0, 0, 0, 0, 1, 0), value=1.0) image_conditioning = image_conditioning.to(x.dtype) return image_conditioning elif sd_model.model.conditioning_key == "crossattn-adm": # UnCLIP models return x.new_zeros(x.shape[0], 2*sd_model.noise_augmentor.time_embed.dim, dtype=x.dtype, device=x.device) else: if sd_model.is_sdxl_inpaint: # The "masked-image" in this case will just be all 0.5 since the entire image is masked. image_conditioning = torch.ones(x.shape[0], 3, height, width, device=x.device) * 0.5 image_conditioning = images_tensor_to_samples(image_conditioning, approximation_indexes.get(opts.sd_vae_encode_method)) # Add the fake full 1s mask to the first dimension. image_conditioning = torch.nn.functional.pad(image_conditioning, (0, 0, 0, 0, 1, 0), value=1.0) image_conditioning = image_conditioning.to(x.dtype) return image_conditioning # Dummy zero conditioning if we're not using inpainting or unclip models. # Still takes up a bit of memory, but no encoder call. # Pretty sure we can just make this a 1x1 image since its not going to be used besides its batch size. return x.new_zeros(x.shape[0], 5, 1, 1, dtype=x.dtype, device=x.device) @dataclass(repr=False) class StableDiffusionProcessing: sd_model: object = None outpath_samples: str = None outpath_grids: str = None prompt: str = "" prompt_for_display: str = None negative_prompt: str = "" styles: list[str] = None seed: int = -1 subseed: int = -1 subseed_strength: float = 0 seed_resize_from_h: int = -1 seed_resize_from_w: int = -1 seed_enable_extras: bool = True sampler_name: str = None scheduler: str = None batch_size: int = 1 n_iter: int = 1 steps: int = 50 cfg_scale: float = 7.0 width: int = 512 height: int = 512 restore_faces: bool = None tiling: bool = None do_not_save_samples: bool = False do_not_save_grid: bool = False extra_generation_params: dict[str, Any] = None overlay_images: list = None eta: float = None do_not_reload_embeddings: bool = False denoising_strength: float = None ddim_discretize: str = None s_min_uncond: float = None s_churn: float = None s_tmax: float = None s_tmin: float = None s_noise: float = None override_settings: dict[str, Any] = None override_settings_restore_afterwards: bool = True sampler_index: int = None refiner_checkpoint: str = None refiner_switch_at: float = None token_merging_ratio = 0 token_merging_ratio_hr = 0 disable_extra_networks: bool = False firstpass_image: Image = None scripts_value: scripts.ScriptRunner = field(default=None, init=False) script_args_value: list = field(default=None, init=False) scripts_setup_complete: bool = field(default=False, init=False) cached_uc = [None, None] cached_c = [None, None] comments: dict = None sampler: sd_samplers_common.Sampler | None = field(default=None, init=False) is_using_inpainting_conditioning: bool = field(default=False, init=False) paste_to: tuple | None = field(default=None, init=False) is_hr_pass: bool = field(default=False, init=False) c: tuple = field(default=None, init=False) uc: tuple = field(default=None, init=False) rng: rng.ImageRNG | None = field(default=None, init=False) step_multiplier: int = field(default=1, init=False) color_corrections: list = field(default=None, init=False) all_prompts: list = field(default=None, init=False) all_negative_prompts: list = field(default=None, init=False) all_seeds: list = field(default=None, init=False) all_subseeds: list = field(default=None, init=False) iteration: int = field(default=0, init=False) main_prompt: str = field(default=None, init=False) main_negative_prompt: str = field(default=None, init=False) prompts: list = field(default=None, init=False) negative_prompts: list = field(default=None, init=False) seeds: list = field(default=None, init=False) subseeds: list = field(default=None, init=False) extra_network_data: dict = field(default=None, init=False) user: str = field(default=None, init=False) sd_model_name: str = field(default=None, init=False) sd_model_hash: str = field(default=None, init=False) sd_vae_name: str = field(default=None, init=False) sd_vae_hash: str = field(default=None, init=False) is_api: bool = field(default=False, init=False) def __post_init__(self): if self.sampler_index is not None: print("sampler_index argument for StableDiffusionProcessing does not do anything; use sampler_name", file=sys.stderr) self.comments = {} if self.styles is None: self.styles = [] self.sampler_noise_scheduler_override = None self.extra_generation_params = self.extra_generation_params or {} self.override_settings = self.override_settings or {} self.script_args = self.script_args or {} self.refiner_checkpoint_info = None if not self.seed_enable_extras: self.subseed = -1 self.subseed_strength = 0 self.seed_resize_from_h = 0 self.seed_resize_from_w = 0 self.cached_uc = StableDiffusionProcessing.cached_uc self.cached_c = StableDiffusionProcessing.cached_c def fill_fields_from_opts(self): self.s_min_uncond = self.s_min_uncond if self.s_min_uncond is not None else opts.s_min_uncond self.s_churn = self.s_churn if self.s_churn is not None else opts.s_churn self.s_tmin = self.s_tmin if self.s_tmin is not None else opts.s_tmin self.s_tmax = (self.s_tmax if self.s_tmax is not None else opts.s_tmax) or float('inf') self.s_noise = self.s_noise if self.s_noise is not None else opts.s_noise @property def sd_model(self): return shared.sd_model @sd_model.setter def sd_model(self, value): pass @property def scripts(self): return self.scripts_value @scripts.setter def scripts(self, value): self.scripts_value = value if self.scripts_value and self.script_args_value and not self.scripts_setup_complete: self.setup_scripts() @property def script_args(self): return self.script_args_value @script_args.setter def script_args(self, value): self.script_args_value = value if self.scripts_value and self.script_args_value and not self.scripts_setup_complete: self.setup_scripts() def setup_scripts(self): self.scripts_setup_complete = True self.scripts.setup_scrips(self, is_ui=not self.is_api) def comment(self, text): self.comments[text] = 1 def txt2img_image_conditioning(self, x, width=None, height=None): self.is_using_inpainting_conditioning = self.sd_model.model.conditioning_key in {'hybrid', 'concat'} return txt2img_image_conditioning(self.sd_model, x, width or self.width, height or self.height) def depth2img_image_conditioning(self, source_image): # Use the AddMiDaS helper to Format our source image to suit the MiDaS model transformer = AddMiDaS(model_type="dpt_hybrid") transformed = transformer({"jpg": rearrange(source_image[0], "c h w -> h w c")}) midas_in = torch.from_numpy(transformed["midas_in"][None, ...]).to(device=shared.device) midas_in = repeat(midas_in, "1 ... -> n ...", n=self.batch_size) conditioning_image = images_tensor_to_samples(source_image*0.5+0.5, approximation_indexes.get(opts.sd_vae_encode_method)) conditioning = torch.nn.functional.interpolate( self.sd_model.depth_model(midas_in), size=conditioning_image.shape[2:], mode="bicubic", align_corners=False, ) (depth_min, depth_max) = torch.aminmax(conditioning) conditioning = 2. * (conditioning - depth_min) / (depth_max - depth_min) - 1. return conditioning def edit_image_conditioning(self, source_image): conditioning_image = shared.sd_model.encode_first_stage(source_image).mode() return conditioning_image def unclip_image_conditioning(self, source_image): c_adm = self.sd_model.embedder(source_image) if self.sd_model.noise_augmentor is not None: noise_level = 0 # TODO: Allow other noise levels? c_adm, noise_level_emb = self.sd_model.noise_augmentor(c_adm, noise_level=repeat(torch.tensor([noise_level]).to(c_adm.device), '1 -> b', b=c_adm.shape[0])) c_adm = torch.cat((c_adm, noise_level_emb), 1) return c_adm def inpainting_image_conditioning(self, source_image, latent_image, image_mask=None, round_image_mask=True): self.is_using_inpainting_conditioning = True # Handle the different mask inputs if image_mask is not None: if torch.is_tensor(image_mask): conditioning_mask = image_mask else: conditioning_mask = np.array(image_mask.convert("L")) conditioning_mask = conditioning_mask.astype(np.float32) / 255.0 conditioning_mask = torch.from_numpy(conditioning_mask[None, None]) if round_image_mask: # Caller is requesting a discretized mask as input, so we round to either 1.0 or 0.0 conditioning_mask = torch.round(conditioning_mask) else: conditioning_mask = source_image.new_ones(1, 1, *source_image.shape[-2:]) # Create another latent image, this time with a masked version of the original input. # Smoothly interpolate between the masked and unmasked latent conditioning image using a parameter. conditioning_mask = conditioning_mask.to(device=source_image.device, dtype=source_image.dtype) conditioning_image = torch.lerp( source_image, source_image * (1.0 - conditioning_mask), getattr(self, "inpainting_mask_weight", shared.opts.inpainting_mask_weight) ) # Encode the new masked image using first stage of network. conditioning_image = self.sd_model.get_first_stage_encoding(self.sd_model.encode_first_stage(conditioning_image)) # Create the concatenated conditioning tensor to be fed to `c_concat` conditioning_mask = torch.nn.functional.interpolate(conditioning_mask, size=latent_image.shape[-2:]) conditioning_mask = conditioning_mask.expand(conditioning_image.shape[0], -1, -1, -1) image_conditioning = torch.cat([conditioning_mask, conditioning_image], dim=1) image_conditioning = image_conditioning.to(shared.device).type(self.sd_model.dtype) return image_conditioning def img2img_image_conditioning(self, source_image, latent_image, image_mask=None, round_image_mask=True): source_image = devices.cond_cast_float(source_image) # HACK: Using introspection as the Depth2Image model doesn't appear to uniquely # identify itself with a field common to all models. The conditioning_key is also hybrid. if isinstance(self.sd_model, LatentDepth2ImageDiffusion): return self.depth2img_image_conditioning(source_image) if self.sd_model.cond_stage_key == "edit": return self.edit_image_conditioning(source_image) if self.sampler.conditioning_key in {'hybrid', 'concat'}: return self.inpainting_image_conditioning(source_image, latent_image, image_mask=image_mask, round_image_mask=round_image_mask) if self.sampler.conditioning_key == "crossattn-adm": return self.unclip_image_conditioning(source_image) if self.sampler.model_wrap.inner_model.is_sdxl_inpaint: return self.inpainting_image_conditioning(source_image, latent_image, image_mask=image_mask) # Dummy zero conditioning if we're not using inpainting or depth model. return latent_image.new_zeros(latent_image.shape[0], 5, 1, 1) def init(self, all_prompts, all_seeds, all_subseeds): pass def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts): raise NotImplementedError() def close(self): self.sampler = None self.c = None self.uc = None if not opts.persistent_cond_cache: StableDiffusionProcessing.cached_c = [None, None] StableDiffusionProcessing.cached_uc = [None, None] def get_token_merging_ratio(self, for_hr=False): if for_hr: return self.token_merging_ratio_hr or opts.token_merging_ratio_hr or self.token_merging_ratio or opts.token_merging_ratio return self.token_merging_ratio or opts.token_merging_ratio def setup_prompts(self): if isinstance(self.prompt,list): self.all_prompts = self.prompt elif isinstance(self.negative_prompt, list): self.all_prompts = [self.prompt] * len(self.negative_prompt) else: self.all_prompts = self.batch_size * self.n_iter * [self.prompt] if isinstance(self.negative_prompt, list): self.all_negative_prompts = self.negative_prompt else: self.all_negative_prompts = [self.negative_prompt] * len(self.all_prompts) if len(self.all_prompts) != len(self.all_negative_prompts): raise RuntimeError(f"Received a different number of prompts ({len(self.all_prompts)}) and negative prompts ({len(self.all_negative_prompts)})") self.all_prompts = [shared.prompt_styles.apply_styles_to_prompt(x, self.styles) for x in self.all_prompts] self.all_negative_prompts = [shared.prompt_styles.apply_negative_styles_to_prompt(x, self.styles) for x in self.all_negative_prompts] self.main_prompt = self.all_prompts[0] self.main_negative_prompt = self.all_negative_prompts[0] def cached_params(self, required_prompts, steps, extra_network_data, hires_steps=None, use_old_scheduling=False): return ( required_prompts, steps, hires_steps, use_old_scheduling, opts.CLIP_stop_at_last_layers, shared.sd_model.sd_checkpoint_info, extra_network_data, opts.sdxl_crop_left, opts.sdxl_crop_top, self.width, self.height, opts.fp8_storage, opts.cache_fp16_weight, opts.emphasis, ) def get_conds_with_caching(self, function, required_prompts, steps, caches, extra_network_data, hires_steps=None): if shared.opts.use_old_scheduling: old_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(required_prompts, steps, hires_steps, False) new_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(required_prompts, steps, hires_steps, True) if old_schedules != new_schedules: self.extra_generation_params["Old prompt editing timelines"] = True cached_params = self.cached_params(required_prompts, steps, extra_network_data, hires_steps, shared.opts.use_old_scheduling) for cache in caches: if cache[0] is not None and cached_params == cache[0]: return cache[1] cache = caches[0] with devices.autocast(): cache[1] = function(shared.sd_model, required_prompts, steps, hires_steps, shared.opts.use_old_scheduling) cache[0] = cached_params return cache[1] def setup_conds(self): prompts = prompt_parser.SdConditioning(self.prompts, width=self.width, height=self.height) negative_prompts = prompt_parser.SdConditioning(self.negative_prompts, width=self.width, height=self.height, is_negative_prompt=True) sampler_config = sd_samplers.find_sampler_config(self.sampler_name) total_steps = sampler_config.total_steps(self.steps) if sampler_config else self.steps self.step_multiplier = total_steps // self.steps self.firstpass_steps = total_steps self.uc = self.get_conds_with_caching(prompt_parser.get_learned_conditioning, negative_prompts, total_steps, [self.cached_uc], self.extra_network_data) self.c = self.get_conds_with_caching(prompt_parser.get_multicond_learned_conditioning, prompts, total_steps, [self.cached_c], self.extra_network_data) def get_conds(self): return self.c, self.uc def parse_extra_network_prompts(self): self.prompts, self.extra_network_data = extra_networks.parse_prompts(self.prompts) def save_samples(self) -> bool: return opts.samples_save and not self.do_not_save_samples and (opts.save_incomplete_images or not state.interrupted and not state.skipped) class Processed: def __init__(self, p: StableDiffusionProcessing, images_list, seed=-1, info="", subseed=None, all_prompts=None, all_negative_prompts=None, all_seeds=None, all_subseeds=None, index_of_first_image=0, infotexts=None, comments=""): self.images = images_list self.prompt = p.prompt self.negative_prompt = p.negative_prompt self.seed = seed self.subseed = subseed self.subseed_strength = p.subseed_strength self.info = info self.comments = "".join(f"{comment}\n" for comment in p.comments) self.width = p.width self.height = p.height self.sampler_name = p.sampler_name self.cfg_scale = p.cfg_scale self.image_cfg_scale = getattr(p, 'image_cfg_scale', None) self.steps = p.steps self.batch_size = p.batch_size self.restore_faces = p.restore_faces self.face_restoration_model = opts.face_restoration_model if p.restore_faces else None self.sd_model_name = p.sd_model_name self.sd_model_hash = p.sd_model_hash self.sd_vae_name = p.sd_vae_name self.sd_vae_hash = p.sd_vae_hash self.seed_resize_from_w = p.seed_resize_from_w self.seed_resize_from_h = p.seed_resize_from_h self.denoising_strength = getattr(p, 'denoising_strength', None) self.extra_generation_params = p.extra_generation_params self.index_of_first_image = index_of_first_image self.styles = p.styles self.job_timestamp = state.job_timestamp self.clip_skip = opts.CLIP_stop_at_last_layers self.token_merging_ratio = p.token_merging_ratio self.token_merging_ratio_hr = p.token_merging_ratio_hr self.eta = p.eta self.ddim_discretize = p.ddim_discretize self.s_churn = p.s_churn self.s_tmin = p.s_tmin self.s_tmax = p.s_tmax self.s_noise = p.s_noise self.s_min_uncond = p.s_min_uncond self.sampler_noise_scheduler_override = p.sampler_noise_scheduler_override self.prompt = self.prompt if not isinstance(self.prompt, list) else self.prompt[0] self.negative_prompt = self.negative_prompt if not isinstance(self.negative_prompt, list) else self.negative_prompt[0] self.seed = int(self.seed if not isinstance(self.seed, list) else self.seed[0]) if self.seed is not None else -1 self.subseed = int(self.subseed if not isinstance(self.subseed, list) else self.subseed[0]) if self.subseed is not None else -1 self.is_using_inpainting_conditioning = p.is_using_inpainting_conditioning self.all_prompts = all_prompts or p.all_prompts or [self.prompt] self.all_negative_prompts = all_negative_prompts or p.all_negative_prompts or [self.negative_prompt] self.all_seeds = all_seeds or p.all_seeds or [self.seed] self.all_subseeds = all_subseeds or p.all_subseeds or [self.subseed] self.infotexts = infotexts or [info] * len(images_list) self.version = program_version() def js(self): obj = { "prompt": self.all_prompts[0], "all_prompts": self.all_prompts, "negative_prompt": self.all_negative_prompts[0], "all_negative_prompts": self.all_negative_prompts, "seed": self.seed, "all_seeds": self.all_seeds, "subseed": self.subseed, "all_subseeds": self.all_subseeds, "subseed_strength": self.subseed_strength, "width": self.width, "height": self.height, "sampler_name": self.sampler_name, "cfg_scale": self.cfg_scale, "steps": self.steps, "batch_size": self.batch_size, "restore_faces": self.restore_faces, "face_restoration_model": self.face_restoration_model, "sd_model_name": self.sd_model_name, "sd_model_hash": self.sd_model_hash, "sd_vae_name": self.sd_vae_name, "sd_vae_hash": self.sd_vae_hash, "seed_resize_from_w": self.seed_resize_from_w, "seed_resize_from_h": self.seed_resize_from_h, "denoising_strength": self.denoising_strength, "extra_generation_params": self.extra_generation_params, "index_of_first_image": self.index_of_first_image, "infotexts": self.infotexts, "styles": self.styles, "job_timestamp": self.job_timestamp, "clip_skip": self.clip_skip, "is_using_inpainting_conditioning": self.is_using_inpainting_conditioning, "version": self.version, } return json.dumps(obj, default=lambda o: None) def infotext(self, p: StableDiffusionProcessing, index): return create_infotext(p, self.all_prompts, self.all_seeds, self.all_subseeds, comments=[], position_in_batch=index % self.batch_size, iteration=index // self.batch_size) def get_token_merging_ratio(self, for_hr=False): return self.token_merging_ratio_hr if for_hr else self.token_merging_ratio def create_random_tensors(shape, seeds, subseeds=None, subseed_strength=0.0, seed_resize_from_h=0, seed_resize_from_w=0, p=None): g = rng.ImageRNG(shape, seeds, subseeds=subseeds, subseed_strength=subseed_strength, seed_resize_from_h=seed_resize_from_h, seed_resize_from_w=seed_resize_from_w) return g.next() class DecodedSamples(list): already_decoded = True def decode_latent_batch(model, batch, target_device=None, check_for_nans=False): samples = DecodedSamples() if check_for_nans: devices.test_for_nans(batch, "unet") for i in range(batch.shape[0]): sample = decode_first_stage(model, batch[i:i + 1])[0] if check_for_nans: try: devices.test_for_nans(sample, "vae") except devices.NansException as e: if shared.opts.auto_vae_precision_bfloat16: autofix_dtype = torch.bfloat16 autofix_dtype_text = "bfloat16" autofix_dtype_setting = "Automatically convert VAE to bfloat16" autofix_dtype_comment = "" elif shared.opts.auto_vae_precision: autofix_dtype = torch.float32 autofix_dtype_text = "32-bit float" autofix_dtype_setting = "Automatically revert VAE to 32-bit floats" autofix_dtype_comment = "\nTo always start with 32-bit VAE, use --no-half-vae commandline flag." else: raise e if devices.dtype_vae == autofix_dtype: raise e errors.print_error_explanation( "A tensor with all NaNs was produced in VAE.\n" f"Web UI will now convert VAE into {autofix_dtype_text} and retry.\n" f"To disable this behavior, disable the '{autofix_dtype_setting}' setting.{autofix_dtype_comment}" ) devices.dtype_vae = autofix_dtype model.first_stage_model.to(devices.dtype_vae) batch = batch.to(devices.dtype_vae) sample = decode_first_stage(model, batch[i:i + 1])[0] if target_device is not None: sample = sample.to(target_device) samples.append(sample) return samples def get_fixed_seed(seed): if seed == '' or seed is None: seed = -1 elif isinstance(seed, str): try: seed = int(seed) except Exception: seed = -1 if seed == -1: return int(random.randrange(4294967294)) return seed def fix_seed(p): p.seed = get_fixed_seed(p.seed) p.subseed = get_fixed_seed(p.subseed) def program_version(): import launch res = launch.git_tag() if res == "<none>": res = None return res def create_infotext(p, all_prompts, all_seeds, all_subseeds, comments=None, iteration=0, position_in_batch=0, use_main_prompt=False, index=None, all_negative_prompts=None): if use_main_prompt: index = 0 elif index is None: index = position_in_batch + iteration * p.batch_size if all_negative_prompts is None: all_negative_prompts = p.all_negative_prompts clip_skip = getattr(p, 'clip_skip', opts.CLIP_stop_at_last_layers) enable_hr = getattr(p, 'enable_hr', False) token_merging_ratio = p.get_token_merging_ratio() token_merging_ratio_hr = p.get_token_merging_ratio(for_hr=True) prompt_text = p.main_prompt if use_main_prompt else all_prompts[index] negative_prompt = p.main_negative_prompt if use_main_prompt else all_negative_prompts[index] uses_ensd = opts.eta_noise_seed_delta != 0 if uses_ensd: uses_ensd = sd_samplers_common.is_sampler_using_eta_noise_seed_delta(p) generation_params = { "Steps": p.steps, "Sampler": p.sampler_name, "Schedule type": p.scheduler, "CFG scale": p.cfg_scale, "Image CFG scale": getattr(p, 'image_cfg_scale', None), "Seed": p.all_seeds[0] if use_main_prompt else all_seeds[index], "Face restoration": opts.face_restoration_model if p.restore_faces else None, "Size": f"{p.width}x{p.height}", "Model hash": p.sd_model_hash if opts.add_model_hash_to_info else None, "Model": p.sd_model_name if opts.add_model_name_to_info else None, "FP8 weight": opts.fp8_storage if devices.fp8 else None, "Cache FP16 weight for LoRA": opts.cache_fp16_weight if devices.fp8 else None, "VAE hash": p.sd_vae_hash if opts.add_vae_hash_to_info else None, "VAE": p.sd_vae_name if opts.add_vae_name_to_info else None, "Variation seed": (None if p.subseed_strength == 0 else (p.all_subseeds[0] if use_main_prompt else all_subseeds[index])), "Variation seed strength": (None if p.subseed_strength == 0 else p.subseed_strength), "Seed resize from": (None if p.seed_resize_from_w <= 0 or p.seed_resize_from_h <= 0 else f"{p.seed_resize_from_w}x{p.seed_resize_from_h}"), "Denoising strength": p.extra_generation_params.get("Denoising strength"), "Conditional mask weight": getattr(p, "inpainting_mask_weight", shared.opts.inpainting_mask_weight) if p.is_using_inpainting_conditioning else None, "Clip skip": None if clip_skip <= 1 else clip_skip, "ENSD": opts.eta_noise_seed_delta if uses_ensd else None, "Token merging ratio": None if token_merging_ratio == 0 else token_merging_ratio, "Token merging ratio hr": None if not enable_hr or token_merging_ratio_hr == 0 else token_merging_ratio_hr, "Init image hash": getattr(p, 'init_img_hash', None), "RNG": opts.randn_source if opts.randn_source != "GPU" else None, "Tiling": "True" if p.tiling else None, **p.extra_generation_params, "Version": program_version() if opts.add_version_to_infotext else None, "User": p.user if opts.add_user_name_to_info else None, } for key, value in generation_params.items(): try: if isinstance(value, list): generation_params[key] = value[index] elif callable(value): generation_params[key] = value(**locals()) except Exception: errors.report(f'Error creating infotext for key "{key}"', exc_info=True) generation_params[key] = None generation_params_text = ", ".join([k if k == v else f'{k}: {infotext_utils.quote(v)}' for k, v in generation_params.items() if v is not None]) negative_prompt_text = f"\nNegative prompt: {negative_prompt}" if negative_prompt else "" return f"{prompt_text}{negative_prompt_text}\n{generation_params_text}".strip() def process_images(p: StableDiffusionProcessing) -> Processed: if p.scripts is not None: p.scripts.before_process(p) stored_opts = {k: opts.data[k] if k in opts.data else opts.get_default(k) for k in p.override_settings.keys() if k in opts.data} try: # if no checkpoint override or the override checkpoint can't be found, remove override entry and load opts checkpoint # and if after running refiner, the refiner model is not unloaded - webui swaps back to main model here, if model over is present it will be reloaded afterwards if sd_models.checkpoint_aliases.get(p.override_settings.get('sd_model_checkpoint')) is None: p.override_settings.pop('sd_model_checkpoint', None) sd_models.reload_model_weights() for k, v in p.override_settings.items(): opts.set(k, v, is_api=True, run_callbacks=False) if k == 'sd_model_checkpoint': sd_models.reload_model_weights() if k == 'sd_vae': sd_vae.reload_vae_weights() sd_models.apply_token_merging(p.sd_model, p.get_token_merging_ratio()) # backwards compatibility, fix sampler and scheduler if invalid sd_samplers.fix_p_invalid_sampler_and_scheduler(p) with profiling.Profiler(): res = process_images_inner(p) finally: sd_models.apply_token_merging(p.sd_model, 0) # restore opts to original state if p.override_settings_restore_afterwards: for k, v in stored_opts.items(): setattr(opts, k, v) if k == 'sd_vae': sd_vae.reload_vae_weights() return res def process_images_inner(p: StableDiffusionProcessing) -> Processed: if isinstance(p.prompt, list): assert(len(p.prompt) > 0) else: assert p.prompt is not None devices.torch_gc() seed = get_fixed_seed(p.seed) subseed = get_fixed_seed(p.subseed) if p.restore_faces is None: p.restore_faces = opts.face_restoration if p.tiling is None: p.tiling = opts.tiling if p.refiner_checkpoint not in (None, "", "None", "none"): p.refiner_checkpoint_info = sd_models.get_closet_checkpoint_match(p.refiner_checkpoint) if p.refiner_checkpoint_info is None: raise Exception(f'Could not find checkpoint with name {p.refiner_checkpoint}') if hasattr(shared.sd_model, 'fix_dimensions'): p.width, p.height = shared.sd_model.fix_dimensions(p.width, p.height) p.sd_model_name = shared.sd_model.sd_checkpoint_info.name_for_extra p.sd_model_hash = shared.sd_model.sd_model_hash p.sd_vae_name = sd_vae.get_loaded_vae_name() p.sd_vae_hash = sd_vae.get_loaded_vae_hash() modules.sd_hijack.model_hijack.apply_circular(p.tiling) modules.sd_hijack.model_hijack.clear_comments() p.fill_fields_from_opts() p.setup_prompts() if isinstance(seed, list): p.all_seeds = seed else: p.all_seeds = [int(seed) + (x if p.subseed_strength == 0 else 0) for x in range(len(p.all_prompts))] if isinstance(subseed, list): p.all_subseeds = subseed else: p.all_subseeds = [int(subseed) + x for x in range(len(p.all_prompts))] if os.path.exists(cmd_opts.embeddings_dir) and not p.do_not_reload_embeddings: model_hijack.embedding_db.load_textual_inversion_embeddings() if p.scripts is not None: p.scripts.process(p) infotexts = [] output_images = [] with torch.no_grad(), p.sd_model.ema_scope(): with devices.autocast(): p.init(p.all_prompts, p.all_seeds, p.all_subseeds) # for OSX, loading the model during sampling changes the generated picture, so it is loaded here if shared.opts.live_previews_enable and opts.show_progress_type == "Approx NN": sd_vae_approx.model() sd_unet.apply_unet() if state.job_count == -1: state.job_count = p.n_iter for n in range(p.n_iter): p.iteration = n if state.skipped: state.skipped = False if state.interrupted or state.stopping_generation: break sd_models.reload_model_weights() # model can be changed for example by refiner p.prompts = p.all_prompts[n * p.batch_size:(n + 1) * p.batch_size] p.negative_prompts = p.all_negative_prompts[n * p.batch_size:(n + 1) * p.batch_size] p.seeds = p.all_seeds[n * p.batch_size:(n + 1) * p.batch_size] p.subseeds = p.all_subseeds[n * p.batch_size:(n + 1) * p.batch_size] latent_channels = getattr(shared.sd_model, 'latent_channels', opt_C) p.rng = rng.ImageRNG((latent_channels, p.height // opt_f, p.width // opt_f), p.seeds, subseeds=p.subseeds, subseed_strength=p.subseed_strength, seed_resize_from_h=p.seed_resize_from_h, seed_resize_from_w=p.seed_resize_from_w) if p.scripts is not None: p.scripts.before_process_batch(p, batch_number=n, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds) if len(p.prompts) == 0: break p.parse_extra_network_prompts() if not p.disable_extra_networks: with devices.autocast(): extra_networks.activate(p, p.extra_network_data) if p.scripts is not None: p.scripts.process_batch(p, batch_number=n, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds) p.setup_conds() p.extra_generation_params.update(model_hijack.extra_generation_params) # params.txt should be saved after scripts.process_batch, since the # infotext could be modified by that callback # Example: a wildcard processed by process_batch sets an extra model # strength, which is saved as "Model Strength: 1.0" in the infotext if n == 0 and not cmd_opts.no_prompt_history: with open(os.path.join(paths.data_path, "params.txt"), "w", encoding="utf8") as file: processed = Processed(p, []) file.write(processed.infotext(p, 0)) for comment in model_hijack.comments: p.comment(comment) if p.n_iter > 1: shared.state.job = f"Batch {n+1} out of {p.n_iter}" sd_models.apply_alpha_schedule_override(p.sd_model, p) with devices.without_autocast() if devices.unet_needs_upcast else devices.autocast(): samples_ddim = p.sample(conditioning=p.c, unconditional_conditioning=p.uc, seeds=p.seeds, subseeds=p.subseeds, subseed_strength=p.subseed_strength, prompts=p.prompts) if p.scripts is not None: ps = scripts.PostSampleArgs(samples_ddim) p.scripts.post_sample(p, ps) samples_ddim = ps.samples if getattr(samples_ddim, 'already_decoded', False): x_samples_ddim = samples_ddim else: devices.test_for_nans(samples_ddim, "unet") if opts.sd_vae_decode_method != 'Full': p.extra_generation_params['VAE Decoder'] = opts.sd_vae_decode_method x_samples_ddim = decode_latent_batch(p.sd_model, samples_ddim, target_device=devices.cpu, check_for_nans=True) x_samples_ddim = torch.stack(x_samples_ddim).float() x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0) del samples_ddim if lowvram.is_enabled(shared.sd_model): lowvram.send_everything_to_cpu() devices.torch_gc() state.nextjob() if p.scripts is not None: p.scripts.postprocess_batch(p, x_samples_ddim, batch_number=n) p.prompts = p.all_prompts[n * p.batch_size:(n + 1) * p.batch_size] p.negative_prompts = p.all_negative_prompts[n * p.batch_size:(n + 1) * p.batch_size] batch_params = scripts.PostprocessBatchListArgs(list(x_samples_ddim)) p.scripts.postprocess_batch_list(p, batch_params, batch_number=n) x_samples_ddim = batch_params.images def infotext(index=0, use_main_prompt=False): return create_infotext(p, p.prompts, p.seeds, p.subseeds, use_main_prompt=use_main_prompt, index=index, all_negative_prompts=p.negative_prompts) save_samples = p.save_samples() for i, x_sample in enumerate(x_samples_ddim): p.batch_index = i x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2) x_sample = x_sample.astype(np.uint8) if p.restore_faces: if save_samples and opts.save_images_before_face_restoration: images.save_image(Image.fromarray(x_sample), p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-before-face-restoration") devices.torch_gc() x_sample = modules.face_restoration.restore_faces(x_sample) devices.torch_gc() image = Image.fromarray(x_sample) if p.scripts is not None: pp = scripts.PostprocessImageArgs(image) p.scripts.postprocess_image(p, pp) image = pp.image mask_for_overlay = getattr(p, "mask_for_overlay", None) if not shared.opts.overlay_inpaint: overlay_image = None elif getattr(p, "overlay_images", None) is not None and i < len(p.overlay_images): overlay_image = p.overlay_images[i] else: overlay_image = None if p.scripts is not None: ppmo = scripts.PostProcessMaskOverlayArgs(i, mask_for_overlay, overlay_image) p.scripts.postprocess_maskoverlay(p, ppmo) mask_for_overlay, overlay_image = ppmo.mask_for_overlay, ppmo.overlay_image if p.color_corrections is not None and i < len(p.color_corrections): if save_samples and opts.save_images_before_color_correction: image_without_cc, _ = apply_overlay(image, p.paste_to, overlay_image) images.save_image(image_without_cc, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-before-color-correction") image = apply_color_correction(p.color_corrections[i], image) # If the intention is to show the output from the model # that is being composited over the original image, # we need to keep the original image around # and use it in the composite step. image, original_denoised_image = apply_overlay(image, p.paste_to, overlay_image) if p.scripts is not None: pp = scripts.PostprocessImageArgs(image) p.scripts.postprocess_image_after_composite(p, pp) image = pp.image if save_samples: images.save_image(image, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p) text = infotext(i) infotexts.append(text) if opts.enable_pnginfo: image.info["parameters"] = text output_images.append(image) if mask_for_overlay is not None: if opts.return_mask or opts.save_mask: image_mask = mask_for_overlay.convert('RGB') if save_samples and opts.save_mask: images.save_image(image_mask, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-mask") if opts.return_mask: output_images.append(image_mask) if opts.return_mask_composite or opts.save_mask_composite: image_mask_composite = Image.composite(original_denoised_image.convert('RGBA').convert('RGBa'), Image.new('RGBa', image.size), images.resize_image(2, mask_for_overlay, image.width, image.height).convert('L')).convert('RGBA') if save_samples and opts.save_mask_composite: images.save_image(image_mask_composite, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-mask-composite") if opts.return_mask_composite: output_images.append(image_mask_composite) del x_samples_ddim devices.torch_gc() if not infotexts: infotexts.append(Processed(p, []).infotext(p, 0)) p.color_corrections = None index_of_first_image = 0 unwanted_grid_because_of_img_count = len(output_images) < 2 and opts.grid_only_if_multiple if (opts.return_grid or opts.grid_save) and not p.do_not_save_grid and not unwanted_grid_because_of_img_count: grid = images.image_grid(output_images, p.batch_size) if opts.return_grid: text = infotext(use_main_prompt=True) infotexts.insert(0, text) if opts.enable_pnginfo: grid.info["parameters"] = text output_images.insert(0, grid) index_of_first_image = 1 if opts.grid_save: images.save_image(grid, p.outpath_grids, "grid", p.all_seeds[0], p.all_prompts[0], opts.grid_format, info=infotext(use_main_prompt=True), short_filename=not opts.grid_extended_filename, p=p, grid=True) if not p.disable_extra_networks and p.extra_network_data: extra_networks.deactivate(p, p.extra_network_data) devices.torch_gc() res = Processed( p, images_list=output_images, seed=p.all_seeds[0], info=infotexts[0], subseed=p.all_subseeds[0], index_of_first_image=index_of_first_image, infotexts=infotexts, ) if p.scripts is not None: p.scripts.postprocess(p, res) return res def old_hires_fix_first_pass_dimensions(width, height): desired_pixel_count = 512 * 512 actual_pixel_count = width * height scale = math.sqrt(desired_pixel_count / actual_pixel_count) width = math.ceil(scale * width / 64) * 64 height = math.ceil(scale * height / 64) * 64 return width, height @dataclass(repr=False) class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing): enable_hr: bool = False denoising_strength: float = 0.75 firstphase_width: int = 0 firstphase_height: int = 0 hr_scale: float = 2.0 hr_upscaler: str = None hr_second_pass_steps: int = 0 hr_resize_x: int = 0 hr_resize_y: int = 0 hr_checkpoint_name: str = None hr_sampler_name: str = None hr_scheduler: str = None hr_prompt: str = '' hr_negative_prompt: str = '' force_task_id: str = None cached_hr_uc = [None, None] cached_hr_c = [None, None] hr_checkpoint_info: dict = field(default=None, init=False) hr_upscale_to_x: int = field(default=0, init=False) hr_upscale_to_y: int = field(default=0, init=False) truncate_x: int = field(default=0, init=False) truncate_y: int = field(default=0, init=False) applied_old_hires_behavior_to: tuple = field(default=None, init=False) latent_scale_mode: dict = field(default=None, init=False) hr_c: tuple | None = field(default=None, init=False) hr_uc: tuple | None = field(default=None, init=False) all_hr_prompts: list = field(default=None, init=False) all_hr_negative_prompts: list = field(default=None, init=False) hr_prompts: list = field(default=None, init=False) hr_negative_prompts: list = field(default=None, init=False) hr_extra_network_data: list = field(default=None, init=False) def __post_init__(self): super().__post_init__() if self.firstphase_width != 0 or self.firstphase_height != 0: self.hr_upscale_to_x = self.width self.hr_upscale_to_y = self.height self.width = self.firstphase_width self.height = self.firstphase_height self.cached_hr_uc = StableDiffusionProcessingTxt2Img.cached_hr_uc self.cached_hr_c = StableDiffusionProcessingTxt2Img.cached_hr_c def calculate_target_resolution(self): if opts.use_old_hires_fix_width_height and self.applied_old_hires_behavior_to != (self.width, self.height): self.hr_resize_x = self.width self.hr_resize_y = self.height self.hr_upscale_to_x = self.width self.hr_upscale_to_y = self.height self.width, self.height = old_hires_fix_first_pass_dimensions(self.width, self.height) self.applied_old_hires_behavior_to = (self.width, self.height) if self.hr_resize_x == 0 and self.hr_resize_y == 0: self.extra_generation_params["Hires upscale"] = self.hr_scale self.hr_upscale_to_x = int(self.width * self.hr_scale) self.hr_upscale_to_y = int(self.height * self.hr_scale) else: self.extra_generation_params["Hires resize"] = f"{self.hr_resize_x}x{self.hr_resize_y}" if self.hr_resize_y == 0: self.hr_upscale_to_x = self.hr_resize_x self.hr_upscale_to_y = self.hr_resize_x * self.height // self.width elif self.hr_resize_x == 0: self.hr_upscale_to_x = self.hr_resize_y * self.width // self.height self.hr_upscale_to_y = self.hr_resize_y else: target_w = self.hr_resize_x target_h = self.hr_resize_y src_ratio = self.width / self.height dst_ratio = self.hr_resize_x / self.hr_resize_y if src_ratio < dst_ratio: self.hr_upscale_to_x = self.hr_resize_x self.hr_upscale_to_y = self.hr_resize_x * self.height // self.width else: self.hr_upscale_to_x = self.hr_resize_y * self.width // self.height self.hr_upscale_to_y = self.hr_resize_y self.truncate_x = (self.hr_upscale_to_x - target_w) // opt_f self.truncate_y = (self.hr_upscale_to_y - target_h) // opt_f def init(self, all_prompts, all_seeds, all_subseeds): if self.enable_hr: self.extra_generation_params["Denoising strength"] = self.denoising_strength if self.hr_checkpoint_name and self.hr_checkpoint_name != 'Use same checkpoint': self.hr_checkpoint_info = sd_models.get_closet_checkpoint_match(self.hr_checkpoint_name) if self.hr_checkpoint_info is None: raise Exception(f'Could not find checkpoint with name {self.hr_checkpoint_name}') self.extra_generation_params["Hires checkpoint"] = self.hr_checkpoint_info.short_title if self.hr_sampler_name is not None and self.hr_sampler_name != self.sampler_name: self.extra_generation_params["Hires sampler"] = self.hr_sampler_name def get_hr_prompt(p, index, prompt_text, **kwargs): hr_prompt = p.all_hr_prompts[index] return hr_prompt if hr_prompt != prompt_text else None def get_hr_negative_prompt(p, index, negative_prompt, **kwargs): hr_negative_prompt = p.all_hr_negative_prompts[index] return hr_negative_prompt if hr_negative_prompt != negative_prompt else None self.extra_generation_params["Hires prompt"] = get_hr_prompt self.extra_generation_params["Hires negative prompt"] = get_hr_negative_prompt self.extra_generation_params["Hires schedule type"] = None # to be set in sd_samplers_kdiffusion.py if self.hr_scheduler is None: self.hr_scheduler = self.scheduler self.latent_scale_mode = shared.latent_upscale_modes.get(self.hr_upscaler, None) if self.hr_upscaler is not None else shared.latent_upscale_modes.get(shared.latent_upscale_default_mode, "nearest") if self.enable_hr and self.latent_scale_mode is None: if not any(x.name == self.hr_upscaler for x in shared.sd_upscalers): raise Exception(f"could not find upscaler named {self.hr_upscaler}") self.calculate_target_resolution() if not state.processing_has_refined_job_count: if state.job_count == -1: state.job_count = self.n_iter if getattr(self, 'txt2img_upscale', False): total_steps = (self.hr_second_pass_steps or self.steps) * state.job_count else: total_steps = (self.steps + (self.hr_second_pass_steps or self.steps)) * state.job_count shared.total_tqdm.updateTotal(total_steps) state.job_count = state.job_count * 2 state.processing_has_refined_job_count = True if self.hr_second_pass_steps: self.extra_generation_params["Hires steps"] = self.hr_second_pass_steps if self.hr_upscaler is not None: self.extra_generation_params["Hires upscaler"] = self.hr_upscaler def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts): self.sampler = sd_samplers.create_sampler(self.sampler_name, self.sd_model) if self.firstpass_image is not None and self.enable_hr: # here we don't need to generate image, we just take self.firstpass_image and prepare it for hires fix if self.latent_scale_mode is None: image = np.array(self.firstpass_image).astype(np.float32) / 255.0 * 2.0 - 1.0 image = np.moveaxis(image, 2, 0) samples = None decoded_samples = torch.asarray(np.expand_dims(image, 0)) else: image = np.array(self.firstpass_image).astype(np.float32) / 255.0 image = np.moveaxis(image, 2, 0) image = torch.from_numpy(np.expand_dims(image, axis=0)) image = image.to(shared.device, dtype=devices.dtype_vae) if opts.sd_vae_encode_method != 'Full': self.extra_generation_params['VAE Encoder'] = opts.sd_vae_encode_method samples = images_tensor_to_samples(image, approximation_indexes.get(opts.sd_vae_encode_method), self.sd_model) decoded_samples = None devices.torch_gc() else: # here we generate an image normally x = self.rng.next() if self.scripts is not None: self.scripts.process_before_every_sampling( p=self, x=x, noise=x, c=conditioning, uc=unconditional_conditioning ) samples = self.sampler.sample(self, x, conditioning, unconditional_conditioning, image_conditioning=self.txt2img_image_conditioning(x)) del x if not self.enable_hr: return samples devices.torch_gc() if self.latent_scale_mode is None: decoded_samples = torch.stack(decode_latent_batch(self.sd_model, samples, target_device=devices.cpu, check_for_nans=True)).to(dtype=torch.float32) else: decoded_samples = None with sd_models.SkipWritingToConfig(): sd_models.reload_model_weights(info=self.hr_checkpoint_info) return self.sample_hr_pass(samples, decoded_samples, seeds, subseeds, subseed_strength, prompts) def sample_hr_pass(self, samples, decoded_samples, seeds, subseeds, subseed_strength, prompts): if shared.state.interrupted: return samples self.is_hr_pass = True target_width = self.hr_upscale_to_x target_height = self.hr_upscale_to_y def save_intermediate(image, index): if not self.save_samples() or not opts.save_images_before_highres_fix: return if not isinstance(image, Image.Image): image = sd_samplers.sample_to_image(image, index, approximation=0) info = create_infotext(self, self.all_prompts, self.all_seeds, self.all_subseeds, [], iteration=self.iteration, position_in_batch=index) images.save_image(image, self.outpath_samples, "", seeds[index], prompts[index], opts.samples_format, info=info, p=self, suffix="-before-highres-fix") img2img_sampler_name = self.hr_sampler_name or self.sampler_name self.sampler = sd_samplers.create_sampler(img2img_sampler_name, self.sd_model) if self.latent_scale_mode is not None: for i in range(samples.shape[0]): save_intermediate(samples, i) samples = torch.nn.functional.interpolate(samples, size=(target_height // opt_f, target_width // opt_f), mode=self.latent_scale_mode["mode"], antialias=self.latent_scale_mode["antialias"]) # Avoid making the inpainting conditioning unless necessary as # this does need some extra compute to decode / encode the image again. if getattr(self, "inpainting_mask_weight", shared.opts.inpainting_mask_weight) < 1.0: image_conditioning = self.img2img_image_conditioning(decode_first_stage(self.sd_model, samples), samples) else: image_conditioning = self.txt2img_image_conditioning(samples) else: lowres_samples = torch.clamp((decoded_samples + 1.0) / 2.0, min=0.0, max=1.0) batch_images = [] for i, x_sample in enumerate(lowres_samples): x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2) x_sample = x_sample.astype(np.uint8) image = Image.fromarray(x_sample) save_intermediate(image, i) image = images.resize_image(0, image, target_width, target_height, upscaler_name=self.hr_upscaler) image = np.array(image).astype(np.float32) / 255.0 image = np.moveaxis(image, 2, 0) batch_images.append(image) decoded_samples = torch.from_numpy(np.array(batch_images)) decoded_samples = decoded_samples.to(shared.device, dtype=devices.dtype_vae) if opts.sd_vae_encode_method != 'Full': self.extra_generation_params['VAE Encoder'] = opts.sd_vae_encode_method samples = images_tensor_to_samples(decoded_samples, approximation_indexes.get(opts.sd_vae_encode_method)) image_conditioning = self.img2img_image_conditioning(decoded_samples, samples) shared.state.nextjob() samples = samples[:, :, self.truncate_y//2:samples.shape[2]-(self.truncate_y+1)//2, self.truncate_x//2:samples.shape[3]-(self.truncate_x+1)//2] self.rng = rng.ImageRNG(samples.shape[1:], self.seeds, subseeds=self.subseeds, subseed_strength=self.subseed_strength, seed_resize_from_h=self.seed_resize_from_h, seed_resize_from_w=self.seed_resize_from_w) noise = self.rng.next() # GC now before running the next img2img to prevent running out of memory devices.torch_gc() if not self.disable_extra_networks: with devices.autocast(): extra_networks.activate(self, self.hr_extra_network_data) with devices.autocast(): self.calculate_hr_conds() sd_models.apply_token_merging(self.sd_model, self.get_token_merging_ratio(for_hr=True)) if self.scripts is not None: self.scripts.before_hr(self) self.scripts.process_before_every_sampling( p=self, x=samples, noise=noise, c=self.hr_c, uc=self.hr_uc, ) samples = self.sampler.sample_img2img(self, samples, noise, self.hr_c, self.hr_uc, steps=self.hr_second_pass_steps or self.steps, image_conditioning=image_conditioning) sd_models.apply_token_merging(self.sd_model, self.get_token_merging_ratio()) self.sampler = None devices.torch_gc() decoded_samples = decode_latent_batch(self.sd_model, samples, target_device=devices.cpu, check_for_nans=True) self.is_hr_pass = False return decoded_samples def close(self): super().close() self.hr_c = None self.hr_uc = None if not opts.persistent_cond_cache: StableDiffusionProcessingTxt2Img.cached_hr_uc = [None, None] StableDiffusionProcessingTxt2Img.cached_hr_c = [None, None] def setup_prompts(self): super().setup_prompts() if not self.enable_hr: return if self.hr_prompt == '': self.hr_prompt = self.prompt if self.hr_negative_prompt == '': self.hr_negative_prompt = self.negative_prompt if isinstance(self.hr_prompt, list): self.all_hr_prompts = self.hr_prompt else: self.all_hr_prompts = self.batch_size * self.n_iter * [self.hr_prompt] if isinstance(self.hr_negative_prompt, list): self.all_hr_negative_prompts = self.hr_negative_prompt else: self.all_hr_negative_prompts = self.batch_size * self.n_iter * [self.hr_negative_prompt] self.all_hr_prompts = [shared.prompt_styles.apply_styles_to_prompt(x, self.styles) for x in self.all_hr_prompts] self.all_hr_negative_prompts = [shared.prompt_styles.apply_negative_styles_to_prompt(x, self.styles) for x in self.all_hr_negative_prompts] def calculate_hr_conds(self): if self.hr_c is not None: return hr_prompts = prompt_parser.SdConditioning(self.hr_prompts, width=self.hr_upscale_to_x, height=self.hr_upscale_to_y) hr_negative_prompts = prompt_parser.SdConditioning(self.hr_negative_prompts, width=self.hr_upscale_to_x, height=self.hr_upscale_to_y, is_negative_prompt=True) sampler_config = sd_samplers.find_sampler_config(self.hr_sampler_name or self.sampler_name) steps = self.hr_second_pass_steps or self.steps total_steps = sampler_config.total_steps(steps) if sampler_config else steps self.hr_uc = self.get_conds_with_caching(prompt_parser.get_learned_conditioning, hr_negative_prompts, self.firstpass_steps, [self.cached_hr_uc, self.cached_uc], self.hr_extra_network_data, total_steps) self.hr_c = self.get_conds_with_caching(prompt_parser.get_multicond_learned_conditioning, hr_prompts, self.firstpass_steps, [self.cached_hr_c, self.cached_c], self.hr_extra_network_data, total_steps) def setup_conds(self): if self.is_hr_pass: # if we are in hr pass right now, the call is being made from the refiner, and we don't need to setup firstpass cons or switch model self.hr_c = None self.calculate_hr_conds() return super().setup_conds() self.hr_uc = None self.hr_c = None if self.enable_hr and self.hr_checkpoint_info is None: if shared.opts.hires_fix_use_firstpass_conds: self.calculate_hr_conds() elif lowvram.is_enabled(shared.sd_model) and shared.sd_model.sd_checkpoint_info == sd_models.select_checkpoint(): # if in lowvram mode, we need to calculate conds right away, before the cond NN is unloaded with devices.autocast(): extra_networks.activate(self, self.hr_extra_network_data) self.calculate_hr_conds() with devices.autocast(): extra_networks.activate(self, self.extra_network_data) def get_conds(self): if self.is_hr_pass: return self.hr_c, self.hr_uc return super().get_conds() def parse_extra_network_prompts(self): res = super().parse_extra_network_prompts() if self.enable_hr: self.hr_prompts = self.all_hr_prompts[self.iteration * self.batch_size:(self.iteration + 1) * self.batch_size] self.hr_negative_prompts = self.all_hr_negative_prompts[self.iteration * self.batch_size:(self.iteration + 1) * self.batch_size] self.hr_prompts, self.hr_extra_network_data = extra_networks.parse_prompts(self.hr_prompts) return res @dataclass(repr=False) class StableDiffusionProcessingImg2Img(StableDiffusionProcessing): init_images: list = None resize_mode: int = 0 denoising_strength: float = 0.75 image_cfg_scale: float = None mask: Any = None mask_blur_x: int = 4 mask_blur_y: int = 4 mask_blur: int = None mask_round: bool = True inpainting_fill: int = 0 inpaint_full_res: bool = True inpaint_full_res_padding: int = 0 inpainting_mask_invert: int = 0 initial_noise_multiplier: float = None latent_mask: Image = None force_task_id: str = None image_mask: Any = field(default=None, init=False) nmask: torch.Tensor = field(default=None, init=False) image_conditioning: torch.Tensor = field(default=None, init=False) init_img_hash: str = field(default=None, init=False) mask_for_overlay: Image = field(default=None, init=False) init_latent: torch.Tensor = field(default=None, init=False) def __post_init__(self): super().__post_init__() self.image_mask = self.mask self.mask = None self.initial_noise_multiplier = opts.initial_noise_multiplier if self.initial_noise_multiplier is None else self.initial_noise_multiplier @property def mask_blur(self): if self.mask_blur_x == self.mask_blur_y: return self.mask_blur_x return None @mask_blur.setter def mask_blur(self, value): if isinstance(value, int): self.mask_blur_x = value self.mask_blur_y = value def init(self, all_prompts, all_seeds, all_subseeds): self.extra_generation_params["Denoising strength"] = self.denoising_strength self.image_cfg_scale: float = self.image_cfg_scale if shared.sd_model.cond_stage_key == "edit" else None self.sampler = sd_samplers.create_sampler(self.sampler_name, self.sd_model) crop_region = None image_mask = self.image_mask if image_mask is not None: # image_mask is passed in as RGBA by Gradio to support alpha masks, # but we still want to support binary masks. image_mask = create_binary_mask(image_mask, round=self.mask_round) if self.inpainting_mask_invert: image_mask = ImageOps.invert(image_mask) self.extra_generation_params["Mask mode"] = "Inpaint not masked" if self.mask_blur_x > 0: np_mask = np.array(image_mask) kernel_size = 2 * int(2.5 * self.mask_blur_x + 0.5) + 1 np_mask = cv2.GaussianBlur(np_mask, (kernel_size, 1), self.mask_blur_x) image_mask = Image.fromarray(np_mask) if self.mask_blur_y > 0: np_mask = np.array(image_mask) kernel_size = 2 * int(2.5 * self.mask_blur_y + 0.5) + 1 np_mask = cv2.GaussianBlur(np_mask, (1, kernel_size), self.mask_blur_y) image_mask = Image.fromarray(np_mask) if self.mask_blur_x > 0 or self.mask_blur_y > 0: self.extra_generation_params["Mask blur"] = self.mask_blur if self.inpaint_full_res: self.mask_for_overlay = image_mask mask = image_mask.convert('L') crop_region = masking.get_crop_region_v2(mask, self.inpaint_full_res_padding) if crop_region: crop_region = masking.expand_crop_region(crop_region, self.width, self.height, mask.width, mask.height) x1, y1, x2, y2 = crop_region mask = mask.crop(crop_region) image_mask = images.resize_image(2, mask, self.width, self.height) self.paste_to = (x1, y1, x2-x1, y2-y1) self.extra_generation_params["Inpaint area"] = "Only masked" self.extra_generation_params["Masked area padding"] = self.inpaint_full_res_padding else: crop_region = None image_mask = None self.mask_for_overlay = None self.inpaint_full_res = False massage = 'Unable to perform "Inpaint Only mask" because mask is blank, switch to img2img mode.' model_hijack.comments.append(massage) logging.info(massage) else: image_mask = images.resize_image(self.resize_mode, image_mask, self.width, self.height) np_mask = np.array(image_mask) np_mask = np.clip((np_mask.astype(np.float32)) * 2, 0, 255).astype(np.uint8) self.mask_for_overlay = Image.fromarray(np_mask) self.overlay_images = [] latent_mask = self.latent_mask if self.latent_mask is not None else image_mask add_color_corrections = opts.img2img_color_correction and self.color_corrections is None if add_color_corrections: self.color_corrections = [] imgs = [] for img in self.init_images: # Save init image if opts.save_init_img: self.init_img_hash = hashlib.md5(img.tobytes()).hexdigest() images.save_image(img, path=opts.outdir_init_images, basename=None, forced_filename=self.init_img_hash, save_to_dirs=False, existing_info=img.info) image = images.flatten(img, opts.img2img_background_color) if crop_region is None and self.resize_mode != 3: image = images.resize_image(self.resize_mode, image, self.width, self.height) if image_mask is not None: if self.mask_for_overlay.size != (image.width, image.height): self.mask_for_overlay = images.resize_image(self.resize_mode, self.mask_for_overlay, image.width, image.height) image_masked = Image.new('RGBa', (image.width, image.height)) image_masked.paste(image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(self.mask_for_overlay.convert('L'))) self.overlay_images.append(image_masked.convert('RGBA')) # crop_region is not None if we are doing inpaint full res if crop_region is not None: image = image.crop(crop_region) image = images.resize_image(2, image, self.width, self.height) if image_mask is not None: if self.inpainting_fill != 1: image = masking.fill(image, latent_mask) if self.inpainting_fill == 0: self.extra_generation_params["Masked content"] = 'fill' if add_color_corrections: self.color_corrections.append(setup_color_correction(image)) image = np.array(image).astype(np.float32) / 255.0 image = np.moveaxis(image, 2, 0) imgs.append(image) if len(imgs) == 1: batch_images = np.expand_dims(imgs[0], axis=0).repeat(self.batch_size, axis=0) if self.overlay_images is not None: self.overlay_images = self.overlay_images * self.batch_size if self.color_corrections is not None and len(self.color_corrections) == 1: self.color_corrections = self.color_corrections * self.batch_size elif len(imgs) <= self.batch_size: self.batch_size = len(imgs) batch_images = np.array(imgs) else: raise RuntimeError(f"bad number of images passed: {len(imgs)}; expecting {self.batch_size} or less") image = torch.from_numpy(batch_images) image = image.to(shared.device, dtype=devices.dtype_vae) if opts.sd_vae_encode_method != 'Full': self.extra_generation_params['VAE Encoder'] = opts.sd_vae_encode_method self.init_latent = images_tensor_to_samples(image, approximation_indexes.get(opts.sd_vae_encode_method), self.sd_model) devices.torch_gc() if self.resize_mode == 3: self.init_latent = torch.nn.functional.interpolate(self.init_latent, size=(self.height // opt_f, self.width // opt_f), mode="bilinear") if image_mask is not None: init_mask = latent_mask latmask = init_mask.convert('RGB').resize((self.init_latent.shape[3], self.init_latent.shape[2])) latmask = np.moveaxis(np.array(latmask, dtype=np.float32), 2, 0) / 255 latmask = latmask[0] if self.mask_round: latmask = np.around(latmask) latmask = np.tile(latmask[None], (self.init_latent.shape[1], 1, 1)) self.mask = torch.asarray(1.0 - latmask).to(shared.device).type(devices.dtype) self.nmask = torch.asarray(latmask).to(shared.device).type(devices.dtype) # this needs to be fixed to be done in sample() using actual seeds for batches if self.inpainting_fill == 2: self.init_latent = self.init_latent * self.mask + create_random_tensors(self.init_latent.shape[1:], all_seeds[0:self.init_latent.shape[0]]) * self.nmask self.extra_generation_params["Masked content"] = 'latent noise' elif self.inpainting_fill == 3: self.init_latent = self.init_latent * self.mask self.extra_generation_params["Masked content"] = 'latent nothing' self.image_conditioning = self.img2img_image_conditioning(image * 2 - 1, self.init_latent, image_mask, self.mask_round) def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts): x = self.rng.next() if self.initial_noise_multiplier != 1.0: self.extra_generation_params["Noise multiplier"] = self.initial_noise_multiplier x *= self.initial_noise_multiplier if self.scripts is not None: self.scripts.process_before_every_sampling( p=self, x=self.init_latent, noise=x, c=conditioning, uc=unconditional_conditioning ) samples = self.sampler.sample_img2img(self, self.init_latent, x, conditioning, unconditional_conditioning, image_conditioning=self.image_conditioning) if self.mask is not None: blended_samples = samples * self.nmask + self.init_latent * self.mask if self.scripts is not None: mba = scripts.MaskBlendArgs(samples, self.nmask, self.init_latent, self.mask, blended_samples) self.scripts.on_mask_blend(self, mba) blended_samples = mba.blended_latent samples = blended_samples del x devices.torch_gc() return samples def get_token_merging_ratio(self, for_hr=False): return self.token_merging_ratio or ("token_merging_ratio" in self.override_settings and opts.token_merging_ratio) or opts.token_merging_ratio_img2img or opts.token_merging_ratio
--- +++ @@ -1,1733 +1,1792 @@-from __future__ import annotations -import json -import logging -import math -import os -import sys -import hashlib -from dataclasses import dataclass, field - -import torch -import numpy as np -from PIL import Image, ImageOps -import random -import cv2 -from skimage import exposure -from typing import Any - -import modules.sd_hijack -from modules import devices, prompt_parser, masking, sd_samplers, lowvram, infotext_utils, extra_networks, sd_vae_approx, scripts, sd_samplers_common, sd_unet, errors, rng, profiling -from modules.rng import slerp # noqa: F401 -from modules.sd_hijack import model_hijack -from modules.sd_samplers_common import images_tensor_to_samples, decode_first_stage, approximation_indexes -from modules.shared import opts, cmd_opts, state -import modules.shared as shared -import modules.paths as paths -import modules.face_restoration -import modules.images as images -import modules.styles -import modules.sd_models as sd_models -import modules.sd_vae as sd_vae -from ldm.data.util import AddMiDaS -from ldm.models.diffusion.ddpm import LatentDepth2ImageDiffusion - -from einops import repeat, rearrange -from blendmodes.blend import blendLayers, BlendType - - -# some of those options should not be changed at all because they would break the model, so I removed them from options. -opt_C = 4 -opt_f = 8 - - -def setup_color_correction(image): - logging.info("Calibrating color correction.") - correction_target = cv2.cvtColor(np.asarray(image.copy()), cv2.COLOR_RGB2LAB) - return correction_target - - -def apply_color_correction(correction, original_image): - logging.info("Applying color correction.") - image = Image.fromarray(cv2.cvtColor(exposure.match_histograms( - cv2.cvtColor( - np.asarray(original_image), - cv2.COLOR_RGB2LAB - ), - correction, - channel_axis=2 - ), cv2.COLOR_LAB2RGB).astype("uint8")) - - image = blendLayers(image, original_image, BlendType.LUMINOSITY) - - return image.convert('RGB') - - -def uncrop(image, dest_size, paste_loc): - x, y, w, h = paste_loc - base_image = Image.new('RGBA', dest_size) - image = images.resize_image(1, image, w, h) - base_image.paste(image, (x, y)) - image = base_image - - return image - - -def apply_overlay(image, paste_loc, overlay): - if overlay is None: - return image, image.copy() - - if paste_loc is not None: - image = uncrop(image, (overlay.width, overlay.height), paste_loc) - - original_denoised_image = image.copy() - - image = image.convert('RGBA') - image.alpha_composite(overlay) - image = image.convert('RGB') - - return image, original_denoised_image - -def create_binary_mask(image, round=True): - if image.mode == 'RGBA' and image.getextrema()[-1] != (255, 255): - if round: - image = image.split()[-1].convert("L").point(lambda x: 255 if x > 128 else 0) - else: - image = image.split()[-1].convert("L") - else: - image = image.convert('L') - return image - -def txt2img_image_conditioning(sd_model, x, width, height): - if sd_model.model.conditioning_key in {'hybrid', 'concat'}: # Inpainting models - - # The "masked-image" in this case will just be all 0.5 since the entire image is masked. - image_conditioning = torch.ones(x.shape[0], 3, height, width, device=x.device) * 0.5 - image_conditioning = images_tensor_to_samples(image_conditioning, approximation_indexes.get(opts.sd_vae_encode_method)) - - # Add the fake full 1s mask to the first dimension. - image_conditioning = torch.nn.functional.pad(image_conditioning, (0, 0, 0, 0, 1, 0), value=1.0) - image_conditioning = image_conditioning.to(x.dtype) - - return image_conditioning - - elif sd_model.model.conditioning_key == "crossattn-adm": # UnCLIP models - - return x.new_zeros(x.shape[0], 2*sd_model.noise_augmentor.time_embed.dim, dtype=x.dtype, device=x.device) - - else: - if sd_model.is_sdxl_inpaint: - # The "masked-image" in this case will just be all 0.5 since the entire image is masked. - image_conditioning = torch.ones(x.shape[0], 3, height, width, device=x.device) * 0.5 - image_conditioning = images_tensor_to_samples(image_conditioning, - approximation_indexes.get(opts.sd_vae_encode_method)) - - # Add the fake full 1s mask to the first dimension. - image_conditioning = torch.nn.functional.pad(image_conditioning, (0, 0, 0, 0, 1, 0), value=1.0) - image_conditioning = image_conditioning.to(x.dtype) - - return image_conditioning - - # Dummy zero conditioning if we're not using inpainting or unclip models. - # Still takes up a bit of memory, but no encoder call. - # Pretty sure we can just make this a 1x1 image since its not going to be used besides its batch size. - return x.new_zeros(x.shape[0], 5, 1, 1, dtype=x.dtype, device=x.device) - - -@dataclass(repr=False) -class StableDiffusionProcessing: - sd_model: object = None - outpath_samples: str = None - outpath_grids: str = None - prompt: str = "" - prompt_for_display: str = None - negative_prompt: str = "" - styles: list[str] = None - seed: int = -1 - subseed: int = -1 - subseed_strength: float = 0 - seed_resize_from_h: int = -1 - seed_resize_from_w: int = -1 - seed_enable_extras: bool = True - sampler_name: str = None - scheduler: str = None - batch_size: int = 1 - n_iter: int = 1 - steps: int = 50 - cfg_scale: float = 7.0 - width: int = 512 - height: int = 512 - restore_faces: bool = None - tiling: bool = None - do_not_save_samples: bool = False - do_not_save_grid: bool = False - extra_generation_params: dict[str, Any] = None - overlay_images: list = None - eta: float = None - do_not_reload_embeddings: bool = False - denoising_strength: float = None - ddim_discretize: str = None - s_min_uncond: float = None - s_churn: float = None - s_tmax: float = None - s_tmin: float = None - s_noise: float = None - override_settings: dict[str, Any] = None - override_settings_restore_afterwards: bool = True - sampler_index: int = None - refiner_checkpoint: str = None - refiner_switch_at: float = None - token_merging_ratio = 0 - token_merging_ratio_hr = 0 - disable_extra_networks: bool = False - firstpass_image: Image = None - - scripts_value: scripts.ScriptRunner = field(default=None, init=False) - script_args_value: list = field(default=None, init=False) - scripts_setup_complete: bool = field(default=False, init=False) - - cached_uc = [None, None] - cached_c = [None, None] - - comments: dict = None - sampler: sd_samplers_common.Sampler | None = field(default=None, init=False) - is_using_inpainting_conditioning: bool = field(default=False, init=False) - paste_to: tuple | None = field(default=None, init=False) - - is_hr_pass: bool = field(default=False, init=False) - - c: tuple = field(default=None, init=False) - uc: tuple = field(default=None, init=False) - - rng: rng.ImageRNG | None = field(default=None, init=False) - step_multiplier: int = field(default=1, init=False) - color_corrections: list = field(default=None, init=False) - - all_prompts: list = field(default=None, init=False) - all_negative_prompts: list = field(default=None, init=False) - all_seeds: list = field(default=None, init=False) - all_subseeds: list = field(default=None, init=False) - iteration: int = field(default=0, init=False) - main_prompt: str = field(default=None, init=False) - main_negative_prompt: str = field(default=None, init=False) - - prompts: list = field(default=None, init=False) - negative_prompts: list = field(default=None, init=False) - seeds: list = field(default=None, init=False) - subseeds: list = field(default=None, init=False) - extra_network_data: dict = field(default=None, init=False) - - user: str = field(default=None, init=False) - - sd_model_name: str = field(default=None, init=False) - sd_model_hash: str = field(default=None, init=False) - sd_vae_name: str = field(default=None, init=False) - sd_vae_hash: str = field(default=None, init=False) - - is_api: bool = field(default=False, init=False) - - def __post_init__(self): - if self.sampler_index is not None: - print("sampler_index argument for StableDiffusionProcessing does not do anything; use sampler_name", file=sys.stderr) - - self.comments = {} - - if self.styles is None: - self.styles = [] - - self.sampler_noise_scheduler_override = None - - self.extra_generation_params = self.extra_generation_params or {} - self.override_settings = self.override_settings or {} - self.script_args = self.script_args or {} - - self.refiner_checkpoint_info = None - - if not self.seed_enable_extras: - self.subseed = -1 - self.subseed_strength = 0 - self.seed_resize_from_h = 0 - self.seed_resize_from_w = 0 - - self.cached_uc = StableDiffusionProcessing.cached_uc - self.cached_c = StableDiffusionProcessing.cached_c - - def fill_fields_from_opts(self): - self.s_min_uncond = self.s_min_uncond if self.s_min_uncond is not None else opts.s_min_uncond - self.s_churn = self.s_churn if self.s_churn is not None else opts.s_churn - self.s_tmin = self.s_tmin if self.s_tmin is not None else opts.s_tmin - self.s_tmax = (self.s_tmax if self.s_tmax is not None else opts.s_tmax) or float('inf') - self.s_noise = self.s_noise if self.s_noise is not None else opts.s_noise - - @property - def sd_model(self): - return shared.sd_model - - @sd_model.setter - def sd_model(self, value): - pass - - @property - def scripts(self): - return self.scripts_value - - @scripts.setter - def scripts(self, value): - self.scripts_value = value - - if self.scripts_value and self.script_args_value and not self.scripts_setup_complete: - self.setup_scripts() - - @property - def script_args(self): - return self.script_args_value - - @script_args.setter - def script_args(self, value): - self.script_args_value = value - - if self.scripts_value and self.script_args_value and not self.scripts_setup_complete: - self.setup_scripts() - - def setup_scripts(self): - self.scripts_setup_complete = True - - self.scripts.setup_scrips(self, is_ui=not self.is_api) - - def comment(self, text): - self.comments[text] = 1 - - def txt2img_image_conditioning(self, x, width=None, height=None): - self.is_using_inpainting_conditioning = self.sd_model.model.conditioning_key in {'hybrid', 'concat'} - - return txt2img_image_conditioning(self.sd_model, x, width or self.width, height or self.height) - - def depth2img_image_conditioning(self, source_image): - # Use the AddMiDaS helper to Format our source image to suit the MiDaS model - transformer = AddMiDaS(model_type="dpt_hybrid") - transformed = transformer({"jpg": rearrange(source_image[0], "c h w -> h w c")}) - midas_in = torch.from_numpy(transformed["midas_in"][None, ...]).to(device=shared.device) - midas_in = repeat(midas_in, "1 ... -> n ...", n=self.batch_size) - - conditioning_image = images_tensor_to_samples(source_image*0.5+0.5, approximation_indexes.get(opts.sd_vae_encode_method)) - conditioning = torch.nn.functional.interpolate( - self.sd_model.depth_model(midas_in), - size=conditioning_image.shape[2:], - mode="bicubic", - align_corners=False, - ) - - (depth_min, depth_max) = torch.aminmax(conditioning) - conditioning = 2. * (conditioning - depth_min) / (depth_max - depth_min) - 1. - return conditioning - - def edit_image_conditioning(self, source_image): - conditioning_image = shared.sd_model.encode_first_stage(source_image).mode() - - return conditioning_image - - def unclip_image_conditioning(self, source_image): - c_adm = self.sd_model.embedder(source_image) - if self.sd_model.noise_augmentor is not None: - noise_level = 0 # TODO: Allow other noise levels? - c_adm, noise_level_emb = self.sd_model.noise_augmentor(c_adm, noise_level=repeat(torch.tensor([noise_level]).to(c_adm.device), '1 -> b', b=c_adm.shape[0])) - c_adm = torch.cat((c_adm, noise_level_emb), 1) - return c_adm - - def inpainting_image_conditioning(self, source_image, latent_image, image_mask=None, round_image_mask=True): - self.is_using_inpainting_conditioning = True - - # Handle the different mask inputs - if image_mask is not None: - if torch.is_tensor(image_mask): - conditioning_mask = image_mask - else: - conditioning_mask = np.array(image_mask.convert("L")) - conditioning_mask = conditioning_mask.astype(np.float32) / 255.0 - conditioning_mask = torch.from_numpy(conditioning_mask[None, None]) - - if round_image_mask: - # Caller is requesting a discretized mask as input, so we round to either 1.0 or 0.0 - conditioning_mask = torch.round(conditioning_mask) - - else: - conditioning_mask = source_image.new_ones(1, 1, *source_image.shape[-2:]) - - # Create another latent image, this time with a masked version of the original input. - # Smoothly interpolate between the masked and unmasked latent conditioning image using a parameter. - conditioning_mask = conditioning_mask.to(device=source_image.device, dtype=source_image.dtype) - conditioning_image = torch.lerp( - source_image, - source_image * (1.0 - conditioning_mask), - getattr(self, "inpainting_mask_weight", shared.opts.inpainting_mask_weight) - ) - - # Encode the new masked image using first stage of network. - conditioning_image = self.sd_model.get_first_stage_encoding(self.sd_model.encode_first_stage(conditioning_image)) - - # Create the concatenated conditioning tensor to be fed to `c_concat` - conditioning_mask = torch.nn.functional.interpolate(conditioning_mask, size=latent_image.shape[-2:]) - conditioning_mask = conditioning_mask.expand(conditioning_image.shape[0], -1, -1, -1) - image_conditioning = torch.cat([conditioning_mask, conditioning_image], dim=1) - image_conditioning = image_conditioning.to(shared.device).type(self.sd_model.dtype) - - return image_conditioning - - def img2img_image_conditioning(self, source_image, latent_image, image_mask=None, round_image_mask=True): - source_image = devices.cond_cast_float(source_image) - - # HACK: Using introspection as the Depth2Image model doesn't appear to uniquely - # identify itself with a field common to all models. The conditioning_key is also hybrid. - if isinstance(self.sd_model, LatentDepth2ImageDiffusion): - return self.depth2img_image_conditioning(source_image) - - if self.sd_model.cond_stage_key == "edit": - return self.edit_image_conditioning(source_image) - - if self.sampler.conditioning_key in {'hybrid', 'concat'}: - return self.inpainting_image_conditioning(source_image, latent_image, image_mask=image_mask, round_image_mask=round_image_mask) - - if self.sampler.conditioning_key == "crossattn-adm": - return self.unclip_image_conditioning(source_image) - - if self.sampler.model_wrap.inner_model.is_sdxl_inpaint: - return self.inpainting_image_conditioning(source_image, latent_image, image_mask=image_mask) - - # Dummy zero conditioning if we're not using inpainting or depth model. - return latent_image.new_zeros(latent_image.shape[0], 5, 1, 1) - - def init(self, all_prompts, all_seeds, all_subseeds): - pass - - def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts): - raise NotImplementedError() - - def close(self): - self.sampler = None - self.c = None - self.uc = None - if not opts.persistent_cond_cache: - StableDiffusionProcessing.cached_c = [None, None] - StableDiffusionProcessing.cached_uc = [None, None] - - def get_token_merging_ratio(self, for_hr=False): - if for_hr: - return self.token_merging_ratio_hr or opts.token_merging_ratio_hr or self.token_merging_ratio or opts.token_merging_ratio - - return self.token_merging_ratio or opts.token_merging_ratio - - def setup_prompts(self): - if isinstance(self.prompt,list): - self.all_prompts = self.prompt - elif isinstance(self.negative_prompt, list): - self.all_prompts = [self.prompt] * len(self.negative_prompt) - else: - self.all_prompts = self.batch_size * self.n_iter * [self.prompt] - - if isinstance(self.negative_prompt, list): - self.all_negative_prompts = self.negative_prompt - else: - self.all_negative_prompts = [self.negative_prompt] * len(self.all_prompts) - - if len(self.all_prompts) != len(self.all_negative_prompts): - raise RuntimeError(f"Received a different number of prompts ({len(self.all_prompts)}) and negative prompts ({len(self.all_negative_prompts)})") - - self.all_prompts = [shared.prompt_styles.apply_styles_to_prompt(x, self.styles) for x in self.all_prompts] - self.all_negative_prompts = [shared.prompt_styles.apply_negative_styles_to_prompt(x, self.styles) for x in self.all_negative_prompts] - - self.main_prompt = self.all_prompts[0] - self.main_negative_prompt = self.all_negative_prompts[0] - - def cached_params(self, required_prompts, steps, extra_network_data, hires_steps=None, use_old_scheduling=False): - - return ( - required_prompts, - steps, - hires_steps, - use_old_scheduling, - opts.CLIP_stop_at_last_layers, - shared.sd_model.sd_checkpoint_info, - extra_network_data, - opts.sdxl_crop_left, - opts.sdxl_crop_top, - self.width, - self.height, - opts.fp8_storage, - opts.cache_fp16_weight, - opts.emphasis, - ) - - def get_conds_with_caching(self, function, required_prompts, steps, caches, extra_network_data, hires_steps=None): - - if shared.opts.use_old_scheduling: - old_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(required_prompts, steps, hires_steps, False) - new_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(required_prompts, steps, hires_steps, True) - if old_schedules != new_schedules: - self.extra_generation_params["Old prompt editing timelines"] = True - - cached_params = self.cached_params(required_prompts, steps, extra_network_data, hires_steps, shared.opts.use_old_scheduling) - - for cache in caches: - if cache[0] is not None and cached_params == cache[0]: - return cache[1] - - cache = caches[0] - - with devices.autocast(): - cache[1] = function(shared.sd_model, required_prompts, steps, hires_steps, shared.opts.use_old_scheduling) - - cache[0] = cached_params - return cache[1] - - def setup_conds(self): - prompts = prompt_parser.SdConditioning(self.prompts, width=self.width, height=self.height) - negative_prompts = prompt_parser.SdConditioning(self.negative_prompts, width=self.width, height=self.height, is_negative_prompt=True) - - sampler_config = sd_samplers.find_sampler_config(self.sampler_name) - total_steps = sampler_config.total_steps(self.steps) if sampler_config else self.steps - self.step_multiplier = total_steps // self.steps - self.firstpass_steps = total_steps - - self.uc = self.get_conds_with_caching(prompt_parser.get_learned_conditioning, negative_prompts, total_steps, [self.cached_uc], self.extra_network_data) - self.c = self.get_conds_with_caching(prompt_parser.get_multicond_learned_conditioning, prompts, total_steps, [self.cached_c], self.extra_network_data) - - def get_conds(self): - return self.c, self.uc - - def parse_extra_network_prompts(self): - self.prompts, self.extra_network_data = extra_networks.parse_prompts(self.prompts) - - def save_samples(self) -> bool: - return opts.samples_save and not self.do_not_save_samples and (opts.save_incomplete_images or not state.interrupted and not state.skipped) - - -class Processed: - def __init__(self, p: StableDiffusionProcessing, images_list, seed=-1, info="", subseed=None, all_prompts=None, all_negative_prompts=None, all_seeds=None, all_subseeds=None, index_of_first_image=0, infotexts=None, comments=""): - self.images = images_list - self.prompt = p.prompt - self.negative_prompt = p.negative_prompt - self.seed = seed - self.subseed = subseed - self.subseed_strength = p.subseed_strength - self.info = info - self.comments = "".join(f"{comment}\n" for comment in p.comments) - self.width = p.width - self.height = p.height - self.sampler_name = p.sampler_name - self.cfg_scale = p.cfg_scale - self.image_cfg_scale = getattr(p, 'image_cfg_scale', None) - self.steps = p.steps - self.batch_size = p.batch_size - self.restore_faces = p.restore_faces - self.face_restoration_model = opts.face_restoration_model if p.restore_faces else None - self.sd_model_name = p.sd_model_name - self.sd_model_hash = p.sd_model_hash - self.sd_vae_name = p.sd_vae_name - self.sd_vae_hash = p.sd_vae_hash - self.seed_resize_from_w = p.seed_resize_from_w - self.seed_resize_from_h = p.seed_resize_from_h - self.denoising_strength = getattr(p, 'denoising_strength', None) - self.extra_generation_params = p.extra_generation_params - self.index_of_first_image = index_of_first_image - self.styles = p.styles - self.job_timestamp = state.job_timestamp - self.clip_skip = opts.CLIP_stop_at_last_layers - self.token_merging_ratio = p.token_merging_ratio - self.token_merging_ratio_hr = p.token_merging_ratio_hr - - self.eta = p.eta - self.ddim_discretize = p.ddim_discretize - self.s_churn = p.s_churn - self.s_tmin = p.s_tmin - self.s_tmax = p.s_tmax - self.s_noise = p.s_noise - self.s_min_uncond = p.s_min_uncond - self.sampler_noise_scheduler_override = p.sampler_noise_scheduler_override - self.prompt = self.prompt if not isinstance(self.prompt, list) else self.prompt[0] - self.negative_prompt = self.negative_prompt if not isinstance(self.negative_prompt, list) else self.negative_prompt[0] - self.seed = int(self.seed if not isinstance(self.seed, list) else self.seed[0]) if self.seed is not None else -1 - self.subseed = int(self.subseed if not isinstance(self.subseed, list) else self.subseed[0]) if self.subseed is not None else -1 - self.is_using_inpainting_conditioning = p.is_using_inpainting_conditioning - - self.all_prompts = all_prompts or p.all_prompts or [self.prompt] - self.all_negative_prompts = all_negative_prompts or p.all_negative_prompts or [self.negative_prompt] - self.all_seeds = all_seeds or p.all_seeds or [self.seed] - self.all_subseeds = all_subseeds or p.all_subseeds or [self.subseed] - self.infotexts = infotexts or [info] * len(images_list) - self.version = program_version() - - def js(self): - obj = { - "prompt": self.all_prompts[0], - "all_prompts": self.all_prompts, - "negative_prompt": self.all_negative_prompts[0], - "all_negative_prompts": self.all_negative_prompts, - "seed": self.seed, - "all_seeds": self.all_seeds, - "subseed": self.subseed, - "all_subseeds": self.all_subseeds, - "subseed_strength": self.subseed_strength, - "width": self.width, - "height": self.height, - "sampler_name": self.sampler_name, - "cfg_scale": self.cfg_scale, - "steps": self.steps, - "batch_size": self.batch_size, - "restore_faces": self.restore_faces, - "face_restoration_model": self.face_restoration_model, - "sd_model_name": self.sd_model_name, - "sd_model_hash": self.sd_model_hash, - "sd_vae_name": self.sd_vae_name, - "sd_vae_hash": self.sd_vae_hash, - "seed_resize_from_w": self.seed_resize_from_w, - "seed_resize_from_h": self.seed_resize_from_h, - "denoising_strength": self.denoising_strength, - "extra_generation_params": self.extra_generation_params, - "index_of_first_image": self.index_of_first_image, - "infotexts": self.infotexts, - "styles": self.styles, - "job_timestamp": self.job_timestamp, - "clip_skip": self.clip_skip, - "is_using_inpainting_conditioning": self.is_using_inpainting_conditioning, - "version": self.version, - } - - return json.dumps(obj, default=lambda o: None) - - def infotext(self, p: StableDiffusionProcessing, index): - return create_infotext(p, self.all_prompts, self.all_seeds, self.all_subseeds, comments=[], position_in_batch=index % self.batch_size, iteration=index // self.batch_size) - - def get_token_merging_ratio(self, for_hr=False): - return self.token_merging_ratio_hr if for_hr else self.token_merging_ratio - - -def create_random_tensors(shape, seeds, subseeds=None, subseed_strength=0.0, seed_resize_from_h=0, seed_resize_from_w=0, p=None): - g = rng.ImageRNG(shape, seeds, subseeds=subseeds, subseed_strength=subseed_strength, seed_resize_from_h=seed_resize_from_h, seed_resize_from_w=seed_resize_from_w) - return g.next() - - -class DecodedSamples(list): - already_decoded = True - - -def decode_latent_batch(model, batch, target_device=None, check_for_nans=False): - samples = DecodedSamples() - - if check_for_nans: - devices.test_for_nans(batch, "unet") - - for i in range(batch.shape[0]): - sample = decode_first_stage(model, batch[i:i + 1])[0] - - if check_for_nans: - - try: - devices.test_for_nans(sample, "vae") - except devices.NansException as e: - if shared.opts.auto_vae_precision_bfloat16: - autofix_dtype = torch.bfloat16 - autofix_dtype_text = "bfloat16" - autofix_dtype_setting = "Automatically convert VAE to bfloat16" - autofix_dtype_comment = "" - elif shared.opts.auto_vae_precision: - autofix_dtype = torch.float32 - autofix_dtype_text = "32-bit float" - autofix_dtype_setting = "Automatically revert VAE to 32-bit floats" - autofix_dtype_comment = "\nTo always start with 32-bit VAE, use --no-half-vae commandline flag." - else: - raise e - - if devices.dtype_vae == autofix_dtype: - raise e - - errors.print_error_explanation( - "A tensor with all NaNs was produced in VAE.\n" - f"Web UI will now convert VAE into {autofix_dtype_text} and retry.\n" - f"To disable this behavior, disable the '{autofix_dtype_setting}' setting.{autofix_dtype_comment}" - ) - - devices.dtype_vae = autofix_dtype - model.first_stage_model.to(devices.dtype_vae) - batch = batch.to(devices.dtype_vae) - - sample = decode_first_stage(model, batch[i:i + 1])[0] - - if target_device is not None: - sample = sample.to(target_device) - - samples.append(sample) - - return samples - - -def get_fixed_seed(seed): - if seed == '' or seed is None: - seed = -1 - elif isinstance(seed, str): - try: - seed = int(seed) - except Exception: - seed = -1 - - if seed == -1: - return int(random.randrange(4294967294)) - - return seed - - -def fix_seed(p): - p.seed = get_fixed_seed(p.seed) - p.subseed = get_fixed_seed(p.subseed) - - -def program_version(): - import launch - - res = launch.git_tag() - if res == "<none>": - res = None - - return res - - -def create_infotext(p, all_prompts, all_seeds, all_subseeds, comments=None, iteration=0, position_in_batch=0, use_main_prompt=False, index=None, all_negative_prompts=None): - - if use_main_prompt: - index = 0 - elif index is None: - index = position_in_batch + iteration * p.batch_size - - if all_negative_prompts is None: - all_negative_prompts = p.all_negative_prompts - - clip_skip = getattr(p, 'clip_skip', opts.CLIP_stop_at_last_layers) - enable_hr = getattr(p, 'enable_hr', False) - token_merging_ratio = p.get_token_merging_ratio() - token_merging_ratio_hr = p.get_token_merging_ratio(for_hr=True) - - prompt_text = p.main_prompt if use_main_prompt else all_prompts[index] - negative_prompt = p.main_negative_prompt if use_main_prompt else all_negative_prompts[index] - - uses_ensd = opts.eta_noise_seed_delta != 0 - if uses_ensd: - uses_ensd = sd_samplers_common.is_sampler_using_eta_noise_seed_delta(p) - - generation_params = { - "Steps": p.steps, - "Sampler": p.sampler_name, - "Schedule type": p.scheduler, - "CFG scale": p.cfg_scale, - "Image CFG scale": getattr(p, 'image_cfg_scale', None), - "Seed": p.all_seeds[0] if use_main_prompt else all_seeds[index], - "Face restoration": opts.face_restoration_model if p.restore_faces else None, - "Size": f"{p.width}x{p.height}", - "Model hash": p.sd_model_hash if opts.add_model_hash_to_info else None, - "Model": p.sd_model_name if opts.add_model_name_to_info else None, - "FP8 weight": opts.fp8_storage if devices.fp8 else None, - "Cache FP16 weight for LoRA": opts.cache_fp16_weight if devices.fp8 else None, - "VAE hash": p.sd_vae_hash if opts.add_vae_hash_to_info else None, - "VAE": p.sd_vae_name if opts.add_vae_name_to_info else None, - "Variation seed": (None if p.subseed_strength == 0 else (p.all_subseeds[0] if use_main_prompt else all_subseeds[index])), - "Variation seed strength": (None if p.subseed_strength == 0 else p.subseed_strength), - "Seed resize from": (None if p.seed_resize_from_w <= 0 or p.seed_resize_from_h <= 0 else f"{p.seed_resize_from_w}x{p.seed_resize_from_h}"), - "Denoising strength": p.extra_generation_params.get("Denoising strength"), - "Conditional mask weight": getattr(p, "inpainting_mask_weight", shared.opts.inpainting_mask_weight) if p.is_using_inpainting_conditioning else None, - "Clip skip": None if clip_skip <= 1 else clip_skip, - "ENSD": opts.eta_noise_seed_delta if uses_ensd else None, - "Token merging ratio": None if token_merging_ratio == 0 else token_merging_ratio, - "Token merging ratio hr": None if not enable_hr or token_merging_ratio_hr == 0 else token_merging_ratio_hr, - "Init image hash": getattr(p, 'init_img_hash', None), - "RNG": opts.randn_source if opts.randn_source != "GPU" else None, - "Tiling": "True" if p.tiling else None, - **p.extra_generation_params, - "Version": program_version() if opts.add_version_to_infotext else None, - "User": p.user if opts.add_user_name_to_info else None, - } - - for key, value in generation_params.items(): - try: - if isinstance(value, list): - generation_params[key] = value[index] - elif callable(value): - generation_params[key] = value(**locals()) - except Exception: - errors.report(f'Error creating infotext for key "{key}"', exc_info=True) - generation_params[key] = None - - generation_params_text = ", ".join([k if k == v else f'{k}: {infotext_utils.quote(v)}' for k, v in generation_params.items() if v is not None]) - - negative_prompt_text = f"\nNegative prompt: {negative_prompt}" if negative_prompt else "" - - return f"{prompt_text}{negative_prompt_text}\n{generation_params_text}".strip() - - -def process_images(p: StableDiffusionProcessing) -> Processed: - if p.scripts is not None: - p.scripts.before_process(p) - - stored_opts = {k: opts.data[k] if k in opts.data else opts.get_default(k) for k in p.override_settings.keys() if k in opts.data} - - try: - # if no checkpoint override or the override checkpoint can't be found, remove override entry and load opts checkpoint - # and if after running refiner, the refiner model is not unloaded - webui swaps back to main model here, if model over is present it will be reloaded afterwards - if sd_models.checkpoint_aliases.get(p.override_settings.get('sd_model_checkpoint')) is None: - p.override_settings.pop('sd_model_checkpoint', None) - sd_models.reload_model_weights() - - for k, v in p.override_settings.items(): - opts.set(k, v, is_api=True, run_callbacks=False) - - if k == 'sd_model_checkpoint': - sd_models.reload_model_weights() - - if k == 'sd_vae': - sd_vae.reload_vae_weights() - - sd_models.apply_token_merging(p.sd_model, p.get_token_merging_ratio()) - - # backwards compatibility, fix sampler and scheduler if invalid - sd_samplers.fix_p_invalid_sampler_and_scheduler(p) - - with profiling.Profiler(): - res = process_images_inner(p) - - finally: - sd_models.apply_token_merging(p.sd_model, 0) - - # restore opts to original state - if p.override_settings_restore_afterwards: - for k, v in stored_opts.items(): - setattr(opts, k, v) - - if k == 'sd_vae': - sd_vae.reload_vae_weights() - - return res - - -def process_images_inner(p: StableDiffusionProcessing) -> Processed: - - if isinstance(p.prompt, list): - assert(len(p.prompt) > 0) - else: - assert p.prompt is not None - - devices.torch_gc() - - seed = get_fixed_seed(p.seed) - subseed = get_fixed_seed(p.subseed) - - if p.restore_faces is None: - p.restore_faces = opts.face_restoration - - if p.tiling is None: - p.tiling = opts.tiling - - if p.refiner_checkpoint not in (None, "", "None", "none"): - p.refiner_checkpoint_info = sd_models.get_closet_checkpoint_match(p.refiner_checkpoint) - if p.refiner_checkpoint_info is None: - raise Exception(f'Could not find checkpoint with name {p.refiner_checkpoint}') - - if hasattr(shared.sd_model, 'fix_dimensions'): - p.width, p.height = shared.sd_model.fix_dimensions(p.width, p.height) - - p.sd_model_name = shared.sd_model.sd_checkpoint_info.name_for_extra - p.sd_model_hash = shared.sd_model.sd_model_hash - p.sd_vae_name = sd_vae.get_loaded_vae_name() - p.sd_vae_hash = sd_vae.get_loaded_vae_hash() - - modules.sd_hijack.model_hijack.apply_circular(p.tiling) - modules.sd_hijack.model_hijack.clear_comments() - - p.fill_fields_from_opts() - p.setup_prompts() - - if isinstance(seed, list): - p.all_seeds = seed - else: - p.all_seeds = [int(seed) + (x if p.subseed_strength == 0 else 0) for x in range(len(p.all_prompts))] - - if isinstance(subseed, list): - p.all_subseeds = subseed - else: - p.all_subseeds = [int(subseed) + x for x in range(len(p.all_prompts))] - - if os.path.exists(cmd_opts.embeddings_dir) and not p.do_not_reload_embeddings: - model_hijack.embedding_db.load_textual_inversion_embeddings() - - if p.scripts is not None: - p.scripts.process(p) - - infotexts = [] - output_images = [] - with torch.no_grad(), p.sd_model.ema_scope(): - with devices.autocast(): - p.init(p.all_prompts, p.all_seeds, p.all_subseeds) - - # for OSX, loading the model during sampling changes the generated picture, so it is loaded here - if shared.opts.live_previews_enable and opts.show_progress_type == "Approx NN": - sd_vae_approx.model() - - sd_unet.apply_unet() - - if state.job_count == -1: - state.job_count = p.n_iter - - for n in range(p.n_iter): - p.iteration = n - - if state.skipped: - state.skipped = False - - if state.interrupted or state.stopping_generation: - break - - sd_models.reload_model_weights() # model can be changed for example by refiner - - p.prompts = p.all_prompts[n * p.batch_size:(n + 1) * p.batch_size] - p.negative_prompts = p.all_negative_prompts[n * p.batch_size:(n + 1) * p.batch_size] - p.seeds = p.all_seeds[n * p.batch_size:(n + 1) * p.batch_size] - p.subseeds = p.all_subseeds[n * p.batch_size:(n + 1) * p.batch_size] - - latent_channels = getattr(shared.sd_model, 'latent_channels', opt_C) - p.rng = rng.ImageRNG((latent_channels, p.height // opt_f, p.width // opt_f), p.seeds, subseeds=p.subseeds, subseed_strength=p.subseed_strength, seed_resize_from_h=p.seed_resize_from_h, seed_resize_from_w=p.seed_resize_from_w) - - if p.scripts is not None: - p.scripts.before_process_batch(p, batch_number=n, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds) - - if len(p.prompts) == 0: - break - - p.parse_extra_network_prompts() - - if not p.disable_extra_networks: - with devices.autocast(): - extra_networks.activate(p, p.extra_network_data) - - if p.scripts is not None: - p.scripts.process_batch(p, batch_number=n, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds) - - p.setup_conds() - - p.extra_generation_params.update(model_hijack.extra_generation_params) - - # params.txt should be saved after scripts.process_batch, since the - # infotext could be modified by that callback - # Example: a wildcard processed by process_batch sets an extra model - # strength, which is saved as "Model Strength: 1.0" in the infotext - if n == 0 and not cmd_opts.no_prompt_history: - with open(os.path.join(paths.data_path, "params.txt"), "w", encoding="utf8") as file: - processed = Processed(p, []) - file.write(processed.infotext(p, 0)) - - for comment in model_hijack.comments: - p.comment(comment) - - if p.n_iter > 1: - shared.state.job = f"Batch {n+1} out of {p.n_iter}" - - sd_models.apply_alpha_schedule_override(p.sd_model, p) - - with devices.without_autocast() if devices.unet_needs_upcast else devices.autocast(): - samples_ddim = p.sample(conditioning=p.c, unconditional_conditioning=p.uc, seeds=p.seeds, subseeds=p.subseeds, subseed_strength=p.subseed_strength, prompts=p.prompts) - - if p.scripts is not None: - ps = scripts.PostSampleArgs(samples_ddim) - p.scripts.post_sample(p, ps) - samples_ddim = ps.samples - - if getattr(samples_ddim, 'already_decoded', False): - x_samples_ddim = samples_ddim - else: - devices.test_for_nans(samples_ddim, "unet") - - if opts.sd_vae_decode_method != 'Full': - p.extra_generation_params['VAE Decoder'] = opts.sd_vae_decode_method - x_samples_ddim = decode_latent_batch(p.sd_model, samples_ddim, target_device=devices.cpu, check_for_nans=True) - - x_samples_ddim = torch.stack(x_samples_ddim).float() - x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0) - - del samples_ddim - - if lowvram.is_enabled(shared.sd_model): - lowvram.send_everything_to_cpu() - - devices.torch_gc() - - state.nextjob() - - if p.scripts is not None: - p.scripts.postprocess_batch(p, x_samples_ddim, batch_number=n) - - p.prompts = p.all_prompts[n * p.batch_size:(n + 1) * p.batch_size] - p.negative_prompts = p.all_negative_prompts[n * p.batch_size:(n + 1) * p.batch_size] - - batch_params = scripts.PostprocessBatchListArgs(list(x_samples_ddim)) - p.scripts.postprocess_batch_list(p, batch_params, batch_number=n) - x_samples_ddim = batch_params.images - - def infotext(index=0, use_main_prompt=False): - return create_infotext(p, p.prompts, p.seeds, p.subseeds, use_main_prompt=use_main_prompt, index=index, all_negative_prompts=p.negative_prompts) - - save_samples = p.save_samples() - - for i, x_sample in enumerate(x_samples_ddim): - p.batch_index = i - - x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2) - x_sample = x_sample.astype(np.uint8) - - if p.restore_faces: - if save_samples and opts.save_images_before_face_restoration: - images.save_image(Image.fromarray(x_sample), p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-before-face-restoration") - - devices.torch_gc() - - x_sample = modules.face_restoration.restore_faces(x_sample) - devices.torch_gc() - - image = Image.fromarray(x_sample) - - if p.scripts is not None: - pp = scripts.PostprocessImageArgs(image) - p.scripts.postprocess_image(p, pp) - image = pp.image - - mask_for_overlay = getattr(p, "mask_for_overlay", None) - - if not shared.opts.overlay_inpaint: - overlay_image = None - elif getattr(p, "overlay_images", None) is not None and i < len(p.overlay_images): - overlay_image = p.overlay_images[i] - else: - overlay_image = None - - if p.scripts is not None: - ppmo = scripts.PostProcessMaskOverlayArgs(i, mask_for_overlay, overlay_image) - p.scripts.postprocess_maskoverlay(p, ppmo) - mask_for_overlay, overlay_image = ppmo.mask_for_overlay, ppmo.overlay_image - - if p.color_corrections is not None and i < len(p.color_corrections): - if save_samples and opts.save_images_before_color_correction: - image_without_cc, _ = apply_overlay(image, p.paste_to, overlay_image) - images.save_image(image_without_cc, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-before-color-correction") - image = apply_color_correction(p.color_corrections[i], image) - - # If the intention is to show the output from the model - # that is being composited over the original image, - # we need to keep the original image around - # and use it in the composite step. - image, original_denoised_image = apply_overlay(image, p.paste_to, overlay_image) - - if p.scripts is not None: - pp = scripts.PostprocessImageArgs(image) - p.scripts.postprocess_image_after_composite(p, pp) - image = pp.image - - if save_samples: - images.save_image(image, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p) - - text = infotext(i) - infotexts.append(text) - if opts.enable_pnginfo: - image.info["parameters"] = text - output_images.append(image) - - if mask_for_overlay is not None: - if opts.return_mask or opts.save_mask: - image_mask = mask_for_overlay.convert('RGB') - if save_samples and opts.save_mask: - images.save_image(image_mask, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-mask") - if opts.return_mask: - output_images.append(image_mask) - - if opts.return_mask_composite or opts.save_mask_composite: - image_mask_composite = Image.composite(original_denoised_image.convert('RGBA').convert('RGBa'), Image.new('RGBa', image.size), images.resize_image(2, mask_for_overlay, image.width, image.height).convert('L')).convert('RGBA') - if save_samples and opts.save_mask_composite: - images.save_image(image_mask_composite, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-mask-composite") - if opts.return_mask_composite: - output_images.append(image_mask_composite) - - del x_samples_ddim - - devices.torch_gc() - - if not infotexts: - infotexts.append(Processed(p, []).infotext(p, 0)) - - p.color_corrections = None - - index_of_first_image = 0 - unwanted_grid_because_of_img_count = len(output_images) < 2 and opts.grid_only_if_multiple - if (opts.return_grid or opts.grid_save) and not p.do_not_save_grid and not unwanted_grid_because_of_img_count: - grid = images.image_grid(output_images, p.batch_size) - - if opts.return_grid: - text = infotext(use_main_prompt=True) - infotexts.insert(0, text) - if opts.enable_pnginfo: - grid.info["parameters"] = text - output_images.insert(0, grid) - index_of_first_image = 1 - if opts.grid_save: - images.save_image(grid, p.outpath_grids, "grid", p.all_seeds[0], p.all_prompts[0], opts.grid_format, info=infotext(use_main_prompt=True), short_filename=not opts.grid_extended_filename, p=p, grid=True) - - if not p.disable_extra_networks and p.extra_network_data: - extra_networks.deactivate(p, p.extra_network_data) - - devices.torch_gc() - - res = Processed( - p, - images_list=output_images, - seed=p.all_seeds[0], - info=infotexts[0], - subseed=p.all_subseeds[0], - index_of_first_image=index_of_first_image, - infotexts=infotexts, - ) - - if p.scripts is not None: - p.scripts.postprocess(p, res) - - return res - - -def old_hires_fix_first_pass_dimensions(width, height): - - desired_pixel_count = 512 * 512 - actual_pixel_count = width * height - scale = math.sqrt(desired_pixel_count / actual_pixel_count) - width = math.ceil(scale * width / 64) * 64 - height = math.ceil(scale * height / 64) * 64 - - return width, height - - -@dataclass(repr=False) -class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing): - enable_hr: bool = False - denoising_strength: float = 0.75 - firstphase_width: int = 0 - firstphase_height: int = 0 - hr_scale: float = 2.0 - hr_upscaler: str = None - hr_second_pass_steps: int = 0 - hr_resize_x: int = 0 - hr_resize_y: int = 0 - hr_checkpoint_name: str = None - hr_sampler_name: str = None - hr_scheduler: str = None - hr_prompt: str = '' - hr_negative_prompt: str = '' - force_task_id: str = None - - cached_hr_uc = [None, None] - cached_hr_c = [None, None] - - hr_checkpoint_info: dict = field(default=None, init=False) - hr_upscale_to_x: int = field(default=0, init=False) - hr_upscale_to_y: int = field(default=0, init=False) - truncate_x: int = field(default=0, init=False) - truncate_y: int = field(default=0, init=False) - applied_old_hires_behavior_to: tuple = field(default=None, init=False) - latent_scale_mode: dict = field(default=None, init=False) - hr_c: tuple | None = field(default=None, init=False) - hr_uc: tuple | None = field(default=None, init=False) - all_hr_prompts: list = field(default=None, init=False) - all_hr_negative_prompts: list = field(default=None, init=False) - hr_prompts: list = field(default=None, init=False) - hr_negative_prompts: list = field(default=None, init=False) - hr_extra_network_data: list = field(default=None, init=False) - - def __post_init__(self): - super().__post_init__() - - if self.firstphase_width != 0 or self.firstphase_height != 0: - self.hr_upscale_to_x = self.width - self.hr_upscale_to_y = self.height - self.width = self.firstphase_width - self.height = self.firstphase_height - - self.cached_hr_uc = StableDiffusionProcessingTxt2Img.cached_hr_uc - self.cached_hr_c = StableDiffusionProcessingTxt2Img.cached_hr_c - - def calculate_target_resolution(self): - if opts.use_old_hires_fix_width_height and self.applied_old_hires_behavior_to != (self.width, self.height): - self.hr_resize_x = self.width - self.hr_resize_y = self.height - self.hr_upscale_to_x = self.width - self.hr_upscale_to_y = self.height - - self.width, self.height = old_hires_fix_first_pass_dimensions(self.width, self.height) - self.applied_old_hires_behavior_to = (self.width, self.height) - - if self.hr_resize_x == 0 and self.hr_resize_y == 0: - self.extra_generation_params["Hires upscale"] = self.hr_scale - self.hr_upscale_to_x = int(self.width * self.hr_scale) - self.hr_upscale_to_y = int(self.height * self.hr_scale) - else: - self.extra_generation_params["Hires resize"] = f"{self.hr_resize_x}x{self.hr_resize_y}" - - if self.hr_resize_y == 0: - self.hr_upscale_to_x = self.hr_resize_x - self.hr_upscale_to_y = self.hr_resize_x * self.height // self.width - elif self.hr_resize_x == 0: - self.hr_upscale_to_x = self.hr_resize_y * self.width // self.height - self.hr_upscale_to_y = self.hr_resize_y - else: - target_w = self.hr_resize_x - target_h = self.hr_resize_y - src_ratio = self.width / self.height - dst_ratio = self.hr_resize_x / self.hr_resize_y - - if src_ratio < dst_ratio: - self.hr_upscale_to_x = self.hr_resize_x - self.hr_upscale_to_y = self.hr_resize_x * self.height // self.width - else: - self.hr_upscale_to_x = self.hr_resize_y * self.width // self.height - self.hr_upscale_to_y = self.hr_resize_y - - self.truncate_x = (self.hr_upscale_to_x - target_w) // opt_f - self.truncate_y = (self.hr_upscale_to_y - target_h) // opt_f - - def init(self, all_prompts, all_seeds, all_subseeds): - if self.enable_hr: - self.extra_generation_params["Denoising strength"] = self.denoising_strength - - if self.hr_checkpoint_name and self.hr_checkpoint_name != 'Use same checkpoint': - self.hr_checkpoint_info = sd_models.get_closet_checkpoint_match(self.hr_checkpoint_name) - - if self.hr_checkpoint_info is None: - raise Exception(f'Could not find checkpoint with name {self.hr_checkpoint_name}') - - self.extra_generation_params["Hires checkpoint"] = self.hr_checkpoint_info.short_title - - if self.hr_sampler_name is not None and self.hr_sampler_name != self.sampler_name: - self.extra_generation_params["Hires sampler"] = self.hr_sampler_name - - def get_hr_prompt(p, index, prompt_text, **kwargs): - hr_prompt = p.all_hr_prompts[index] - return hr_prompt if hr_prompt != prompt_text else None - - def get_hr_negative_prompt(p, index, negative_prompt, **kwargs): - hr_negative_prompt = p.all_hr_negative_prompts[index] - return hr_negative_prompt if hr_negative_prompt != negative_prompt else None - - self.extra_generation_params["Hires prompt"] = get_hr_prompt - self.extra_generation_params["Hires negative prompt"] = get_hr_negative_prompt - - self.extra_generation_params["Hires schedule type"] = None # to be set in sd_samplers_kdiffusion.py - - if self.hr_scheduler is None: - self.hr_scheduler = self.scheduler - - self.latent_scale_mode = shared.latent_upscale_modes.get(self.hr_upscaler, None) if self.hr_upscaler is not None else shared.latent_upscale_modes.get(shared.latent_upscale_default_mode, "nearest") - if self.enable_hr and self.latent_scale_mode is None: - if not any(x.name == self.hr_upscaler for x in shared.sd_upscalers): - raise Exception(f"could not find upscaler named {self.hr_upscaler}") - - self.calculate_target_resolution() - - if not state.processing_has_refined_job_count: - if state.job_count == -1: - state.job_count = self.n_iter - if getattr(self, 'txt2img_upscale', False): - total_steps = (self.hr_second_pass_steps or self.steps) * state.job_count - else: - total_steps = (self.steps + (self.hr_second_pass_steps or self.steps)) * state.job_count - shared.total_tqdm.updateTotal(total_steps) - state.job_count = state.job_count * 2 - state.processing_has_refined_job_count = True - - if self.hr_second_pass_steps: - self.extra_generation_params["Hires steps"] = self.hr_second_pass_steps - - if self.hr_upscaler is not None: - self.extra_generation_params["Hires upscaler"] = self.hr_upscaler - - def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts): - self.sampler = sd_samplers.create_sampler(self.sampler_name, self.sd_model) - - if self.firstpass_image is not None and self.enable_hr: - # here we don't need to generate image, we just take self.firstpass_image and prepare it for hires fix - - if self.latent_scale_mode is None: - image = np.array(self.firstpass_image).astype(np.float32) / 255.0 * 2.0 - 1.0 - image = np.moveaxis(image, 2, 0) - - samples = None - decoded_samples = torch.asarray(np.expand_dims(image, 0)) - - else: - image = np.array(self.firstpass_image).astype(np.float32) / 255.0 - image = np.moveaxis(image, 2, 0) - image = torch.from_numpy(np.expand_dims(image, axis=0)) - image = image.to(shared.device, dtype=devices.dtype_vae) - - if opts.sd_vae_encode_method != 'Full': - self.extra_generation_params['VAE Encoder'] = opts.sd_vae_encode_method - - samples = images_tensor_to_samples(image, approximation_indexes.get(opts.sd_vae_encode_method), self.sd_model) - decoded_samples = None - devices.torch_gc() - - else: - # here we generate an image normally - - x = self.rng.next() - if self.scripts is not None: - self.scripts.process_before_every_sampling( - p=self, - x=x, - noise=x, - c=conditioning, - uc=unconditional_conditioning - ) - - samples = self.sampler.sample(self, x, conditioning, unconditional_conditioning, image_conditioning=self.txt2img_image_conditioning(x)) - del x - - if not self.enable_hr: - return samples - - devices.torch_gc() - - if self.latent_scale_mode is None: - decoded_samples = torch.stack(decode_latent_batch(self.sd_model, samples, target_device=devices.cpu, check_for_nans=True)).to(dtype=torch.float32) - else: - decoded_samples = None - - with sd_models.SkipWritingToConfig(): - sd_models.reload_model_weights(info=self.hr_checkpoint_info) - - return self.sample_hr_pass(samples, decoded_samples, seeds, subseeds, subseed_strength, prompts) - - def sample_hr_pass(self, samples, decoded_samples, seeds, subseeds, subseed_strength, prompts): - if shared.state.interrupted: - return samples - - self.is_hr_pass = True - target_width = self.hr_upscale_to_x - target_height = self.hr_upscale_to_y - - def save_intermediate(image, index): - - if not self.save_samples() or not opts.save_images_before_highres_fix: - return - - if not isinstance(image, Image.Image): - image = sd_samplers.sample_to_image(image, index, approximation=0) - - info = create_infotext(self, self.all_prompts, self.all_seeds, self.all_subseeds, [], iteration=self.iteration, position_in_batch=index) - images.save_image(image, self.outpath_samples, "", seeds[index], prompts[index], opts.samples_format, info=info, p=self, suffix="-before-highres-fix") - - img2img_sampler_name = self.hr_sampler_name or self.sampler_name - - self.sampler = sd_samplers.create_sampler(img2img_sampler_name, self.sd_model) - - if self.latent_scale_mode is not None: - for i in range(samples.shape[0]): - save_intermediate(samples, i) - - samples = torch.nn.functional.interpolate(samples, size=(target_height // opt_f, target_width // opt_f), mode=self.latent_scale_mode["mode"], antialias=self.latent_scale_mode["antialias"]) - - # Avoid making the inpainting conditioning unless necessary as - # this does need some extra compute to decode / encode the image again. - if getattr(self, "inpainting_mask_weight", shared.opts.inpainting_mask_weight) < 1.0: - image_conditioning = self.img2img_image_conditioning(decode_first_stage(self.sd_model, samples), samples) - else: - image_conditioning = self.txt2img_image_conditioning(samples) - else: - lowres_samples = torch.clamp((decoded_samples + 1.0) / 2.0, min=0.0, max=1.0) - - batch_images = [] - for i, x_sample in enumerate(lowres_samples): - x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2) - x_sample = x_sample.astype(np.uint8) - image = Image.fromarray(x_sample) - - save_intermediate(image, i) - - image = images.resize_image(0, image, target_width, target_height, upscaler_name=self.hr_upscaler) - image = np.array(image).astype(np.float32) / 255.0 - image = np.moveaxis(image, 2, 0) - batch_images.append(image) - - decoded_samples = torch.from_numpy(np.array(batch_images)) - decoded_samples = decoded_samples.to(shared.device, dtype=devices.dtype_vae) - - if opts.sd_vae_encode_method != 'Full': - self.extra_generation_params['VAE Encoder'] = opts.sd_vae_encode_method - samples = images_tensor_to_samples(decoded_samples, approximation_indexes.get(opts.sd_vae_encode_method)) - - image_conditioning = self.img2img_image_conditioning(decoded_samples, samples) - - shared.state.nextjob() - - samples = samples[:, :, self.truncate_y//2:samples.shape[2]-(self.truncate_y+1)//2, self.truncate_x//2:samples.shape[3]-(self.truncate_x+1)//2] - - self.rng = rng.ImageRNG(samples.shape[1:], self.seeds, subseeds=self.subseeds, subseed_strength=self.subseed_strength, seed_resize_from_h=self.seed_resize_from_h, seed_resize_from_w=self.seed_resize_from_w) - noise = self.rng.next() - - # GC now before running the next img2img to prevent running out of memory - devices.torch_gc() - - if not self.disable_extra_networks: - with devices.autocast(): - extra_networks.activate(self, self.hr_extra_network_data) - - with devices.autocast(): - self.calculate_hr_conds() - - sd_models.apply_token_merging(self.sd_model, self.get_token_merging_ratio(for_hr=True)) - - if self.scripts is not None: - self.scripts.before_hr(self) - self.scripts.process_before_every_sampling( - p=self, - x=samples, - noise=noise, - c=self.hr_c, - uc=self.hr_uc, - ) - - samples = self.sampler.sample_img2img(self, samples, noise, self.hr_c, self.hr_uc, steps=self.hr_second_pass_steps or self.steps, image_conditioning=image_conditioning) - - sd_models.apply_token_merging(self.sd_model, self.get_token_merging_ratio()) - - self.sampler = None - devices.torch_gc() - - decoded_samples = decode_latent_batch(self.sd_model, samples, target_device=devices.cpu, check_for_nans=True) - - self.is_hr_pass = False - return decoded_samples - - def close(self): - super().close() - self.hr_c = None - self.hr_uc = None - if not opts.persistent_cond_cache: - StableDiffusionProcessingTxt2Img.cached_hr_uc = [None, None] - StableDiffusionProcessingTxt2Img.cached_hr_c = [None, None] - - def setup_prompts(self): - super().setup_prompts() - - if not self.enable_hr: - return - - if self.hr_prompt == '': - self.hr_prompt = self.prompt - - if self.hr_negative_prompt == '': - self.hr_negative_prompt = self.negative_prompt - - if isinstance(self.hr_prompt, list): - self.all_hr_prompts = self.hr_prompt - else: - self.all_hr_prompts = self.batch_size * self.n_iter * [self.hr_prompt] - - if isinstance(self.hr_negative_prompt, list): - self.all_hr_negative_prompts = self.hr_negative_prompt - else: - self.all_hr_negative_prompts = self.batch_size * self.n_iter * [self.hr_negative_prompt] - - self.all_hr_prompts = [shared.prompt_styles.apply_styles_to_prompt(x, self.styles) for x in self.all_hr_prompts] - self.all_hr_negative_prompts = [shared.prompt_styles.apply_negative_styles_to_prompt(x, self.styles) for x in self.all_hr_negative_prompts] - - def calculate_hr_conds(self): - if self.hr_c is not None: - return - - hr_prompts = prompt_parser.SdConditioning(self.hr_prompts, width=self.hr_upscale_to_x, height=self.hr_upscale_to_y) - hr_negative_prompts = prompt_parser.SdConditioning(self.hr_negative_prompts, width=self.hr_upscale_to_x, height=self.hr_upscale_to_y, is_negative_prompt=True) - - sampler_config = sd_samplers.find_sampler_config(self.hr_sampler_name or self.sampler_name) - steps = self.hr_second_pass_steps or self.steps - total_steps = sampler_config.total_steps(steps) if sampler_config else steps - - self.hr_uc = self.get_conds_with_caching(prompt_parser.get_learned_conditioning, hr_negative_prompts, self.firstpass_steps, [self.cached_hr_uc, self.cached_uc], self.hr_extra_network_data, total_steps) - self.hr_c = self.get_conds_with_caching(prompt_parser.get_multicond_learned_conditioning, hr_prompts, self.firstpass_steps, [self.cached_hr_c, self.cached_c], self.hr_extra_network_data, total_steps) - - def setup_conds(self): - if self.is_hr_pass: - # if we are in hr pass right now, the call is being made from the refiner, and we don't need to setup firstpass cons or switch model - self.hr_c = None - self.calculate_hr_conds() - return - - super().setup_conds() - - self.hr_uc = None - self.hr_c = None - - if self.enable_hr and self.hr_checkpoint_info is None: - if shared.opts.hires_fix_use_firstpass_conds: - self.calculate_hr_conds() - - elif lowvram.is_enabled(shared.sd_model) and shared.sd_model.sd_checkpoint_info == sd_models.select_checkpoint(): # if in lowvram mode, we need to calculate conds right away, before the cond NN is unloaded - with devices.autocast(): - extra_networks.activate(self, self.hr_extra_network_data) - - self.calculate_hr_conds() - - with devices.autocast(): - extra_networks.activate(self, self.extra_network_data) - - def get_conds(self): - if self.is_hr_pass: - return self.hr_c, self.hr_uc - - return super().get_conds() - - def parse_extra_network_prompts(self): - res = super().parse_extra_network_prompts() - - if self.enable_hr: - self.hr_prompts = self.all_hr_prompts[self.iteration * self.batch_size:(self.iteration + 1) * self.batch_size] - self.hr_negative_prompts = self.all_hr_negative_prompts[self.iteration * self.batch_size:(self.iteration + 1) * self.batch_size] - - self.hr_prompts, self.hr_extra_network_data = extra_networks.parse_prompts(self.hr_prompts) - - return res - - -@dataclass(repr=False) -class StableDiffusionProcessingImg2Img(StableDiffusionProcessing): - init_images: list = None - resize_mode: int = 0 - denoising_strength: float = 0.75 - image_cfg_scale: float = None - mask: Any = None - mask_blur_x: int = 4 - mask_blur_y: int = 4 - mask_blur: int = None - mask_round: bool = True - inpainting_fill: int = 0 - inpaint_full_res: bool = True - inpaint_full_res_padding: int = 0 - inpainting_mask_invert: int = 0 - initial_noise_multiplier: float = None - latent_mask: Image = None - force_task_id: str = None - - image_mask: Any = field(default=None, init=False) - - nmask: torch.Tensor = field(default=None, init=False) - image_conditioning: torch.Tensor = field(default=None, init=False) - init_img_hash: str = field(default=None, init=False) - mask_for_overlay: Image = field(default=None, init=False) - init_latent: torch.Tensor = field(default=None, init=False) - - def __post_init__(self): - super().__post_init__() - - self.image_mask = self.mask - self.mask = None - self.initial_noise_multiplier = opts.initial_noise_multiplier if self.initial_noise_multiplier is None else self.initial_noise_multiplier - - @property - def mask_blur(self): - if self.mask_blur_x == self.mask_blur_y: - return self.mask_blur_x - return None - - @mask_blur.setter - def mask_blur(self, value): - if isinstance(value, int): - self.mask_blur_x = value - self.mask_blur_y = value - - def init(self, all_prompts, all_seeds, all_subseeds): - self.extra_generation_params["Denoising strength"] = self.denoising_strength - - self.image_cfg_scale: float = self.image_cfg_scale if shared.sd_model.cond_stage_key == "edit" else None - - self.sampler = sd_samplers.create_sampler(self.sampler_name, self.sd_model) - crop_region = None - - image_mask = self.image_mask - - if image_mask is not None: - # image_mask is passed in as RGBA by Gradio to support alpha masks, - # but we still want to support binary masks. - image_mask = create_binary_mask(image_mask, round=self.mask_round) - - if self.inpainting_mask_invert: - image_mask = ImageOps.invert(image_mask) - self.extra_generation_params["Mask mode"] = "Inpaint not masked" - - if self.mask_blur_x > 0: - np_mask = np.array(image_mask) - kernel_size = 2 * int(2.5 * self.mask_blur_x + 0.5) + 1 - np_mask = cv2.GaussianBlur(np_mask, (kernel_size, 1), self.mask_blur_x) - image_mask = Image.fromarray(np_mask) - - if self.mask_blur_y > 0: - np_mask = np.array(image_mask) - kernel_size = 2 * int(2.5 * self.mask_blur_y + 0.5) + 1 - np_mask = cv2.GaussianBlur(np_mask, (1, kernel_size), self.mask_blur_y) - image_mask = Image.fromarray(np_mask) - - if self.mask_blur_x > 0 or self.mask_blur_y > 0: - self.extra_generation_params["Mask blur"] = self.mask_blur - - if self.inpaint_full_res: - self.mask_for_overlay = image_mask - mask = image_mask.convert('L') - crop_region = masking.get_crop_region_v2(mask, self.inpaint_full_res_padding) - if crop_region: - crop_region = masking.expand_crop_region(crop_region, self.width, self.height, mask.width, mask.height) - x1, y1, x2, y2 = crop_region - mask = mask.crop(crop_region) - image_mask = images.resize_image(2, mask, self.width, self.height) - self.paste_to = (x1, y1, x2-x1, y2-y1) - self.extra_generation_params["Inpaint area"] = "Only masked" - self.extra_generation_params["Masked area padding"] = self.inpaint_full_res_padding - else: - crop_region = None - image_mask = None - self.mask_for_overlay = None - self.inpaint_full_res = False - massage = 'Unable to perform "Inpaint Only mask" because mask is blank, switch to img2img mode.' - model_hijack.comments.append(massage) - logging.info(massage) - else: - image_mask = images.resize_image(self.resize_mode, image_mask, self.width, self.height) - np_mask = np.array(image_mask) - np_mask = np.clip((np_mask.astype(np.float32)) * 2, 0, 255).astype(np.uint8) - self.mask_for_overlay = Image.fromarray(np_mask) - - self.overlay_images = [] - - latent_mask = self.latent_mask if self.latent_mask is not None else image_mask - - add_color_corrections = opts.img2img_color_correction and self.color_corrections is None - if add_color_corrections: - self.color_corrections = [] - imgs = [] - for img in self.init_images: - - # Save init image - if opts.save_init_img: - self.init_img_hash = hashlib.md5(img.tobytes()).hexdigest() - images.save_image(img, path=opts.outdir_init_images, basename=None, forced_filename=self.init_img_hash, save_to_dirs=False, existing_info=img.info) - - image = images.flatten(img, opts.img2img_background_color) - - if crop_region is None and self.resize_mode != 3: - image = images.resize_image(self.resize_mode, image, self.width, self.height) - - if image_mask is not None: - if self.mask_for_overlay.size != (image.width, image.height): - self.mask_for_overlay = images.resize_image(self.resize_mode, self.mask_for_overlay, image.width, image.height) - image_masked = Image.new('RGBa', (image.width, image.height)) - image_masked.paste(image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(self.mask_for_overlay.convert('L'))) - - self.overlay_images.append(image_masked.convert('RGBA')) - - # crop_region is not None if we are doing inpaint full res - if crop_region is not None: - image = image.crop(crop_region) - image = images.resize_image(2, image, self.width, self.height) - - if image_mask is not None: - if self.inpainting_fill != 1: - image = masking.fill(image, latent_mask) - - if self.inpainting_fill == 0: - self.extra_generation_params["Masked content"] = 'fill' - - if add_color_corrections: - self.color_corrections.append(setup_color_correction(image)) - - image = np.array(image).astype(np.float32) / 255.0 - image = np.moveaxis(image, 2, 0) - - imgs.append(image) - - if len(imgs) == 1: - batch_images = np.expand_dims(imgs[0], axis=0).repeat(self.batch_size, axis=0) - if self.overlay_images is not None: - self.overlay_images = self.overlay_images * self.batch_size - - if self.color_corrections is not None and len(self.color_corrections) == 1: - self.color_corrections = self.color_corrections * self.batch_size - - elif len(imgs) <= self.batch_size: - self.batch_size = len(imgs) - batch_images = np.array(imgs) - else: - raise RuntimeError(f"bad number of images passed: {len(imgs)}; expecting {self.batch_size} or less") - - image = torch.from_numpy(batch_images) - image = image.to(shared.device, dtype=devices.dtype_vae) - - if opts.sd_vae_encode_method != 'Full': - self.extra_generation_params['VAE Encoder'] = opts.sd_vae_encode_method - - self.init_latent = images_tensor_to_samples(image, approximation_indexes.get(opts.sd_vae_encode_method), self.sd_model) - devices.torch_gc() - - if self.resize_mode == 3: - self.init_latent = torch.nn.functional.interpolate(self.init_latent, size=(self.height // opt_f, self.width // opt_f), mode="bilinear") - - if image_mask is not None: - init_mask = latent_mask - latmask = init_mask.convert('RGB').resize((self.init_latent.shape[3], self.init_latent.shape[2])) - latmask = np.moveaxis(np.array(latmask, dtype=np.float32), 2, 0) / 255 - latmask = latmask[0] - if self.mask_round: - latmask = np.around(latmask) - latmask = np.tile(latmask[None], (self.init_latent.shape[1], 1, 1)) - - self.mask = torch.asarray(1.0 - latmask).to(shared.device).type(devices.dtype) - self.nmask = torch.asarray(latmask).to(shared.device).type(devices.dtype) - - # this needs to be fixed to be done in sample() using actual seeds for batches - if self.inpainting_fill == 2: - self.init_latent = self.init_latent * self.mask + create_random_tensors(self.init_latent.shape[1:], all_seeds[0:self.init_latent.shape[0]]) * self.nmask - self.extra_generation_params["Masked content"] = 'latent noise' - - elif self.inpainting_fill == 3: - self.init_latent = self.init_latent * self.mask - self.extra_generation_params["Masked content"] = 'latent nothing' - - self.image_conditioning = self.img2img_image_conditioning(image * 2 - 1, self.init_latent, image_mask, self.mask_round) - - def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts): - x = self.rng.next() - - if self.initial_noise_multiplier != 1.0: - self.extra_generation_params["Noise multiplier"] = self.initial_noise_multiplier - x *= self.initial_noise_multiplier - - if self.scripts is not None: - self.scripts.process_before_every_sampling( - p=self, - x=self.init_latent, - noise=x, - c=conditioning, - uc=unconditional_conditioning - ) - samples = self.sampler.sample_img2img(self, self.init_latent, x, conditioning, unconditional_conditioning, image_conditioning=self.image_conditioning) - - if self.mask is not None: - blended_samples = samples * self.nmask + self.init_latent * self.mask - - if self.scripts is not None: - mba = scripts.MaskBlendArgs(samples, self.nmask, self.init_latent, self.mask, blended_samples) - self.scripts.on_mask_blend(self, mba) - blended_samples = mba.blended_latent - - samples = blended_samples - - del x - devices.torch_gc() - - return samples - - def get_token_merging_ratio(self, for_hr=False): - return self.token_merging_ratio or ("token_merging_ratio" in self.override_settings and opts.token_merging_ratio) or opts.token_merging_ratio_img2img or opts.token_merging_ratio+from __future__ import annotations +import json +import logging +import math +import os +import sys +import hashlib +from dataclasses import dataclass, field + +import torch +import numpy as np +from PIL import Image, ImageOps +import random +import cv2 +from skimage import exposure +from typing import Any + +import modules.sd_hijack +from modules import devices, prompt_parser, masking, sd_samplers, lowvram, infotext_utils, extra_networks, sd_vae_approx, scripts, sd_samplers_common, sd_unet, errors, rng, profiling +from modules.rng import slerp # noqa: F401 +from modules.sd_hijack import model_hijack +from modules.sd_samplers_common import images_tensor_to_samples, decode_first_stage, approximation_indexes +from modules.shared import opts, cmd_opts, state +import modules.shared as shared +import modules.paths as paths +import modules.face_restoration +import modules.images as images +import modules.styles +import modules.sd_models as sd_models +import modules.sd_vae as sd_vae +from ldm.data.util import AddMiDaS +from ldm.models.diffusion.ddpm import LatentDepth2ImageDiffusion + +from einops import repeat, rearrange +from blendmodes.blend import blendLayers, BlendType + + +# some of those options should not be changed at all because they would break the model, so I removed them from options. +opt_C = 4 +opt_f = 8 + + +def setup_color_correction(image): + logging.info("Calibrating color correction.") + correction_target = cv2.cvtColor(np.asarray(image.copy()), cv2.COLOR_RGB2LAB) + return correction_target + + +def apply_color_correction(correction, original_image): + logging.info("Applying color correction.") + image = Image.fromarray(cv2.cvtColor(exposure.match_histograms( + cv2.cvtColor( + np.asarray(original_image), + cv2.COLOR_RGB2LAB + ), + correction, + channel_axis=2 + ), cv2.COLOR_LAB2RGB).astype("uint8")) + + image = blendLayers(image, original_image, BlendType.LUMINOSITY) + + return image.convert('RGB') + + +def uncrop(image, dest_size, paste_loc): + x, y, w, h = paste_loc + base_image = Image.new('RGBA', dest_size) + image = images.resize_image(1, image, w, h) + base_image.paste(image, (x, y)) + image = base_image + + return image + + +def apply_overlay(image, paste_loc, overlay): + if overlay is None: + return image, image.copy() + + if paste_loc is not None: + image = uncrop(image, (overlay.width, overlay.height), paste_loc) + + original_denoised_image = image.copy() + + image = image.convert('RGBA') + image.alpha_composite(overlay) + image = image.convert('RGB') + + return image, original_denoised_image + +def create_binary_mask(image, round=True): + if image.mode == 'RGBA' and image.getextrema()[-1] != (255, 255): + if round: + image = image.split()[-1].convert("L").point(lambda x: 255 if x > 128 else 0) + else: + image = image.split()[-1].convert("L") + else: + image = image.convert('L') + return image + +def txt2img_image_conditioning(sd_model, x, width, height): + if sd_model.model.conditioning_key in {'hybrid', 'concat'}: # Inpainting models + + # The "masked-image" in this case will just be all 0.5 since the entire image is masked. + image_conditioning = torch.ones(x.shape[0], 3, height, width, device=x.device) * 0.5 + image_conditioning = images_tensor_to_samples(image_conditioning, approximation_indexes.get(opts.sd_vae_encode_method)) + + # Add the fake full 1s mask to the first dimension. + image_conditioning = torch.nn.functional.pad(image_conditioning, (0, 0, 0, 0, 1, 0), value=1.0) + image_conditioning = image_conditioning.to(x.dtype) + + return image_conditioning + + elif sd_model.model.conditioning_key == "crossattn-adm": # UnCLIP models + + return x.new_zeros(x.shape[0], 2*sd_model.noise_augmentor.time_embed.dim, dtype=x.dtype, device=x.device) + + else: + if sd_model.is_sdxl_inpaint: + # The "masked-image" in this case will just be all 0.5 since the entire image is masked. + image_conditioning = torch.ones(x.shape[0], 3, height, width, device=x.device) * 0.5 + image_conditioning = images_tensor_to_samples(image_conditioning, + approximation_indexes.get(opts.sd_vae_encode_method)) + + # Add the fake full 1s mask to the first dimension. + image_conditioning = torch.nn.functional.pad(image_conditioning, (0, 0, 0, 0, 1, 0), value=1.0) + image_conditioning = image_conditioning.to(x.dtype) + + return image_conditioning + + # Dummy zero conditioning if we're not using inpainting or unclip models. + # Still takes up a bit of memory, but no encoder call. + # Pretty sure we can just make this a 1x1 image since its not going to be used besides its batch size. + return x.new_zeros(x.shape[0], 5, 1, 1, dtype=x.dtype, device=x.device) + + +@dataclass(repr=False) +class StableDiffusionProcessing: + sd_model: object = None + outpath_samples: str = None + outpath_grids: str = None + prompt: str = "" + prompt_for_display: str = None + negative_prompt: str = "" + styles: list[str] = None + seed: int = -1 + subseed: int = -1 + subseed_strength: float = 0 + seed_resize_from_h: int = -1 + seed_resize_from_w: int = -1 + seed_enable_extras: bool = True + sampler_name: str = None + scheduler: str = None + batch_size: int = 1 + n_iter: int = 1 + steps: int = 50 + cfg_scale: float = 7.0 + width: int = 512 + height: int = 512 + restore_faces: bool = None + tiling: bool = None + do_not_save_samples: bool = False + do_not_save_grid: bool = False + extra_generation_params: dict[str, Any] = None + overlay_images: list = None + eta: float = None + do_not_reload_embeddings: bool = False + denoising_strength: float = None + ddim_discretize: str = None + s_min_uncond: float = None + s_churn: float = None + s_tmax: float = None + s_tmin: float = None + s_noise: float = None + override_settings: dict[str, Any] = None + override_settings_restore_afterwards: bool = True + sampler_index: int = None + refiner_checkpoint: str = None + refiner_switch_at: float = None + token_merging_ratio = 0 + token_merging_ratio_hr = 0 + disable_extra_networks: bool = False + firstpass_image: Image = None + + scripts_value: scripts.ScriptRunner = field(default=None, init=False) + script_args_value: list = field(default=None, init=False) + scripts_setup_complete: bool = field(default=False, init=False) + + cached_uc = [None, None] + cached_c = [None, None] + + comments: dict = None + sampler: sd_samplers_common.Sampler | None = field(default=None, init=False) + is_using_inpainting_conditioning: bool = field(default=False, init=False) + paste_to: tuple | None = field(default=None, init=False) + + is_hr_pass: bool = field(default=False, init=False) + + c: tuple = field(default=None, init=False) + uc: tuple = field(default=None, init=False) + + rng: rng.ImageRNG | None = field(default=None, init=False) + step_multiplier: int = field(default=1, init=False) + color_corrections: list = field(default=None, init=False) + + all_prompts: list = field(default=None, init=False) + all_negative_prompts: list = field(default=None, init=False) + all_seeds: list = field(default=None, init=False) + all_subseeds: list = field(default=None, init=False) + iteration: int = field(default=0, init=False) + main_prompt: str = field(default=None, init=False) + main_negative_prompt: str = field(default=None, init=False) + + prompts: list = field(default=None, init=False) + negative_prompts: list = field(default=None, init=False) + seeds: list = field(default=None, init=False) + subseeds: list = field(default=None, init=False) + extra_network_data: dict = field(default=None, init=False) + + user: str = field(default=None, init=False) + + sd_model_name: str = field(default=None, init=False) + sd_model_hash: str = field(default=None, init=False) + sd_vae_name: str = field(default=None, init=False) + sd_vae_hash: str = field(default=None, init=False) + + is_api: bool = field(default=False, init=False) + + def __post_init__(self): + if self.sampler_index is not None: + print("sampler_index argument for StableDiffusionProcessing does not do anything; use sampler_name", file=sys.stderr) + + self.comments = {} + + if self.styles is None: + self.styles = [] + + self.sampler_noise_scheduler_override = None + + self.extra_generation_params = self.extra_generation_params or {} + self.override_settings = self.override_settings or {} + self.script_args = self.script_args or {} + + self.refiner_checkpoint_info = None + + if not self.seed_enable_extras: + self.subseed = -1 + self.subseed_strength = 0 + self.seed_resize_from_h = 0 + self.seed_resize_from_w = 0 + + self.cached_uc = StableDiffusionProcessing.cached_uc + self.cached_c = StableDiffusionProcessing.cached_c + + def fill_fields_from_opts(self): + self.s_min_uncond = self.s_min_uncond if self.s_min_uncond is not None else opts.s_min_uncond + self.s_churn = self.s_churn if self.s_churn is not None else opts.s_churn + self.s_tmin = self.s_tmin if self.s_tmin is not None else opts.s_tmin + self.s_tmax = (self.s_tmax if self.s_tmax is not None else opts.s_tmax) or float('inf') + self.s_noise = self.s_noise if self.s_noise is not None else opts.s_noise + + @property + def sd_model(self): + return shared.sd_model + + @sd_model.setter + def sd_model(self, value): + pass + + @property + def scripts(self): + return self.scripts_value + + @scripts.setter + def scripts(self, value): + self.scripts_value = value + + if self.scripts_value and self.script_args_value and not self.scripts_setup_complete: + self.setup_scripts() + + @property + def script_args(self): + return self.script_args_value + + @script_args.setter + def script_args(self, value): + self.script_args_value = value + + if self.scripts_value and self.script_args_value and not self.scripts_setup_complete: + self.setup_scripts() + + def setup_scripts(self): + self.scripts_setup_complete = True + + self.scripts.setup_scrips(self, is_ui=not self.is_api) + + def comment(self, text): + self.comments[text] = 1 + + def txt2img_image_conditioning(self, x, width=None, height=None): + self.is_using_inpainting_conditioning = self.sd_model.model.conditioning_key in {'hybrid', 'concat'} + + return txt2img_image_conditioning(self.sd_model, x, width or self.width, height or self.height) + + def depth2img_image_conditioning(self, source_image): + # Use the AddMiDaS helper to Format our source image to suit the MiDaS model + transformer = AddMiDaS(model_type="dpt_hybrid") + transformed = transformer({"jpg": rearrange(source_image[0], "c h w -> h w c")}) + midas_in = torch.from_numpy(transformed["midas_in"][None, ...]).to(device=shared.device) + midas_in = repeat(midas_in, "1 ... -> n ...", n=self.batch_size) + + conditioning_image = images_tensor_to_samples(source_image*0.5+0.5, approximation_indexes.get(opts.sd_vae_encode_method)) + conditioning = torch.nn.functional.interpolate( + self.sd_model.depth_model(midas_in), + size=conditioning_image.shape[2:], + mode="bicubic", + align_corners=False, + ) + + (depth_min, depth_max) = torch.aminmax(conditioning) + conditioning = 2. * (conditioning - depth_min) / (depth_max - depth_min) - 1. + return conditioning + + def edit_image_conditioning(self, source_image): + conditioning_image = shared.sd_model.encode_first_stage(source_image).mode() + + return conditioning_image + + def unclip_image_conditioning(self, source_image): + c_adm = self.sd_model.embedder(source_image) + if self.sd_model.noise_augmentor is not None: + noise_level = 0 # TODO: Allow other noise levels? + c_adm, noise_level_emb = self.sd_model.noise_augmentor(c_adm, noise_level=repeat(torch.tensor([noise_level]).to(c_adm.device), '1 -> b', b=c_adm.shape[0])) + c_adm = torch.cat((c_adm, noise_level_emb), 1) + return c_adm + + def inpainting_image_conditioning(self, source_image, latent_image, image_mask=None, round_image_mask=True): + self.is_using_inpainting_conditioning = True + + # Handle the different mask inputs + if image_mask is not None: + if torch.is_tensor(image_mask): + conditioning_mask = image_mask + else: + conditioning_mask = np.array(image_mask.convert("L")) + conditioning_mask = conditioning_mask.astype(np.float32) / 255.0 + conditioning_mask = torch.from_numpy(conditioning_mask[None, None]) + + if round_image_mask: + # Caller is requesting a discretized mask as input, so we round to either 1.0 or 0.0 + conditioning_mask = torch.round(conditioning_mask) + + else: + conditioning_mask = source_image.new_ones(1, 1, *source_image.shape[-2:]) + + # Create another latent image, this time with a masked version of the original input. + # Smoothly interpolate between the masked and unmasked latent conditioning image using a parameter. + conditioning_mask = conditioning_mask.to(device=source_image.device, dtype=source_image.dtype) + conditioning_image = torch.lerp( + source_image, + source_image * (1.0 - conditioning_mask), + getattr(self, "inpainting_mask_weight", shared.opts.inpainting_mask_weight) + ) + + # Encode the new masked image using first stage of network. + conditioning_image = self.sd_model.get_first_stage_encoding(self.sd_model.encode_first_stage(conditioning_image)) + + # Create the concatenated conditioning tensor to be fed to `c_concat` + conditioning_mask = torch.nn.functional.interpolate(conditioning_mask, size=latent_image.shape[-2:]) + conditioning_mask = conditioning_mask.expand(conditioning_image.shape[0], -1, -1, -1) + image_conditioning = torch.cat([conditioning_mask, conditioning_image], dim=1) + image_conditioning = image_conditioning.to(shared.device).type(self.sd_model.dtype) + + return image_conditioning + + def img2img_image_conditioning(self, source_image, latent_image, image_mask=None, round_image_mask=True): + source_image = devices.cond_cast_float(source_image) + + # HACK: Using introspection as the Depth2Image model doesn't appear to uniquely + # identify itself with a field common to all models. The conditioning_key is also hybrid. + if isinstance(self.sd_model, LatentDepth2ImageDiffusion): + return self.depth2img_image_conditioning(source_image) + + if self.sd_model.cond_stage_key == "edit": + return self.edit_image_conditioning(source_image) + + if self.sampler.conditioning_key in {'hybrid', 'concat'}: + return self.inpainting_image_conditioning(source_image, latent_image, image_mask=image_mask, round_image_mask=round_image_mask) + + if self.sampler.conditioning_key == "crossattn-adm": + return self.unclip_image_conditioning(source_image) + + if self.sampler.model_wrap.inner_model.is_sdxl_inpaint: + return self.inpainting_image_conditioning(source_image, latent_image, image_mask=image_mask) + + # Dummy zero conditioning if we're not using inpainting or depth model. + return latent_image.new_zeros(latent_image.shape[0], 5, 1, 1) + + def init(self, all_prompts, all_seeds, all_subseeds): + pass + + def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts): + raise NotImplementedError() + + def close(self): + self.sampler = None + self.c = None + self.uc = None + if not opts.persistent_cond_cache: + StableDiffusionProcessing.cached_c = [None, None] + StableDiffusionProcessing.cached_uc = [None, None] + + def get_token_merging_ratio(self, for_hr=False): + if for_hr: + return self.token_merging_ratio_hr or opts.token_merging_ratio_hr or self.token_merging_ratio or opts.token_merging_ratio + + return self.token_merging_ratio or opts.token_merging_ratio + + def setup_prompts(self): + if isinstance(self.prompt,list): + self.all_prompts = self.prompt + elif isinstance(self.negative_prompt, list): + self.all_prompts = [self.prompt] * len(self.negative_prompt) + else: + self.all_prompts = self.batch_size * self.n_iter * [self.prompt] + + if isinstance(self.negative_prompt, list): + self.all_negative_prompts = self.negative_prompt + else: + self.all_negative_prompts = [self.negative_prompt] * len(self.all_prompts) + + if len(self.all_prompts) != len(self.all_negative_prompts): + raise RuntimeError(f"Received a different number of prompts ({len(self.all_prompts)}) and negative prompts ({len(self.all_negative_prompts)})") + + self.all_prompts = [shared.prompt_styles.apply_styles_to_prompt(x, self.styles) for x in self.all_prompts] + self.all_negative_prompts = [shared.prompt_styles.apply_negative_styles_to_prompt(x, self.styles) for x in self.all_negative_prompts] + + self.main_prompt = self.all_prompts[0] + self.main_negative_prompt = self.all_negative_prompts[0] + + def cached_params(self, required_prompts, steps, extra_network_data, hires_steps=None, use_old_scheduling=False): + """Returns parameters that invalidate the cond cache if changed""" + + return ( + required_prompts, + steps, + hires_steps, + use_old_scheduling, + opts.CLIP_stop_at_last_layers, + shared.sd_model.sd_checkpoint_info, + extra_network_data, + opts.sdxl_crop_left, + opts.sdxl_crop_top, + self.width, + self.height, + opts.fp8_storage, + opts.cache_fp16_weight, + opts.emphasis, + ) + + def get_conds_with_caching(self, function, required_prompts, steps, caches, extra_network_data, hires_steps=None): + """ + Returns the result of calling function(shared.sd_model, required_prompts, steps) + using a cache to store the result if the same arguments have been used before. + + cache is an array containing two elements. The first element is a tuple + representing the previously used arguments, or None if no arguments + have been used before. The second element is where the previously + computed result is stored. + + caches is a list with items described above. + """ + + if shared.opts.use_old_scheduling: + old_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(required_prompts, steps, hires_steps, False) + new_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(required_prompts, steps, hires_steps, True) + if old_schedules != new_schedules: + self.extra_generation_params["Old prompt editing timelines"] = True + + cached_params = self.cached_params(required_prompts, steps, extra_network_data, hires_steps, shared.opts.use_old_scheduling) + + for cache in caches: + if cache[0] is not None and cached_params == cache[0]: + return cache[1] + + cache = caches[0] + + with devices.autocast(): + cache[1] = function(shared.sd_model, required_prompts, steps, hires_steps, shared.opts.use_old_scheduling) + + cache[0] = cached_params + return cache[1] + + def setup_conds(self): + prompts = prompt_parser.SdConditioning(self.prompts, width=self.width, height=self.height) + negative_prompts = prompt_parser.SdConditioning(self.negative_prompts, width=self.width, height=self.height, is_negative_prompt=True) + + sampler_config = sd_samplers.find_sampler_config(self.sampler_name) + total_steps = sampler_config.total_steps(self.steps) if sampler_config else self.steps + self.step_multiplier = total_steps // self.steps + self.firstpass_steps = total_steps + + self.uc = self.get_conds_with_caching(prompt_parser.get_learned_conditioning, negative_prompts, total_steps, [self.cached_uc], self.extra_network_data) + self.c = self.get_conds_with_caching(prompt_parser.get_multicond_learned_conditioning, prompts, total_steps, [self.cached_c], self.extra_network_data) + + def get_conds(self): + return self.c, self.uc + + def parse_extra_network_prompts(self): + self.prompts, self.extra_network_data = extra_networks.parse_prompts(self.prompts) + + def save_samples(self) -> bool: + """Returns whether generated images need to be written to disk""" + return opts.samples_save and not self.do_not_save_samples and (opts.save_incomplete_images or not state.interrupted and not state.skipped) + + +class Processed: + def __init__(self, p: StableDiffusionProcessing, images_list, seed=-1, info="", subseed=None, all_prompts=None, all_negative_prompts=None, all_seeds=None, all_subseeds=None, index_of_first_image=0, infotexts=None, comments=""): + self.images = images_list + self.prompt = p.prompt + self.negative_prompt = p.negative_prompt + self.seed = seed + self.subseed = subseed + self.subseed_strength = p.subseed_strength + self.info = info + self.comments = "".join(f"{comment}\n" for comment in p.comments) + self.width = p.width + self.height = p.height + self.sampler_name = p.sampler_name + self.cfg_scale = p.cfg_scale + self.image_cfg_scale = getattr(p, 'image_cfg_scale', None) + self.steps = p.steps + self.batch_size = p.batch_size + self.restore_faces = p.restore_faces + self.face_restoration_model = opts.face_restoration_model if p.restore_faces else None + self.sd_model_name = p.sd_model_name + self.sd_model_hash = p.sd_model_hash + self.sd_vae_name = p.sd_vae_name + self.sd_vae_hash = p.sd_vae_hash + self.seed_resize_from_w = p.seed_resize_from_w + self.seed_resize_from_h = p.seed_resize_from_h + self.denoising_strength = getattr(p, 'denoising_strength', None) + self.extra_generation_params = p.extra_generation_params + self.index_of_first_image = index_of_first_image + self.styles = p.styles + self.job_timestamp = state.job_timestamp + self.clip_skip = opts.CLIP_stop_at_last_layers + self.token_merging_ratio = p.token_merging_ratio + self.token_merging_ratio_hr = p.token_merging_ratio_hr + + self.eta = p.eta + self.ddim_discretize = p.ddim_discretize + self.s_churn = p.s_churn + self.s_tmin = p.s_tmin + self.s_tmax = p.s_tmax + self.s_noise = p.s_noise + self.s_min_uncond = p.s_min_uncond + self.sampler_noise_scheduler_override = p.sampler_noise_scheduler_override + self.prompt = self.prompt if not isinstance(self.prompt, list) else self.prompt[0] + self.negative_prompt = self.negative_prompt if not isinstance(self.negative_prompt, list) else self.negative_prompt[0] + self.seed = int(self.seed if not isinstance(self.seed, list) else self.seed[0]) if self.seed is not None else -1 + self.subseed = int(self.subseed if not isinstance(self.subseed, list) else self.subseed[0]) if self.subseed is not None else -1 + self.is_using_inpainting_conditioning = p.is_using_inpainting_conditioning + + self.all_prompts = all_prompts or p.all_prompts or [self.prompt] + self.all_negative_prompts = all_negative_prompts or p.all_negative_prompts or [self.negative_prompt] + self.all_seeds = all_seeds or p.all_seeds or [self.seed] + self.all_subseeds = all_subseeds or p.all_subseeds or [self.subseed] + self.infotexts = infotexts or [info] * len(images_list) + self.version = program_version() + + def js(self): + obj = { + "prompt": self.all_prompts[0], + "all_prompts": self.all_prompts, + "negative_prompt": self.all_negative_prompts[0], + "all_negative_prompts": self.all_negative_prompts, + "seed": self.seed, + "all_seeds": self.all_seeds, + "subseed": self.subseed, + "all_subseeds": self.all_subseeds, + "subseed_strength": self.subseed_strength, + "width": self.width, + "height": self.height, + "sampler_name": self.sampler_name, + "cfg_scale": self.cfg_scale, + "steps": self.steps, + "batch_size": self.batch_size, + "restore_faces": self.restore_faces, + "face_restoration_model": self.face_restoration_model, + "sd_model_name": self.sd_model_name, + "sd_model_hash": self.sd_model_hash, + "sd_vae_name": self.sd_vae_name, + "sd_vae_hash": self.sd_vae_hash, + "seed_resize_from_w": self.seed_resize_from_w, + "seed_resize_from_h": self.seed_resize_from_h, + "denoising_strength": self.denoising_strength, + "extra_generation_params": self.extra_generation_params, + "index_of_first_image": self.index_of_first_image, + "infotexts": self.infotexts, + "styles": self.styles, + "job_timestamp": self.job_timestamp, + "clip_skip": self.clip_skip, + "is_using_inpainting_conditioning": self.is_using_inpainting_conditioning, + "version": self.version, + } + + return json.dumps(obj, default=lambda o: None) + + def infotext(self, p: StableDiffusionProcessing, index): + return create_infotext(p, self.all_prompts, self.all_seeds, self.all_subseeds, comments=[], position_in_batch=index % self.batch_size, iteration=index // self.batch_size) + + def get_token_merging_ratio(self, for_hr=False): + return self.token_merging_ratio_hr if for_hr else self.token_merging_ratio + + +def create_random_tensors(shape, seeds, subseeds=None, subseed_strength=0.0, seed_resize_from_h=0, seed_resize_from_w=0, p=None): + g = rng.ImageRNG(shape, seeds, subseeds=subseeds, subseed_strength=subseed_strength, seed_resize_from_h=seed_resize_from_h, seed_resize_from_w=seed_resize_from_w) + return g.next() + + +class DecodedSamples(list): + already_decoded = True + + +def decode_latent_batch(model, batch, target_device=None, check_for_nans=False): + samples = DecodedSamples() + + if check_for_nans: + devices.test_for_nans(batch, "unet") + + for i in range(batch.shape[0]): + sample = decode_first_stage(model, batch[i:i + 1])[0] + + if check_for_nans: + + try: + devices.test_for_nans(sample, "vae") + except devices.NansException as e: + if shared.opts.auto_vae_precision_bfloat16: + autofix_dtype = torch.bfloat16 + autofix_dtype_text = "bfloat16" + autofix_dtype_setting = "Automatically convert VAE to bfloat16" + autofix_dtype_comment = "" + elif shared.opts.auto_vae_precision: + autofix_dtype = torch.float32 + autofix_dtype_text = "32-bit float" + autofix_dtype_setting = "Automatically revert VAE to 32-bit floats" + autofix_dtype_comment = "\nTo always start with 32-bit VAE, use --no-half-vae commandline flag." + else: + raise e + + if devices.dtype_vae == autofix_dtype: + raise e + + errors.print_error_explanation( + "A tensor with all NaNs was produced in VAE.\n" + f"Web UI will now convert VAE into {autofix_dtype_text} and retry.\n" + f"To disable this behavior, disable the '{autofix_dtype_setting}' setting.{autofix_dtype_comment}" + ) + + devices.dtype_vae = autofix_dtype + model.first_stage_model.to(devices.dtype_vae) + batch = batch.to(devices.dtype_vae) + + sample = decode_first_stage(model, batch[i:i + 1])[0] + + if target_device is not None: + sample = sample.to(target_device) + + samples.append(sample) + + return samples + + +def get_fixed_seed(seed): + if seed == '' or seed is None: + seed = -1 + elif isinstance(seed, str): + try: + seed = int(seed) + except Exception: + seed = -1 + + if seed == -1: + return int(random.randrange(4294967294)) + + return seed + + +def fix_seed(p): + p.seed = get_fixed_seed(p.seed) + p.subseed = get_fixed_seed(p.subseed) + + +def program_version(): + import launch + + res = launch.git_tag() + if res == "<none>": + res = None + + return res + + +def create_infotext(p, all_prompts, all_seeds, all_subseeds, comments=None, iteration=0, position_in_batch=0, use_main_prompt=False, index=None, all_negative_prompts=None): + """ + this function is used to generate the infotext that is stored in the generated images, it's contains the parameters that are required to generate the imagee + Args: + p: StableDiffusionProcessing + all_prompts: list[str] + all_seeds: list[int] + all_subseeds: list[int] + comments: list[str] + iteration: int + position_in_batch: int + use_main_prompt: bool + index: int + all_negative_prompts: list[str] + + Returns: str + + Extra generation params + p.extra_generation_params dictionary allows for additional parameters to be added to the infotext + this can be use by the base webui or extensions. + To add a new entry, add a new key value pair, the dictionary key will be used as the key of the parameter in the infotext + the value generation_params can be defined as: + - str | None + - List[str|None] + - callable func(**kwargs) -> str | None + + When defined as a string, it will be used as without extra processing; this is this most common use case. + + Defining as a list allows for parameter that changes across images in the job, for example, the 'Seed' parameter. + The list should have the same length as the total number of images in the entire job. + + Defining as a callable function allows parameter cannot be generated earlier or when extra logic is required. + For example 'Hires prompt', due to reasons the hr_prompt might be changed by process in the pipeline or extensions + and may vary across different images, defining as a static string or list would not work. + + The function takes locals() as **kwargs, as such will have access to variables like 'p' and 'index'. + the base signature of the function should be: + func(**kwargs) -> str | None + optionally it can have additional arguments that will be used in the function: + func(p, index, **kwargs) -> str | None + note: for better future compatibility even though this function will have access to all variables in the locals(), + it is recommended to only use the arguments present in the function signature of create_infotext. + For actual implementation examples, see StableDiffusionProcessingTxt2Img.init > get_hr_prompt. + """ + + if use_main_prompt: + index = 0 + elif index is None: + index = position_in_batch + iteration * p.batch_size + + if all_negative_prompts is None: + all_negative_prompts = p.all_negative_prompts + + clip_skip = getattr(p, 'clip_skip', opts.CLIP_stop_at_last_layers) + enable_hr = getattr(p, 'enable_hr', False) + token_merging_ratio = p.get_token_merging_ratio() + token_merging_ratio_hr = p.get_token_merging_ratio(for_hr=True) + + prompt_text = p.main_prompt if use_main_prompt else all_prompts[index] + negative_prompt = p.main_negative_prompt if use_main_prompt else all_negative_prompts[index] + + uses_ensd = opts.eta_noise_seed_delta != 0 + if uses_ensd: + uses_ensd = sd_samplers_common.is_sampler_using_eta_noise_seed_delta(p) + + generation_params = { + "Steps": p.steps, + "Sampler": p.sampler_name, + "Schedule type": p.scheduler, + "CFG scale": p.cfg_scale, + "Image CFG scale": getattr(p, 'image_cfg_scale', None), + "Seed": p.all_seeds[0] if use_main_prompt else all_seeds[index], + "Face restoration": opts.face_restoration_model if p.restore_faces else None, + "Size": f"{p.width}x{p.height}", + "Model hash": p.sd_model_hash if opts.add_model_hash_to_info else None, + "Model": p.sd_model_name if opts.add_model_name_to_info else None, + "FP8 weight": opts.fp8_storage if devices.fp8 else None, + "Cache FP16 weight for LoRA": opts.cache_fp16_weight if devices.fp8 else None, + "VAE hash": p.sd_vae_hash if opts.add_vae_hash_to_info else None, + "VAE": p.sd_vae_name if opts.add_vae_name_to_info else None, + "Variation seed": (None if p.subseed_strength == 0 else (p.all_subseeds[0] if use_main_prompt else all_subseeds[index])), + "Variation seed strength": (None if p.subseed_strength == 0 else p.subseed_strength), + "Seed resize from": (None if p.seed_resize_from_w <= 0 or p.seed_resize_from_h <= 0 else f"{p.seed_resize_from_w}x{p.seed_resize_from_h}"), + "Denoising strength": p.extra_generation_params.get("Denoising strength"), + "Conditional mask weight": getattr(p, "inpainting_mask_weight", shared.opts.inpainting_mask_weight) if p.is_using_inpainting_conditioning else None, + "Clip skip": None if clip_skip <= 1 else clip_skip, + "ENSD": opts.eta_noise_seed_delta if uses_ensd else None, + "Token merging ratio": None if token_merging_ratio == 0 else token_merging_ratio, + "Token merging ratio hr": None if not enable_hr or token_merging_ratio_hr == 0 else token_merging_ratio_hr, + "Init image hash": getattr(p, 'init_img_hash', None), + "RNG": opts.randn_source if opts.randn_source != "GPU" else None, + "Tiling": "True" if p.tiling else None, + **p.extra_generation_params, + "Version": program_version() if opts.add_version_to_infotext else None, + "User": p.user if opts.add_user_name_to_info else None, + } + + for key, value in generation_params.items(): + try: + if isinstance(value, list): + generation_params[key] = value[index] + elif callable(value): + generation_params[key] = value(**locals()) + except Exception: + errors.report(f'Error creating infotext for key "{key}"', exc_info=True) + generation_params[key] = None + + generation_params_text = ", ".join([k if k == v else f'{k}: {infotext_utils.quote(v)}' for k, v in generation_params.items() if v is not None]) + + negative_prompt_text = f"\nNegative prompt: {negative_prompt}" if negative_prompt else "" + + return f"{prompt_text}{negative_prompt_text}\n{generation_params_text}".strip() + + +def process_images(p: StableDiffusionProcessing) -> Processed: + if p.scripts is not None: + p.scripts.before_process(p) + + stored_opts = {k: opts.data[k] if k in opts.data else opts.get_default(k) for k in p.override_settings.keys() if k in opts.data} + + try: + # if no checkpoint override or the override checkpoint can't be found, remove override entry and load opts checkpoint + # and if after running refiner, the refiner model is not unloaded - webui swaps back to main model here, if model over is present it will be reloaded afterwards + if sd_models.checkpoint_aliases.get(p.override_settings.get('sd_model_checkpoint')) is None: + p.override_settings.pop('sd_model_checkpoint', None) + sd_models.reload_model_weights() + + for k, v in p.override_settings.items(): + opts.set(k, v, is_api=True, run_callbacks=False) + + if k == 'sd_model_checkpoint': + sd_models.reload_model_weights() + + if k == 'sd_vae': + sd_vae.reload_vae_weights() + + sd_models.apply_token_merging(p.sd_model, p.get_token_merging_ratio()) + + # backwards compatibility, fix sampler and scheduler if invalid + sd_samplers.fix_p_invalid_sampler_and_scheduler(p) + + with profiling.Profiler(): + res = process_images_inner(p) + + finally: + sd_models.apply_token_merging(p.sd_model, 0) + + # restore opts to original state + if p.override_settings_restore_afterwards: + for k, v in stored_opts.items(): + setattr(opts, k, v) + + if k == 'sd_vae': + sd_vae.reload_vae_weights() + + return res + + +def process_images_inner(p: StableDiffusionProcessing) -> Processed: + """this is the main loop that both txt2img and img2img use; it calls func_init once inside all the scopes and func_sample once per batch""" + + if isinstance(p.prompt, list): + assert(len(p.prompt) > 0) + else: + assert p.prompt is not None + + devices.torch_gc() + + seed = get_fixed_seed(p.seed) + subseed = get_fixed_seed(p.subseed) + + if p.restore_faces is None: + p.restore_faces = opts.face_restoration + + if p.tiling is None: + p.tiling = opts.tiling + + if p.refiner_checkpoint not in (None, "", "None", "none"): + p.refiner_checkpoint_info = sd_models.get_closet_checkpoint_match(p.refiner_checkpoint) + if p.refiner_checkpoint_info is None: + raise Exception(f'Could not find checkpoint with name {p.refiner_checkpoint}') + + if hasattr(shared.sd_model, 'fix_dimensions'): + p.width, p.height = shared.sd_model.fix_dimensions(p.width, p.height) + + p.sd_model_name = shared.sd_model.sd_checkpoint_info.name_for_extra + p.sd_model_hash = shared.sd_model.sd_model_hash + p.sd_vae_name = sd_vae.get_loaded_vae_name() + p.sd_vae_hash = sd_vae.get_loaded_vae_hash() + + modules.sd_hijack.model_hijack.apply_circular(p.tiling) + modules.sd_hijack.model_hijack.clear_comments() + + p.fill_fields_from_opts() + p.setup_prompts() + + if isinstance(seed, list): + p.all_seeds = seed + else: + p.all_seeds = [int(seed) + (x if p.subseed_strength == 0 else 0) for x in range(len(p.all_prompts))] + + if isinstance(subseed, list): + p.all_subseeds = subseed + else: + p.all_subseeds = [int(subseed) + x for x in range(len(p.all_prompts))] + + if os.path.exists(cmd_opts.embeddings_dir) and not p.do_not_reload_embeddings: + model_hijack.embedding_db.load_textual_inversion_embeddings() + + if p.scripts is not None: + p.scripts.process(p) + + infotexts = [] + output_images = [] + with torch.no_grad(), p.sd_model.ema_scope(): + with devices.autocast(): + p.init(p.all_prompts, p.all_seeds, p.all_subseeds) + + # for OSX, loading the model during sampling changes the generated picture, so it is loaded here + if shared.opts.live_previews_enable and opts.show_progress_type == "Approx NN": + sd_vae_approx.model() + + sd_unet.apply_unet() + + if state.job_count == -1: + state.job_count = p.n_iter + + for n in range(p.n_iter): + p.iteration = n + + if state.skipped: + state.skipped = False + + if state.interrupted or state.stopping_generation: + break + + sd_models.reload_model_weights() # model can be changed for example by refiner + + p.prompts = p.all_prompts[n * p.batch_size:(n + 1) * p.batch_size] + p.negative_prompts = p.all_negative_prompts[n * p.batch_size:(n + 1) * p.batch_size] + p.seeds = p.all_seeds[n * p.batch_size:(n + 1) * p.batch_size] + p.subseeds = p.all_subseeds[n * p.batch_size:(n + 1) * p.batch_size] + + latent_channels = getattr(shared.sd_model, 'latent_channels', opt_C) + p.rng = rng.ImageRNG((latent_channels, p.height // opt_f, p.width // opt_f), p.seeds, subseeds=p.subseeds, subseed_strength=p.subseed_strength, seed_resize_from_h=p.seed_resize_from_h, seed_resize_from_w=p.seed_resize_from_w) + + if p.scripts is not None: + p.scripts.before_process_batch(p, batch_number=n, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds) + + if len(p.prompts) == 0: + break + + p.parse_extra_network_prompts() + + if not p.disable_extra_networks: + with devices.autocast(): + extra_networks.activate(p, p.extra_network_data) + + if p.scripts is not None: + p.scripts.process_batch(p, batch_number=n, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds) + + p.setup_conds() + + p.extra_generation_params.update(model_hijack.extra_generation_params) + + # params.txt should be saved after scripts.process_batch, since the + # infotext could be modified by that callback + # Example: a wildcard processed by process_batch sets an extra model + # strength, which is saved as "Model Strength: 1.0" in the infotext + if n == 0 and not cmd_opts.no_prompt_history: + with open(os.path.join(paths.data_path, "params.txt"), "w", encoding="utf8") as file: + processed = Processed(p, []) + file.write(processed.infotext(p, 0)) + + for comment in model_hijack.comments: + p.comment(comment) + + if p.n_iter > 1: + shared.state.job = f"Batch {n+1} out of {p.n_iter}" + + sd_models.apply_alpha_schedule_override(p.sd_model, p) + + with devices.without_autocast() if devices.unet_needs_upcast else devices.autocast(): + samples_ddim = p.sample(conditioning=p.c, unconditional_conditioning=p.uc, seeds=p.seeds, subseeds=p.subseeds, subseed_strength=p.subseed_strength, prompts=p.prompts) + + if p.scripts is not None: + ps = scripts.PostSampleArgs(samples_ddim) + p.scripts.post_sample(p, ps) + samples_ddim = ps.samples + + if getattr(samples_ddim, 'already_decoded', False): + x_samples_ddim = samples_ddim + else: + devices.test_for_nans(samples_ddim, "unet") + + if opts.sd_vae_decode_method != 'Full': + p.extra_generation_params['VAE Decoder'] = opts.sd_vae_decode_method + x_samples_ddim = decode_latent_batch(p.sd_model, samples_ddim, target_device=devices.cpu, check_for_nans=True) + + x_samples_ddim = torch.stack(x_samples_ddim).float() + x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0) + + del samples_ddim + + if lowvram.is_enabled(shared.sd_model): + lowvram.send_everything_to_cpu() + + devices.torch_gc() + + state.nextjob() + + if p.scripts is not None: + p.scripts.postprocess_batch(p, x_samples_ddim, batch_number=n) + + p.prompts = p.all_prompts[n * p.batch_size:(n + 1) * p.batch_size] + p.negative_prompts = p.all_negative_prompts[n * p.batch_size:(n + 1) * p.batch_size] + + batch_params = scripts.PostprocessBatchListArgs(list(x_samples_ddim)) + p.scripts.postprocess_batch_list(p, batch_params, batch_number=n) + x_samples_ddim = batch_params.images + + def infotext(index=0, use_main_prompt=False): + return create_infotext(p, p.prompts, p.seeds, p.subseeds, use_main_prompt=use_main_prompt, index=index, all_negative_prompts=p.negative_prompts) + + save_samples = p.save_samples() + + for i, x_sample in enumerate(x_samples_ddim): + p.batch_index = i + + x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2) + x_sample = x_sample.astype(np.uint8) + + if p.restore_faces: + if save_samples and opts.save_images_before_face_restoration: + images.save_image(Image.fromarray(x_sample), p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-before-face-restoration") + + devices.torch_gc() + + x_sample = modules.face_restoration.restore_faces(x_sample) + devices.torch_gc() + + image = Image.fromarray(x_sample) + + if p.scripts is not None: + pp = scripts.PostprocessImageArgs(image) + p.scripts.postprocess_image(p, pp) + image = pp.image + + mask_for_overlay = getattr(p, "mask_for_overlay", None) + + if not shared.opts.overlay_inpaint: + overlay_image = None + elif getattr(p, "overlay_images", None) is not None and i < len(p.overlay_images): + overlay_image = p.overlay_images[i] + else: + overlay_image = None + + if p.scripts is not None: + ppmo = scripts.PostProcessMaskOverlayArgs(i, mask_for_overlay, overlay_image) + p.scripts.postprocess_maskoverlay(p, ppmo) + mask_for_overlay, overlay_image = ppmo.mask_for_overlay, ppmo.overlay_image + + if p.color_corrections is not None and i < len(p.color_corrections): + if save_samples and opts.save_images_before_color_correction: + image_without_cc, _ = apply_overlay(image, p.paste_to, overlay_image) + images.save_image(image_without_cc, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-before-color-correction") + image = apply_color_correction(p.color_corrections[i], image) + + # If the intention is to show the output from the model + # that is being composited over the original image, + # we need to keep the original image around + # and use it in the composite step. + image, original_denoised_image = apply_overlay(image, p.paste_to, overlay_image) + + if p.scripts is not None: + pp = scripts.PostprocessImageArgs(image) + p.scripts.postprocess_image_after_composite(p, pp) + image = pp.image + + if save_samples: + images.save_image(image, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p) + + text = infotext(i) + infotexts.append(text) + if opts.enable_pnginfo: + image.info["parameters"] = text + output_images.append(image) + + if mask_for_overlay is not None: + if opts.return_mask or opts.save_mask: + image_mask = mask_for_overlay.convert('RGB') + if save_samples and opts.save_mask: + images.save_image(image_mask, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-mask") + if opts.return_mask: + output_images.append(image_mask) + + if opts.return_mask_composite or opts.save_mask_composite: + image_mask_composite = Image.composite(original_denoised_image.convert('RGBA').convert('RGBa'), Image.new('RGBa', image.size), images.resize_image(2, mask_for_overlay, image.width, image.height).convert('L')).convert('RGBA') + if save_samples and opts.save_mask_composite: + images.save_image(image_mask_composite, p.outpath_samples, "", p.seeds[i], p.prompts[i], opts.samples_format, info=infotext(i), p=p, suffix="-mask-composite") + if opts.return_mask_composite: + output_images.append(image_mask_composite) + + del x_samples_ddim + + devices.torch_gc() + + if not infotexts: + infotexts.append(Processed(p, []).infotext(p, 0)) + + p.color_corrections = None + + index_of_first_image = 0 + unwanted_grid_because_of_img_count = len(output_images) < 2 and opts.grid_only_if_multiple + if (opts.return_grid or opts.grid_save) and not p.do_not_save_grid and not unwanted_grid_because_of_img_count: + grid = images.image_grid(output_images, p.batch_size) + + if opts.return_grid: + text = infotext(use_main_prompt=True) + infotexts.insert(0, text) + if opts.enable_pnginfo: + grid.info["parameters"] = text + output_images.insert(0, grid) + index_of_first_image = 1 + if opts.grid_save: + images.save_image(grid, p.outpath_grids, "grid", p.all_seeds[0], p.all_prompts[0], opts.grid_format, info=infotext(use_main_prompt=True), short_filename=not opts.grid_extended_filename, p=p, grid=True) + + if not p.disable_extra_networks and p.extra_network_data: + extra_networks.deactivate(p, p.extra_network_data) + + devices.torch_gc() + + res = Processed( + p, + images_list=output_images, + seed=p.all_seeds[0], + info=infotexts[0], + subseed=p.all_subseeds[0], + index_of_first_image=index_of_first_image, + infotexts=infotexts, + ) + + if p.scripts is not None: + p.scripts.postprocess(p, res) + + return res + + +def old_hires_fix_first_pass_dimensions(width, height): + """old algorithm for auto-calculating first pass size""" + + desired_pixel_count = 512 * 512 + actual_pixel_count = width * height + scale = math.sqrt(desired_pixel_count / actual_pixel_count) + width = math.ceil(scale * width / 64) * 64 + height = math.ceil(scale * height / 64) * 64 + + return width, height + + +@dataclass(repr=False) +class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing): + enable_hr: bool = False + denoising_strength: float = 0.75 + firstphase_width: int = 0 + firstphase_height: int = 0 + hr_scale: float = 2.0 + hr_upscaler: str = None + hr_second_pass_steps: int = 0 + hr_resize_x: int = 0 + hr_resize_y: int = 0 + hr_checkpoint_name: str = None + hr_sampler_name: str = None + hr_scheduler: str = None + hr_prompt: str = '' + hr_negative_prompt: str = '' + force_task_id: str = None + + cached_hr_uc = [None, None] + cached_hr_c = [None, None] + + hr_checkpoint_info: dict = field(default=None, init=False) + hr_upscale_to_x: int = field(default=0, init=False) + hr_upscale_to_y: int = field(default=0, init=False) + truncate_x: int = field(default=0, init=False) + truncate_y: int = field(default=0, init=False) + applied_old_hires_behavior_to: tuple = field(default=None, init=False) + latent_scale_mode: dict = field(default=None, init=False) + hr_c: tuple | None = field(default=None, init=False) + hr_uc: tuple | None = field(default=None, init=False) + all_hr_prompts: list = field(default=None, init=False) + all_hr_negative_prompts: list = field(default=None, init=False) + hr_prompts: list = field(default=None, init=False) + hr_negative_prompts: list = field(default=None, init=False) + hr_extra_network_data: list = field(default=None, init=False) + + def __post_init__(self): + super().__post_init__() + + if self.firstphase_width != 0 or self.firstphase_height != 0: + self.hr_upscale_to_x = self.width + self.hr_upscale_to_y = self.height + self.width = self.firstphase_width + self.height = self.firstphase_height + + self.cached_hr_uc = StableDiffusionProcessingTxt2Img.cached_hr_uc + self.cached_hr_c = StableDiffusionProcessingTxt2Img.cached_hr_c + + def calculate_target_resolution(self): + if opts.use_old_hires_fix_width_height and self.applied_old_hires_behavior_to != (self.width, self.height): + self.hr_resize_x = self.width + self.hr_resize_y = self.height + self.hr_upscale_to_x = self.width + self.hr_upscale_to_y = self.height + + self.width, self.height = old_hires_fix_first_pass_dimensions(self.width, self.height) + self.applied_old_hires_behavior_to = (self.width, self.height) + + if self.hr_resize_x == 0 and self.hr_resize_y == 0: + self.extra_generation_params["Hires upscale"] = self.hr_scale + self.hr_upscale_to_x = int(self.width * self.hr_scale) + self.hr_upscale_to_y = int(self.height * self.hr_scale) + else: + self.extra_generation_params["Hires resize"] = f"{self.hr_resize_x}x{self.hr_resize_y}" + + if self.hr_resize_y == 0: + self.hr_upscale_to_x = self.hr_resize_x + self.hr_upscale_to_y = self.hr_resize_x * self.height // self.width + elif self.hr_resize_x == 0: + self.hr_upscale_to_x = self.hr_resize_y * self.width // self.height + self.hr_upscale_to_y = self.hr_resize_y + else: + target_w = self.hr_resize_x + target_h = self.hr_resize_y + src_ratio = self.width / self.height + dst_ratio = self.hr_resize_x / self.hr_resize_y + + if src_ratio < dst_ratio: + self.hr_upscale_to_x = self.hr_resize_x + self.hr_upscale_to_y = self.hr_resize_x * self.height // self.width + else: + self.hr_upscale_to_x = self.hr_resize_y * self.width // self.height + self.hr_upscale_to_y = self.hr_resize_y + + self.truncate_x = (self.hr_upscale_to_x - target_w) // opt_f + self.truncate_y = (self.hr_upscale_to_y - target_h) // opt_f + + def init(self, all_prompts, all_seeds, all_subseeds): + if self.enable_hr: + self.extra_generation_params["Denoising strength"] = self.denoising_strength + + if self.hr_checkpoint_name and self.hr_checkpoint_name != 'Use same checkpoint': + self.hr_checkpoint_info = sd_models.get_closet_checkpoint_match(self.hr_checkpoint_name) + + if self.hr_checkpoint_info is None: + raise Exception(f'Could not find checkpoint with name {self.hr_checkpoint_name}') + + self.extra_generation_params["Hires checkpoint"] = self.hr_checkpoint_info.short_title + + if self.hr_sampler_name is not None and self.hr_sampler_name != self.sampler_name: + self.extra_generation_params["Hires sampler"] = self.hr_sampler_name + + def get_hr_prompt(p, index, prompt_text, **kwargs): + hr_prompt = p.all_hr_prompts[index] + return hr_prompt if hr_prompt != prompt_text else None + + def get_hr_negative_prompt(p, index, negative_prompt, **kwargs): + hr_negative_prompt = p.all_hr_negative_prompts[index] + return hr_negative_prompt if hr_negative_prompt != negative_prompt else None + + self.extra_generation_params["Hires prompt"] = get_hr_prompt + self.extra_generation_params["Hires negative prompt"] = get_hr_negative_prompt + + self.extra_generation_params["Hires schedule type"] = None # to be set in sd_samplers_kdiffusion.py + + if self.hr_scheduler is None: + self.hr_scheduler = self.scheduler + + self.latent_scale_mode = shared.latent_upscale_modes.get(self.hr_upscaler, None) if self.hr_upscaler is not None else shared.latent_upscale_modes.get(shared.latent_upscale_default_mode, "nearest") + if self.enable_hr and self.latent_scale_mode is None: + if not any(x.name == self.hr_upscaler for x in shared.sd_upscalers): + raise Exception(f"could not find upscaler named {self.hr_upscaler}") + + self.calculate_target_resolution() + + if not state.processing_has_refined_job_count: + if state.job_count == -1: + state.job_count = self.n_iter + if getattr(self, 'txt2img_upscale', False): + total_steps = (self.hr_second_pass_steps or self.steps) * state.job_count + else: + total_steps = (self.steps + (self.hr_second_pass_steps or self.steps)) * state.job_count + shared.total_tqdm.updateTotal(total_steps) + state.job_count = state.job_count * 2 + state.processing_has_refined_job_count = True + + if self.hr_second_pass_steps: + self.extra_generation_params["Hires steps"] = self.hr_second_pass_steps + + if self.hr_upscaler is not None: + self.extra_generation_params["Hires upscaler"] = self.hr_upscaler + + def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts): + self.sampler = sd_samplers.create_sampler(self.sampler_name, self.sd_model) + + if self.firstpass_image is not None and self.enable_hr: + # here we don't need to generate image, we just take self.firstpass_image and prepare it for hires fix + + if self.latent_scale_mode is None: + image = np.array(self.firstpass_image).astype(np.float32) / 255.0 * 2.0 - 1.0 + image = np.moveaxis(image, 2, 0) + + samples = None + decoded_samples = torch.asarray(np.expand_dims(image, 0)) + + else: + image = np.array(self.firstpass_image).astype(np.float32) / 255.0 + image = np.moveaxis(image, 2, 0) + image = torch.from_numpy(np.expand_dims(image, axis=0)) + image = image.to(shared.device, dtype=devices.dtype_vae) + + if opts.sd_vae_encode_method != 'Full': + self.extra_generation_params['VAE Encoder'] = opts.sd_vae_encode_method + + samples = images_tensor_to_samples(image, approximation_indexes.get(opts.sd_vae_encode_method), self.sd_model) + decoded_samples = None + devices.torch_gc() + + else: + # here we generate an image normally + + x = self.rng.next() + if self.scripts is not None: + self.scripts.process_before_every_sampling( + p=self, + x=x, + noise=x, + c=conditioning, + uc=unconditional_conditioning + ) + + samples = self.sampler.sample(self, x, conditioning, unconditional_conditioning, image_conditioning=self.txt2img_image_conditioning(x)) + del x + + if not self.enable_hr: + return samples + + devices.torch_gc() + + if self.latent_scale_mode is None: + decoded_samples = torch.stack(decode_latent_batch(self.sd_model, samples, target_device=devices.cpu, check_for_nans=True)).to(dtype=torch.float32) + else: + decoded_samples = None + + with sd_models.SkipWritingToConfig(): + sd_models.reload_model_weights(info=self.hr_checkpoint_info) + + return self.sample_hr_pass(samples, decoded_samples, seeds, subseeds, subseed_strength, prompts) + + def sample_hr_pass(self, samples, decoded_samples, seeds, subseeds, subseed_strength, prompts): + if shared.state.interrupted: + return samples + + self.is_hr_pass = True + target_width = self.hr_upscale_to_x + target_height = self.hr_upscale_to_y + + def save_intermediate(image, index): + """saves image before applying hires fix, if enabled in options; takes as an argument either an image or batch with latent space images""" + + if not self.save_samples() or not opts.save_images_before_highres_fix: + return + + if not isinstance(image, Image.Image): + image = sd_samplers.sample_to_image(image, index, approximation=0) + + info = create_infotext(self, self.all_prompts, self.all_seeds, self.all_subseeds, [], iteration=self.iteration, position_in_batch=index) + images.save_image(image, self.outpath_samples, "", seeds[index], prompts[index], opts.samples_format, info=info, p=self, suffix="-before-highres-fix") + + img2img_sampler_name = self.hr_sampler_name or self.sampler_name + + self.sampler = sd_samplers.create_sampler(img2img_sampler_name, self.sd_model) + + if self.latent_scale_mode is not None: + for i in range(samples.shape[0]): + save_intermediate(samples, i) + + samples = torch.nn.functional.interpolate(samples, size=(target_height // opt_f, target_width // opt_f), mode=self.latent_scale_mode["mode"], antialias=self.latent_scale_mode["antialias"]) + + # Avoid making the inpainting conditioning unless necessary as + # this does need some extra compute to decode / encode the image again. + if getattr(self, "inpainting_mask_weight", shared.opts.inpainting_mask_weight) < 1.0: + image_conditioning = self.img2img_image_conditioning(decode_first_stage(self.sd_model, samples), samples) + else: + image_conditioning = self.txt2img_image_conditioning(samples) + else: + lowres_samples = torch.clamp((decoded_samples + 1.0) / 2.0, min=0.0, max=1.0) + + batch_images = [] + for i, x_sample in enumerate(lowres_samples): + x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2) + x_sample = x_sample.astype(np.uint8) + image = Image.fromarray(x_sample) + + save_intermediate(image, i) + + image = images.resize_image(0, image, target_width, target_height, upscaler_name=self.hr_upscaler) + image = np.array(image).astype(np.float32) / 255.0 + image = np.moveaxis(image, 2, 0) + batch_images.append(image) + + decoded_samples = torch.from_numpy(np.array(batch_images)) + decoded_samples = decoded_samples.to(shared.device, dtype=devices.dtype_vae) + + if opts.sd_vae_encode_method != 'Full': + self.extra_generation_params['VAE Encoder'] = opts.sd_vae_encode_method + samples = images_tensor_to_samples(decoded_samples, approximation_indexes.get(opts.sd_vae_encode_method)) + + image_conditioning = self.img2img_image_conditioning(decoded_samples, samples) + + shared.state.nextjob() + + samples = samples[:, :, self.truncate_y//2:samples.shape[2]-(self.truncate_y+1)//2, self.truncate_x//2:samples.shape[3]-(self.truncate_x+1)//2] + + self.rng = rng.ImageRNG(samples.shape[1:], self.seeds, subseeds=self.subseeds, subseed_strength=self.subseed_strength, seed_resize_from_h=self.seed_resize_from_h, seed_resize_from_w=self.seed_resize_from_w) + noise = self.rng.next() + + # GC now before running the next img2img to prevent running out of memory + devices.torch_gc() + + if not self.disable_extra_networks: + with devices.autocast(): + extra_networks.activate(self, self.hr_extra_network_data) + + with devices.autocast(): + self.calculate_hr_conds() + + sd_models.apply_token_merging(self.sd_model, self.get_token_merging_ratio(for_hr=True)) + + if self.scripts is not None: + self.scripts.before_hr(self) + self.scripts.process_before_every_sampling( + p=self, + x=samples, + noise=noise, + c=self.hr_c, + uc=self.hr_uc, + ) + + samples = self.sampler.sample_img2img(self, samples, noise, self.hr_c, self.hr_uc, steps=self.hr_second_pass_steps or self.steps, image_conditioning=image_conditioning) + + sd_models.apply_token_merging(self.sd_model, self.get_token_merging_ratio()) + + self.sampler = None + devices.torch_gc() + + decoded_samples = decode_latent_batch(self.sd_model, samples, target_device=devices.cpu, check_for_nans=True) + + self.is_hr_pass = False + return decoded_samples + + def close(self): + super().close() + self.hr_c = None + self.hr_uc = None + if not opts.persistent_cond_cache: + StableDiffusionProcessingTxt2Img.cached_hr_uc = [None, None] + StableDiffusionProcessingTxt2Img.cached_hr_c = [None, None] + + def setup_prompts(self): + super().setup_prompts() + + if not self.enable_hr: + return + + if self.hr_prompt == '': + self.hr_prompt = self.prompt + + if self.hr_negative_prompt == '': + self.hr_negative_prompt = self.negative_prompt + + if isinstance(self.hr_prompt, list): + self.all_hr_prompts = self.hr_prompt + else: + self.all_hr_prompts = self.batch_size * self.n_iter * [self.hr_prompt] + + if isinstance(self.hr_negative_prompt, list): + self.all_hr_negative_prompts = self.hr_negative_prompt + else: + self.all_hr_negative_prompts = self.batch_size * self.n_iter * [self.hr_negative_prompt] + + self.all_hr_prompts = [shared.prompt_styles.apply_styles_to_prompt(x, self.styles) for x in self.all_hr_prompts] + self.all_hr_negative_prompts = [shared.prompt_styles.apply_negative_styles_to_prompt(x, self.styles) for x in self.all_hr_negative_prompts] + + def calculate_hr_conds(self): + if self.hr_c is not None: + return + + hr_prompts = prompt_parser.SdConditioning(self.hr_prompts, width=self.hr_upscale_to_x, height=self.hr_upscale_to_y) + hr_negative_prompts = prompt_parser.SdConditioning(self.hr_negative_prompts, width=self.hr_upscale_to_x, height=self.hr_upscale_to_y, is_negative_prompt=True) + + sampler_config = sd_samplers.find_sampler_config(self.hr_sampler_name or self.sampler_name) + steps = self.hr_second_pass_steps or self.steps + total_steps = sampler_config.total_steps(steps) if sampler_config else steps + + self.hr_uc = self.get_conds_with_caching(prompt_parser.get_learned_conditioning, hr_negative_prompts, self.firstpass_steps, [self.cached_hr_uc, self.cached_uc], self.hr_extra_network_data, total_steps) + self.hr_c = self.get_conds_with_caching(prompt_parser.get_multicond_learned_conditioning, hr_prompts, self.firstpass_steps, [self.cached_hr_c, self.cached_c], self.hr_extra_network_data, total_steps) + + def setup_conds(self): + if self.is_hr_pass: + # if we are in hr pass right now, the call is being made from the refiner, and we don't need to setup firstpass cons or switch model + self.hr_c = None + self.calculate_hr_conds() + return + + super().setup_conds() + + self.hr_uc = None + self.hr_c = None + + if self.enable_hr and self.hr_checkpoint_info is None: + if shared.opts.hires_fix_use_firstpass_conds: + self.calculate_hr_conds() + + elif lowvram.is_enabled(shared.sd_model) and shared.sd_model.sd_checkpoint_info == sd_models.select_checkpoint(): # if in lowvram mode, we need to calculate conds right away, before the cond NN is unloaded + with devices.autocast(): + extra_networks.activate(self, self.hr_extra_network_data) + + self.calculate_hr_conds() + + with devices.autocast(): + extra_networks.activate(self, self.extra_network_data) + + def get_conds(self): + if self.is_hr_pass: + return self.hr_c, self.hr_uc + + return super().get_conds() + + def parse_extra_network_prompts(self): + res = super().parse_extra_network_prompts() + + if self.enable_hr: + self.hr_prompts = self.all_hr_prompts[self.iteration * self.batch_size:(self.iteration + 1) * self.batch_size] + self.hr_negative_prompts = self.all_hr_negative_prompts[self.iteration * self.batch_size:(self.iteration + 1) * self.batch_size] + + self.hr_prompts, self.hr_extra_network_data = extra_networks.parse_prompts(self.hr_prompts) + + return res + + +@dataclass(repr=False) +class StableDiffusionProcessingImg2Img(StableDiffusionProcessing): + init_images: list = None + resize_mode: int = 0 + denoising_strength: float = 0.75 + image_cfg_scale: float = None + mask: Any = None + mask_blur_x: int = 4 + mask_blur_y: int = 4 + mask_blur: int = None + mask_round: bool = True + inpainting_fill: int = 0 + inpaint_full_res: bool = True + inpaint_full_res_padding: int = 0 + inpainting_mask_invert: int = 0 + initial_noise_multiplier: float = None + latent_mask: Image = None + force_task_id: str = None + + image_mask: Any = field(default=None, init=False) + + nmask: torch.Tensor = field(default=None, init=False) + image_conditioning: torch.Tensor = field(default=None, init=False) + init_img_hash: str = field(default=None, init=False) + mask_for_overlay: Image = field(default=None, init=False) + init_latent: torch.Tensor = field(default=None, init=False) + + def __post_init__(self): + super().__post_init__() + + self.image_mask = self.mask + self.mask = None + self.initial_noise_multiplier = opts.initial_noise_multiplier if self.initial_noise_multiplier is None else self.initial_noise_multiplier + + @property + def mask_blur(self): + if self.mask_blur_x == self.mask_blur_y: + return self.mask_blur_x + return None + + @mask_blur.setter + def mask_blur(self, value): + if isinstance(value, int): + self.mask_blur_x = value + self.mask_blur_y = value + + def init(self, all_prompts, all_seeds, all_subseeds): + self.extra_generation_params["Denoising strength"] = self.denoising_strength + + self.image_cfg_scale: float = self.image_cfg_scale if shared.sd_model.cond_stage_key == "edit" else None + + self.sampler = sd_samplers.create_sampler(self.sampler_name, self.sd_model) + crop_region = None + + image_mask = self.image_mask + + if image_mask is not None: + # image_mask is passed in as RGBA by Gradio to support alpha masks, + # but we still want to support binary masks. + image_mask = create_binary_mask(image_mask, round=self.mask_round) + + if self.inpainting_mask_invert: + image_mask = ImageOps.invert(image_mask) + self.extra_generation_params["Mask mode"] = "Inpaint not masked" + + if self.mask_blur_x > 0: + np_mask = np.array(image_mask) + kernel_size = 2 * int(2.5 * self.mask_blur_x + 0.5) + 1 + np_mask = cv2.GaussianBlur(np_mask, (kernel_size, 1), self.mask_blur_x) + image_mask = Image.fromarray(np_mask) + + if self.mask_blur_y > 0: + np_mask = np.array(image_mask) + kernel_size = 2 * int(2.5 * self.mask_blur_y + 0.5) + 1 + np_mask = cv2.GaussianBlur(np_mask, (1, kernel_size), self.mask_blur_y) + image_mask = Image.fromarray(np_mask) + + if self.mask_blur_x > 0 or self.mask_blur_y > 0: + self.extra_generation_params["Mask blur"] = self.mask_blur + + if self.inpaint_full_res: + self.mask_for_overlay = image_mask + mask = image_mask.convert('L') + crop_region = masking.get_crop_region_v2(mask, self.inpaint_full_res_padding) + if crop_region: + crop_region = masking.expand_crop_region(crop_region, self.width, self.height, mask.width, mask.height) + x1, y1, x2, y2 = crop_region + mask = mask.crop(crop_region) + image_mask = images.resize_image(2, mask, self.width, self.height) + self.paste_to = (x1, y1, x2-x1, y2-y1) + self.extra_generation_params["Inpaint area"] = "Only masked" + self.extra_generation_params["Masked area padding"] = self.inpaint_full_res_padding + else: + crop_region = None + image_mask = None + self.mask_for_overlay = None + self.inpaint_full_res = False + massage = 'Unable to perform "Inpaint Only mask" because mask is blank, switch to img2img mode.' + model_hijack.comments.append(massage) + logging.info(massage) + else: + image_mask = images.resize_image(self.resize_mode, image_mask, self.width, self.height) + np_mask = np.array(image_mask) + np_mask = np.clip((np_mask.astype(np.float32)) * 2, 0, 255).astype(np.uint8) + self.mask_for_overlay = Image.fromarray(np_mask) + + self.overlay_images = [] + + latent_mask = self.latent_mask if self.latent_mask is not None else image_mask + + add_color_corrections = opts.img2img_color_correction and self.color_corrections is None + if add_color_corrections: + self.color_corrections = [] + imgs = [] + for img in self.init_images: + + # Save init image + if opts.save_init_img: + self.init_img_hash = hashlib.md5(img.tobytes()).hexdigest() + images.save_image(img, path=opts.outdir_init_images, basename=None, forced_filename=self.init_img_hash, save_to_dirs=False, existing_info=img.info) + + image = images.flatten(img, opts.img2img_background_color) + + if crop_region is None and self.resize_mode != 3: + image = images.resize_image(self.resize_mode, image, self.width, self.height) + + if image_mask is not None: + if self.mask_for_overlay.size != (image.width, image.height): + self.mask_for_overlay = images.resize_image(self.resize_mode, self.mask_for_overlay, image.width, image.height) + image_masked = Image.new('RGBa', (image.width, image.height)) + image_masked.paste(image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(self.mask_for_overlay.convert('L'))) + + self.overlay_images.append(image_masked.convert('RGBA')) + + # crop_region is not None if we are doing inpaint full res + if crop_region is not None: + image = image.crop(crop_region) + image = images.resize_image(2, image, self.width, self.height) + + if image_mask is not None: + if self.inpainting_fill != 1: + image = masking.fill(image, latent_mask) + + if self.inpainting_fill == 0: + self.extra_generation_params["Masked content"] = 'fill' + + if add_color_corrections: + self.color_corrections.append(setup_color_correction(image)) + + image = np.array(image).astype(np.float32) / 255.0 + image = np.moveaxis(image, 2, 0) + + imgs.append(image) + + if len(imgs) == 1: + batch_images = np.expand_dims(imgs[0], axis=0).repeat(self.batch_size, axis=0) + if self.overlay_images is not None: + self.overlay_images = self.overlay_images * self.batch_size + + if self.color_corrections is not None and len(self.color_corrections) == 1: + self.color_corrections = self.color_corrections * self.batch_size + + elif len(imgs) <= self.batch_size: + self.batch_size = len(imgs) + batch_images = np.array(imgs) + else: + raise RuntimeError(f"bad number of images passed: {len(imgs)}; expecting {self.batch_size} or less") + + image = torch.from_numpy(batch_images) + image = image.to(shared.device, dtype=devices.dtype_vae) + + if opts.sd_vae_encode_method != 'Full': + self.extra_generation_params['VAE Encoder'] = opts.sd_vae_encode_method + + self.init_latent = images_tensor_to_samples(image, approximation_indexes.get(opts.sd_vae_encode_method), self.sd_model) + devices.torch_gc() + + if self.resize_mode == 3: + self.init_latent = torch.nn.functional.interpolate(self.init_latent, size=(self.height // opt_f, self.width // opt_f), mode="bilinear") + + if image_mask is not None: + init_mask = latent_mask + latmask = init_mask.convert('RGB').resize((self.init_latent.shape[3], self.init_latent.shape[2])) + latmask = np.moveaxis(np.array(latmask, dtype=np.float32), 2, 0) / 255 + latmask = latmask[0] + if self.mask_round: + latmask = np.around(latmask) + latmask = np.tile(latmask[None], (self.init_latent.shape[1], 1, 1)) + + self.mask = torch.asarray(1.0 - latmask).to(shared.device).type(devices.dtype) + self.nmask = torch.asarray(latmask).to(shared.device).type(devices.dtype) + + # this needs to be fixed to be done in sample() using actual seeds for batches + if self.inpainting_fill == 2: + self.init_latent = self.init_latent * self.mask + create_random_tensors(self.init_latent.shape[1:], all_seeds[0:self.init_latent.shape[0]]) * self.nmask + self.extra_generation_params["Masked content"] = 'latent noise' + + elif self.inpainting_fill == 3: + self.init_latent = self.init_latent * self.mask + self.extra_generation_params["Masked content"] = 'latent nothing' + + self.image_conditioning = self.img2img_image_conditioning(image * 2 - 1, self.init_latent, image_mask, self.mask_round) + + def sample(self, conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts): + x = self.rng.next() + + if self.initial_noise_multiplier != 1.0: + self.extra_generation_params["Noise multiplier"] = self.initial_noise_multiplier + x *= self.initial_noise_multiplier + + if self.scripts is not None: + self.scripts.process_before_every_sampling( + p=self, + x=self.init_latent, + noise=x, + c=conditioning, + uc=unconditional_conditioning + ) + samples = self.sampler.sample_img2img(self, self.init_latent, x, conditioning, unconditional_conditioning, image_conditioning=self.image_conditioning) + + if self.mask is not None: + blended_samples = samples * self.nmask + self.init_latent * self.mask + + if self.scripts is not None: + mba = scripts.MaskBlendArgs(samples, self.nmask, self.init_latent, self.mask, blended_samples) + self.scripts.on_mask_blend(self, mba) + blended_samples = mba.blended_latent + + samples = blended_samples + + del x + devices.torch_gc() + + return samples + + def get_token_merging_ratio(self, for_hr=False): + return self.token_merging_ratio or ("token_merging_ratio" in self.override_settings and opts.token_merging_ratio) or opts.token_merging_ratio_img2img or opts.token_merging_ratio
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/processing.py
Document classes and their methods
import math from collections import namedtuple import torch from modules import prompt_parser, devices, sd_hijack, sd_emphasis from modules.shared import opts class PromptChunk: def __init__(self): self.tokens = [] self.multipliers = [] self.fixes = [] PromptChunkFix = namedtuple('PromptChunkFix', ['offset', 'embedding']) """An object of this type is a marker showing that textual inversion embedding's vectors have to placed at offset in the prompt chunk. Those objects are found in PromptChunk.fixes and, are placed into FrozenCLIPEmbedderWithCustomWordsBase.hijack.fixes, and finally are applied by sd_hijack.EmbeddingsWithFixes's forward function.""" class TextConditionalModel(torch.nn.Module): def __init__(self): super().__init__() self.hijack = sd_hijack.model_hijack self.chunk_length = 75 self.is_trainable = False self.input_key = 'txt' self.return_pooled = False self.comma_token = None self.id_start = None self.id_end = None self.id_pad = None def empty_chunk(self): chunk = PromptChunk() chunk.tokens = [self.id_start] + [self.id_end] * (self.chunk_length + 1) chunk.multipliers = [1.0] * (self.chunk_length + 2) return chunk def get_target_prompt_token_count(self, token_count): return math.ceil(max(token_count, 1) / self.chunk_length) * self.chunk_length def tokenize(self, texts): raise NotImplementedError def encode_with_transformers(self, tokens): raise NotImplementedError def encode_embedding_init_text(self, init_text, nvpt): raise NotImplementedError def tokenize_line(self, line): if opts.emphasis != "None": parsed = prompt_parser.parse_prompt_attention(line) else: parsed = [[line, 1.0]] tokenized = self.tokenize([text for text, _ in parsed]) chunks = [] chunk = PromptChunk() token_count = 0 last_comma = -1 def next_chunk(is_last=False): nonlocal token_count nonlocal last_comma nonlocal chunk if is_last: token_count += len(chunk.tokens) else: token_count += self.chunk_length to_add = self.chunk_length - len(chunk.tokens) if to_add > 0: chunk.tokens += [self.id_end] * to_add chunk.multipliers += [1.0] * to_add chunk.tokens = [self.id_start] + chunk.tokens + [self.id_end] chunk.multipliers = [1.0] + chunk.multipliers + [1.0] last_comma = -1 chunks.append(chunk) chunk = PromptChunk() for tokens, (text, weight) in zip(tokenized, parsed): if text == 'BREAK' and weight == -1: next_chunk() continue position = 0 while position < len(tokens): token = tokens[position] if token == self.comma_token: last_comma = len(chunk.tokens) # this is when we are at the end of allotted 75 tokens for the current chunk, and the current token is not a comma. opts.comma_padding_backtrack # is a setting that specifies that if there is a comma nearby, the text after the comma should be moved out of this chunk and into the next. elif opts.comma_padding_backtrack != 0 and len(chunk.tokens) == self.chunk_length and last_comma != -1 and len(chunk.tokens) - last_comma <= opts.comma_padding_backtrack: break_location = last_comma + 1 reloc_tokens = chunk.tokens[break_location:] reloc_mults = chunk.multipliers[break_location:] chunk.tokens = chunk.tokens[:break_location] chunk.multipliers = chunk.multipliers[:break_location] next_chunk() chunk.tokens = reloc_tokens chunk.multipliers = reloc_mults if len(chunk.tokens) == self.chunk_length: next_chunk() embedding, embedding_length_in_tokens = self.hijack.embedding_db.find_embedding_at_position(tokens, position) if embedding is None: chunk.tokens.append(token) chunk.multipliers.append(weight) position += 1 continue emb_len = int(embedding.vectors) if len(chunk.tokens) + emb_len > self.chunk_length: next_chunk() chunk.fixes.append(PromptChunkFix(len(chunk.tokens), embedding)) chunk.tokens += [0] * emb_len chunk.multipliers += [weight] * emb_len position += embedding_length_in_tokens if chunk.tokens or not chunks: next_chunk(is_last=True) return chunks, token_count def process_texts(self, texts): token_count = 0 cache = {} batch_chunks = [] for line in texts: if line in cache: chunks = cache[line] else: chunks, current_token_count = self.tokenize_line(line) token_count = max(current_token_count, token_count) cache[line] = chunks batch_chunks.append(chunks) return batch_chunks, token_count def forward(self, texts): batch_chunks, token_count = self.process_texts(texts) used_embeddings = {} chunk_count = max([len(x) for x in batch_chunks]) zs = [] for i in range(chunk_count): batch_chunk = [chunks[i] if i < len(chunks) else self.empty_chunk() for chunks in batch_chunks] tokens = [x.tokens for x in batch_chunk] multipliers = [x.multipliers for x in batch_chunk] self.hijack.fixes = [x.fixes for x in batch_chunk] for fixes in self.hijack.fixes: for _position, embedding in fixes: used_embeddings[embedding.name] = embedding devices.torch_npu_set_device() z = self.process_tokens(tokens, multipliers) zs.append(z) if opts.textual_inversion_add_hashes_to_infotext and used_embeddings: hashes = [] for name, embedding in used_embeddings.items(): shorthash = embedding.shorthash if not shorthash: continue name = name.replace(":", "").replace(",", "") hashes.append(f"{name}: {shorthash}") if hashes: if self.hijack.extra_generation_params.get("TI hashes"): hashes.append(self.hijack.extra_generation_params.get("TI hashes")) self.hijack.extra_generation_params["TI hashes"] = ", ".join(hashes) if any(x for x in texts if "(" in x or "[" in x) and opts.emphasis != "Original": self.hijack.extra_generation_params["Emphasis"] = opts.emphasis if self.return_pooled: return torch.hstack(zs), zs[0].pooled else: return torch.hstack(zs) def process_tokens(self, remade_batch_tokens, batch_multipliers): tokens = torch.asarray(remade_batch_tokens).to(devices.device) # this is for SD2: SD1 uses the same token for padding and end of text, while SD2 uses different ones. if self.id_end != self.id_pad: for batch_pos in range(len(remade_batch_tokens)): index = remade_batch_tokens[batch_pos].index(self.id_end) tokens[batch_pos, index+1:tokens.shape[1]] = self.id_pad z = self.encode_with_transformers(tokens) pooled = getattr(z, 'pooled', None) emphasis = sd_emphasis.get_current_option(opts.emphasis)() emphasis.tokens = remade_batch_tokens emphasis.multipliers = torch.asarray(batch_multipliers).to(devices.device) emphasis.z = z emphasis.after_transformers() z = emphasis.z if pooled is not None: z.pooled = pooled return z class FrozenCLIPEmbedderWithCustomWordsBase(TextConditionalModel): def __init__(self, wrapped, hijack): super().__init__() self.hijack = hijack self.wrapped = wrapped """Original FrozenCLIPEmbedder module; can also be FrozenOpenCLIPEmbedder or xlmr.BertSeriesModelWithTransformation, depending on model.""" self.is_trainable = getattr(wrapped, 'is_trainable', False) self.input_key = getattr(wrapped, 'input_key', 'txt') self.return_pooled = getattr(self.wrapped, 'return_pooled', False) self.legacy_ucg_val = None # for sgm codebase def forward(self, texts): if opts.use_old_emphasis_implementation: import modules.sd_hijack_clip_old return modules.sd_hijack_clip_old.forward_old(self, texts) return super().forward(texts) class FrozenCLIPEmbedderWithCustomWords(FrozenCLIPEmbedderWithCustomWordsBase): def __init__(self, wrapped, hijack): super().__init__(wrapped, hijack) self.tokenizer = wrapped.tokenizer vocab = self.tokenizer.get_vocab() self.comma_token = vocab.get(',</w>', None) self.token_mults = {} tokens_with_parens = [(k, v) for k, v in vocab.items() if '(' in k or ')' in k or '[' in k or ']' in k] for text, ident in tokens_with_parens: mult = 1.0 for c in text: if c == '[': mult /= 1.1 if c == ']': mult *= 1.1 if c == '(': mult *= 1.1 if c == ')': mult /= 1.1 if mult != 1.0: self.token_mults[ident] = mult self.id_start = self.wrapped.tokenizer.bos_token_id self.id_end = self.wrapped.tokenizer.eos_token_id self.id_pad = self.id_end def tokenize(self, texts): tokenized = self.wrapped.tokenizer(texts, truncation=False, add_special_tokens=False)["input_ids"] return tokenized def encode_with_transformers(self, tokens): outputs = self.wrapped.transformer(input_ids=tokens, output_hidden_states=-opts.CLIP_stop_at_last_layers) if opts.CLIP_stop_at_last_layers > 1: z = outputs.hidden_states[-opts.CLIP_stop_at_last_layers] z = self.wrapped.transformer.text_model.final_layer_norm(z) else: z = outputs.last_hidden_state return z def encode_embedding_init_text(self, init_text, nvpt): embedding_layer = self.wrapped.transformer.text_model.embeddings ids = self.wrapped.tokenizer(init_text, max_length=nvpt, return_tensors="pt", add_special_tokens=False)["input_ids"] embedded = embedding_layer.token_embedding.wrapped(ids.to(embedding_layer.token_embedding.wrapped.weight.device)).squeeze(0) return embedded class FrozenCLIPEmbedderForSDXLWithCustomWords(FrozenCLIPEmbedderWithCustomWords): def __init__(self, wrapped, hijack): super().__init__(wrapped, hijack) def encode_with_transformers(self, tokens): outputs = self.wrapped.transformer(input_ids=tokens, output_hidden_states=self.wrapped.layer == "hidden") if opts.sdxl_clip_l_skip is True: z = outputs.hidden_states[-opts.CLIP_stop_at_last_layers] elif self.wrapped.layer == "last": z = outputs.last_hidden_state else: z = outputs.hidden_states[self.wrapped.layer_idx] return z
--- +++ @@ -1,336 +1,384 @@-import math -from collections import namedtuple - -import torch - -from modules import prompt_parser, devices, sd_hijack, sd_emphasis -from modules.shared import opts - - -class PromptChunk: - - def __init__(self): - self.tokens = [] - self.multipliers = [] - self.fixes = [] - - -PromptChunkFix = namedtuple('PromptChunkFix', ['offset', 'embedding']) -"""An object of this type is a marker showing that textual inversion embedding's vectors have to placed at offset in the prompt -chunk. Those objects are found in PromptChunk.fixes and, are placed into FrozenCLIPEmbedderWithCustomWordsBase.hijack.fixes, and finally -are applied by sd_hijack.EmbeddingsWithFixes's forward function.""" - - -class TextConditionalModel(torch.nn.Module): - def __init__(self): - super().__init__() - - self.hijack = sd_hijack.model_hijack - self.chunk_length = 75 - - self.is_trainable = False - self.input_key = 'txt' - self.return_pooled = False - - self.comma_token = None - self.id_start = None - self.id_end = None - self.id_pad = None - - def empty_chunk(self): - - chunk = PromptChunk() - chunk.tokens = [self.id_start] + [self.id_end] * (self.chunk_length + 1) - chunk.multipliers = [1.0] * (self.chunk_length + 2) - return chunk - - def get_target_prompt_token_count(self, token_count): - - return math.ceil(max(token_count, 1) / self.chunk_length) * self.chunk_length - - def tokenize(self, texts): - - raise NotImplementedError - - def encode_with_transformers(self, tokens): - - raise NotImplementedError - - def encode_embedding_init_text(self, init_text, nvpt): - - raise NotImplementedError - - def tokenize_line(self, line): - - if opts.emphasis != "None": - parsed = prompt_parser.parse_prompt_attention(line) - else: - parsed = [[line, 1.0]] - - tokenized = self.tokenize([text for text, _ in parsed]) - - chunks = [] - chunk = PromptChunk() - token_count = 0 - last_comma = -1 - - def next_chunk(is_last=False): - nonlocal token_count - nonlocal last_comma - nonlocal chunk - - if is_last: - token_count += len(chunk.tokens) - else: - token_count += self.chunk_length - - to_add = self.chunk_length - len(chunk.tokens) - if to_add > 0: - chunk.tokens += [self.id_end] * to_add - chunk.multipliers += [1.0] * to_add - - chunk.tokens = [self.id_start] + chunk.tokens + [self.id_end] - chunk.multipliers = [1.0] + chunk.multipliers + [1.0] - - last_comma = -1 - chunks.append(chunk) - chunk = PromptChunk() - - for tokens, (text, weight) in zip(tokenized, parsed): - if text == 'BREAK' and weight == -1: - next_chunk() - continue - - position = 0 - while position < len(tokens): - token = tokens[position] - - if token == self.comma_token: - last_comma = len(chunk.tokens) - - # this is when we are at the end of allotted 75 tokens for the current chunk, and the current token is not a comma. opts.comma_padding_backtrack - # is a setting that specifies that if there is a comma nearby, the text after the comma should be moved out of this chunk and into the next. - elif opts.comma_padding_backtrack != 0 and len(chunk.tokens) == self.chunk_length and last_comma != -1 and len(chunk.tokens) - last_comma <= opts.comma_padding_backtrack: - break_location = last_comma + 1 - - reloc_tokens = chunk.tokens[break_location:] - reloc_mults = chunk.multipliers[break_location:] - - chunk.tokens = chunk.tokens[:break_location] - chunk.multipliers = chunk.multipliers[:break_location] - - next_chunk() - chunk.tokens = reloc_tokens - chunk.multipliers = reloc_mults - - if len(chunk.tokens) == self.chunk_length: - next_chunk() - - embedding, embedding_length_in_tokens = self.hijack.embedding_db.find_embedding_at_position(tokens, position) - if embedding is None: - chunk.tokens.append(token) - chunk.multipliers.append(weight) - position += 1 - continue - - emb_len = int(embedding.vectors) - if len(chunk.tokens) + emb_len > self.chunk_length: - next_chunk() - - chunk.fixes.append(PromptChunkFix(len(chunk.tokens), embedding)) - - chunk.tokens += [0] * emb_len - chunk.multipliers += [weight] * emb_len - position += embedding_length_in_tokens - - if chunk.tokens or not chunks: - next_chunk(is_last=True) - - return chunks, token_count - - def process_texts(self, texts): - - token_count = 0 - - cache = {} - batch_chunks = [] - for line in texts: - if line in cache: - chunks = cache[line] - else: - chunks, current_token_count = self.tokenize_line(line) - token_count = max(current_token_count, token_count) - - cache[line] = chunks - - batch_chunks.append(chunks) - - return batch_chunks, token_count - - def forward(self, texts): - - batch_chunks, token_count = self.process_texts(texts) - - used_embeddings = {} - chunk_count = max([len(x) for x in batch_chunks]) - - zs = [] - for i in range(chunk_count): - batch_chunk = [chunks[i] if i < len(chunks) else self.empty_chunk() for chunks in batch_chunks] - - tokens = [x.tokens for x in batch_chunk] - multipliers = [x.multipliers for x in batch_chunk] - self.hijack.fixes = [x.fixes for x in batch_chunk] - - for fixes in self.hijack.fixes: - for _position, embedding in fixes: - used_embeddings[embedding.name] = embedding - devices.torch_npu_set_device() - z = self.process_tokens(tokens, multipliers) - zs.append(z) - - if opts.textual_inversion_add_hashes_to_infotext and used_embeddings: - hashes = [] - for name, embedding in used_embeddings.items(): - shorthash = embedding.shorthash - if not shorthash: - continue - - name = name.replace(":", "").replace(",", "") - hashes.append(f"{name}: {shorthash}") - - if hashes: - if self.hijack.extra_generation_params.get("TI hashes"): - hashes.append(self.hijack.extra_generation_params.get("TI hashes")) - self.hijack.extra_generation_params["TI hashes"] = ", ".join(hashes) - - if any(x for x in texts if "(" in x or "[" in x) and opts.emphasis != "Original": - self.hijack.extra_generation_params["Emphasis"] = opts.emphasis - - if self.return_pooled: - return torch.hstack(zs), zs[0].pooled - else: - return torch.hstack(zs) - - def process_tokens(self, remade_batch_tokens, batch_multipliers): - tokens = torch.asarray(remade_batch_tokens).to(devices.device) - - # this is for SD2: SD1 uses the same token for padding and end of text, while SD2 uses different ones. - if self.id_end != self.id_pad: - for batch_pos in range(len(remade_batch_tokens)): - index = remade_batch_tokens[batch_pos].index(self.id_end) - tokens[batch_pos, index+1:tokens.shape[1]] = self.id_pad - - z = self.encode_with_transformers(tokens) - - pooled = getattr(z, 'pooled', None) - - emphasis = sd_emphasis.get_current_option(opts.emphasis)() - emphasis.tokens = remade_batch_tokens - emphasis.multipliers = torch.asarray(batch_multipliers).to(devices.device) - emphasis.z = z - - emphasis.after_transformers() - - z = emphasis.z - - if pooled is not None: - z.pooled = pooled - - return z - - -class FrozenCLIPEmbedderWithCustomWordsBase(TextConditionalModel): - - def __init__(self, wrapped, hijack): - super().__init__() - - self.hijack = hijack - - self.wrapped = wrapped - """Original FrozenCLIPEmbedder module; can also be FrozenOpenCLIPEmbedder or xlmr.BertSeriesModelWithTransformation, - depending on model.""" - - self.is_trainable = getattr(wrapped, 'is_trainable', False) - self.input_key = getattr(wrapped, 'input_key', 'txt') - self.return_pooled = getattr(self.wrapped, 'return_pooled', False) - - self.legacy_ucg_val = None # for sgm codebase - - def forward(self, texts): - if opts.use_old_emphasis_implementation: - import modules.sd_hijack_clip_old - return modules.sd_hijack_clip_old.forward_old(self, texts) - - return super().forward(texts) - - -class FrozenCLIPEmbedderWithCustomWords(FrozenCLIPEmbedderWithCustomWordsBase): - def __init__(self, wrapped, hijack): - super().__init__(wrapped, hijack) - self.tokenizer = wrapped.tokenizer - - vocab = self.tokenizer.get_vocab() - - self.comma_token = vocab.get(',</w>', None) - - self.token_mults = {} - tokens_with_parens = [(k, v) for k, v in vocab.items() if '(' in k or ')' in k or '[' in k or ']' in k] - for text, ident in tokens_with_parens: - mult = 1.0 - for c in text: - if c == '[': - mult /= 1.1 - if c == ']': - mult *= 1.1 - if c == '(': - mult *= 1.1 - if c == ')': - mult /= 1.1 - - if mult != 1.0: - self.token_mults[ident] = mult - - self.id_start = self.wrapped.tokenizer.bos_token_id - self.id_end = self.wrapped.tokenizer.eos_token_id - self.id_pad = self.id_end - - def tokenize(self, texts): - tokenized = self.wrapped.tokenizer(texts, truncation=False, add_special_tokens=False)["input_ids"] - - return tokenized - - def encode_with_transformers(self, tokens): - outputs = self.wrapped.transformer(input_ids=tokens, output_hidden_states=-opts.CLIP_stop_at_last_layers) - - if opts.CLIP_stop_at_last_layers > 1: - z = outputs.hidden_states[-opts.CLIP_stop_at_last_layers] - z = self.wrapped.transformer.text_model.final_layer_norm(z) - else: - z = outputs.last_hidden_state - - return z - - def encode_embedding_init_text(self, init_text, nvpt): - embedding_layer = self.wrapped.transformer.text_model.embeddings - ids = self.wrapped.tokenizer(init_text, max_length=nvpt, return_tensors="pt", add_special_tokens=False)["input_ids"] - embedded = embedding_layer.token_embedding.wrapped(ids.to(embedding_layer.token_embedding.wrapped.weight.device)).squeeze(0) - - return embedded - - -class FrozenCLIPEmbedderForSDXLWithCustomWords(FrozenCLIPEmbedderWithCustomWords): - def __init__(self, wrapped, hijack): - super().__init__(wrapped, hijack) - - def encode_with_transformers(self, tokens): - outputs = self.wrapped.transformer(input_ids=tokens, output_hidden_states=self.wrapped.layer == "hidden") - - if opts.sdxl_clip_l_skip is True: - z = outputs.hidden_states[-opts.CLIP_stop_at_last_layers] - elif self.wrapped.layer == "last": - z = outputs.last_hidden_state - else: - z = outputs.hidden_states[self.wrapped.layer_idx] - - return z+import math +from collections import namedtuple + +import torch + +from modules import prompt_parser, devices, sd_hijack, sd_emphasis +from modules.shared import opts + + +class PromptChunk: + """ + This object contains token ids, weight (multipliers:1.4) and textual inversion embedding info for a chunk of prompt. + If a prompt is short, it is represented by one PromptChunk, otherwise, multiple are necessary. + Each PromptChunk contains an exact amount of tokens - 77, which includes one for start and end token, + so just 75 tokens from prompt. + """ + + def __init__(self): + self.tokens = [] + self.multipliers = [] + self.fixes = [] + + +PromptChunkFix = namedtuple('PromptChunkFix', ['offset', 'embedding']) +"""An object of this type is a marker showing that textual inversion embedding's vectors have to placed at offset in the prompt +chunk. Those objects are found in PromptChunk.fixes and, are placed into FrozenCLIPEmbedderWithCustomWordsBase.hijack.fixes, and finally +are applied by sd_hijack.EmbeddingsWithFixes's forward function.""" + + +class TextConditionalModel(torch.nn.Module): + def __init__(self): + super().__init__() + + self.hijack = sd_hijack.model_hijack + self.chunk_length = 75 + + self.is_trainable = False + self.input_key = 'txt' + self.return_pooled = False + + self.comma_token = None + self.id_start = None + self.id_end = None + self.id_pad = None + + def empty_chunk(self): + """creates an empty PromptChunk and returns it""" + + chunk = PromptChunk() + chunk.tokens = [self.id_start] + [self.id_end] * (self.chunk_length + 1) + chunk.multipliers = [1.0] * (self.chunk_length + 2) + return chunk + + def get_target_prompt_token_count(self, token_count): + """returns the maximum number of tokens a prompt of a known length can have before it requires one more PromptChunk to be represented""" + + return math.ceil(max(token_count, 1) / self.chunk_length) * self.chunk_length + + def tokenize(self, texts): + """Converts a batch of texts into a batch of token ids""" + + raise NotImplementedError + + def encode_with_transformers(self, tokens): + """ + converts a batch of token ids (in python lists) into a single tensor with numeric representation of those tokens; + All python lists with tokens are assumed to have same length, usually 77. + if input is a list with B elements and each element has T tokens, expected output shape is (B, T, C), where C depends on + model - can be 768 and 1024. + Among other things, this call will read self.hijack.fixes, apply it to its inputs, and clear it (setting it to None). + """ + + raise NotImplementedError + + def encode_embedding_init_text(self, init_text, nvpt): + """Converts text into a tensor with this text's tokens' embeddings. Note that those are embeddings before they are passed through + transformers. nvpt is used as a maximum length in tokens. If text produces less teokens than nvpt, only this many is returned.""" + + raise NotImplementedError + + def tokenize_line(self, line): + """ + this transforms a single prompt into a list of PromptChunk objects - as many as needed to + represent the prompt. + Returns the list and the total number of tokens in the prompt. + """ + + if opts.emphasis != "None": + parsed = prompt_parser.parse_prompt_attention(line) + else: + parsed = [[line, 1.0]] + + tokenized = self.tokenize([text for text, _ in parsed]) + + chunks = [] + chunk = PromptChunk() + token_count = 0 + last_comma = -1 + + def next_chunk(is_last=False): + """puts current chunk into the list of results and produces the next one - empty; + if is_last is true, tokens <end-of-text> tokens at the end won't add to token_count""" + nonlocal token_count + nonlocal last_comma + nonlocal chunk + + if is_last: + token_count += len(chunk.tokens) + else: + token_count += self.chunk_length + + to_add = self.chunk_length - len(chunk.tokens) + if to_add > 0: + chunk.tokens += [self.id_end] * to_add + chunk.multipliers += [1.0] * to_add + + chunk.tokens = [self.id_start] + chunk.tokens + [self.id_end] + chunk.multipliers = [1.0] + chunk.multipliers + [1.0] + + last_comma = -1 + chunks.append(chunk) + chunk = PromptChunk() + + for tokens, (text, weight) in zip(tokenized, parsed): + if text == 'BREAK' and weight == -1: + next_chunk() + continue + + position = 0 + while position < len(tokens): + token = tokens[position] + + if token == self.comma_token: + last_comma = len(chunk.tokens) + + # this is when we are at the end of allotted 75 tokens for the current chunk, and the current token is not a comma. opts.comma_padding_backtrack + # is a setting that specifies that if there is a comma nearby, the text after the comma should be moved out of this chunk and into the next. + elif opts.comma_padding_backtrack != 0 and len(chunk.tokens) == self.chunk_length and last_comma != -1 and len(chunk.tokens) - last_comma <= opts.comma_padding_backtrack: + break_location = last_comma + 1 + + reloc_tokens = chunk.tokens[break_location:] + reloc_mults = chunk.multipliers[break_location:] + + chunk.tokens = chunk.tokens[:break_location] + chunk.multipliers = chunk.multipliers[:break_location] + + next_chunk() + chunk.tokens = reloc_tokens + chunk.multipliers = reloc_mults + + if len(chunk.tokens) == self.chunk_length: + next_chunk() + + embedding, embedding_length_in_tokens = self.hijack.embedding_db.find_embedding_at_position(tokens, position) + if embedding is None: + chunk.tokens.append(token) + chunk.multipliers.append(weight) + position += 1 + continue + + emb_len = int(embedding.vectors) + if len(chunk.tokens) + emb_len > self.chunk_length: + next_chunk() + + chunk.fixes.append(PromptChunkFix(len(chunk.tokens), embedding)) + + chunk.tokens += [0] * emb_len + chunk.multipliers += [weight] * emb_len + position += embedding_length_in_tokens + + if chunk.tokens or not chunks: + next_chunk(is_last=True) + + return chunks, token_count + + def process_texts(self, texts): + """ + Accepts a list of texts and calls tokenize_line() on each, with cache. Returns the list of results and maximum + length, in tokens, of all texts. + """ + + token_count = 0 + + cache = {} + batch_chunks = [] + for line in texts: + if line in cache: + chunks = cache[line] + else: + chunks, current_token_count = self.tokenize_line(line) + token_count = max(current_token_count, token_count) + + cache[line] = chunks + + batch_chunks.append(chunks) + + return batch_chunks, token_count + + def forward(self, texts): + """ + Accepts an array of texts; Passes texts through transformers network to create a tensor with numerical representation of those texts. + Returns a tensor with shape of (B, T, C), where B is length of the array; T is length, in tokens, of texts (including padding) - T will + be a multiple of 77; and C is dimensionality of each token - for SD1 it's 768, for SD2 it's 1024, and for SDXL it's 1280. + An example shape returned by this function can be: (2, 77, 768). + For SDXL, instead of returning one tensor avobe, it returns a tuple with two: the other one with shape (B, 1280) with pooled values. + Webui usually sends just one text at a time through this function - the only time when texts is an array with more than one element + is when you do prompt editing: "a picture of a [cat:dog:0.4] eating ice cream" + """ + + batch_chunks, token_count = self.process_texts(texts) + + used_embeddings = {} + chunk_count = max([len(x) for x in batch_chunks]) + + zs = [] + for i in range(chunk_count): + batch_chunk = [chunks[i] if i < len(chunks) else self.empty_chunk() for chunks in batch_chunks] + + tokens = [x.tokens for x in batch_chunk] + multipliers = [x.multipliers for x in batch_chunk] + self.hijack.fixes = [x.fixes for x in batch_chunk] + + for fixes in self.hijack.fixes: + for _position, embedding in fixes: + used_embeddings[embedding.name] = embedding + devices.torch_npu_set_device() + z = self.process_tokens(tokens, multipliers) + zs.append(z) + + if opts.textual_inversion_add_hashes_to_infotext and used_embeddings: + hashes = [] + for name, embedding in used_embeddings.items(): + shorthash = embedding.shorthash + if not shorthash: + continue + + name = name.replace(":", "").replace(",", "") + hashes.append(f"{name}: {shorthash}") + + if hashes: + if self.hijack.extra_generation_params.get("TI hashes"): + hashes.append(self.hijack.extra_generation_params.get("TI hashes")) + self.hijack.extra_generation_params["TI hashes"] = ", ".join(hashes) + + if any(x for x in texts if "(" in x or "[" in x) and opts.emphasis != "Original": + self.hijack.extra_generation_params["Emphasis"] = opts.emphasis + + if self.return_pooled: + return torch.hstack(zs), zs[0].pooled + else: + return torch.hstack(zs) + + def process_tokens(self, remade_batch_tokens, batch_multipliers): + """ + sends one single prompt chunk to be encoded by transformers neural network. + remade_batch_tokens is a batch of tokens - a list, where every element is a list of tokens; usually + there are exactly 77 tokens in the list. batch_multipliers is the same but for multipliers instead of tokens. + Multipliers are used to give more or less weight to the outputs of transformers network. Each multiplier + corresponds to one token. + """ + tokens = torch.asarray(remade_batch_tokens).to(devices.device) + + # this is for SD2: SD1 uses the same token for padding and end of text, while SD2 uses different ones. + if self.id_end != self.id_pad: + for batch_pos in range(len(remade_batch_tokens)): + index = remade_batch_tokens[batch_pos].index(self.id_end) + tokens[batch_pos, index+1:tokens.shape[1]] = self.id_pad + + z = self.encode_with_transformers(tokens) + + pooled = getattr(z, 'pooled', None) + + emphasis = sd_emphasis.get_current_option(opts.emphasis)() + emphasis.tokens = remade_batch_tokens + emphasis.multipliers = torch.asarray(batch_multipliers).to(devices.device) + emphasis.z = z + + emphasis.after_transformers() + + z = emphasis.z + + if pooled is not None: + z.pooled = pooled + + return z + + +class FrozenCLIPEmbedderWithCustomWordsBase(TextConditionalModel): + """A pytorch module that is a wrapper for FrozenCLIPEmbedder module. it enhances FrozenCLIPEmbedder, making it possible to + have unlimited prompt length and assign weights to tokens in prompt. + """ + + def __init__(self, wrapped, hijack): + super().__init__() + + self.hijack = hijack + + self.wrapped = wrapped + """Original FrozenCLIPEmbedder module; can also be FrozenOpenCLIPEmbedder or xlmr.BertSeriesModelWithTransformation, + depending on model.""" + + self.is_trainable = getattr(wrapped, 'is_trainable', False) + self.input_key = getattr(wrapped, 'input_key', 'txt') + self.return_pooled = getattr(self.wrapped, 'return_pooled', False) + + self.legacy_ucg_val = None # for sgm codebase + + def forward(self, texts): + if opts.use_old_emphasis_implementation: + import modules.sd_hijack_clip_old + return modules.sd_hijack_clip_old.forward_old(self, texts) + + return super().forward(texts) + + +class FrozenCLIPEmbedderWithCustomWords(FrozenCLIPEmbedderWithCustomWordsBase): + def __init__(self, wrapped, hijack): + super().__init__(wrapped, hijack) + self.tokenizer = wrapped.tokenizer + + vocab = self.tokenizer.get_vocab() + + self.comma_token = vocab.get(',</w>', None) + + self.token_mults = {} + tokens_with_parens = [(k, v) for k, v in vocab.items() if '(' in k or ')' in k or '[' in k or ']' in k] + for text, ident in tokens_with_parens: + mult = 1.0 + for c in text: + if c == '[': + mult /= 1.1 + if c == ']': + mult *= 1.1 + if c == '(': + mult *= 1.1 + if c == ')': + mult /= 1.1 + + if mult != 1.0: + self.token_mults[ident] = mult + + self.id_start = self.wrapped.tokenizer.bos_token_id + self.id_end = self.wrapped.tokenizer.eos_token_id + self.id_pad = self.id_end + + def tokenize(self, texts): + tokenized = self.wrapped.tokenizer(texts, truncation=False, add_special_tokens=False)["input_ids"] + + return tokenized + + def encode_with_transformers(self, tokens): + outputs = self.wrapped.transformer(input_ids=tokens, output_hidden_states=-opts.CLIP_stop_at_last_layers) + + if opts.CLIP_stop_at_last_layers > 1: + z = outputs.hidden_states[-opts.CLIP_stop_at_last_layers] + z = self.wrapped.transformer.text_model.final_layer_norm(z) + else: + z = outputs.last_hidden_state + + return z + + def encode_embedding_init_text(self, init_text, nvpt): + embedding_layer = self.wrapped.transformer.text_model.embeddings + ids = self.wrapped.tokenizer(init_text, max_length=nvpt, return_tensors="pt", add_special_tokens=False)["input_ids"] + embedded = embedding_layer.token_embedding.wrapped(ids.to(embedding_layer.token_embedding.wrapped.weight.device)).squeeze(0) + + return embedded + + +class FrozenCLIPEmbedderForSDXLWithCustomWords(FrozenCLIPEmbedderWithCustomWords): + def __init__(self, wrapped, hijack): + super().__init__(wrapped, hijack) + + def encode_with_transformers(self, tokens): + outputs = self.wrapped.transformer(input_ids=tokens, output_hidden_states=self.wrapped.layer == "hidden") + + if opts.sdxl_clip_l_skip is True: + z = outputs.hidden_states[-opts.CLIP_stop_at_last_layers] + elif self.wrapped.layer == "last": + z = outputs.last_hidden_state + else: + z = outputs.hidden_states[self.wrapped.layer_idx] + + return z
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_hijack_clip.py
Add docstrings that explain purpose and usage
import ldm.modules.encoders.modules import open_clip import torch import transformers.utils.hub from modules import shared class ReplaceHelper: def __init__(self): self.replaced = [] def replace(self, obj, field, func): original = getattr(obj, field, None) if original is None: return None self.replaced.append((obj, field, original)) setattr(obj, field, func) return original def restore(self): for obj, field, original in self.replaced: setattr(obj, field, original) self.replaced.clear() class DisableInitialization(ReplaceHelper): def __init__(self, disable_clip=True): super().__init__() self.disable_clip = disable_clip def replace(self, obj, field, func): original = getattr(obj, field, None) if original is None: return None self.replaced.append((obj, field, original)) setattr(obj, field, func) return original def __enter__(self): def do_nothing(*args, **kwargs): pass def create_model_and_transforms_without_pretrained(*args, pretrained=None, **kwargs): return self.create_model_and_transforms(*args, pretrained=None, **kwargs) def CLIPTextModel_from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs): res = self.CLIPTextModel_from_pretrained(None, *model_args, config=pretrained_model_name_or_path, state_dict={}, **kwargs) res.name_or_path = pretrained_model_name_or_path return res def transformers_modeling_utils_load_pretrained_model(*args, **kwargs): args = args[0:3] + ('/', ) + args[4:] # resolved_archive_file; must set it to something to prevent what seems to be a bug return self.transformers_modeling_utils_load_pretrained_model(*args, **kwargs) def transformers_utils_hub_get_file_from_cache(original, url, *args, **kwargs): # this file is always 404, prevent making request if url == 'https://huggingface.co/openai/clip-vit-large-patch14/resolve/main/added_tokens.json' or url == 'openai/clip-vit-large-patch14' and args[0] == 'added_tokens.json': return None try: res = original(url, *args, local_files_only=True, **kwargs) if res is None: res = original(url, *args, local_files_only=False, **kwargs) return res except Exception: return original(url, *args, local_files_only=False, **kwargs) def transformers_utils_hub_get_from_cache(url, *args, local_files_only=False, **kwargs): return transformers_utils_hub_get_file_from_cache(self.transformers_utils_hub_get_from_cache, url, *args, **kwargs) def transformers_tokenization_utils_base_cached_file(url, *args, local_files_only=False, **kwargs): return transformers_utils_hub_get_file_from_cache(self.transformers_tokenization_utils_base_cached_file, url, *args, **kwargs) def transformers_configuration_utils_cached_file(url, *args, local_files_only=False, **kwargs): return transformers_utils_hub_get_file_from_cache(self.transformers_configuration_utils_cached_file, url, *args, **kwargs) self.replace(torch.nn.init, 'kaiming_uniform_', do_nothing) self.replace(torch.nn.init, '_no_grad_normal_', do_nothing) self.replace(torch.nn.init, '_no_grad_uniform_', do_nothing) if self.disable_clip: self.create_model_and_transforms = self.replace(open_clip, 'create_model_and_transforms', create_model_and_transforms_without_pretrained) self.CLIPTextModel_from_pretrained = self.replace(ldm.modules.encoders.modules.CLIPTextModel, 'from_pretrained', CLIPTextModel_from_pretrained) self.transformers_modeling_utils_load_pretrained_model = self.replace(transformers.modeling_utils.PreTrainedModel, '_load_pretrained_model', transformers_modeling_utils_load_pretrained_model) self.transformers_tokenization_utils_base_cached_file = self.replace(transformers.tokenization_utils_base, 'cached_file', transformers_tokenization_utils_base_cached_file) self.transformers_configuration_utils_cached_file = self.replace(transformers.configuration_utils, 'cached_file', transformers_configuration_utils_cached_file) self.transformers_utils_hub_get_from_cache = self.replace(transformers.utils.hub, 'get_from_cache', transformers_utils_hub_get_from_cache) def __exit__(self, exc_type, exc_val, exc_tb): self.restore() class InitializeOnMeta(ReplaceHelper): def __enter__(self): if shared.cmd_opts.disable_model_loading_ram_optimization: return def set_device(x): x["device"] = "meta" return x linear_init = self.replace(torch.nn.Linear, '__init__', lambda *args, **kwargs: linear_init(*args, **set_device(kwargs))) conv2d_init = self.replace(torch.nn.Conv2d, '__init__', lambda *args, **kwargs: conv2d_init(*args, **set_device(kwargs))) mha_init = self.replace(torch.nn.MultiheadAttention, '__init__', lambda *args, **kwargs: mha_init(*args, **set_device(kwargs))) self.replace(torch.nn.Module, 'to', lambda *args, **kwargs: None) def __exit__(self, exc_type, exc_val, exc_tb): self.restore() class LoadStateDictOnMeta(ReplaceHelper): def __init__(self, state_dict, device, weight_dtype_conversion=None): super().__init__() self.state_dict = state_dict self.device = device self.weight_dtype_conversion = weight_dtype_conversion or {} self.default_dtype = self.weight_dtype_conversion.get('') def get_weight_dtype(self, key): key_first_term, _ = key.split('.', 1) return self.weight_dtype_conversion.get(key_first_term, self.default_dtype) def __enter__(self): if shared.cmd_opts.disable_model_loading_ram_optimization: return sd = self.state_dict device = self.device def load_from_state_dict(original, module, state_dict, prefix, *args, **kwargs): used_param_keys = [] for name, param in module._parameters.items(): if param is None: continue key = prefix + name sd_param = sd.pop(key, None) if sd_param is not None: state_dict[key] = sd_param.to(dtype=self.get_weight_dtype(key)) used_param_keys.append(key) if param.is_meta: dtype = sd_param.dtype if sd_param is not None else param.dtype module._parameters[name] = torch.nn.parameter.Parameter(torch.zeros_like(param, device=device, dtype=dtype), requires_grad=param.requires_grad) for name in module._buffers: key = prefix + name sd_param = sd.pop(key, None) if sd_param is not None: state_dict[key] = sd_param used_param_keys.append(key) original(module, state_dict, prefix, *args, **kwargs) for key in used_param_keys: state_dict.pop(key, None) def load_state_dict(original, module, state_dict, strict=True): if state_dict is sd: state_dict = {k: v.to(device="meta", dtype=v.dtype) for k, v in state_dict.items()} original(module, state_dict, strict=strict) module_load_state_dict = self.replace(torch.nn.Module, 'load_state_dict', lambda *args, **kwargs: load_state_dict(module_load_state_dict, *args, **kwargs)) module_load_from_state_dict = self.replace(torch.nn.Module, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(module_load_from_state_dict, *args, **kwargs)) linear_load_from_state_dict = self.replace(torch.nn.Linear, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(linear_load_from_state_dict, *args, **kwargs)) conv2d_load_from_state_dict = self.replace(torch.nn.Conv2d, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(conv2d_load_from_state_dict, *args, **kwargs)) mha_load_from_state_dict = self.replace(torch.nn.MultiheadAttention, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(mha_load_from_state_dict, *args, **kwargs)) layer_norm_load_from_state_dict = self.replace(torch.nn.LayerNorm, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(layer_norm_load_from_state_dict, *args, **kwargs)) group_norm_load_from_state_dict = self.replace(torch.nn.GroupNorm, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(group_norm_load_from_state_dict, *args, **kwargs)) def __exit__(self, exc_type, exc_val, exc_tb): self.restore()
--- +++ @@ -1,186 +1,232 @@-import ldm.modules.encoders.modules -import open_clip -import torch -import transformers.utils.hub - -from modules import shared - - -class ReplaceHelper: - def __init__(self): - self.replaced = [] - - def replace(self, obj, field, func): - original = getattr(obj, field, None) - if original is None: - return None - - self.replaced.append((obj, field, original)) - setattr(obj, field, func) - - return original - - def restore(self): - for obj, field, original in self.replaced: - setattr(obj, field, original) - - self.replaced.clear() - - -class DisableInitialization(ReplaceHelper): - - def __init__(self, disable_clip=True): - super().__init__() - self.disable_clip = disable_clip - - def replace(self, obj, field, func): - original = getattr(obj, field, None) - if original is None: - return None - - self.replaced.append((obj, field, original)) - setattr(obj, field, func) - - return original - - def __enter__(self): - def do_nothing(*args, **kwargs): - pass - - def create_model_and_transforms_without_pretrained(*args, pretrained=None, **kwargs): - return self.create_model_and_transforms(*args, pretrained=None, **kwargs) - - def CLIPTextModel_from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs): - res = self.CLIPTextModel_from_pretrained(None, *model_args, config=pretrained_model_name_or_path, state_dict={}, **kwargs) - res.name_or_path = pretrained_model_name_or_path - return res - - def transformers_modeling_utils_load_pretrained_model(*args, **kwargs): - args = args[0:3] + ('/', ) + args[4:] # resolved_archive_file; must set it to something to prevent what seems to be a bug - return self.transformers_modeling_utils_load_pretrained_model(*args, **kwargs) - - def transformers_utils_hub_get_file_from_cache(original, url, *args, **kwargs): - - # this file is always 404, prevent making request - if url == 'https://huggingface.co/openai/clip-vit-large-patch14/resolve/main/added_tokens.json' or url == 'openai/clip-vit-large-patch14' and args[0] == 'added_tokens.json': - return None - - try: - res = original(url, *args, local_files_only=True, **kwargs) - if res is None: - res = original(url, *args, local_files_only=False, **kwargs) - return res - except Exception: - return original(url, *args, local_files_only=False, **kwargs) - - def transformers_utils_hub_get_from_cache(url, *args, local_files_only=False, **kwargs): - return transformers_utils_hub_get_file_from_cache(self.transformers_utils_hub_get_from_cache, url, *args, **kwargs) - - def transformers_tokenization_utils_base_cached_file(url, *args, local_files_only=False, **kwargs): - return transformers_utils_hub_get_file_from_cache(self.transformers_tokenization_utils_base_cached_file, url, *args, **kwargs) - - def transformers_configuration_utils_cached_file(url, *args, local_files_only=False, **kwargs): - return transformers_utils_hub_get_file_from_cache(self.transformers_configuration_utils_cached_file, url, *args, **kwargs) - - self.replace(torch.nn.init, 'kaiming_uniform_', do_nothing) - self.replace(torch.nn.init, '_no_grad_normal_', do_nothing) - self.replace(torch.nn.init, '_no_grad_uniform_', do_nothing) - - if self.disable_clip: - self.create_model_and_transforms = self.replace(open_clip, 'create_model_and_transforms', create_model_and_transforms_without_pretrained) - self.CLIPTextModel_from_pretrained = self.replace(ldm.modules.encoders.modules.CLIPTextModel, 'from_pretrained', CLIPTextModel_from_pretrained) - self.transformers_modeling_utils_load_pretrained_model = self.replace(transformers.modeling_utils.PreTrainedModel, '_load_pretrained_model', transformers_modeling_utils_load_pretrained_model) - self.transformers_tokenization_utils_base_cached_file = self.replace(transformers.tokenization_utils_base, 'cached_file', transformers_tokenization_utils_base_cached_file) - self.transformers_configuration_utils_cached_file = self.replace(transformers.configuration_utils, 'cached_file', transformers_configuration_utils_cached_file) - self.transformers_utils_hub_get_from_cache = self.replace(transformers.utils.hub, 'get_from_cache', transformers_utils_hub_get_from_cache) - - def __exit__(self, exc_type, exc_val, exc_tb): - self.restore() - - -class InitializeOnMeta(ReplaceHelper): - - def __enter__(self): - if shared.cmd_opts.disable_model_loading_ram_optimization: - return - - def set_device(x): - x["device"] = "meta" - return x - - linear_init = self.replace(torch.nn.Linear, '__init__', lambda *args, **kwargs: linear_init(*args, **set_device(kwargs))) - conv2d_init = self.replace(torch.nn.Conv2d, '__init__', lambda *args, **kwargs: conv2d_init(*args, **set_device(kwargs))) - mha_init = self.replace(torch.nn.MultiheadAttention, '__init__', lambda *args, **kwargs: mha_init(*args, **set_device(kwargs))) - self.replace(torch.nn.Module, 'to', lambda *args, **kwargs: None) - - def __exit__(self, exc_type, exc_val, exc_tb): - self.restore() - - -class LoadStateDictOnMeta(ReplaceHelper): - - def __init__(self, state_dict, device, weight_dtype_conversion=None): - super().__init__() - self.state_dict = state_dict - self.device = device - self.weight_dtype_conversion = weight_dtype_conversion or {} - self.default_dtype = self.weight_dtype_conversion.get('') - - def get_weight_dtype(self, key): - key_first_term, _ = key.split('.', 1) - return self.weight_dtype_conversion.get(key_first_term, self.default_dtype) - - def __enter__(self): - if shared.cmd_opts.disable_model_loading_ram_optimization: - return - - sd = self.state_dict - device = self.device - - def load_from_state_dict(original, module, state_dict, prefix, *args, **kwargs): - used_param_keys = [] - - for name, param in module._parameters.items(): - if param is None: - continue - - key = prefix + name - sd_param = sd.pop(key, None) - if sd_param is not None: - state_dict[key] = sd_param.to(dtype=self.get_weight_dtype(key)) - used_param_keys.append(key) - - if param.is_meta: - dtype = sd_param.dtype if sd_param is not None else param.dtype - module._parameters[name] = torch.nn.parameter.Parameter(torch.zeros_like(param, device=device, dtype=dtype), requires_grad=param.requires_grad) - - for name in module._buffers: - key = prefix + name - - sd_param = sd.pop(key, None) - if sd_param is not None: - state_dict[key] = sd_param - used_param_keys.append(key) - - original(module, state_dict, prefix, *args, **kwargs) - - for key in used_param_keys: - state_dict.pop(key, None) - - def load_state_dict(original, module, state_dict, strict=True): - - if state_dict is sd: - state_dict = {k: v.to(device="meta", dtype=v.dtype) for k, v in state_dict.items()} - - original(module, state_dict, strict=strict) - - module_load_state_dict = self.replace(torch.nn.Module, 'load_state_dict', lambda *args, **kwargs: load_state_dict(module_load_state_dict, *args, **kwargs)) - module_load_from_state_dict = self.replace(torch.nn.Module, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(module_load_from_state_dict, *args, **kwargs)) - linear_load_from_state_dict = self.replace(torch.nn.Linear, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(linear_load_from_state_dict, *args, **kwargs)) - conv2d_load_from_state_dict = self.replace(torch.nn.Conv2d, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(conv2d_load_from_state_dict, *args, **kwargs)) - mha_load_from_state_dict = self.replace(torch.nn.MultiheadAttention, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(mha_load_from_state_dict, *args, **kwargs)) - layer_norm_load_from_state_dict = self.replace(torch.nn.LayerNorm, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(layer_norm_load_from_state_dict, *args, **kwargs)) - group_norm_load_from_state_dict = self.replace(torch.nn.GroupNorm, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(group_norm_load_from_state_dict, *args, **kwargs)) - - def __exit__(self, exc_type, exc_val, exc_tb): - self.restore()+import ldm.modules.encoders.modules +import open_clip +import torch +import transformers.utils.hub + +from modules import shared + + +class ReplaceHelper: + def __init__(self): + self.replaced = [] + + def replace(self, obj, field, func): + original = getattr(obj, field, None) + if original is None: + return None + + self.replaced.append((obj, field, original)) + setattr(obj, field, func) + + return original + + def restore(self): + for obj, field, original in self.replaced: + setattr(obj, field, original) + + self.replaced.clear() + + +class DisableInitialization(ReplaceHelper): + """ + When an object of this class enters a `with` block, it starts: + - preventing torch's layer initialization functions from working + - changes CLIP and OpenCLIP to not download model weights + - changes CLIP to not make requests to check if there is a new version of a file you already have + + When it leaves the block, it reverts everything to how it was before. + + Use it like this: + ``` + with DisableInitialization(): + do_things() + ``` + """ + + def __init__(self, disable_clip=True): + super().__init__() + self.disable_clip = disable_clip + + def replace(self, obj, field, func): + original = getattr(obj, field, None) + if original is None: + return None + + self.replaced.append((obj, field, original)) + setattr(obj, field, func) + + return original + + def __enter__(self): + def do_nothing(*args, **kwargs): + pass + + def create_model_and_transforms_without_pretrained(*args, pretrained=None, **kwargs): + return self.create_model_and_transforms(*args, pretrained=None, **kwargs) + + def CLIPTextModel_from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs): + res = self.CLIPTextModel_from_pretrained(None, *model_args, config=pretrained_model_name_or_path, state_dict={}, **kwargs) + res.name_or_path = pretrained_model_name_or_path + return res + + def transformers_modeling_utils_load_pretrained_model(*args, **kwargs): + args = args[0:3] + ('/', ) + args[4:] # resolved_archive_file; must set it to something to prevent what seems to be a bug + return self.transformers_modeling_utils_load_pretrained_model(*args, **kwargs) + + def transformers_utils_hub_get_file_from_cache(original, url, *args, **kwargs): + + # this file is always 404, prevent making request + if url == 'https://huggingface.co/openai/clip-vit-large-patch14/resolve/main/added_tokens.json' or url == 'openai/clip-vit-large-patch14' and args[0] == 'added_tokens.json': + return None + + try: + res = original(url, *args, local_files_only=True, **kwargs) + if res is None: + res = original(url, *args, local_files_only=False, **kwargs) + return res + except Exception: + return original(url, *args, local_files_only=False, **kwargs) + + def transformers_utils_hub_get_from_cache(url, *args, local_files_only=False, **kwargs): + return transformers_utils_hub_get_file_from_cache(self.transformers_utils_hub_get_from_cache, url, *args, **kwargs) + + def transformers_tokenization_utils_base_cached_file(url, *args, local_files_only=False, **kwargs): + return transformers_utils_hub_get_file_from_cache(self.transformers_tokenization_utils_base_cached_file, url, *args, **kwargs) + + def transformers_configuration_utils_cached_file(url, *args, local_files_only=False, **kwargs): + return transformers_utils_hub_get_file_from_cache(self.transformers_configuration_utils_cached_file, url, *args, **kwargs) + + self.replace(torch.nn.init, 'kaiming_uniform_', do_nothing) + self.replace(torch.nn.init, '_no_grad_normal_', do_nothing) + self.replace(torch.nn.init, '_no_grad_uniform_', do_nothing) + + if self.disable_clip: + self.create_model_and_transforms = self.replace(open_clip, 'create_model_and_transforms', create_model_and_transforms_without_pretrained) + self.CLIPTextModel_from_pretrained = self.replace(ldm.modules.encoders.modules.CLIPTextModel, 'from_pretrained', CLIPTextModel_from_pretrained) + self.transformers_modeling_utils_load_pretrained_model = self.replace(transformers.modeling_utils.PreTrainedModel, '_load_pretrained_model', transformers_modeling_utils_load_pretrained_model) + self.transformers_tokenization_utils_base_cached_file = self.replace(transformers.tokenization_utils_base, 'cached_file', transformers_tokenization_utils_base_cached_file) + self.transformers_configuration_utils_cached_file = self.replace(transformers.configuration_utils, 'cached_file', transformers_configuration_utils_cached_file) + self.transformers_utils_hub_get_from_cache = self.replace(transformers.utils.hub, 'get_from_cache', transformers_utils_hub_get_from_cache) + + def __exit__(self, exc_type, exc_val, exc_tb): + self.restore() + + +class InitializeOnMeta(ReplaceHelper): + """ + Context manager that causes all parameters for linear/conv2d/mha layers to be allocated on meta device, + which results in those parameters having no values and taking no memory. model.to() will be broken and + will need to be repaired by using LoadStateDictOnMeta below when loading params from state dict. + + Usage: + ``` + with sd_disable_initialization.InitializeOnMeta(): + sd_model = instantiate_from_config(sd_config.model) + ``` + """ + + def __enter__(self): + if shared.cmd_opts.disable_model_loading_ram_optimization: + return + + def set_device(x): + x["device"] = "meta" + return x + + linear_init = self.replace(torch.nn.Linear, '__init__', lambda *args, **kwargs: linear_init(*args, **set_device(kwargs))) + conv2d_init = self.replace(torch.nn.Conv2d, '__init__', lambda *args, **kwargs: conv2d_init(*args, **set_device(kwargs))) + mha_init = self.replace(torch.nn.MultiheadAttention, '__init__', lambda *args, **kwargs: mha_init(*args, **set_device(kwargs))) + self.replace(torch.nn.Module, 'to', lambda *args, **kwargs: None) + + def __exit__(self, exc_type, exc_val, exc_tb): + self.restore() + + +class LoadStateDictOnMeta(ReplaceHelper): + """ + Context manager that allows to read parameters from state_dict into a model that has some of its parameters in the meta device. + As those parameters are read from state_dict, they will be deleted from it, so by the end state_dict will be mostly empty, to save memory. + Meant to be used together with InitializeOnMeta above. + + Usage: + ``` + with sd_disable_initialization.LoadStateDictOnMeta(state_dict): + model.load_state_dict(state_dict, strict=False) + ``` + """ + + def __init__(self, state_dict, device, weight_dtype_conversion=None): + super().__init__() + self.state_dict = state_dict + self.device = device + self.weight_dtype_conversion = weight_dtype_conversion or {} + self.default_dtype = self.weight_dtype_conversion.get('') + + def get_weight_dtype(self, key): + key_first_term, _ = key.split('.', 1) + return self.weight_dtype_conversion.get(key_first_term, self.default_dtype) + + def __enter__(self): + if shared.cmd_opts.disable_model_loading_ram_optimization: + return + + sd = self.state_dict + device = self.device + + def load_from_state_dict(original, module, state_dict, prefix, *args, **kwargs): + used_param_keys = [] + + for name, param in module._parameters.items(): + if param is None: + continue + + key = prefix + name + sd_param = sd.pop(key, None) + if sd_param is not None: + state_dict[key] = sd_param.to(dtype=self.get_weight_dtype(key)) + used_param_keys.append(key) + + if param.is_meta: + dtype = sd_param.dtype if sd_param is not None else param.dtype + module._parameters[name] = torch.nn.parameter.Parameter(torch.zeros_like(param, device=device, dtype=dtype), requires_grad=param.requires_grad) + + for name in module._buffers: + key = prefix + name + + sd_param = sd.pop(key, None) + if sd_param is not None: + state_dict[key] = sd_param + used_param_keys.append(key) + + original(module, state_dict, prefix, *args, **kwargs) + + for key in used_param_keys: + state_dict.pop(key, None) + + def load_state_dict(original, module, state_dict, strict=True): + """torch makes a lot of copies of the dictionary with weights, so just deleting entries from state_dict does not help + because the same values are stored in multiple copies of the dict. The trick used here is to give torch a dict with + all weights on meta device, i.e. deleted, and then it doesn't matter how many copies torch makes. + + In _load_from_state_dict, the correct weight will be obtained from a single dict with the right weights (sd). + + The dangerous thing about this is if _load_from_state_dict is not called, (if some exotic module overloads + the function and does not call the original) the state dict will just fail to load because weights + would be on the meta device. + """ + + if state_dict is sd: + state_dict = {k: v.to(device="meta", dtype=v.dtype) for k, v in state_dict.items()} + + original(module, state_dict, strict=strict) + + module_load_state_dict = self.replace(torch.nn.Module, 'load_state_dict', lambda *args, **kwargs: load_state_dict(module_load_state_dict, *args, **kwargs)) + module_load_from_state_dict = self.replace(torch.nn.Module, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(module_load_from_state_dict, *args, **kwargs)) + linear_load_from_state_dict = self.replace(torch.nn.Linear, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(linear_load_from_state_dict, *args, **kwargs)) + conv2d_load_from_state_dict = self.replace(torch.nn.Conv2d, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(conv2d_load_from_state_dict, *args, **kwargs)) + mha_load_from_state_dict = self.replace(torch.nn.MultiheadAttention, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(mha_load_from_state_dict, *args, **kwargs)) + layer_norm_load_from_state_dict = self.replace(torch.nn.LayerNorm, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(layer_norm_load_from_state_dict, *args, **kwargs)) + group_norm_load_from_state_dict = self.replace(torch.nn.GroupNorm, '_load_from_state_dict', lambda *args, **kwargs: load_from_state_dict(group_norm_load_from_state_dict, *args, **kwargs)) + + def __exit__(self, exc_type, exc_val, exc_tb): + self.restore()
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_disable_initialization.py
Create Google-style docstrings for my code
import os import json import sys from dataclasses import dataclass import gradio as gr from modules import errors from modules.shared_cmd_options import cmd_opts from modules.paths_internal import script_path class OptionInfo: def __init__(self, default=None, label="", component=None, component_args=None, onchange=None, section=None, refresh=None, comment_before='', comment_after='', infotext=None, restrict_api=False, category_id=None): self.default = default self.label = label self.component = component self.component_args = component_args self.onchange = onchange self.section = section self.category_id = category_id self.refresh = refresh self.do_not_save = False self.comment_before = comment_before """HTML text that will be added after label in UI""" self.comment_after = comment_after """HTML text that will be added before label in UI""" self.infotext = infotext self.restrict_api = restrict_api """If True, the setting will not be accessible via API""" def link(self, label, url): self.comment_before += f"[<a href='{url}' target='_blank'>{label}</a>]" return self def js(self, label, js_func): self.comment_before += f"[<a onclick='{js_func}(); return false'>{label}</a>]" return self def info(self, info): self.comment_after += f"<span class='info'>({info})</span>" return self def html(self, html): self.comment_after += html return self def needs_restart(self): self.comment_after += " <span class='info'>(requires restart)</span>" return self def needs_reload_ui(self): self.comment_after += " <span class='info'>(requires Reload UI)</span>" return self class OptionHTML(OptionInfo): def __init__(self, text): super().__init__(str(text).strip(), label='', component=lambda **kwargs: gr.HTML(elem_classes="settings-info", **kwargs)) self.do_not_save = True def options_section(section_identifier, options_dict): for v in options_dict.values(): if len(section_identifier) == 2: v.section = section_identifier elif len(section_identifier) == 3: v.section = section_identifier[0:2] v.category_id = section_identifier[2] return options_dict options_builtin_fields = {"data_labels", "data", "restricted_opts", "typemap"} class Options: typemap = {int: float} def __init__(self, data_labels: dict[str, OptionInfo], restricted_opts): self.data_labels = data_labels self.data = {k: v.default for k, v in self.data_labels.items() if not v.do_not_save} self.restricted_opts = restricted_opts def __setattr__(self, key, value): if key in options_builtin_fields: return super(Options, self).__setattr__(key, value) if self.data is not None: if key in self.data or key in self.data_labels: # Check that settings aren't globally frozen assert not cmd_opts.freeze_settings, "changing settings is disabled" # Get the info related to the setting being changed info = self.data_labels.get(key, None) if info.do_not_save: return # Restrict component arguments comp_args = info.component_args if info else None if isinstance(comp_args, dict) and comp_args.get('visible', True) is False: raise RuntimeError(f"not possible to set '{key}' because it is restricted") # Check that this section isn't frozen if cmd_opts.freeze_settings_in_sections is not None: frozen_sections = list(map(str.strip, cmd_opts.freeze_settings_in_sections.split(','))) # Trim whitespace from section names section_key = info.section[0] section_name = info.section[1] assert section_key not in frozen_sections, f"not possible to set '{key}' because settings in section '{section_name}' ({section_key}) are frozen with --freeze-settings-in-sections" # Check that this section of the settings isn't frozen if cmd_opts.freeze_specific_settings is not None: frozen_keys = list(map(str.strip, cmd_opts.freeze_specific_settings.split(','))) # Trim whitespace from setting keys assert key not in frozen_keys, f"not possible to set '{key}' because this setting is frozen with --freeze-specific-settings" # Check shorthand option which disables editing options in "saving-paths" if cmd_opts.hide_ui_dir_config and key in self.restricted_opts: raise RuntimeError(f"not possible to set '{key}' because it is restricted with --hide_ui_dir_config") self.data[key] = value return return super(Options, self).__setattr__(key, value) def __getattr__(self, item): if item in options_builtin_fields: return super(Options, self).__getattribute__(item) if self.data is not None: if item in self.data: return self.data[item] if item in self.data_labels: return self.data_labels[item].default return super(Options, self).__getattribute__(item) def set(self, key, value, is_api=False, run_callbacks=True): oldval = self.data.get(key, None) if oldval == value: return False option = self.data_labels[key] if option.do_not_save: return False if is_api and option.restrict_api: return False try: setattr(self, key, value) except RuntimeError: return False if run_callbacks and option.onchange is not None: try: option.onchange() except Exception as e: errors.display(e, f"changing setting {key} to {value}") setattr(self, key, oldval) return False return True def get_default(self, key): data_label = self.data_labels.get(key) if data_label is None: return None return data_label.default def save(self, filename): assert not cmd_opts.freeze_settings, "saving settings is disabled" with open(filename, "w", encoding="utf8") as file: json.dump(self.data, file, indent=4, ensure_ascii=False) def same_type(self, x, y): if x is None or y is None: return True type_x = self.typemap.get(type(x), type(x)) type_y = self.typemap.get(type(y), type(y)) return type_x == type_y def load(self, filename): try: with open(filename, "r", encoding="utf8") as file: self.data = json.load(file) except FileNotFoundError: self.data = {} except Exception: errors.report(f'\nCould not load settings\nThe config file "{filename}" is likely corrupted\nIt has been moved to the "tmp/config.json"\nReverting config to default\n\n''', exc_info=True) os.replace(filename, os.path.join(script_path, "tmp", "config.json")) self.data = {} # 1.6.0 VAE defaults if self.data.get('sd_vae_as_default') is not None and self.data.get('sd_vae_overrides_per_model_preferences') is None: self.data['sd_vae_overrides_per_model_preferences'] = not self.data.get('sd_vae_as_default') # 1.1.1 quicksettings list migration if self.data.get('quicksettings') is not None and self.data.get('quicksettings_list') is None: self.data['quicksettings_list'] = [i.strip() for i in self.data.get('quicksettings').split(',')] # 1.4.0 ui_reorder if isinstance(self.data.get('ui_reorder'), str) and self.data.get('ui_reorder') and "ui_reorder_list" not in self.data: self.data['ui_reorder_list'] = [i.strip() for i in self.data.get('ui_reorder').split(',')] bad_settings = 0 for k, v in self.data.items(): info = self.data_labels.get(k, None) if info is not None and not self.same_type(info.default, v): print(f"Warning: bad setting value: {k}: {v} ({type(v).__name__}; expected {type(info.default).__name__})", file=sys.stderr) bad_settings += 1 if bad_settings > 0: print(f"The program is likely to not work with bad settings.\nSettings file: {filename}\nEither fix the file, or delete it and restart.", file=sys.stderr) def onchange(self, key, func, call=True): item = self.data_labels.get(key) item.onchange = func if call: func() def dumpjson(self): d = {k: self.data.get(k, v.default) for k, v in self.data_labels.items()} d["_comments_before"] = {k: v.comment_before for k, v in self.data_labels.items() if v.comment_before is not None} d["_comments_after"] = {k: v.comment_after for k, v in self.data_labels.items() if v.comment_after is not None} item_categories = {} for item in self.data_labels.values(): if item.section[0] is None: continue category = categories.mapping.get(item.category_id) category = "Uncategorized" if category is None else category.label if category not in item_categories: item_categories[category] = item.section[1] # _categories is a list of pairs: [section, category]. Each section (a setting page) will get a special heading above it with the category as text. d["_categories"] = [[v, k] for k, v in item_categories.items()] + [["Defaults", "Other"]] return json.dumps(d) def add_option(self, key, info): self.data_labels[key] = info if key not in self.data and not info.do_not_save: self.data[key] = info.default def reorder(self): category_ids = {} section_categories = {} settings_items = self.data_labels.items() for _, item in settings_items: if item.section not in section_categories: section_categories[item.section] = item.category_id for _, item in settings_items: item.category_id = section_categories.get(item.section) for category_id in categories.mapping: if category_id not in category_ids: category_ids[category_id] = len(category_ids) def sort_key(x): item: OptionInfo = x[1] category_order = category_ids.get(item.category_id, len(category_ids)) section_order = item.section[1] return category_order, section_order self.data_labels = dict(sorted(settings_items, key=sort_key)) def cast_value(self, key, value): if value is None: return None default_value = self.data_labels[key].default if default_value is None: default_value = getattr(self, key, None) if default_value is None: return None expected_type = type(default_value) if expected_type == bool and value == "False": value = False else: value = expected_type(value) return value @dataclass class OptionsCategory: id: str label: str class OptionsCategories: def __init__(self): self.mapping = {} def register_category(self, category_id, label): if category_id in self.mapping: return category_id self.mapping[category_id] = OptionsCategory(category_id, label) categories = OptionsCategories()
--- +++ @@ -1,321 +1,336 @@-import os -import json -import sys -from dataclasses import dataclass - -import gradio as gr - -from modules import errors -from modules.shared_cmd_options import cmd_opts -from modules.paths_internal import script_path - - -class OptionInfo: - def __init__(self, default=None, label="", component=None, component_args=None, onchange=None, section=None, refresh=None, comment_before='', comment_after='', infotext=None, restrict_api=False, category_id=None): - self.default = default - self.label = label - self.component = component - self.component_args = component_args - self.onchange = onchange - self.section = section - self.category_id = category_id - self.refresh = refresh - self.do_not_save = False - - self.comment_before = comment_before - """HTML text that will be added after label in UI""" - - self.comment_after = comment_after - """HTML text that will be added before label in UI""" - - self.infotext = infotext - - self.restrict_api = restrict_api - """If True, the setting will not be accessible via API""" - - def link(self, label, url): - self.comment_before += f"[<a href='{url}' target='_blank'>{label}</a>]" - return self - - def js(self, label, js_func): - self.comment_before += f"[<a onclick='{js_func}(); return false'>{label}</a>]" - return self - - def info(self, info): - self.comment_after += f"<span class='info'>({info})</span>" - return self - - def html(self, html): - self.comment_after += html - return self - - def needs_restart(self): - self.comment_after += " <span class='info'>(requires restart)</span>" - return self - - def needs_reload_ui(self): - self.comment_after += " <span class='info'>(requires Reload UI)</span>" - return self - - -class OptionHTML(OptionInfo): - def __init__(self, text): - super().__init__(str(text).strip(), label='', component=lambda **kwargs: gr.HTML(elem_classes="settings-info", **kwargs)) - - self.do_not_save = True - - -def options_section(section_identifier, options_dict): - for v in options_dict.values(): - if len(section_identifier) == 2: - v.section = section_identifier - elif len(section_identifier) == 3: - v.section = section_identifier[0:2] - v.category_id = section_identifier[2] - - return options_dict - - -options_builtin_fields = {"data_labels", "data", "restricted_opts", "typemap"} - - -class Options: - typemap = {int: float} - - def __init__(self, data_labels: dict[str, OptionInfo], restricted_opts): - self.data_labels = data_labels - self.data = {k: v.default for k, v in self.data_labels.items() if not v.do_not_save} - self.restricted_opts = restricted_opts - - def __setattr__(self, key, value): - if key in options_builtin_fields: - return super(Options, self).__setattr__(key, value) - - if self.data is not None: - if key in self.data or key in self.data_labels: - - # Check that settings aren't globally frozen - assert not cmd_opts.freeze_settings, "changing settings is disabled" - - # Get the info related to the setting being changed - info = self.data_labels.get(key, None) - if info.do_not_save: - return - - # Restrict component arguments - comp_args = info.component_args if info else None - if isinstance(comp_args, dict) and comp_args.get('visible', True) is False: - raise RuntimeError(f"not possible to set '{key}' because it is restricted") - - # Check that this section isn't frozen - if cmd_opts.freeze_settings_in_sections is not None: - frozen_sections = list(map(str.strip, cmd_opts.freeze_settings_in_sections.split(','))) # Trim whitespace from section names - section_key = info.section[0] - section_name = info.section[1] - assert section_key not in frozen_sections, f"not possible to set '{key}' because settings in section '{section_name}' ({section_key}) are frozen with --freeze-settings-in-sections" - - # Check that this section of the settings isn't frozen - if cmd_opts.freeze_specific_settings is not None: - frozen_keys = list(map(str.strip, cmd_opts.freeze_specific_settings.split(','))) # Trim whitespace from setting keys - assert key not in frozen_keys, f"not possible to set '{key}' because this setting is frozen with --freeze-specific-settings" - - # Check shorthand option which disables editing options in "saving-paths" - if cmd_opts.hide_ui_dir_config and key in self.restricted_opts: - raise RuntimeError(f"not possible to set '{key}' because it is restricted with --hide_ui_dir_config") - - self.data[key] = value - return - - return super(Options, self).__setattr__(key, value) - - def __getattr__(self, item): - if item in options_builtin_fields: - return super(Options, self).__getattribute__(item) - - if self.data is not None: - if item in self.data: - return self.data[item] - - if item in self.data_labels: - return self.data_labels[item].default - - return super(Options, self).__getattribute__(item) - - def set(self, key, value, is_api=False, run_callbacks=True): - - oldval = self.data.get(key, None) - if oldval == value: - return False - - option = self.data_labels[key] - if option.do_not_save: - return False - - if is_api and option.restrict_api: - return False - - try: - setattr(self, key, value) - except RuntimeError: - return False - - if run_callbacks and option.onchange is not None: - try: - option.onchange() - except Exception as e: - errors.display(e, f"changing setting {key} to {value}") - setattr(self, key, oldval) - return False - - return True - - def get_default(self, key): - - data_label = self.data_labels.get(key) - if data_label is None: - return None - - return data_label.default - - def save(self, filename): - assert not cmd_opts.freeze_settings, "saving settings is disabled" - - with open(filename, "w", encoding="utf8") as file: - json.dump(self.data, file, indent=4, ensure_ascii=False) - - def same_type(self, x, y): - if x is None or y is None: - return True - - type_x = self.typemap.get(type(x), type(x)) - type_y = self.typemap.get(type(y), type(y)) - - return type_x == type_y - - def load(self, filename): - try: - with open(filename, "r", encoding="utf8") as file: - self.data = json.load(file) - except FileNotFoundError: - self.data = {} - except Exception: - errors.report(f'\nCould not load settings\nThe config file "{filename}" is likely corrupted\nIt has been moved to the "tmp/config.json"\nReverting config to default\n\n''', exc_info=True) - os.replace(filename, os.path.join(script_path, "tmp", "config.json")) - self.data = {} - # 1.6.0 VAE defaults - if self.data.get('sd_vae_as_default') is not None and self.data.get('sd_vae_overrides_per_model_preferences') is None: - self.data['sd_vae_overrides_per_model_preferences'] = not self.data.get('sd_vae_as_default') - - # 1.1.1 quicksettings list migration - if self.data.get('quicksettings') is not None and self.data.get('quicksettings_list') is None: - self.data['quicksettings_list'] = [i.strip() for i in self.data.get('quicksettings').split(',')] - - # 1.4.0 ui_reorder - if isinstance(self.data.get('ui_reorder'), str) and self.data.get('ui_reorder') and "ui_reorder_list" not in self.data: - self.data['ui_reorder_list'] = [i.strip() for i in self.data.get('ui_reorder').split(',')] - - bad_settings = 0 - for k, v in self.data.items(): - info = self.data_labels.get(k, None) - if info is not None and not self.same_type(info.default, v): - print(f"Warning: bad setting value: {k}: {v} ({type(v).__name__}; expected {type(info.default).__name__})", file=sys.stderr) - bad_settings += 1 - - if bad_settings > 0: - print(f"The program is likely to not work with bad settings.\nSettings file: {filename}\nEither fix the file, or delete it and restart.", file=sys.stderr) - - def onchange(self, key, func, call=True): - item = self.data_labels.get(key) - item.onchange = func - - if call: - func() - - def dumpjson(self): - d = {k: self.data.get(k, v.default) for k, v in self.data_labels.items()} - d["_comments_before"] = {k: v.comment_before for k, v in self.data_labels.items() if v.comment_before is not None} - d["_comments_after"] = {k: v.comment_after for k, v in self.data_labels.items() if v.comment_after is not None} - - item_categories = {} - for item in self.data_labels.values(): - if item.section[0] is None: - continue - - category = categories.mapping.get(item.category_id) - category = "Uncategorized" if category is None else category.label - if category not in item_categories: - item_categories[category] = item.section[1] - - # _categories is a list of pairs: [section, category]. Each section (a setting page) will get a special heading above it with the category as text. - d["_categories"] = [[v, k] for k, v in item_categories.items()] + [["Defaults", "Other"]] - - return json.dumps(d) - - def add_option(self, key, info): - self.data_labels[key] = info - if key not in self.data and not info.do_not_save: - self.data[key] = info.default - - def reorder(self): - - category_ids = {} - section_categories = {} - - settings_items = self.data_labels.items() - for _, item in settings_items: - if item.section not in section_categories: - section_categories[item.section] = item.category_id - - for _, item in settings_items: - item.category_id = section_categories.get(item.section) - - for category_id in categories.mapping: - if category_id not in category_ids: - category_ids[category_id] = len(category_ids) - - def sort_key(x): - item: OptionInfo = x[1] - category_order = category_ids.get(item.category_id, len(category_ids)) - section_order = item.section[1] - - return category_order, section_order - - self.data_labels = dict(sorted(settings_items, key=sort_key)) - - def cast_value(self, key, value): - - if value is None: - return None - - default_value = self.data_labels[key].default - if default_value is None: - default_value = getattr(self, key, None) - if default_value is None: - return None - - expected_type = type(default_value) - if expected_type == bool and value == "False": - value = False - else: - value = expected_type(value) - - return value - - -@dataclass -class OptionsCategory: - id: str - label: str - -class OptionsCategories: - def __init__(self): - self.mapping = {} - - def register_category(self, category_id, label): - if category_id in self.mapping: - return category_id - - self.mapping[category_id] = OptionsCategory(category_id, label) - - -categories = OptionsCategories()+import os +import json +import sys +from dataclasses import dataclass + +import gradio as gr + +from modules import errors +from modules.shared_cmd_options import cmd_opts +from modules.paths_internal import script_path + + +class OptionInfo: + def __init__(self, default=None, label="", component=None, component_args=None, onchange=None, section=None, refresh=None, comment_before='', comment_after='', infotext=None, restrict_api=False, category_id=None): + self.default = default + self.label = label + self.component = component + self.component_args = component_args + self.onchange = onchange + self.section = section + self.category_id = category_id + self.refresh = refresh + self.do_not_save = False + + self.comment_before = comment_before + """HTML text that will be added after label in UI""" + + self.comment_after = comment_after + """HTML text that will be added before label in UI""" + + self.infotext = infotext + + self.restrict_api = restrict_api + """If True, the setting will not be accessible via API""" + + def link(self, label, url): + self.comment_before += f"[<a href='{url}' target='_blank'>{label}</a>]" + return self + + def js(self, label, js_func): + self.comment_before += f"[<a onclick='{js_func}(); return false'>{label}</a>]" + return self + + def info(self, info): + self.comment_after += f"<span class='info'>({info})</span>" + return self + + def html(self, html): + self.comment_after += html + return self + + def needs_restart(self): + self.comment_after += " <span class='info'>(requires restart)</span>" + return self + + def needs_reload_ui(self): + self.comment_after += " <span class='info'>(requires Reload UI)</span>" + return self + + +class OptionHTML(OptionInfo): + def __init__(self, text): + super().__init__(str(text).strip(), label='', component=lambda **kwargs: gr.HTML(elem_classes="settings-info", **kwargs)) + + self.do_not_save = True + + +def options_section(section_identifier, options_dict): + for v in options_dict.values(): + if len(section_identifier) == 2: + v.section = section_identifier + elif len(section_identifier) == 3: + v.section = section_identifier[0:2] + v.category_id = section_identifier[2] + + return options_dict + + +options_builtin_fields = {"data_labels", "data", "restricted_opts", "typemap"} + + +class Options: + typemap = {int: float} + + def __init__(self, data_labels: dict[str, OptionInfo], restricted_opts): + self.data_labels = data_labels + self.data = {k: v.default for k, v in self.data_labels.items() if not v.do_not_save} + self.restricted_opts = restricted_opts + + def __setattr__(self, key, value): + if key in options_builtin_fields: + return super(Options, self).__setattr__(key, value) + + if self.data is not None: + if key in self.data or key in self.data_labels: + + # Check that settings aren't globally frozen + assert not cmd_opts.freeze_settings, "changing settings is disabled" + + # Get the info related to the setting being changed + info = self.data_labels.get(key, None) + if info.do_not_save: + return + + # Restrict component arguments + comp_args = info.component_args if info else None + if isinstance(comp_args, dict) and comp_args.get('visible', True) is False: + raise RuntimeError(f"not possible to set '{key}' because it is restricted") + + # Check that this section isn't frozen + if cmd_opts.freeze_settings_in_sections is not None: + frozen_sections = list(map(str.strip, cmd_opts.freeze_settings_in_sections.split(','))) # Trim whitespace from section names + section_key = info.section[0] + section_name = info.section[1] + assert section_key not in frozen_sections, f"not possible to set '{key}' because settings in section '{section_name}' ({section_key}) are frozen with --freeze-settings-in-sections" + + # Check that this section of the settings isn't frozen + if cmd_opts.freeze_specific_settings is not None: + frozen_keys = list(map(str.strip, cmd_opts.freeze_specific_settings.split(','))) # Trim whitespace from setting keys + assert key not in frozen_keys, f"not possible to set '{key}' because this setting is frozen with --freeze-specific-settings" + + # Check shorthand option which disables editing options in "saving-paths" + if cmd_opts.hide_ui_dir_config and key in self.restricted_opts: + raise RuntimeError(f"not possible to set '{key}' because it is restricted with --hide_ui_dir_config") + + self.data[key] = value + return + + return super(Options, self).__setattr__(key, value) + + def __getattr__(self, item): + if item in options_builtin_fields: + return super(Options, self).__getattribute__(item) + + if self.data is not None: + if item in self.data: + return self.data[item] + + if item in self.data_labels: + return self.data_labels[item].default + + return super(Options, self).__getattribute__(item) + + def set(self, key, value, is_api=False, run_callbacks=True): + """sets an option and calls its onchange callback, returning True if the option changed and False otherwise""" + + oldval = self.data.get(key, None) + if oldval == value: + return False + + option = self.data_labels[key] + if option.do_not_save: + return False + + if is_api and option.restrict_api: + return False + + try: + setattr(self, key, value) + except RuntimeError: + return False + + if run_callbacks and option.onchange is not None: + try: + option.onchange() + except Exception as e: + errors.display(e, f"changing setting {key} to {value}") + setattr(self, key, oldval) + return False + + return True + + def get_default(self, key): + """returns the default value for the key""" + + data_label = self.data_labels.get(key) + if data_label is None: + return None + + return data_label.default + + def save(self, filename): + assert not cmd_opts.freeze_settings, "saving settings is disabled" + + with open(filename, "w", encoding="utf8") as file: + json.dump(self.data, file, indent=4, ensure_ascii=False) + + def same_type(self, x, y): + if x is None or y is None: + return True + + type_x = self.typemap.get(type(x), type(x)) + type_y = self.typemap.get(type(y), type(y)) + + return type_x == type_y + + def load(self, filename): + try: + with open(filename, "r", encoding="utf8") as file: + self.data = json.load(file) + except FileNotFoundError: + self.data = {} + except Exception: + errors.report(f'\nCould not load settings\nThe config file "{filename}" is likely corrupted\nIt has been moved to the "tmp/config.json"\nReverting config to default\n\n''', exc_info=True) + os.replace(filename, os.path.join(script_path, "tmp", "config.json")) + self.data = {} + # 1.6.0 VAE defaults + if self.data.get('sd_vae_as_default') is not None and self.data.get('sd_vae_overrides_per_model_preferences') is None: + self.data['sd_vae_overrides_per_model_preferences'] = not self.data.get('sd_vae_as_default') + + # 1.1.1 quicksettings list migration + if self.data.get('quicksettings') is not None and self.data.get('quicksettings_list') is None: + self.data['quicksettings_list'] = [i.strip() for i in self.data.get('quicksettings').split(',')] + + # 1.4.0 ui_reorder + if isinstance(self.data.get('ui_reorder'), str) and self.data.get('ui_reorder') and "ui_reorder_list" not in self.data: + self.data['ui_reorder_list'] = [i.strip() for i in self.data.get('ui_reorder').split(',')] + + bad_settings = 0 + for k, v in self.data.items(): + info = self.data_labels.get(k, None) + if info is not None and not self.same_type(info.default, v): + print(f"Warning: bad setting value: {k}: {v} ({type(v).__name__}; expected {type(info.default).__name__})", file=sys.stderr) + bad_settings += 1 + + if bad_settings > 0: + print(f"The program is likely to not work with bad settings.\nSettings file: {filename}\nEither fix the file, or delete it and restart.", file=sys.stderr) + + def onchange(self, key, func, call=True): + item = self.data_labels.get(key) + item.onchange = func + + if call: + func() + + def dumpjson(self): + d = {k: self.data.get(k, v.default) for k, v in self.data_labels.items()} + d["_comments_before"] = {k: v.comment_before for k, v in self.data_labels.items() if v.comment_before is not None} + d["_comments_after"] = {k: v.comment_after for k, v in self.data_labels.items() if v.comment_after is not None} + + item_categories = {} + for item in self.data_labels.values(): + if item.section[0] is None: + continue + + category = categories.mapping.get(item.category_id) + category = "Uncategorized" if category is None else category.label + if category not in item_categories: + item_categories[category] = item.section[1] + + # _categories is a list of pairs: [section, category]. Each section (a setting page) will get a special heading above it with the category as text. + d["_categories"] = [[v, k] for k, v in item_categories.items()] + [["Defaults", "Other"]] + + return json.dumps(d) + + def add_option(self, key, info): + self.data_labels[key] = info + if key not in self.data and not info.do_not_save: + self.data[key] = info.default + + def reorder(self): + """Reorder settings so that: + - all items related to section always go together + - all sections belonging to a category go together + - sections inside a category are ordered alphabetically + - categories are ordered by creation order + + Category is a superset of sections: for category "postprocessing" there could be multiple sections: "face restoration", "upscaling". + + This function also changes items' category_id so that all items belonging to a section have the same category_id. + """ + + category_ids = {} + section_categories = {} + + settings_items = self.data_labels.items() + for _, item in settings_items: + if item.section not in section_categories: + section_categories[item.section] = item.category_id + + for _, item in settings_items: + item.category_id = section_categories.get(item.section) + + for category_id in categories.mapping: + if category_id not in category_ids: + category_ids[category_id] = len(category_ids) + + def sort_key(x): + item: OptionInfo = x[1] + category_order = category_ids.get(item.category_id, len(category_ids)) + section_order = item.section[1] + + return category_order, section_order + + self.data_labels = dict(sorted(settings_items, key=sort_key)) + + def cast_value(self, key, value): + """casts an arbitrary to the same type as this setting's value with key + Example: cast_value("eta_noise_seed_delta", "12") -> returns 12 (an int rather than str) + """ + + if value is None: + return None + + default_value = self.data_labels[key].default + if default_value is None: + default_value = getattr(self, key, None) + if default_value is None: + return None + + expected_type = type(default_value) + if expected_type == bool and value == "False": + value = False + else: + value = expected_type(value) + + return value + + +@dataclass +class OptionsCategory: + id: str + label: str + +class OptionsCategories: + def __init__(self): + self.mapping = {} + + def register_category(self, category_id, label): + if category_id in self.mapping: + return category_id + + self.mapping[category_id] = OptionsCategory(category_id, label) + + +categories = OptionsCategories()
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/options.py
Generate docstrings for each module
import torch from torch.nn.functional import silu from types import MethodType from modules import devices, sd_hijack_optimizations, shared, script_callbacks, errors, sd_unet, patches from modules.hypernetworks import hypernetwork from modules.shared import cmd_opts from modules import sd_hijack_clip, sd_hijack_open_clip, sd_hijack_unet, sd_hijack_xlmr, xlmr, xlmr_m18 import ldm.modules.attention import ldm.modules.diffusionmodules.model import ldm.modules.diffusionmodules.openaimodel import ldm.models.diffusion.ddpm import ldm.models.diffusion.ddim import ldm.models.diffusion.plms import ldm.modules.encoders.modules import sgm.modules.attention import sgm.modules.diffusionmodules.model import sgm.modules.diffusionmodules.openaimodel import sgm.modules.encoders.modules attention_CrossAttention_forward = ldm.modules.attention.CrossAttention.forward diffusionmodules_model_nonlinearity = ldm.modules.diffusionmodules.model.nonlinearity diffusionmodules_model_AttnBlock_forward = ldm.modules.diffusionmodules.model.AttnBlock.forward # new memory efficient cross attention blocks do not support hypernets and we already # have memory efficient cross attention anyway, so this disables SD2.0's memory efficient cross attention ldm.modules.attention.MemoryEfficientCrossAttention = ldm.modules.attention.CrossAttention ldm.modules.attention.BasicTransformerBlock.ATTENTION_MODES["softmax-xformers"] = ldm.modules.attention.CrossAttention # silence new console spam from SD2 ldm.modules.attention.print = shared.ldm_print ldm.modules.diffusionmodules.model.print = shared.ldm_print ldm.util.print = shared.ldm_print ldm.models.diffusion.ddpm.print = shared.ldm_print optimizers = [] current_optimizer: sd_hijack_optimizations.SdOptimization = None ldm_patched_forward = sd_unet.create_unet_forward(ldm.modules.diffusionmodules.openaimodel.UNetModel.forward) ldm_original_forward = patches.patch(__file__, ldm.modules.diffusionmodules.openaimodel.UNetModel, "forward", ldm_patched_forward) sgm_patched_forward = sd_unet.create_unet_forward(sgm.modules.diffusionmodules.openaimodel.UNetModel.forward) sgm_original_forward = patches.patch(__file__, sgm.modules.diffusionmodules.openaimodel.UNetModel, "forward", sgm_patched_forward) def list_optimizers(): new_optimizers = script_callbacks.list_optimizers_callback() new_optimizers = [x for x in new_optimizers if x.is_available()] new_optimizers = sorted(new_optimizers, key=lambda x: x.priority, reverse=True) optimizers.clear() optimizers.extend(new_optimizers) def apply_optimizations(option=None): global current_optimizer undo_optimizations() if len(optimizers) == 0: # a script can access the model very early, and optimizations would not be filled by then current_optimizer = None return '' ldm.modules.diffusionmodules.model.nonlinearity = silu ldm.modules.diffusionmodules.openaimodel.th = sd_hijack_unet.th sgm.modules.diffusionmodules.model.nonlinearity = silu sgm.modules.diffusionmodules.openaimodel.th = sd_hijack_unet.th if current_optimizer is not None: current_optimizer.undo() current_optimizer = None selection = option or shared.opts.cross_attention_optimization if selection == "Automatic" and len(optimizers) > 0: matching_optimizer = next(iter([x for x in optimizers if x.cmd_opt and getattr(shared.cmd_opts, x.cmd_opt, False)]), optimizers[0]) else: matching_optimizer = next(iter([x for x in optimizers if x.title() == selection]), None) if selection == "None": matching_optimizer = None elif selection == "Automatic" and shared.cmd_opts.disable_opt_split_attention: matching_optimizer = None elif matching_optimizer is None: matching_optimizer = optimizers[0] if matching_optimizer is not None: print(f"Applying attention optimization: {matching_optimizer.name}... ", end='') matching_optimizer.apply() print("done.") current_optimizer = matching_optimizer return current_optimizer.name else: print("Disabling attention optimization") return '' def undo_optimizations(): ldm.modules.diffusionmodules.model.nonlinearity = diffusionmodules_model_nonlinearity ldm.modules.attention.CrossAttention.forward = hypernetwork.attention_CrossAttention_forward ldm.modules.diffusionmodules.model.AttnBlock.forward = diffusionmodules_model_AttnBlock_forward sgm.modules.diffusionmodules.model.nonlinearity = diffusionmodules_model_nonlinearity sgm.modules.attention.CrossAttention.forward = hypernetwork.attention_CrossAttention_forward sgm.modules.diffusionmodules.model.AttnBlock.forward = diffusionmodules_model_AttnBlock_forward def fix_checkpoint(): pass def weighted_loss(sd_model, pred, target, mean=True): #Calculate the weight normally, but ignore the mean loss = sd_model._old_get_loss(pred, target, mean=False) #Check if we have weights available weight = getattr(sd_model, '_custom_loss_weight', None) if weight is not None: loss *= weight #Return the loss, as mean if specified return loss.mean() if mean else loss def weighted_forward(sd_model, x, c, w, *args, **kwargs): try: #Temporarily append weights to a place accessible during loss calc sd_model._custom_loss_weight = w #Replace 'get_loss' with a weight-aware one. Otherwise we need to reimplement 'forward' completely #Keep 'get_loss', but don't overwrite the previous old_get_loss if it's already set if not hasattr(sd_model, '_old_get_loss'): sd_model._old_get_loss = sd_model.get_loss sd_model.get_loss = MethodType(weighted_loss, sd_model) #Run the standard forward function, but with the patched 'get_loss' return sd_model.forward(x, c, *args, **kwargs) finally: try: #Delete temporary weights if appended del sd_model._custom_loss_weight except AttributeError: pass #If we have an old loss function, reset the loss function to the original one if hasattr(sd_model, '_old_get_loss'): sd_model.get_loss = sd_model._old_get_loss del sd_model._old_get_loss def apply_weighted_forward(sd_model): #Add new function 'weighted_forward' that can be called to calc weighted loss sd_model.weighted_forward = MethodType(weighted_forward, sd_model) def undo_weighted_forward(sd_model): try: del sd_model.weighted_forward except AttributeError: pass class StableDiffusionModelHijack: fixes = None layers = None circular_enabled = False clip = None optimization_method = None def __init__(self): import modules.textual_inversion.textual_inversion self.extra_generation_params = {} self.comments = [] self.embedding_db = modules.textual_inversion.textual_inversion.EmbeddingDatabase() self.embedding_db.add_embedding_dir(cmd_opts.embeddings_dir) def apply_optimizations(self, option=None): try: self.optimization_method = apply_optimizations(option) except Exception as e: errors.display(e, "applying cross attention optimization") undo_optimizations() def convert_sdxl_to_ssd(self, m): delattr(m.model.diffusion_model.middle_block, '1') delattr(m.model.diffusion_model.middle_block, '2') for i in ['9', '8', '7', '6', '5', '4']: delattr(m.model.diffusion_model.input_blocks[7][1].transformer_blocks, i) delattr(m.model.diffusion_model.input_blocks[8][1].transformer_blocks, i) delattr(m.model.diffusion_model.output_blocks[0][1].transformer_blocks, i) delattr(m.model.diffusion_model.output_blocks[1][1].transformer_blocks, i) delattr(m.model.diffusion_model.output_blocks[4][1].transformer_blocks, '1') delattr(m.model.diffusion_model.output_blocks[5][1].transformer_blocks, '1') devices.torch_gc() def hijack(self, m): conditioner = getattr(m, 'conditioner', None) if conditioner: text_cond_models = [] for i in range(len(conditioner.embedders)): embedder = conditioner.embedders[i] typename = type(embedder).__name__ if typename == 'FrozenOpenCLIPEmbedder': embedder.model.token_embedding = EmbeddingsWithFixes(embedder.model.token_embedding, self) conditioner.embedders[i] = sd_hijack_open_clip.FrozenOpenCLIPEmbedderWithCustomWords(embedder, self) text_cond_models.append(conditioner.embedders[i]) if typename == 'FrozenCLIPEmbedder': model_embeddings = embedder.transformer.text_model.embeddings model_embeddings.token_embedding = EmbeddingsWithFixes(model_embeddings.token_embedding, self) conditioner.embedders[i] = sd_hijack_clip.FrozenCLIPEmbedderForSDXLWithCustomWords(embedder, self) text_cond_models.append(conditioner.embedders[i]) if typename == 'FrozenOpenCLIPEmbedder2': embedder.model.token_embedding = EmbeddingsWithFixes(embedder.model.token_embedding, self, textual_inversion_key='clip_g') conditioner.embedders[i] = sd_hijack_open_clip.FrozenOpenCLIPEmbedder2WithCustomWords(embedder, self) text_cond_models.append(conditioner.embedders[i]) if len(text_cond_models) == 1: m.cond_stage_model = text_cond_models[0] else: m.cond_stage_model = conditioner if type(m.cond_stage_model) == xlmr.BertSeriesModelWithTransformation or type(m.cond_stage_model) == xlmr_m18.BertSeriesModelWithTransformation: model_embeddings = m.cond_stage_model.roberta.embeddings model_embeddings.token_embedding = EmbeddingsWithFixes(model_embeddings.word_embeddings, self) m.cond_stage_model = sd_hijack_xlmr.FrozenXLMREmbedderWithCustomWords(m.cond_stage_model, self) elif type(m.cond_stage_model) == ldm.modules.encoders.modules.FrozenCLIPEmbedder: model_embeddings = m.cond_stage_model.transformer.text_model.embeddings model_embeddings.token_embedding = EmbeddingsWithFixes(model_embeddings.token_embedding, self) m.cond_stage_model = sd_hijack_clip.FrozenCLIPEmbedderWithCustomWords(m.cond_stage_model, self) elif type(m.cond_stage_model) == ldm.modules.encoders.modules.FrozenOpenCLIPEmbedder: m.cond_stage_model.model.token_embedding = EmbeddingsWithFixes(m.cond_stage_model.model.token_embedding, self) m.cond_stage_model = sd_hijack_open_clip.FrozenOpenCLIPEmbedderWithCustomWords(m.cond_stage_model, self) apply_weighted_forward(m) if m.cond_stage_key == "edit": sd_hijack_unet.hijack_ddpm_edit() self.apply_optimizations() self.clip = m.cond_stage_model def flatten(el): flattened = [flatten(children) for children in el.children()] res = [el] for c in flattened: res += c return res self.layers = flatten(m) import modules.models.diffusion.ddpm_edit if isinstance(m, ldm.models.diffusion.ddpm.LatentDiffusion): sd_unet.original_forward = ldm_original_forward elif isinstance(m, modules.models.diffusion.ddpm_edit.LatentDiffusion): sd_unet.original_forward = ldm_original_forward elif isinstance(m, sgm.models.diffusion.DiffusionEngine): sd_unet.original_forward = sgm_original_forward else: sd_unet.original_forward = None def undo_hijack(self, m): conditioner = getattr(m, 'conditioner', None) if conditioner: for i in range(len(conditioner.embedders)): embedder = conditioner.embedders[i] if isinstance(embedder, (sd_hijack_open_clip.FrozenOpenCLIPEmbedderWithCustomWords, sd_hijack_open_clip.FrozenOpenCLIPEmbedder2WithCustomWords)): embedder.wrapped.model.token_embedding = embedder.wrapped.model.token_embedding.wrapped conditioner.embedders[i] = embedder.wrapped if isinstance(embedder, sd_hijack_clip.FrozenCLIPEmbedderForSDXLWithCustomWords): embedder.wrapped.transformer.text_model.embeddings.token_embedding = embedder.wrapped.transformer.text_model.embeddings.token_embedding.wrapped conditioner.embedders[i] = embedder.wrapped if hasattr(m, 'cond_stage_model'): delattr(m, 'cond_stage_model') elif type(m.cond_stage_model) == sd_hijack_xlmr.FrozenXLMREmbedderWithCustomWords: m.cond_stage_model = m.cond_stage_model.wrapped elif type(m.cond_stage_model) == sd_hijack_clip.FrozenCLIPEmbedderWithCustomWords: m.cond_stage_model = m.cond_stage_model.wrapped model_embeddings = m.cond_stage_model.transformer.text_model.embeddings if type(model_embeddings.token_embedding) == EmbeddingsWithFixes: model_embeddings.token_embedding = model_embeddings.token_embedding.wrapped elif type(m.cond_stage_model) == sd_hijack_open_clip.FrozenOpenCLIPEmbedderWithCustomWords: m.cond_stage_model.wrapped.model.token_embedding = m.cond_stage_model.wrapped.model.token_embedding.wrapped m.cond_stage_model = m.cond_stage_model.wrapped undo_optimizations() undo_weighted_forward(m) self.apply_circular(False) self.layers = None self.clip = None def apply_circular(self, enable): if self.circular_enabled == enable: return self.circular_enabled = enable for layer in [layer for layer in self.layers if type(layer) == torch.nn.Conv2d]: layer.padding_mode = 'circular' if enable else 'zeros' def clear_comments(self): self.comments = [] self.extra_generation_params = {} def get_prompt_lengths(self, text): if self.clip is None: return "-", "-" if hasattr(self.clip, 'get_token_count'): token_count = self.clip.get_token_count(text) else: _, token_count = self.clip.process_texts([text]) return token_count, self.clip.get_target_prompt_token_count(token_count) def redo_hijack(self, m): self.undo_hijack(m) self.hijack(m) class EmbeddingsWithFixes(torch.nn.Module): def __init__(self, wrapped, embeddings, textual_inversion_key='clip_l'): super().__init__() self.wrapped = wrapped self.embeddings = embeddings self.textual_inversion_key = textual_inversion_key def forward(self, input_ids): batch_fixes = self.embeddings.fixes self.embeddings.fixes = None inputs_embeds = self.wrapped(input_ids) if batch_fixes is None or len(batch_fixes) == 0 or max([len(x) for x in batch_fixes]) == 0: return inputs_embeds vecs = [] for fixes, tensor in zip(batch_fixes, inputs_embeds): for offset, embedding in fixes: vec = embedding.vec[self.textual_inversion_key] if isinstance(embedding.vec, dict) else embedding.vec emb = devices.cond_cast_unet(vec) emb_len = min(tensor.shape[0] - offset - 1, emb.shape[0]) tensor = torch.cat([tensor[0:offset + 1], emb[0:emb_len], tensor[offset + 1 + emb_len:]]).to(dtype=inputs_embeds.dtype) vecs.append(tensor) return torch.stack(vecs) class TextualInversionEmbeddings(torch.nn.Embedding): def __init__(self, num_embeddings: int, embedding_dim: int, textual_inversion_key='clip_l', **kwargs): super().__init__(num_embeddings, embedding_dim, **kwargs) self.embeddings = model_hijack self.textual_inversion_key = textual_inversion_key @property def wrapped(self): return super().forward def forward(self, input_ids): return EmbeddingsWithFixes.forward(self, input_ids) def add_circular_option_to_conv_2d(): conv2d_constructor = torch.nn.Conv2d.__init__ def conv2d_constructor_circular(self, *args, **kwargs): return conv2d_constructor(self, *args, padding_mode='circular', **kwargs) torch.nn.Conv2d.__init__ = conv2d_constructor_circular model_hijack = StableDiffusionModelHijack() def register_buffer(self, name, attr): if type(attr) == torch.Tensor: if attr.device != devices.device: attr = attr.to(device=devices.device, dtype=(torch.float32 if devices.device.type == 'mps' else None)) setattr(self, name, attr) ldm.models.diffusion.ddim.DDIMSampler.register_buffer = register_buffer ldm.models.diffusion.plms.PLMSSampler.register_buffer = register_buffer
--- +++ @@ -1,403 +1,409 @@-import torch -from torch.nn.functional import silu -from types import MethodType - -from modules import devices, sd_hijack_optimizations, shared, script_callbacks, errors, sd_unet, patches -from modules.hypernetworks import hypernetwork -from modules.shared import cmd_opts -from modules import sd_hijack_clip, sd_hijack_open_clip, sd_hijack_unet, sd_hijack_xlmr, xlmr, xlmr_m18 - -import ldm.modules.attention -import ldm.modules.diffusionmodules.model -import ldm.modules.diffusionmodules.openaimodel -import ldm.models.diffusion.ddpm -import ldm.models.diffusion.ddim -import ldm.models.diffusion.plms -import ldm.modules.encoders.modules - -import sgm.modules.attention -import sgm.modules.diffusionmodules.model -import sgm.modules.diffusionmodules.openaimodel -import sgm.modules.encoders.modules - -attention_CrossAttention_forward = ldm.modules.attention.CrossAttention.forward -diffusionmodules_model_nonlinearity = ldm.modules.diffusionmodules.model.nonlinearity -diffusionmodules_model_AttnBlock_forward = ldm.modules.diffusionmodules.model.AttnBlock.forward - -# new memory efficient cross attention blocks do not support hypernets and we already -# have memory efficient cross attention anyway, so this disables SD2.0's memory efficient cross attention -ldm.modules.attention.MemoryEfficientCrossAttention = ldm.modules.attention.CrossAttention -ldm.modules.attention.BasicTransformerBlock.ATTENTION_MODES["softmax-xformers"] = ldm.modules.attention.CrossAttention - -# silence new console spam from SD2 -ldm.modules.attention.print = shared.ldm_print -ldm.modules.diffusionmodules.model.print = shared.ldm_print -ldm.util.print = shared.ldm_print -ldm.models.diffusion.ddpm.print = shared.ldm_print - -optimizers = [] -current_optimizer: sd_hijack_optimizations.SdOptimization = None - -ldm_patched_forward = sd_unet.create_unet_forward(ldm.modules.diffusionmodules.openaimodel.UNetModel.forward) -ldm_original_forward = patches.patch(__file__, ldm.modules.diffusionmodules.openaimodel.UNetModel, "forward", ldm_patched_forward) - -sgm_patched_forward = sd_unet.create_unet_forward(sgm.modules.diffusionmodules.openaimodel.UNetModel.forward) -sgm_original_forward = patches.patch(__file__, sgm.modules.diffusionmodules.openaimodel.UNetModel, "forward", sgm_patched_forward) - - -def list_optimizers(): - new_optimizers = script_callbacks.list_optimizers_callback() - - new_optimizers = [x for x in new_optimizers if x.is_available()] - - new_optimizers = sorted(new_optimizers, key=lambda x: x.priority, reverse=True) - - optimizers.clear() - optimizers.extend(new_optimizers) - - -def apply_optimizations(option=None): - global current_optimizer - - undo_optimizations() - - if len(optimizers) == 0: - # a script can access the model very early, and optimizations would not be filled by then - current_optimizer = None - return '' - - ldm.modules.diffusionmodules.model.nonlinearity = silu - ldm.modules.diffusionmodules.openaimodel.th = sd_hijack_unet.th - - sgm.modules.diffusionmodules.model.nonlinearity = silu - sgm.modules.diffusionmodules.openaimodel.th = sd_hijack_unet.th - - if current_optimizer is not None: - current_optimizer.undo() - current_optimizer = None - - selection = option or shared.opts.cross_attention_optimization - if selection == "Automatic" and len(optimizers) > 0: - matching_optimizer = next(iter([x for x in optimizers if x.cmd_opt and getattr(shared.cmd_opts, x.cmd_opt, False)]), optimizers[0]) - else: - matching_optimizer = next(iter([x for x in optimizers if x.title() == selection]), None) - - if selection == "None": - matching_optimizer = None - elif selection == "Automatic" and shared.cmd_opts.disable_opt_split_attention: - matching_optimizer = None - elif matching_optimizer is None: - matching_optimizer = optimizers[0] - - if matching_optimizer is not None: - print(f"Applying attention optimization: {matching_optimizer.name}... ", end='') - matching_optimizer.apply() - print("done.") - current_optimizer = matching_optimizer - return current_optimizer.name - else: - print("Disabling attention optimization") - return '' - - -def undo_optimizations(): - ldm.modules.diffusionmodules.model.nonlinearity = diffusionmodules_model_nonlinearity - ldm.modules.attention.CrossAttention.forward = hypernetwork.attention_CrossAttention_forward - ldm.modules.diffusionmodules.model.AttnBlock.forward = diffusionmodules_model_AttnBlock_forward - - sgm.modules.diffusionmodules.model.nonlinearity = diffusionmodules_model_nonlinearity - sgm.modules.attention.CrossAttention.forward = hypernetwork.attention_CrossAttention_forward - sgm.modules.diffusionmodules.model.AttnBlock.forward = diffusionmodules_model_AttnBlock_forward - - -def fix_checkpoint(): - - pass - - -def weighted_loss(sd_model, pred, target, mean=True): - #Calculate the weight normally, but ignore the mean - loss = sd_model._old_get_loss(pred, target, mean=False) - - #Check if we have weights available - weight = getattr(sd_model, '_custom_loss_weight', None) - if weight is not None: - loss *= weight - - #Return the loss, as mean if specified - return loss.mean() if mean else loss - -def weighted_forward(sd_model, x, c, w, *args, **kwargs): - try: - #Temporarily append weights to a place accessible during loss calc - sd_model._custom_loss_weight = w - - #Replace 'get_loss' with a weight-aware one. Otherwise we need to reimplement 'forward' completely - #Keep 'get_loss', but don't overwrite the previous old_get_loss if it's already set - if not hasattr(sd_model, '_old_get_loss'): - sd_model._old_get_loss = sd_model.get_loss - sd_model.get_loss = MethodType(weighted_loss, sd_model) - - #Run the standard forward function, but with the patched 'get_loss' - return sd_model.forward(x, c, *args, **kwargs) - finally: - try: - #Delete temporary weights if appended - del sd_model._custom_loss_weight - except AttributeError: - pass - - #If we have an old loss function, reset the loss function to the original one - if hasattr(sd_model, '_old_get_loss'): - sd_model.get_loss = sd_model._old_get_loss - del sd_model._old_get_loss - -def apply_weighted_forward(sd_model): - #Add new function 'weighted_forward' that can be called to calc weighted loss - sd_model.weighted_forward = MethodType(weighted_forward, sd_model) - -def undo_weighted_forward(sd_model): - try: - del sd_model.weighted_forward - except AttributeError: - pass - - -class StableDiffusionModelHijack: - fixes = None - layers = None - circular_enabled = False - clip = None - optimization_method = None - - def __init__(self): - import modules.textual_inversion.textual_inversion - - self.extra_generation_params = {} - self.comments = [] - - self.embedding_db = modules.textual_inversion.textual_inversion.EmbeddingDatabase() - self.embedding_db.add_embedding_dir(cmd_opts.embeddings_dir) - - def apply_optimizations(self, option=None): - try: - self.optimization_method = apply_optimizations(option) - except Exception as e: - errors.display(e, "applying cross attention optimization") - undo_optimizations() - - def convert_sdxl_to_ssd(self, m): - - delattr(m.model.diffusion_model.middle_block, '1') - delattr(m.model.diffusion_model.middle_block, '2') - for i in ['9', '8', '7', '6', '5', '4']: - delattr(m.model.diffusion_model.input_blocks[7][1].transformer_blocks, i) - delattr(m.model.diffusion_model.input_blocks[8][1].transformer_blocks, i) - delattr(m.model.diffusion_model.output_blocks[0][1].transformer_blocks, i) - delattr(m.model.diffusion_model.output_blocks[1][1].transformer_blocks, i) - delattr(m.model.diffusion_model.output_blocks[4][1].transformer_blocks, '1') - delattr(m.model.diffusion_model.output_blocks[5][1].transformer_blocks, '1') - devices.torch_gc() - - def hijack(self, m): - conditioner = getattr(m, 'conditioner', None) - if conditioner: - text_cond_models = [] - - for i in range(len(conditioner.embedders)): - embedder = conditioner.embedders[i] - typename = type(embedder).__name__ - if typename == 'FrozenOpenCLIPEmbedder': - embedder.model.token_embedding = EmbeddingsWithFixes(embedder.model.token_embedding, self) - conditioner.embedders[i] = sd_hijack_open_clip.FrozenOpenCLIPEmbedderWithCustomWords(embedder, self) - text_cond_models.append(conditioner.embedders[i]) - if typename == 'FrozenCLIPEmbedder': - model_embeddings = embedder.transformer.text_model.embeddings - model_embeddings.token_embedding = EmbeddingsWithFixes(model_embeddings.token_embedding, self) - conditioner.embedders[i] = sd_hijack_clip.FrozenCLIPEmbedderForSDXLWithCustomWords(embedder, self) - text_cond_models.append(conditioner.embedders[i]) - if typename == 'FrozenOpenCLIPEmbedder2': - embedder.model.token_embedding = EmbeddingsWithFixes(embedder.model.token_embedding, self, textual_inversion_key='clip_g') - conditioner.embedders[i] = sd_hijack_open_clip.FrozenOpenCLIPEmbedder2WithCustomWords(embedder, self) - text_cond_models.append(conditioner.embedders[i]) - - if len(text_cond_models) == 1: - m.cond_stage_model = text_cond_models[0] - else: - m.cond_stage_model = conditioner - - if type(m.cond_stage_model) == xlmr.BertSeriesModelWithTransformation or type(m.cond_stage_model) == xlmr_m18.BertSeriesModelWithTransformation: - model_embeddings = m.cond_stage_model.roberta.embeddings - model_embeddings.token_embedding = EmbeddingsWithFixes(model_embeddings.word_embeddings, self) - m.cond_stage_model = sd_hijack_xlmr.FrozenXLMREmbedderWithCustomWords(m.cond_stage_model, self) - - elif type(m.cond_stage_model) == ldm.modules.encoders.modules.FrozenCLIPEmbedder: - model_embeddings = m.cond_stage_model.transformer.text_model.embeddings - model_embeddings.token_embedding = EmbeddingsWithFixes(model_embeddings.token_embedding, self) - m.cond_stage_model = sd_hijack_clip.FrozenCLIPEmbedderWithCustomWords(m.cond_stage_model, self) - - elif type(m.cond_stage_model) == ldm.modules.encoders.modules.FrozenOpenCLIPEmbedder: - m.cond_stage_model.model.token_embedding = EmbeddingsWithFixes(m.cond_stage_model.model.token_embedding, self) - m.cond_stage_model = sd_hijack_open_clip.FrozenOpenCLIPEmbedderWithCustomWords(m.cond_stage_model, self) - - apply_weighted_forward(m) - if m.cond_stage_key == "edit": - sd_hijack_unet.hijack_ddpm_edit() - - self.apply_optimizations() - - self.clip = m.cond_stage_model - - def flatten(el): - flattened = [flatten(children) for children in el.children()] - res = [el] - for c in flattened: - res += c - return res - - self.layers = flatten(m) - - import modules.models.diffusion.ddpm_edit - - if isinstance(m, ldm.models.diffusion.ddpm.LatentDiffusion): - sd_unet.original_forward = ldm_original_forward - elif isinstance(m, modules.models.diffusion.ddpm_edit.LatentDiffusion): - sd_unet.original_forward = ldm_original_forward - elif isinstance(m, sgm.models.diffusion.DiffusionEngine): - sd_unet.original_forward = sgm_original_forward - else: - sd_unet.original_forward = None - - - def undo_hijack(self, m): - conditioner = getattr(m, 'conditioner', None) - if conditioner: - for i in range(len(conditioner.embedders)): - embedder = conditioner.embedders[i] - if isinstance(embedder, (sd_hijack_open_clip.FrozenOpenCLIPEmbedderWithCustomWords, sd_hijack_open_clip.FrozenOpenCLIPEmbedder2WithCustomWords)): - embedder.wrapped.model.token_embedding = embedder.wrapped.model.token_embedding.wrapped - conditioner.embedders[i] = embedder.wrapped - if isinstance(embedder, sd_hijack_clip.FrozenCLIPEmbedderForSDXLWithCustomWords): - embedder.wrapped.transformer.text_model.embeddings.token_embedding = embedder.wrapped.transformer.text_model.embeddings.token_embedding.wrapped - conditioner.embedders[i] = embedder.wrapped - - if hasattr(m, 'cond_stage_model'): - delattr(m, 'cond_stage_model') - - elif type(m.cond_stage_model) == sd_hijack_xlmr.FrozenXLMREmbedderWithCustomWords: - m.cond_stage_model = m.cond_stage_model.wrapped - - elif type(m.cond_stage_model) == sd_hijack_clip.FrozenCLIPEmbedderWithCustomWords: - m.cond_stage_model = m.cond_stage_model.wrapped - - model_embeddings = m.cond_stage_model.transformer.text_model.embeddings - if type(model_embeddings.token_embedding) == EmbeddingsWithFixes: - model_embeddings.token_embedding = model_embeddings.token_embedding.wrapped - elif type(m.cond_stage_model) == sd_hijack_open_clip.FrozenOpenCLIPEmbedderWithCustomWords: - m.cond_stage_model.wrapped.model.token_embedding = m.cond_stage_model.wrapped.model.token_embedding.wrapped - m.cond_stage_model = m.cond_stage_model.wrapped - - undo_optimizations() - undo_weighted_forward(m) - - self.apply_circular(False) - self.layers = None - self.clip = None - - - def apply_circular(self, enable): - if self.circular_enabled == enable: - return - - self.circular_enabled = enable - - for layer in [layer for layer in self.layers if type(layer) == torch.nn.Conv2d]: - layer.padding_mode = 'circular' if enable else 'zeros' - - def clear_comments(self): - self.comments = [] - self.extra_generation_params = {} - - def get_prompt_lengths(self, text): - if self.clip is None: - return "-", "-" - - if hasattr(self.clip, 'get_token_count'): - token_count = self.clip.get_token_count(text) - else: - _, token_count = self.clip.process_texts([text]) - - return token_count, self.clip.get_target_prompt_token_count(token_count) - - def redo_hijack(self, m): - self.undo_hijack(m) - self.hijack(m) - - -class EmbeddingsWithFixes(torch.nn.Module): - def __init__(self, wrapped, embeddings, textual_inversion_key='clip_l'): - super().__init__() - self.wrapped = wrapped - self.embeddings = embeddings - self.textual_inversion_key = textual_inversion_key - - def forward(self, input_ids): - batch_fixes = self.embeddings.fixes - self.embeddings.fixes = None - - inputs_embeds = self.wrapped(input_ids) - - if batch_fixes is None or len(batch_fixes) == 0 or max([len(x) for x in batch_fixes]) == 0: - return inputs_embeds - - vecs = [] - for fixes, tensor in zip(batch_fixes, inputs_embeds): - for offset, embedding in fixes: - vec = embedding.vec[self.textual_inversion_key] if isinstance(embedding.vec, dict) else embedding.vec - emb = devices.cond_cast_unet(vec) - emb_len = min(tensor.shape[0] - offset - 1, emb.shape[0]) - tensor = torch.cat([tensor[0:offset + 1], emb[0:emb_len], tensor[offset + 1 + emb_len:]]).to(dtype=inputs_embeds.dtype) - - vecs.append(tensor) - - return torch.stack(vecs) - - -class TextualInversionEmbeddings(torch.nn.Embedding): - def __init__(self, num_embeddings: int, embedding_dim: int, textual_inversion_key='clip_l', **kwargs): - super().__init__(num_embeddings, embedding_dim, **kwargs) - - self.embeddings = model_hijack - self.textual_inversion_key = textual_inversion_key - - @property - def wrapped(self): - return super().forward - - def forward(self, input_ids): - return EmbeddingsWithFixes.forward(self, input_ids) - - -def add_circular_option_to_conv_2d(): - conv2d_constructor = torch.nn.Conv2d.__init__ - - def conv2d_constructor_circular(self, *args, **kwargs): - return conv2d_constructor(self, *args, padding_mode='circular', **kwargs) - - torch.nn.Conv2d.__init__ = conv2d_constructor_circular - - -model_hijack = StableDiffusionModelHijack() - - -def register_buffer(self, name, attr): - - if type(attr) == torch.Tensor: - if attr.device != devices.device: - attr = attr.to(device=devices.device, dtype=(torch.float32 if devices.device.type == 'mps' else None)) - - setattr(self, name, attr) - - -ldm.models.diffusion.ddim.DDIMSampler.register_buffer = register_buffer -ldm.models.diffusion.plms.PLMSSampler.register_buffer = register_buffer+import torch +from torch.nn.functional import silu +from types import MethodType + +from modules import devices, sd_hijack_optimizations, shared, script_callbacks, errors, sd_unet, patches +from modules.hypernetworks import hypernetwork +from modules.shared import cmd_opts +from modules import sd_hijack_clip, sd_hijack_open_clip, sd_hijack_unet, sd_hijack_xlmr, xlmr, xlmr_m18 + +import ldm.modules.attention +import ldm.modules.diffusionmodules.model +import ldm.modules.diffusionmodules.openaimodel +import ldm.models.diffusion.ddpm +import ldm.models.diffusion.ddim +import ldm.models.diffusion.plms +import ldm.modules.encoders.modules + +import sgm.modules.attention +import sgm.modules.diffusionmodules.model +import sgm.modules.diffusionmodules.openaimodel +import sgm.modules.encoders.modules + +attention_CrossAttention_forward = ldm.modules.attention.CrossAttention.forward +diffusionmodules_model_nonlinearity = ldm.modules.diffusionmodules.model.nonlinearity +diffusionmodules_model_AttnBlock_forward = ldm.modules.diffusionmodules.model.AttnBlock.forward + +# new memory efficient cross attention blocks do not support hypernets and we already +# have memory efficient cross attention anyway, so this disables SD2.0's memory efficient cross attention +ldm.modules.attention.MemoryEfficientCrossAttention = ldm.modules.attention.CrossAttention +ldm.modules.attention.BasicTransformerBlock.ATTENTION_MODES["softmax-xformers"] = ldm.modules.attention.CrossAttention + +# silence new console spam from SD2 +ldm.modules.attention.print = shared.ldm_print +ldm.modules.diffusionmodules.model.print = shared.ldm_print +ldm.util.print = shared.ldm_print +ldm.models.diffusion.ddpm.print = shared.ldm_print + +optimizers = [] +current_optimizer: sd_hijack_optimizations.SdOptimization = None + +ldm_patched_forward = sd_unet.create_unet_forward(ldm.modules.diffusionmodules.openaimodel.UNetModel.forward) +ldm_original_forward = patches.patch(__file__, ldm.modules.diffusionmodules.openaimodel.UNetModel, "forward", ldm_patched_forward) + +sgm_patched_forward = sd_unet.create_unet_forward(sgm.modules.diffusionmodules.openaimodel.UNetModel.forward) +sgm_original_forward = patches.patch(__file__, sgm.modules.diffusionmodules.openaimodel.UNetModel, "forward", sgm_patched_forward) + + +def list_optimizers(): + new_optimizers = script_callbacks.list_optimizers_callback() + + new_optimizers = [x for x in new_optimizers if x.is_available()] + + new_optimizers = sorted(new_optimizers, key=lambda x: x.priority, reverse=True) + + optimizers.clear() + optimizers.extend(new_optimizers) + + +def apply_optimizations(option=None): + global current_optimizer + + undo_optimizations() + + if len(optimizers) == 0: + # a script can access the model very early, and optimizations would not be filled by then + current_optimizer = None + return '' + + ldm.modules.diffusionmodules.model.nonlinearity = silu + ldm.modules.diffusionmodules.openaimodel.th = sd_hijack_unet.th + + sgm.modules.diffusionmodules.model.nonlinearity = silu + sgm.modules.diffusionmodules.openaimodel.th = sd_hijack_unet.th + + if current_optimizer is not None: + current_optimizer.undo() + current_optimizer = None + + selection = option or shared.opts.cross_attention_optimization + if selection == "Automatic" and len(optimizers) > 0: + matching_optimizer = next(iter([x for x in optimizers if x.cmd_opt and getattr(shared.cmd_opts, x.cmd_opt, False)]), optimizers[0]) + else: + matching_optimizer = next(iter([x for x in optimizers if x.title() == selection]), None) + + if selection == "None": + matching_optimizer = None + elif selection == "Automatic" and shared.cmd_opts.disable_opt_split_attention: + matching_optimizer = None + elif matching_optimizer is None: + matching_optimizer = optimizers[0] + + if matching_optimizer is not None: + print(f"Applying attention optimization: {matching_optimizer.name}... ", end='') + matching_optimizer.apply() + print("done.") + current_optimizer = matching_optimizer + return current_optimizer.name + else: + print("Disabling attention optimization") + return '' + + +def undo_optimizations(): + ldm.modules.diffusionmodules.model.nonlinearity = diffusionmodules_model_nonlinearity + ldm.modules.attention.CrossAttention.forward = hypernetwork.attention_CrossAttention_forward + ldm.modules.diffusionmodules.model.AttnBlock.forward = diffusionmodules_model_AttnBlock_forward + + sgm.modules.diffusionmodules.model.nonlinearity = diffusionmodules_model_nonlinearity + sgm.modules.attention.CrossAttention.forward = hypernetwork.attention_CrossAttention_forward + sgm.modules.diffusionmodules.model.AttnBlock.forward = diffusionmodules_model_AttnBlock_forward + + +def fix_checkpoint(): + """checkpoints are now added and removed in embedding/hypernet code, since torch doesn't want + checkpoints to be added when not training (there's a warning)""" + + pass + + +def weighted_loss(sd_model, pred, target, mean=True): + #Calculate the weight normally, but ignore the mean + loss = sd_model._old_get_loss(pred, target, mean=False) + + #Check if we have weights available + weight = getattr(sd_model, '_custom_loss_weight', None) + if weight is not None: + loss *= weight + + #Return the loss, as mean if specified + return loss.mean() if mean else loss + +def weighted_forward(sd_model, x, c, w, *args, **kwargs): + try: + #Temporarily append weights to a place accessible during loss calc + sd_model._custom_loss_weight = w + + #Replace 'get_loss' with a weight-aware one. Otherwise we need to reimplement 'forward' completely + #Keep 'get_loss', but don't overwrite the previous old_get_loss if it's already set + if not hasattr(sd_model, '_old_get_loss'): + sd_model._old_get_loss = sd_model.get_loss + sd_model.get_loss = MethodType(weighted_loss, sd_model) + + #Run the standard forward function, but with the patched 'get_loss' + return sd_model.forward(x, c, *args, **kwargs) + finally: + try: + #Delete temporary weights if appended + del sd_model._custom_loss_weight + except AttributeError: + pass + + #If we have an old loss function, reset the loss function to the original one + if hasattr(sd_model, '_old_get_loss'): + sd_model.get_loss = sd_model._old_get_loss + del sd_model._old_get_loss + +def apply_weighted_forward(sd_model): + #Add new function 'weighted_forward' that can be called to calc weighted loss + sd_model.weighted_forward = MethodType(weighted_forward, sd_model) + +def undo_weighted_forward(sd_model): + try: + del sd_model.weighted_forward + except AttributeError: + pass + + +class StableDiffusionModelHijack: + fixes = None + layers = None + circular_enabled = False + clip = None + optimization_method = None + + def __init__(self): + import modules.textual_inversion.textual_inversion + + self.extra_generation_params = {} + self.comments = [] + + self.embedding_db = modules.textual_inversion.textual_inversion.EmbeddingDatabase() + self.embedding_db.add_embedding_dir(cmd_opts.embeddings_dir) + + def apply_optimizations(self, option=None): + try: + self.optimization_method = apply_optimizations(option) + except Exception as e: + errors.display(e, "applying cross attention optimization") + undo_optimizations() + + def convert_sdxl_to_ssd(self, m): + """Converts an SDXL model to a Segmind Stable Diffusion model (see https://huggingface.co/segmind/SSD-1B)""" + + delattr(m.model.diffusion_model.middle_block, '1') + delattr(m.model.diffusion_model.middle_block, '2') + for i in ['9', '8', '7', '6', '5', '4']: + delattr(m.model.diffusion_model.input_blocks[7][1].transformer_blocks, i) + delattr(m.model.diffusion_model.input_blocks[8][1].transformer_blocks, i) + delattr(m.model.diffusion_model.output_blocks[0][1].transformer_blocks, i) + delattr(m.model.diffusion_model.output_blocks[1][1].transformer_blocks, i) + delattr(m.model.diffusion_model.output_blocks[4][1].transformer_blocks, '1') + delattr(m.model.diffusion_model.output_blocks[5][1].transformer_blocks, '1') + devices.torch_gc() + + def hijack(self, m): + conditioner = getattr(m, 'conditioner', None) + if conditioner: + text_cond_models = [] + + for i in range(len(conditioner.embedders)): + embedder = conditioner.embedders[i] + typename = type(embedder).__name__ + if typename == 'FrozenOpenCLIPEmbedder': + embedder.model.token_embedding = EmbeddingsWithFixes(embedder.model.token_embedding, self) + conditioner.embedders[i] = sd_hijack_open_clip.FrozenOpenCLIPEmbedderWithCustomWords(embedder, self) + text_cond_models.append(conditioner.embedders[i]) + if typename == 'FrozenCLIPEmbedder': + model_embeddings = embedder.transformer.text_model.embeddings + model_embeddings.token_embedding = EmbeddingsWithFixes(model_embeddings.token_embedding, self) + conditioner.embedders[i] = sd_hijack_clip.FrozenCLIPEmbedderForSDXLWithCustomWords(embedder, self) + text_cond_models.append(conditioner.embedders[i]) + if typename == 'FrozenOpenCLIPEmbedder2': + embedder.model.token_embedding = EmbeddingsWithFixes(embedder.model.token_embedding, self, textual_inversion_key='clip_g') + conditioner.embedders[i] = sd_hijack_open_clip.FrozenOpenCLIPEmbedder2WithCustomWords(embedder, self) + text_cond_models.append(conditioner.embedders[i]) + + if len(text_cond_models) == 1: + m.cond_stage_model = text_cond_models[0] + else: + m.cond_stage_model = conditioner + + if type(m.cond_stage_model) == xlmr.BertSeriesModelWithTransformation or type(m.cond_stage_model) == xlmr_m18.BertSeriesModelWithTransformation: + model_embeddings = m.cond_stage_model.roberta.embeddings + model_embeddings.token_embedding = EmbeddingsWithFixes(model_embeddings.word_embeddings, self) + m.cond_stage_model = sd_hijack_xlmr.FrozenXLMREmbedderWithCustomWords(m.cond_stage_model, self) + + elif type(m.cond_stage_model) == ldm.modules.encoders.modules.FrozenCLIPEmbedder: + model_embeddings = m.cond_stage_model.transformer.text_model.embeddings + model_embeddings.token_embedding = EmbeddingsWithFixes(model_embeddings.token_embedding, self) + m.cond_stage_model = sd_hijack_clip.FrozenCLIPEmbedderWithCustomWords(m.cond_stage_model, self) + + elif type(m.cond_stage_model) == ldm.modules.encoders.modules.FrozenOpenCLIPEmbedder: + m.cond_stage_model.model.token_embedding = EmbeddingsWithFixes(m.cond_stage_model.model.token_embedding, self) + m.cond_stage_model = sd_hijack_open_clip.FrozenOpenCLIPEmbedderWithCustomWords(m.cond_stage_model, self) + + apply_weighted_forward(m) + if m.cond_stage_key == "edit": + sd_hijack_unet.hijack_ddpm_edit() + + self.apply_optimizations() + + self.clip = m.cond_stage_model + + def flatten(el): + flattened = [flatten(children) for children in el.children()] + res = [el] + for c in flattened: + res += c + return res + + self.layers = flatten(m) + + import modules.models.diffusion.ddpm_edit + + if isinstance(m, ldm.models.diffusion.ddpm.LatentDiffusion): + sd_unet.original_forward = ldm_original_forward + elif isinstance(m, modules.models.diffusion.ddpm_edit.LatentDiffusion): + sd_unet.original_forward = ldm_original_forward + elif isinstance(m, sgm.models.diffusion.DiffusionEngine): + sd_unet.original_forward = sgm_original_forward + else: + sd_unet.original_forward = None + + + def undo_hijack(self, m): + conditioner = getattr(m, 'conditioner', None) + if conditioner: + for i in range(len(conditioner.embedders)): + embedder = conditioner.embedders[i] + if isinstance(embedder, (sd_hijack_open_clip.FrozenOpenCLIPEmbedderWithCustomWords, sd_hijack_open_clip.FrozenOpenCLIPEmbedder2WithCustomWords)): + embedder.wrapped.model.token_embedding = embedder.wrapped.model.token_embedding.wrapped + conditioner.embedders[i] = embedder.wrapped + if isinstance(embedder, sd_hijack_clip.FrozenCLIPEmbedderForSDXLWithCustomWords): + embedder.wrapped.transformer.text_model.embeddings.token_embedding = embedder.wrapped.transformer.text_model.embeddings.token_embedding.wrapped + conditioner.embedders[i] = embedder.wrapped + + if hasattr(m, 'cond_stage_model'): + delattr(m, 'cond_stage_model') + + elif type(m.cond_stage_model) == sd_hijack_xlmr.FrozenXLMREmbedderWithCustomWords: + m.cond_stage_model = m.cond_stage_model.wrapped + + elif type(m.cond_stage_model) == sd_hijack_clip.FrozenCLIPEmbedderWithCustomWords: + m.cond_stage_model = m.cond_stage_model.wrapped + + model_embeddings = m.cond_stage_model.transformer.text_model.embeddings + if type(model_embeddings.token_embedding) == EmbeddingsWithFixes: + model_embeddings.token_embedding = model_embeddings.token_embedding.wrapped + elif type(m.cond_stage_model) == sd_hijack_open_clip.FrozenOpenCLIPEmbedderWithCustomWords: + m.cond_stage_model.wrapped.model.token_embedding = m.cond_stage_model.wrapped.model.token_embedding.wrapped + m.cond_stage_model = m.cond_stage_model.wrapped + + undo_optimizations() + undo_weighted_forward(m) + + self.apply_circular(False) + self.layers = None + self.clip = None + + + def apply_circular(self, enable): + if self.circular_enabled == enable: + return + + self.circular_enabled = enable + + for layer in [layer for layer in self.layers if type(layer) == torch.nn.Conv2d]: + layer.padding_mode = 'circular' if enable else 'zeros' + + def clear_comments(self): + self.comments = [] + self.extra_generation_params = {} + + def get_prompt_lengths(self, text): + if self.clip is None: + return "-", "-" + + if hasattr(self.clip, 'get_token_count'): + token_count = self.clip.get_token_count(text) + else: + _, token_count = self.clip.process_texts([text]) + + return token_count, self.clip.get_target_prompt_token_count(token_count) + + def redo_hijack(self, m): + self.undo_hijack(m) + self.hijack(m) + + +class EmbeddingsWithFixes(torch.nn.Module): + def __init__(self, wrapped, embeddings, textual_inversion_key='clip_l'): + super().__init__() + self.wrapped = wrapped + self.embeddings = embeddings + self.textual_inversion_key = textual_inversion_key + + def forward(self, input_ids): + batch_fixes = self.embeddings.fixes + self.embeddings.fixes = None + + inputs_embeds = self.wrapped(input_ids) + + if batch_fixes is None or len(batch_fixes) == 0 or max([len(x) for x in batch_fixes]) == 0: + return inputs_embeds + + vecs = [] + for fixes, tensor in zip(batch_fixes, inputs_embeds): + for offset, embedding in fixes: + vec = embedding.vec[self.textual_inversion_key] if isinstance(embedding.vec, dict) else embedding.vec + emb = devices.cond_cast_unet(vec) + emb_len = min(tensor.shape[0] - offset - 1, emb.shape[0]) + tensor = torch.cat([tensor[0:offset + 1], emb[0:emb_len], tensor[offset + 1 + emb_len:]]).to(dtype=inputs_embeds.dtype) + + vecs.append(tensor) + + return torch.stack(vecs) + + +class TextualInversionEmbeddings(torch.nn.Embedding): + def __init__(self, num_embeddings: int, embedding_dim: int, textual_inversion_key='clip_l', **kwargs): + super().__init__(num_embeddings, embedding_dim, **kwargs) + + self.embeddings = model_hijack + self.textual_inversion_key = textual_inversion_key + + @property + def wrapped(self): + return super().forward + + def forward(self, input_ids): + return EmbeddingsWithFixes.forward(self, input_ids) + + +def add_circular_option_to_conv_2d(): + conv2d_constructor = torch.nn.Conv2d.__init__ + + def conv2d_constructor_circular(self, *args, **kwargs): + return conv2d_constructor(self, *args, padding_mode='circular', **kwargs) + + torch.nn.Conv2d.__init__ = conv2d_constructor_circular + + +model_hijack = StableDiffusionModelHijack() + + +def register_buffer(self, name, attr): + """ + Fix register buffer bug for Mac OS. + """ + + if type(attr) == torch.Tensor: + if attr.device != devices.device: + attr = attr.to(device=devices.device, dtype=(torch.float32 if devices.device.type == 'mps' else None)) + + setattr(self, name, attr) + + +ldm.models.diffusion.ddim.DDIMSampler.register_buffer = register_buffer +ldm.models.diffusion.plms.PLMSSampler.register_buffer = register_buffer
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_hijack.py
Add docstrings to improve readability
import torch from packaging import version from einops import repeat import math from modules import devices from modules.sd_hijack_utils import CondFunc class TorchHijackForUnet: def __getattr__(self, item): if item == 'cat': return self.cat if hasattr(torch, item): return getattr(torch, item) raise AttributeError(f"'{type(self).__name__}' object has no attribute '{item}'") def cat(self, tensors, *args, **kwargs): if len(tensors) == 2: a, b = tensors if a.shape[-2:] != b.shape[-2:]: a = torch.nn.functional.interpolate(a, b.shape[-2:], mode="nearest") tensors = (a, b) return torch.cat(tensors, *args, **kwargs) th = TorchHijackForUnet() # Below are monkey patches to enable upcasting a float16 UNet for float32 sampling def apply_model(orig_func, self, x_noisy, t, cond, **kwargs): if isinstance(cond, dict): for y in cond.keys(): if isinstance(cond[y], list): cond[y] = [x.to(devices.dtype_unet) if isinstance(x, torch.Tensor) else x for x in cond[y]] else: cond[y] = cond[y].to(devices.dtype_unet) if isinstance(cond[y], torch.Tensor) else cond[y] with devices.autocast(): result = orig_func(self, x_noisy.to(devices.dtype_unet), t.to(devices.dtype_unet), cond, **kwargs) if devices.unet_needs_upcast: return result.float() else: return result # Monkey patch to create timestep embed tensor on device, avoiding a block. def timestep_embedding(_, timesteps, dim, max_period=10000, repeat_only=False): if not repeat_only: half = dim // 2 freqs = torch.exp( -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=timesteps.device) / half ) args = timesteps[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) else: embedding = repeat(timesteps, 'b -> b d', d=dim) return embedding # Monkey patch to SpatialTransformer removing unnecessary contiguous calls. # Prevents a lot of unnecessary aten::copy_ calls def spatial_transformer_forward(_, self, x: torch.Tensor, context=None): # note: if no context is given, cross-attention defaults to self-attention if not isinstance(context, list): context = [context] b, c, h, w = x.shape x_in = x x = self.norm(x) if not self.use_linear: x = self.proj_in(x) x = x.permute(0, 2, 3, 1).reshape(b, h * w, c) if self.use_linear: x = self.proj_in(x) for i, block in enumerate(self.transformer_blocks): x = block(x, context=context[i]) if self.use_linear: x = self.proj_out(x) x = x.view(b, h, w, c).permute(0, 3, 1, 2) if not self.use_linear: x = self.proj_out(x) return x + x_in class GELUHijack(torch.nn.GELU, torch.nn.Module): def __init__(self, *args, **kwargs): torch.nn.GELU.__init__(self, *args, **kwargs) def forward(self, x): if devices.unet_needs_upcast: return torch.nn.GELU.forward(self.float(), x.float()).to(devices.dtype_unet) else: return torch.nn.GELU.forward(self, x) ddpm_edit_hijack = None def hijack_ddpm_edit(): global ddpm_edit_hijack if not ddpm_edit_hijack: CondFunc('modules.models.diffusion.ddpm_edit.LatentDiffusion.decode_first_stage', first_stage_sub, first_stage_cond) CondFunc('modules.models.diffusion.ddpm_edit.LatentDiffusion.encode_first_stage', first_stage_sub, first_stage_cond) ddpm_edit_hijack = CondFunc('modules.models.diffusion.ddpm_edit.LatentDiffusion.apply_model', apply_model) unet_needs_upcast = lambda *args, **kwargs: devices.unet_needs_upcast CondFunc('ldm.models.diffusion.ddpm.LatentDiffusion.apply_model', apply_model, unet_needs_upcast) CondFunc('ldm.modules.diffusionmodules.openaimodel.timestep_embedding', timestep_embedding) CondFunc('ldm.modules.attention.SpatialTransformer.forward', spatial_transformer_forward) CondFunc('ldm.modules.diffusionmodules.openaimodel.timestep_embedding', lambda orig_func, timesteps, *args, **kwargs: orig_func(timesteps, *args, **kwargs).to(torch.float32 if timesteps.dtype == torch.int64 else devices.dtype_unet), unet_needs_upcast) if version.parse(torch.__version__) <= version.parse("1.13.2") or torch.cuda.is_available(): CondFunc('ldm.modules.diffusionmodules.util.GroupNorm32.forward', lambda orig_func, self, *args, **kwargs: orig_func(self.float(), *args, **kwargs), unet_needs_upcast) CondFunc('ldm.modules.attention.GEGLU.forward', lambda orig_func, self, x: orig_func(self.float(), x.float()).to(devices.dtype_unet), unet_needs_upcast) CondFunc('open_clip.transformer.ResidualAttentionBlock.__init__', lambda orig_func, *args, **kwargs: kwargs.update({'act_layer': GELUHijack}) and False or orig_func(*args, **kwargs), lambda _, *args, **kwargs: kwargs.get('act_layer') is None or kwargs['act_layer'] == torch.nn.GELU) first_stage_cond = lambda _, self, *args, **kwargs: devices.unet_needs_upcast and self.model.diffusion_model.dtype == torch.float16 first_stage_sub = lambda orig_func, self, x, **kwargs: orig_func(self, x.to(devices.dtype_vae), **kwargs) CondFunc('ldm.models.diffusion.ddpm.LatentDiffusion.decode_first_stage', first_stage_sub, first_stage_cond) CondFunc('ldm.models.diffusion.ddpm.LatentDiffusion.encode_first_stage', first_stage_sub, first_stage_cond) CondFunc('ldm.models.diffusion.ddpm.LatentDiffusion.get_first_stage_encoding', lambda orig_func, *args, **kwargs: orig_func(*args, **kwargs).float(), first_stage_cond) CondFunc('ldm.models.diffusion.ddpm.LatentDiffusion.apply_model', apply_model) CondFunc('sgm.modules.diffusionmodules.wrappers.OpenAIWrapper.forward', apply_model) def timestep_embedding_cast_result(orig_func, timesteps, *args, **kwargs): if devices.unet_needs_upcast and timesteps.dtype == torch.int64: dtype = torch.float32 else: dtype = devices.dtype_unet return orig_func(timesteps, *args, **kwargs).to(dtype=dtype) CondFunc('ldm.modules.diffusionmodules.openaimodel.timestep_embedding', timestep_embedding_cast_result) CondFunc('sgm.modules.diffusionmodules.openaimodel.timestep_embedding', timestep_embedding_cast_result)
--- +++ @@ -1,141 +1,154 @@-import torch -from packaging import version -from einops import repeat -import math - -from modules import devices -from modules.sd_hijack_utils import CondFunc - - -class TorchHijackForUnet: - - def __getattr__(self, item): - if item == 'cat': - return self.cat - - if hasattr(torch, item): - return getattr(torch, item) - - raise AttributeError(f"'{type(self).__name__}' object has no attribute '{item}'") - - def cat(self, tensors, *args, **kwargs): - if len(tensors) == 2: - a, b = tensors - if a.shape[-2:] != b.shape[-2:]: - a = torch.nn.functional.interpolate(a, b.shape[-2:], mode="nearest") - - tensors = (a, b) - - return torch.cat(tensors, *args, **kwargs) - - -th = TorchHijackForUnet() - - -# Below are monkey patches to enable upcasting a float16 UNet for float32 sampling -def apply_model(orig_func, self, x_noisy, t, cond, **kwargs): - if isinstance(cond, dict): - for y in cond.keys(): - if isinstance(cond[y], list): - cond[y] = [x.to(devices.dtype_unet) if isinstance(x, torch.Tensor) else x for x in cond[y]] - else: - cond[y] = cond[y].to(devices.dtype_unet) if isinstance(cond[y], torch.Tensor) else cond[y] - - with devices.autocast(): - result = orig_func(self, x_noisy.to(devices.dtype_unet), t.to(devices.dtype_unet), cond, **kwargs) - if devices.unet_needs_upcast: - return result.float() - else: - return result - - -# Monkey patch to create timestep embed tensor on device, avoiding a block. -def timestep_embedding(_, timesteps, dim, max_period=10000, repeat_only=False): - if not repeat_only: - half = dim // 2 - freqs = torch.exp( - -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=timesteps.device) / half - ) - args = timesteps[:, None].float() * freqs[None] - embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) - if dim % 2: - embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) - else: - embedding = repeat(timesteps, 'b -> b d', d=dim) - return embedding - - -# Monkey patch to SpatialTransformer removing unnecessary contiguous calls. -# Prevents a lot of unnecessary aten::copy_ calls -def spatial_transformer_forward(_, self, x: torch.Tensor, context=None): - # note: if no context is given, cross-attention defaults to self-attention - if not isinstance(context, list): - context = [context] - b, c, h, w = x.shape - x_in = x - x = self.norm(x) - if not self.use_linear: - x = self.proj_in(x) - x = x.permute(0, 2, 3, 1).reshape(b, h * w, c) - if self.use_linear: - x = self.proj_in(x) - for i, block in enumerate(self.transformer_blocks): - x = block(x, context=context[i]) - if self.use_linear: - x = self.proj_out(x) - x = x.view(b, h, w, c).permute(0, 3, 1, 2) - if not self.use_linear: - x = self.proj_out(x) - return x + x_in - - -class GELUHijack(torch.nn.GELU, torch.nn.Module): - def __init__(self, *args, **kwargs): - torch.nn.GELU.__init__(self, *args, **kwargs) - def forward(self, x): - if devices.unet_needs_upcast: - return torch.nn.GELU.forward(self.float(), x.float()).to(devices.dtype_unet) - else: - return torch.nn.GELU.forward(self, x) - - -ddpm_edit_hijack = None -def hijack_ddpm_edit(): - global ddpm_edit_hijack - if not ddpm_edit_hijack: - CondFunc('modules.models.diffusion.ddpm_edit.LatentDiffusion.decode_first_stage', first_stage_sub, first_stage_cond) - CondFunc('modules.models.diffusion.ddpm_edit.LatentDiffusion.encode_first_stage', first_stage_sub, first_stage_cond) - ddpm_edit_hijack = CondFunc('modules.models.diffusion.ddpm_edit.LatentDiffusion.apply_model', apply_model) - - -unet_needs_upcast = lambda *args, **kwargs: devices.unet_needs_upcast -CondFunc('ldm.models.diffusion.ddpm.LatentDiffusion.apply_model', apply_model, unet_needs_upcast) -CondFunc('ldm.modules.diffusionmodules.openaimodel.timestep_embedding', timestep_embedding) -CondFunc('ldm.modules.attention.SpatialTransformer.forward', spatial_transformer_forward) -CondFunc('ldm.modules.diffusionmodules.openaimodel.timestep_embedding', lambda orig_func, timesteps, *args, **kwargs: orig_func(timesteps, *args, **kwargs).to(torch.float32 if timesteps.dtype == torch.int64 else devices.dtype_unet), unet_needs_upcast) - -if version.parse(torch.__version__) <= version.parse("1.13.2") or torch.cuda.is_available(): - CondFunc('ldm.modules.diffusionmodules.util.GroupNorm32.forward', lambda orig_func, self, *args, **kwargs: orig_func(self.float(), *args, **kwargs), unet_needs_upcast) - CondFunc('ldm.modules.attention.GEGLU.forward', lambda orig_func, self, x: orig_func(self.float(), x.float()).to(devices.dtype_unet), unet_needs_upcast) - CondFunc('open_clip.transformer.ResidualAttentionBlock.__init__', lambda orig_func, *args, **kwargs: kwargs.update({'act_layer': GELUHijack}) and False or orig_func(*args, **kwargs), lambda _, *args, **kwargs: kwargs.get('act_layer') is None or kwargs['act_layer'] == torch.nn.GELU) - -first_stage_cond = lambda _, self, *args, **kwargs: devices.unet_needs_upcast and self.model.diffusion_model.dtype == torch.float16 -first_stage_sub = lambda orig_func, self, x, **kwargs: orig_func(self, x.to(devices.dtype_vae), **kwargs) -CondFunc('ldm.models.diffusion.ddpm.LatentDiffusion.decode_first_stage', first_stage_sub, first_stage_cond) -CondFunc('ldm.models.diffusion.ddpm.LatentDiffusion.encode_first_stage', first_stage_sub, first_stage_cond) -CondFunc('ldm.models.diffusion.ddpm.LatentDiffusion.get_first_stage_encoding', lambda orig_func, *args, **kwargs: orig_func(*args, **kwargs).float(), first_stage_cond) - -CondFunc('ldm.models.diffusion.ddpm.LatentDiffusion.apply_model', apply_model) -CondFunc('sgm.modules.diffusionmodules.wrappers.OpenAIWrapper.forward', apply_model) - - -def timestep_embedding_cast_result(orig_func, timesteps, *args, **kwargs): - if devices.unet_needs_upcast and timesteps.dtype == torch.int64: - dtype = torch.float32 - else: - dtype = devices.dtype_unet - return orig_func(timesteps, *args, **kwargs).to(dtype=dtype) - - -CondFunc('ldm.modules.diffusionmodules.openaimodel.timestep_embedding', timestep_embedding_cast_result) -CondFunc('sgm.modules.diffusionmodules.openaimodel.timestep_embedding', timestep_embedding_cast_result)+import torch +from packaging import version +from einops import repeat +import math + +from modules import devices +from modules.sd_hijack_utils import CondFunc + + +class TorchHijackForUnet: + """ + This is torch, but with cat that resizes tensors to appropriate dimensions if they do not match; + this makes it possible to create pictures with dimensions that are multiples of 8 rather than 64 + """ + + def __getattr__(self, item): + if item == 'cat': + return self.cat + + if hasattr(torch, item): + return getattr(torch, item) + + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{item}'") + + def cat(self, tensors, *args, **kwargs): + if len(tensors) == 2: + a, b = tensors + if a.shape[-2:] != b.shape[-2:]: + a = torch.nn.functional.interpolate(a, b.shape[-2:], mode="nearest") + + tensors = (a, b) + + return torch.cat(tensors, *args, **kwargs) + + +th = TorchHijackForUnet() + + +# Below are monkey patches to enable upcasting a float16 UNet for float32 sampling +def apply_model(orig_func, self, x_noisy, t, cond, **kwargs): + """Always make sure inputs to unet are in correct dtype.""" + if isinstance(cond, dict): + for y in cond.keys(): + if isinstance(cond[y], list): + cond[y] = [x.to(devices.dtype_unet) if isinstance(x, torch.Tensor) else x for x in cond[y]] + else: + cond[y] = cond[y].to(devices.dtype_unet) if isinstance(cond[y], torch.Tensor) else cond[y] + + with devices.autocast(): + result = orig_func(self, x_noisy.to(devices.dtype_unet), t.to(devices.dtype_unet), cond, **kwargs) + if devices.unet_needs_upcast: + return result.float() + else: + return result + + +# Monkey patch to create timestep embed tensor on device, avoiding a block. +def timestep_embedding(_, timesteps, dim, max_period=10000, repeat_only=False): + """ + Create sinusoidal timestep embeddings. + :param timesteps: a 1-D Tensor of N indices, one per batch element. + These may be fractional. + :param dim: the dimension of the output. + :param max_period: controls the minimum frequency of the embeddings. + :return: an [N x dim] Tensor of positional embeddings. + """ + if not repeat_only: + half = dim // 2 + freqs = torch.exp( + -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32, device=timesteps.device) / half + ) + args = timesteps[:, None].float() * freqs[None] + embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) + if dim % 2: + embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) + else: + embedding = repeat(timesteps, 'b -> b d', d=dim) + return embedding + + +# Monkey patch to SpatialTransformer removing unnecessary contiguous calls. +# Prevents a lot of unnecessary aten::copy_ calls +def spatial_transformer_forward(_, self, x: torch.Tensor, context=None): + # note: if no context is given, cross-attention defaults to self-attention + if not isinstance(context, list): + context = [context] + b, c, h, w = x.shape + x_in = x + x = self.norm(x) + if not self.use_linear: + x = self.proj_in(x) + x = x.permute(0, 2, 3, 1).reshape(b, h * w, c) + if self.use_linear: + x = self.proj_in(x) + for i, block in enumerate(self.transformer_blocks): + x = block(x, context=context[i]) + if self.use_linear: + x = self.proj_out(x) + x = x.view(b, h, w, c).permute(0, 3, 1, 2) + if not self.use_linear: + x = self.proj_out(x) + return x + x_in + + +class GELUHijack(torch.nn.GELU, torch.nn.Module): + def __init__(self, *args, **kwargs): + torch.nn.GELU.__init__(self, *args, **kwargs) + def forward(self, x): + if devices.unet_needs_upcast: + return torch.nn.GELU.forward(self.float(), x.float()).to(devices.dtype_unet) + else: + return torch.nn.GELU.forward(self, x) + + +ddpm_edit_hijack = None +def hijack_ddpm_edit(): + global ddpm_edit_hijack + if not ddpm_edit_hijack: + CondFunc('modules.models.diffusion.ddpm_edit.LatentDiffusion.decode_first_stage', first_stage_sub, first_stage_cond) + CondFunc('modules.models.diffusion.ddpm_edit.LatentDiffusion.encode_first_stage', first_stage_sub, first_stage_cond) + ddpm_edit_hijack = CondFunc('modules.models.diffusion.ddpm_edit.LatentDiffusion.apply_model', apply_model) + + +unet_needs_upcast = lambda *args, **kwargs: devices.unet_needs_upcast +CondFunc('ldm.models.diffusion.ddpm.LatentDiffusion.apply_model', apply_model, unet_needs_upcast) +CondFunc('ldm.modules.diffusionmodules.openaimodel.timestep_embedding', timestep_embedding) +CondFunc('ldm.modules.attention.SpatialTransformer.forward', spatial_transformer_forward) +CondFunc('ldm.modules.diffusionmodules.openaimodel.timestep_embedding', lambda orig_func, timesteps, *args, **kwargs: orig_func(timesteps, *args, **kwargs).to(torch.float32 if timesteps.dtype == torch.int64 else devices.dtype_unet), unet_needs_upcast) + +if version.parse(torch.__version__) <= version.parse("1.13.2") or torch.cuda.is_available(): + CondFunc('ldm.modules.diffusionmodules.util.GroupNorm32.forward', lambda orig_func, self, *args, **kwargs: orig_func(self.float(), *args, **kwargs), unet_needs_upcast) + CondFunc('ldm.modules.attention.GEGLU.forward', lambda orig_func, self, x: orig_func(self.float(), x.float()).to(devices.dtype_unet), unet_needs_upcast) + CondFunc('open_clip.transformer.ResidualAttentionBlock.__init__', lambda orig_func, *args, **kwargs: kwargs.update({'act_layer': GELUHijack}) and False or orig_func(*args, **kwargs), lambda _, *args, **kwargs: kwargs.get('act_layer') is None or kwargs['act_layer'] == torch.nn.GELU) + +first_stage_cond = lambda _, self, *args, **kwargs: devices.unet_needs_upcast and self.model.diffusion_model.dtype == torch.float16 +first_stage_sub = lambda orig_func, self, x, **kwargs: orig_func(self, x.to(devices.dtype_vae), **kwargs) +CondFunc('ldm.models.diffusion.ddpm.LatentDiffusion.decode_first_stage', first_stage_sub, first_stage_cond) +CondFunc('ldm.models.diffusion.ddpm.LatentDiffusion.encode_first_stage', first_stage_sub, first_stage_cond) +CondFunc('ldm.models.diffusion.ddpm.LatentDiffusion.get_first_stage_encoding', lambda orig_func, *args, **kwargs: orig_func(*args, **kwargs).float(), first_stage_cond) + +CondFunc('ldm.models.diffusion.ddpm.LatentDiffusion.apply_model', apply_model) +CondFunc('sgm.modules.diffusionmodules.wrappers.OpenAIWrapper.forward', apply_model) + + +def timestep_embedding_cast_result(orig_func, timesteps, *args, **kwargs): + if devices.unet_needs_upcast and timesteps.dtype == torch.int64: + dtype = torch.float32 + else: + dtype = devices.dtype_unet + return orig_func(timesteps, *args, **kwargs).to(dtype=dtype) + + +CondFunc('ldm.modules.diffusionmodules.openaimodel.timestep_embedding', timestep_embedding_cast_result) +CondFunc('sgm.modules.diffusionmodules.openaimodel.timestep_embedding', timestep_embedding_cast_result)
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_hijack_unet.py
Write docstrings for this repository
import collections import importlib import os import sys import threading import enum import torch import re import safetensors.torch from omegaconf import OmegaConf, ListConfig from urllib import request import ldm.modules.midas as midas from modules import paths, shared, modelloader, devices, script_callbacks, sd_vae, sd_disable_initialization, errors, hashes, sd_models_config, sd_unet, sd_models_xl, cache, extra_networks, processing, lowvram, sd_hijack, patches from modules.timer import Timer from modules.shared import opts import tomesd import numpy as np model_dir = "Stable-diffusion" model_path = os.path.abspath(os.path.join(paths.models_path, model_dir)) checkpoints_list = {} checkpoint_aliases = {} checkpoint_alisases = checkpoint_aliases # for compatibility with old name checkpoints_loaded = collections.OrderedDict() class ModelType(enum.Enum): SD1 = 1 SD2 = 2 SDXL = 3 SSD = 4 SD3 = 5 def replace_key(d, key, new_key, value): keys = list(d.keys()) d[new_key] = value if key not in keys: return d index = keys.index(key) keys[index] = new_key new_d = {k: d[k] for k in keys} d.clear() d.update(new_d) return d class CheckpointInfo: def __init__(self, filename): self.filename = filename abspath = os.path.abspath(filename) abs_ckpt_dir = os.path.abspath(shared.cmd_opts.ckpt_dir) if shared.cmd_opts.ckpt_dir is not None else None self.is_safetensors = os.path.splitext(filename)[1].lower() == ".safetensors" if abs_ckpt_dir and abspath.startswith(abs_ckpt_dir): name = abspath.replace(abs_ckpt_dir, '') elif abspath.startswith(model_path): name = abspath.replace(model_path, '') else: name = os.path.basename(filename) if name.startswith("\\") or name.startswith("/"): name = name[1:] def read_metadata(): metadata = read_metadata_from_safetensors(filename) self.modelspec_thumbnail = metadata.pop('modelspec.thumbnail', None) return metadata self.metadata = {} if self.is_safetensors: try: self.metadata = cache.cached_data_for_file('safetensors-metadata', "checkpoint/" + name, filename, read_metadata) except Exception as e: errors.display(e, f"reading metadata for {filename}") self.name = name self.name_for_extra = os.path.splitext(os.path.basename(filename))[0] self.model_name = os.path.splitext(name.replace("/", "_").replace("\\", "_"))[0] self.hash = model_hash(filename) self.sha256 = hashes.sha256_from_cache(self.filename, f"checkpoint/{name}") self.shorthash = self.sha256[0:10] if self.sha256 else None self.title = name if self.shorthash is None else f'{name} [{self.shorthash}]' self.short_title = self.name_for_extra if self.shorthash is None else f'{self.name_for_extra} [{self.shorthash}]' self.ids = [self.hash, self.model_name, self.title, name, self.name_for_extra, f'{name} [{self.hash}]'] if self.shorthash: self.ids += [self.shorthash, self.sha256, f'{self.name} [{self.shorthash}]', f'{self.name_for_extra} [{self.shorthash}]'] def register(self): checkpoints_list[self.title] = self for id in self.ids: checkpoint_aliases[id] = self def calculate_shorthash(self): self.sha256 = hashes.sha256(self.filename, f"checkpoint/{self.name}") if self.sha256 is None: return shorthash = self.sha256[0:10] if self.shorthash == self.sha256[0:10]: return self.shorthash self.shorthash = shorthash if self.shorthash not in self.ids: self.ids += [self.shorthash, self.sha256, f'{self.name} [{self.shorthash}]', f'{self.name_for_extra} [{self.shorthash}]'] old_title = self.title self.title = f'{self.name} [{self.shorthash}]' self.short_title = f'{self.name_for_extra} [{self.shorthash}]' replace_key(checkpoints_list, old_title, self.title, self) self.register() return self.shorthash try: # this silences the annoying "Some weights of the model checkpoint were not used when initializing..." message at start. from transformers import logging, CLIPModel # noqa: F401 logging.set_verbosity_error() except Exception: pass def setup_model(): os.makedirs(model_path, exist_ok=True) enable_midas_autodownload() patch_given_betas() def checkpoint_tiles(use_short=False): return [x.short_title if use_short else x.title for x in checkpoints_list.values()] def list_models(): checkpoints_list.clear() checkpoint_aliases.clear() cmd_ckpt = shared.cmd_opts.ckpt if shared.cmd_opts.no_download_sd_model or cmd_ckpt != shared.sd_model_file or os.path.exists(cmd_ckpt): model_url = None expected_sha256 = None else: model_url = f"{shared.hf_endpoint}/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.safetensors" expected_sha256 = '6ce0161689b3853acaa03779ec93eafe75a02f4ced659bee03f50797806fa2fa' model_list = modelloader.load_models(model_path=model_path, model_url=model_url, command_path=shared.cmd_opts.ckpt_dir, ext_filter=[".ckpt", ".safetensors"], download_name="v1-5-pruned-emaonly.safetensors", ext_blacklist=[".vae.ckpt", ".vae.safetensors"], hash_prefix=expected_sha256) if os.path.exists(cmd_ckpt): checkpoint_info = CheckpointInfo(cmd_ckpt) checkpoint_info.register() shared.opts.data['sd_model_checkpoint'] = checkpoint_info.title elif cmd_ckpt is not None and cmd_ckpt != shared.default_sd_model_file: print(f"Checkpoint in --ckpt argument not found (Possible it was moved to {model_path}: {cmd_ckpt}", file=sys.stderr) for filename in model_list: checkpoint_info = CheckpointInfo(filename) checkpoint_info.register() re_strip_checksum = re.compile(r"\s*\[[^]]+]\s*$") def get_closet_checkpoint_match(search_string): if not search_string: return None checkpoint_info = checkpoint_aliases.get(search_string, None) if checkpoint_info is not None: return checkpoint_info found = sorted([info for info in checkpoints_list.values() if search_string in info.title], key=lambda x: len(x.title)) if found: return found[0] search_string_without_checksum = re.sub(re_strip_checksum, '', search_string) found = sorted([info for info in checkpoints_list.values() if search_string_without_checksum in info.title], key=lambda x: len(x.title)) if found: return found[0] return None def model_hash(filename): try: with open(filename, "rb") as file: import hashlib m = hashlib.sha256() file.seek(0x100000) m.update(file.read(0x10000)) return m.hexdigest()[0:8] except FileNotFoundError: return 'NOFILE' def select_checkpoint(): model_checkpoint = shared.opts.sd_model_checkpoint checkpoint_info = checkpoint_aliases.get(model_checkpoint, None) if checkpoint_info is not None: return checkpoint_info if len(checkpoints_list) == 0: error_message = "No checkpoints found. When searching for checkpoints, looked at:" if shared.cmd_opts.ckpt is not None: error_message += f"\n - file {os.path.abspath(shared.cmd_opts.ckpt)}" error_message += f"\n - directory {model_path}" if shared.cmd_opts.ckpt_dir is not None: error_message += f"\n - directory {os.path.abspath(shared.cmd_opts.ckpt_dir)}" error_message += "Can't run without a checkpoint. Find and place a .ckpt or .safetensors file into any of those locations." raise FileNotFoundError(error_message) checkpoint_info = next(iter(checkpoints_list.values())) if model_checkpoint is not None: print(f"Checkpoint {model_checkpoint} not found; loading fallback {checkpoint_info.title}", file=sys.stderr) return checkpoint_info checkpoint_dict_replacements_sd1 = { 'cond_stage_model.transformer.embeddings.': 'cond_stage_model.transformer.text_model.embeddings.', 'cond_stage_model.transformer.encoder.': 'cond_stage_model.transformer.text_model.encoder.', 'cond_stage_model.transformer.final_layer_norm.': 'cond_stage_model.transformer.text_model.final_layer_norm.', } checkpoint_dict_replacements_sd2_turbo = { # Converts SD 2.1 Turbo from SGM to LDM format. 'conditioner.embedders.0.': 'cond_stage_model.', } def transform_checkpoint_dict_key(k, replacements): for text, replacement in replacements.items(): if k.startswith(text): k = replacement + k[len(text):] return k def get_state_dict_from_checkpoint(pl_sd): pl_sd = pl_sd.pop("state_dict", pl_sd) pl_sd.pop("state_dict", None) is_sd2_turbo = 'conditioner.embedders.0.model.ln_final.weight' in pl_sd and pl_sd['conditioner.embedders.0.model.ln_final.weight'].size()[0] == 1024 sd = {} for k, v in pl_sd.items(): if is_sd2_turbo: new_key = transform_checkpoint_dict_key(k, checkpoint_dict_replacements_sd2_turbo) else: new_key = transform_checkpoint_dict_key(k, checkpoint_dict_replacements_sd1) if new_key is not None: sd[new_key] = v pl_sd.clear() pl_sd.update(sd) return pl_sd def read_metadata_from_safetensors(filename): import json with open(filename, mode="rb") as file: metadata_len = file.read(8) metadata_len = int.from_bytes(metadata_len, "little") json_start = file.read(2) assert metadata_len > 2 and json_start in (b'{"', b"{'"), f"{filename} is not a safetensors file" res = {} try: json_data = json_start + file.read(metadata_len-2) json_obj = json.loads(json_data) for k, v in json_obj.get("__metadata__", {}).items(): res[k] = v if isinstance(v, str) and v[0:1] == '{': try: res[k] = json.loads(v) except Exception: pass except Exception: errors.report(f"Error reading metadata from file: {filename}", exc_info=True) return res def read_state_dict(checkpoint_file, print_global_state=False, map_location=None): _, extension = os.path.splitext(checkpoint_file) if extension.lower() == ".safetensors": device = map_location or shared.weight_load_location or devices.get_optimal_device_name() if not shared.opts.disable_mmap_load_safetensors: pl_sd = safetensors.torch.load_file(checkpoint_file, device=device) else: pl_sd = safetensors.torch.load(open(checkpoint_file, 'rb').read()) pl_sd = {k: v.to(device) for k, v in pl_sd.items()} else: pl_sd = torch.load(checkpoint_file, map_location=map_location or shared.weight_load_location) if print_global_state and "global_step" in pl_sd: print(f"Global Step: {pl_sd['global_step']}") sd = get_state_dict_from_checkpoint(pl_sd) return sd def get_checkpoint_state_dict(checkpoint_info: CheckpointInfo, timer): sd_model_hash = checkpoint_info.calculate_shorthash() timer.record("calculate hash") if checkpoint_info in checkpoints_loaded: # use checkpoint cache print(f"Loading weights [{sd_model_hash}] from cache") # move to end as latest checkpoints_loaded.move_to_end(checkpoint_info) return checkpoints_loaded[checkpoint_info] print(f"Loading weights [{sd_model_hash}] from {checkpoint_info.filename}") res = read_state_dict(checkpoint_info.filename) timer.record("load weights from disk") return res class SkipWritingToConfig: skip = False previous = None def __enter__(self): self.previous = SkipWritingToConfig.skip SkipWritingToConfig.skip = True return self def __exit__(self, exc_type, exc_value, exc_traceback): SkipWritingToConfig.skip = self.previous def check_fp8(model): if model is None: return None if devices.get_optimal_device_name() == "mps": enable_fp8 = False elif shared.opts.fp8_storage == "Enable": enable_fp8 = True elif getattr(model, "is_sdxl", False) and shared.opts.fp8_storage == "Enable for SDXL": enable_fp8 = True else: enable_fp8 = False return enable_fp8 def set_model_type(model, state_dict): model.is_sd1 = False model.is_sd2 = False model.is_sdxl = False model.is_ssd = False model.is_sd3 = False if "model.diffusion_model.x_embedder.proj.weight" in state_dict: model.is_sd3 = True model.model_type = ModelType.SD3 elif hasattr(model, 'conditioner'): model.is_sdxl = True if 'model.diffusion_model.middle_block.1.transformer_blocks.0.attn1.to_q.weight' not in state_dict.keys(): model.is_ssd = True model.model_type = ModelType.SSD else: model.model_type = ModelType.SDXL elif hasattr(model.cond_stage_model, 'model'): model.is_sd2 = True model.model_type = ModelType.SD2 else: model.is_sd1 = True model.model_type = ModelType.SD1 def set_model_fields(model): if not hasattr(model, 'latent_channels'): model.latent_channels = 4 def load_model_weights(model, checkpoint_info: CheckpointInfo, state_dict, timer): sd_model_hash = checkpoint_info.calculate_shorthash() timer.record("calculate hash") if devices.fp8: # prevent model to load state dict in fp8 model.half() if not SkipWritingToConfig.skip: shared.opts.data["sd_model_checkpoint"] = checkpoint_info.title if state_dict is None: state_dict = get_checkpoint_state_dict(checkpoint_info, timer) set_model_type(model, state_dict) set_model_fields(model) if model.is_sdxl: sd_models_xl.extend_sdxl(model) if model.is_ssd: sd_hijack.model_hijack.convert_sdxl_to_ssd(model) if shared.opts.sd_checkpoint_cache > 0: # cache newly loaded model checkpoints_loaded[checkpoint_info] = state_dict.copy() if hasattr(model, "before_load_weights"): model.before_load_weights(state_dict) model.load_state_dict(state_dict, strict=False) timer.record("apply weights to model") if hasattr(model, "after_load_weights"): model.after_load_weights(state_dict) del state_dict # Set is_sdxl_inpaint flag. # Checks Unet structure to detect inpaint model. The inpaint model's # checkpoint state_dict does not contain the key # 'diffusion_model.input_blocks.0.0.weight'. diffusion_model_input = model.model.state_dict().get( 'diffusion_model.input_blocks.0.0.weight' ) model.is_sdxl_inpaint = ( model.is_sdxl and diffusion_model_input is not None and diffusion_model_input.shape[1] == 9 ) if shared.cmd_opts.opt_channelslast: model.to(memory_format=torch.channels_last) timer.record("apply channels_last") if shared.cmd_opts.no_half: model.float() model.alphas_cumprod_original = model.alphas_cumprod devices.dtype_unet = torch.float32 assert shared.cmd_opts.precision != "half", "Cannot use --precision half with --no-half" timer.record("apply float()") else: vae = model.first_stage_model depth_model = getattr(model, 'depth_model', None) # with --no-half-vae, remove VAE from model when doing half() to prevent its weights from being converted to float16 if shared.cmd_opts.no_half_vae: model.first_stage_model = None # with --upcast-sampling, don't convert the depth model weights to float16 if shared.cmd_opts.upcast_sampling and depth_model: model.depth_model = None alphas_cumprod = model.alphas_cumprod model.alphas_cumprod = None model.half() model.alphas_cumprod = alphas_cumprod model.alphas_cumprod_original = alphas_cumprod model.first_stage_model = vae if depth_model: model.depth_model = depth_model devices.dtype_unet = torch.float16 timer.record("apply half()") apply_alpha_schedule_override(model) for module in model.modules(): if hasattr(module, 'fp16_weight'): del module.fp16_weight if hasattr(module, 'fp16_bias'): del module.fp16_bias if check_fp8(model): devices.fp8 = True first_stage = model.first_stage_model model.first_stage_model = None for module in model.modules(): if isinstance(module, (torch.nn.Conv2d, torch.nn.Linear)): if shared.opts.cache_fp16_weight: module.fp16_weight = module.weight.data.clone().cpu().half() if module.bias is not None: module.fp16_bias = module.bias.data.clone().cpu().half() module.to(torch.float8_e4m3fn) model.first_stage_model = first_stage timer.record("apply fp8") else: devices.fp8 = False devices.unet_needs_upcast = shared.cmd_opts.upcast_sampling and devices.dtype == torch.float16 and devices.dtype_unet == torch.float16 model.first_stage_model.to(devices.dtype_vae) timer.record("apply dtype to VAE") # clean up cache if limit is reached while len(checkpoints_loaded) > shared.opts.sd_checkpoint_cache: checkpoints_loaded.popitem(last=False) model.sd_model_hash = sd_model_hash model.sd_model_checkpoint = checkpoint_info.filename model.sd_checkpoint_info = checkpoint_info shared.opts.data["sd_checkpoint_hash"] = checkpoint_info.sha256 if hasattr(model, 'logvar'): model.logvar = model.logvar.to(devices.device) # fix for training sd_vae.delete_base_vae() sd_vae.clear_loaded_vae() vae_file, vae_source = sd_vae.resolve_vae(checkpoint_info.filename).tuple() sd_vae.load_vae(model, vae_file, vae_source) timer.record("load VAE") def enable_midas_autodownload(): midas_path = os.path.join(paths.models_path, 'midas') # stable-diffusion-stability-ai hard-codes the midas model path to # a location that differs from where other scripts using this model look. # HACK: Overriding the path here. for k, v in midas.api.ISL_PATHS.items(): file_name = os.path.basename(v) midas.api.ISL_PATHS[k] = os.path.join(midas_path, file_name) midas_urls = { "dpt_large": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", "dpt_hybrid": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid-midas-501f0c75.pt", "midas_v21": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21-f6b98070.pt", "midas_v21_small": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21_small-70d6b9c8.pt", } midas.api.load_model_inner = midas.api.load_model def load_model_wrapper(model_type): path = midas.api.ISL_PATHS[model_type] if not os.path.exists(path): if not os.path.exists(midas_path): os.mkdir(midas_path) print(f"Downloading midas model weights for {model_type} to {path}") request.urlretrieve(midas_urls[model_type], path) print(f"{model_type} downloaded") return midas.api.load_model_inner(model_type) midas.api.load_model = load_model_wrapper def patch_given_betas(): import ldm.models.diffusion.ddpm def patched_register_schedule(*args, **kwargs): if isinstance(args[1], ListConfig): args = (args[0], np.array(args[1]), *args[2:]) original_register_schedule(*args, **kwargs) original_register_schedule = patches.patch(__name__, ldm.models.diffusion.ddpm.DDPM, 'register_schedule', patched_register_schedule) def repair_config(sd_config, state_dict=None): if not hasattr(sd_config.model.params, "use_ema"): sd_config.model.params.use_ema = False if hasattr(sd_config.model.params, 'unet_config'): if shared.cmd_opts.no_half: sd_config.model.params.unet_config.params.use_fp16 = False elif shared.cmd_opts.upcast_sampling or shared.cmd_opts.precision == "half": sd_config.model.params.unet_config.params.use_fp16 = True if hasattr(sd_config.model.params, 'first_stage_config'): if getattr(sd_config.model.params.first_stage_config.params.ddconfig, "attn_type", None) == "vanilla-xformers" and not shared.xformers_available: sd_config.model.params.first_stage_config.params.ddconfig.attn_type = "vanilla" # For UnCLIP-L, override the hardcoded karlo directory if hasattr(sd_config.model.params, "noise_aug_config") and hasattr(sd_config.model.params.noise_aug_config.params, "clip_stats_path"): karlo_path = os.path.join(paths.models_path, 'karlo') sd_config.model.params.noise_aug_config.params.clip_stats_path = sd_config.model.params.noise_aug_config.params.clip_stats_path.replace("checkpoints/karlo_models", karlo_path) # Do not use checkpoint for inference. # This helps prevent extra performance overhead on checking parameters. # The perf overhead is about 100ms/it on 4090 for SDXL. if hasattr(sd_config.model.params, "network_config"): sd_config.model.params.network_config.params.use_checkpoint = False if hasattr(sd_config.model.params, "unet_config"): sd_config.model.params.unet_config.params.use_checkpoint = False def rescale_zero_terminal_snr_abar(alphas_cumprod): alphas_bar_sqrt = alphas_cumprod.sqrt() # Store old values. alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone() alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone() # Shift so the last timestep is zero. alphas_bar_sqrt -= (alphas_bar_sqrt_T) # Scale so the first timestep is back to the old value. alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T) # Convert alphas_bar_sqrt to betas alphas_bar = alphas_bar_sqrt ** 2 # Revert sqrt alphas_bar[-1] = 4.8973451890853435e-08 return alphas_bar def apply_alpha_schedule_override(sd_model, p=None): if not hasattr(sd_model, 'alphas_cumprod') or not hasattr(sd_model, 'alphas_cumprod_original'): return sd_model.alphas_cumprod = sd_model.alphas_cumprod_original.to(shared.device) if opts.use_downcasted_alpha_bar: if p is not None: p.extra_generation_params['Downcast alphas_cumprod'] = opts.use_downcasted_alpha_bar sd_model.alphas_cumprod = sd_model.alphas_cumprod.half().to(shared.device) if opts.sd_noise_schedule == "Zero Terminal SNR": if p is not None: p.extra_generation_params['Noise Schedule'] = opts.sd_noise_schedule sd_model.alphas_cumprod = rescale_zero_terminal_snr_abar(sd_model.alphas_cumprod).to(shared.device) sd1_clip_weight = 'cond_stage_model.transformer.text_model.embeddings.token_embedding.weight' sd2_clip_weight = 'cond_stage_model.model.transformer.resblocks.0.attn.in_proj_weight' sdxl_clip_weight = 'conditioner.embedders.1.model.ln_final.weight' sdxl_refiner_clip_weight = 'conditioner.embedders.0.model.ln_final.weight' class SdModelData: def __init__(self): self.sd_model = None self.loaded_sd_models = [] self.was_loaded_at_least_once = False self.lock = threading.Lock() def get_sd_model(self): if self.was_loaded_at_least_once: return self.sd_model if self.sd_model is None: with self.lock: if self.sd_model is not None or self.was_loaded_at_least_once: return self.sd_model try: load_model() except Exception as e: errors.display(e, "loading stable diffusion model", full_traceback=True) print("", file=sys.stderr) print("Stable diffusion model failed to load", file=sys.stderr) self.sd_model = None return self.sd_model def set_sd_model(self, v, already_loaded=False): self.sd_model = v if already_loaded: sd_vae.base_vae = getattr(v, "base_vae", None) sd_vae.loaded_vae_file = getattr(v, "loaded_vae_file", None) sd_vae.checkpoint_info = v.sd_checkpoint_info try: self.loaded_sd_models.remove(v) except ValueError: pass if v is not None: self.loaded_sd_models.insert(0, v) model_data = SdModelData() def get_empty_cond(sd_model): p = processing.StableDiffusionProcessingTxt2Img() extra_networks.activate(p, {}) if hasattr(sd_model, 'get_learned_conditioning'): d = sd_model.get_learned_conditioning([""]) else: d = sd_model.cond_stage_model([""]) if isinstance(d, dict): d = d['crossattn'] return d def send_model_to_cpu(m): if m is not None: if m.lowvram: lowvram.send_everything_to_cpu() else: m.to(devices.cpu) devices.torch_gc() def model_target_device(m): if lowvram.is_needed(m): return devices.cpu else: return devices.device def send_model_to_device(m): lowvram.apply(m) if not m.lowvram: m.to(shared.device) def send_model_to_trash(m): m.to(device="meta") devices.torch_gc() def instantiate_from_config(config, state_dict=None): constructor = get_obj_from_str(config["target"]) params = {**config.get("params", {})} if state_dict and "state_dict" in params and params["state_dict"] is None: params["state_dict"] = state_dict return constructor(**params) def get_obj_from_str(string, reload=False): module, cls = string.rsplit(".", 1) if reload: module_imp = importlib.import_module(module) importlib.reload(module_imp) return getattr(importlib.import_module(module, package=None), cls) def load_model(checkpoint_info=None, already_loaded_state_dict=None): from modules import sd_hijack checkpoint_info = checkpoint_info or select_checkpoint() timer = Timer() if model_data.sd_model: send_model_to_trash(model_data.sd_model) model_data.sd_model = None devices.torch_gc() timer.record("unload existing model") if already_loaded_state_dict is not None: state_dict = already_loaded_state_dict else: state_dict = get_checkpoint_state_dict(checkpoint_info, timer) checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info) clip_is_included_into_sd = any(x for x in [sd1_clip_weight, sd2_clip_weight, sdxl_clip_weight, sdxl_refiner_clip_weight] if x in state_dict) timer.record("find config") sd_config = OmegaConf.load(checkpoint_config) repair_config(sd_config, state_dict) timer.record("load config") print(f"Creating model from config: {checkpoint_config}") sd_model = None try: with sd_disable_initialization.DisableInitialization(disable_clip=clip_is_included_into_sd or shared.cmd_opts.do_not_download_clip): with sd_disable_initialization.InitializeOnMeta(): sd_model = instantiate_from_config(sd_config.model, state_dict) except Exception as e: errors.display(e, "creating model quickly", full_traceback=True) if sd_model is None: print('Failed to create model quickly; will retry using slow method.', file=sys.stderr) with sd_disable_initialization.InitializeOnMeta(): sd_model = instantiate_from_config(sd_config.model, state_dict) sd_model.used_config = checkpoint_config timer.record("create model") if shared.cmd_opts.no_half: weight_dtype_conversion = None else: weight_dtype_conversion = { 'first_stage_model': None, 'alphas_cumprod': None, '': torch.float16, } with sd_disable_initialization.LoadStateDictOnMeta(state_dict, device=model_target_device(sd_model), weight_dtype_conversion=weight_dtype_conversion): load_model_weights(sd_model, checkpoint_info, state_dict, timer) timer.record("load weights from state dict") send_model_to_device(sd_model) timer.record("move model to device") sd_hijack.model_hijack.hijack(sd_model) timer.record("hijack") sd_model.eval() model_data.set_sd_model(sd_model) model_data.was_loaded_at_least_once = True sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings(force_reload=True) # Reload embeddings after model load as they may or may not fit the model timer.record("load textual inversion embeddings") script_callbacks.model_loaded_callback(sd_model) timer.record("scripts callbacks") with devices.autocast(), torch.no_grad(): sd_model.cond_stage_model_empty_prompt = get_empty_cond(sd_model) timer.record("calculate empty prompt") print(f"Model loaded in {timer.summary()}.") return sd_model def reuse_model_from_already_loaded(sd_model, checkpoint_info, timer): if sd_model is not None and sd_model.sd_checkpoint_info.filename == checkpoint_info.filename: return sd_model if shared.opts.sd_checkpoints_keep_in_cpu: send_model_to_cpu(sd_model) timer.record("send model to cpu") already_loaded = None for i in reversed(range(len(model_data.loaded_sd_models))): loaded_model = model_data.loaded_sd_models[i] if loaded_model.sd_checkpoint_info.filename == checkpoint_info.filename: already_loaded = loaded_model continue if len(model_data.loaded_sd_models) > shared.opts.sd_checkpoints_limit > 0: print(f"Unloading model {len(model_data.loaded_sd_models)} over the limit of {shared.opts.sd_checkpoints_limit}: {loaded_model.sd_checkpoint_info.title}") del model_data.loaded_sd_models[i] send_model_to_trash(loaded_model) timer.record("send model to trash") if already_loaded is not None: send_model_to_device(already_loaded) timer.record("send model to device") model_data.set_sd_model(already_loaded, already_loaded=True) if not SkipWritingToConfig.skip: shared.opts.data["sd_model_checkpoint"] = already_loaded.sd_checkpoint_info.title shared.opts.data["sd_checkpoint_hash"] = already_loaded.sd_checkpoint_info.sha256 print(f"Using already loaded model {already_loaded.sd_checkpoint_info.title}: done in {timer.summary()}") sd_vae.reload_vae_weights(already_loaded) return model_data.sd_model elif shared.opts.sd_checkpoints_limit > 1 and len(model_data.loaded_sd_models) < shared.opts.sd_checkpoints_limit: print(f"Loading model {checkpoint_info.title} ({len(model_data.loaded_sd_models) + 1} out of {shared.opts.sd_checkpoints_limit})") model_data.sd_model = None load_model(checkpoint_info) return model_data.sd_model elif len(model_data.loaded_sd_models) > 0: sd_model = model_data.loaded_sd_models.pop() model_data.sd_model = sd_model sd_vae.base_vae = getattr(sd_model, "base_vae", None) sd_vae.loaded_vae_file = getattr(sd_model, "loaded_vae_file", None) sd_vae.checkpoint_info = sd_model.sd_checkpoint_info print(f"Reusing loaded model {sd_model.sd_checkpoint_info.title} to load {checkpoint_info.title}") return sd_model else: return None def reload_model_weights(sd_model=None, info=None, forced_reload=False): checkpoint_info = info or select_checkpoint() timer = Timer() if not sd_model: sd_model = model_data.sd_model if sd_model is None: # previous model load failed current_checkpoint_info = None else: current_checkpoint_info = sd_model.sd_checkpoint_info if check_fp8(sd_model) != devices.fp8: # load from state dict again to prevent extra numerical errors forced_reload = True elif sd_model.sd_model_checkpoint == checkpoint_info.filename and not forced_reload: return sd_model sd_model = reuse_model_from_already_loaded(sd_model, checkpoint_info, timer) if not forced_reload and sd_model is not None and sd_model.sd_checkpoint_info.filename == checkpoint_info.filename: return sd_model if sd_model is not None: sd_unet.apply_unet("None") send_model_to_cpu(sd_model) sd_hijack.model_hijack.undo_hijack(sd_model) state_dict = get_checkpoint_state_dict(checkpoint_info, timer) checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info) timer.record("find config") if sd_model is None or checkpoint_config != sd_model.used_config: if sd_model is not None: send_model_to_trash(sd_model) load_model(checkpoint_info, already_loaded_state_dict=state_dict) return model_data.sd_model try: load_model_weights(sd_model, checkpoint_info, state_dict, timer) except Exception: print("Failed to load checkpoint, restoring previous") load_model_weights(sd_model, current_checkpoint_info, None, timer) raise finally: sd_hijack.model_hijack.hijack(sd_model) timer.record("hijack") if not sd_model.lowvram: sd_model.to(devices.device) timer.record("move model to device") script_callbacks.model_loaded_callback(sd_model) timer.record("script callbacks") print(f"Weights loaded in {timer.summary()}.") model_data.set_sd_model(sd_model) sd_unet.apply_unet() return sd_model def unload_model_weights(sd_model=None, info=None): send_model_to_cpu(sd_model or shared.sd_model) return sd_model def apply_token_merging(sd_model, token_merging_ratio): current_token_merging_ratio = getattr(sd_model, 'applied_token_merged_ratio', 0) if current_token_merging_ratio == token_merging_ratio: return if current_token_merging_ratio > 0: tomesd.remove_patch(sd_model) if token_merging_ratio > 0: tomesd.apply_patch( sd_model, ratio=token_merging_ratio, use_rand=False, # can cause issues with some samplers merge_attn=True, merge_crossattn=False, merge_mlp=False ) sd_model.applied_token_merged_ratio = token_merging_ratio
--- +++ @@ -1,1006 +1,1034 @@-import collections -import importlib -import os -import sys -import threading -import enum - -import torch -import re -import safetensors.torch -from omegaconf import OmegaConf, ListConfig -from urllib import request -import ldm.modules.midas as midas - -from modules import paths, shared, modelloader, devices, script_callbacks, sd_vae, sd_disable_initialization, errors, hashes, sd_models_config, sd_unet, sd_models_xl, cache, extra_networks, processing, lowvram, sd_hijack, patches -from modules.timer import Timer -from modules.shared import opts -import tomesd -import numpy as np - -model_dir = "Stable-diffusion" -model_path = os.path.abspath(os.path.join(paths.models_path, model_dir)) - -checkpoints_list = {} -checkpoint_aliases = {} -checkpoint_alisases = checkpoint_aliases # for compatibility with old name -checkpoints_loaded = collections.OrderedDict() - - -class ModelType(enum.Enum): - SD1 = 1 - SD2 = 2 - SDXL = 3 - SSD = 4 - SD3 = 5 - - -def replace_key(d, key, new_key, value): - keys = list(d.keys()) - - d[new_key] = value - - if key not in keys: - return d - - index = keys.index(key) - keys[index] = new_key - - new_d = {k: d[k] for k in keys} - - d.clear() - d.update(new_d) - return d - - -class CheckpointInfo: - def __init__(self, filename): - self.filename = filename - abspath = os.path.abspath(filename) - abs_ckpt_dir = os.path.abspath(shared.cmd_opts.ckpt_dir) if shared.cmd_opts.ckpt_dir is not None else None - - self.is_safetensors = os.path.splitext(filename)[1].lower() == ".safetensors" - - if abs_ckpt_dir and abspath.startswith(abs_ckpt_dir): - name = abspath.replace(abs_ckpt_dir, '') - elif abspath.startswith(model_path): - name = abspath.replace(model_path, '') - else: - name = os.path.basename(filename) - - if name.startswith("\\") or name.startswith("/"): - name = name[1:] - - def read_metadata(): - metadata = read_metadata_from_safetensors(filename) - self.modelspec_thumbnail = metadata.pop('modelspec.thumbnail', None) - - return metadata - - self.metadata = {} - if self.is_safetensors: - try: - self.metadata = cache.cached_data_for_file('safetensors-metadata', "checkpoint/" + name, filename, read_metadata) - except Exception as e: - errors.display(e, f"reading metadata for {filename}") - - self.name = name - self.name_for_extra = os.path.splitext(os.path.basename(filename))[0] - self.model_name = os.path.splitext(name.replace("/", "_").replace("\\", "_"))[0] - self.hash = model_hash(filename) - - self.sha256 = hashes.sha256_from_cache(self.filename, f"checkpoint/{name}") - self.shorthash = self.sha256[0:10] if self.sha256 else None - - self.title = name if self.shorthash is None else f'{name} [{self.shorthash}]' - self.short_title = self.name_for_extra if self.shorthash is None else f'{self.name_for_extra} [{self.shorthash}]' - - self.ids = [self.hash, self.model_name, self.title, name, self.name_for_extra, f'{name} [{self.hash}]'] - if self.shorthash: - self.ids += [self.shorthash, self.sha256, f'{self.name} [{self.shorthash}]', f'{self.name_for_extra} [{self.shorthash}]'] - - def register(self): - checkpoints_list[self.title] = self - for id in self.ids: - checkpoint_aliases[id] = self - - def calculate_shorthash(self): - self.sha256 = hashes.sha256(self.filename, f"checkpoint/{self.name}") - if self.sha256 is None: - return - - shorthash = self.sha256[0:10] - if self.shorthash == self.sha256[0:10]: - return self.shorthash - - self.shorthash = shorthash - - if self.shorthash not in self.ids: - self.ids += [self.shorthash, self.sha256, f'{self.name} [{self.shorthash}]', f'{self.name_for_extra} [{self.shorthash}]'] - - old_title = self.title - self.title = f'{self.name} [{self.shorthash}]' - self.short_title = f'{self.name_for_extra} [{self.shorthash}]' - - replace_key(checkpoints_list, old_title, self.title, self) - self.register() - - return self.shorthash - - -try: - # this silences the annoying "Some weights of the model checkpoint were not used when initializing..." message at start. - from transformers import logging, CLIPModel # noqa: F401 - - logging.set_verbosity_error() -except Exception: - pass - - -def setup_model(): - - os.makedirs(model_path, exist_ok=True) - - enable_midas_autodownload() - patch_given_betas() - - -def checkpoint_tiles(use_short=False): - return [x.short_title if use_short else x.title for x in checkpoints_list.values()] - - -def list_models(): - checkpoints_list.clear() - checkpoint_aliases.clear() - - cmd_ckpt = shared.cmd_opts.ckpt - if shared.cmd_opts.no_download_sd_model or cmd_ckpt != shared.sd_model_file or os.path.exists(cmd_ckpt): - model_url = None - expected_sha256 = None - else: - model_url = f"{shared.hf_endpoint}/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.safetensors" - expected_sha256 = '6ce0161689b3853acaa03779ec93eafe75a02f4ced659bee03f50797806fa2fa' - - model_list = modelloader.load_models(model_path=model_path, model_url=model_url, command_path=shared.cmd_opts.ckpt_dir, ext_filter=[".ckpt", ".safetensors"], download_name="v1-5-pruned-emaonly.safetensors", ext_blacklist=[".vae.ckpt", ".vae.safetensors"], hash_prefix=expected_sha256) - - if os.path.exists(cmd_ckpt): - checkpoint_info = CheckpointInfo(cmd_ckpt) - checkpoint_info.register() - - shared.opts.data['sd_model_checkpoint'] = checkpoint_info.title - elif cmd_ckpt is not None and cmd_ckpt != shared.default_sd_model_file: - print(f"Checkpoint in --ckpt argument not found (Possible it was moved to {model_path}: {cmd_ckpt}", file=sys.stderr) - - for filename in model_list: - checkpoint_info = CheckpointInfo(filename) - checkpoint_info.register() - - -re_strip_checksum = re.compile(r"\s*\[[^]]+]\s*$") - - -def get_closet_checkpoint_match(search_string): - if not search_string: - return None - - checkpoint_info = checkpoint_aliases.get(search_string, None) - if checkpoint_info is not None: - return checkpoint_info - - found = sorted([info for info in checkpoints_list.values() if search_string in info.title], key=lambda x: len(x.title)) - if found: - return found[0] - - search_string_without_checksum = re.sub(re_strip_checksum, '', search_string) - found = sorted([info for info in checkpoints_list.values() if search_string_without_checksum in info.title], key=lambda x: len(x.title)) - if found: - return found[0] - - return None - - -def model_hash(filename): - - try: - with open(filename, "rb") as file: - import hashlib - m = hashlib.sha256() - - file.seek(0x100000) - m.update(file.read(0x10000)) - return m.hexdigest()[0:8] - except FileNotFoundError: - return 'NOFILE' - - -def select_checkpoint(): - model_checkpoint = shared.opts.sd_model_checkpoint - - checkpoint_info = checkpoint_aliases.get(model_checkpoint, None) - if checkpoint_info is not None: - return checkpoint_info - - if len(checkpoints_list) == 0: - error_message = "No checkpoints found. When searching for checkpoints, looked at:" - if shared.cmd_opts.ckpt is not None: - error_message += f"\n - file {os.path.abspath(shared.cmd_opts.ckpt)}" - error_message += f"\n - directory {model_path}" - if shared.cmd_opts.ckpt_dir is not None: - error_message += f"\n - directory {os.path.abspath(shared.cmd_opts.ckpt_dir)}" - error_message += "Can't run without a checkpoint. Find and place a .ckpt or .safetensors file into any of those locations." - raise FileNotFoundError(error_message) - - checkpoint_info = next(iter(checkpoints_list.values())) - if model_checkpoint is not None: - print(f"Checkpoint {model_checkpoint} not found; loading fallback {checkpoint_info.title}", file=sys.stderr) - - return checkpoint_info - - -checkpoint_dict_replacements_sd1 = { - 'cond_stage_model.transformer.embeddings.': 'cond_stage_model.transformer.text_model.embeddings.', - 'cond_stage_model.transformer.encoder.': 'cond_stage_model.transformer.text_model.encoder.', - 'cond_stage_model.transformer.final_layer_norm.': 'cond_stage_model.transformer.text_model.final_layer_norm.', -} - -checkpoint_dict_replacements_sd2_turbo = { # Converts SD 2.1 Turbo from SGM to LDM format. - 'conditioner.embedders.0.': 'cond_stage_model.', -} - - -def transform_checkpoint_dict_key(k, replacements): - for text, replacement in replacements.items(): - if k.startswith(text): - k = replacement + k[len(text):] - - return k - - -def get_state_dict_from_checkpoint(pl_sd): - pl_sd = pl_sd.pop("state_dict", pl_sd) - pl_sd.pop("state_dict", None) - - is_sd2_turbo = 'conditioner.embedders.0.model.ln_final.weight' in pl_sd and pl_sd['conditioner.embedders.0.model.ln_final.weight'].size()[0] == 1024 - - sd = {} - for k, v in pl_sd.items(): - if is_sd2_turbo: - new_key = transform_checkpoint_dict_key(k, checkpoint_dict_replacements_sd2_turbo) - else: - new_key = transform_checkpoint_dict_key(k, checkpoint_dict_replacements_sd1) - - if new_key is not None: - sd[new_key] = v - - pl_sd.clear() - pl_sd.update(sd) - - return pl_sd - - -def read_metadata_from_safetensors(filename): - import json - - with open(filename, mode="rb") as file: - metadata_len = file.read(8) - metadata_len = int.from_bytes(metadata_len, "little") - json_start = file.read(2) - - assert metadata_len > 2 and json_start in (b'{"', b"{'"), f"{filename} is not a safetensors file" - - res = {} - - try: - json_data = json_start + file.read(metadata_len-2) - json_obj = json.loads(json_data) - for k, v in json_obj.get("__metadata__", {}).items(): - res[k] = v - if isinstance(v, str) and v[0:1] == '{': - try: - res[k] = json.loads(v) - except Exception: - pass - except Exception: - errors.report(f"Error reading metadata from file: {filename}", exc_info=True) - - return res - - -def read_state_dict(checkpoint_file, print_global_state=False, map_location=None): - _, extension = os.path.splitext(checkpoint_file) - if extension.lower() == ".safetensors": - device = map_location or shared.weight_load_location or devices.get_optimal_device_name() - - if not shared.opts.disable_mmap_load_safetensors: - pl_sd = safetensors.torch.load_file(checkpoint_file, device=device) - else: - pl_sd = safetensors.torch.load(open(checkpoint_file, 'rb').read()) - pl_sd = {k: v.to(device) for k, v in pl_sd.items()} - else: - pl_sd = torch.load(checkpoint_file, map_location=map_location or shared.weight_load_location) - - if print_global_state and "global_step" in pl_sd: - print(f"Global Step: {pl_sd['global_step']}") - - sd = get_state_dict_from_checkpoint(pl_sd) - return sd - - -def get_checkpoint_state_dict(checkpoint_info: CheckpointInfo, timer): - sd_model_hash = checkpoint_info.calculate_shorthash() - timer.record("calculate hash") - - if checkpoint_info in checkpoints_loaded: - # use checkpoint cache - print(f"Loading weights [{sd_model_hash}] from cache") - # move to end as latest - checkpoints_loaded.move_to_end(checkpoint_info) - return checkpoints_loaded[checkpoint_info] - - print(f"Loading weights [{sd_model_hash}] from {checkpoint_info.filename}") - res = read_state_dict(checkpoint_info.filename) - timer.record("load weights from disk") - - return res - - -class SkipWritingToConfig: - - skip = False - previous = None - - def __enter__(self): - self.previous = SkipWritingToConfig.skip - SkipWritingToConfig.skip = True - return self - - def __exit__(self, exc_type, exc_value, exc_traceback): - SkipWritingToConfig.skip = self.previous - - -def check_fp8(model): - if model is None: - return None - if devices.get_optimal_device_name() == "mps": - enable_fp8 = False - elif shared.opts.fp8_storage == "Enable": - enable_fp8 = True - elif getattr(model, "is_sdxl", False) and shared.opts.fp8_storage == "Enable for SDXL": - enable_fp8 = True - else: - enable_fp8 = False - return enable_fp8 - - -def set_model_type(model, state_dict): - model.is_sd1 = False - model.is_sd2 = False - model.is_sdxl = False - model.is_ssd = False - model.is_sd3 = False - - if "model.diffusion_model.x_embedder.proj.weight" in state_dict: - model.is_sd3 = True - model.model_type = ModelType.SD3 - elif hasattr(model, 'conditioner'): - model.is_sdxl = True - - if 'model.diffusion_model.middle_block.1.transformer_blocks.0.attn1.to_q.weight' not in state_dict.keys(): - model.is_ssd = True - model.model_type = ModelType.SSD - else: - model.model_type = ModelType.SDXL - elif hasattr(model.cond_stage_model, 'model'): - model.is_sd2 = True - model.model_type = ModelType.SD2 - else: - model.is_sd1 = True - model.model_type = ModelType.SD1 - - -def set_model_fields(model): - if not hasattr(model, 'latent_channels'): - model.latent_channels = 4 - - -def load_model_weights(model, checkpoint_info: CheckpointInfo, state_dict, timer): - sd_model_hash = checkpoint_info.calculate_shorthash() - timer.record("calculate hash") - - if devices.fp8: - # prevent model to load state dict in fp8 - model.half() - - if not SkipWritingToConfig.skip: - shared.opts.data["sd_model_checkpoint"] = checkpoint_info.title - - if state_dict is None: - state_dict = get_checkpoint_state_dict(checkpoint_info, timer) - - set_model_type(model, state_dict) - set_model_fields(model) - - if model.is_sdxl: - sd_models_xl.extend_sdxl(model) - - if model.is_ssd: - sd_hijack.model_hijack.convert_sdxl_to_ssd(model) - - if shared.opts.sd_checkpoint_cache > 0: - # cache newly loaded model - checkpoints_loaded[checkpoint_info] = state_dict.copy() - - if hasattr(model, "before_load_weights"): - model.before_load_weights(state_dict) - - model.load_state_dict(state_dict, strict=False) - timer.record("apply weights to model") - - if hasattr(model, "after_load_weights"): - model.after_load_weights(state_dict) - - del state_dict - - # Set is_sdxl_inpaint flag. - # Checks Unet structure to detect inpaint model. The inpaint model's - # checkpoint state_dict does not contain the key - # 'diffusion_model.input_blocks.0.0.weight'. - diffusion_model_input = model.model.state_dict().get( - 'diffusion_model.input_blocks.0.0.weight' - ) - model.is_sdxl_inpaint = ( - model.is_sdxl and - diffusion_model_input is not None and - diffusion_model_input.shape[1] == 9 - ) - - if shared.cmd_opts.opt_channelslast: - model.to(memory_format=torch.channels_last) - timer.record("apply channels_last") - - if shared.cmd_opts.no_half: - model.float() - model.alphas_cumprod_original = model.alphas_cumprod - devices.dtype_unet = torch.float32 - assert shared.cmd_opts.precision != "half", "Cannot use --precision half with --no-half" - timer.record("apply float()") - else: - vae = model.first_stage_model - depth_model = getattr(model, 'depth_model', None) - - # with --no-half-vae, remove VAE from model when doing half() to prevent its weights from being converted to float16 - if shared.cmd_opts.no_half_vae: - model.first_stage_model = None - # with --upcast-sampling, don't convert the depth model weights to float16 - if shared.cmd_opts.upcast_sampling and depth_model: - model.depth_model = None - - alphas_cumprod = model.alphas_cumprod - model.alphas_cumprod = None - model.half() - model.alphas_cumprod = alphas_cumprod - model.alphas_cumprod_original = alphas_cumprod - model.first_stage_model = vae - if depth_model: - model.depth_model = depth_model - - devices.dtype_unet = torch.float16 - timer.record("apply half()") - - apply_alpha_schedule_override(model) - - for module in model.modules(): - if hasattr(module, 'fp16_weight'): - del module.fp16_weight - if hasattr(module, 'fp16_bias'): - del module.fp16_bias - - if check_fp8(model): - devices.fp8 = True - first_stage = model.first_stage_model - model.first_stage_model = None - for module in model.modules(): - if isinstance(module, (torch.nn.Conv2d, torch.nn.Linear)): - if shared.opts.cache_fp16_weight: - module.fp16_weight = module.weight.data.clone().cpu().half() - if module.bias is not None: - module.fp16_bias = module.bias.data.clone().cpu().half() - module.to(torch.float8_e4m3fn) - model.first_stage_model = first_stage - timer.record("apply fp8") - else: - devices.fp8 = False - - devices.unet_needs_upcast = shared.cmd_opts.upcast_sampling and devices.dtype == torch.float16 and devices.dtype_unet == torch.float16 - - model.first_stage_model.to(devices.dtype_vae) - timer.record("apply dtype to VAE") - - # clean up cache if limit is reached - while len(checkpoints_loaded) > shared.opts.sd_checkpoint_cache: - checkpoints_loaded.popitem(last=False) - - model.sd_model_hash = sd_model_hash - model.sd_model_checkpoint = checkpoint_info.filename - model.sd_checkpoint_info = checkpoint_info - shared.opts.data["sd_checkpoint_hash"] = checkpoint_info.sha256 - - if hasattr(model, 'logvar'): - model.logvar = model.logvar.to(devices.device) # fix for training - - sd_vae.delete_base_vae() - sd_vae.clear_loaded_vae() - vae_file, vae_source = sd_vae.resolve_vae(checkpoint_info.filename).tuple() - sd_vae.load_vae(model, vae_file, vae_source) - timer.record("load VAE") - - -def enable_midas_autodownload(): - - midas_path = os.path.join(paths.models_path, 'midas') - - # stable-diffusion-stability-ai hard-codes the midas model path to - # a location that differs from where other scripts using this model look. - # HACK: Overriding the path here. - for k, v in midas.api.ISL_PATHS.items(): - file_name = os.path.basename(v) - midas.api.ISL_PATHS[k] = os.path.join(midas_path, file_name) - - midas_urls = { - "dpt_large": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", - "dpt_hybrid": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid-midas-501f0c75.pt", - "midas_v21": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21-f6b98070.pt", - "midas_v21_small": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21_small-70d6b9c8.pt", - } - - midas.api.load_model_inner = midas.api.load_model - - def load_model_wrapper(model_type): - path = midas.api.ISL_PATHS[model_type] - if not os.path.exists(path): - if not os.path.exists(midas_path): - os.mkdir(midas_path) - - print(f"Downloading midas model weights for {model_type} to {path}") - request.urlretrieve(midas_urls[model_type], path) - print(f"{model_type} downloaded") - - return midas.api.load_model_inner(model_type) - - midas.api.load_model = load_model_wrapper - - -def patch_given_betas(): - import ldm.models.diffusion.ddpm - - def patched_register_schedule(*args, **kwargs): - - if isinstance(args[1], ListConfig): - args = (args[0], np.array(args[1]), *args[2:]) - - original_register_schedule(*args, **kwargs) - - original_register_schedule = patches.patch(__name__, ldm.models.diffusion.ddpm.DDPM, 'register_schedule', patched_register_schedule) - - -def repair_config(sd_config, state_dict=None): - if not hasattr(sd_config.model.params, "use_ema"): - sd_config.model.params.use_ema = False - - if hasattr(sd_config.model.params, 'unet_config'): - if shared.cmd_opts.no_half: - sd_config.model.params.unet_config.params.use_fp16 = False - elif shared.cmd_opts.upcast_sampling or shared.cmd_opts.precision == "half": - sd_config.model.params.unet_config.params.use_fp16 = True - - if hasattr(sd_config.model.params, 'first_stage_config'): - if getattr(sd_config.model.params.first_stage_config.params.ddconfig, "attn_type", None) == "vanilla-xformers" and not shared.xformers_available: - sd_config.model.params.first_stage_config.params.ddconfig.attn_type = "vanilla" - - # For UnCLIP-L, override the hardcoded karlo directory - if hasattr(sd_config.model.params, "noise_aug_config") and hasattr(sd_config.model.params.noise_aug_config.params, "clip_stats_path"): - karlo_path = os.path.join(paths.models_path, 'karlo') - sd_config.model.params.noise_aug_config.params.clip_stats_path = sd_config.model.params.noise_aug_config.params.clip_stats_path.replace("checkpoints/karlo_models", karlo_path) - - # Do not use checkpoint for inference. - # This helps prevent extra performance overhead on checking parameters. - # The perf overhead is about 100ms/it on 4090 for SDXL. - if hasattr(sd_config.model.params, "network_config"): - sd_config.model.params.network_config.params.use_checkpoint = False - if hasattr(sd_config.model.params, "unet_config"): - sd_config.model.params.unet_config.params.use_checkpoint = False - - - -def rescale_zero_terminal_snr_abar(alphas_cumprod): - alphas_bar_sqrt = alphas_cumprod.sqrt() - - # Store old values. - alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone() - alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone() - - # Shift so the last timestep is zero. - alphas_bar_sqrt -= (alphas_bar_sqrt_T) - - # Scale so the first timestep is back to the old value. - alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T) - - # Convert alphas_bar_sqrt to betas - alphas_bar = alphas_bar_sqrt ** 2 # Revert sqrt - alphas_bar[-1] = 4.8973451890853435e-08 - return alphas_bar - - -def apply_alpha_schedule_override(sd_model, p=None): - - if not hasattr(sd_model, 'alphas_cumprod') or not hasattr(sd_model, 'alphas_cumprod_original'): - return - - sd_model.alphas_cumprod = sd_model.alphas_cumprod_original.to(shared.device) - - if opts.use_downcasted_alpha_bar: - if p is not None: - p.extra_generation_params['Downcast alphas_cumprod'] = opts.use_downcasted_alpha_bar - sd_model.alphas_cumprod = sd_model.alphas_cumprod.half().to(shared.device) - - if opts.sd_noise_schedule == "Zero Terminal SNR": - if p is not None: - p.extra_generation_params['Noise Schedule'] = opts.sd_noise_schedule - sd_model.alphas_cumprod = rescale_zero_terminal_snr_abar(sd_model.alphas_cumprod).to(shared.device) - - -sd1_clip_weight = 'cond_stage_model.transformer.text_model.embeddings.token_embedding.weight' -sd2_clip_weight = 'cond_stage_model.model.transformer.resblocks.0.attn.in_proj_weight' -sdxl_clip_weight = 'conditioner.embedders.1.model.ln_final.weight' -sdxl_refiner_clip_weight = 'conditioner.embedders.0.model.ln_final.weight' - - -class SdModelData: - def __init__(self): - self.sd_model = None - self.loaded_sd_models = [] - self.was_loaded_at_least_once = False - self.lock = threading.Lock() - - def get_sd_model(self): - if self.was_loaded_at_least_once: - return self.sd_model - - if self.sd_model is None: - with self.lock: - if self.sd_model is not None or self.was_loaded_at_least_once: - return self.sd_model - - try: - load_model() - - except Exception as e: - errors.display(e, "loading stable diffusion model", full_traceback=True) - print("", file=sys.stderr) - print("Stable diffusion model failed to load", file=sys.stderr) - self.sd_model = None - - return self.sd_model - - def set_sd_model(self, v, already_loaded=False): - self.sd_model = v - if already_loaded: - sd_vae.base_vae = getattr(v, "base_vae", None) - sd_vae.loaded_vae_file = getattr(v, "loaded_vae_file", None) - sd_vae.checkpoint_info = v.sd_checkpoint_info - - try: - self.loaded_sd_models.remove(v) - except ValueError: - pass - - if v is not None: - self.loaded_sd_models.insert(0, v) - - -model_data = SdModelData() - - -def get_empty_cond(sd_model): - - p = processing.StableDiffusionProcessingTxt2Img() - extra_networks.activate(p, {}) - - if hasattr(sd_model, 'get_learned_conditioning'): - d = sd_model.get_learned_conditioning([""]) - else: - d = sd_model.cond_stage_model([""]) - - if isinstance(d, dict): - d = d['crossattn'] - - return d - - -def send_model_to_cpu(m): - if m is not None: - if m.lowvram: - lowvram.send_everything_to_cpu() - else: - m.to(devices.cpu) - - devices.torch_gc() - - -def model_target_device(m): - if lowvram.is_needed(m): - return devices.cpu - else: - return devices.device - - -def send_model_to_device(m): - lowvram.apply(m) - - if not m.lowvram: - m.to(shared.device) - - -def send_model_to_trash(m): - m.to(device="meta") - devices.torch_gc() - - -def instantiate_from_config(config, state_dict=None): - constructor = get_obj_from_str(config["target"]) - - params = {**config.get("params", {})} - - if state_dict and "state_dict" in params and params["state_dict"] is None: - params["state_dict"] = state_dict - - return constructor(**params) - - -def get_obj_from_str(string, reload=False): - module, cls = string.rsplit(".", 1) - if reload: - module_imp = importlib.import_module(module) - importlib.reload(module_imp) - return getattr(importlib.import_module(module, package=None), cls) - - -def load_model(checkpoint_info=None, already_loaded_state_dict=None): - from modules import sd_hijack - checkpoint_info = checkpoint_info or select_checkpoint() - - timer = Timer() - - if model_data.sd_model: - send_model_to_trash(model_data.sd_model) - model_data.sd_model = None - devices.torch_gc() - - timer.record("unload existing model") - - if already_loaded_state_dict is not None: - state_dict = already_loaded_state_dict - else: - state_dict = get_checkpoint_state_dict(checkpoint_info, timer) - - checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info) - clip_is_included_into_sd = any(x for x in [sd1_clip_weight, sd2_clip_weight, sdxl_clip_weight, sdxl_refiner_clip_weight] if x in state_dict) - - timer.record("find config") - - sd_config = OmegaConf.load(checkpoint_config) - repair_config(sd_config, state_dict) - - timer.record("load config") - - print(f"Creating model from config: {checkpoint_config}") - - sd_model = None - try: - with sd_disable_initialization.DisableInitialization(disable_clip=clip_is_included_into_sd or shared.cmd_opts.do_not_download_clip): - with sd_disable_initialization.InitializeOnMeta(): - sd_model = instantiate_from_config(sd_config.model, state_dict) - - except Exception as e: - errors.display(e, "creating model quickly", full_traceback=True) - - if sd_model is None: - print('Failed to create model quickly; will retry using slow method.', file=sys.stderr) - - with sd_disable_initialization.InitializeOnMeta(): - sd_model = instantiate_from_config(sd_config.model, state_dict) - - sd_model.used_config = checkpoint_config - - timer.record("create model") - - if shared.cmd_opts.no_half: - weight_dtype_conversion = None - else: - weight_dtype_conversion = { - 'first_stage_model': None, - 'alphas_cumprod': None, - '': torch.float16, - } - - with sd_disable_initialization.LoadStateDictOnMeta(state_dict, device=model_target_device(sd_model), weight_dtype_conversion=weight_dtype_conversion): - load_model_weights(sd_model, checkpoint_info, state_dict, timer) - - timer.record("load weights from state dict") - - send_model_to_device(sd_model) - timer.record("move model to device") - - sd_hijack.model_hijack.hijack(sd_model) - - timer.record("hijack") - - sd_model.eval() - model_data.set_sd_model(sd_model) - model_data.was_loaded_at_least_once = True - - sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings(force_reload=True) # Reload embeddings after model load as they may or may not fit the model - - timer.record("load textual inversion embeddings") - - script_callbacks.model_loaded_callback(sd_model) - - timer.record("scripts callbacks") - - with devices.autocast(), torch.no_grad(): - sd_model.cond_stage_model_empty_prompt = get_empty_cond(sd_model) - - timer.record("calculate empty prompt") - - print(f"Model loaded in {timer.summary()}.") - - return sd_model - - -def reuse_model_from_already_loaded(sd_model, checkpoint_info, timer): - - if sd_model is not None and sd_model.sd_checkpoint_info.filename == checkpoint_info.filename: - return sd_model - - if shared.opts.sd_checkpoints_keep_in_cpu: - send_model_to_cpu(sd_model) - timer.record("send model to cpu") - - already_loaded = None - for i in reversed(range(len(model_data.loaded_sd_models))): - loaded_model = model_data.loaded_sd_models[i] - if loaded_model.sd_checkpoint_info.filename == checkpoint_info.filename: - already_loaded = loaded_model - continue - - if len(model_data.loaded_sd_models) > shared.opts.sd_checkpoints_limit > 0: - print(f"Unloading model {len(model_data.loaded_sd_models)} over the limit of {shared.opts.sd_checkpoints_limit}: {loaded_model.sd_checkpoint_info.title}") - del model_data.loaded_sd_models[i] - send_model_to_trash(loaded_model) - timer.record("send model to trash") - - if already_loaded is not None: - send_model_to_device(already_loaded) - timer.record("send model to device") - - model_data.set_sd_model(already_loaded, already_loaded=True) - - if not SkipWritingToConfig.skip: - shared.opts.data["sd_model_checkpoint"] = already_loaded.sd_checkpoint_info.title - shared.opts.data["sd_checkpoint_hash"] = already_loaded.sd_checkpoint_info.sha256 - - print(f"Using already loaded model {already_loaded.sd_checkpoint_info.title}: done in {timer.summary()}") - sd_vae.reload_vae_weights(already_loaded) - return model_data.sd_model - elif shared.opts.sd_checkpoints_limit > 1 and len(model_data.loaded_sd_models) < shared.opts.sd_checkpoints_limit: - print(f"Loading model {checkpoint_info.title} ({len(model_data.loaded_sd_models) + 1} out of {shared.opts.sd_checkpoints_limit})") - - model_data.sd_model = None - load_model(checkpoint_info) - return model_data.sd_model - elif len(model_data.loaded_sd_models) > 0: - sd_model = model_data.loaded_sd_models.pop() - model_data.sd_model = sd_model - - sd_vae.base_vae = getattr(sd_model, "base_vae", None) - sd_vae.loaded_vae_file = getattr(sd_model, "loaded_vae_file", None) - sd_vae.checkpoint_info = sd_model.sd_checkpoint_info - - print(f"Reusing loaded model {sd_model.sd_checkpoint_info.title} to load {checkpoint_info.title}") - return sd_model - else: - return None - - -def reload_model_weights(sd_model=None, info=None, forced_reload=False): - checkpoint_info = info or select_checkpoint() - - timer = Timer() - - if not sd_model: - sd_model = model_data.sd_model - - if sd_model is None: # previous model load failed - current_checkpoint_info = None - else: - current_checkpoint_info = sd_model.sd_checkpoint_info - if check_fp8(sd_model) != devices.fp8: - # load from state dict again to prevent extra numerical errors - forced_reload = True - elif sd_model.sd_model_checkpoint == checkpoint_info.filename and not forced_reload: - return sd_model - - sd_model = reuse_model_from_already_loaded(sd_model, checkpoint_info, timer) - if not forced_reload and sd_model is not None and sd_model.sd_checkpoint_info.filename == checkpoint_info.filename: - return sd_model - - if sd_model is not None: - sd_unet.apply_unet("None") - send_model_to_cpu(sd_model) - sd_hijack.model_hijack.undo_hijack(sd_model) - - state_dict = get_checkpoint_state_dict(checkpoint_info, timer) - - checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info) - - timer.record("find config") - - if sd_model is None or checkpoint_config != sd_model.used_config: - if sd_model is not None: - send_model_to_trash(sd_model) - - load_model(checkpoint_info, already_loaded_state_dict=state_dict) - return model_data.sd_model - - try: - load_model_weights(sd_model, checkpoint_info, state_dict, timer) - except Exception: - print("Failed to load checkpoint, restoring previous") - load_model_weights(sd_model, current_checkpoint_info, None, timer) - raise - finally: - sd_hijack.model_hijack.hijack(sd_model) - timer.record("hijack") - - if not sd_model.lowvram: - sd_model.to(devices.device) - timer.record("move model to device") - - script_callbacks.model_loaded_callback(sd_model) - timer.record("script callbacks") - - print(f"Weights loaded in {timer.summary()}.") - - model_data.set_sd_model(sd_model) - sd_unet.apply_unet() - - return sd_model - - -def unload_model_weights(sd_model=None, info=None): - send_model_to_cpu(sd_model or shared.sd_model) - - return sd_model - - -def apply_token_merging(sd_model, token_merging_ratio): - - current_token_merging_ratio = getattr(sd_model, 'applied_token_merged_ratio', 0) - - if current_token_merging_ratio == token_merging_ratio: - return - - if current_token_merging_ratio > 0: - tomesd.remove_patch(sd_model) - - if token_merging_ratio > 0: - tomesd.apply_patch( - sd_model, - ratio=token_merging_ratio, - use_rand=False, # can cause issues with some samplers - merge_attn=True, - merge_crossattn=False, - merge_mlp=False - ) - - sd_model.applied_token_merged_ratio = token_merging_ratio+import collections +import importlib +import os +import sys +import threading +import enum + +import torch +import re +import safetensors.torch +from omegaconf import OmegaConf, ListConfig +from urllib import request +import ldm.modules.midas as midas + +from modules import paths, shared, modelloader, devices, script_callbacks, sd_vae, sd_disable_initialization, errors, hashes, sd_models_config, sd_unet, sd_models_xl, cache, extra_networks, processing, lowvram, sd_hijack, patches +from modules.timer import Timer +from modules.shared import opts +import tomesd +import numpy as np + +model_dir = "Stable-diffusion" +model_path = os.path.abspath(os.path.join(paths.models_path, model_dir)) + +checkpoints_list = {} +checkpoint_aliases = {} +checkpoint_alisases = checkpoint_aliases # for compatibility with old name +checkpoints_loaded = collections.OrderedDict() + + +class ModelType(enum.Enum): + SD1 = 1 + SD2 = 2 + SDXL = 3 + SSD = 4 + SD3 = 5 + + +def replace_key(d, key, new_key, value): + keys = list(d.keys()) + + d[new_key] = value + + if key not in keys: + return d + + index = keys.index(key) + keys[index] = new_key + + new_d = {k: d[k] for k in keys} + + d.clear() + d.update(new_d) + return d + + +class CheckpointInfo: + def __init__(self, filename): + self.filename = filename + abspath = os.path.abspath(filename) + abs_ckpt_dir = os.path.abspath(shared.cmd_opts.ckpt_dir) if shared.cmd_opts.ckpt_dir is not None else None + + self.is_safetensors = os.path.splitext(filename)[1].lower() == ".safetensors" + + if abs_ckpt_dir and abspath.startswith(abs_ckpt_dir): + name = abspath.replace(abs_ckpt_dir, '') + elif abspath.startswith(model_path): + name = abspath.replace(model_path, '') + else: + name = os.path.basename(filename) + + if name.startswith("\\") or name.startswith("/"): + name = name[1:] + + def read_metadata(): + metadata = read_metadata_from_safetensors(filename) + self.modelspec_thumbnail = metadata.pop('modelspec.thumbnail', None) + + return metadata + + self.metadata = {} + if self.is_safetensors: + try: + self.metadata = cache.cached_data_for_file('safetensors-metadata', "checkpoint/" + name, filename, read_metadata) + except Exception as e: + errors.display(e, f"reading metadata for {filename}") + + self.name = name + self.name_for_extra = os.path.splitext(os.path.basename(filename))[0] + self.model_name = os.path.splitext(name.replace("/", "_").replace("\\", "_"))[0] + self.hash = model_hash(filename) + + self.sha256 = hashes.sha256_from_cache(self.filename, f"checkpoint/{name}") + self.shorthash = self.sha256[0:10] if self.sha256 else None + + self.title = name if self.shorthash is None else f'{name} [{self.shorthash}]' + self.short_title = self.name_for_extra if self.shorthash is None else f'{self.name_for_extra} [{self.shorthash}]' + + self.ids = [self.hash, self.model_name, self.title, name, self.name_for_extra, f'{name} [{self.hash}]'] + if self.shorthash: + self.ids += [self.shorthash, self.sha256, f'{self.name} [{self.shorthash}]', f'{self.name_for_extra} [{self.shorthash}]'] + + def register(self): + checkpoints_list[self.title] = self + for id in self.ids: + checkpoint_aliases[id] = self + + def calculate_shorthash(self): + self.sha256 = hashes.sha256(self.filename, f"checkpoint/{self.name}") + if self.sha256 is None: + return + + shorthash = self.sha256[0:10] + if self.shorthash == self.sha256[0:10]: + return self.shorthash + + self.shorthash = shorthash + + if self.shorthash not in self.ids: + self.ids += [self.shorthash, self.sha256, f'{self.name} [{self.shorthash}]', f'{self.name_for_extra} [{self.shorthash}]'] + + old_title = self.title + self.title = f'{self.name} [{self.shorthash}]' + self.short_title = f'{self.name_for_extra} [{self.shorthash}]' + + replace_key(checkpoints_list, old_title, self.title, self) + self.register() + + return self.shorthash + + +try: + # this silences the annoying "Some weights of the model checkpoint were not used when initializing..." message at start. + from transformers import logging, CLIPModel # noqa: F401 + + logging.set_verbosity_error() +except Exception: + pass + + +def setup_model(): + """called once at startup to do various one-time tasks related to SD models""" + + os.makedirs(model_path, exist_ok=True) + + enable_midas_autodownload() + patch_given_betas() + + +def checkpoint_tiles(use_short=False): + return [x.short_title if use_short else x.title for x in checkpoints_list.values()] + + +def list_models(): + checkpoints_list.clear() + checkpoint_aliases.clear() + + cmd_ckpt = shared.cmd_opts.ckpt + if shared.cmd_opts.no_download_sd_model or cmd_ckpt != shared.sd_model_file or os.path.exists(cmd_ckpt): + model_url = None + expected_sha256 = None + else: + model_url = f"{shared.hf_endpoint}/runwayml/stable-diffusion-v1-5/resolve/main/v1-5-pruned-emaonly.safetensors" + expected_sha256 = '6ce0161689b3853acaa03779ec93eafe75a02f4ced659bee03f50797806fa2fa' + + model_list = modelloader.load_models(model_path=model_path, model_url=model_url, command_path=shared.cmd_opts.ckpt_dir, ext_filter=[".ckpt", ".safetensors"], download_name="v1-5-pruned-emaonly.safetensors", ext_blacklist=[".vae.ckpt", ".vae.safetensors"], hash_prefix=expected_sha256) + + if os.path.exists(cmd_ckpt): + checkpoint_info = CheckpointInfo(cmd_ckpt) + checkpoint_info.register() + + shared.opts.data['sd_model_checkpoint'] = checkpoint_info.title + elif cmd_ckpt is not None and cmd_ckpt != shared.default_sd_model_file: + print(f"Checkpoint in --ckpt argument not found (Possible it was moved to {model_path}: {cmd_ckpt}", file=sys.stderr) + + for filename in model_list: + checkpoint_info = CheckpointInfo(filename) + checkpoint_info.register() + + +re_strip_checksum = re.compile(r"\s*\[[^]]+]\s*$") + + +def get_closet_checkpoint_match(search_string): + if not search_string: + return None + + checkpoint_info = checkpoint_aliases.get(search_string, None) + if checkpoint_info is not None: + return checkpoint_info + + found = sorted([info for info in checkpoints_list.values() if search_string in info.title], key=lambda x: len(x.title)) + if found: + return found[0] + + search_string_without_checksum = re.sub(re_strip_checksum, '', search_string) + found = sorted([info for info in checkpoints_list.values() if search_string_without_checksum in info.title], key=lambda x: len(x.title)) + if found: + return found[0] + + return None + + +def model_hash(filename): + """old hash that only looks at a small part of the file and is prone to collisions""" + + try: + with open(filename, "rb") as file: + import hashlib + m = hashlib.sha256() + + file.seek(0x100000) + m.update(file.read(0x10000)) + return m.hexdigest()[0:8] + except FileNotFoundError: + return 'NOFILE' + + +def select_checkpoint(): + """Raises `FileNotFoundError` if no checkpoints are found.""" + model_checkpoint = shared.opts.sd_model_checkpoint + + checkpoint_info = checkpoint_aliases.get(model_checkpoint, None) + if checkpoint_info is not None: + return checkpoint_info + + if len(checkpoints_list) == 0: + error_message = "No checkpoints found. When searching for checkpoints, looked at:" + if shared.cmd_opts.ckpt is not None: + error_message += f"\n - file {os.path.abspath(shared.cmd_opts.ckpt)}" + error_message += f"\n - directory {model_path}" + if shared.cmd_opts.ckpt_dir is not None: + error_message += f"\n - directory {os.path.abspath(shared.cmd_opts.ckpt_dir)}" + error_message += "Can't run without a checkpoint. Find and place a .ckpt or .safetensors file into any of those locations." + raise FileNotFoundError(error_message) + + checkpoint_info = next(iter(checkpoints_list.values())) + if model_checkpoint is not None: + print(f"Checkpoint {model_checkpoint} not found; loading fallback {checkpoint_info.title}", file=sys.stderr) + + return checkpoint_info + + +checkpoint_dict_replacements_sd1 = { + 'cond_stage_model.transformer.embeddings.': 'cond_stage_model.transformer.text_model.embeddings.', + 'cond_stage_model.transformer.encoder.': 'cond_stage_model.transformer.text_model.encoder.', + 'cond_stage_model.transformer.final_layer_norm.': 'cond_stage_model.transformer.text_model.final_layer_norm.', +} + +checkpoint_dict_replacements_sd2_turbo = { # Converts SD 2.1 Turbo from SGM to LDM format. + 'conditioner.embedders.0.': 'cond_stage_model.', +} + + +def transform_checkpoint_dict_key(k, replacements): + for text, replacement in replacements.items(): + if k.startswith(text): + k = replacement + k[len(text):] + + return k + + +def get_state_dict_from_checkpoint(pl_sd): + pl_sd = pl_sd.pop("state_dict", pl_sd) + pl_sd.pop("state_dict", None) + + is_sd2_turbo = 'conditioner.embedders.0.model.ln_final.weight' in pl_sd and pl_sd['conditioner.embedders.0.model.ln_final.weight'].size()[0] == 1024 + + sd = {} + for k, v in pl_sd.items(): + if is_sd2_turbo: + new_key = transform_checkpoint_dict_key(k, checkpoint_dict_replacements_sd2_turbo) + else: + new_key = transform_checkpoint_dict_key(k, checkpoint_dict_replacements_sd1) + + if new_key is not None: + sd[new_key] = v + + pl_sd.clear() + pl_sd.update(sd) + + return pl_sd + + +def read_metadata_from_safetensors(filename): + import json + + with open(filename, mode="rb") as file: + metadata_len = file.read(8) + metadata_len = int.from_bytes(metadata_len, "little") + json_start = file.read(2) + + assert metadata_len > 2 and json_start in (b'{"', b"{'"), f"{filename} is not a safetensors file" + + res = {} + + try: + json_data = json_start + file.read(metadata_len-2) + json_obj = json.loads(json_data) + for k, v in json_obj.get("__metadata__", {}).items(): + res[k] = v + if isinstance(v, str) and v[0:1] == '{': + try: + res[k] = json.loads(v) + except Exception: + pass + except Exception: + errors.report(f"Error reading metadata from file: {filename}", exc_info=True) + + return res + + +def read_state_dict(checkpoint_file, print_global_state=False, map_location=None): + _, extension = os.path.splitext(checkpoint_file) + if extension.lower() == ".safetensors": + device = map_location or shared.weight_load_location or devices.get_optimal_device_name() + + if not shared.opts.disable_mmap_load_safetensors: + pl_sd = safetensors.torch.load_file(checkpoint_file, device=device) + else: + pl_sd = safetensors.torch.load(open(checkpoint_file, 'rb').read()) + pl_sd = {k: v.to(device) for k, v in pl_sd.items()} + else: + pl_sd = torch.load(checkpoint_file, map_location=map_location or shared.weight_load_location) + + if print_global_state and "global_step" in pl_sd: + print(f"Global Step: {pl_sd['global_step']}") + + sd = get_state_dict_from_checkpoint(pl_sd) + return sd + + +def get_checkpoint_state_dict(checkpoint_info: CheckpointInfo, timer): + sd_model_hash = checkpoint_info.calculate_shorthash() + timer.record("calculate hash") + + if checkpoint_info in checkpoints_loaded: + # use checkpoint cache + print(f"Loading weights [{sd_model_hash}] from cache") + # move to end as latest + checkpoints_loaded.move_to_end(checkpoint_info) + return checkpoints_loaded[checkpoint_info] + + print(f"Loading weights [{sd_model_hash}] from {checkpoint_info.filename}") + res = read_state_dict(checkpoint_info.filename) + timer.record("load weights from disk") + + return res + + +class SkipWritingToConfig: + """This context manager prevents load_model_weights from writing checkpoint name to the config when it loads weight.""" + + skip = False + previous = None + + def __enter__(self): + self.previous = SkipWritingToConfig.skip + SkipWritingToConfig.skip = True + return self + + def __exit__(self, exc_type, exc_value, exc_traceback): + SkipWritingToConfig.skip = self.previous + + +def check_fp8(model): + if model is None: + return None + if devices.get_optimal_device_name() == "mps": + enable_fp8 = False + elif shared.opts.fp8_storage == "Enable": + enable_fp8 = True + elif getattr(model, "is_sdxl", False) and shared.opts.fp8_storage == "Enable for SDXL": + enable_fp8 = True + else: + enable_fp8 = False + return enable_fp8 + + +def set_model_type(model, state_dict): + model.is_sd1 = False + model.is_sd2 = False + model.is_sdxl = False + model.is_ssd = False + model.is_sd3 = False + + if "model.diffusion_model.x_embedder.proj.weight" in state_dict: + model.is_sd3 = True + model.model_type = ModelType.SD3 + elif hasattr(model, 'conditioner'): + model.is_sdxl = True + + if 'model.diffusion_model.middle_block.1.transformer_blocks.0.attn1.to_q.weight' not in state_dict.keys(): + model.is_ssd = True + model.model_type = ModelType.SSD + else: + model.model_type = ModelType.SDXL + elif hasattr(model.cond_stage_model, 'model'): + model.is_sd2 = True + model.model_type = ModelType.SD2 + else: + model.is_sd1 = True + model.model_type = ModelType.SD1 + + +def set_model_fields(model): + if not hasattr(model, 'latent_channels'): + model.latent_channels = 4 + + +def load_model_weights(model, checkpoint_info: CheckpointInfo, state_dict, timer): + sd_model_hash = checkpoint_info.calculate_shorthash() + timer.record("calculate hash") + + if devices.fp8: + # prevent model to load state dict in fp8 + model.half() + + if not SkipWritingToConfig.skip: + shared.opts.data["sd_model_checkpoint"] = checkpoint_info.title + + if state_dict is None: + state_dict = get_checkpoint_state_dict(checkpoint_info, timer) + + set_model_type(model, state_dict) + set_model_fields(model) + + if model.is_sdxl: + sd_models_xl.extend_sdxl(model) + + if model.is_ssd: + sd_hijack.model_hijack.convert_sdxl_to_ssd(model) + + if shared.opts.sd_checkpoint_cache > 0: + # cache newly loaded model + checkpoints_loaded[checkpoint_info] = state_dict.copy() + + if hasattr(model, "before_load_weights"): + model.before_load_weights(state_dict) + + model.load_state_dict(state_dict, strict=False) + timer.record("apply weights to model") + + if hasattr(model, "after_load_weights"): + model.after_load_weights(state_dict) + + del state_dict + + # Set is_sdxl_inpaint flag. + # Checks Unet structure to detect inpaint model. The inpaint model's + # checkpoint state_dict does not contain the key + # 'diffusion_model.input_blocks.0.0.weight'. + diffusion_model_input = model.model.state_dict().get( + 'diffusion_model.input_blocks.0.0.weight' + ) + model.is_sdxl_inpaint = ( + model.is_sdxl and + diffusion_model_input is not None and + diffusion_model_input.shape[1] == 9 + ) + + if shared.cmd_opts.opt_channelslast: + model.to(memory_format=torch.channels_last) + timer.record("apply channels_last") + + if shared.cmd_opts.no_half: + model.float() + model.alphas_cumprod_original = model.alphas_cumprod + devices.dtype_unet = torch.float32 + assert shared.cmd_opts.precision != "half", "Cannot use --precision half with --no-half" + timer.record("apply float()") + else: + vae = model.first_stage_model + depth_model = getattr(model, 'depth_model', None) + + # with --no-half-vae, remove VAE from model when doing half() to prevent its weights from being converted to float16 + if shared.cmd_opts.no_half_vae: + model.first_stage_model = None + # with --upcast-sampling, don't convert the depth model weights to float16 + if shared.cmd_opts.upcast_sampling and depth_model: + model.depth_model = None + + alphas_cumprod = model.alphas_cumprod + model.alphas_cumprod = None + model.half() + model.alphas_cumprod = alphas_cumprod + model.alphas_cumprod_original = alphas_cumprod + model.first_stage_model = vae + if depth_model: + model.depth_model = depth_model + + devices.dtype_unet = torch.float16 + timer.record("apply half()") + + apply_alpha_schedule_override(model) + + for module in model.modules(): + if hasattr(module, 'fp16_weight'): + del module.fp16_weight + if hasattr(module, 'fp16_bias'): + del module.fp16_bias + + if check_fp8(model): + devices.fp8 = True + first_stage = model.first_stage_model + model.first_stage_model = None + for module in model.modules(): + if isinstance(module, (torch.nn.Conv2d, torch.nn.Linear)): + if shared.opts.cache_fp16_weight: + module.fp16_weight = module.weight.data.clone().cpu().half() + if module.bias is not None: + module.fp16_bias = module.bias.data.clone().cpu().half() + module.to(torch.float8_e4m3fn) + model.first_stage_model = first_stage + timer.record("apply fp8") + else: + devices.fp8 = False + + devices.unet_needs_upcast = shared.cmd_opts.upcast_sampling and devices.dtype == torch.float16 and devices.dtype_unet == torch.float16 + + model.first_stage_model.to(devices.dtype_vae) + timer.record("apply dtype to VAE") + + # clean up cache if limit is reached + while len(checkpoints_loaded) > shared.opts.sd_checkpoint_cache: + checkpoints_loaded.popitem(last=False) + + model.sd_model_hash = sd_model_hash + model.sd_model_checkpoint = checkpoint_info.filename + model.sd_checkpoint_info = checkpoint_info + shared.opts.data["sd_checkpoint_hash"] = checkpoint_info.sha256 + + if hasattr(model, 'logvar'): + model.logvar = model.logvar.to(devices.device) # fix for training + + sd_vae.delete_base_vae() + sd_vae.clear_loaded_vae() + vae_file, vae_source = sd_vae.resolve_vae(checkpoint_info.filename).tuple() + sd_vae.load_vae(model, vae_file, vae_source) + timer.record("load VAE") + + +def enable_midas_autodownload(): + """ + Gives the ldm.modules.midas.api.load_model function automatic downloading. + + When the 512-depth-ema model, and other future models like it, is loaded, + it calls midas.api.load_model to load the associated midas depth model. + This function applies a wrapper to download the model to the correct + location automatically. + """ + + midas_path = os.path.join(paths.models_path, 'midas') + + # stable-diffusion-stability-ai hard-codes the midas model path to + # a location that differs from where other scripts using this model look. + # HACK: Overriding the path here. + for k, v in midas.api.ISL_PATHS.items(): + file_name = os.path.basename(v) + midas.api.ISL_PATHS[k] = os.path.join(midas_path, file_name) + + midas_urls = { + "dpt_large": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", + "dpt_hybrid": "https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid-midas-501f0c75.pt", + "midas_v21": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21-f6b98070.pt", + "midas_v21_small": "https://github.com/AlexeyAB/MiDaS/releases/download/midas_dpt/midas_v21_small-70d6b9c8.pt", + } + + midas.api.load_model_inner = midas.api.load_model + + def load_model_wrapper(model_type): + path = midas.api.ISL_PATHS[model_type] + if not os.path.exists(path): + if not os.path.exists(midas_path): + os.mkdir(midas_path) + + print(f"Downloading midas model weights for {model_type} to {path}") + request.urlretrieve(midas_urls[model_type], path) + print(f"{model_type} downloaded") + + return midas.api.load_model_inner(model_type) + + midas.api.load_model = load_model_wrapper + + +def patch_given_betas(): + import ldm.models.diffusion.ddpm + + def patched_register_schedule(*args, **kwargs): + """a modified version of register_schedule function that converts plain list from Omegaconf into numpy""" + + if isinstance(args[1], ListConfig): + args = (args[0], np.array(args[1]), *args[2:]) + + original_register_schedule(*args, **kwargs) + + original_register_schedule = patches.patch(__name__, ldm.models.diffusion.ddpm.DDPM, 'register_schedule', patched_register_schedule) + + +def repair_config(sd_config, state_dict=None): + if not hasattr(sd_config.model.params, "use_ema"): + sd_config.model.params.use_ema = False + + if hasattr(sd_config.model.params, 'unet_config'): + if shared.cmd_opts.no_half: + sd_config.model.params.unet_config.params.use_fp16 = False + elif shared.cmd_opts.upcast_sampling or shared.cmd_opts.precision == "half": + sd_config.model.params.unet_config.params.use_fp16 = True + + if hasattr(sd_config.model.params, 'first_stage_config'): + if getattr(sd_config.model.params.first_stage_config.params.ddconfig, "attn_type", None) == "vanilla-xformers" and not shared.xformers_available: + sd_config.model.params.first_stage_config.params.ddconfig.attn_type = "vanilla" + + # For UnCLIP-L, override the hardcoded karlo directory + if hasattr(sd_config.model.params, "noise_aug_config") and hasattr(sd_config.model.params.noise_aug_config.params, "clip_stats_path"): + karlo_path = os.path.join(paths.models_path, 'karlo') + sd_config.model.params.noise_aug_config.params.clip_stats_path = sd_config.model.params.noise_aug_config.params.clip_stats_path.replace("checkpoints/karlo_models", karlo_path) + + # Do not use checkpoint for inference. + # This helps prevent extra performance overhead on checking parameters. + # The perf overhead is about 100ms/it on 4090 for SDXL. + if hasattr(sd_config.model.params, "network_config"): + sd_config.model.params.network_config.params.use_checkpoint = False + if hasattr(sd_config.model.params, "unet_config"): + sd_config.model.params.unet_config.params.use_checkpoint = False + + + +def rescale_zero_terminal_snr_abar(alphas_cumprod): + alphas_bar_sqrt = alphas_cumprod.sqrt() + + # Store old values. + alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone() + alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone() + + # Shift so the last timestep is zero. + alphas_bar_sqrt -= (alphas_bar_sqrt_T) + + # Scale so the first timestep is back to the old value. + alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T) + + # Convert alphas_bar_sqrt to betas + alphas_bar = alphas_bar_sqrt ** 2 # Revert sqrt + alphas_bar[-1] = 4.8973451890853435e-08 + return alphas_bar + + +def apply_alpha_schedule_override(sd_model, p=None): + """ + Applies an override to the alpha schedule of the model according to settings. + - downcasts the alpha schedule to half precision + - rescales the alpha schedule to have zero terminal SNR + """ + + if not hasattr(sd_model, 'alphas_cumprod') or not hasattr(sd_model, 'alphas_cumprod_original'): + return + + sd_model.alphas_cumprod = sd_model.alphas_cumprod_original.to(shared.device) + + if opts.use_downcasted_alpha_bar: + if p is not None: + p.extra_generation_params['Downcast alphas_cumprod'] = opts.use_downcasted_alpha_bar + sd_model.alphas_cumprod = sd_model.alphas_cumprod.half().to(shared.device) + + if opts.sd_noise_schedule == "Zero Terminal SNR": + if p is not None: + p.extra_generation_params['Noise Schedule'] = opts.sd_noise_schedule + sd_model.alphas_cumprod = rescale_zero_terminal_snr_abar(sd_model.alphas_cumprod).to(shared.device) + + +sd1_clip_weight = 'cond_stage_model.transformer.text_model.embeddings.token_embedding.weight' +sd2_clip_weight = 'cond_stage_model.model.transformer.resblocks.0.attn.in_proj_weight' +sdxl_clip_weight = 'conditioner.embedders.1.model.ln_final.weight' +sdxl_refiner_clip_weight = 'conditioner.embedders.0.model.ln_final.weight' + + +class SdModelData: + def __init__(self): + self.sd_model = None + self.loaded_sd_models = [] + self.was_loaded_at_least_once = False + self.lock = threading.Lock() + + def get_sd_model(self): + if self.was_loaded_at_least_once: + return self.sd_model + + if self.sd_model is None: + with self.lock: + if self.sd_model is not None or self.was_loaded_at_least_once: + return self.sd_model + + try: + load_model() + + except Exception as e: + errors.display(e, "loading stable diffusion model", full_traceback=True) + print("", file=sys.stderr) + print("Stable diffusion model failed to load", file=sys.stderr) + self.sd_model = None + + return self.sd_model + + def set_sd_model(self, v, already_loaded=False): + self.sd_model = v + if already_loaded: + sd_vae.base_vae = getattr(v, "base_vae", None) + sd_vae.loaded_vae_file = getattr(v, "loaded_vae_file", None) + sd_vae.checkpoint_info = v.sd_checkpoint_info + + try: + self.loaded_sd_models.remove(v) + except ValueError: + pass + + if v is not None: + self.loaded_sd_models.insert(0, v) + + +model_data = SdModelData() + + +def get_empty_cond(sd_model): + + p = processing.StableDiffusionProcessingTxt2Img() + extra_networks.activate(p, {}) + + if hasattr(sd_model, 'get_learned_conditioning'): + d = sd_model.get_learned_conditioning([""]) + else: + d = sd_model.cond_stage_model([""]) + + if isinstance(d, dict): + d = d['crossattn'] + + return d + + +def send_model_to_cpu(m): + if m is not None: + if m.lowvram: + lowvram.send_everything_to_cpu() + else: + m.to(devices.cpu) + + devices.torch_gc() + + +def model_target_device(m): + if lowvram.is_needed(m): + return devices.cpu + else: + return devices.device + + +def send_model_to_device(m): + lowvram.apply(m) + + if not m.lowvram: + m.to(shared.device) + + +def send_model_to_trash(m): + m.to(device="meta") + devices.torch_gc() + + +def instantiate_from_config(config, state_dict=None): + constructor = get_obj_from_str(config["target"]) + + params = {**config.get("params", {})} + + if state_dict and "state_dict" in params and params["state_dict"] is None: + params["state_dict"] = state_dict + + return constructor(**params) + + +def get_obj_from_str(string, reload=False): + module, cls = string.rsplit(".", 1) + if reload: + module_imp = importlib.import_module(module) + importlib.reload(module_imp) + return getattr(importlib.import_module(module, package=None), cls) + + +def load_model(checkpoint_info=None, already_loaded_state_dict=None): + from modules import sd_hijack + checkpoint_info = checkpoint_info or select_checkpoint() + + timer = Timer() + + if model_data.sd_model: + send_model_to_trash(model_data.sd_model) + model_data.sd_model = None + devices.torch_gc() + + timer.record("unload existing model") + + if already_loaded_state_dict is not None: + state_dict = already_loaded_state_dict + else: + state_dict = get_checkpoint_state_dict(checkpoint_info, timer) + + checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info) + clip_is_included_into_sd = any(x for x in [sd1_clip_weight, sd2_clip_weight, sdxl_clip_weight, sdxl_refiner_clip_weight] if x in state_dict) + + timer.record("find config") + + sd_config = OmegaConf.load(checkpoint_config) + repair_config(sd_config, state_dict) + + timer.record("load config") + + print(f"Creating model from config: {checkpoint_config}") + + sd_model = None + try: + with sd_disable_initialization.DisableInitialization(disable_clip=clip_is_included_into_sd or shared.cmd_opts.do_not_download_clip): + with sd_disable_initialization.InitializeOnMeta(): + sd_model = instantiate_from_config(sd_config.model, state_dict) + + except Exception as e: + errors.display(e, "creating model quickly", full_traceback=True) + + if sd_model is None: + print('Failed to create model quickly; will retry using slow method.', file=sys.stderr) + + with sd_disable_initialization.InitializeOnMeta(): + sd_model = instantiate_from_config(sd_config.model, state_dict) + + sd_model.used_config = checkpoint_config + + timer.record("create model") + + if shared.cmd_opts.no_half: + weight_dtype_conversion = None + else: + weight_dtype_conversion = { + 'first_stage_model': None, + 'alphas_cumprod': None, + '': torch.float16, + } + + with sd_disable_initialization.LoadStateDictOnMeta(state_dict, device=model_target_device(sd_model), weight_dtype_conversion=weight_dtype_conversion): + load_model_weights(sd_model, checkpoint_info, state_dict, timer) + + timer.record("load weights from state dict") + + send_model_to_device(sd_model) + timer.record("move model to device") + + sd_hijack.model_hijack.hijack(sd_model) + + timer.record("hijack") + + sd_model.eval() + model_data.set_sd_model(sd_model) + model_data.was_loaded_at_least_once = True + + sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings(force_reload=True) # Reload embeddings after model load as they may or may not fit the model + + timer.record("load textual inversion embeddings") + + script_callbacks.model_loaded_callback(sd_model) + + timer.record("scripts callbacks") + + with devices.autocast(), torch.no_grad(): + sd_model.cond_stage_model_empty_prompt = get_empty_cond(sd_model) + + timer.record("calculate empty prompt") + + print(f"Model loaded in {timer.summary()}.") + + return sd_model + + +def reuse_model_from_already_loaded(sd_model, checkpoint_info, timer): + """ + Checks if the desired checkpoint from checkpoint_info is not already loaded in model_data.loaded_sd_models. + If it is loaded, returns that (moving it to GPU if necessary, and moving the currently loadded model to CPU if necessary). + If not, returns the model that can be used to load weights from checkpoint_info's file. + If no such model exists, returns None. + Additionally deletes loaded models that are over the limit set in settings (sd_checkpoints_limit). + """ + + if sd_model is not None and sd_model.sd_checkpoint_info.filename == checkpoint_info.filename: + return sd_model + + if shared.opts.sd_checkpoints_keep_in_cpu: + send_model_to_cpu(sd_model) + timer.record("send model to cpu") + + already_loaded = None + for i in reversed(range(len(model_data.loaded_sd_models))): + loaded_model = model_data.loaded_sd_models[i] + if loaded_model.sd_checkpoint_info.filename == checkpoint_info.filename: + already_loaded = loaded_model + continue + + if len(model_data.loaded_sd_models) > shared.opts.sd_checkpoints_limit > 0: + print(f"Unloading model {len(model_data.loaded_sd_models)} over the limit of {shared.opts.sd_checkpoints_limit}: {loaded_model.sd_checkpoint_info.title}") + del model_data.loaded_sd_models[i] + send_model_to_trash(loaded_model) + timer.record("send model to trash") + + if already_loaded is not None: + send_model_to_device(already_loaded) + timer.record("send model to device") + + model_data.set_sd_model(already_loaded, already_loaded=True) + + if not SkipWritingToConfig.skip: + shared.opts.data["sd_model_checkpoint"] = already_loaded.sd_checkpoint_info.title + shared.opts.data["sd_checkpoint_hash"] = already_loaded.sd_checkpoint_info.sha256 + + print(f"Using already loaded model {already_loaded.sd_checkpoint_info.title}: done in {timer.summary()}") + sd_vae.reload_vae_weights(already_loaded) + return model_data.sd_model + elif shared.opts.sd_checkpoints_limit > 1 and len(model_data.loaded_sd_models) < shared.opts.sd_checkpoints_limit: + print(f"Loading model {checkpoint_info.title} ({len(model_data.loaded_sd_models) + 1} out of {shared.opts.sd_checkpoints_limit})") + + model_data.sd_model = None + load_model(checkpoint_info) + return model_data.sd_model + elif len(model_data.loaded_sd_models) > 0: + sd_model = model_data.loaded_sd_models.pop() + model_data.sd_model = sd_model + + sd_vae.base_vae = getattr(sd_model, "base_vae", None) + sd_vae.loaded_vae_file = getattr(sd_model, "loaded_vae_file", None) + sd_vae.checkpoint_info = sd_model.sd_checkpoint_info + + print(f"Reusing loaded model {sd_model.sd_checkpoint_info.title} to load {checkpoint_info.title}") + return sd_model + else: + return None + + +def reload_model_weights(sd_model=None, info=None, forced_reload=False): + checkpoint_info = info or select_checkpoint() + + timer = Timer() + + if not sd_model: + sd_model = model_data.sd_model + + if sd_model is None: # previous model load failed + current_checkpoint_info = None + else: + current_checkpoint_info = sd_model.sd_checkpoint_info + if check_fp8(sd_model) != devices.fp8: + # load from state dict again to prevent extra numerical errors + forced_reload = True + elif sd_model.sd_model_checkpoint == checkpoint_info.filename and not forced_reload: + return sd_model + + sd_model = reuse_model_from_already_loaded(sd_model, checkpoint_info, timer) + if not forced_reload and sd_model is not None and sd_model.sd_checkpoint_info.filename == checkpoint_info.filename: + return sd_model + + if sd_model is not None: + sd_unet.apply_unet("None") + send_model_to_cpu(sd_model) + sd_hijack.model_hijack.undo_hijack(sd_model) + + state_dict = get_checkpoint_state_dict(checkpoint_info, timer) + + checkpoint_config = sd_models_config.find_checkpoint_config(state_dict, checkpoint_info) + + timer.record("find config") + + if sd_model is None or checkpoint_config != sd_model.used_config: + if sd_model is not None: + send_model_to_trash(sd_model) + + load_model(checkpoint_info, already_loaded_state_dict=state_dict) + return model_data.sd_model + + try: + load_model_weights(sd_model, checkpoint_info, state_dict, timer) + except Exception: + print("Failed to load checkpoint, restoring previous") + load_model_weights(sd_model, current_checkpoint_info, None, timer) + raise + finally: + sd_hijack.model_hijack.hijack(sd_model) + timer.record("hijack") + + if not sd_model.lowvram: + sd_model.to(devices.device) + timer.record("move model to device") + + script_callbacks.model_loaded_callback(sd_model) + timer.record("script callbacks") + + print(f"Weights loaded in {timer.summary()}.") + + model_data.set_sd_model(sd_model) + sd_unet.apply_unet() + + return sd_model + + +def unload_model_weights(sd_model=None, info=None): + send_model_to_cpu(sd_model or shared.sd_model) + + return sd_model + + +def apply_token_merging(sd_model, token_merging_ratio): + """ + Applies speed and memory optimizations from tomesd. + """ + + current_token_merging_ratio = getattr(sd_model, 'applied_token_merged_ratio', 0) + + if current_token_merging_ratio == token_merging_ratio: + return + + if current_token_merging_ratio > 0: + tomesd.remove_patch(sd_model) + + if token_merging_ratio > 0: + tomesd.apply_patch( + sd_model, + ratio=token_merging_ratio, + use_rand=False, # can cause issues with some samplers + merge_attn=True, + merge_crossattn=False, + merge_mlp=False + ) + + sd_model.applied_token_merged_ratio = token_merging_ratio
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_models.py
Generate docstrings with parameter types
import dataclasses import os import gradio as gr from modules import errors, shared @dataclasses.dataclass class PostprocessedImageSharedInfo: target_width: int = None target_height: int = None class PostprocessedImage: def __init__(self, image): self.image = image self.info = {} self.shared = PostprocessedImageSharedInfo() self.extra_images = [] self.nametags = [] self.disable_processing = False self.caption = None def get_suffix(self, used_suffixes=None): used_suffixes = {} if used_suffixes is None else used_suffixes suffix = "-".join(self.nametags) if suffix: suffix = "-" + suffix if suffix not in used_suffixes: used_suffixes[suffix] = 1 return suffix for i in range(1, 100): proposed_suffix = suffix + "-" + str(i) if proposed_suffix not in used_suffixes: used_suffixes[proposed_suffix] = 1 return proposed_suffix return suffix def create_copy(self, new_image, *, nametags=None, disable_processing=False): pp = PostprocessedImage(new_image) pp.shared = self.shared pp.nametags = self.nametags.copy() pp.info = self.info.copy() pp.disable_processing = disable_processing if nametags is not None: pp.nametags += nametags return pp class ScriptPostprocessing: filename = None controls = None args_from = None args_to = None order = 1000 """scripts will be ordred by this value in postprocessing UI""" name = None """this function should return the title of the script.""" group = None """A gr.Group component that has all script's UI inside it""" def ui(self): pass def process(self, pp: PostprocessedImage, **args): pass def process_firstpass(self, pp: PostprocessedImage, **args): pass def image_changed(self): pass def wrap_call(func, filename, funcname, *args, default=None, **kwargs): try: res = func(*args, **kwargs) return res except Exception as e: errors.display(e, f"calling {filename}/{funcname}") return default class ScriptPostprocessingRunner: def __init__(self): self.scripts = None self.ui_created = False def initialize_scripts(self, scripts_data): self.scripts = [] for script_data in scripts_data: script: ScriptPostprocessing = script_data.script_class() script.filename = script_data.path if script.name == "Simple Upscale": continue self.scripts.append(script) def create_script_ui(self, script, inputs): script.args_from = len(inputs) script.args_to = len(inputs) script.controls = wrap_call(script.ui, script.filename, "ui") for control in script.controls.values(): control.custom_script_source = os.path.basename(script.filename) inputs += list(script.controls.values()) script.args_to = len(inputs) def scripts_in_preferred_order(self): if self.scripts is None: import modules.scripts self.initialize_scripts(modules.scripts.postprocessing_scripts_data) scripts_order = shared.opts.postprocessing_operation_order scripts_filter_out = set(shared.opts.postprocessing_disable_in_extras) def script_score(name): for i, possible_match in enumerate(scripts_order): if possible_match == name: return i return len(self.scripts) filtered_scripts = [script for script in self.scripts if script.name not in scripts_filter_out] script_scores = {script.name: (script_score(script.name), script.order, script.name, original_index) for original_index, script in enumerate(filtered_scripts)} return sorted(filtered_scripts, key=lambda x: script_scores[x.name]) def setup_ui(self): inputs = [] for script in self.scripts_in_preferred_order(): with gr.Row() as group: self.create_script_ui(script, inputs) script.group = group self.ui_created = True return inputs def run(self, pp: PostprocessedImage, args): scripts = [] for script in self.scripts_in_preferred_order(): script_args = args[script.args_from:script.args_to] process_args = {} for (name, _component), value in zip(script.controls.items(), script_args): process_args[name] = value scripts.append((script, process_args)) for script, process_args in scripts: script.process_firstpass(pp, **process_args) all_images = [pp] for script, process_args in scripts: if shared.state.skipped: break shared.state.job = script.name for single_image in all_images.copy(): if not single_image.disable_processing: script.process(single_image, **process_args) for extra_image in single_image.extra_images: if not isinstance(extra_image, PostprocessedImage): extra_image = single_image.create_copy(extra_image) all_images.append(extra_image) single_image.extra_images.clear() pp.extra_images = all_images[1:] def create_args_for_run(self, scripts_args): if not self.ui_created: with gr.Blocks(analytics_enabled=False): self.setup_ui() scripts = self.scripts_in_preferred_order() args = [None] * max([x.args_to for x in scripts]) for script in scripts: script_args_dict = scripts_args.get(script.name, None) if script_args_dict is not None: for i, name in enumerate(script.controls): args[script.args_from + i] = script_args_dict.get(name, None) return args def image_changed(self): for script in self.scripts_in_preferred_order(): script.image_changed()
--- +++ @@ -1,215 +1,230 @@-import dataclasses -import os -import gradio as gr - -from modules import errors, shared - - -@dataclasses.dataclass -class PostprocessedImageSharedInfo: - target_width: int = None - target_height: int = None - - -class PostprocessedImage: - def __init__(self, image): - self.image = image - self.info = {} - self.shared = PostprocessedImageSharedInfo() - self.extra_images = [] - self.nametags = [] - self.disable_processing = False - self.caption = None - - def get_suffix(self, used_suffixes=None): - used_suffixes = {} if used_suffixes is None else used_suffixes - suffix = "-".join(self.nametags) - if suffix: - suffix = "-" + suffix - - if suffix not in used_suffixes: - used_suffixes[suffix] = 1 - return suffix - - for i in range(1, 100): - proposed_suffix = suffix + "-" + str(i) - - if proposed_suffix not in used_suffixes: - used_suffixes[proposed_suffix] = 1 - return proposed_suffix - - return suffix - - def create_copy(self, new_image, *, nametags=None, disable_processing=False): - pp = PostprocessedImage(new_image) - pp.shared = self.shared - pp.nametags = self.nametags.copy() - pp.info = self.info.copy() - pp.disable_processing = disable_processing - - if nametags is not None: - pp.nametags += nametags - - return pp - - -class ScriptPostprocessing: - filename = None - controls = None - args_from = None - args_to = None - - order = 1000 - """scripts will be ordred by this value in postprocessing UI""" - - name = None - """this function should return the title of the script.""" - - group = None - """A gr.Group component that has all script's UI inside it""" - - def ui(self): - - pass - - def process(self, pp: PostprocessedImage, **args): - - pass - - def process_firstpass(self, pp: PostprocessedImage, **args): - - pass - - def image_changed(self): - pass - - -def wrap_call(func, filename, funcname, *args, default=None, **kwargs): - try: - res = func(*args, **kwargs) - return res - except Exception as e: - errors.display(e, f"calling {filename}/{funcname}") - - return default - - -class ScriptPostprocessingRunner: - def __init__(self): - self.scripts = None - self.ui_created = False - - def initialize_scripts(self, scripts_data): - self.scripts = [] - - for script_data in scripts_data: - script: ScriptPostprocessing = script_data.script_class() - script.filename = script_data.path - - if script.name == "Simple Upscale": - continue - - self.scripts.append(script) - - def create_script_ui(self, script, inputs): - script.args_from = len(inputs) - script.args_to = len(inputs) - - script.controls = wrap_call(script.ui, script.filename, "ui") - - for control in script.controls.values(): - control.custom_script_source = os.path.basename(script.filename) - - inputs += list(script.controls.values()) - script.args_to = len(inputs) - - def scripts_in_preferred_order(self): - if self.scripts is None: - import modules.scripts - self.initialize_scripts(modules.scripts.postprocessing_scripts_data) - - scripts_order = shared.opts.postprocessing_operation_order - scripts_filter_out = set(shared.opts.postprocessing_disable_in_extras) - - def script_score(name): - for i, possible_match in enumerate(scripts_order): - if possible_match == name: - return i - - return len(self.scripts) - - filtered_scripts = [script for script in self.scripts if script.name not in scripts_filter_out] - script_scores = {script.name: (script_score(script.name), script.order, script.name, original_index) for original_index, script in enumerate(filtered_scripts)} - - return sorted(filtered_scripts, key=lambda x: script_scores[x.name]) - - def setup_ui(self): - inputs = [] - - for script in self.scripts_in_preferred_order(): - with gr.Row() as group: - self.create_script_ui(script, inputs) - - script.group = group - - self.ui_created = True - return inputs - - def run(self, pp: PostprocessedImage, args): - scripts = [] - - for script in self.scripts_in_preferred_order(): - script_args = args[script.args_from:script.args_to] - - process_args = {} - for (name, _component), value in zip(script.controls.items(), script_args): - process_args[name] = value - - scripts.append((script, process_args)) - - for script, process_args in scripts: - script.process_firstpass(pp, **process_args) - - all_images = [pp] - - for script, process_args in scripts: - if shared.state.skipped: - break - - shared.state.job = script.name - - for single_image in all_images.copy(): - - if not single_image.disable_processing: - script.process(single_image, **process_args) - - for extra_image in single_image.extra_images: - if not isinstance(extra_image, PostprocessedImage): - extra_image = single_image.create_copy(extra_image) - - all_images.append(extra_image) - - single_image.extra_images.clear() - - pp.extra_images = all_images[1:] - - def create_args_for_run(self, scripts_args): - if not self.ui_created: - with gr.Blocks(analytics_enabled=False): - self.setup_ui() - - scripts = self.scripts_in_preferred_order() - args = [None] * max([x.args_to for x in scripts]) - - for script in scripts: - script_args_dict = scripts_args.get(script.name, None) - if script_args_dict is not None: - - for i, name in enumerate(script.controls): - args[script.args_from + i] = script_args_dict.get(name, None) - - return args - - def image_changed(self): - for script in self.scripts_in_preferred_order(): - script.image_changed() +import dataclasses +import os +import gradio as gr + +from modules import errors, shared + + +@dataclasses.dataclass +class PostprocessedImageSharedInfo: + target_width: int = None + target_height: int = None + + +class PostprocessedImage: + def __init__(self, image): + self.image = image + self.info = {} + self.shared = PostprocessedImageSharedInfo() + self.extra_images = [] + self.nametags = [] + self.disable_processing = False + self.caption = None + + def get_suffix(self, used_suffixes=None): + used_suffixes = {} if used_suffixes is None else used_suffixes + suffix = "-".join(self.nametags) + if suffix: + suffix = "-" + suffix + + if suffix not in used_suffixes: + used_suffixes[suffix] = 1 + return suffix + + for i in range(1, 100): + proposed_suffix = suffix + "-" + str(i) + + if proposed_suffix not in used_suffixes: + used_suffixes[proposed_suffix] = 1 + return proposed_suffix + + return suffix + + def create_copy(self, new_image, *, nametags=None, disable_processing=False): + pp = PostprocessedImage(new_image) + pp.shared = self.shared + pp.nametags = self.nametags.copy() + pp.info = self.info.copy() + pp.disable_processing = disable_processing + + if nametags is not None: + pp.nametags += nametags + + return pp + + +class ScriptPostprocessing: + filename = None + controls = None + args_from = None + args_to = None + + order = 1000 + """scripts will be ordred by this value in postprocessing UI""" + + name = None + """this function should return the title of the script.""" + + group = None + """A gr.Group component that has all script's UI inside it""" + + def ui(self): + """ + This function should create gradio UI elements. See https://gradio.app/docs/#components + The return value should be a dictionary that maps parameter names to components used in processing. + Values of those components will be passed to process() function. + """ + + pass + + def process(self, pp: PostprocessedImage, **args): + """ + This function is called to postprocess the image. + args contains a dictionary with all values returned by components from ui() + """ + + pass + + def process_firstpass(self, pp: PostprocessedImage, **args): + """ + Called for all scripts before calling process(). Scripts can examine the image here and set fields + of the pp object to communicate things to other scripts. + args contains a dictionary with all values returned by components from ui() + """ + + pass + + def image_changed(self): + pass + + +def wrap_call(func, filename, funcname, *args, default=None, **kwargs): + try: + res = func(*args, **kwargs) + return res + except Exception as e: + errors.display(e, f"calling {filename}/{funcname}") + + return default + + +class ScriptPostprocessingRunner: + def __init__(self): + self.scripts = None + self.ui_created = False + + def initialize_scripts(self, scripts_data): + self.scripts = [] + + for script_data in scripts_data: + script: ScriptPostprocessing = script_data.script_class() + script.filename = script_data.path + + if script.name == "Simple Upscale": + continue + + self.scripts.append(script) + + def create_script_ui(self, script, inputs): + script.args_from = len(inputs) + script.args_to = len(inputs) + + script.controls = wrap_call(script.ui, script.filename, "ui") + + for control in script.controls.values(): + control.custom_script_source = os.path.basename(script.filename) + + inputs += list(script.controls.values()) + script.args_to = len(inputs) + + def scripts_in_preferred_order(self): + if self.scripts is None: + import modules.scripts + self.initialize_scripts(modules.scripts.postprocessing_scripts_data) + + scripts_order = shared.opts.postprocessing_operation_order + scripts_filter_out = set(shared.opts.postprocessing_disable_in_extras) + + def script_score(name): + for i, possible_match in enumerate(scripts_order): + if possible_match == name: + return i + + return len(self.scripts) + + filtered_scripts = [script for script in self.scripts if script.name not in scripts_filter_out] + script_scores = {script.name: (script_score(script.name), script.order, script.name, original_index) for original_index, script in enumerate(filtered_scripts)} + + return sorted(filtered_scripts, key=lambda x: script_scores[x.name]) + + def setup_ui(self): + inputs = [] + + for script in self.scripts_in_preferred_order(): + with gr.Row() as group: + self.create_script_ui(script, inputs) + + script.group = group + + self.ui_created = True + return inputs + + def run(self, pp: PostprocessedImage, args): + scripts = [] + + for script in self.scripts_in_preferred_order(): + script_args = args[script.args_from:script.args_to] + + process_args = {} + for (name, _component), value in zip(script.controls.items(), script_args): + process_args[name] = value + + scripts.append((script, process_args)) + + for script, process_args in scripts: + script.process_firstpass(pp, **process_args) + + all_images = [pp] + + for script, process_args in scripts: + if shared.state.skipped: + break + + shared.state.job = script.name + + for single_image in all_images.copy(): + + if not single_image.disable_processing: + script.process(single_image, **process_args) + + for extra_image in single_image.extra_images: + if not isinstance(extra_image, PostprocessedImage): + extra_image = single_image.create_copy(extra_image) + + all_images.append(extra_image) + + single_image.extra_images.clear() + + pp.extra_images = all_images[1:] + + def create_args_for_run(self, scripts_args): + if not self.ui_created: + with gr.Blocks(analytics_enabled=False): + self.setup_ui() + + scripts = self.scripts_in_preferred_order() + args = [None] * max([x.args_to for x in scripts]) + + for script in scripts: + script_args_dict = scripts_args.get(script.name, None) + if script_args_dict is not None: + + for i, name in enumerate(script.controls): + args[script.args_from + i] = script_args_dict.get(name, None) + + return args + + def image_changed(self): + for script in self.scripts_in_preferred_order(): + script.image_changed() +
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/scripts_postprocessing.py
Add docstrings following best practices
from collections import defaultdict def patch(key, obj, field, replacement): patch_key = (obj, field) if patch_key in originals[key]: raise RuntimeError(f"patch for {field} is already applied") original_func = getattr(obj, field) originals[key][patch_key] = original_func setattr(obj, field, replacement) return original_func def undo(key, obj, field): patch_key = (obj, field) if patch_key not in originals[key]: raise RuntimeError(f"there is no patch for {field} to undo") original_func = originals[key].pop(patch_key) setattr(obj, field, original_func) return None def original(key, obj, field): patch_key = (obj, field) return originals[key].get(patch_key, None) originals = defaultdict(dict)
--- +++ @@ -1,37 +1,64 @@-from collections import defaultdict - - -def patch(key, obj, field, replacement): - - patch_key = (obj, field) - if patch_key in originals[key]: - raise RuntimeError(f"patch for {field} is already applied") - - original_func = getattr(obj, field) - originals[key][patch_key] = original_func - - setattr(obj, field, replacement) - - return original_func - - -def undo(key, obj, field): - - patch_key = (obj, field) - - if patch_key not in originals[key]: - raise RuntimeError(f"there is no patch for {field} to undo") - - original_func = originals[key].pop(patch_key) - setattr(obj, field, original_func) - - return None - - -def original(key, obj, field): - patch_key = (obj, field) - - return originals[key].get(patch_key, None) - - -originals = defaultdict(dict)+from collections import defaultdict + + +def patch(key, obj, field, replacement): + """Replaces a function in a module or a class. + + Also stores the original function in this module, possible to be retrieved via original(key, obj, field). + If the function is already replaced by this caller (key), an exception is raised -- use undo() before that. + + Arguments: + key: identifying information for who is doing the replacement. You can use __name__. + obj: the module or the class + field: name of the function as a string + replacement: the new function + + Returns: + the original function + """ + + patch_key = (obj, field) + if patch_key in originals[key]: + raise RuntimeError(f"patch for {field} is already applied") + + original_func = getattr(obj, field) + originals[key][patch_key] = original_func + + setattr(obj, field, replacement) + + return original_func + + +def undo(key, obj, field): + """Undoes the peplacement by the patch(). + + If the function is not replaced, raises an exception. + + Arguments: + key: identifying information for who is doing the replacement. You can use __name__. + obj: the module or the class + field: name of the function as a string + + Returns: + Always None + """ + + patch_key = (obj, field) + + if patch_key not in originals[key]: + raise RuntimeError(f"there is no patch for {field} to undo") + + original_func = originals[key].pop(patch_key) + setattr(obj, field, original_func) + + return None + + +def original(key, obj, field): + """Returns the original function for the patch created by the patch() function""" + patch_key = (obj, field) + + return originals[key].get(patch_key, None) + + +originals = defaultdict(dict)
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/patches.py
Generate docstrings for each module
from __future__ import annotations import torch class Emphasis: name: str = "Base" description: str = "" tokens: list[list[int]] """tokens from the chunk of the prompt""" multipliers: torch.Tensor """tensor with multipliers, once for each token""" z: torch.Tensor """output of cond transformers network (CLIP)""" def after_transformers(self): pass class EmphasisNone(Emphasis): name = "None" description = "disable the mechanism entirely and treat (:.1.1) as literal characters" class EmphasisIgnore(Emphasis): name = "Ignore" description = "treat all empasised words as if they have no emphasis" class EmphasisOriginal(Emphasis): name = "Original" description = "the original emphasis implementation" def after_transformers(self): original_mean = self.z.mean() self.z = self.z * self.multipliers.reshape(self.multipliers.shape + (1,)).expand(self.z.shape) # restoring original mean is likely not correct, but it seems to work well to prevent artifacts that happen otherwise new_mean = self.z.mean() self.z = self.z * (original_mean / new_mean) class EmphasisOriginalNoNorm(EmphasisOriginal): name = "No norm" description = "same as original, but without normalization (seems to work better for SDXL)" def after_transformers(self): self.z = self.z * self.multipliers.reshape(self.multipliers.shape + (1,)).expand(self.z.shape) def get_current_option(emphasis_option_name): return next(iter([x for x in options if x.name == emphasis_option_name]), EmphasisOriginal) def get_options_descriptions(): return ", ".join(f"{x.name}: {x.description}" for x in options) options = [ EmphasisNone, EmphasisIgnore, EmphasisOriginal, EmphasisOriginalNoNorm, ]
--- +++ @@ -1,68 +1,70 @@-from __future__ import annotations -import torch - - -class Emphasis: - - name: str = "Base" - description: str = "" - - tokens: list[list[int]] - """tokens from the chunk of the prompt""" - - multipliers: torch.Tensor - """tensor with multipliers, once for each token""" - - z: torch.Tensor - """output of cond transformers network (CLIP)""" - - def after_transformers(self): - - pass - - -class EmphasisNone(Emphasis): - name = "None" - description = "disable the mechanism entirely and treat (:.1.1) as literal characters" - - -class EmphasisIgnore(Emphasis): - name = "Ignore" - description = "treat all empasised words as if they have no emphasis" - - -class EmphasisOriginal(Emphasis): - name = "Original" - description = "the original emphasis implementation" - - def after_transformers(self): - original_mean = self.z.mean() - self.z = self.z * self.multipliers.reshape(self.multipliers.shape + (1,)).expand(self.z.shape) - - # restoring original mean is likely not correct, but it seems to work well to prevent artifacts that happen otherwise - new_mean = self.z.mean() - self.z = self.z * (original_mean / new_mean) - - -class EmphasisOriginalNoNorm(EmphasisOriginal): - name = "No norm" - description = "same as original, but without normalization (seems to work better for SDXL)" - - def after_transformers(self): - self.z = self.z * self.multipliers.reshape(self.multipliers.shape + (1,)).expand(self.z.shape) - - -def get_current_option(emphasis_option_name): - return next(iter([x for x in options if x.name == emphasis_option_name]), EmphasisOriginal) - - -def get_options_descriptions(): - return ", ".join(f"{x.name}: {x.description}" for x in options) - - -options = [ - EmphasisNone, - EmphasisIgnore, - EmphasisOriginal, - EmphasisOriginalNoNorm, -]+from __future__ import annotations +import torch + + +class Emphasis: + """Emphasis class decides how to death with (emphasized:1.1) text in prompts""" + + name: str = "Base" + description: str = "" + + tokens: list[list[int]] + """tokens from the chunk of the prompt""" + + multipliers: torch.Tensor + """tensor with multipliers, once for each token""" + + z: torch.Tensor + """output of cond transformers network (CLIP)""" + + def after_transformers(self): + """Called after cond transformers network has processed the chunk of the prompt; this function should modify self.z to apply the emphasis""" + + pass + + +class EmphasisNone(Emphasis): + name = "None" + description = "disable the mechanism entirely and treat (:.1.1) as literal characters" + + +class EmphasisIgnore(Emphasis): + name = "Ignore" + description = "treat all empasised words as if they have no emphasis" + + +class EmphasisOriginal(Emphasis): + name = "Original" + description = "the original emphasis implementation" + + def after_transformers(self): + original_mean = self.z.mean() + self.z = self.z * self.multipliers.reshape(self.multipliers.shape + (1,)).expand(self.z.shape) + + # restoring original mean is likely not correct, but it seems to work well to prevent artifacts that happen otherwise + new_mean = self.z.mean() + self.z = self.z * (original_mean / new_mean) + + +class EmphasisOriginalNoNorm(EmphasisOriginal): + name = "No norm" + description = "same as original, but without normalization (seems to work better for SDXL)" + + def after_transformers(self): + self.z = self.z * self.multipliers.reshape(self.multipliers.shape + (1,)).expand(self.z.shape) + + +def get_current_option(emphasis_option_name): + return next(iter([x for x in options if x.name == emphasis_option_name]), EmphasisOriginal) + + +def get_options_descriptions(): + return ", ".join(f"{x.name}: {x.description}" for x in options) + + +options = [ + EmphasisNone, + EmphasisIgnore, + EmphasisOriginal, + EmphasisOriginalNoNorm, +]
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_emphasis.py
Create docstrings for all classes and functions
from __future__ import annotations import re from collections import namedtuple import lark # a prompt like this: "fantasy landscape with a [mountain:lake:0.25] and [an oak:a christmas tree:0.75][ in foreground::0.6][: in background:0.25] [shoddy:masterful:0.5]" # will be represented with prompt_schedule like this (assuming steps=100): # [25, 'fantasy landscape with a mountain and an oak in foreground shoddy'] # [50, 'fantasy landscape with a lake and an oak in foreground in background shoddy'] # [60, 'fantasy landscape with a lake and an oak in foreground in background masterful'] # [75, 'fantasy landscape with a lake and an oak in background masterful'] # [100, 'fantasy landscape with a lake and a christmas tree in background masterful'] schedule_parser = lark.Lark(r""" !start: (prompt | /[][():]/+)* prompt: (emphasized | scheduled | alternate | plain | WHITESPACE)* !emphasized: "(" prompt ")" | "(" prompt ":" prompt ")" | "[" prompt "]" scheduled: "[" [prompt ":"] prompt ":" [WHITESPACE] NUMBER [WHITESPACE] "]" alternate: "[" prompt ("|" [prompt])+ "]" WHITESPACE: /\s+/ plain: /([^\\\[\]():|]|\\.)+/ %import common.SIGNED_NUMBER -> NUMBER """) def get_learned_conditioning_prompt_schedules(prompts, base_steps, hires_steps=None, use_old_scheduling=False): if hires_steps is None or use_old_scheduling: int_offset = 0 flt_offset = 0 steps = base_steps else: int_offset = base_steps flt_offset = 1.0 steps = hires_steps def collect_steps(steps, tree): res = [steps] class CollectSteps(lark.Visitor): def scheduled(self, tree): s = tree.children[-2] v = float(s) if use_old_scheduling: v = v*steps if v<1 else v else: if "." in s: v = (v - flt_offset) * steps else: v = (v - int_offset) tree.children[-2] = min(steps, int(v)) if tree.children[-2] >= 1: res.append(tree.children[-2]) def alternate(self, tree): res.extend(range(1, steps+1)) CollectSteps().visit(tree) return sorted(set(res)) def at_step(step, tree): class AtStep(lark.Transformer): def scheduled(self, args): before, after, _, when, _ = args yield before or () if step <= when else after def alternate(self, args): args = ["" if not arg else arg for arg in args] yield args[(step - 1) % len(args)] def start(self, args): def flatten(x): if isinstance(x, str): yield x else: for gen in x: yield from flatten(gen) return ''.join(flatten(args)) def plain(self, args): yield args[0].value def __default__(self, data, children, meta): for child in children: yield child return AtStep().transform(tree) def get_schedule(prompt): try: tree = schedule_parser.parse(prompt) except lark.exceptions.LarkError: if 0: import traceback traceback.print_exc() return [[steps, prompt]] return [[t, at_step(t, tree)] for t in collect_steps(steps, tree)] promptdict = {prompt: get_schedule(prompt) for prompt in set(prompts)} return [promptdict[prompt] for prompt in prompts] ScheduledPromptConditioning = namedtuple("ScheduledPromptConditioning", ["end_at_step", "cond"]) class SdConditioning(list): def __init__(self, prompts, is_negative_prompt=False, width=None, height=None, copy_from=None): super().__init__() self.extend(prompts) if copy_from is None: copy_from = prompts self.is_negative_prompt = is_negative_prompt or getattr(copy_from, 'is_negative_prompt', False) self.width = width or getattr(copy_from, 'width', None) self.height = height or getattr(copy_from, 'height', None) def get_learned_conditioning(model, prompts: SdConditioning | list[str], steps, hires_steps=None, use_old_scheduling=False): res = [] prompt_schedules = get_learned_conditioning_prompt_schedules(prompts, steps, hires_steps, use_old_scheduling) cache = {} for prompt, prompt_schedule in zip(prompts, prompt_schedules): cached = cache.get(prompt, None) if cached is not None: res.append(cached) continue texts = SdConditioning([x[1] for x in prompt_schedule], copy_from=prompts) conds = model.get_learned_conditioning(texts) cond_schedule = [] for i, (end_at_step, _) in enumerate(prompt_schedule): if isinstance(conds, dict): cond = {k: v[i] for k, v in conds.items()} else: cond = conds[i] cond_schedule.append(ScheduledPromptConditioning(end_at_step, cond)) cache[prompt] = cond_schedule res.append(cond_schedule) return res re_AND = re.compile(r"\bAND\b") re_weight = re.compile(r"^((?:\s|.)*?)(?:\s*:\s*([-+]?(?:\d+\.?|\d*\.\d+)))?\s*$") def get_multicond_prompt_list(prompts: SdConditioning | list[str]): res_indexes = [] prompt_indexes = {} prompt_flat_list = SdConditioning(prompts) prompt_flat_list.clear() for prompt in prompts: subprompts = re_AND.split(prompt) indexes = [] for subprompt in subprompts: match = re_weight.search(subprompt) text, weight = match.groups() if match is not None else (subprompt, 1.0) weight = float(weight) if weight is not None else 1.0 index = prompt_indexes.get(text, None) if index is None: index = len(prompt_flat_list) prompt_flat_list.append(text) prompt_indexes[text] = index indexes.append((index, weight)) res_indexes.append(indexes) return res_indexes, prompt_flat_list, prompt_indexes class ComposableScheduledPromptConditioning: def __init__(self, schedules, weight=1.0): self.schedules: list[ScheduledPromptConditioning] = schedules self.weight: float = weight class MulticondLearnedConditioning: def __init__(self, shape, batch): self.shape: tuple = shape # the shape field is needed to send this object to DDIM/PLMS self.batch: list[list[ComposableScheduledPromptConditioning]] = batch def get_multicond_learned_conditioning(model, prompts, steps, hires_steps=None, use_old_scheduling=False) -> MulticondLearnedConditioning: res_indexes, prompt_flat_list, prompt_indexes = get_multicond_prompt_list(prompts) learned_conditioning = get_learned_conditioning(model, prompt_flat_list, steps, hires_steps, use_old_scheduling) res = [] for indexes in res_indexes: res.append([ComposableScheduledPromptConditioning(learned_conditioning[i], weight) for i, weight in indexes]) return MulticondLearnedConditioning(shape=(len(prompts),), batch=res) class DictWithShape(dict): def __init__(self, x, shape=None): super().__init__() self.update(x) @property def shape(self): return self["crossattn"].shape def reconstruct_cond_batch(c: list[list[ScheduledPromptConditioning]], current_step): param = c[0][0].cond is_dict = isinstance(param, dict) if is_dict: dict_cond = param res = {k: torch.zeros((len(c),) + param.shape, device=param.device, dtype=param.dtype) for k, param in dict_cond.items()} res = DictWithShape(res, (len(c),) + dict_cond['crossattn'].shape) else: res = torch.zeros((len(c),) + param.shape, device=param.device, dtype=param.dtype) for i, cond_schedule in enumerate(c): target_index = 0 for current, entry in enumerate(cond_schedule): if current_step <= entry.end_at_step: target_index = current break if is_dict: for k, param in cond_schedule[target_index].cond.items(): res[k][i] = param else: res[i] = cond_schedule[target_index].cond return res def stack_conds(tensors): # if prompts have wildly different lengths above the limit we'll get tensors of different shapes # and won't be able to torch.stack them. So this fixes that. token_count = max([x.shape[0] for x in tensors]) for i in range(len(tensors)): if tensors[i].shape[0] != token_count: last_vector = tensors[i][-1:] last_vector_repeated = last_vector.repeat([token_count - tensors[i].shape[0], 1]) tensors[i] = torch.vstack([tensors[i], last_vector_repeated]) return torch.stack(tensors) def reconstruct_multicond_batch(c: MulticondLearnedConditioning, current_step): param = c.batch[0][0].schedules[0].cond tensors = [] conds_list = [] for composable_prompts in c.batch: conds_for_batch = [] for composable_prompt in composable_prompts: target_index = 0 for current, entry in enumerate(composable_prompt.schedules): if current_step <= entry.end_at_step: target_index = current break conds_for_batch.append((len(tensors), composable_prompt.weight)) tensors.append(composable_prompt.schedules[target_index].cond) conds_list.append(conds_for_batch) if isinstance(tensors[0], dict): keys = list(tensors[0].keys()) stacked = {k: stack_conds([x[k] for x in tensors]) for k in keys} stacked = DictWithShape(stacked, stacked['crossattn'].shape) else: stacked = stack_conds(tensors).to(device=param.device, dtype=param.dtype) return conds_list, stacked re_attention = re.compile(r""" \\\(| \\\)| \\\[| \\]| \\\\| \\| \(| \[| :\s*([+-]?[.\d]+)\s*\)| \)| ]| [^\\()\[\]:]+| : """, re.X) re_break = re.compile(r"\s*\bBREAK\b\s*", re.S) def parse_prompt_attention(text): res = [] round_brackets = [] square_brackets = [] round_bracket_multiplier = 1.1 square_bracket_multiplier = 1 / 1.1 def multiply_range(start_position, multiplier): for p in range(start_position, len(res)): res[p][1] *= multiplier for m in re_attention.finditer(text): text = m.group(0) weight = m.group(1) if text.startswith('\\'): res.append([text[1:], 1.0]) elif text == '(': round_brackets.append(len(res)) elif text == '[': square_brackets.append(len(res)) elif weight is not None and round_brackets: multiply_range(round_brackets.pop(), float(weight)) elif text == ')' and round_brackets: multiply_range(round_brackets.pop(), round_bracket_multiplier) elif text == ']' and square_brackets: multiply_range(square_brackets.pop(), square_bracket_multiplier) else: parts = re.split(re_break, text) for i, part in enumerate(parts): if i > 0: res.append(["BREAK", -1]) res.append([part, 1.0]) for pos in round_brackets: multiply_range(pos, round_bracket_multiplier) for pos in square_brackets: multiply_range(pos, square_bracket_multiplier) if len(res) == 0: res = [["", 1.0]] # merge runs of identical weights i = 0 while i + 1 < len(res): if res[i][1] == res[i + 1][1]: res[i][0] += res[i + 1][0] res.pop(i + 1) else: i += 1 return res if __name__ == "__main__": import doctest doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE) else: import torch # doctest faster
--- +++ @@ -1,368 +1,464 @@-from __future__ import annotations - -import re -from collections import namedtuple -import lark - -# a prompt like this: "fantasy landscape with a [mountain:lake:0.25] and [an oak:a christmas tree:0.75][ in foreground::0.6][: in background:0.25] [shoddy:masterful:0.5]" -# will be represented with prompt_schedule like this (assuming steps=100): -# [25, 'fantasy landscape with a mountain and an oak in foreground shoddy'] -# [50, 'fantasy landscape with a lake and an oak in foreground in background shoddy'] -# [60, 'fantasy landscape with a lake and an oak in foreground in background masterful'] -# [75, 'fantasy landscape with a lake and an oak in background masterful'] -# [100, 'fantasy landscape with a lake and a christmas tree in background masterful'] - -schedule_parser = lark.Lark(r""" -!start: (prompt | /[][():]/+)* -prompt: (emphasized | scheduled | alternate | plain | WHITESPACE)* -!emphasized: "(" prompt ")" - | "(" prompt ":" prompt ")" - | "[" prompt "]" -scheduled: "[" [prompt ":"] prompt ":" [WHITESPACE] NUMBER [WHITESPACE] "]" -alternate: "[" prompt ("|" [prompt])+ "]" -WHITESPACE: /\s+/ -plain: /([^\\\[\]():|]|\\.)+/ -%import common.SIGNED_NUMBER -> NUMBER -""") - -def get_learned_conditioning_prompt_schedules(prompts, base_steps, hires_steps=None, use_old_scheduling=False): - - if hires_steps is None or use_old_scheduling: - int_offset = 0 - flt_offset = 0 - steps = base_steps - else: - int_offset = base_steps - flt_offset = 1.0 - steps = hires_steps - - def collect_steps(steps, tree): - res = [steps] - - class CollectSteps(lark.Visitor): - def scheduled(self, tree): - s = tree.children[-2] - v = float(s) - if use_old_scheduling: - v = v*steps if v<1 else v - else: - if "." in s: - v = (v - flt_offset) * steps - else: - v = (v - int_offset) - tree.children[-2] = min(steps, int(v)) - if tree.children[-2] >= 1: - res.append(tree.children[-2]) - - def alternate(self, tree): - res.extend(range(1, steps+1)) - - CollectSteps().visit(tree) - return sorted(set(res)) - - def at_step(step, tree): - class AtStep(lark.Transformer): - def scheduled(self, args): - before, after, _, when, _ = args - yield before or () if step <= when else after - def alternate(self, args): - args = ["" if not arg else arg for arg in args] - yield args[(step - 1) % len(args)] - def start(self, args): - def flatten(x): - if isinstance(x, str): - yield x - else: - for gen in x: - yield from flatten(gen) - return ''.join(flatten(args)) - def plain(self, args): - yield args[0].value - def __default__(self, data, children, meta): - for child in children: - yield child - return AtStep().transform(tree) - - def get_schedule(prompt): - try: - tree = schedule_parser.parse(prompt) - except lark.exceptions.LarkError: - if 0: - import traceback - traceback.print_exc() - return [[steps, prompt]] - return [[t, at_step(t, tree)] for t in collect_steps(steps, tree)] - - promptdict = {prompt: get_schedule(prompt) for prompt in set(prompts)} - return [promptdict[prompt] for prompt in prompts] - - -ScheduledPromptConditioning = namedtuple("ScheduledPromptConditioning", ["end_at_step", "cond"]) - - -class SdConditioning(list): - def __init__(self, prompts, is_negative_prompt=False, width=None, height=None, copy_from=None): - super().__init__() - self.extend(prompts) - - if copy_from is None: - copy_from = prompts - - self.is_negative_prompt = is_negative_prompt or getattr(copy_from, 'is_negative_prompt', False) - self.width = width or getattr(copy_from, 'width', None) - self.height = height or getattr(copy_from, 'height', None) - - - -def get_learned_conditioning(model, prompts: SdConditioning | list[str], steps, hires_steps=None, use_old_scheduling=False): - res = [] - - prompt_schedules = get_learned_conditioning_prompt_schedules(prompts, steps, hires_steps, use_old_scheduling) - cache = {} - - for prompt, prompt_schedule in zip(prompts, prompt_schedules): - - cached = cache.get(prompt, None) - if cached is not None: - res.append(cached) - continue - - texts = SdConditioning([x[1] for x in prompt_schedule], copy_from=prompts) - conds = model.get_learned_conditioning(texts) - - cond_schedule = [] - for i, (end_at_step, _) in enumerate(prompt_schedule): - if isinstance(conds, dict): - cond = {k: v[i] for k, v in conds.items()} - else: - cond = conds[i] - - cond_schedule.append(ScheduledPromptConditioning(end_at_step, cond)) - - cache[prompt] = cond_schedule - res.append(cond_schedule) - - return res - - -re_AND = re.compile(r"\bAND\b") -re_weight = re.compile(r"^((?:\s|.)*?)(?:\s*:\s*([-+]?(?:\d+\.?|\d*\.\d+)))?\s*$") - - -def get_multicond_prompt_list(prompts: SdConditioning | list[str]): - res_indexes = [] - - prompt_indexes = {} - prompt_flat_list = SdConditioning(prompts) - prompt_flat_list.clear() - - for prompt in prompts: - subprompts = re_AND.split(prompt) - - indexes = [] - for subprompt in subprompts: - match = re_weight.search(subprompt) - - text, weight = match.groups() if match is not None else (subprompt, 1.0) - - weight = float(weight) if weight is not None else 1.0 - - index = prompt_indexes.get(text, None) - if index is None: - index = len(prompt_flat_list) - prompt_flat_list.append(text) - prompt_indexes[text] = index - - indexes.append((index, weight)) - - res_indexes.append(indexes) - - return res_indexes, prompt_flat_list, prompt_indexes - - -class ComposableScheduledPromptConditioning: - def __init__(self, schedules, weight=1.0): - self.schedules: list[ScheduledPromptConditioning] = schedules - self.weight: float = weight - - -class MulticondLearnedConditioning: - def __init__(self, shape, batch): - self.shape: tuple = shape # the shape field is needed to send this object to DDIM/PLMS - self.batch: list[list[ComposableScheduledPromptConditioning]] = batch - - -def get_multicond_learned_conditioning(model, prompts, steps, hires_steps=None, use_old_scheduling=False) -> MulticondLearnedConditioning: - - res_indexes, prompt_flat_list, prompt_indexes = get_multicond_prompt_list(prompts) - - learned_conditioning = get_learned_conditioning(model, prompt_flat_list, steps, hires_steps, use_old_scheduling) - - res = [] - for indexes in res_indexes: - res.append([ComposableScheduledPromptConditioning(learned_conditioning[i], weight) for i, weight in indexes]) - - return MulticondLearnedConditioning(shape=(len(prompts),), batch=res) - - -class DictWithShape(dict): - def __init__(self, x, shape=None): - super().__init__() - self.update(x) - - @property - def shape(self): - return self["crossattn"].shape - - -def reconstruct_cond_batch(c: list[list[ScheduledPromptConditioning]], current_step): - param = c[0][0].cond - is_dict = isinstance(param, dict) - - if is_dict: - dict_cond = param - res = {k: torch.zeros((len(c),) + param.shape, device=param.device, dtype=param.dtype) for k, param in dict_cond.items()} - res = DictWithShape(res, (len(c),) + dict_cond['crossattn'].shape) - else: - res = torch.zeros((len(c),) + param.shape, device=param.device, dtype=param.dtype) - - for i, cond_schedule in enumerate(c): - target_index = 0 - for current, entry in enumerate(cond_schedule): - if current_step <= entry.end_at_step: - target_index = current - break - - if is_dict: - for k, param in cond_schedule[target_index].cond.items(): - res[k][i] = param - else: - res[i] = cond_schedule[target_index].cond - - return res - - -def stack_conds(tensors): - # if prompts have wildly different lengths above the limit we'll get tensors of different shapes - # and won't be able to torch.stack them. So this fixes that. - token_count = max([x.shape[0] for x in tensors]) - for i in range(len(tensors)): - if tensors[i].shape[0] != token_count: - last_vector = tensors[i][-1:] - last_vector_repeated = last_vector.repeat([token_count - tensors[i].shape[0], 1]) - tensors[i] = torch.vstack([tensors[i], last_vector_repeated]) - - return torch.stack(tensors) - - - -def reconstruct_multicond_batch(c: MulticondLearnedConditioning, current_step): - param = c.batch[0][0].schedules[0].cond - - tensors = [] - conds_list = [] - - for composable_prompts in c.batch: - conds_for_batch = [] - - for composable_prompt in composable_prompts: - target_index = 0 - for current, entry in enumerate(composable_prompt.schedules): - if current_step <= entry.end_at_step: - target_index = current - break - - conds_for_batch.append((len(tensors), composable_prompt.weight)) - tensors.append(composable_prompt.schedules[target_index].cond) - - conds_list.append(conds_for_batch) - - if isinstance(tensors[0], dict): - keys = list(tensors[0].keys()) - stacked = {k: stack_conds([x[k] for x in tensors]) for k in keys} - stacked = DictWithShape(stacked, stacked['crossattn'].shape) - else: - stacked = stack_conds(tensors).to(device=param.device, dtype=param.dtype) - - return conds_list, stacked - - -re_attention = re.compile(r""" -\\\(| -\\\)| -\\\[| -\\]| -\\\\| -\\| -\(| -\[| -:\s*([+-]?[.\d]+)\s*\)| -\)| -]| -[^\\()\[\]:]+| -: -""", re.X) - -re_break = re.compile(r"\s*\bBREAK\b\s*", re.S) - -def parse_prompt_attention(text): - - res = [] - round_brackets = [] - square_brackets = [] - - round_bracket_multiplier = 1.1 - square_bracket_multiplier = 1 / 1.1 - - def multiply_range(start_position, multiplier): - for p in range(start_position, len(res)): - res[p][1] *= multiplier - - for m in re_attention.finditer(text): - text = m.group(0) - weight = m.group(1) - - if text.startswith('\\'): - res.append([text[1:], 1.0]) - elif text == '(': - round_brackets.append(len(res)) - elif text == '[': - square_brackets.append(len(res)) - elif weight is not None and round_brackets: - multiply_range(round_brackets.pop(), float(weight)) - elif text == ')' and round_brackets: - multiply_range(round_brackets.pop(), round_bracket_multiplier) - elif text == ']' and square_brackets: - multiply_range(square_brackets.pop(), square_bracket_multiplier) - else: - parts = re.split(re_break, text) - for i, part in enumerate(parts): - if i > 0: - res.append(["BREAK", -1]) - res.append([part, 1.0]) - - for pos in round_brackets: - multiply_range(pos, round_bracket_multiplier) - - for pos in square_brackets: - multiply_range(pos, square_bracket_multiplier) - - if len(res) == 0: - res = [["", 1.0]] - - # merge runs of identical weights - i = 0 - while i + 1 < len(res): - if res[i][1] == res[i + 1][1]: - res[i][0] += res[i + 1][0] - res.pop(i + 1) - else: - i += 1 - - return res - -if __name__ == "__main__": - import doctest - doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE) -else: - import torch # doctest faster+from __future__ import annotations + +import re +from collections import namedtuple +import lark + +# a prompt like this: "fantasy landscape with a [mountain:lake:0.25] and [an oak:a christmas tree:0.75][ in foreground::0.6][: in background:0.25] [shoddy:masterful:0.5]" +# will be represented with prompt_schedule like this (assuming steps=100): +# [25, 'fantasy landscape with a mountain and an oak in foreground shoddy'] +# [50, 'fantasy landscape with a lake and an oak in foreground in background shoddy'] +# [60, 'fantasy landscape with a lake and an oak in foreground in background masterful'] +# [75, 'fantasy landscape with a lake and an oak in background masterful'] +# [100, 'fantasy landscape with a lake and a christmas tree in background masterful'] + +schedule_parser = lark.Lark(r""" +!start: (prompt | /[][():]/+)* +prompt: (emphasized | scheduled | alternate | plain | WHITESPACE)* +!emphasized: "(" prompt ")" + | "(" prompt ":" prompt ")" + | "[" prompt "]" +scheduled: "[" [prompt ":"] prompt ":" [WHITESPACE] NUMBER [WHITESPACE] "]" +alternate: "[" prompt ("|" [prompt])+ "]" +WHITESPACE: /\s+/ +plain: /([^\\\[\]():|]|\\.)+/ +%import common.SIGNED_NUMBER -> NUMBER +""") + +def get_learned_conditioning_prompt_schedules(prompts, base_steps, hires_steps=None, use_old_scheduling=False): + """ + >>> g = lambda p: get_learned_conditioning_prompt_schedules([p], 10)[0] + >>> g("test") + [[10, 'test']] + >>> g("a [b:3]") + [[3, 'a '], [10, 'a b']] + >>> g("a [b: 3]") + [[3, 'a '], [10, 'a b']] + >>> g("a [[[b]]:2]") + [[2, 'a '], [10, 'a [[b]]']] + >>> g("[(a:2):3]") + [[3, ''], [10, '(a:2)']] + >>> g("a [b : c : 1] d") + [[1, 'a b d'], [10, 'a c d']] + >>> g("a[b:[c:d:2]:1]e") + [[1, 'abe'], [2, 'ace'], [10, 'ade']] + >>> g("a [unbalanced") + [[10, 'a [unbalanced']] + >>> g("a [b:.5] c") + [[5, 'a c'], [10, 'a b c']] + >>> g("a [{b|d{:.5] c") # not handling this right now + [[5, 'a c'], [10, 'a {b|d{ c']] + >>> g("((a][:b:c [d:3]") + [[3, '((a][:b:c '], [10, '((a][:b:c d']] + >>> g("[a|(b:1.1)]") + [[1, 'a'], [2, '(b:1.1)'], [3, 'a'], [4, '(b:1.1)'], [5, 'a'], [6, '(b:1.1)'], [7, 'a'], [8, '(b:1.1)'], [9, 'a'], [10, '(b:1.1)']] + >>> g("[fe|]male") + [[1, 'female'], [2, 'male'], [3, 'female'], [4, 'male'], [5, 'female'], [6, 'male'], [7, 'female'], [8, 'male'], [9, 'female'], [10, 'male']] + >>> g("[fe|||]male") + [[1, 'female'], [2, 'male'], [3, 'male'], [4, 'male'], [5, 'female'], [6, 'male'], [7, 'male'], [8, 'male'], [9, 'female'], [10, 'male']] + >>> g = lambda p: get_learned_conditioning_prompt_schedules([p], 10, 10)[0] + >>> g("a [b:.5] c") + [[10, 'a b c']] + >>> g("a [b:1.5] c") + [[5, 'a c'], [10, 'a b c']] + """ + + if hires_steps is None or use_old_scheduling: + int_offset = 0 + flt_offset = 0 + steps = base_steps + else: + int_offset = base_steps + flt_offset = 1.0 + steps = hires_steps + + def collect_steps(steps, tree): + res = [steps] + + class CollectSteps(lark.Visitor): + def scheduled(self, tree): + s = tree.children[-2] + v = float(s) + if use_old_scheduling: + v = v*steps if v<1 else v + else: + if "." in s: + v = (v - flt_offset) * steps + else: + v = (v - int_offset) + tree.children[-2] = min(steps, int(v)) + if tree.children[-2] >= 1: + res.append(tree.children[-2]) + + def alternate(self, tree): + res.extend(range(1, steps+1)) + + CollectSteps().visit(tree) + return sorted(set(res)) + + def at_step(step, tree): + class AtStep(lark.Transformer): + def scheduled(self, args): + before, after, _, when, _ = args + yield before or () if step <= when else after + def alternate(self, args): + args = ["" if not arg else arg for arg in args] + yield args[(step - 1) % len(args)] + def start(self, args): + def flatten(x): + if isinstance(x, str): + yield x + else: + for gen in x: + yield from flatten(gen) + return ''.join(flatten(args)) + def plain(self, args): + yield args[0].value + def __default__(self, data, children, meta): + for child in children: + yield child + return AtStep().transform(tree) + + def get_schedule(prompt): + try: + tree = schedule_parser.parse(prompt) + except lark.exceptions.LarkError: + if 0: + import traceback + traceback.print_exc() + return [[steps, prompt]] + return [[t, at_step(t, tree)] for t in collect_steps(steps, tree)] + + promptdict = {prompt: get_schedule(prompt) for prompt in set(prompts)} + return [promptdict[prompt] for prompt in prompts] + + +ScheduledPromptConditioning = namedtuple("ScheduledPromptConditioning", ["end_at_step", "cond"]) + + +class SdConditioning(list): + """ + A list with prompts for stable diffusion's conditioner model. + Can also specify width and height of created image - SDXL needs it. + """ + def __init__(self, prompts, is_negative_prompt=False, width=None, height=None, copy_from=None): + super().__init__() + self.extend(prompts) + + if copy_from is None: + copy_from = prompts + + self.is_negative_prompt = is_negative_prompt or getattr(copy_from, 'is_negative_prompt', False) + self.width = width or getattr(copy_from, 'width', None) + self.height = height or getattr(copy_from, 'height', None) + + + +def get_learned_conditioning(model, prompts: SdConditioning | list[str], steps, hires_steps=None, use_old_scheduling=False): + """converts a list of prompts into a list of prompt schedules - each schedule is a list of ScheduledPromptConditioning, specifying the comdition (cond), + and the sampling step at which this condition is to be replaced by the next one. + + Input: + (model, ['a red crown', 'a [blue:green:5] jeweled crown'], 20) + + Output: + [ + [ + ScheduledPromptConditioning(end_at_step=20, cond=tensor([[-0.3886, 0.0229, -0.0523, ..., -0.4901, -0.3066, 0.0674], ..., [ 0.3317, -0.5102, -0.4066, ..., 0.4119, -0.7647, -1.0160]], device='cuda:0')) + ], + [ + ScheduledPromptConditioning(end_at_step=5, cond=tensor([[-0.3886, 0.0229, -0.0522, ..., -0.4901, -0.3067, 0.0673], ..., [-0.0192, 0.3867, -0.4644, ..., 0.1135, -0.3696, -0.4625]], device='cuda:0')), + ScheduledPromptConditioning(end_at_step=20, cond=tensor([[-0.3886, 0.0229, -0.0522, ..., -0.4901, -0.3067, 0.0673], ..., [-0.7352, -0.4356, -0.7888, ..., 0.6994, -0.4312, -1.2593]], device='cuda:0')) + ] + ] + """ + res = [] + + prompt_schedules = get_learned_conditioning_prompt_schedules(prompts, steps, hires_steps, use_old_scheduling) + cache = {} + + for prompt, prompt_schedule in zip(prompts, prompt_schedules): + + cached = cache.get(prompt, None) + if cached is not None: + res.append(cached) + continue + + texts = SdConditioning([x[1] for x in prompt_schedule], copy_from=prompts) + conds = model.get_learned_conditioning(texts) + + cond_schedule = [] + for i, (end_at_step, _) in enumerate(prompt_schedule): + if isinstance(conds, dict): + cond = {k: v[i] for k, v in conds.items()} + else: + cond = conds[i] + + cond_schedule.append(ScheduledPromptConditioning(end_at_step, cond)) + + cache[prompt] = cond_schedule + res.append(cond_schedule) + + return res + + +re_AND = re.compile(r"\bAND\b") +re_weight = re.compile(r"^((?:\s|.)*?)(?:\s*:\s*([-+]?(?:\d+\.?|\d*\.\d+)))?\s*$") + + +def get_multicond_prompt_list(prompts: SdConditioning | list[str]): + res_indexes = [] + + prompt_indexes = {} + prompt_flat_list = SdConditioning(prompts) + prompt_flat_list.clear() + + for prompt in prompts: + subprompts = re_AND.split(prompt) + + indexes = [] + for subprompt in subprompts: + match = re_weight.search(subprompt) + + text, weight = match.groups() if match is not None else (subprompt, 1.0) + + weight = float(weight) if weight is not None else 1.0 + + index = prompt_indexes.get(text, None) + if index is None: + index = len(prompt_flat_list) + prompt_flat_list.append(text) + prompt_indexes[text] = index + + indexes.append((index, weight)) + + res_indexes.append(indexes) + + return res_indexes, prompt_flat_list, prompt_indexes + + +class ComposableScheduledPromptConditioning: + def __init__(self, schedules, weight=1.0): + self.schedules: list[ScheduledPromptConditioning] = schedules + self.weight: float = weight + + +class MulticondLearnedConditioning: + def __init__(self, shape, batch): + self.shape: tuple = shape # the shape field is needed to send this object to DDIM/PLMS + self.batch: list[list[ComposableScheduledPromptConditioning]] = batch + + +def get_multicond_learned_conditioning(model, prompts, steps, hires_steps=None, use_old_scheduling=False) -> MulticondLearnedConditioning: + """same as get_learned_conditioning, but returns a list of ScheduledPromptConditioning along with the weight objects for each prompt. + For each prompt, the list is obtained by splitting the prompt using the AND separator. + + https://energy-based-model.github.io/Compositional-Visual-Generation-with-Composable-Diffusion-Models/ + """ + + res_indexes, prompt_flat_list, prompt_indexes = get_multicond_prompt_list(prompts) + + learned_conditioning = get_learned_conditioning(model, prompt_flat_list, steps, hires_steps, use_old_scheduling) + + res = [] + for indexes in res_indexes: + res.append([ComposableScheduledPromptConditioning(learned_conditioning[i], weight) for i, weight in indexes]) + + return MulticondLearnedConditioning(shape=(len(prompts),), batch=res) + + +class DictWithShape(dict): + def __init__(self, x, shape=None): + super().__init__() + self.update(x) + + @property + def shape(self): + return self["crossattn"].shape + + +def reconstruct_cond_batch(c: list[list[ScheduledPromptConditioning]], current_step): + param = c[0][0].cond + is_dict = isinstance(param, dict) + + if is_dict: + dict_cond = param + res = {k: torch.zeros((len(c),) + param.shape, device=param.device, dtype=param.dtype) for k, param in dict_cond.items()} + res = DictWithShape(res, (len(c),) + dict_cond['crossattn'].shape) + else: + res = torch.zeros((len(c),) + param.shape, device=param.device, dtype=param.dtype) + + for i, cond_schedule in enumerate(c): + target_index = 0 + for current, entry in enumerate(cond_schedule): + if current_step <= entry.end_at_step: + target_index = current + break + + if is_dict: + for k, param in cond_schedule[target_index].cond.items(): + res[k][i] = param + else: + res[i] = cond_schedule[target_index].cond + + return res + + +def stack_conds(tensors): + # if prompts have wildly different lengths above the limit we'll get tensors of different shapes + # and won't be able to torch.stack them. So this fixes that. + token_count = max([x.shape[0] for x in tensors]) + for i in range(len(tensors)): + if tensors[i].shape[0] != token_count: + last_vector = tensors[i][-1:] + last_vector_repeated = last_vector.repeat([token_count - tensors[i].shape[0], 1]) + tensors[i] = torch.vstack([tensors[i], last_vector_repeated]) + + return torch.stack(tensors) + + + +def reconstruct_multicond_batch(c: MulticondLearnedConditioning, current_step): + param = c.batch[0][0].schedules[0].cond + + tensors = [] + conds_list = [] + + for composable_prompts in c.batch: + conds_for_batch = [] + + for composable_prompt in composable_prompts: + target_index = 0 + for current, entry in enumerate(composable_prompt.schedules): + if current_step <= entry.end_at_step: + target_index = current + break + + conds_for_batch.append((len(tensors), composable_prompt.weight)) + tensors.append(composable_prompt.schedules[target_index].cond) + + conds_list.append(conds_for_batch) + + if isinstance(tensors[0], dict): + keys = list(tensors[0].keys()) + stacked = {k: stack_conds([x[k] for x in tensors]) for k in keys} + stacked = DictWithShape(stacked, stacked['crossattn'].shape) + else: + stacked = stack_conds(tensors).to(device=param.device, dtype=param.dtype) + + return conds_list, stacked + + +re_attention = re.compile(r""" +\\\(| +\\\)| +\\\[| +\\]| +\\\\| +\\| +\(| +\[| +:\s*([+-]?[.\d]+)\s*\)| +\)| +]| +[^\\()\[\]:]+| +: +""", re.X) + +re_break = re.compile(r"\s*\bBREAK\b\s*", re.S) + +def parse_prompt_attention(text): + """ + Parses a string with attention tokens and returns a list of pairs: text and its associated weight. + Accepted tokens are: + (abc) - increases attention to abc by a multiplier of 1.1 + (abc:3.12) - increases attention to abc by a multiplier of 3.12 + [abc] - decreases attention to abc by a multiplier of 1.1 + \( - literal character '(' + \[ - literal character '[' + \) - literal character ')' + \] - literal character ']' + \\ - literal character '\' + anything else - just text + + >>> parse_prompt_attention('normal text') + [['normal text', 1.0]] + >>> parse_prompt_attention('an (important) word') + [['an ', 1.0], ['important', 1.1], [' word', 1.0]] + >>> parse_prompt_attention('(unbalanced') + [['unbalanced', 1.1]] + >>> parse_prompt_attention('\(literal\]') + [['(literal]', 1.0]] + >>> parse_prompt_attention('(unnecessary)(parens)') + [['unnecessaryparens', 1.1]] + >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).') + [['a ', 1.0], + ['house', 1.5730000000000004], + [' ', 1.1], + ['on', 1.0], + [' a ', 1.1], + ['hill', 0.55], + [', sun, ', 1.1], + ['sky', 1.4641000000000006], + ['.', 1.1]] + """ + + res = [] + round_brackets = [] + square_brackets = [] + + round_bracket_multiplier = 1.1 + square_bracket_multiplier = 1 / 1.1 + + def multiply_range(start_position, multiplier): + for p in range(start_position, len(res)): + res[p][1] *= multiplier + + for m in re_attention.finditer(text): + text = m.group(0) + weight = m.group(1) + + if text.startswith('\\'): + res.append([text[1:], 1.0]) + elif text == '(': + round_brackets.append(len(res)) + elif text == '[': + square_brackets.append(len(res)) + elif weight is not None and round_brackets: + multiply_range(round_brackets.pop(), float(weight)) + elif text == ')' and round_brackets: + multiply_range(round_brackets.pop(), round_bracket_multiplier) + elif text == ']' and square_brackets: + multiply_range(square_brackets.pop(), square_bracket_multiplier) + else: + parts = re.split(re_break, text) + for i, part in enumerate(parts): + if i > 0: + res.append(["BREAK", -1]) + res.append([part, 1.0]) + + for pos in round_brackets: + multiply_range(pos, round_bracket_multiplier) + + for pos in square_brackets: + multiply_range(pos, square_bracket_multiplier) + + if len(res) == 0: + res = [["", 1.0]] + + # merge runs of identical weights + i = 0 + while i + 1 < len(res): + if res[i][1] == res[i + 1][1]: + res[i][0] += res[i + 1][0] + res.pop(i + 1) + else: + i += 1 + + return res + +if __name__ == "__main__": + import doctest + doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE) +else: + import torch # doctest faster
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/prompt_parser.py
Add docstrings for utility scripts
import numpy as np philox_m = [0xD2511F53, 0xCD9E8D57] philox_w = [0x9E3779B9, 0xBB67AE85] two_pow32_inv = np.array([2.3283064e-10], dtype=np.float32) two_pow32_inv_2pi = np.array([2.3283064e-10 * 6.2831855], dtype=np.float32) def uint32(x): return x.view(np.uint32).reshape(-1, 2).transpose(1, 0) def philox4_round(counter, key): v1 = uint32(counter[0].astype(np.uint64) * philox_m[0]) v2 = uint32(counter[2].astype(np.uint64) * philox_m[1]) counter[0] = v2[1] ^ counter[1] ^ key[0] counter[1] = v2[0] counter[2] = v1[1] ^ counter[3] ^ key[1] counter[3] = v1[0] def philox4_32(counter, key, rounds=10): for _ in range(rounds - 1): philox4_round(counter, key) key[0] = key[0] + philox_w[0] key[1] = key[1] + philox_w[1] philox4_round(counter, key) return counter def box_muller(x, y): u = x * two_pow32_inv + two_pow32_inv / 2 v = y * two_pow32_inv_2pi + two_pow32_inv_2pi / 2 s = np.sqrt(-2.0 * np.log(u)) r1 = s * np.sin(v) return r1.astype(np.float32) class Generator: def __init__(self, seed): self.seed = seed self.offset = 0 def randn(self, shape): n = 1 for x in shape: n *= x counter = np.zeros((4, n), dtype=np.uint32) counter[0] = self.offset counter[2] = np.arange(n, dtype=np.uint32) # up to 2^32 numbers can be generated - if you want more you'd need to spill into counter[3] self.offset += 1 key = np.empty(n, dtype=np.uint64) key.fill(self.seed) key = uint32(key) g = philox4_32(counter, key) return box_muller(g[0], g[1]).reshape(shape) # discard g[2] and g[3]
--- +++ @@ -1,71 +1,102 @@- -import numpy as np - -philox_m = [0xD2511F53, 0xCD9E8D57] -philox_w = [0x9E3779B9, 0xBB67AE85] - -two_pow32_inv = np.array([2.3283064e-10], dtype=np.float32) -two_pow32_inv_2pi = np.array([2.3283064e-10 * 6.2831855], dtype=np.float32) - - -def uint32(x): - return x.view(np.uint32).reshape(-1, 2).transpose(1, 0) - - -def philox4_round(counter, key): - - v1 = uint32(counter[0].astype(np.uint64) * philox_m[0]) - v2 = uint32(counter[2].astype(np.uint64) * philox_m[1]) - - counter[0] = v2[1] ^ counter[1] ^ key[0] - counter[1] = v2[0] - counter[2] = v1[1] ^ counter[3] ^ key[1] - counter[3] = v1[0] - - -def philox4_32(counter, key, rounds=10): - - for _ in range(rounds - 1): - philox4_round(counter, key) - - key[0] = key[0] + philox_w[0] - key[1] = key[1] + philox_w[1] - - philox4_round(counter, key) - return counter - - -def box_muller(x, y): - u = x * two_pow32_inv + two_pow32_inv / 2 - v = y * two_pow32_inv_2pi + two_pow32_inv_2pi / 2 - - s = np.sqrt(-2.0 * np.log(u)) - - r1 = s * np.sin(v) - return r1.astype(np.float32) - - -class Generator: - - def __init__(self, seed): - self.seed = seed - self.offset = 0 - - def randn(self, shape): - - n = 1 - for x in shape: - n *= x - - counter = np.zeros((4, n), dtype=np.uint32) - counter[0] = self.offset - counter[2] = np.arange(n, dtype=np.uint32) # up to 2^32 numbers can be generated - if you want more you'd need to spill into counter[3] - self.offset += 1 - - key = np.empty(n, dtype=np.uint64) - key.fill(self.seed) - key = uint32(key) - - g = philox4_32(counter, key) - - return box_muller(g[0], g[1]).reshape(shape) # discard g[2] and g[3]+"""RNG imitiating torch cuda randn on CPU. You are welcome. + +Usage: + +``` +g = Generator(seed=0) +print(g.randn(shape=(3, 4))) +``` + +Expected output: +``` +[[-0.92466259 -0.42534415 -2.6438457 0.14518388] + [-0.12086647 -0.57972564 -0.62285122 -0.32838709] + [-1.07454231 -0.36314407 -1.67105067 2.26550497]] +``` +""" + +import numpy as np + +philox_m = [0xD2511F53, 0xCD9E8D57] +philox_w = [0x9E3779B9, 0xBB67AE85] + +two_pow32_inv = np.array([2.3283064e-10], dtype=np.float32) +two_pow32_inv_2pi = np.array([2.3283064e-10 * 6.2831855], dtype=np.float32) + + +def uint32(x): + """Converts (N,) np.uint64 array into (2, N) np.unit32 array.""" + return x.view(np.uint32).reshape(-1, 2).transpose(1, 0) + + +def philox4_round(counter, key): + """A single round of the Philox 4x32 random number generator.""" + + v1 = uint32(counter[0].astype(np.uint64) * philox_m[0]) + v2 = uint32(counter[2].astype(np.uint64) * philox_m[1]) + + counter[0] = v2[1] ^ counter[1] ^ key[0] + counter[1] = v2[0] + counter[2] = v1[1] ^ counter[3] ^ key[1] + counter[3] = v1[0] + + +def philox4_32(counter, key, rounds=10): + """Generates 32-bit random numbers using the Philox 4x32 random number generator. + + Parameters: + counter (numpy.ndarray): A 4xN array of 32-bit integers representing the counter values (offset into generation). + key (numpy.ndarray): A 2xN array of 32-bit integers representing the key values (seed). + rounds (int): The number of rounds to perform. + + Returns: + numpy.ndarray: A 4xN array of 32-bit integers containing the generated random numbers. + """ + + for _ in range(rounds - 1): + philox4_round(counter, key) + + key[0] = key[0] + philox_w[0] + key[1] = key[1] + philox_w[1] + + philox4_round(counter, key) + return counter + + +def box_muller(x, y): + """Returns just the first out of two numbers generated by Box–Muller transform algorithm.""" + u = x * two_pow32_inv + two_pow32_inv / 2 + v = y * two_pow32_inv_2pi + two_pow32_inv_2pi / 2 + + s = np.sqrt(-2.0 * np.log(u)) + + r1 = s * np.sin(v) + return r1.astype(np.float32) + + +class Generator: + """RNG that produces same outputs as torch.randn(..., device='cuda') on CPU""" + + def __init__(self, seed): + self.seed = seed + self.offset = 0 + + def randn(self, shape): + """Generate a sequence of n standard normal random variables using the Philox 4x32 random number generator and the Box-Muller transform.""" + + n = 1 + for x in shape: + n *= x + + counter = np.zeros((4, n), dtype=np.uint32) + counter[0] = self.offset + counter[2] = np.arange(n, dtype=np.uint32) # up to 2^32 numbers can be generated - if you want more you'd need to spill into counter[3] + self.offset += 1 + + key = np.empty(n, dtype=np.uint64) + key.fill(self.seed) + key = uint32(key) + + g = philox4_32(counter, key) + + return box_muller(g[0], g[1]).reshape(shape) # discard g[2] and g[3]
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/rng_philox.py
Write docstrings for utility functions
from __future__ import annotations import torch import sgm.models.diffusion import sgm.modules.diffusionmodules.denoiser_scaling import sgm.modules.diffusionmodules.discretizer from modules import devices, shared, prompt_parser from modules import torch_utils def get_learned_conditioning(self: sgm.models.diffusion.DiffusionEngine, batch: prompt_parser.SdConditioning | list[str]): for embedder in self.conditioner.embedders: embedder.ucg_rate = 0.0 width = getattr(batch, 'width', 1024) or 1024 height = getattr(batch, 'height', 1024) or 1024 is_negative_prompt = getattr(batch, 'is_negative_prompt', False) aesthetic_score = shared.opts.sdxl_refiner_low_aesthetic_score if is_negative_prompt else shared.opts.sdxl_refiner_high_aesthetic_score devices_args = dict(device=devices.device, dtype=devices.dtype) sdxl_conds = { "txt": batch, "original_size_as_tuple": torch.tensor([height, width], **devices_args).repeat(len(batch), 1), "crop_coords_top_left": torch.tensor([shared.opts.sdxl_crop_top, shared.opts.sdxl_crop_left], **devices_args).repeat(len(batch), 1), "target_size_as_tuple": torch.tensor([height, width], **devices_args).repeat(len(batch), 1), "aesthetic_score": torch.tensor([aesthetic_score], **devices_args).repeat(len(batch), 1), } force_zero_negative_prompt = is_negative_prompt and all(x == '' for x in batch) c = self.conditioner(sdxl_conds, force_zero_embeddings=['txt'] if force_zero_negative_prompt else []) return c def apply_model(self: sgm.models.diffusion.DiffusionEngine, x, t, cond): if self.is_sdxl_inpaint: x = torch.cat([x] + cond['c_concat'], dim=1) return self.model(x, t, cond) def get_first_stage_encoding(self, x): # SDXL's encode_first_stage does everything so get_first_stage_encoding is just there for compatibility return x sgm.models.diffusion.DiffusionEngine.get_learned_conditioning = get_learned_conditioning sgm.models.diffusion.DiffusionEngine.apply_model = apply_model sgm.models.diffusion.DiffusionEngine.get_first_stage_encoding = get_first_stage_encoding def encode_embedding_init_text(self: sgm.modules.GeneralConditioner, init_text, nvpt): res = [] for embedder in [embedder for embedder in self.embedders if hasattr(embedder, 'encode_embedding_init_text')]: encoded = embedder.encode_embedding_init_text(init_text, nvpt) res.append(encoded) return torch.cat(res, dim=1) def tokenize(self: sgm.modules.GeneralConditioner, texts): for embedder in [embedder for embedder in self.embedders if hasattr(embedder, 'tokenize')]: return embedder.tokenize(texts) raise AssertionError('no tokenizer available') def process_texts(self, texts): for embedder in [embedder for embedder in self.embedders if hasattr(embedder, 'process_texts')]: return embedder.process_texts(texts) def get_target_prompt_token_count(self, token_count): for embedder in [embedder for embedder in self.embedders if hasattr(embedder, 'get_target_prompt_token_count')]: return embedder.get_target_prompt_token_count(token_count) # those additions to GeneralConditioner make it possible to use it as model.cond_stage_model from SD1.5 in exist sgm.modules.GeneralConditioner.encode_embedding_init_text = encode_embedding_init_text sgm.modules.GeneralConditioner.tokenize = tokenize sgm.modules.GeneralConditioner.process_texts = process_texts sgm.modules.GeneralConditioner.get_target_prompt_token_count = get_target_prompt_token_count def extend_sdxl(model): dtype = torch_utils.get_param(model.model.diffusion_model).dtype model.model.diffusion_model.dtype = dtype model.model.conditioning_key = 'crossattn' model.cond_stage_key = 'txt' # model.cond_stage_model will be set in sd_hijack model.parameterization = "v" if isinstance(model.denoiser.scaling, sgm.modules.diffusionmodules.denoiser_scaling.VScaling) else "eps" discretization = sgm.modules.diffusionmodules.discretizer.LegacyDDPMDiscretization() model.alphas_cumprod = torch.asarray(discretization.alphas_cumprod, device=devices.device, dtype=torch.float32) model.conditioner.wrapped = torch.nn.Module() sgm.modules.attention.print = shared.ldm_print sgm.modules.diffusionmodules.model.print = shared.ldm_print sgm.modules.diffusionmodules.openaimodel.print = shared.ldm_print sgm.modules.encoders.modules.print = shared.ldm_print # this gets the code to load the vanilla attention that we override sgm.modules.attention.SDP_IS_AVAILABLE = True sgm.modules.attention.XFORMERS_IS_AVAILABLE = False
--- +++ @@ -1,111 +1,114 @@-from __future__ import annotations - -import torch - -import sgm.models.diffusion -import sgm.modules.diffusionmodules.denoiser_scaling -import sgm.modules.diffusionmodules.discretizer -from modules import devices, shared, prompt_parser -from modules import torch_utils - - -def get_learned_conditioning(self: sgm.models.diffusion.DiffusionEngine, batch: prompt_parser.SdConditioning | list[str]): - for embedder in self.conditioner.embedders: - embedder.ucg_rate = 0.0 - - width = getattr(batch, 'width', 1024) or 1024 - height = getattr(batch, 'height', 1024) or 1024 - is_negative_prompt = getattr(batch, 'is_negative_prompt', False) - aesthetic_score = shared.opts.sdxl_refiner_low_aesthetic_score if is_negative_prompt else shared.opts.sdxl_refiner_high_aesthetic_score - - devices_args = dict(device=devices.device, dtype=devices.dtype) - - sdxl_conds = { - "txt": batch, - "original_size_as_tuple": torch.tensor([height, width], **devices_args).repeat(len(batch), 1), - "crop_coords_top_left": torch.tensor([shared.opts.sdxl_crop_top, shared.opts.sdxl_crop_left], **devices_args).repeat(len(batch), 1), - "target_size_as_tuple": torch.tensor([height, width], **devices_args).repeat(len(batch), 1), - "aesthetic_score": torch.tensor([aesthetic_score], **devices_args).repeat(len(batch), 1), - } - - force_zero_negative_prompt = is_negative_prompt and all(x == '' for x in batch) - c = self.conditioner(sdxl_conds, force_zero_embeddings=['txt'] if force_zero_negative_prompt else []) - - return c - - -def apply_model(self: sgm.models.diffusion.DiffusionEngine, x, t, cond): - if self.is_sdxl_inpaint: - x = torch.cat([x] + cond['c_concat'], dim=1) - - return self.model(x, t, cond) - - -def get_first_stage_encoding(self, x): # SDXL's encode_first_stage does everything so get_first_stage_encoding is just there for compatibility - return x - - -sgm.models.diffusion.DiffusionEngine.get_learned_conditioning = get_learned_conditioning -sgm.models.diffusion.DiffusionEngine.apply_model = apply_model -sgm.models.diffusion.DiffusionEngine.get_first_stage_encoding = get_first_stage_encoding - - -def encode_embedding_init_text(self: sgm.modules.GeneralConditioner, init_text, nvpt): - res = [] - - for embedder in [embedder for embedder in self.embedders if hasattr(embedder, 'encode_embedding_init_text')]: - encoded = embedder.encode_embedding_init_text(init_text, nvpt) - res.append(encoded) - - return torch.cat(res, dim=1) - - -def tokenize(self: sgm.modules.GeneralConditioner, texts): - for embedder in [embedder for embedder in self.embedders if hasattr(embedder, 'tokenize')]: - return embedder.tokenize(texts) - - raise AssertionError('no tokenizer available') - - - -def process_texts(self, texts): - for embedder in [embedder for embedder in self.embedders if hasattr(embedder, 'process_texts')]: - return embedder.process_texts(texts) - - -def get_target_prompt_token_count(self, token_count): - for embedder in [embedder for embedder in self.embedders if hasattr(embedder, 'get_target_prompt_token_count')]: - return embedder.get_target_prompt_token_count(token_count) - - -# those additions to GeneralConditioner make it possible to use it as model.cond_stage_model from SD1.5 in exist -sgm.modules.GeneralConditioner.encode_embedding_init_text = encode_embedding_init_text -sgm.modules.GeneralConditioner.tokenize = tokenize -sgm.modules.GeneralConditioner.process_texts = process_texts -sgm.modules.GeneralConditioner.get_target_prompt_token_count = get_target_prompt_token_count - - -def extend_sdxl(model): - - dtype = torch_utils.get_param(model.model.diffusion_model).dtype - model.model.diffusion_model.dtype = dtype - model.model.conditioning_key = 'crossattn' - model.cond_stage_key = 'txt' - # model.cond_stage_model will be set in sd_hijack - - model.parameterization = "v" if isinstance(model.denoiser.scaling, sgm.modules.diffusionmodules.denoiser_scaling.VScaling) else "eps" - - discretization = sgm.modules.diffusionmodules.discretizer.LegacyDDPMDiscretization() - model.alphas_cumprod = torch.asarray(discretization.alphas_cumprod, device=devices.device, dtype=torch.float32) - - model.conditioner.wrapped = torch.nn.Module() - - -sgm.modules.attention.print = shared.ldm_print -sgm.modules.diffusionmodules.model.print = shared.ldm_print -sgm.modules.diffusionmodules.openaimodel.print = shared.ldm_print -sgm.modules.encoders.modules.print = shared.ldm_print - -# this gets the code to load the vanilla attention that we override -sgm.modules.attention.SDP_IS_AVAILABLE = True -sgm.modules.attention.XFORMERS_IS_AVAILABLE = False+from __future__ import annotations + +import torch + +import sgm.models.diffusion +import sgm.modules.diffusionmodules.denoiser_scaling +import sgm.modules.diffusionmodules.discretizer +from modules import devices, shared, prompt_parser +from modules import torch_utils + + +def get_learned_conditioning(self: sgm.models.diffusion.DiffusionEngine, batch: prompt_parser.SdConditioning | list[str]): + for embedder in self.conditioner.embedders: + embedder.ucg_rate = 0.0 + + width = getattr(batch, 'width', 1024) or 1024 + height = getattr(batch, 'height', 1024) or 1024 + is_negative_prompt = getattr(batch, 'is_negative_prompt', False) + aesthetic_score = shared.opts.sdxl_refiner_low_aesthetic_score if is_negative_prompt else shared.opts.sdxl_refiner_high_aesthetic_score + + devices_args = dict(device=devices.device, dtype=devices.dtype) + + sdxl_conds = { + "txt": batch, + "original_size_as_tuple": torch.tensor([height, width], **devices_args).repeat(len(batch), 1), + "crop_coords_top_left": torch.tensor([shared.opts.sdxl_crop_top, shared.opts.sdxl_crop_left], **devices_args).repeat(len(batch), 1), + "target_size_as_tuple": torch.tensor([height, width], **devices_args).repeat(len(batch), 1), + "aesthetic_score": torch.tensor([aesthetic_score], **devices_args).repeat(len(batch), 1), + } + + force_zero_negative_prompt = is_negative_prompt and all(x == '' for x in batch) + c = self.conditioner(sdxl_conds, force_zero_embeddings=['txt'] if force_zero_negative_prompt else []) + + return c + + +def apply_model(self: sgm.models.diffusion.DiffusionEngine, x, t, cond): + """WARNING: This function is called once per denoising iteration. DO NOT add + expensive functionc calls such as `model.state_dict`. """ + if self.is_sdxl_inpaint: + x = torch.cat([x] + cond['c_concat'], dim=1) + + return self.model(x, t, cond) + + +def get_first_stage_encoding(self, x): # SDXL's encode_first_stage does everything so get_first_stage_encoding is just there for compatibility + return x + + +sgm.models.diffusion.DiffusionEngine.get_learned_conditioning = get_learned_conditioning +sgm.models.diffusion.DiffusionEngine.apply_model = apply_model +sgm.models.diffusion.DiffusionEngine.get_first_stage_encoding = get_first_stage_encoding + + +def encode_embedding_init_text(self: sgm.modules.GeneralConditioner, init_text, nvpt): + res = [] + + for embedder in [embedder for embedder in self.embedders if hasattr(embedder, 'encode_embedding_init_text')]: + encoded = embedder.encode_embedding_init_text(init_text, nvpt) + res.append(encoded) + + return torch.cat(res, dim=1) + + +def tokenize(self: sgm.modules.GeneralConditioner, texts): + for embedder in [embedder for embedder in self.embedders if hasattr(embedder, 'tokenize')]: + return embedder.tokenize(texts) + + raise AssertionError('no tokenizer available') + + + +def process_texts(self, texts): + for embedder in [embedder for embedder in self.embedders if hasattr(embedder, 'process_texts')]: + return embedder.process_texts(texts) + + +def get_target_prompt_token_count(self, token_count): + for embedder in [embedder for embedder in self.embedders if hasattr(embedder, 'get_target_prompt_token_count')]: + return embedder.get_target_prompt_token_count(token_count) + + +# those additions to GeneralConditioner make it possible to use it as model.cond_stage_model from SD1.5 in exist +sgm.modules.GeneralConditioner.encode_embedding_init_text = encode_embedding_init_text +sgm.modules.GeneralConditioner.tokenize = tokenize +sgm.modules.GeneralConditioner.process_texts = process_texts +sgm.modules.GeneralConditioner.get_target_prompt_token_count = get_target_prompt_token_count + + +def extend_sdxl(model): + """this adds a bunch of parameters to make SDXL model look a bit more like SD1.5 to the rest of the codebase.""" + + dtype = torch_utils.get_param(model.model.diffusion_model).dtype + model.model.diffusion_model.dtype = dtype + model.model.conditioning_key = 'crossattn' + model.cond_stage_key = 'txt' + # model.cond_stage_model will be set in sd_hijack + + model.parameterization = "v" if isinstance(model.denoiser.scaling, sgm.modules.diffusionmodules.denoiser_scaling.VScaling) else "eps" + + discretization = sgm.modules.diffusionmodules.discretizer.LegacyDDPMDiscretization() + model.alphas_cumprod = torch.asarray(discretization.alphas_cumprod, device=devices.device, dtype=torch.float32) + + model.conditioner.wrapped = torch.nn.Module() + + +sgm.modules.attention.print = shared.ldm_print +sgm.modules.diffusionmodules.model.print = shared.ldm_print +sgm.modules.diffusionmodules.openaimodel.print = shared.ldm_print +sgm.modules.encoders.modules.print = shared.ldm_print + +# this gets the code to load the vanilla attention that we override +sgm.modules.attention.SDP_IS_AVAILABLE = True +sgm.modules.attention.XFORMERS_IS_AVAILABLE = False
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_models_xl.py
Add docstrings to improve readability
import torch from modules import prompt_parser, sd_samplers_common from modules.shared import opts, state import modules.shared as shared from modules.script_callbacks import CFGDenoiserParams, cfg_denoiser_callback from modules.script_callbacks import CFGDenoisedParams, cfg_denoised_callback from modules.script_callbacks import AfterCFGCallbackParams, cfg_after_cfg_callback def catenate_conds(conds): if not isinstance(conds[0], dict): return torch.cat(conds) return {key: torch.cat([x[key] for x in conds]) for key in conds[0].keys()} def subscript_cond(cond, a, b): if not isinstance(cond, dict): return cond[a:b] return {key: vec[a:b] for key, vec in cond.items()} def pad_cond(tensor, repeats, empty): if not isinstance(tensor, dict): return torch.cat([tensor, empty.repeat((tensor.shape[0], repeats, 1))], axis=1) tensor['crossattn'] = pad_cond(tensor['crossattn'], repeats, empty) return tensor class CFGDenoiser(torch.nn.Module): def __init__(self, sampler): super().__init__() self.model_wrap = None self.mask = None self.nmask = None self.init_latent = None self.steps = None """number of steps as specified by user in UI""" self.total_steps = None """expected number of calls to denoiser calculated from self.steps and specifics of the selected sampler""" self.step = 0 self.image_cfg_scale = None self.padded_cond_uncond = False self.padded_cond_uncond_v0 = False self.sampler = sampler self.model_wrap = None self.p = None self.cond_scale_miltiplier = 1.0 self.need_last_noise_uncond = False self.last_noise_uncond = None # NOTE: masking before denoising can cause the original latents to be oversmoothed # as the original latents do not have noise self.mask_before_denoising = False @property def inner_model(self): raise NotImplementedError() def combine_denoised(self, x_out, conds_list, uncond, cond_scale): denoised_uncond = x_out[-uncond.shape[0]:] denoised = torch.clone(denoised_uncond) for i, conds in enumerate(conds_list): for cond_index, weight in conds: denoised[i] += (x_out[cond_index] - denoised_uncond[i]) * (weight * cond_scale) return denoised def combine_denoised_for_edit_model(self, x_out, cond_scale): out_cond, out_img_cond, out_uncond = x_out.chunk(3) denoised = out_uncond + cond_scale * (out_cond - out_img_cond) + self.image_cfg_scale * (out_img_cond - out_uncond) return denoised def get_pred_x0(self, x_in, x_out, sigma): return x_out def update_inner_model(self): self.model_wrap = None c, uc = self.p.get_conds() self.sampler.sampler_extra_args['cond'] = c self.sampler.sampler_extra_args['uncond'] = uc def pad_cond_uncond(self, cond, uncond): empty = shared.sd_model.cond_stage_model_empty_prompt num_repeats = (cond.shape[1] - uncond.shape[1]) // empty.shape[1] if num_repeats < 0: cond = pad_cond(cond, -num_repeats, empty) self.padded_cond_uncond = True elif num_repeats > 0: uncond = pad_cond(uncond, num_repeats, empty) self.padded_cond_uncond = True return cond, uncond def pad_cond_uncond_v0(self, cond, uncond): is_dict_cond = isinstance(uncond, dict) uncond_vec = uncond['crossattn'] if is_dict_cond else uncond if uncond_vec.shape[1] < cond.shape[1]: last_vector = uncond_vec[:, -1:] last_vector_repeated = last_vector.repeat([1, cond.shape[1] - uncond_vec.shape[1], 1]) uncond_vec = torch.hstack([uncond_vec, last_vector_repeated]) self.padded_cond_uncond_v0 = True elif uncond_vec.shape[1] > cond.shape[1]: uncond_vec = uncond_vec[:, :cond.shape[1]] self.padded_cond_uncond_v0 = True if is_dict_cond: uncond['crossattn'] = uncond_vec else: uncond = uncond_vec return cond, uncond def forward(self, x, sigma, uncond, cond, cond_scale, s_min_uncond, image_cond): if state.interrupted or state.skipped: raise sd_samplers_common.InterruptedException if sd_samplers_common.apply_refiner(self, sigma): cond = self.sampler.sampler_extra_args['cond'] uncond = self.sampler.sampler_extra_args['uncond'] # at self.image_cfg_scale == 1.0 produced results for edit model are the same as with normal sampling, # so is_edit_model is set to False to support AND composition. is_edit_model = shared.sd_model.cond_stage_key == "edit" and self.image_cfg_scale is not None and self.image_cfg_scale != 1.0 conds_list, tensor = prompt_parser.reconstruct_multicond_batch(cond, self.step) uncond = prompt_parser.reconstruct_cond_batch(uncond, self.step) assert not is_edit_model or all(len(conds) == 1 for conds in conds_list), "AND is not supported for InstructPix2Pix checkpoint (unless using Image CFG scale = 1.0)" # If we use masks, blending between the denoised and original latent images occurs here. def apply_blend(current_latent): blended_latent = current_latent * self.nmask + self.init_latent * self.mask if self.p.scripts is not None: from modules import scripts mba = scripts.MaskBlendArgs(current_latent, self.nmask, self.init_latent, self.mask, blended_latent, denoiser=self, sigma=sigma) self.p.scripts.on_mask_blend(self.p, mba) blended_latent = mba.blended_latent return blended_latent # Blend in the original latents (before) if self.mask_before_denoising and self.mask is not None: x = apply_blend(x) batch_size = len(conds_list) repeats = [len(conds_list[i]) for i in range(batch_size)] if shared.sd_model.model.conditioning_key == "crossattn-adm": image_uncond = torch.zeros_like(image_cond) make_condition_dict = lambda c_crossattn, c_adm: {"c_crossattn": [c_crossattn], "c_adm": c_adm} else: image_uncond = image_cond if isinstance(uncond, dict): make_condition_dict = lambda c_crossattn, c_concat: {**c_crossattn, "c_concat": [c_concat]} else: make_condition_dict = lambda c_crossattn, c_concat: {"c_crossattn": [c_crossattn], "c_concat": [c_concat]} if not is_edit_model: x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x]) sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma]) image_cond_in = torch.cat([torch.stack([image_cond[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [image_uncond]) else: x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x] + [x]) sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma] + [sigma]) image_cond_in = torch.cat([torch.stack([image_cond[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [image_uncond] + [torch.zeros_like(self.init_latent)]) denoiser_params = CFGDenoiserParams(x_in, image_cond_in, sigma_in, state.sampling_step, state.sampling_steps, tensor, uncond, self) cfg_denoiser_callback(denoiser_params) x_in = denoiser_params.x image_cond_in = denoiser_params.image_cond sigma_in = denoiser_params.sigma tensor = denoiser_params.text_cond uncond = denoiser_params.text_uncond skip_uncond = False if shared.opts.skip_early_cond != 0. and self.step / self.total_steps <= shared.opts.skip_early_cond: skip_uncond = True self.p.extra_generation_params["Skip Early CFG"] = shared.opts.skip_early_cond elif (self.step % 2 or shared.opts.s_min_uncond_all) and s_min_uncond > 0 and sigma[0] < s_min_uncond and not is_edit_model: skip_uncond = True self.p.extra_generation_params["NGMS"] = s_min_uncond if shared.opts.s_min_uncond_all: self.p.extra_generation_params["NGMS all steps"] = shared.opts.s_min_uncond_all if skip_uncond: x_in = x_in[:-batch_size] sigma_in = sigma_in[:-batch_size] self.padded_cond_uncond = False self.padded_cond_uncond_v0 = False if shared.opts.pad_cond_uncond_v0 and tensor.shape[1] != uncond.shape[1]: tensor, uncond = self.pad_cond_uncond_v0(tensor, uncond) elif shared.opts.pad_cond_uncond and tensor.shape[1] != uncond.shape[1]: tensor, uncond = self.pad_cond_uncond(tensor, uncond) if tensor.shape[1] == uncond.shape[1] or skip_uncond: if is_edit_model: cond_in = catenate_conds([tensor, uncond, uncond]) elif skip_uncond: cond_in = tensor else: cond_in = catenate_conds([tensor, uncond]) if shared.opts.batch_cond_uncond: x_out = self.inner_model(x_in, sigma_in, cond=make_condition_dict(cond_in, image_cond_in)) else: x_out = torch.zeros_like(x_in) for batch_offset in range(0, x_out.shape[0], batch_size): a = batch_offset b = a + batch_size x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], cond=make_condition_dict(subscript_cond(cond_in, a, b), image_cond_in[a:b])) else: x_out = torch.zeros_like(x_in) batch_size = batch_size*2 if shared.opts.batch_cond_uncond else batch_size for batch_offset in range(0, tensor.shape[0], batch_size): a = batch_offset b = min(a + batch_size, tensor.shape[0]) if not is_edit_model: c_crossattn = subscript_cond(tensor, a, b) else: c_crossattn = torch.cat([tensor[a:b]], uncond) x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], cond=make_condition_dict(c_crossattn, image_cond_in[a:b])) if not skip_uncond: x_out[-uncond.shape[0]:] = self.inner_model(x_in[-uncond.shape[0]:], sigma_in[-uncond.shape[0]:], cond=make_condition_dict(uncond, image_cond_in[-uncond.shape[0]:])) denoised_image_indexes = [x[0][0] for x in conds_list] if skip_uncond: fake_uncond = torch.cat([x_out[i:i+1] for i in denoised_image_indexes]) x_out = torch.cat([x_out, fake_uncond]) # we skipped uncond denoising, so we put cond-denoised image to where the uncond-denoised image should be denoised_params = CFGDenoisedParams(x_out, state.sampling_step, state.sampling_steps, self.inner_model) cfg_denoised_callback(denoised_params) if self.need_last_noise_uncond: self.last_noise_uncond = torch.clone(x_out[-uncond.shape[0]:]) if is_edit_model: denoised = self.combine_denoised_for_edit_model(x_out, cond_scale * self.cond_scale_miltiplier) elif skip_uncond: denoised = self.combine_denoised(x_out, conds_list, uncond, 1.0) else: denoised = self.combine_denoised(x_out, conds_list, uncond, cond_scale * self.cond_scale_miltiplier) # Blend in the original latents (after) if not self.mask_before_denoising and self.mask is not None: denoised = apply_blend(denoised) self.sampler.last_latent = self.get_pred_x0(torch.cat([x_in[i:i + 1] for i in denoised_image_indexes]), torch.cat([x_out[i:i + 1] for i in denoised_image_indexes]), sigma) if opts.live_preview_content == "Prompt": preview = self.sampler.last_latent elif opts.live_preview_content == "Negative prompt": preview = self.get_pred_x0(x_in[-uncond.shape[0]:], x_out[-uncond.shape[0]:], sigma) else: preview = self.get_pred_x0(torch.cat([x_in[i:i+1] for i in denoised_image_indexes]), torch.cat([denoised[i:i+1] for i in denoised_image_indexes]), sigma) sd_samplers_common.store_latent(preview) after_cfg_callback_params = AfterCFGCallbackParams(denoised, state.sampling_step, state.sampling_steps) cfg_after_cfg_callback(after_cfg_callback_params) denoised = after_cfg_callback_params.x self.step += 1 return denoised
--- +++ @@ -1,283 +1,312 @@-import torch -from modules import prompt_parser, sd_samplers_common - -from modules.shared import opts, state -import modules.shared as shared -from modules.script_callbacks import CFGDenoiserParams, cfg_denoiser_callback -from modules.script_callbacks import CFGDenoisedParams, cfg_denoised_callback -from modules.script_callbacks import AfterCFGCallbackParams, cfg_after_cfg_callback - - -def catenate_conds(conds): - if not isinstance(conds[0], dict): - return torch.cat(conds) - - return {key: torch.cat([x[key] for x in conds]) for key in conds[0].keys()} - - -def subscript_cond(cond, a, b): - if not isinstance(cond, dict): - return cond[a:b] - - return {key: vec[a:b] for key, vec in cond.items()} - - -def pad_cond(tensor, repeats, empty): - if not isinstance(tensor, dict): - return torch.cat([tensor, empty.repeat((tensor.shape[0], repeats, 1))], axis=1) - - tensor['crossattn'] = pad_cond(tensor['crossattn'], repeats, empty) - return tensor - - -class CFGDenoiser(torch.nn.Module): - - def __init__(self, sampler): - super().__init__() - self.model_wrap = None - self.mask = None - self.nmask = None - self.init_latent = None - self.steps = None - """number of steps as specified by user in UI""" - - self.total_steps = None - """expected number of calls to denoiser calculated from self.steps and specifics of the selected sampler""" - - self.step = 0 - self.image_cfg_scale = None - self.padded_cond_uncond = False - self.padded_cond_uncond_v0 = False - self.sampler = sampler - self.model_wrap = None - self.p = None - - self.cond_scale_miltiplier = 1.0 - - self.need_last_noise_uncond = False - self.last_noise_uncond = None - - # NOTE: masking before denoising can cause the original latents to be oversmoothed - # as the original latents do not have noise - self.mask_before_denoising = False - - @property - def inner_model(self): - raise NotImplementedError() - - def combine_denoised(self, x_out, conds_list, uncond, cond_scale): - denoised_uncond = x_out[-uncond.shape[0]:] - denoised = torch.clone(denoised_uncond) - - for i, conds in enumerate(conds_list): - for cond_index, weight in conds: - denoised[i] += (x_out[cond_index] - denoised_uncond[i]) * (weight * cond_scale) - - return denoised - - def combine_denoised_for_edit_model(self, x_out, cond_scale): - out_cond, out_img_cond, out_uncond = x_out.chunk(3) - denoised = out_uncond + cond_scale * (out_cond - out_img_cond) + self.image_cfg_scale * (out_img_cond - out_uncond) - - return denoised - - def get_pred_x0(self, x_in, x_out, sigma): - return x_out - - def update_inner_model(self): - self.model_wrap = None - - c, uc = self.p.get_conds() - self.sampler.sampler_extra_args['cond'] = c - self.sampler.sampler_extra_args['uncond'] = uc - - def pad_cond_uncond(self, cond, uncond): - empty = shared.sd_model.cond_stage_model_empty_prompt - num_repeats = (cond.shape[1] - uncond.shape[1]) // empty.shape[1] - - if num_repeats < 0: - cond = pad_cond(cond, -num_repeats, empty) - self.padded_cond_uncond = True - elif num_repeats > 0: - uncond = pad_cond(uncond, num_repeats, empty) - self.padded_cond_uncond = True - - return cond, uncond - - def pad_cond_uncond_v0(self, cond, uncond): - - is_dict_cond = isinstance(uncond, dict) - uncond_vec = uncond['crossattn'] if is_dict_cond else uncond - - if uncond_vec.shape[1] < cond.shape[1]: - last_vector = uncond_vec[:, -1:] - last_vector_repeated = last_vector.repeat([1, cond.shape[1] - uncond_vec.shape[1], 1]) - uncond_vec = torch.hstack([uncond_vec, last_vector_repeated]) - self.padded_cond_uncond_v0 = True - elif uncond_vec.shape[1] > cond.shape[1]: - uncond_vec = uncond_vec[:, :cond.shape[1]] - self.padded_cond_uncond_v0 = True - - if is_dict_cond: - uncond['crossattn'] = uncond_vec - else: - uncond = uncond_vec - - return cond, uncond - - def forward(self, x, sigma, uncond, cond, cond_scale, s_min_uncond, image_cond): - if state.interrupted or state.skipped: - raise sd_samplers_common.InterruptedException - - if sd_samplers_common.apply_refiner(self, sigma): - cond = self.sampler.sampler_extra_args['cond'] - uncond = self.sampler.sampler_extra_args['uncond'] - - # at self.image_cfg_scale == 1.0 produced results for edit model are the same as with normal sampling, - # so is_edit_model is set to False to support AND composition. - is_edit_model = shared.sd_model.cond_stage_key == "edit" and self.image_cfg_scale is not None and self.image_cfg_scale != 1.0 - - conds_list, tensor = prompt_parser.reconstruct_multicond_batch(cond, self.step) - uncond = prompt_parser.reconstruct_cond_batch(uncond, self.step) - - assert not is_edit_model or all(len(conds) == 1 for conds in conds_list), "AND is not supported for InstructPix2Pix checkpoint (unless using Image CFG scale = 1.0)" - - # If we use masks, blending between the denoised and original latent images occurs here. - def apply_blend(current_latent): - blended_latent = current_latent * self.nmask + self.init_latent * self.mask - - if self.p.scripts is not None: - from modules import scripts - mba = scripts.MaskBlendArgs(current_latent, self.nmask, self.init_latent, self.mask, blended_latent, denoiser=self, sigma=sigma) - self.p.scripts.on_mask_blend(self.p, mba) - blended_latent = mba.blended_latent - - return blended_latent - - # Blend in the original latents (before) - if self.mask_before_denoising and self.mask is not None: - x = apply_blend(x) - - batch_size = len(conds_list) - repeats = [len(conds_list[i]) for i in range(batch_size)] - - if shared.sd_model.model.conditioning_key == "crossattn-adm": - image_uncond = torch.zeros_like(image_cond) - make_condition_dict = lambda c_crossattn, c_adm: {"c_crossattn": [c_crossattn], "c_adm": c_adm} - else: - image_uncond = image_cond - if isinstance(uncond, dict): - make_condition_dict = lambda c_crossattn, c_concat: {**c_crossattn, "c_concat": [c_concat]} - else: - make_condition_dict = lambda c_crossattn, c_concat: {"c_crossattn": [c_crossattn], "c_concat": [c_concat]} - - if not is_edit_model: - x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x]) - sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma]) - image_cond_in = torch.cat([torch.stack([image_cond[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [image_uncond]) - else: - x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x] + [x]) - sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma] + [sigma]) - image_cond_in = torch.cat([torch.stack([image_cond[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [image_uncond] + [torch.zeros_like(self.init_latent)]) - - denoiser_params = CFGDenoiserParams(x_in, image_cond_in, sigma_in, state.sampling_step, state.sampling_steps, tensor, uncond, self) - cfg_denoiser_callback(denoiser_params) - x_in = denoiser_params.x - image_cond_in = denoiser_params.image_cond - sigma_in = denoiser_params.sigma - tensor = denoiser_params.text_cond - uncond = denoiser_params.text_uncond - skip_uncond = False - - if shared.opts.skip_early_cond != 0. and self.step / self.total_steps <= shared.opts.skip_early_cond: - skip_uncond = True - self.p.extra_generation_params["Skip Early CFG"] = shared.opts.skip_early_cond - elif (self.step % 2 or shared.opts.s_min_uncond_all) and s_min_uncond > 0 and sigma[0] < s_min_uncond and not is_edit_model: - skip_uncond = True - self.p.extra_generation_params["NGMS"] = s_min_uncond - if shared.opts.s_min_uncond_all: - self.p.extra_generation_params["NGMS all steps"] = shared.opts.s_min_uncond_all - - if skip_uncond: - x_in = x_in[:-batch_size] - sigma_in = sigma_in[:-batch_size] - - self.padded_cond_uncond = False - self.padded_cond_uncond_v0 = False - if shared.opts.pad_cond_uncond_v0 and tensor.shape[1] != uncond.shape[1]: - tensor, uncond = self.pad_cond_uncond_v0(tensor, uncond) - elif shared.opts.pad_cond_uncond and tensor.shape[1] != uncond.shape[1]: - tensor, uncond = self.pad_cond_uncond(tensor, uncond) - - if tensor.shape[1] == uncond.shape[1] or skip_uncond: - if is_edit_model: - cond_in = catenate_conds([tensor, uncond, uncond]) - elif skip_uncond: - cond_in = tensor - else: - cond_in = catenate_conds([tensor, uncond]) - - if shared.opts.batch_cond_uncond: - x_out = self.inner_model(x_in, sigma_in, cond=make_condition_dict(cond_in, image_cond_in)) - else: - x_out = torch.zeros_like(x_in) - for batch_offset in range(0, x_out.shape[0], batch_size): - a = batch_offset - b = a + batch_size - x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], cond=make_condition_dict(subscript_cond(cond_in, a, b), image_cond_in[a:b])) - else: - x_out = torch.zeros_like(x_in) - batch_size = batch_size*2 if shared.opts.batch_cond_uncond else batch_size - for batch_offset in range(0, tensor.shape[0], batch_size): - a = batch_offset - b = min(a + batch_size, tensor.shape[0]) - - if not is_edit_model: - c_crossattn = subscript_cond(tensor, a, b) - else: - c_crossattn = torch.cat([tensor[a:b]], uncond) - - x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], cond=make_condition_dict(c_crossattn, image_cond_in[a:b])) - - if not skip_uncond: - x_out[-uncond.shape[0]:] = self.inner_model(x_in[-uncond.shape[0]:], sigma_in[-uncond.shape[0]:], cond=make_condition_dict(uncond, image_cond_in[-uncond.shape[0]:])) - - denoised_image_indexes = [x[0][0] for x in conds_list] - if skip_uncond: - fake_uncond = torch.cat([x_out[i:i+1] for i in denoised_image_indexes]) - x_out = torch.cat([x_out, fake_uncond]) # we skipped uncond denoising, so we put cond-denoised image to where the uncond-denoised image should be - - denoised_params = CFGDenoisedParams(x_out, state.sampling_step, state.sampling_steps, self.inner_model) - cfg_denoised_callback(denoised_params) - - if self.need_last_noise_uncond: - self.last_noise_uncond = torch.clone(x_out[-uncond.shape[0]:]) - - if is_edit_model: - denoised = self.combine_denoised_for_edit_model(x_out, cond_scale * self.cond_scale_miltiplier) - elif skip_uncond: - denoised = self.combine_denoised(x_out, conds_list, uncond, 1.0) - else: - denoised = self.combine_denoised(x_out, conds_list, uncond, cond_scale * self.cond_scale_miltiplier) - - # Blend in the original latents (after) - if not self.mask_before_denoising and self.mask is not None: - denoised = apply_blend(denoised) - - self.sampler.last_latent = self.get_pred_x0(torch.cat([x_in[i:i + 1] for i in denoised_image_indexes]), torch.cat([x_out[i:i + 1] for i in denoised_image_indexes]), sigma) - - if opts.live_preview_content == "Prompt": - preview = self.sampler.last_latent - elif opts.live_preview_content == "Negative prompt": - preview = self.get_pred_x0(x_in[-uncond.shape[0]:], x_out[-uncond.shape[0]:], sigma) - else: - preview = self.get_pred_x0(torch.cat([x_in[i:i+1] for i in denoised_image_indexes]), torch.cat([denoised[i:i+1] for i in denoised_image_indexes]), sigma) - - sd_samplers_common.store_latent(preview) - - after_cfg_callback_params = AfterCFGCallbackParams(denoised, state.sampling_step, state.sampling_steps) - cfg_after_cfg_callback(after_cfg_callback_params) - denoised = after_cfg_callback_params.x - - self.step += 1 - return denoised +import torch +from modules import prompt_parser, sd_samplers_common + +from modules.shared import opts, state +import modules.shared as shared +from modules.script_callbacks import CFGDenoiserParams, cfg_denoiser_callback +from modules.script_callbacks import CFGDenoisedParams, cfg_denoised_callback +from modules.script_callbacks import AfterCFGCallbackParams, cfg_after_cfg_callback + + +def catenate_conds(conds): + if not isinstance(conds[0], dict): + return torch.cat(conds) + + return {key: torch.cat([x[key] for x in conds]) for key in conds[0].keys()} + + +def subscript_cond(cond, a, b): + if not isinstance(cond, dict): + return cond[a:b] + + return {key: vec[a:b] for key, vec in cond.items()} + + +def pad_cond(tensor, repeats, empty): + if not isinstance(tensor, dict): + return torch.cat([tensor, empty.repeat((tensor.shape[0], repeats, 1))], axis=1) + + tensor['crossattn'] = pad_cond(tensor['crossattn'], repeats, empty) + return tensor + + +class CFGDenoiser(torch.nn.Module): + """ + Classifier free guidance denoiser. A wrapper for stable diffusion model (specifically for unet) + that can take a noisy picture and produce a noise-free picture using two guidances (prompts) + instead of one. Originally, the second prompt is just an empty string, but we use non-empty + negative prompt. + """ + + def __init__(self, sampler): + super().__init__() + self.model_wrap = None + self.mask = None + self.nmask = None + self.init_latent = None + self.steps = None + """number of steps as specified by user in UI""" + + self.total_steps = None + """expected number of calls to denoiser calculated from self.steps and specifics of the selected sampler""" + + self.step = 0 + self.image_cfg_scale = None + self.padded_cond_uncond = False + self.padded_cond_uncond_v0 = False + self.sampler = sampler + self.model_wrap = None + self.p = None + + self.cond_scale_miltiplier = 1.0 + + self.need_last_noise_uncond = False + self.last_noise_uncond = None + + # NOTE: masking before denoising can cause the original latents to be oversmoothed + # as the original latents do not have noise + self.mask_before_denoising = False + + @property + def inner_model(self): + raise NotImplementedError() + + def combine_denoised(self, x_out, conds_list, uncond, cond_scale): + denoised_uncond = x_out[-uncond.shape[0]:] + denoised = torch.clone(denoised_uncond) + + for i, conds in enumerate(conds_list): + for cond_index, weight in conds: + denoised[i] += (x_out[cond_index] - denoised_uncond[i]) * (weight * cond_scale) + + return denoised + + def combine_denoised_for_edit_model(self, x_out, cond_scale): + out_cond, out_img_cond, out_uncond = x_out.chunk(3) + denoised = out_uncond + cond_scale * (out_cond - out_img_cond) + self.image_cfg_scale * (out_img_cond - out_uncond) + + return denoised + + def get_pred_x0(self, x_in, x_out, sigma): + return x_out + + def update_inner_model(self): + self.model_wrap = None + + c, uc = self.p.get_conds() + self.sampler.sampler_extra_args['cond'] = c + self.sampler.sampler_extra_args['uncond'] = uc + + def pad_cond_uncond(self, cond, uncond): + empty = shared.sd_model.cond_stage_model_empty_prompt + num_repeats = (cond.shape[1] - uncond.shape[1]) // empty.shape[1] + + if num_repeats < 0: + cond = pad_cond(cond, -num_repeats, empty) + self.padded_cond_uncond = True + elif num_repeats > 0: + uncond = pad_cond(uncond, num_repeats, empty) + self.padded_cond_uncond = True + + return cond, uncond + + def pad_cond_uncond_v0(self, cond, uncond): + """ + Pads the 'uncond' tensor to match the shape of the 'cond' tensor. + + If 'uncond' is a dictionary, it is assumed that the 'crossattn' key holds the tensor to be padded. + If 'uncond' is a tensor, it is padded directly. + + If the number of columns in 'uncond' is less than the number of columns in 'cond', the last column of 'uncond' + is repeated to match the number of columns in 'cond'. + + If the number of columns in 'uncond' is greater than the number of columns in 'cond', 'uncond' is truncated + to match the number of columns in 'cond'. + + Args: + cond (torch.Tensor or DictWithShape): The condition tensor to match the shape of 'uncond'. + uncond (torch.Tensor or DictWithShape): The tensor to be padded, or a dictionary containing the tensor to be padded. + + Returns: + tuple: A tuple containing the 'cond' tensor and the padded 'uncond' tensor. + + Note: + This is the padding that was always used in DDIM before version 1.6.0 + """ + + is_dict_cond = isinstance(uncond, dict) + uncond_vec = uncond['crossattn'] if is_dict_cond else uncond + + if uncond_vec.shape[1] < cond.shape[1]: + last_vector = uncond_vec[:, -1:] + last_vector_repeated = last_vector.repeat([1, cond.shape[1] - uncond_vec.shape[1], 1]) + uncond_vec = torch.hstack([uncond_vec, last_vector_repeated]) + self.padded_cond_uncond_v0 = True + elif uncond_vec.shape[1] > cond.shape[1]: + uncond_vec = uncond_vec[:, :cond.shape[1]] + self.padded_cond_uncond_v0 = True + + if is_dict_cond: + uncond['crossattn'] = uncond_vec + else: + uncond = uncond_vec + + return cond, uncond + + def forward(self, x, sigma, uncond, cond, cond_scale, s_min_uncond, image_cond): + if state.interrupted or state.skipped: + raise sd_samplers_common.InterruptedException + + if sd_samplers_common.apply_refiner(self, sigma): + cond = self.sampler.sampler_extra_args['cond'] + uncond = self.sampler.sampler_extra_args['uncond'] + + # at self.image_cfg_scale == 1.0 produced results for edit model are the same as with normal sampling, + # so is_edit_model is set to False to support AND composition. + is_edit_model = shared.sd_model.cond_stage_key == "edit" and self.image_cfg_scale is not None and self.image_cfg_scale != 1.0 + + conds_list, tensor = prompt_parser.reconstruct_multicond_batch(cond, self.step) + uncond = prompt_parser.reconstruct_cond_batch(uncond, self.step) + + assert not is_edit_model or all(len(conds) == 1 for conds in conds_list), "AND is not supported for InstructPix2Pix checkpoint (unless using Image CFG scale = 1.0)" + + # If we use masks, blending between the denoised and original latent images occurs here. + def apply_blend(current_latent): + blended_latent = current_latent * self.nmask + self.init_latent * self.mask + + if self.p.scripts is not None: + from modules import scripts + mba = scripts.MaskBlendArgs(current_latent, self.nmask, self.init_latent, self.mask, blended_latent, denoiser=self, sigma=sigma) + self.p.scripts.on_mask_blend(self.p, mba) + blended_latent = mba.blended_latent + + return blended_latent + + # Blend in the original latents (before) + if self.mask_before_denoising and self.mask is not None: + x = apply_blend(x) + + batch_size = len(conds_list) + repeats = [len(conds_list[i]) for i in range(batch_size)] + + if shared.sd_model.model.conditioning_key == "crossattn-adm": + image_uncond = torch.zeros_like(image_cond) + make_condition_dict = lambda c_crossattn, c_adm: {"c_crossattn": [c_crossattn], "c_adm": c_adm} + else: + image_uncond = image_cond + if isinstance(uncond, dict): + make_condition_dict = lambda c_crossattn, c_concat: {**c_crossattn, "c_concat": [c_concat]} + else: + make_condition_dict = lambda c_crossattn, c_concat: {"c_crossattn": [c_crossattn], "c_concat": [c_concat]} + + if not is_edit_model: + x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x]) + sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma]) + image_cond_in = torch.cat([torch.stack([image_cond[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [image_uncond]) + else: + x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x] + [x]) + sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma] + [sigma]) + image_cond_in = torch.cat([torch.stack([image_cond[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [image_uncond] + [torch.zeros_like(self.init_latent)]) + + denoiser_params = CFGDenoiserParams(x_in, image_cond_in, sigma_in, state.sampling_step, state.sampling_steps, tensor, uncond, self) + cfg_denoiser_callback(denoiser_params) + x_in = denoiser_params.x + image_cond_in = denoiser_params.image_cond + sigma_in = denoiser_params.sigma + tensor = denoiser_params.text_cond + uncond = denoiser_params.text_uncond + skip_uncond = False + + if shared.opts.skip_early_cond != 0. and self.step / self.total_steps <= shared.opts.skip_early_cond: + skip_uncond = True + self.p.extra_generation_params["Skip Early CFG"] = shared.opts.skip_early_cond + elif (self.step % 2 or shared.opts.s_min_uncond_all) and s_min_uncond > 0 and sigma[0] < s_min_uncond and not is_edit_model: + skip_uncond = True + self.p.extra_generation_params["NGMS"] = s_min_uncond + if shared.opts.s_min_uncond_all: + self.p.extra_generation_params["NGMS all steps"] = shared.opts.s_min_uncond_all + + if skip_uncond: + x_in = x_in[:-batch_size] + sigma_in = sigma_in[:-batch_size] + + self.padded_cond_uncond = False + self.padded_cond_uncond_v0 = False + if shared.opts.pad_cond_uncond_v0 and tensor.shape[1] != uncond.shape[1]: + tensor, uncond = self.pad_cond_uncond_v0(tensor, uncond) + elif shared.opts.pad_cond_uncond and tensor.shape[1] != uncond.shape[1]: + tensor, uncond = self.pad_cond_uncond(tensor, uncond) + + if tensor.shape[1] == uncond.shape[1] or skip_uncond: + if is_edit_model: + cond_in = catenate_conds([tensor, uncond, uncond]) + elif skip_uncond: + cond_in = tensor + else: + cond_in = catenate_conds([tensor, uncond]) + + if shared.opts.batch_cond_uncond: + x_out = self.inner_model(x_in, sigma_in, cond=make_condition_dict(cond_in, image_cond_in)) + else: + x_out = torch.zeros_like(x_in) + for batch_offset in range(0, x_out.shape[0], batch_size): + a = batch_offset + b = a + batch_size + x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], cond=make_condition_dict(subscript_cond(cond_in, a, b), image_cond_in[a:b])) + else: + x_out = torch.zeros_like(x_in) + batch_size = batch_size*2 if shared.opts.batch_cond_uncond else batch_size + for batch_offset in range(0, tensor.shape[0], batch_size): + a = batch_offset + b = min(a + batch_size, tensor.shape[0]) + + if not is_edit_model: + c_crossattn = subscript_cond(tensor, a, b) + else: + c_crossattn = torch.cat([tensor[a:b]], uncond) + + x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], cond=make_condition_dict(c_crossattn, image_cond_in[a:b])) + + if not skip_uncond: + x_out[-uncond.shape[0]:] = self.inner_model(x_in[-uncond.shape[0]:], sigma_in[-uncond.shape[0]:], cond=make_condition_dict(uncond, image_cond_in[-uncond.shape[0]:])) + + denoised_image_indexes = [x[0][0] for x in conds_list] + if skip_uncond: + fake_uncond = torch.cat([x_out[i:i+1] for i in denoised_image_indexes]) + x_out = torch.cat([x_out, fake_uncond]) # we skipped uncond denoising, so we put cond-denoised image to where the uncond-denoised image should be + + denoised_params = CFGDenoisedParams(x_out, state.sampling_step, state.sampling_steps, self.inner_model) + cfg_denoised_callback(denoised_params) + + if self.need_last_noise_uncond: + self.last_noise_uncond = torch.clone(x_out[-uncond.shape[0]:]) + + if is_edit_model: + denoised = self.combine_denoised_for_edit_model(x_out, cond_scale * self.cond_scale_miltiplier) + elif skip_uncond: + denoised = self.combine_denoised(x_out, conds_list, uncond, 1.0) + else: + denoised = self.combine_denoised(x_out, conds_list, uncond, cond_scale * self.cond_scale_miltiplier) + + # Blend in the original latents (after) + if not self.mask_before_denoising and self.mask is not None: + denoised = apply_blend(denoised) + + self.sampler.last_latent = self.get_pred_x0(torch.cat([x_in[i:i + 1] for i in denoised_image_indexes]), torch.cat([x_out[i:i + 1] for i in denoised_image_indexes]), sigma) + + if opts.live_preview_content == "Prompt": + preview = self.sampler.last_latent + elif opts.live_preview_content == "Negative prompt": + preview = self.get_pred_x0(x_in[-uncond.shape[0]:], x_out[-uncond.shape[0]:], sigma) + else: + preview = self.get_pred_x0(torch.cat([x_in[i:i+1] for i in denoised_image_indexes]), torch.cat([denoised[i:i+1] for i in denoised_image_indexes]), sigma) + + sd_samplers_common.store_latent(preview) + + after_cfg_callback_params = AfterCFGCallbackParams(denoised, state.sampling_step, state.sampling_steps) + cfg_after_cfg_callback(after_cfg_callback_params) + denoised = after_cfg_callback_params.x + + self.step += 1 + return denoised +
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_samplers_cfg_denoiser.py
Auto-generate documentation strings for this file
from __future__ import annotations from pathlib import Path from modules import errors import csv import os import typing import shutil class PromptStyle(typing.NamedTuple): name: str prompt: str | None negative_prompt: str | None path: str | None = None def merge_prompts(style_prompt: str, prompt: str) -> str: if "{prompt}" in style_prompt: res = style_prompt.replace("{prompt}", prompt) else: parts = filter(None, (prompt.strip(), style_prompt.strip())) res = ", ".join(parts) return res def apply_styles_to_prompt(prompt, styles): for style in styles: prompt = merge_prompts(style, prompt) return prompt def extract_style_text_from_prompt(style_text, prompt): stripped_prompt = prompt.strip() stripped_style_text = style_text.strip() if "{prompt}" in stripped_style_text: left, _, right = stripped_style_text.partition("{prompt}") if stripped_prompt.startswith(left) and stripped_prompt.endswith(right): prompt = stripped_prompt[len(left):len(stripped_prompt)-len(right)] return True, prompt else: if stripped_prompt.endswith(stripped_style_text): prompt = stripped_prompt[:len(stripped_prompt)-len(stripped_style_text)] if prompt.endswith(', '): prompt = prompt[:-2] return True, prompt return False, prompt def extract_original_prompts(style: PromptStyle, prompt, negative_prompt): if not style.prompt and not style.negative_prompt: return False, prompt, negative_prompt match_positive, extracted_positive = extract_style_text_from_prompt(style.prompt, prompt) if not match_positive: return False, prompt, negative_prompt match_negative, extracted_negative = extract_style_text_from_prompt(style.negative_prompt, negative_prompt) if not match_negative: return False, prompt, negative_prompt return True, extracted_positive, extracted_negative class StyleDatabase: def __init__(self, paths: list[str | Path]): self.no_style = PromptStyle("None", "", "", None) self.styles = {} self.paths = paths self.all_styles_files: list[Path] = [] folder, file = os.path.split(self.paths[0]) if '*' in file or '?' in file: # if the first path is a wildcard pattern, find the first match else use "folder/styles.csv" as the default path self.default_path = next(Path(folder).glob(file), Path(os.path.join(folder, 'styles.csv'))) self.paths.insert(0, self.default_path) else: self.default_path = Path(self.paths[0]) self.prompt_fields = [field for field in PromptStyle._fields if field != "path"] self.reload() def reload(self): self.styles.clear() # scans for all styles files all_styles_files = [] for pattern in self.paths: folder, file = os.path.split(pattern) if '*' in file or '?' in file: found_files = Path(folder).glob(file) [all_styles_files.append(file) for file in found_files] else: # if os.path.exists(pattern): all_styles_files.append(Path(pattern)) # Remove any duplicate entries seen = set() self.all_styles_files = [s for s in all_styles_files if not (s in seen or seen.add(s))] for styles_file in self.all_styles_files: if len(all_styles_files) > 1: # add divider when more than styles file # '---------------- STYLES ----------------' divider = f' {styles_file.stem.upper()} '.center(40, '-') self.styles[divider] = PromptStyle(f"{divider}", None, None, "do_not_save") if styles_file.is_file(): self.load_from_csv(styles_file) def load_from_csv(self, path: str | Path): try: with open(path, "r", encoding="utf-8-sig", newline="") as file: reader = csv.DictReader(file, skipinitialspace=True) for row in reader: # Ignore empty rows or rows starting with a comment if not row or row["name"].startswith("#"): continue # Support loading old CSV format with "name, text"-columns prompt = row["prompt"] if "prompt" in row else row["text"] negative_prompt = row.get("negative_prompt", "") # Add style to database self.styles[row["name"]] = PromptStyle( row["name"], prompt, negative_prompt, str(path) ) except Exception: errors.report(f'Error loading styles from {path}: ', exc_info=True) def get_style_paths(self) -> set: # Update any styles without a path to the default path for style in list(self.styles.values()): if not style.path: self.styles[style.name] = style._replace(path=str(self.default_path)) # Create a list of all distinct paths, including the default path style_paths = set() style_paths.add(str(self.default_path)) for _, style in self.styles.items(): if style.path: style_paths.add(style.path) # Remove any paths for styles that are just list dividers style_paths.discard("do_not_save") return style_paths def get_style_prompts(self, styles): return [self.styles.get(x, self.no_style).prompt for x in styles] def get_negative_style_prompts(self, styles): return [self.styles.get(x, self.no_style).negative_prompt for x in styles] def apply_styles_to_prompt(self, prompt, styles): return apply_styles_to_prompt( prompt, [self.styles.get(x, self.no_style).prompt for x in styles] ) def apply_negative_styles_to_prompt(self, prompt, styles): return apply_styles_to_prompt( prompt, [self.styles.get(x, self.no_style).negative_prompt for x in styles] ) def save_styles(self, path: str = None) -> None: # The path argument is deprecated, but kept for backwards compatibility style_paths = self.get_style_paths() csv_names = [os.path.split(path)[1].lower() for path in style_paths] for style_path in style_paths: # Always keep a backup file around if os.path.exists(style_path): shutil.copy(style_path, f"{style_path}.bak") # Write the styles to the CSV file with open(style_path, "w", encoding="utf-8-sig", newline="") as file: writer = csv.DictWriter(file, fieldnames=self.prompt_fields) writer.writeheader() for style in (s for s in self.styles.values() if s.path == style_path): # Skip style list dividers, e.g. "STYLES.CSV" if style.name.lower().strip("# ") in csv_names: continue # Write style fields, ignoring the path field writer.writerow( {k: v for k, v in style._asdict().items() if k != "path"} ) def extract_styles_from_prompt(self, prompt, negative_prompt): extracted = [] applicable_styles = list(self.styles.values()) while True: found_style = None for style in applicable_styles: is_match, new_prompt, new_neg_prompt = extract_original_prompts( style, prompt, negative_prompt ) if is_match: found_style = style prompt = new_prompt negative_prompt = new_neg_prompt break if not found_style: break applicable_styles.remove(found_style) extracted.append(found_style.name) return list(reversed(extracted)), prompt, negative_prompt
--- +++ @@ -1,218 +1,234 @@-from __future__ import annotations -from pathlib import Path -from modules import errors -import csv -import os -import typing -import shutil - - -class PromptStyle(typing.NamedTuple): - name: str - prompt: str | None - negative_prompt: str | None - path: str | None = None - - -def merge_prompts(style_prompt: str, prompt: str) -> str: - if "{prompt}" in style_prompt: - res = style_prompt.replace("{prompt}", prompt) - else: - parts = filter(None, (prompt.strip(), style_prompt.strip())) - res = ", ".join(parts) - - return res - - -def apply_styles_to_prompt(prompt, styles): - for style in styles: - prompt = merge_prompts(style, prompt) - - return prompt - - -def extract_style_text_from_prompt(style_text, prompt): - - stripped_prompt = prompt.strip() - stripped_style_text = style_text.strip() - - if "{prompt}" in stripped_style_text: - left, _, right = stripped_style_text.partition("{prompt}") - if stripped_prompt.startswith(left) and stripped_prompt.endswith(right): - prompt = stripped_prompt[len(left):len(stripped_prompt)-len(right)] - return True, prompt - else: - if stripped_prompt.endswith(stripped_style_text): - prompt = stripped_prompt[:len(stripped_prompt)-len(stripped_style_text)] - - if prompt.endswith(', '): - prompt = prompt[:-2] - - return True, prompt - - return False, prompt - - -def extract_original_prompts(style: PromptStyle, prompt, negative_prompt): - if not style.prompt and not style.negative_prompt: - return False, prompt, negative_prompt - - match_positive, extracted_positive = extract_style_text_from_prompt(style.prompt, prompt) - if not match_positive: - return False, prompt, negative_prompt - - match_negative, extracted_negative = extract_style_text_from_prompt(style.negative_prompt, negative_prompt) - if not match_negative: - return False, prompt, negative_prompt - - return True, extracted_positive, extracted_negative - - -class StyleDatabase: - def __init__(self, paths: list[str | Path]): - self.no_style = PromptStyle("None", "", "", None) - self.styles = {} - self.paths = paths - self.all_styles_files: list[Path] = [] - - folder, file = os.path.split(self.paths[0]) - if '*' in file or '?' in file: - # if the first path is a wildcard pattern, find the first match else use "folder/styles.csv" as the default path - self.default_path = next(Path(folder).glob(file), Path(os.path.join(folder, 'styles.csv'))) - self.paths.insert(0, self.default_path) - else: - self.default_path = Path(self.paths[0]) - - self.prompt_fields = [field for field in PromptStyle._fields if field != "path"] - - self.reload() - - def reload(self): - self.styles.clear() - - # scans for all styles files - all_styles_files = [] - for pattern in self.paths: - folder, file = os.path.split(pattern) - if '*' in file or '?' in file: - found_files = Path(folder).glob(file) - [all_styles_files.append(file) for file in found_files] - else: - # if os.path.exists(pattern): - all_styles_files.append(Path(pattern)) - - # Remove any duplicate entries - seen = set() - self.all_styles_files = [s for s in all_styles_files if not (s in seen or seen.add(s))] - - for styles_file in self.all_styles_files: - if len(all_styles_files) > 1: - # add divider when more than styles file - # '---------------- STYLES ----------------' - divider = f' {styles_file.stem.upper()} '.center(40, '-') - self.styles[divider] = PromptStyle(f"{divider}", None, None, "do_not_save") - if styles_file.is_file(): - self.load_from_csv(styles_file) - - def load_from_csv(self, path: str | Path): - try: - with open(path, "r", encoding="utf-8-sig", newline="") as file: - reader = csv.DictReader(file, skipinitialspace=True) - for row in reader: - # Ignore empty rows or rows starting with a comment - if not row or row["name"].startswith("#"): - continue - # Support loading old CSV format with "name, text"-columns - prompt = row["prompt"] if "prompt" in row else row["text"] - negative_prompt = row.get("negative_prompt", "") - # Add style to database - self.styles[row["name"]] = PromptStyle( - row["name"], prompt, negative_prompt, str(path) - ) - except Exception: - errors.report(f'Error loading styles from {path}: ', exc_info=True) - - def get_style_paths(self) -> set: - # Update any styles without a path to the default path - for style in list(self.styles.values()): - if not style.path: - self.styles[style.name] = style._replace(path=str(self.default_path)) - - # Create a list of all distinct paths, including the default path - style_paths = set() - style_paths.add(str(self.default_path)) - for _, style in self.styles.items(): - if style.path: - style_paths.add(style.path) - - # Remove any paths for styles that are just list dividers - style_paths.discard("do_not_save") - - return style_paths - - def get_style_prompts(self, styles): - return [self.styles.get(x, self.no_style).prompt for x in styles] - - def get_negative_style_prompts(self, styles): - return [self.styles.get(x, self.no_style).negative_prompt for x in styles] - - def apply_styles_to_prompt(self, prompt, styles): - return apply_styles_to_prompt( - prompt, [self.styles.get(x, self.no_style).prompt for x in styles] - ) - - def apply_negative_styles_to_prompt(self, prompt, styles): - return apply_styles_to_prompt( - prompt, [self.styles.get(x, self.no_style).negative_prompt for x in styles] - ) - - def save_styles(self, path: str = None) -> None: - # The path argument is deprecated, but kept for backwards compatibility - - style_paths = self.get_style_paths() - - csv_names = [os.path.split(path)[1].lower() for path in style_paths] - - for style_path in style_paths: - # Always keep a backup file around - if os.path.exists(style_path): - shutil.copy(style_path, f"{style_path}.bak") - - # Write the styles to the CSV file - with open(style_path, "w", encoding="utf-8-sig", newline="") as file: - writer = csv.DictWriter(file, fieldnames=self.prompt_fields) - writer.writeheader() - for style in (s for s in self.styles.values() if s.path == style_path): - # Skip style list dividers, e.g. "STYLES.CSV" - if style.name.lower().strip("# ") in csv_names: - continue - # Write style fields, ignoring the path field - writer.writerow( - {k: v for k, v in style._asdict().items() if k != "path"} - ) - - def extract_styles_from_prompt(self, prompt, negative_prompt): - extracted = [] - - applicable_styles = list(self.styles.values()) - - while True: - found_style = None - - for style in applicable_styles: - is_match, new_prompt, new_neg_prompt = extract_original_prompts( - style, prompt, negative_prompt - ) - if is_match: - found_style = style - prompt = new_prompt - negative_prompt = new_neg_prompt - break - - if not found_style: - break - - applicable_styles.remove(found_style) - extracted.append(found_style.name) - - return list(reversed(extracted)), prompt, negative_prompt+from __future__ import annotations +from pathlib import Path +from modules import errors +import csv +import os +import typing +import shutil + + +class PromptStyle(typing.NamedTuple): + name: str + prompt: str | None + negative_prompt: str | None + path: str | None = None + + +def merge_prompts(style_prompt: str, prompt: str) -> str: + if "{prompt}" in style_prompt: + res = style_prompt.replace("{prompt}", prompt) + else: + parts = filter(None, (prompt.strip(), style_prompt.strip())) + res = ", ".join(parts) + + return res + + +def apply_styles_to_prompt(prompt, styles): + for style in styles: + prompt = merge_prompts(style, prompt) + + return prompt + + +def extract_style_text_from_prompt(style_text, prompt): + """This function extracts the text from a given prompt based on a provided style text. It checks if the style text contains the placeholder {prompt} or if it appears at the end of the prompt. If a match is found, it returns True along with the extracted text. Otherwise, it returns False and the original prompt. + + extract_style_text_from_prompt("masterpiece", "1girl, art by greg, masterpiece") outputs (True, "1girl, art by greg") + extract_style_text_from_prompt("masterpiece, {prompt}", "masterpiece, 1girl, art by greg") outputs (True, "1girl, art by greg") + extract_style_text_from_prompt("masterpiece, {prompt}", "exquisite, 1girl, art by greg") outputs (False, "exquisite, 1girl, art by greg") + """ + + stripped_prompt = prompt.strip() + stripped_style_text = style_text.strip() + + if "{prompt}" in stripped_style_text: + left, _, right = stripped_style_text.partition("{prompt}") + if stripped_prompt.startswith(left) and stripped_prompt.endswith(right): + prompt = stripped_prompt[len(left):len(stripped_prompt)-len(right)] + return True, prompt + else: + if stripped_prompt.endswith(stripped_style_text): + prompt = stripped_prompt[:len(stripped_prompt)-len(stripped_style_text)] + + if prompt.endswith(', '): + prompt = prompt[:-2] + + return True, prompt + + return False, prompt + + +def extract_original_prompts(style: PromptStyle, prompt, negative_prompt): + """ + Takes a style and compares it to the prompt and negative prompt. If the style + matches, returns True plus the prompt and negative prompt with the style text + removed. Otherwise, returns False with the original prompt and negative prompt. + """ + if not style.prompt and not style.negative_prompt: + return False, prompt, negative_prompt + + match_positive, extracted_positive = extract_style_text_from_prompt(style.prompt, prompt) + if not match_positive: + return False, prompt, negative_prompt + + match_negative, extracted_negative = extract_style_text_from_prompt(style.negative_prompt, negative_prompt) + if not match_negative: + return False, prompt, negative_prompt + + return True, extracted_positive, extracted_negative + + +class StyleDatabase: + def __init__(self, paths: list[str | Path]): + self.no_style = PromptStyle("None", "", "", None) + self.styles = {} + self.paths = paths + self.all_styles_files: list[Path] = [] + + folder, file = os.path.split(self.paths[0]) + if '*' in file or '?' in file: + # if the first path is a wildcard pattern, find the first match else use "folder/styles.csv" as the default path + self.default_path = next(Path(folder).glob(file), Path(os.path.join(folder, 'styles.csv'))) + self.paths.insert(0, self.default_path) + else: + self.default_path = Path(self.paths[0]) + + self.prompt_fields = [field for field in PromptStyle._fields if field != "path"] + + self.reload() + + def reload(self): + """ + Clears the style database and reloads the styles from the CSV file(s) + matching the path used to initialize the database. + """ + self.styles.clear() + + # scans for all styles files + all_styles_files = [] + for pattern in self.paths: + folder, file = os.path.split(pattern) + if '*' in file or '?' in file: + found_files = Path(folder).glob(file) + [all_styles_files.append(file) for file in found_files] + else: + # if os.path.exists(pattern): + all_styles_files.append(Path(pattern)) + + # Remove any duplicate entries + seen = set() + self.all_styles_files = [s for s in all_styles_files if not (s in seen or seen.add(s))] + + for styles_file in self.all_styles_files: + if len(all_styles_files) > 1: + # add divider when more than styles file + # '---------------- STYLES ----------------' + divider = f' {styles_file.stem.upper()} '.center(40, '-') + self.styles[divider] = PromptStyle(f"{divider}", None, None, "do_not_save") + if styles_file.is_file(): + self.load_from_csv(styles_file) + + def load_from_csv(self, path: str | Path): + try: + with open(path, "r", encoding="utf-8-sig", newline="") as file: + reader = csv.DictReader(file, skipinitialspace=True) + for row in reader: + # Ignore empty rows or rows starting with a comment + if not row or row["name"].startswith("#"): + continue + # Support loading old CSV format with "name, text"-columns + prompt = row["prompt"] if "prompt" in row else row["text"] + negative_prompt = row.get("negative_prompt", "") + # Add style to database + self.styles[row["name"]] = PromptStyle( + row["name"], prompt, negative_prompt, str(path) + ) + except Exception: + errors.report(f'Error loading styles from {path}: ', exc_info=True) + + def get_style_paths(self) -> set: + """Returns a set of all distinct paths of files that styles are loaded from.""" + # Update any styles without a path to the default path + for style in list(self.styles.values()): + if not style.path: + self.styles[style.name] = style._replace(path=str(self.default_path)) + + # Create a list of all distinct paths, including the default path + style_paths = set() + style_paths.add(str(self.default_path)) + for _, style in self.styles.items(): + if style.path: + style_paths.add(style.path) + + # Remove any paths for styles that are just list dividers + style_paths.discard("do_not_save") + + return style_paths + + def get_style_prompts(self, styles): + return [self.styles.get(x, self.no_style).prompt for x in styles] + + def get_negative_style_prompts(self, styles): + return [self.styles.get(x, self.no_style).negative_prompt for x in styles] + + def apply_styles_to_prompt(self, prompt, styles): + return apply_styles_to_prompt( + prompt, [self.styles.get(x, self.no_style).prompt for x in styles] + ) + + def apply_negative_styles_to_prompt(self, prompt, styles): + return apply_styles_to_prompt( + prompt, [self.styles.get(x, self.no_style).negative_prompt for x in styles] + ) + + def save_styles(self, path: str = None) -> None: + # The path argument is deprecated, but kept for backwards compatibility + + style_paths = self.get_style_paths() + + csv_names = [os.path.split(path)[1].lower() for path in style_paths] + + for style_path in style_paths: + # Always keep a backup file around + if os.path.exists(style_path): + shutil.copy(style_path, f"{style_path}.bak") + + # Write the styles to the CSV file + with open(style_path, "w", encoding="utf-8-sig", newline="") as file: + writer = csv.DictWriter(file, fieldnames=self.prompt_fields) + writer.writeheader() + for style in (s for s in self.styles.values() if s.path == style_path): + # Skip style list dividers, e.g. "STYLES.CSV" + if style.name.lower().strip("# ") in csv_names: + continue + # Write style fields, ignoring the path field + writer.writerow( + {k: v for k, v in style._asdict().items() if k != "path"} + ) + + def extract_styles_from_prompt(self, prompt, negative_prompt): + extracted = [] + + applicable_styles = list(self.styles.values()) + + while True: + found_style = None + + for style in applicable_styles: + is_match, new_prompt, new_neg_prompt = extract_original_prompts( + style, prompt, negative_prompt + ) + if is_match: + found_style = style + prompt = new_prompt + negative_prompt = new_neg_prompt + break + + if not found_style: + break + + applicable_styles.remove(found_style) + extracted.append(found_style.name) + + return list(reversed(extracted)), prompt, negative_prompt
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/styles.py
Add detailed documentation for each class
import datetime import logging import threading import time from modules import errors, shared, devices from typing import Optional log = logging.getLogger(__name__) class State: skipped = False interrupted = False stopping_generation = False job = "" job_no = 0 job_count = 0 processing_has_refined_job_count = False job_timestamp = '0' sampling_step = 0 sampling_steps = 0 current_latent = None current_image = None current_image_sampling_step = 0 id_live_preview = 0 textinfo = None time_start = None server_start = None _server_command_signal = threading.Event() _server_command: Optional[str] = None def __init__(self): self.server_start = time.time() @property def need_restart(self) -> bool: # Compatibility getter for need_restart. return self.server_command == "restart" @need_restart.setter def need_restart(self, value: bool) -> None: # Compatibility setter for need_restart. if value: self.server_command = "restart" @property def server_command(self): return self._server_command @server_command.setter def server_command(self, value: Optional[str]) -> None: self._server_command = value self._server_command_signal.set() def wait_for_server_command(self, timeout: Optional[float] = None) -> Optional[str]: if self._server_command_signal.wait(timeout): self._server_command_signal.clear() req = self._server_command self._server_command = None return req return None def request_restart(self) -> None: self.interrupt() self.server_command = "restart" log.info("Received restart request") def skip(self): self.skipped = True log.info("Received skip request") def interrupt(self): self.interrupted = True log.info("Received interrupt request") def stop_generating(self): self.stopping_generation = True log.info("Received stop generating request") def nextjob(self): if shared.opts.live_previews_enable and shared.opts.show_progress_every_n_steps == -1: self.do_set_current_image() self.job_no += 1 self.sampling_step = 0 self.current_image_sampling_step = 0 def dict(self): obj = { "skipped": self.skipped, "interrupted": self.interrupted, "stopping_generation": self.stopping_generation, "job": self.job, "job_count": self.job_count, "job_timestamp": self.job_timestamp, "job_no": self.job_no, "sampling_step": self.sampling_step, "sampling_steps": self.sampling_steps, } return obj def begin(self, job: str = "(unknown)"): self.sampling_step = 0 self.time_start = time.time() self.job_count = -1 self.processing_has_refined_job_count = False self.job_no = 0 self.job_timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S") self.current_latent = None self.current_image = None self.current_image_sampling_step = 0 self.id_live_preview = 0 self.skipped = False self.interrupted = False self.stopping_generation = False self.textinfo = None self.job = job devices.torch_gc() log.info("Starting job %s", job) def end(self): duration = time.time() - self.time_start log.info("Ending job %s (%.2f seconds)", self.job, duration) self.job = "" self.job_count = 0 devices.torch_gc() def set_current_image(self): if not shared.parallel_processing_allowed: return if self.sampling_step - self.current_image_sampling_step >= shared.opts.show_progress_every_n_steps and shared.opts.live_previews_enable and shared.opts.show_progress_every_n_steps != -1: self.do_set_current_image() def do_set_current_image(self): if self.current_latent is None: return import modules.sd_samplers try: if shared.opts.show_progress_grid: self.assign_current_image(modules.sd_samplers.samples_to_image_grid(self.current_latent)) else: self.assign_current_image(modules.sd_samplers.sample_to_image(self.current_latent)) self.current_image_sampling_step = self.sampling_step except Exception: # when switching models during generation, VAE would be on CPU, so creating an image will fail. # we silently ignore this error errors.record_exception() def assign_current_image(self, image): if shared.opts.live_previews_image_format == 'jpeg' and image.mode in ('RGBA', 'P'): image = image.convert('RGB') self.current_image = image self.id_live_preview += 1
--- +++ @@ -1,161 +1,168 @@-import datetime -import logging -import threading -import time - -from modules import errors, shared, devices -from typing import Optional - -log = logging.getLogger(__name__) - - -class State: - skipped = False - interrupted = False - stopping_generation = False - job = "" - job_no = 0 - job_count = 0 - processing_has_refined_job_count = False - job_timestamp = '0' - sampling_step = 0 - sampling_steps = 0 - current_latent = None - current_image = None - current_image_sampling_step = 0 - id_live_preview = 0 - textinfo = None - time_start = None - server_start = None - _server_command_signal = threading.Event() - _server_command: Optional[str] = None - - def __init__(self): - self.server_start = time.time() - - @property - def need_restart(self) -> bool: - # Compatibility getter for need_restart. - return self.server_command == "restart" - - @need_restart.setter - def need_restart(self, value: bool) -> None: - # Compatibility setter for need_restart. - if value: - self.server_command = "restart" - - @property - def server_command(self): - return self._server_command - - @server_command.setter - def server_command(self, value: Optional[str]) -> None: - self._server_command = value - self._server_command_signal.set() - - def wait_for_server_command(self, timeout: Optional[float] = None) -> Optional[str]: - if self._server_command_signal.wait(timeout): - self._server_command_signal.clear() - req = self._server_command - self._server_command = None - return req - return None - - def request_restart(self) -> None: - self.interrupt() - self.server_command = "restart" - log.info("Received restart request") - - def skip(self): - self.skipped = True - log.info("Received skip request") - - def interrupt(self): - self.interrupted = True - log.info("Received interrupt request") - - def stop_generating(self): - self.stopping_generation = True - log.info("Received stop generating request") - - def nextjob(self): - if shared.opts.live_previews_enable and shared.opts.show_progress_every_n_steps == -1: - self.do_set_current_image() - - self.job_no += 1 - self.sampling_step = 0 - self.current_image_sampling_step = 0 - - def dict(self): - obj = { - "skipped": self.skipped, - "interrupted": self.interrupted, - "stopping_generation": self.stopping_generation, - "job": self.job, - "job_count": self.job_count, - "job_timestamp": self.job_timestamp, - "job_no": self.job_no, - "sampling_step": self.sampling_step, - "sampling_steps": self.sampling_steps, - } - - return obj - - def begin(self, job: str = "(unknown)"): - self.sampling_step = 0 - self.time_start = time.time() - self.job_count = -1 - self.processing_has_refined_job_count = False - self.job_no = 0 - self.job_timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S") - self.current_latent = None - self.current_image = None - self.current_image_sampling_step = 0 - self.id_live_preview = 0 - self.skipped = False - self.interrupted = False - self.stopping_generation = False - self.textinfo = None - self.job = job - devices.torch_gc() - log.info("Starting job %s", job) - - def end(self): - duration = time.time() - self.time_start - log.info("Ending job %s (%.2f seconds)", self.job, duration) - self.job = "" - self.job_count = 0 - - devices.torch_gc() - - def set_current_image(self): - if not shared.parallel_processing_allowed: - return - - if self.sampling_step - self.current_image_sampling_step >= shared.opts.show_progress_every_n_steps and shared.opts.live_previews_enable and shared.opts.show_progress_every_n_steps != -1: - self.do_set_current_image() - - def do_set_current_image(self): - if self.current_latent is None: - return - - import modules.sd_samplers - - try: - if shared.opts.show_progress_grid: - self.assign_current_image(modules.sd_samplers.samples_to_image_grid(self.current_latent)) - else: - self.assign_current_image(modules.sd_samplers.sample_to_image(self.current_latent)) - - self.current_image_sampling_step = self.sampling_step - - except Exception: - # when switching models during generation, VAE would be on CPU, so creating an image will fail. - # we silently ignore this error - errors.record_exception() - - def assign_current_image(self, image): - if shared.opts.live_previews_image_format == 'jpeg' and image.mode in ('RGBA', 'P'): - image = image.convert('RGB') - self.current_image = image - self.id_live_preview += 1+import datetime +import logging +import threading +import time + +from modules import errors, shared, devices +from typing import Optional + +log = logging.getLogger(__name__) + + +class State: + skipped = False + interrupted = False + stopping_generation = False + job = "" + job_no = 0 + job_count = 0 + processing_has_refined_job_count = False + job_timestamp = '0' + sampling_step = 0 + sampling_steps = 0 + current_latent = None + current_image = None + current_image_sampling_step = 0 + id_live_preview = 0 + textinfo = None + time_start = None + server_start = None + _server_command_signal = threading.Event() + _server_command: Optional[str] = None + + def __init__(self): + self.server_start = time.time() + + @property + def need_restart(self) -> bool: + # Compatibility getter for need_restart. + return self.server_command == "restart" + + @need_restart.setter + def need_restart(self, value: bool) -> None: + # Compatibility setter for need_restart. + if value: + self.server_command = "restart" + + @property + def server_command(self): + return self._server_command + + @server_command.setter + def server_command(self, value: Optional[str]) -> None: + """ + Set the server command to `value` and signal that it's been set. + """ + self._server_command = value + self._server_command_signal.set() + + def wait_for_server_command(self, timeout: Optional[float] = None) -> Optional[str]: + """ + Wait for server command to get set; return and clear the value and signal. + """ + if self._server_command_signal.wait(timeout): + self._server_command_signal.clear() + req = self._server_command + self._server_command = None + return req + return None + + def request_restart(self) -> None: + self.interrupt() + self.server_command = "restart" + log.info("Received restart request") + + def skip(self): + self.skipped = True + log.info("Received skip request") + + def interrupt(self): + self.interrupted = True + log.info("Received interrupt request") + + def stop_generating(self): + self.stopping_generation = True + log.info("Received stop generating request") + + def nextjob(self): + if shared.opts.live_previews_enable and shared.opts.show_progress_every_n_steps == -1: + self.do_set_current_image() + + self.job_no += 1 + self.sampling_step = 0 + self.current_image_sampling_step = 0 + + def dict(self): + obj = { + "skipped": self.skipped, + "interrupted": self.interrupted, + "stopping_generation": self.stopping_generation, + "job": self.job, + "job_count": self.job_count, + "job_timestamp": self.job_timestamp, + "job_no": self.job_no, + "sampling_step": self.sampling_step, + "sampling_steps": self.sampling_steps, + } + + return obj + + def begin(self, job: str = "(unknown)"): + self.sampling_step = 0 + self.time_start = time.time() + self.job_count = -1 + self.processing_has_refined_job_count = False + self.job_no = 0 + self.job_timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + self.current_latent = None + self.current_image = None + self.current_image_sampling_step = 0 + self.id_live_preview = 0 + self.skipped = False + self.interrupted = False + self.stopping_generation = False + self.textinfo = None + self.job = job + devices.torch_gc() + log.info("Starting job %s", job) + + def end(self): + duration = time.time() - self.time_start + log.info("Ending job %s (%.2f seconds)", self.job, duration) + self.job = "" + self.job_count = 0 + + devices.torch_gc() + + def set_current_image(self): + """if enough sampling steps have been made after the last call to this, sets self.current_image from self.current_latent, and modifies self.id_live_preview accordingly""" + if not shared.parallel_processing_allowed: + return + + if self.sampling_step - self.current_image_sampling_step >= shared.opts.show_progress_every_n_steps and shared.opts.live_previews_enable and shared.opts.show_progress_every_n_steps != -1: + self.do_set_current_image() + + def do_set_current_image(self): + if self.current_latent is None: + return + + import modules.sd_samplers + + try: + if shared.opts.show_progress_grid: + self.assign_current_image(modules.sd_samplers.samples_to_image_grid(self.current_latent)) + else: + self.assign_current_image(modules.sd_samplers.sample_to_image(self.current_latent)) + + self.current_image_sampling_step = self.sampling_step + + except Exception: + # when switching models during generation, VAE would be on CPU, so creating an image will fail. + # we silently ignore this error + errors.record_exception() + + def assign_current_image(self, image): + if shared.opts.live_previews_image_format == 'jpeg' and image.mode in ('RGBA', 'P'): + image = image.convert('RGB') + self.current_image = image + self.id_live_preview += 1
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/shared_state.py
Add docstrings explaining edge cases
import os import re import sys import inspect from collections import namedtuple from dataclasses import dataclass import gradio as gr from modules import shared, paths, script_callbacks, extensions, script_loading, scripts_postprocessing, errors, timer, util topological_sort = util.topological_sort AlwaysVisible = object() class MaskBlendArgs: def __init__(self, current_latent, nmask, init_latent, mask, blended_latent, denoiser=None, sigma=None): self.current_latent = current_latent self.nmask = nmask self.init_latent = init_latent self.mask = mask self.blended_latent = blended_latent self.denoiser = denoiser self.is_final_blend = denoiser is None self.sigma = sigma class PostSampleArgs: def __init__(self, samples): self.samples = samples class PostprocessImageArgs: def __init__(self, image): self.image = image class PostProcessMaskOverlayArgs: def __init__(self, index, mask_for_overlay, overlay_image): self.index = index self.mask_for_overlay = mask_for_overlay self.overlay_image = overlay_image class PostprocessBatchListArgs: def __init__(self, images): self.images = images @dataclass class OnComponent: component: gr.blocks.Block class Script: name = None """script's internal name derived from title""" section = None """name of UI section that the script's controls will be placed into""" filename = None args_from = None args_to = None alwayson = False is_txt2img = False is_img2img = False tabname = None group = None """A gr.Group component that has all script's UI inside it.""" create_group = True """If False, for alwayson scripts, a group component will not be created.""" infotext_fields = None """if set in ui(), this is a list of pairs of gradio component + text; the text will be used when parsing infotext to set the value for the component; see ui.py's txt2img_paste_fields for an example """ paste_field_names = None """if set in ui(), this is a list of names of infotext fields; the fields will be sent through the various "Send to <X>" buttons when clicked """ api_info = None """Generated value of type modules.api.models.ScriptInfo with information about the script for API""" on_before_component_elem_id = None """list of callbacks to be called before a component with an elem_id is created""" on_after_component_elem_id = None """list of callbacks to be called after a component with an elem_id is created""" setup_for_ui_only = False """If true, the script setup will only be run in Gradio UI, not in API""" controls = None """A list of controls returned by the ui().""" def title(self): raise NotImplementedError() def ui(self, is_img2img): pass def show(self, is_img2img): return True def run(self, p, *args): pass def setup(self, p, *args): pass def before_process(self, p, *args): pass def process(self, p, *args): pass def before_process_batch(self, p, *args, **kwargs): pass def after_extra_networks_activate(self, p, *args, **kwargs): pass def process_before_every_sampling(self, p, *args, **kwargs): pass def process_batch(self, p, *args, **kwargs): pass def postprocess_batch(self, p, *args, **kwargs): pass def postprocess_batch_list(self, p, pp: PostprocessBatchListArgs, *args, **kwargs): pass def on_mask_blend(self, p, mba: MaskBlendArgs, *args): pass def post_sample(self, p, ps: PostSampleArgs, *args): pass def postprocess_image(self, p, pp: PostprocessImageArgs, *args): pass def postprocess_maskoverlay(self, p, ppmo: PostProcessMaskOverlayArgs, *args): pass def postprocess_image_after_composite(self, p, pp: PostprocessImageArgs, *args): pass def postprocess(self, p, processed, *args): pass def before_component(self, component, **kwargs): pass def after_component(self, component, **kwargs): pass def on_before_component(self, callback, *, elem_id): if self.on_before_component_elem_id is None: self.on_before_component_elem_id = [] self.on_before_component_elem_id.append((elem_id, callback)) def on_after_component(self, callback, *, elem_id): if self.on_after_component_elem_id is None: self.on_after_component_elem_id = [] self.on_after_component_elem_id.append((elem_id, callback)) def describe(self): return "" def elem_id(self, item_id): need_tabname = self.show(True) == self.show(False) tabkind = 'img2img' if self.is_img2img else 'txt2img' tabname = f"{tabkind}_" if need_tabname else "" title = re.sub(r'[^a-z_0-9]', '', re.sub(r'\s', '_', self.title().lower())) return f'script_{tabname}{title}_{item_id}' def before_hr(self, p, *args): pass class ScriptBuiltinUI(Script): setup_for_ui_only = True def elem_id(self, item_id): need_tabname = self.show(True) == self.show(False) tabname = ('img2img' if self.is_img2img else 'txt2img') + "_" if need_tabname else "" return f'{tabname}{item_id}' def show(self, is_img2img): return AlwaysVisible current_basedir = paths.script_path def basedir(): return current_basedir ScriptFile = namedtuple("ScriptFile", ["basedir", "filename", "path"]) scripts_data = [] postprocessing_scripts_data = [] ScriptClassData = namedtuple("ScriptClassData", ["script_class", "path", "basedir", "module"]) @dataclass class ScriptWithDependencies: script_canonical_name: str file: ScriptFile requires: list load_before: list load_after: list def list_scripts(scriptdirname, extension, *, include_extensions=True): scripts = {} loaded_extensions = {ext.canonical_name: ext for ext in extensions.active()} loaded_extensions_scripts = {ext.canonical_name: [] for ext in extensions.active()} # build script dependency map root_script_basedir = os.path.join(paths.script_path, scriptdirname) if os.path.exists(root_script_basedir): for filename in sorted(os.listdir(root_script_basedir)): if not os.path.isfile(os.path.join(root_script_basedir, filename)): continue if os.path.splitext(filename)[1].lower() != extension: continue script_file = ScriptFile(paths.script_path, filename, os.path.join(root_script_basedir, filename)) scripts[filename] = ScriptWithDependencies(filename, script_file, [], [], []) if include_extensions: for ext in extensions.active(): extension_scripts_list = ext.list_files(scriptdirname, extension) for extension_script in extension_scripts_list: if not os.path.isfile(extension_script.path): continue script_canonical_name = ("builtin/" if ext.is_builtin else "") + ext.canonical_name + "/" + extension_script.filename relative_path = scriptdirname + "/" + extension_script.filename script = ScriptWithDependencies( script_canonical_name=script_canonical_name, file=extension_script, requires=ext.metadata.get_script_requirements("Requires", relative_path, scriptdirname), load_before=ext.metadata.get_script_requirements("Before", relative_path, scriptdirname), load_after=ext.metadata.get_script_requirements("After", relative_path, scriptdirname), ) scripts[script_canonical_name] = script loaded_extensions_scripts[ext.canonical_name].append(script) for script_canonical_name, script in scripts.items(): # load before requires inverse dependency # in this case, append the script name into the load_after list of the specified script for load_before in script.load_before: # if this requires an individual script to be loaded before other_script = scripts.get(load_before) if other_script: other_script.load_after.append(script_canonical_name) # if this requires an extension other_extension_scripts = loaded_extensions_scripts.get(load_before) if other_extension_scripts: for other_script in other_extension_scripts: other_script.load_after.append(script_canonical_name) # if After mentions an extension, remove it and instead add all of its scripts for load_after in list(script.load_after): if load_after not in scripts and load_after in loaded_extensions_scripts: script.load_after.remove(load_after) for other_script in loaded_extensions_scripts.get(load_after, []): script.load_after.append(other_script.script_canonical_name) dependencies = {} for script_canonical_name, script in scripts.items(): for required_script in script.requires: if required_script not in scripts and required_script not in loaded_extensions: errors.report(f'Script "{script_canonical_name}" requires "{required_script}" to be loaded, but it is not.', exc_info=False) dependencies[script_canonical_name] = script.load_after ordered_scripts = topological_sort(dependencies) scripts_list = [scripts[script_canonical_name].file for script_canonical_name in ordered_scripts] return scripts_list def list_files_with_name(filename): res = [] dirs = [paths.script_path] + [ext.path for ext in extensions.active()] for dirpath in dirs: if not os.path.isdir(dirpath): continue path = os.path.join(dirpath, filename) if os.path.isfile(path): res.append(path) return res def load_scripts(): global current_basedir scripts_data.clear() postprocessing_scripts_data.clear() script_callbacks.clear_callbacks() scripts_list = list_scripts("scripts", ".py") + list_scripts("modules/processing_scripts", ".py", include_extensions=False) syspath = sys.path def register_scripts_from_module(module): for script_class in module.__dict__.values(): if not inspect.isclass(script_class): continue if issubclass(script_class, Script): scripts_data.append(ScriptClassData(script_class, scriptfile.path, scriptfile.basedir, module)) elif issubclass(script_class, scripts_postprocessing.ScriptPostprocessing): postprocessing_scripts_data.append(ScriptClassData(script_class, scriptfile.path, scriptfile.basedir, module)) # here the scripts_list is already ordered # processing_script is not considered though for scriptfile in scripts_list: try: if scriptfile.basedir != paths.script_path: sys.path = [scriptfile.basedir] + sys.path current_basedir = scriptfile.basedir script_module = script_loading.load_module(scriptfile.path) register_scripts_from_module(script_module) except Exception: errors.report(f"Error loading script: {scriptfile.filename}", exc_info=True) finally: sys.path = syspath current_basedir = paths.script_path timer.startup_timer.record(scriptfile.filename) global scripts_txt2img, scripts_img2img, scripts_postproc scripts_txt2img = ScriptRunner() scripts_img2img = ScriptRunner() scripts_postproc = scripts_postprocessing.ScriptPostprocessingRunner() def wrap_call(func, filename, funcname, *args, default=None, **kwargs): try: return func(*args, **kwargs) except Exception: errors.report(f"Error calling: {filename}/{funcname}", exc_info=True) return default class ScriptRunner: def __init__(self): self.scripts = [] self.selectable_scripts = [] self.alwayson_scripts = [] self.titles = [] self.title_map = {} self.infotext_fields = [] self.paste_field_names = [] self.inputs = [None] self.callback_map = {} self.callback_names = [ 'before_process', 'process', 'before_process_batch', 'after_extra_networks_activate', 'process_batch', 'postprocess', 'postprocess_batch', 'postprocess_batch_list', 'post_sample', 'on_mask_blend', 'postprocess_image', 'postprocess_maskoverlay', 'postprocess_image_after_composite', 'before_component', 'after_component', ] self.on_before_component_elem_id = {} """dict of callbacks to be called before an element is created; key=elem_id, value=list of callbacks""" self.on_after_component_elem_id = {} """dict of callbacks to be called after an element is created; key=elem_id, value=list of callbacks""" def initialize_scripts(self, is_img2img): from modules import scripts_auto_postprocessing self.scripts.clear() self.alwayson_scripts.clear() self.selectable_scripts.clear() auto_processing_scripts = scripts_auto_postprocessing.create_auto_preprocessing_script_data() for script_data in auto_processing_scripts + scripts_data: try: script = script_data.script_class() except Exception: errors.report(f"Error # failed to initialize Script {script_data.module}: ", exc_info=True) continue script.filename = script_data.path script.is_txt2img = not is_img2img script.is_img2img = is_img2img script.tabname = "img2img" if is_img2img else "txt2img" visibility = script.show(script.is_img2img) if visibility == AlwaysVisible: self.scripts.append(script) self.alwayson_scripts.append(script) script.alwayson = True elif visibility: self.scripts.append(script) self.selectable_scripts.append(script) self.callback_map.clear() self.apply_on_before_component_callbacks() def apply_on_before_component_callbacks(self): for script in self.scripts: on_before = script.on_before_component_elem_id or [] on_after = script.on_after_component_elem_id or [] for elem_id, callback in on_before: if elem_id not in self.on_before_component_elem_id: self.on_before_component_elem_id[elem_id] = [] self.on_before_component_elem_id[elem_id].append((callback, script)) for elem_id, callback in on_after: if elem_id not in self.on_after_component_elem_id: self.on_after_component_elem_id[elem_id] = [] self.on_after_component_elem_id[elem_id].append((callback, script)) on_before.clear() on_after.clear() def create_script_ui(self, script): script.args_from = len(self.inputs) script.args_to = len(self.inputs) try: self.create_script_ui_inner(script) except Exception: errors.report(f"Error creating UI for {script.name}: ", exc_info=True) def create_script_ui_inner(self, script): import modules.api.models as api_models controls = wrap_call(script.ui, script.filename, "ui", script.is_img2img) script.controls = controls if controls is None: return script.name = wrap_call(script.title, script.filename, "title", default=script.filename).lower() api_args = [] for control in controls: control.custom_script_source = os.path.basename(script.filename) arg_info = api_models.ScriptArg(label=control.label or "") for field in ("value", "minimum", "maximum", "step"): v = getattr(control, field, None) if v is not None: setattr(arg_info, field, v) choices = getattr(control, 'choices', None) # as of gradio 3.41, some items in choices are strings, and some are tuples where the first elem is the string if choices is not None: arg_info.choices = [x[0] if isinstance(x, tuple) else x for x in choices] api_args.append(arg_info) script.api_info = api_models.ScriptInfo( name=script.name, is_img2img=script.is_img2img, is_alwayson=script.alwayson, args=api_args, ) if script.infotext_fields is not None: self.infotext_fields += script.infotext_fields if script.paste_field_names is not None: self.paste_field_names += script.paste_field_names self.inputs += controls script.args_to = len(self.inputs) def setup_ui_for_section(self, section, scriptlist=None): if scriptlist is None: scriptlist = self.alwayson_scripts for script in scriptlist: if script.alwayson and script.section != section: continue if script.create_group: with gr.Group(visible=script.alwayson) as group: self.create_script_ui(script) script.group = group else: self.create_script_ui(script) def prepare_ui(self): self.inputs = [None] def setup_ui(self): all_titles = [wrap_call(script.title, script.filename, "title") or script.filename for script in self.scripts] self.title_map = {title.lower(): script for title, script in zip(all_titles, self.scripts)} self.titles = [wrap_call(script.title, script.filename, "title") or f"{script.filename} [error]" for script in self.selectable_scripts] self.setup_ui_for_section(None) dropdown = gr.Dropdown(label="Script", elem_id="script_list", choices=["None"] + self.titles, value="None", type="index") self.inputs[0] = dropdown self.setup_ui_for_section(None, self.selectable_scripts) def select_script(script_index): if script_index is None: script_index = 0 selected_script = self.selectable_scripts[script_index - 1] if script_index>0 else None return [gr.update(visible=selected_script == s) for s in self.selectable_scripts] def init_field(title): if title == 'None': return script_index = self.titles.index(title) self.selectable_scripts[script_index].group.visible = True dropdown.init_field = init_field dropdown.change( fn=select_script, inputs=[dropdown], outputs=[script.group for script in self.selectable_scripts] ) self.script_load_ctr = 0 def onload_script_visibility(params): title = params.get('Script', None) if title: try: title_index = self.titles.index(title) visibility = title_index == self.script_load_ctr self.script_load_ctr = (self.script_load_ctr + 1) % len(self.titles) return gr.update(visible=visibility) except ValueError: params['Script'] = None massage = f'Cannot find Script: "{title}"' print(massage) gr.Warning(massage) return gr.update(visible=False) self.infotext_fields.append((dropdown, lambda x: gr.update(value=x.get('Script', 'None')))) self.infotext_fields.extend([(script.group, onload_script_visibility) for script in self.selectable_scripts]) self.apply_on_before_component_callbacks() return self.inputs def run(self, p, *args): script_index = args[0] if script_index == 0 or script_index is None: return None script = self.selectable_scripts[script_index-1] if script is None: return None script_args = args[script.args_from:script.args_to] processed = script.run(p, *script_args) shared.total_tqdm.clear() return processed def list_scripts_for_method(self, method_name): if method_name in ('before_component', 'after_component'): return self.scripts else: return self.alwayson_scripts def create_ordered_callbacks_list(self, method_name, *, enable_user_sort=True): script_list = self.list_scripts_for_method(method_name) category = f'script_{method_name}' callbacks = [] for script in script_list: if getattr(script.__class__, method_name, None) == getattr(Script, method_name, None): continue script_callbacks.add_callback(callbacks, script, category=category, name=script.__class__.__name__, filename=script.filename) return script_callbacks.sort_callbacks(category, callbacks, enable_user_sort=enable_user_sort) def ordered_callbacks(self, method_name, *, enable_user_sort=True): script_list = self.list_scripts_for_method(method_name) category = f'script_{method_name}' scrpts_len, callbacks = self.callback_map.get(category, (-1, None)) if callbacks is None or scrpts_len != len(script_list): callbacks = self.create_ordered_callbacks_list(method_name, enable_user_sort=enable_user_sort) self.callback_map[category] = len(script_list), callbacks return callbacks def ordered_scripts(self, method_name): return [x.callback for x in self.ordered_callbacks(method_name)] def before_process(self, p): for script in self.ordered_scripts('before_process'): try: script_args = p.script_args[script.args_from:script.args_to] script.before_process(p, *script_args) except Exception: errors.report(f"Error running before_process: {script.filename}", exc_info=True) def process(self, p): for script in self.ordered_scripts('process'): try: script_args = p.script_args[script.args_from:script.args_to] script.process(p, *script_args) except Exception: errors.report(f"Error running process: {script.filename}", exc_info=True) def process_before_every_sampling(self, p, **kwargs): for script in self.ordered_scripts('process_before_every_sampling'): try: script_args = p.script_args[script.args_from:script.args_to] script.process_before_every_sampling(p, *script_args, **kwargs) except Exception: errors.report(f"Error running process_before_every_sampling: {script.filename}", exc_info=True) def before_process_batch(self, p, **kwargs): for script in self.ordered_scripts('before_process_batch'): try: script_args = p.script_args[script.args_from:script.args_to] script.before_process_batch(p, *script_args, **kwargs) except Exception: errors.report(f"Error running before_process_batch: {script.filename}", exc_info=True) def after_extra_networks_activate(self, p, **kwargs): for script in self.ordered_scripts('after_extra_networks_activate'): try: script_args = p.script_args[script.args_from:script.args_to] script.after_extra_networks_activate(p, *script_args, **kwargs) except Exception: errors.report(f"Error running after_extra_networks_activate: {script.filename}", exc_info=True) def process_batch(self, p, **kwargs): for script in self.ordered_scripts('process_batch'): try: script_args = p.script_args[script.args_from:script.args_to] script.process_batch(p, *script_args, **kwargs) except Exception: errors.report(f"Error running process_batch: {script.filename}", exc_info=True) def postprocess(self, p, processed): for script in self.ordered_scripts('postprocess'): try: script_args = p.script_args[script.args_from:script.args_to] script.postprocess(p, processed, *script_args) except Exception: errors.report(f"Error running postprocess: {script.filename}", exc_info=True) def postprocess_batch(self, p, images, **kwargs): for script in self.ordered_scripts('postprocess_batch'): try: script_args = p.script_args[script.args_from:script.args_to] script.postprocess_batch(p, *script_args, images=images, **kwargs) except Exception: errors.report(f"Error running postprocess_batch: {script.filename}", exc_info=True) def postprocess_batch_list(self, p, pp: PostprocessBatchListArgs, **kwargs): for script in self.ordered_scripts('postprocess_batch_list'): try: script_args = p.script_args[script.args_from:script.args_to] script.postprocess_batch_list(p, pp, *script_args, **kwargs) except Exception: errors.report(f"Error running postprocess_batch_list: {script.filename}", exc_info=True) def post_sample(self, p, ps: PostSampleArgs): for script in self.ordered_scripts('post_sample'): try: script_args = p.script_args[script.args_from:script.args_to] script.post_sample(p, ps, *script_args) except Exception: errors.report(f"Error running post_sample: {script.filename}", exc_info=True) def on_mask_blend(self, p, mba: MaskBlendArgs): for script in self.ordered_scripts('on_mask_blend'): try: script_args = p.script_args[script.args_from:script.args_to] script.on_mask_blend(p, mba, *script_args) except Exception: errors.report(f"Error running post_sample: {script.filename}", exc_info=True) def postprocess_image(self, p, pp: PostprocessImageArgs): for script in self.ordered_scripts('postprocess_image'): try: script_args = p.script_args[script.args_from:script.args_to] script.postprocess_image(p, pp, *script_args) except Exception: errors.report(f"Error running postprocess_image: {script.filename}", exc_info=True) def postprocess_maskoverlay(self, p, ppmo: PostProcessMaskOverlayArgs): for script in self.ordered_scripts('postprocess_maskoverlay'): try: script_args = p.script_args[script.args_from:script.args_to] script.postprocess_maskoverlay(p, ppmo, *script_args) except Exception: errors.report(f"Error running postprocess_image: {script.filename}", exc_info=True) def postprocess_image_after_composite(self, p, pp: PostprocessImageArgs): for script in self.ordered_scripts('postprocess_image_after_composite'): try: script_args = p.script_args[script.args_from:script.args_to] script.postprocess_image_after_composite(p, pp, *script_args) except Exception: errors.report(f"Error running postprocess_image_after_composite: {script.filename}", exc_info=True) def before_component(self, component, **kwargs): for callback, script in self.on_before_component_elem_id.get(kwargs.get("elem_id"), []): try: callback(OnComponent(component=component)) except Exception: errors.report(f"Error running on_before_component: {script.filename}", exc_info=True) for script in self.ordered_scripts('before_component'): try: script.before_component(component, **kwargs) except Exception: errors.report(f"Error running before_component: {script.filename}", exc_info=True) def after_component(self, component, **kwargs): for callback, script in self.on_after_component_elem_id.get(component.elem_id, []): try: callback(OnComponent(component=component)) except Exception: errors.report(f"Error running on_after_component: {script.filename}", exc_info=True) for script in self.ordered_scripts('after_component'): try: script.after_component(component, **kwargs) except Exception: errors.report(f"Error running after_component: {script.filename}", exc_info=True) def script(self, title): return self.title_map.get(title.lower()) def reload_sources(self, cache): for si, script in list(enumerate(self.scripts)): args_from = script.args_from args_to = script.args_to filename = script.filename module = cache.get(filename, None) if module is None: module = script_loading.load_module(script.filename) cache[filename] = module for script_class in module.__dict__.values(): if type(script_class) == type and issubclass(script_class, Script): self.scripts[si] = script_class() self.scripts[si].filename = filename self.scripts[si].args_from = args_from self.scripts[si].args_to = args_to def before_hr(self, p): for script in self.ordered_scripts('before_hr'): try: script_args = p.script_args[script.args_from:script.args_to] script.before_hr(p, *script_args) except Exception: errors.report(f"Error running before_hr: {script.filename}", exc_info=True) def setup_scrips(self, p, *, is_ui=True): for script in self.ordered_scripts('setup'): if not is_ui and script.setup_for_ui_only: continue try: script_args = p.script_args[script.args_from:script.args_to] script.setup(p, *script_args) except Exception: errors.report(f"Error running setup: {script.filename}", exc_info=True) def set_named_arg(self, args, script_name, arg_elem_id, value, fuzzy=False): script = next((x for x in self.scripts if x.name == script_name), None) if script is None: raise RuntimeError(f"script {script_name} not found") for i, control in enumerate(script.controls): if arg_elem_id in control.elem_id if fuzzy else arg_elem_id == control.elem_id: index = script.args_from + i if isinstance(args, tuple): return args[:index] + (value,) + args[index + 1:] elif isinstance(args, list): args[index] = value return args else: raise RuntimeError(f"args is not a list or tuple, but {type(args)}") raise RuntimeError(f"arg_elem_id {arg_elem_id} not found in script {script_name}") scripts_txt2img: ScriptRunner = None scripts_img2img: ScriptRunner = None scripts_postproc: scripts_postprocessing.ScriptPostprocessingRunner = None scripts_current: ScriptRunner = None def reload_script_body_only(): cache = {} scripts_txt2img.reload_sources(cache) scripts_img2img.reload_sources(cache) reload_scripts = load_scripts # compatibility alias
--- +++ @@ -1,880 +1,1040 @@-import os -import re -import sys -import inspect -from collections import namedtuple -from dataclasses import dataclass - -import gradio as gr - -from modules import shared, paths, script_callbacks, extensions, script_loading, scripts_postprocessing, errors, timer, util - -topological_sort = util.topological_sort - -AlwaysVisible = object() - -class MaskBlendArgs: - def __init__(self, current_latent, nmask, init_latent, mask, blended_latent, denoiser=None, sigma=None): - self.current_latent = current_latent - self.nmask = nmask - self.init_latent = init_latent - self.mask = mask - self.blended_latent = blended_latent - - self.denoiser = denoiser - self.is_final_blend = denoiser is None - self.sigma = sigma - -class PostSampleArgs: - def __init__(self, samples): - self.samples = samples - -class PostprocessImageArgs: - def __init__(self, image): - self.image = image - -class PostProcessMaskOverlayArgs: - def __init__(self, index, mask_for_overlay, overlay_image): - self.index = index - self.mask_for_overlay = mask_for_overlay - self.overlay_image = overlay_image - -class PostprocessBatchListArgs: - def __init__(self, images): - self.images = images - - -@dataclass -class OnComponent: - component: gr.blocks.Block - - -class Script: - name = None - """script's internal name derived from title""" - - section = None - """name of UI section that the script's controls will be placed into""" - - filename = None - args_from = None - args_to = None - alwayson = False - - is_txt2img = False - is_img2img = False - tabname = None - - group = None - """A gr.Group component that has all script's UI inside it.""" - - create_group = True - """If False, for alwayson scripts, a group component will not be created.""" - - infotext_fields = None - """if set in ui(), this is a list of pairs of gradio component + text; the text will be used when - parsing infotext to set the value for the component; see ui.py's txt2img_paste_fields for an example - """ - - paste_field_names = None - """if set in ui(), this is a list of names of infotext fields; the fields will be sent through the - various "Send to <X>" buttons when clicked - """ - - api_info = None - """Generated value of type modules.api.models.ScriptInfo with information about the script for API""" - - on_before_component_elem_id = None - """list of callbacks to be called before a component with an elem_id is created""" - - on_after_component_elem_id = None - """list of callbacks to be called after a component with an elem_id is created""" - - setup_for_ui_only = False - """If true, the script setup will only be run in Gradio UI, not in API""" - - controls = None - """A list of controls returned by the ui().""" - - def title(self): - - raise NotImplementedError() - - def ui(self, is_img2img): - - pass - - def show(self, is_img2img): - - return True - - def run(self, p, *args): - - pass - - def setup(self, p, *args): - pass - - def before_process(self, p, *args): - - pass - - def process(self, p, *args): - - pass - - def before_process_batch(self, p, *args, **kwargs): - - pass - - def after_extra_networks_activate(self, p, *args, **kwargs): - pass - - def process_before_every_sampling(self, p, *args, **kwargs): - pass - - def process_batch(self, p, *args, **kwargs): - - pass - - def postprocess_batch(self, p, *args, **kwargs): - - pass - - def postprocess_batch_list(self, p, pp: PostprocessBatchListArgs, *args, **kwargs): - - pass - - def on_mask_blend(self, p, mba: MaskBlendArgs, *args): - - pass - - def post_sample(self, p, ps: PostSampleArgs, *args): - - pass - - def postprocess_image(self, p, pp: PostprocessImageArgs, *args): - - pass - - def postprocess_maskoverlay(self, p, ppmo: PostProcessMaskOverlayArgs, *args): - - pass - - def postprocess_image_after_composite(self, p, pp: PostprocessImageArgs, *args): - - pass - - def postprocess(self, p, processed, *args): - - pass - - def before_component(self, component, **kwargs): - - pass - - def after_component(self, component, **kwargs): - - pass - - def on_before_component(self, callback, *, elem_id): - if self.on_before_component_elem_id is None: - self.on_before_component_elem_id = [] - - self.on_before_component_elem_id.append((elem_id, callback)) - - def on_after_component(self, callback, *, elem_id): - if self.on_after_component_elem_id is None: - self.on_after_component_elem_id = [] - - self.on_after_component_elem_id.append((elem_id, callback)) - - def describe(self): - return "" - - def elem_id(self, item_id): - - need_tabname = self.show(True) == self.show(False) - tabkind = 'img2img' if self.is_img2img else 'txt2img' - tabname = f"{tabkind}_" if need_tabname else "" - title = re.sub(r'[^a-z_0-9]', '', re.sub(r'\s', '_', self.title().lower())) - - return f'script_{tabname}{title}_{item_id}' - - def before_hr(self, p, *args): - pass - - -class ScriptBuiltinUI(Script): - setup_for_ui_only = True - - def elem_id(self, item_id): - - need_tabname = self.show(True) == self.show(False) - tabname = ('img2img' if self.is_img2img else 'txt2img') + "_" if need_tabname else "" - - return f'{tabname}{item_id}' - - def show(self, is_img2img): - return AlwaysVisible - - -current_basedir = paths.script_path - - -def basedir(): - return current_basedir - - -ScriptFile = namedtuple("ScriptFile", ["basedir", "filename", "path"]) - -scripts_data = [] -postprocessing_scripts_data = [] -ScriptClassData = namedtuple("ScriptClassData", ["script_class", "path", "basedir", "module"]) - - -@dataclass -class ScriptWithDependencies: - script_canonical_name: str - file: ScriptFile - requires: list - load_before: list - load_after: list - - -def list_scripts(scriptdirname, extension, *, include_extensions=True): - scripts = {} - - loaded_extensions = {ext.canonical_name: ext for ext in extensions.active()} - loaded_extensions_scripts = {ext.canonical_name: [] for ext in extensions.active()} - - # build script dependency map - root_script_basedir = os.path.join(paths.script_path, scriptdirname) - if os.path.exists(root_script_basedir): - for filename in sorted(os.listdir(root_script_basedir)): - if not os.path.isfile(os.path.join(root_script_basedir, filename)): - continue - - if os.path.splitext(filename)[1].lower() != extension: - continue - - script_file = ScriptFile(paths.script_path, filename, os.path.join(root_script_basedir, filename)) - scripts[filename] = ScriptWithDependencies(filename, script_file, [], [], []) - - if include_extensions: - for ext in extensions.active(): - extension_scripts_list = ext.list_files(scriptdirname, extension) - for extension_script in extension_scripts_list: - if not os.path.isfile(extension_script.path): - continue - - script_canonical_name = ("builtin/" if ext.is_builtin else "") + ext.canonical_name + "/" + extension_script.filename - relative_path = scriptdirname + "/" + extension_script.filename - - script = ScriptWithDependencies( - script_canonical_name=script_canonical_name, - file=extension_script, - requires=ext.metadata.get_script_requirements("Requires", relative_path, scriptdirname), - load_before=ext.metadata.get_script_requirements("Before", relative_path, scriptdirname), - load_after=ext.metadata.get_script_requirements("After", relative_path, scriptdirname), - ) - - scripts[script_canonical_name] = script - loaded_extensions_scripts[ext.canonical_name].append(script) - - for script_canonical_name, script in scripts.items(): - # load before requires inverse dependency - # in this case, append the script name into the load_after list of the specified script - for load_before in script.load_before: - # if this requires an individual script to be loaded before - other_script = scripts.get(load_before) - if other_script: - other_script.load_after.append(script_canonical_name) - - # if this requires an extension - other_extension_scripts = loaded_extensions_scripts.get(load_before) - if other_extension_scripts: - for other_script in other_extension_scripts: - other_script.load_after.append(script_canonical_name) - - # if After mentions an extension, remove it and instead add all of its scripts - for load_after in list(script.load_after): - if load_after not in scripts and load_after in loaded_extensions_scripts: - script.load_after.remove(load_after) - - for other_script in loaded_extensions_scripts.get(load_after, []): - script.load_after.append(other_script.script_canonical_name) - - dependencies = {} - - for script_canonical_name, script in scripts.items(): - for required_script in script.requires: - if required_script not in scripts and required_script not in loaded_extensions: - errors.report(f'Script "{script_canonical_name}" requires "{required_script}" to be loaded, but it is not.', exc_info=False) - - dependencies[script_canonical_name] = script.load_after - - ordered_scripts = topological_sort(dependencies) - scripts_list = [scripts[script_canonical_name].file for script_canonical_name in ordered_scripts] - - return scripts_list - - -def list_files_with_name(filename): - res = [] - - dirs = [paths.script_path] + [ext.path for ext in extensions.active()] - - for dirpath in dirs: - if not os.path.isdir(dirpath): - continue - - path = os.path.join(dirpath, filename) - if os.path.isfile(path): - res.append(path) - - return res - - -def load_scripts(): - global current_basedir - scripts_data.clear() - postprocessing_scripts_data.clear() - script_callbacks.clear_callbacks() - - scripts_list = list_scripts("scripts", ".py") + list_scripts("modules/processing_scripts", ".py", include_extensions=False) - - syspath = sys.path - - def register_scripts_from_module(module): - for script_class in module.__dict__.values(): - if not inspect.isclass(script_class): - continue - - if issubclass(script_class, Script): - scripts_data.append(ScriptClassData(script_class, scriptfile.path, scriptfile.basedir, module)) - elif issubclass(script_class, scripts_postprocessing.ScriptPostprocessing): - postprocessing_scripts_data.append(ScriptClassData(script_class, scriptfile.path, scriptfile.basedir, module)) - - # here the scripts_list is already ordered - # processing_script is not considered though - for scriptfile in scripts_list: - try: - if scriptfile.basedir != paths.script_path: - sys.path = [scriptfile.basedir] + sys.path - current_basedir = scriptfile.basedir - - script_module = script_loading.load_module(scriptfile.path) - register_scripts_from_module(script_module) - - except Exception: - errors.report(f"Error loading script: {scriptfile.filename}", exc_info=True) - - finally: - sys.path = syspath - current_basedir = paths.script_path - timer.startup_timer.record(scriptfile.filename) - - global scripts_txt2img, scripts_img2img, scripts_postproc - - scripts_txt2img = ScriptRunner() - scripts_img2img = ScriptRunner() - scripts_postproc = scripts_postprocessing.ScriptPostprocessingRunner() - - -def wrap_call(func, filename, funcname, *args, default=None, **kwargs): - try: - return func(*args, **kwargs) - except Exception: - errors.report(f"Error calling: {filename}/{funcname}", exc_info=True) - - return default - - -class ScriptRunner: - def __init__(self): - self.scripts = [] - self.selectable_scripts = [] - self.alwayson_scripts = [] - self.titles = [] - self.title_map = {} - self.infotext_fields = [] - self.paste_field_names = [] - self.inputs = [None] - - self.callback_map = {} - self.callback_names = [ - 'before_process', - 'process', - 'before_process_batch', - 'after_extra_networks_activate', - 'process_batch', - 'postprocess', - 'postprocess_batch', - 'postprocess_batch_list', - 'post_sample', - 'on_mask_blend', - 'postprocess_image', - 'postprocess_maskoverlay', - 'postprocess_image_after_composite', - 'before_component', - 'after_component', - ] - - self.on_before_component_elem_id = {} - """dict of callbacks to be called before an element is created; key=elem_id, value=list of callbacks""" - - self.on_after_component_elem_id = {} - """dict of callbacks to be called after an element is created; key=elem_id, value=list of callbacks""" - - def initialize_scripts(self, is_img2img): - from modules import scripts_auto_postprocessing - - self.scripts.clear() - self.alwayson_scripts.clear() - self.selectable_scripts.clear() - - auto_processing_scripts = scripts_auto_postprocessing.create_auto_preprocessing_script_data() - - for script_data in auto_processing_scripts + scripts_data: - try: - script = script_data.script_class() - except Exception: - errors.report(f"Error # failed to initialize Script {script_data.module}: ", exc_info=True) - continue - - script.filename = script_data.path - script.is_txt2img = not is_img2img - script.is_img2img = is_img2img - script.tabname = "img2img" if is_img2img else "txt2img" - - visibility = script.show(script.is_img2img) - - if visibility == AlwaysVisible: - self.scripts.append(script) - self.alwayson_scripts.append(script) - script.alwayson = True - - elif visibility: - self.scripts.append(script) - self.selectable_scripts.append(script) - - self.callback_map.clear() - - self.apply_on_before_component_callbacks() - - def apply_on_before_component_callbacks(self): - for script in self.scripts: - on_before = script.on_before_component_elem_id or [] - on_after = script.on_after_component_elem_id or [] - - for elem_id, callback in on_before: - if elem_id not in self.on_before_component_elem_id: - self.on_before_component_elem_id[elem_id] = [] - - self.on_before_component_elem_id[elem_id].append((callback, script)) - - for elem_id, callback in on_after: - if elem_id not in self.on_after_component_elem_id: - self.on_after_component_elem_id[elem_id] = [] - - self.on_after_component_elem_id[elem_id].append((callback, script)) - - on_before.clear() - on_after.clear() - - def create_script_ui(self, script): - - script.args_from = len(self.inputs) - script.args_to = len(self.inputs) - - try: - self.create_script_ui_inner(script) - except Exception: - errors.report(f"Error creating UI for {script.name}: ", exc_info=True) - - def create_script_ui_inner(self, script): - import modules.api.models as api_models - - controls = wrap_call(script.ui, script.filename, "ui", script.is_img2img) - script.controls = controls - - if controls is None: - return - - script.name = wrap_call(script.title, script.filename, "title", default=script.filename).lower() - - api_args = [] - - for control in controls: - control.custom_script_source = os.path.basename(script.filename) - - arg_info = api_models.ScriptArg(label=control.label or "") - - for field in ("value", "minimum", "maximum", "step"): - v = getattr(control, field, None) - if v is not None: - setattr(arg_info, field, v) - - choices = getattr(control, 'choices', None) # as of gradio 3.41, some items in choices are strings, and some are tuples where the first elem is the string - if choices is not None: - arg_info.choices = [x[0] if isinstance(x, tuple) else x for x in choices] - - api_args.append(arg_info) - - script.api_info = api_models.ScriptInfo( - name=script.name, - is_img2img=script.is_img2img, - is_alwayson=script.alwayson, - args=api_args, - ) - - if script.infotext_fields is not None: - self.infotext_fields += script.infotext_fields - - if script.paste_field_names is not None: - self.paste_field_names += script.paste_field_names - - self.inputs += controls - script.args_to = len(self.inputs) - - def setup_ui_for_section(self, section, scriptlist=None): - if scriptlist is None: - scriptlist = self.alwayson_scripts - - for script in scriptlist: - if script.alwayson and script.section != section: - continue - - if script.create_group: - with gr.Group(visible=script.alwayson) as group: - self.create_script_ui(script) - - script.group = group - else: - self.create_script_ui(script) - - def prepare_ui(self): - self.inputs = [None] - - def setup_ui(self): - all_titles = [wrap_call(script.title, script.filename, "title") or script.filename for script in self.scripts] - self.title_map = {title.lower(): script for title, script in zip(all_titles, self.scripts)} - self.titles = [wrap_call(script.title, script.filename, "title") or f"{script.filename} [error]" for script in self.selectable_scripts] - - self.setup_ui_for_section(None) - - dropdown = gr.Dropdown(label="Script", elem_id="script_list", choices=["None"] + self.titles, value="None", type="index") - self.inputs[0] = dropdown - - self.setup_ui_for_section(None, self.selectable_scripts) - - def select_script(script_index): - if script_index is None: - script_index = 0 - selected_script = self.selectable_scripts[script_index - 1] if script_index>0 else None - - return [gr.update(visible=selected_script == s) for s in self.selectable_scripts] - - def init_field(title): - - if title == 'None': - return - - script_index = self.titles.index(title) - self.selectable_scripts[script_index].group.visible = True - - dropdown.init_field = init_field - - dropdown.change( - fn=select_script, - inputs=[dropdown], - outputs=[script.group for script in self.selectable_scripts] - ) - - self.script_load_ctr = 0 - - def onload_script_visibility(params): - title = params.get('Script', None) - if title: - try: - title_index = self.titles.index(title) - visibility = title_index == self.script_load_ctr - self.script_load_ctr = (self.script_load_ctr + 1) % len(self.titles) - return gr.update(visible=visibility) - except ValueError: - params['Script'] = None - massage = f'Cannot find Script: "{title}"' - print(massage) - gr.Warning(massage) - return gr.update(visible=False) - - self.infotext_fields.append((dropdown, lambda x: gr.update(value=x.get('Script', 'None')))) - self.infotext_fields.extend([(script.group, onload_script_visibility) for script in self.selectable_scripts]) - - self.apply_on_before_component_callbacks() - - return self.inputs - - def run(self, p, *args): - script_index = args[0] - - if script_index == 0 or script_index is None: - return None - - script = self.selectable_scripts[script_index-1] - - if script is None: - return None - - script_args = args[script.args_from:script.args_to] - processed = script.run(p, *script_args) - - shared.total_tqdm.clear() - - return processed - - def list_scripts_for_method(self, method_name): - if method_name in ('before_component', 'after_component'): - return self.scripts - else: - return self.alwayson_scripts - - def create_ordered_callbacks_list(self, method_name, *, enable_user_sort=True): - script_list = self.list_scripts_for_method(method_name) - category = f'script_{method_name}' - callbacks = [] - - for script in script_list: - if getattr(script.__class__, method_name, None) == getattr(Script, method_name, None): - continue - - script_callbacks.add_callback(callbacks, script, category=category, name=script.__class__.__name__, filename=script.filename) - - return script_callbacks.sort_callbacks(category, callbacks, enable_user_sort=enable_user_sort) - - def ordered_callbacks(self, method_name, *, enable_user_sort=True): - script_list = self.list_scripts_for_method(method_name) - category = f'script_{method_name}' - - scrpts_len, callbacks = self.callback_map.get(category, (-1, None)) - - if callbacks is None or scrpts_len != len(script_list): - callbacks = self.create_ordered_callbacks_list(method_name, enable_user_sort=enable_user_sort) - self.callback_map[category] = len(script_list), callbacks - - return callbacks - - def ordered_scripts(self, method_name): - return [x.callback for x in self.ordered_callbacks(method_name)] - - def before_process(self, p): - for script in self.ordered_scripts('before_process'): - try: - script_args = p.script_args[script.args_from:script.args_to] - script.before_process(p, *script_args) - except Exception: - errors.report(f"Error running before_process: {script.filename}", exc_info=True) - - def process(self, p): - for script in self.ordered_scripts('process'): - try: - script_args = p.script_args[script.args_from:script.args_to] - script.process(p, *script_args) - except Exception: - errors.report(f"Error running process: {script.filename}", exc_info=True) - - def process_before_every_sampling(self, p, **kwargs): - for script in self.ordered_scripts('process_before_every_sampling'): - try: - script_args = p.script_args[script.args_from:script.args_to] - script.process_before_every_sampling(p, *script_args, **kwargs) - except Exception: - errors.report(f"Error running process_before_every_sampling: {script.filename}", exc_info=True) - - def before_process_batch(self, p, **kwargs): - for script in self.ordered_scripts('before_process_batch'): - try: - script_args = p.script_args[script.args_from:script.args_to] - script.before_process_batch(p, *script_args, **kwargs) - except Exception: - errors.report(f"Error running before_process_batch: {script.filename}", exc_info=True) - - def after_extra_networks_activate(self, p, **kwargs): - for script in self.ordered_scripts('after_extra_networks_activate'): - try: - script_args = p.script_args[script.args_from:script.args_to] - script.after_extra_networks_activate(p, *script_args, **kwargs) - except Exception: - errors.report(f"Error running after_extra_networks_activate: {script.filename}", exc_info=True) - - def process_batch(self, p, **kwargs): - for script in self.ordered_scripts('process_batch'): - try: - script_args = p.script_args[script.args_from:script.args_to] - script.process_batch(p, *script_args, **kwargs) - except Exception: - errors.report(f"Error running process_batch: {script.filename}", exc_info=True) - - def postprocess(self, p, processed): - for script in self.ordered_scripts('postprocess'): - try: - script_args = p.script_args[script.args_from:script.args_to] - script.postprocess(p, processed, *script_args) - except Exception: - errors.report(f"Error running postprocess: {script.filename}", exc_info=True) - - def postprocess_batch(self, p, images, **kwargs): - for script in self.ordered_scripts('postprocess_batch'): - try: - script_args = p.script_args[script.args_from:script.args_to] - script.postprocess_batch(p, *script_args, images=images, **kwargs) - except Exception: - errors.report(f"Error running postprocess_batch: {script.filename}", exc_info=True) - - def postprocess_batch_list(self, p, pp: PostprocessBatchListArgs, **kwargs): - for script in self.ordered_scripts('postprocess_batch_list'): - try: - script_args = p.script_args[script.args_from:script.args_to] - script.postprocess_batch_list(p, pp, *script_args, **kwargs) - except Exception: - errors.report(f"Error running postprocess_batch_list: {script.filename}", exc_info=True) - - def post_sample(self, p, ps: PostSampleArgs): - for script in self.ordered_scripts('post_sample'): - try: - script_args = p.script_args[script.args_from:script.args_to] - script.post_sample(p, ps, *script_args) - except Exception: - errors.report(f"Error running post_sample: {script.filename}", exc_info=True) - - def on_mask_blend(self, p, mba: MaskBlendArgs): - for script in self.ordered_scripts('on_mask_blend'): - try: - script_args = p.script_args[script.args_from:script.args_to] - script.on_mask_blend(p, mba, *script_args) - except Exception: - errors.report(f"Error running post_sample: {script.filename}", exc_info=True) - - def postprocess_image(self, p, pp: PostprocessImageArgs): - for script in self.ordered_scripts('postprocess_image'): - try: - script_args = p.script_args[script.args_from:script.args_to] - script.postprocess_image(p, pp, *script_args) - except Exception: - errors.report(f"Error running postprocess_image: {script.filename}", exc_info=True) - - def postprocess_maskoverlay(self, p, ppmo: PostProcessMaskOverlayArgs): - for script in self.ordered_scripts('postprocess_maskoverlay'): - try: - script_args = p.script_args[script.args_from:script.args_to] - script.postprocess_maskoverlay(p, ppmo, *script_args) - except Exception: - errors.report(f"Error running postprocess_image: {script.filename}", exc_info=True) - - def postprocess_image_after_composite(self, p, pp: PostprocessImageArgs): - for script in self.ordered_scripts('postprocess_image_after_composite'): - try: - script_args = p.script_args[script.args_from:script.args_to] - script.postprocess_image_after_composite(p, pp, *script_args) - except Exception: - errors.report(f"Error running postprocess_image_after_composite: {script.filename}", exc_info=True) - - def before_component(self, component, **kwargs): - for callback, script in self.on_before_component_elem_id.get(kwargs.get("elem_id"), []): - try: - callback(OnComponent(component=component)) - except Exception: - errors.report(f"Error running on_before_component: {script.filename}", exc_info=True) - - for script in self.ordered_scripts('before_component'): - try: - script.before_component(component, **kwargs) - except Exception: - errors.report(f"Error running before_component: {script.filename}", exc_info=True) - - def after_component(self, component, **kwargs): - for callback, script in self.on_after_component_elem_id.get(component.elem_id, []): - try: - callback(OnComponent(component=component)) - except Exception: - errors.report(f"Error running on_after_component: {script.filename}", exc_info=True) - - for script in self.ordered_scripts('after_component'): - try: - script.after_component(component, **kwargs) - except Exception: - errors.report(f"Error running after_component: {script.filename}", exc_info=True) - - def script(self, title): - return self.title_map.get(title.lower()) - - def reload_sources(self, cache): - for si, script in list(enumerate(self.scripts)): - args_from = script.args_from - args_to = script.args_to - filename = script.filename - - module = cache.get(filename, None) - if module is None: - module = script_loading.load_module(script.filename) - cache[filename] = module - - for script_class in module.__dict__.values(): - if type(script_class) == type and issubclass(script_class, Script): - self.scripts[si] = script_class() - self.scripts[si].filename = filename - self.scripts[si].args_from = args_from - self.scripts[si].args_to = args_to - - def before_hr(self, p): - for script in self.ordered_scripts('before_hr'): - try: - script_args = p.script_args[script.args_from:script.args_to] - script.before_hr(p, *script_args) - except Exception: - errors.report(f"Error running before_hr: {script.filename}", exc_info=True) - - def setup_scrips(self, p, *, is_ui=True): - for script in self.ordered_scripts('setup'): - if not is_ui and script.setup_for_ui_only: - continue - - try: - script_args = p.script_args[script.args_from:script.args_to] - script.setup(p, *script_args) - except Exception: - errors.report(f"Error running setup: {script.filename}", exc_info=True) - - def set_named_arg(self, args, script_name, arg_elem_id, value, fuzzy=False): - script = next((x for x in self.scripts if x.name == script_name), None) - if script is None: - raise RuntimeError(f"script {script_name} not found") - - for i, control in enumerate(script.controls): - if arg_elem_id in control.elem_id if fuzzy else arg_elem_id == control.elem_id: - index = script.args_from + i - - if isinstance(args, tuple): - return args[:index] + (value,) + args[index + 1:] - elif isinstance(args, list): - args[index] = value - return args - else: - raise RuntimeError(f"args is not a list or tuple, but {type(args)}") - raise RuntimeError(f"arg_elem_id {arg_elem_id} not found in script {script_name}") - - -scripts_txt2img: ScriptRunner = None -scripts_img2img: ScriptRunner = None -scripts_postproc: scripts_postprocessing.ScriptPostprocessingRunner = None -scripts_current: ScriptRunner = None - - -def reload_script_body_only(): - cache = {} - scripts_txt2img.reload_sources(cache) - scripts_img2img.reload_sources(cache) - - -reload_scripts = load_scripts # compatibility alias+import os +import re +import sys +import inspect +from collections import namedtuple +from dataclasses import dataclass + +import gradio as gr + +from modules import shared, paths, script_callbacks, extensions, script_loading, scripts_postprocessing, errors, timer, util + +topological_sort = util.topological_sort + +AlwaysVisible = object() + +class MaskBlendArgs: + def __init__(self, current_latent, nmask, init_latent, mask, blended_latent, denoiser=None, sigma=None): + self.current_latent = current_latent + self.nmask = nmask + self.init_latent = init_latent + self.mask = mask + self.blended_latent = blended_latent + + self.denoiser = denoiser + self.is_final_blend = denoiser is None + self.sigma = sigma + +class PostSampleArgs: + def __init__(self, samples): + self.samples = samples + +class PostprocessImageArgs: + def __init__(self, image): + self.image = image + +class PostProcessMaskOverlayArgs: + def __init__(self, index, mask_for_overlay, overlay_image): + self.index = index + self.mask_for_overlay = mask_for_overlay + self.overlay_image = overlay_image + +class PostprocessBatchListArgs: + def __init__(self, images): + self.images = images + + +@dataclass +class OnComponent: + component: gr.blocks.Block + + +class Script: + name = None + """script's internal name derived from title""" + + section = None + """name of UI section that the script's controls will be placed into""" + + filename = None + args_from = None + args_to = None + alwayson = False + + is_txt2img = False + is_img2img = False + tabname = None + + group = None + """A gr.Group component that has all script's UI inside it.""" + + create_group = True + """If False, for alwayson scripts, a group component will not be created.""" + + infotext_fields = None + """if set in ui(), this is a list of pairs of gradio component + text; the text will be used when + parsing infotext to set the value for the component; see ui.py's txt2img_paste_fields for an example + """ + + paste_field_names = None + """if set in ui(), this is a list of names of infotext fields; the fields will be sent through the + various "Send to <X>" buttons when clicked + """ + + api_info = None + """Generated value of type modules.api.models.ScriptInfo with information about the script for API""" + + on_before_component_elem_id = None + """list of callbacks to be called before a component with an elem_id is created""" + + on_after_component_elem_id = None + """list of callbacks to be called after a component with an elem_id is created""" + + setup_for_ui_only = False + """If true, the script setup will only be run in Gradio UI, not in API""" + + controls = None + """A list of controls returned by the ui().""" + + def title(self): + """this function should return the title of the script. This is what will be displayed in the dropdown menu.""" + + raise NotImplementedError() + + def ui(self, is_img2img): + """this function should create gradio UI elements. See https://gradio.app/docs/#components + The return value should be an array of all components that are used in processing. + Values of those returned components will be passed to run() and process() functions. + """ + + pass + + def show(self, is_img2img): + """ + is_img2img is True if this function is called for the img2img interface, and False otherwise + + This function should return: + - False if the script should not be shown in UI at all + - True if the script should be shown in UI if it's selected in the scripts dropdown + - script.AlwaysVisible if the script should be shown in UI at all times + """ + + return True + + def run(self, p, *args): + """ + This function is called if the script has been selected in the script dropdown. + It must do all processing and return the Processed object with results, same as + one returned by processing.process_images. + + Usually the processing is done by calling the processing.process_images function. + + args contains all values returned by components from ui() + """ + + pass + + def setup(self, p, *args): + """For AlwaysVisible scripts, this function is called when the processing object is set up, before any processing starts. + args contains all values returned by components from ui(). + """ + pass + + def before_process(self, p, *args): + """ + This function is called very early during processing begins for AlwaysVisible scripts. + You can modify the processing object (p) here, inject hooks, etc. + args contains all values returned by components from ui() + """ + + pass + + def process(self, p, *args): + """ + This function is called before processing begins for AlwaysVisible scripts. + You can modify the processing object (p) here, inject hooks, etc. + args contains all values returned by components from ui() + """ + + pass + + def before_process_batch(self, p, *args, **kwargs): + """ + Called before extra networks are parsed from the prompt, so you can add + new extra network keywords to the prompt with this callback. + + **kwargs will have those items: + - batch_number - index of current batch, from 0 to number of batches-1 + - prompts - list of prompts for current batch; you can change contents of this list but changing the number of entries will likely break things + - seeds - list of seeds for current batch + - subseeds - list of subseeds for current batch + """ + + pass + + def after_extra_networks_activate(self, p, *args, **kwargs): + """ + Called after extra networks activation, before conds calculation + allow modification of the network after extra networks activation been applied + won't be call if p.disable_extra_networks + + **kwargs will have those items: + - batch_number - index of current batch, from 0 to number of batches-1 + - prompts - list of prompts for current batch; you can change contents of this list but changing the number of entries will likely break things + - seeds - list of seeds for current batch + - subseeds - list of subseeds for current batch + - extra_network_data - list of ExtraNetworkParams for current stage + """ + pass + + def process_before_every_sampling(self, p, *args, **kwargs): + """ + Similar to process(), called before every sampling. + If you use high-res fix, this will be called two times. + """ + pass + + def process_batch(self, p, *args, **kwargs): + """ + Same as process(), but called for every batch. + + **kwargs will have those items: + - batch_number - index of current batch, from 0 to number of batches-1 + - prompts - list of prompts for current batch; you can change contents of this list but changing the number of entries will likely break things + - seeds - list of seeds for current batch + - subseeds - list of subseeds for current batch + """ + + pass + + def postprocess_batch(self, p, *args, **kwargs): + """ + Same as process_batch(), but called for every batch after it has been generated. + + **kwargs will have same items as process_batch, and also: + - batch_number - index of current batch, from 0 to number of batches-1 + - images - torch tensor with all generated images, with values ranging from 0 to 1; + """ + + pass + + def postprocess_batch_list(self, p, pp: PostprocessBatchListArgs, *args, **kwargs): + """ + Same as postprocess_batch(), but receives batch images as a list of 3D tensors instead of a 4D tensor. + This is useful when you want to update the entire batch instead of individual images. + + You can modify the postprocessing object (pp) to update the images in the batch, remove images, add images, etc. + If the number of images is different from the batch size when returning, + then the script has the responsibility to also update the following attributes in the processing object (p): + - p.prompts + - p.negative_prompts + - p.seeds + - p.subseeds + + **kwargs will have same items as process_batch, and also: + - batch_number - index of current batch, from 0 to number of batches-1 + """ + + pass + + def on_mask_blend(self, p, mba: MaskBlendArgs, *args): + """ + Called in inpainting mode when the original content is blended with the inpainted content. + This is called at every step in the denoising process and once at the end. + If is_final_blend is true, this is called for the final blending stage. + Otherwise, denoiser and sigma are defined and may be used to inform the procedure. + """ + + pass + + def post_sample(self, p, ps: PostSampleArgs, *args): + """ + Called after the samples have been generated, + but before they have been decoded by the VAE, if applicable. + Check getattr(samples, 'already_decoded', False) to test if the images are decoded. + """ + + pass + + def postprocess_image(self, p, pp: PostprocessImageArgs, *args): + """ + Called for every image after it has been generated. + """ + + pass + + def postprocess_maskoverlay(self, p, ppmo: PostProcessMaskOverlayArgs, *args): + """ + Called for every image after it has been generated. + """ + + pass + + def postprocess_image_after_composite(self, p, pp: PostprocessImageArgs, *args): + """ + Called for every image after it has been generated. + Same as postprocess_image but after inpaint_full_res composite + So that it operates on the full image instead of the inpaint_full_res crop region. + """ + + pass + + def postprocess(self, p, processed, *args): + """ + This function is called after processing ends for AlwaysVisible scripts. + args contains all values returned by components from ui() + """ + + pass + + def before_component(self, component, **kwargs): + """ + Called before a component is created. + Use elem_id/label fields of kwargs to figure out which component it is. + This can be useful to inject your own components somewhere in the middle of vanilla UI. + You can return created components in the ui() function to add them to the list of arguments for your processing functions + """ + + pass + + def after_component(self, component, **kwargs): + """ + Called after a component is created. Same as above. + """ + + pass + + def on_before_component(self, callback, *, elem_id): + """ + Calls callback before a component is created. The callback function is called with a single argument of type OnComponent. + + May be called in show() or ui() - but it may be too late in latter as some components may already be created. + + This function is an alternative to before_component in that it also cllows to run before a component is created, but + it doesn't require to be called for every created component - just for the one you need. + """ + if self.on_before_component_elem_id is None: + self.on_before_component_elem_id = [] + + self.on_before_component_elem_id.append((elem_id, callback)) + + def on_after_component(self, callback, *, elem_id): + """ + Calls callback after a component is created. The callback function is called with a single argument of type OnComponent. + """ + if self.on_after_component_elem_id is None: + self.on_after_component_elem_id = [] + + self.on_after_component_elem_id.append((elem_id, callback)) + + def describe(self): + """unused""" + return "" + + def elem_id(self, item_id): + """helper function to generate id for a HTML element, constructs final id out of script name, tab and user-supplied item_id""" + + need_tabname = self.show(True) == self.show(False) + tabkind = 'img2img' if self.is_img2img else 'txt2img' + tabname = f"{tabkind}_" if need_tabname else "" + title = re.sub(r'[^a-z_0-9]', '', re.sub(r'\s', '_', self.title().lower())) + + return f'script_{tabname}{title}_{item_id}' + + def before_hr(self, p, *args): + """ + This function is called before hires fix start. + """ + pass + + +class ScriptBuiltinUI(Script): + setup_for_ui_only = True + + def elem_id(self, item_id): + """helper function to generate id for a HTML element, constructs final id out of tab and user-supplied item_id""" + + need_tabname = self.show(True) == self.show(False) + tabname = ('img2img' if self.is_img2img else 'txt2img') + "_" if need_tabname else "" + + return f'{tabname}{item_id}' + + def show(self, is_img2img): + return AlwaysVisible + + +current_basedir = paths.script_path + + +def basedir(): + """returns the base directory for the current script. For scripts in the main scripts directory, + this is the main directory (where webui.py resides), and for scripts in extensions directory + (ie extensions/aesthetic/script/aesthetic.py), this is extension's directory (extensions/aesthetic) + """ + return current_basedir + + +ScriptFile = namedtuple("ScriptFile", ["basedir", "filename", "path"]) + +scripts_data = [] +postprocessing_scripts_data = [] +ScriptClassData = namedtuple("ScriptClassData", ["script_class", "path", "basedir", "module"]) + + +@dataclass +class ScriptWithDependencies: + script_canonical_name: str + file: ScriptFile + requires: list + load_before: list + load_after: list + + +def list_scripts(scriptdirname, extension, *, include_extensions=True): + scripts = {} + + loaded_extensions = {ext.canonical_name: ext for ext in extensions.active()} + loaded_extensions_scripts = {ext.canonical_name: [] for ext in extensions.active()} + + # build script dependency map + root_script_basedir = os.path.join(paths.script_path, scriptdirname) + if os.path.exists(root_script_basedir): + for filename in sorted(os.listdir(root_script_basedir)): + if not os.path.isfile(os.path.join(root_script_basedir, filename)): + continue + + if os.path.splitext(filename)[1].lower() != extension: + continue + + script_file = ScriptFile(paths.script_path, filename, os.path.join(root_script_basedir, filename)) + scripts[filename] = ScriptWithDependencies(filename, script_file, [], [], []) + + if include_extensions: + for ext in extensions.active(): + extension_scripts_list = ext.list_files(scriptdirname, extension) + for extension_script in extension_scripts_list: + if not os.path.isfile(extension_script.path): + continue + + script_canonical_name = ("builtin/" if ext.is_builtin else "") + ext.canonical_name + "/" + extension_script.filename + relative_path = scriptdirname + "/" + extension_script.filename + + script = ScriptWithDependencies( + script_canonical_name=script_canonical_name, + file=extension_script, + requires=ext.metadata.get_script_requirements("Requires", relative_path, scriptdirname), + load_before=ext.metadata.get_script_requirements("Before", relative_path, scriptdirname), + load_after=ext.metadata.get_script_requirements("After", relative_path, scriptdirname), + ) + + scripts[script_canonical_name] = script + loaded_extensions_scripts[ext.canonical_name].append(script) + + for script_canonical_name, script in scripts.items(): + # load before requires inverse dependency + # in this case, append the script name into the load_after list of the specified script + for load_before in script.load_before: + # if this requires an individual script to be loaded before + other_script = scripts.get(load_before) + if other_script: + other_script.load_after.append(script_canonical_name) + + # if this requires an extension + other_extension_scripts = loaded_extensions_scripts.get(load_before) + if other_extension_scripts: + for other_script in other_extension_scripts: + other_script.load_after.append(script_canonical_name) + + # if After mentions an extension, remove it and instead add all of its scripts + for load_after in list(script.load_after): + if load_after not in scripts and load_after in loaded_extensions_scripts: + script.load_after.remove(load_after) + + for other_script in loaded_extensions_scripts.get(load_after, []): + script.load_after.append(other_script.script_canonical_name) + + dependencies = {} + + for script_canonical_name, script in scripts.items(): + for required_script in script.requires: + if required_script not in scripts and required_script not in loaded_extensions: + errors.report(f'Script "{script_canonical_name}" requires "{required_script}" to be loaded, but it is not.', exc_info=False) + + dependencies[script_canonical_name] = script.load_after + + ordered_scripts = topological_sort(dependencies) + scripts_list = [scripts[script_canonical_name].file for script_canonical_name in ordered_scripts] + + return scripts_list + + +def list_files_with_name(filename): + res = [] + + dirs = [paths.script_path] + [ext.path for ext in extensions.active()] + + for dirpath in dirs: + if not os.path.isdir(dirpath): + continue + + path = os.path.join(dirpath, filename) + if os.path.isfile(path): + res.append(path) + + return res + + +def load_scripts(): + global current_basedir + scripts_data.clear() + postprocessing_scripts_data.clear() + script_callbacks.clear_callbacks() + + scripts_list = list_scripts("scripts", ".py") + list_scripts("modules/processing_scripts", ".py", include_extensions=False) + + syspath = sys.path + + def register_scripts_from_module(module): + for script_class in module.__dict__.values(): + if not inspect.isclass(script_class): + continue + + if issubclass(script_class, Script): + scripts_data.append(ScriptClassData(script_class, scriptfile.path, scriptfile.basedir, module)) + elif issubclass(script_class, scripts_postprocessing.ScriptPostprocessing): + postprocessing_scripts_data.append(ScriptClassData(script_class, scriptfile.path, scriptfile.basedir, module)) + + # here the scripts_list is already ordered + # processing_script is not considered though + for scriptfile in scripts_list: + try: + if scriptfile.basedir != paths.script_path: + sys.path = [scriptfile.basedir] + sys.path + current_basedir = scriptfile.basedir + + script_module = script_loading.load_module(scriptfile.path) + register_scripts_from_module(script_module) + + except Exception: + errors.report(f"Error loading script: {scriptfile.filename}", exc_info=True) + + finally: + sys.path = syspath + current_basedir = paths.script_path + timer.startup_timer.record(scriptfile.filename) + + global scripts_txt2img, scripts_img2img, scripts_postproc + + scripts_txt2img = ScriptRunner() + scripts_img2img = ScriptRunner() + scripts_postproc = scripts_postprocessing.ScriptPostprocessingRunner() + + +def wrap_call(func, filename, funcname, *args, default=None, **kwargs): + try: + return func(*args, **kwargs) + except Exception: + errors.report(f"Error calling: {filename}/{funcname}", exc_info=True) + + return default + + +class ScriptRunner: + def __init__(self): + self.scripts = [] + self.selectable_scripts = [] + self.alwayson_scripts = [] + self.titles = [] + self.title_map = {} + self.infotext_fields = [] + self.paste_field_names = [] + self.inputs = [None] + + self.callback_map = {} + self.callback_names = [ + 'before_process', + 'process', + 'before_process_batch', + 'after_extra_networks_activate', + 'process_batch', + 'postprocess', + 'postprocess_batch', + 'postprocess_batch_list', + 'post_sample', + 'on_mask_blend', + 'postprocess_image', + 'postprocess_maskoverlay', + 'postprocess_image_after_composite', + 'before_component', + 'after_component', + ] + + self.on_before_component_elem_id = {} + """dict of callbacks to be called before an element is created; key=elem_id, value=list of callbacks""" + + self.on_after_component_elem_id = {} + """dict of callbacks to be called after an element is created; key=elem_id, value=list of callbacks""" + + def initialize_scripts(self, is_img2img): + from modules import scripts_auto_postprocessing + + self.scripts.clear() + self.alwayson_scripts.clear() + self.selectable_scripts.clear() + + auto_processing_scripts = scripts_auto_postprocessing.create_auto_preprocessing_script_data() + + for script_data in auto_processing_scripts + scripts_data: + try: + script = script_data.script_class() + except Exception: + errors.report(f"Error # failed to initialize Script {script_data.module}: ", exc_info=True) + continue + + script.filename = script_data.path + script.is_txt2img = not is_img2img + script.is_img2img = is_img2img + script.tabname = "img2img" if is_img2img else "txt2img" + + visibility = script.show(script.is_img2img) + + if visibility == AlwaysVisible: + self.scripts.append(script) + self.alwayson_scripts.append(script) + script.alwayson = True + + elif visibility: + self.scripts.append(script) + self.selectable_scripts.append(script) + + self.callback_map.clear() + + self.apply_on_before_component_callbacks() + + def apply_on_before_component_callbacks(self): + for script in self.scripts: + on_before = script.on_before_component_elem_id or [] + on_after = script.on_after_component_elem_id or [] + + for elem_id, callback in on_before: + if elem_id not in self.on_before_component_elem_id: + self.on_before_component_elem_id[elem_id] = [] + + self.on_before_component_elem_id[elem_id].append((callback, script)) + + for elem_id, callback in on_after: + if elem_id not in self.on_after_component_elem_id: + self.on_after_component_elem_id[elem_id] = [] + + self.on_after_component_elem_id[elem_id].append((callback, script)) + + on_before.clear() + on_after.clear() + + def create_script_ui(self, script): + + script.args_from = len(self.inputs) + script.args_to = len(self.inputs) + + try: + self.create_script_ui_inner(script) + except Exception: + errors.report(f"Error creating UI for {script.name}: ", exc_info=True) + + def create_script_ui_inner(self, script): + import modules.api.models as api_models + + controls = wrap_call(script.ui, script.filename, "ui", script.is_img2img) + script.controls = controls + + if controls is None: + return + + script.name = wrap_call(script.title, script.filename, "title", default=script.filename).lower() + + api_args = [] + + for control in controls: + control.custom_script_source = os.path.basename(script.filename) + + arg_info = api_models.ScriptArg(label=control.label or "") + + for field in ("value", "minimum", "maximum", "step"): + v = getattr(control, field, None) + if v is not None: + setattr(arg_info, field, v) + + choices = getattr(control, 'choices', None) # as of gradio 3.41, some items in choices are strings, and some are tuples where the first elem is the string + if choices is not None: + arg_info.choices = [x[0] if isinstance(x, tuple) else x for x in choices] + + api_args.append(arg_info) + + script.api_info = api_models.ScriptInfo( + name=script.name, + is_img2img=script.is_img2img, + is_alwayson=script.alwayson, + args=api_args, + ) + + if script.infotext_fields is not None: + self.infotext_fields += script.infotext_fields + + if script.paste_field_names is not None: + self.paste_field_names += script.paste_field_names + + self.inputs += controls + script.args_to = len(self.inputs) + + def setup_ui_for_section(self, section, scriptlist=None): + if scriptlist is None: + scriptlist = self.alwayson_scripts + + for script in scriptlist: + if script.alwayson and script.section != section: + continue + + if script.create_group: + with gr.Group(visible=script.alwayson) as group: + self.create_script_ui(script) + + script.group = group + else: + self.create_script_ui(script) + + def prepare_ui(self): + self.inputs = [None] + + def setup_ui(self): + all_titles = [wrap_call(script.title, script.filename, "title") or script.filename for script in self.scripts] + self.title_map = {title.lower(): script for title, script in zip(all_titles, self.scripts)} + self.titles = [wrap_call(script.title, script.filename, "title") or f"{script.filename} [error]" for script in self.selectable_scripts] + + self.setup_ui_for_section(None) + + dropdown = gr.Dropdown(label="Script", elem_id="script_list", choices=["None"] + self.titles, value="None", type="index") + self.inputs[0] = dropdown + + self.setup_ui_for_section(None, self.selectable_scripts) + + def select_script(script_index): + if script_index is None: + script_index = 0 + selected_script = self.selectable_scripts[script_index - 1] if script_index>0 else None + + return [gr.update(visible=selected_script == s) for s in self.selectable_scripts] + + def init_field(title): + """called when an initial value is set from ui-config.json to show script's UI components""" + + if title == 'None': + return + + script_index = self.titles.index(title) + self.selectable_scripts[script_index].group.visible = True + + dropdown.init_field = init_field + + dropdown.change( + fn=select_script, + inputs=[dropdown], + outputs=[script.group for script in self.selectable_scripts] + ) + + self.script_load_ctr = 0 + + def onload_script_visibility(params): + title = params.get('Script', None) + if title: + try: + title_index = self.titles.index(title) + visibility = title_index == self.script_load_ctr + self.script_load_ctr = (self.script_load_ctr + 1) % len(self.titles) + return gr.update(visible=visibility) + except ValueError: + params['Script'] = None + massage = f'Cannot find Script: "{title}"' + print(massage) + gr.Warning(massage) + return gr.update(visible=False) + + self.infotext_fields.append((dropdown, lambda x: gr.update(value=x.get('Script', 'None')))) + self.infotext_fields.extend([(script.group, onload_script_visibility) for script in self.selectable_scripts]) + + self.apply_on_before_component_callbacks() + + return self.inputs + + def run(self, p, *args): + script_index = args[0] + + if script_index == 0 or script_index is None: + return None + + script = self.selectable_scripts[script_index-1] + + if script is None: + return None + + script_args = args[script.args_from:script.args_to] + processed = script.run(p, *script_args) + + shared.total_tqdm.clear() + + return processed + + def list_scripts_for_method(self, method_name): + if method_name in ('before_component', 'after_component'): + return self.scripts + else: + return self.alwayson_scripts + + def create_ordered_callbacks_list(self, method_name, *, enable_user_sort=True): + script_list = self.list_scripts_for_method(method_name) + category = f'script_{method_name}' + callbacks = [] + + for script in script_list: + if getattr(script.__class__, method_name, None) == getattr(Script, method_name, None): + continue + + script_callbacks.add_callback(callbacks, script, category=category, name=script.__class__.__name__, filename=script.filename) + + return script_callbacks.sort_callbacks(category, callbacks, enable_user_sort=enable_user_sort) + + def ordered_callbacks(self, method_name, *, enable_user_sort=True): + script_list = self.list_scripts_for_method(method_name) + category = f'script_{method_name}' + + scrpts_len, callbacks = self.callback_map.get(category, (-1, None)) + + if callbacks is None or scrpts_len != len(script_list): + callbacks = self.create_ordered_callbacks_list(method_name, enable_user_sort=enable_user_sort) + self.callback_map[category] = len(script_list), callbacks + + return callbacks + + def ordered_scripts(self, method_name): + return [x.callback for x in self.ordered_callbacks(method_name)] + + def before_process(self, p): + for script in self.ordered_scripts('before_process'): + try: + script_args = p.script_args[script.args_from:script.args_to] + script.before_process(p, *script_args) + except Exception: + errors.report(f"Error running before_process: {script.filename}", exc_info=True) + + def process(self, p): + for script in self.ordered_scripts('process'): + try: + script_args = p.script_args[script.args_from:script.args_to] + script.process(p, *script_args) + except Exception: + errors.report(f"Error running process: {script.filename}", exc_info=True) + + def process_before_every_sampling(self, p, **kwargs): + for script in self.ordered_scripts('process_before_every_sampling'): + try: + script_args = p.script_args[script.args_from:script.args_to] + script.process_before_every_sampling(p, *script_args, **kwargs) + except Exception: + errors.report(f"Error running process_before_every_sampling: {script.filename}", exc_info=True) + + def before_process_batch(self, p, **kwargs): + for script in self.ordered_scripts('before_process_batch'): + try: + script_args = p.script_args[script.args_from:script.args_to] + script.before_process_batch(p, *script_args, **kwargs) + except Exception: + errors.report(f"Error running before_process_batch: {script.filename}", exc_info=True) + + def after_extra_networks_activate(self, p, **kwargs): + for script in self.ordered_scripts('after_extra_networks_activate'): + try: + script_args = p.script_args[script.args_from:script.args_to] + script.after_extra_networks_activate(p, *script_args, **kwargs) + except Exception: + errors.report(f"Error running after_extra_networks_activate: {script.filename}", exc_info=True) + + def process_batch(self, p, **kwargs): + for script in self.ordered_scripts('process_batch'): + try: + script_args = p.script_args[script.args_from:script.args_to] + script.process_batch(p, *script_args, **kwargs) + except Exception: + errors.report(f"Error running process_batch: {script.filename}", exc_info=True) + + def postprocess(self, p, processed): + for script in self.ordered_scripts('postprocess'): + try: + script_args = p.script_args[script.args_from:script.args_to] + script.postprocess(p, processed, *script_args) + except Exception: + errors.report(f"Error running postprocess: {script.filename}", exc_info=True) + + def postprocess_batch(self, p, images, **kwargs): + for script in self.ordered_scripts('postprocess_batch'): + try: + script_args = p.script_args[script.args_from:script.args_to] + script.postprocess_batch(p, *script_args, images=images, **kwargs) + except Exception: + errors.report(f"Error running postprocess_batch: {script.filename}", exc_info=True) + + def postprocess_batch_list(self, p, pp: PostprocessBatchListArgs, **kwargs): + for script in self.ordered_scripts('postprocess_batch_list'): + try: + script_args = p.script_args[script.args_from:script.args_to] + script.postprocess_batch_list(p, pp, *script_args, **kwargs) + except Exception: + errors.report(f"Error running postprocess_batch_list: {script.filename}", exc_info=True) + + def post_sample(self, p, ps: PostSampleArgs): + for script in self.ordered_scripts('post_sample'): + try: + script_args = p.script_args[script.args_from:script.args_to] + script.post_sample(p, ps, *script_args) + except Exception: + errors.report(f"Error running post_sample: {script.filename}", exc_info=True) + + def on_mask_blend(self, p, mba: MaskBlendArgs): + for script in self.ordered_scripts('on_mask_blend'): + try: + script_args = p.script_args[script.args_from:script.args_to] + script.on_mask_blend(p, mba, *script_args) + except Exception: + errors.report(f"Error running post_sample: {script.filename}", exc_info=True) + + def postprocess_image(self, p, pp: PostprocessImageArgs): + for script in self.ordered_scripts('postprocess_image'): + try: + script_args = p.script_args[script.args_from:script.args_to] + script.postprocess_image(p, pp, *script_args) + except Exception: + errors.report(f"Error running postprocess_image: {script.filename}", exc_info=True) + + def postprocess_maskoverlay(self, p, ppmo: PostProcessMaskOverlayArgs): + for script in self.ordered_scripts('postprocess_maskoverlay'): + try: + script_args = p.script_args[script.args_from:script.args_to] + script.postprocess_maskoverlay(p, ppmo, *script_args) + except Exception: + errors.report(f"Error running postprocess_image: {script.filename}", exc_info=True) + + def postprocess_image_after_composite(self, p, pp: PostprocessImageArgs): + for script in self.ordered_scripts('postprocess_image_after_composite'): + try: + script_args = p.script_args[script.args_from:script.args_to] + script.postprocess_image_after_composite(p, pp, *script_args) + except Exception: + errors.report(f"Error running postprocess_image_after_composite: {script.filename}", exc_info=True) + + def before_component(self, component, **kwargs): + for callback, script in self.on_before_component_elem_id.get(kwargs.get("elem_id"), []): + try: + callback(OnComponent(component=component)) + except Exception: + errors.report(f"Error running on_before_component: {script.filename}", exc_info=True) + + for script in self.ordered_scripts('before_component'): + try: + script.before_component(component, **kwargs) + except Exception: + errors.report(f"Error running before_component: {script.filename}", exc_info=True) + + def after_component(self, component, **kwargs): + for callback, script in self.on_after_component_elem_id.get(component.elem_id, []): + try: + callback(OnComponent(component=component)) + except Exception: + errors.report(f"Error running on_after_component: {script.filename}", exc_info=True) + + for script in self.ordered_scripts('after_component'): + try: + script.after_component(component, **kwargs) + except Exception: + errors.report(f"Error running after_component: {script.filename}", exc_info=True) + + def script(self, title): + return self.title_map.get(title.lower()) + + def reload_sources(self, cache): + for si, script in list(enumerate(self.scripts)): + args_from = script.args_from + args_to = script.args_to + filename = script.filename + + module = cache.get(filename, None) + if module is None: + module = script_loading.load_module(script.filename) + cache[filename] = module + + for script_class in module.__dict__.values(): + if type(script_class) == type and issubclass(script_class, Script): + self.scripts[si] = script_class() + self.scripts[si].filename = filename + self.scripts[si].args_from = args_from + self.scripts[si].args_to = args_to + + def before_hr(self, p): + for script in self.ordered_scripts('before_hr'): + try: + script_args = p.script_args[script.args_from:script.args_to] + script.before_hr(p, *script_args) + except Exception: + errors.report(f"Error running before_hr: {script.filename}", exc_info=True) + + def setup_scrips(self, p, *, is_ui=True): + for script in self.ordered_scripts('setup'): + if not is_ui and script.setup_for_ui_only: + continue + + try: + script_args = p.script_args[script.args_from:script.args_to] + script.setup(p, *script_args) + except Exception: + errors.report(f"Error running setup: {script.filename}", exc_info=True) + + def set_named_arg(self, args, script_name, arg_elem_id, value, fuzzy=False): + """Locate an arg of a specific script in script_args and set its value + Args: + args: all script args of process p, p.script_args + script_name: the name target script name to + arg_elem_id: the elem_id of the target arg + value: the value to set + fuzzy: if True, arg_elem_id can be a substring of the control.elem_id else exact match + Returns: + Updated script args + when script_name in not found or arg_elem_id is not found in script controls, raise RuntimeError + """ + script = next((x for x in self.scripts if x.name == script_name), None) + if script is None: + raise RuntimeError(f"script {script_name} not found") + + for i, control in enumerate(script.controls): + if arg_elem_id in control.elem_id if fuzzy else arg_elem_id == control.elem_id: + index = script.args_from + i + + if isinstance(args, tuple): + return args[:index] + (value,) + args[index + 1:] + elif isinstance(args, list): + args[index] = value + return args + else: + raise RuntimeError(f"args is not a list or tuple, but {type(args)}") + raise RuntimeError(f"arg_elem_id {arg_elem_id} not found in script {script_name}") + + +scripts_txt2img: ScriptRunner = None +scripts_img2img: ScriptRunner = None +scripts_postproc: scripts_postprocessing.ScriptPostprocessingRunner = None +scripts_current: ScriptRunner = None + + +def reload_script_body_only(): + cache = {} + scripts_txt2img.reload_sources(cache) + scripts_img2img.reload_sources(cache) + + +reload_scripts = load_scripts # compatibility alias
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/scripts.py
Add return value explanations in docstrings
# this code is adapted from the script contributed by anon from /h/ import pickle import collections import torch import numpy import _codecs import zipfile import re # PyTorch 1.13 and later have _TypedStorage renamed to TypedStorage from modules import errors TypedStorage = torch.storage.TypedStorage if hasattr(torch.storage, 'TypedStorage') else torch.storage._TypedStorage def encode(*args): out = _codecs.encode(*args) return out class RestrictedUnpickler(pickle.Unpickler): extra_handler = None def persistent_load(self, saved_id): assert saved_id[0] == 'storage' try: return TypedStorage(_internal=True) except TypeError: return TypedStorage() # PyTorch before 2.0 does not have the _internal argument def find_class(self, module, name): if self.extra_handler is not None: res = self.extra_handler(module, name) if res is not None: return res if module == 'collections' and name == 'OrderedDict': return getattr(collections, name) if module == 'torch._utils' and name in ['_rebuild_tensor_v2', '_rebuild_parameter', '_rebuild_device_tensor_from_numpy']: return getattr(torch._utils, name) if module == 'torch' and name in ['FloatStorage', 'HalfStorage', 'IntStorage', 'LongStorage', 'DoubleStorage', 'ByteStorage', 'float32', 'BFloat16Storage']: return getattr(torch, name) if module == 'torch.nn.modules.container' and name in ['ParameterDict']: return getattr(torch.nn.modules.container, name) if module == 'numpy.core.multiarray' and name in ['scalar', '_reconstruct']: return getattr(numpy.core.multiarray, name) if module == 'numpy' and name in ['dtype', 'ndarray']: return getattr(numpy, name) if module == '_codecs' and name == 'encode': return encode if module == "pytorch_lightning.callbacks" and name == 'model_checkpoint': import pytorch_lightning.callbacks return pytorch_lightning.callbacks.model_checkpoint if module == "pytorch_lightning.callbacks.model_checkpoint" and name == 'ModelCheckpoint': import pytorch_lightning.callbacks.model_checkpoint return pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint if module == "__builtin__" and name == 'set': return set # Forbid everything else. raise Exception(f"global '{module}/{name}' is forbidden") # Regular expression that accepts 'dirname/version', 'dirname/byteorder', 'dirname/data.pkl', '.data/serialization_id', and 'dirname/data/<number>' allowed_zip_names_re = re.compile(r"^([^/]+)/((data/\d+)|version|byteorder|.data/serialization_id|(data\.pkl))$") data_pkl_re = re.compile(r"^([^/]+)/data\.pkl$") def check_zip_filenames(filename, names): for name in names: if allowed_zip_names_re.match(name): continue raise Exception(f"bad file inside {filename}: {name}") def check_pt(filename, extra_handler): try: # new pytorch format is a zip file with zipfile.ZipFile(filename) as z: check_zip_filenames(filename, z.namelist()) # find filename of data.pkl in zip file: '<directory name>/data.pkl' data_pkl_filenames = [f for f in z.namelist() if data_pkl_re.match(f)] if len(data_pkl_filenames) == 0: raise Exception(f"data.pkl not found in {filename}") if len(data_pkl_filenames) > 1: raise Exception(f"Multiple data.pkl found in {filename}") with z.open(data_pkl_filenames[0]) as file: unpickler = RestrictedUnpickler(file) unpickler.extra_handler = extra_handler unpickler.load() except zipfile.BadZipfile: # if it's not a zip file, it's an old pytorch format, with five objects written to pickle with open(filename, "rb") as file: unpickler = RestrictedUnpickler(file) unpickler.extra_handler = extra_handler for _ in range(5): unpickler.load() def load(filename, *args, **kwargs): return load_with_extra(filename, *args, extra_handler=global_extra_handler, **kwargs) def load_with_extra(filename, extra_handler=None, *args, **kwargs): from modules import shared try: if not shared.cmd_opts.disable_safe_unpickle: check_pt(filename, extra_handler) except pickle.UnpicklingError: errors.report( f"Error verifying pickled file from {filename}\n" "-----> !!!! The file is most likely corrupted !!!! <-----\n" "You can skip this check with --disable-safe-unpickle commandline argument, but that is not going to help you.\n\n", exc_info=True, ) return None except Exception: errors.report( f"Error verifying pickled file from {filename}\n" f"The file may be malicious, so the program is not going to read it.\n" f"You can skip this check with --disable-safe-unpickle commandline argument.\n\n", exc_info=True, ) return None return unsafe_torch_load(filename, *args, **kwargs) class Extra: def __init__(self, handler): self.handler = handler def __enter__(self): global global_extra_handler assert global_extra_handler is None, 'already inside an Extra() block' global_extra_handler = self.handler def __exit__(self, exc_type, exc_val, exc_tb): global global_extra_handler global_extra_handler = None unsafe_torch_load = torch.load torch.load = load global_extra_handler = None
--- +++ @@ -1,158 +1,196 @@-# this code is adapted from the script contributed by anon from /h/ - -import pickle -import collections - -import torch -import numpy -import _codecs -import zipfile -import re - - -# PyTorch 1.13 and later have _TypedStorage renamed to TypedStorage -from modules import errors - -TypedStorage = torch.storage.TypedStorage if hasattr(torch.storage, 'TypedStorage') else torch.storage._TypedStorage - -def encode(*args): - out = _codecs.encode(*args) - return out - - -class RestrictedUnpickler(pickle.Unpickler): - extra_handler = None - - def persistent_load(self, saved_id): - assert saved_id[0] == 'storage' - - try: - return TypedStorage(_internal=True) - except TypeError: - return TypedStorage() # PyTorch before 2.0 does not have the _internal argument - - def find_class(self, module, name): - if self.extra_handler is not None: - res = self.extra_handler(module, name) - if res is not None: - return res - - if module == 'collections' and name == 'OrderedDict': - return getattr(collections, name) - if module == 'torch._utils' and name in ['_rebuild_tensor_v2', '_rebuild_parameter', '_rebuild_device_tensor_from_numpy']: - return getattr(torch._utils, name) - if module == 'torch' and name in ['FloatStorage', 'HalfStorage', 'IntStorage', 'LongStorage', 'DoubleStorage', 'ByteStorage', 'float32', 'BFloat16Storage']: - return getattr(torch, name) - if module == 'torch.nn.modules.container' and name in ['ParameterDict']: - return getattr(torch.nn.modules.container, name) - if module == 'numpy.core.multiarray' and name in ['scalar', '_reconstruct']: - return getattr(numpy.core.multiarray, name) - if module == 'numpy' and name in ['dtype', 'ndarray']: - return getattr(numpy, name) - if module == '_codecs' and name == 'encode': - return encode - if module == "pytorch_lightning.callbacks" and name == 'model_checkpoint': - import pytorch_lightning.callbacks - return pytorch_lightning.callbacks.model_checkpoint - if module == "pytorch_lightning.callbacks.model_checkpoint" and name == 'ModelCheckpoint': - import pytorch_lightning.callbacks.model_checkpoint - return pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint - if module == "__builtin__" and name == 'set': - return set - - # Forbid everything else. - raise Exception(f"global '{module}/{name}' is forbidden") - - -# Regular expression that accepts 'dirname/version', 'dirname/byteorder', 'dirname/data.pkl', '.data/serialization_id', and 'dirname/data/<number>' -allowed_zip_names_re = re.compile(r"^([^/]+)/((data/\d+)|version|byteorder|.data/serialization_id|(data\.pkl))$") -data_pkl_re = re.compile(r"^([^/]+)/data\.pkl$") - -def check_zip_filenames(filename, names): - for name in names: - if allowed_zip_names_re.match(name): - continue - - raise Exception(f"bad file inside {filename}: {name}") - - -def check_pt(filename, extra_handler): - try: - - # new pytorch format is a zip file - with zipfile.ZipFile(filename) as z: - check_zip_filenames(filename, z.namelist()) - - # find filename of data.pkl in zip file: '<directory name>/data.pkl' - data_pkl_filenames = [f for f in z.namelist() if data_pkl_re.match(f)] - if len(data_pkl_filenames) == 0: - raise Exception(f"data.pkl not found in {filename}") - if len(data_pkl_filenames) > 1: - raise Exception(f"Multiple data.pkl found in {filename}") - with z.open(data_pkl_filenames[0]) as file: - unpickler = RestrictedUnpickler(file) - unpickler.extra_handler = extra_handler - unpickler.load() - - except zipfile.BadZipfile: - - # if it's not a zip file, it's an old pytorch format, with five objects written to pickle - with open(filename, "rb") as file: - unpickler = RestrictedUnpickler(file) - unpickler.extra_handler = extra_handler - for _ in range(5): - unpickler.load() - - -def load(filename, *args, **kwargs): - return load_with_extra(filename, *args, extra_handler=global_extra_handler, **kwargs) - - -def load_with_extra(filename, extra_handler=None, *args, **kwargs): - - from modules import shared - - try: - if not shared.cmd_opts.disable_safe_unpickle: - check_pt(filename, extra_handler) - - except pickle.UnpicklingError: - errors.report( - f"Error verifying pickled file from {filename}\n" - "-----> !!!! The file is most likely corrupted !!!! <-----\n" - "You can skip this check with --disable-safe-unpickle commandline argument, but that is not going to help you.\n\n", - exc_info=True, - ) - return None - except Exception: - errors.report( - f"Error verifying pickled file from {filename}\n" - f"The file may be malicious, so the program is not going to read it.\n" - f"You can skip this check with --disable-safe-unpickle commandline argument.\n\n", - exc_info=True, - ) - return None - - return unsafe_torch_load(filename, *args, **kwargs) - - -class Extra: - - def __init__(self, handler): - self.handler = handler - - def __enter__(self): - global global_extra_handler - - assert global_extra_handler is None, 'already inside an Extra() block' - global_extra_handler = self.handler - - def __exit__(self, exc_type, exc_val, exc_tb): - global global_extra_handler - - global_extra_handler = None - - -unsafe_torch_load = torch.load -torch.load = load -global_extra_handler = None+# this code is adapted from the script contributed by anon from /h/ + +import pickle +import collections + +import torch +import numpy +import _codecs +import zipfile +import re + + +# PyTorch 1.13 and later have _TypedStorage renamed to TypedStorage +from modules import errors + +TypedStorage = torch.storage.TypedStorage if hasattr(torch.storage, 'TypedStorage') else torch.storage._TypedStorage + +def encode(*args): + out = _codecs.encode(*args) + return out + + +class RestrictedUnpickler(pickle.Unpickler): + extra_handler = None + + def persistent_load(self, saved_id): + assert saved_id[0] == 'storage' + + try: + return TypedStorage(_internal=True) + except TypeError: + return TypedStorage() # PyTorch before 2.0 does not have the _internal argument + + def find_class(self, module, name): + if self.extra_handler is not None: + res = self.extra_handler(module, name) + if res is not None: + return res + + if module == 'collections' and name == 'OrderedDict': + return getattr(collections, name) + if module == 'torch._utils' and name in ['_rebuild_tensor_v2', '_rebuild_parameter', '_rebuild_device_tensor_from_numpy']: + return getattr(torch._utils, name) + if module == 'torch' and name in ['FloatStorage', 'HalfStorage', 'IntStorage', 'LongStorage', 'DoubleStorage', 'ByteStorage', 'float32', 'BFloat16Storage']: + return getattr(torch, name) + if module == 'torch.nn.modules.container' and name in ['ParameterDict']: + return getattr(torch.nn.modules.container, name) + if module == 'numpy.core.multiarray' and name in ['scalar', '_reconstruct']: + return getattr(numpy.core.multiarray, name) + if module == 'numpy' and name in ['dtype', 'ndarray']: + return getattr(numpy, name) + if module == '_codecs' and name == 'encode': + return encode + if module == "pytorch_lightning.callbacks" and name == 'model_checkpoint': + import pytorch_lightning.callbacks + return pytorch_lightning.callbacks.model_checkpoint + if module == "pytorch_lightning.callbacks.model_checkpoint" and name == 'ModelCheckpoint': + import pytorch_lightning.callbacks.model_checkpoint + return pytorch_lightning.callbacks.model_checkpoint.ModelCheckpoint + if module == "__builtin__" and name == 'set': + return set + + # Forbid everything else. + raise Exception(f"global '{module}/{name}' is forbidden") + + +# Regular expression that accepts 'dirname/version', 'dirname/byteorder', 'dirname/data.pkl', '.data/serialization_id', and 'dirname/data/<number>' +allowed_zip_names_re = re.compile(r"^([^/]+)/((data/\d+)|version|byteorder|.data/serialization_id|(data\.pkl))$") +data_pkl_re = re.compile(r"^([^/]+)/data\.pkl$") + +def check_zip_filenames(filename, names): + for name in names: + if allowed_zip_names_re.match(name): + continue + + raise Exception(f"bad file inside {filename}: {name}") + + +def check_pt(filename, extra_handler): + try: + + # new pytorch format is a zip file + with zipfile.ZipFile(filename) as z: + check_zip_filenames(filename, z.namelist()) + + # find filename of data.pkl in zip file: '<directory name>/data.pkl' + data_pkl_filenames = [f for f in z.namelist() if data_pkl_re.match(f)] + if len(data_pkl_filenames) == 0: + raise Exception(f"data.pkl not found in {filename}") + if len(data_pkl_filenames) > 1: + raise Exception(f"Multiple data.pkl found in {filename}") + with z.open(data_pkl_filenames[0]) as file: + unpickler = RestrictedUnpickler(file) + unpickler.extra_handler = extra_handler + unpickler.load() + + except zipfile.BadZipfile: + + # if it's not a zip file, it's an old pytorch format, with five objects written to pickle + with open(filename, "rb") as file: + unpickler = RestrictedUnpickler(file) + unpickler.extra_handler = extra_handler + for _ in range(5): + unpickler.load() + + +def load(filename, *args, **kwargs): + return load_with_extra(filename, *args, extra_handler=global_extra_handler, **kwargs) + + +def load_with_extra(filename, extra_handler=None, *args, **kwargs): + """ + this function is intended to be used by extensions that want to load models with + some extra classes in them that the usual unpickler would find suspicious. + + Use the extra_handler argument to specify a function that takes module and field name as text, + and returns that field's value: + + ```python + def extra(module, name): + if module == 'collections' and name == 'OrderedDict': + return collections.OrderedDict + + return None + + safe.load_with_extra('model.pt', extra_handler=extra) + ``` + + The alternative to this is just to use safe.unsafe_torch_load('model.pt'), which as the name implies is + definitely unsafe. + """ + + from modules import shared + + try: + if not shared.cmd_opts.disable_safe_unpickle: + check_pt(filename, extra_handler) + + except pickle.UnpicklingError: + errors.report( + f"Error verifying pickled file from {filename}\n" + "-----> !!!! The file is most likely corrupted !!!! <-----\n" + "You can skip this check with --disable-safe-unpickle commandline argument, but that is not going to help you.\n\n", + exc_info=True, + ) + return None + except Exception: + errors.report( + f"Error verifying pickled file from {filename}\n" + f"The file may be malicious, so the program is not going to read it.\n" + f"You can skip this check with --disable-safe-unpickle commandline argument.\n\n", + exc_info=True, + ) + return None + + return unsafe_torch_load(filename, *args, **kwargs) + + +class Extra: + """ + A class for temporarily setting the global handler for when you can't explicitly call load_with_extra + (because it's not your code making the torch.load call). The intended use is like this: + +``` +import torch +from modules import safe + +def handler(module, name): + if module == 'torch' and name in ['float64', 'float16']: + return getattr(torch, name) + + return None + +with safe.Extra(handler): + x = torch.load('model.pt') +``` + """ + + def __init__(self, handler): + self.handler = handler + + def __enter__(self): + global global_extra_handler + + assert global_extra_handler is None, 'already inside an Extra() block' + global_extra_handler = self.handler + + def __exit__(self, exc_type, exc_val, exc_tb): + global global_extra_handler + + global_extra_handler = None + + +unsafe_torch_load = torch.load +torch.load = load +global_extra_handler = None
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/safe.py
Add verbose docstrings with examples
from __future__ import annotations import torch.nn import torch def get_param(model) -> torch.nn.Parameter: if hasattr(model, "model") and hasattr(model.model, "parameters"): # Unpeel a model descriptor to get at the actual Torch module. model = model.model for param in model.parameters(): return param raise ValueError(f"No parameters found in model {model!r}") def float64(t: torch.Tensor): if t.device.type in ['mps', 'xpu']: return torch.float32 return torch.float64
--- +++ @@ -5,6 +5,9 @@ def get_param(model) -> torch.nn.Parameter: + """ + Find the first parameter in a model or module. + """ if hasattr(model, "model") and hasattr(model.model, "parameters"): # Unpeel a model descriptor to get at the actual Torch module. model = model.model @@ -16,6 +19,7 @@ def float64(t: torch.Tensor): + """return torch.float64 if device is not mps or xpu, else return torch.float32""" if t.device.type in ['mps', 'xpu']: return torch.float32 - return torch.float64+ return torch.float64
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/torch_utils.py
Add docstrings that explain logic
import dataclasses import torch import k_diffusion import numpy as np from scipy import stats from modules import shared def to_d(x, sigma, denoised): return (x - denoised) / sigma k_diffusion.sampling.to_d = to_d @dataclasses.dataclass class Scheduler: name: str label: str function: any default_rho: float = -1 need_inner_model: bool = False aliases: list = None def uniform(n, sigma_min, sigma_max, inner_model, device): return inner_model.get_sigmas(n).to(device) def sgm_uniform(n, sigma_min, sigma_max, inner_model, device): start = inner_model.sigma_to_t(torch.tensor(sigma_max)) end = inner_model.sigma_to_t(torch.tensor(sigma_min)) sigs = [ inner_model.t_to_sigma(ts) for ts in torch.linspace(start, end, n + 1)[:-1] ] sigs += [0.0] return torch.FloatTensor(sigs).to(device) def get_align_your_steps_sigmas(n, sigma_min, sigma_max, device): # https://research.nvidia.com/labs/toronto-ai/AlignYourSteps/howto.html def loglinear_interp(t_steps, num_steps): xs = np.linspace(0, 1, len(t_steps)) ys = np.log(t_steps[::-1]) new_xs = np.linspace(0, 1, num_steps) new_ys = np.interp(new_xs, xs, ys) interped_ys = np.exp(new_ys)[::-1].copy() return interped_ys if shared.sd_model.is_sdxl: sigmas = [14.615, 6.315, 3.771, 2.181, 1.342, 0.862, 0.555, 0.380, 0.234, 0.113, 0.029] else: # Default to SD 1.5 sigmas. sigmas = [14.615, 6.475, 3.861, 2.697, 1.886, 1.396, 0.963, 0.652, 0.399, 0.152, 0.029] if n != len(sigmas): sigmas = np.append(loglinear_interp(sigmas, n), [0.0]) else: sigmas.append(0.0) return torch.FloatTensor(sigmas).to(device) def kl_optimal(n, sigma_min, sigma_max, device): alpha_min = torch.arctan(torch.tensor(sigma_min, device=device)) alpha_max = torch.arctan(torch.tensor(sigma_max, device=device)) step_indices = torch.arange(n + 1, device=device) sigmas = torch.tan(step_indices / n * alpha_min + (1.0 - step_indices / n) * alpha_max) return sigmas def simple_scheduler(n, sigma_min, sigma_max, inner_model, device): sigs = [] ss = len(inner_model.sigmas) / n for x in range(n): sigs += [float(inner_model.sigmas[-(1 + int(x * ss))])] sigs += [0.0] return torch.FloatTensor(sigs).to(device) def normal_scheduler(n, sigma_min, sigma_max, inner_model, device, sgm=False, floor=False): start = inner_model.sigma_to_t(torch.tensor(sigma_max)) end = inner_model.sigma_to_t(torch.tensor(sigma_min)) if sgm: timesteps = torch.linspace(start, end, n + 1)[:-1] else: timesteps = torch.linspace(start, end, n) sigs = [] for x in range(len(timesteps)): ts = timesteps[x] sigs.append(inner_model.t_to_sigma(ts)) sigs += [0.0] return torch.FloatTensor(sigs).to(device) def ddim_scheduler(n, sigma_min, sigma_max, inner_model, device): sigs = [] ss = max(len(inner_model.sigmas) // n, 1) x = 1 while x < len(inner_model.sigmas): sigs += [float(inner_model.sigmas[x])] x += ss sigs = sigs[::-1] sigs += [0.0] return torch.FloatTensor(sigs).to(device) def beta_scheduler(n, sigma_min, sigma_max, inner_model, device): # From "Beta Sampling is All You Need" [arXiv:2407.12173] (Lee et. al, 2024) """ alpha = shared.opts.beta_dist_alpha beta = shared.opts.beta_dist_beta timesteps = 1 - np.linspace(0, 1, n) timesteps = [stats.beta.ppf(x, alpha, beta) for x in timesteps] sigmas = [sigma_min + (x * (sigma_max-sigma_min)) for x in timesteps] sigmas += [0.0] return torch.FloatTensor(sigmas).to(device) schedulers = [ Scheduler('automatic', 'Automatic', None), Scheduler('uniform', 'Uniform', uniform, need_inner_model=True), Scheduler('karras', 'Karras', k_diffusion.sampling.get_sigmas_karras, default_rho=7.0), Scheduler('exponential', 'Exponential', k_diffusion.sampling.get_sigmas_exponential), Scheduler('polyexponential', 'Polyexponential', k_diffusion.sampling.get_sigmas_polyexponential, default_rho=1.0), Scheduler('sgm_uniform', 'SGM Uniform', sgm_uniform, need_inner_model=True, aliases=["SGMUniform"]), Scheduler('kl_optimal', 'KL Optimal', kl_optimal), Scheduler('align_your_steps', 'Align Your Steps', get_align_your_steps_sigmas), Scheduler('simple', 'Simple', simple_scheduler, need_inner_model=True), Scheduler('normal', 'Normal', normal_scheduler, need_inner_model=True), Scheduler('ddim', 'DDIM', ddim_scheduler, need_inner_model=True), Scheduler('beta', 'Beta', beta_scheduler, need_inner_model=True), ] schedulers_map = {**{x.name: x for x in schedulers}, **{x.label: x for x in schedulers}}
--- +++ @@ -8,6 +8,7 @@ def to_d(x, sigma, denoised): + """Converts a denoiser output to a Karras ODE derivative.""" return (x - denoised) / sigma @@ -43,6 +44,9 @@ def get_align_your_steps_sigmas(n, sigma_min, sigma_max, device): # https://research.nvidia.com/labs/toronto-ai/AlignYourSteps/howto.html def loglinear_interp(t_steps, num_steps): + """ + Performs log-linear interpolation of a given array of decreasing numbers. + """ xs = np.linspace(0, 1, len(t_steps)) ys = np.log(t_steps[::-1]) @@ -138,4 +142,4 @@ Scheduler('beta', 'Beta', beta_scheduler, need_inner_model=True), ] -schedulers_map = {**{x.name: x for x in schedulers}, **{x.label: x for x in schedulers}}+schedulers_map = {**{x.name: x for x in schedulers}, **{x.label: x for x in schedulers}}
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_schedulers.py
Create Google-style docstrings for my code
import os from pathlib import Path from modules.paths_internal import script_path def is_restartable() -> bool: return bool(os.environ.get('SD_WEBUI_RESTART')) def restart_program() -> None: tmpdir = Path(script_path) / "tmp" tmpdir.mkdir(parents=True, exist_ok=True) (tmpdir / "restart").touch() stop_program() def stop_program() -> None: os._exit(0)
--- +++ @@ -5,10 +5,14 @@ def is_restartable() -> bool: + """ + Return True if the webui is restartable (i.e. there is something watching to restart it with) + """ return bool(os.environ.get('SD_WEBUI_RESTART')) def restart_program() -> None: + """creates file tmp/restart and immediately stops the process, which webui.bat/webui.sh interpret as a command to start webui again""" tmpdir = Path(script_path) / "tmp" tmpdir.mkdir(parents=True, exist_ok=True) @@ -18,4 +22,4 @@ def stop_program() -> None: - os._exit(0)+ os._exit(0)
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/restart.py
Can you add docstrings to this Python file?
import functools import os.path import urllib.parse from base64 import b64decode from io import BytesIO from pathlib import Path from typing import Optional, Union from dataclasses import dataclass from modules import shared, ui_extra_networks_user_metadata, errors, extra_networks, util from modules.images import read_info_from_image, save_image_with_geninfo import gradio as gr import json import html from fastapi.exceptions import HTTPException from PIL import Image from modules.infotext_utils import image_from_url_text extra_pages = [] allowed_dirs = set() default_allowed_preview_extensions = ["png", "jpg", "jpeg", "webp", "gif"] @functools.cache def allowed_preview_extensions_with_extra(extra_extensions=None): return set(default_allowed_preview_extensions) | set(extra_extensions or []) def allowed_preview_extensions(): return allowed_preview_extensions_with_extra((shared.opts.samples_format, )) @dataclass class ExtraNetworksItem: item: dict def get_tree(paths: Union[str, list[str]], items: dict[str, ExtraNetworksItem]) -> dict: if isinstance(paths, (str,)): paths = [paths] def _get_tree(_paths: list[str], _root: str): _res = {} for path in _paths: relpath = os.path.relpath(path, _root) if os.path.isdir(path): dir_items = os.listdir(path) # Ignore empty directories. if not dir_items: continue dir_tree = _get_tree([os.path.join(path, x) for x in dir_items], _root) # We only want to store non-empty folders in the tree. if dir_tree: _res[relpath] = dir_tree else: if path not in items: continue # Add the ExtraNetworksItem to the result. _res[relpath] = items[path] return _res res = {} # Handle each root directory separately. # Each root WILL have a key/value at the root of the result dict though # the value can be an empty dict if the directory is empty. We want these # placeholders for empty dirs so we can inform the user later. for path in paths: root = os.path.dirname(path) relpath = os.path.relpath(path, root) # Wrap the path in a list since that is what the `_get_tree` expects. res[relpath] = _get_tree([path], root) if res[relpath]: # We need to pull the inner path out one for these root dirs. res[relpath] = res[relpath][relpath] return res def register_page(page): extra_pages.append(page) allowed_dirs.clear() allowed_dirs.update(set(sum([x.allowed_directories_for_previews() for x in extra_pages], []))) def fetch_file(filename: str = ""): from starlette.responses import FileResponse if not os.path.isfile(filename): raise HTTPException(status_code=404, detail="File not found") if not any(Path(x).absolute() in Path(filename).absolute().parents for x in allowed_dirs): raise ValueError(f"File cannot be fetched: {filename}. Must be in one of directories registered by extra pages.") ext = os.path.splitext(filename)[1].lower()[1:] if ext not in allowed_preview_extensions(): raise ValueError(f"File cannot be fetched: {filename}. Extensions allowed: {allowed_preview_extensions()}.") # would profit from returning 304 return FileResponse(filename, headers={"Accept-Ranges": "bytes"}) def fetch_cover_images(page: str = "", item: str = "", index: int = 0): from starlette.responses import Response page = next(iter([x for x in extra_pages if x.name == page]), None) if page is None: raise HTTPException(status_code=404, detail="File not found") metadata = page.metadata.get(item) if metadata is None: raise HTTPException(status_code=404, detail="File not found") cover_images = json.loads(metadata.get('ssmd_cover_images', {})) image = cover_images[index] if index < len(cover_images) else None if not image: raise HTTPException(status_code=404, detail="File not found") try: image = Image.open(BytesIO(b64decode(image))) buffer = BytesIO() image.save(buffer, format=image.format) return Response(content=buffer.getvalue(), media_type=image.get_format_mimetype()) except Exception as err: raise ValueError(f"File cannot be fetched: {item}. Failed to load cover image.") from err def get_metadata(page: str = "", item: str = ""): from starlette.responses import JSONResponse page = next(iter([x for x in extra_pages if x.name == page]), None) if page is None: return JSONResponse({}) metadata = page.metadata.get(item) if metadata is None: return JSONResponse({}) metadata = {i:metadata[i] for i in metadata if i != 'ssmd_cover_images'} # those are cover images, and they are too big to display in UI as text return JSONResponse({"metadata": json.dumps(metadata, indent=4, ensure_ascii=False)}) def get_single_card(page: str = "", tabname: str = "", name: str = ""): from starlette.responses import JSONResponse page = next(iter([x for x in extra_pages if x.name == page]), None) try: item = page.create_item(name, enable_filter=False) page.items[name] = item except Exception as e: errors.display(e, "creating item for extra network") item = page.items.get(name) page.read_user_metadata(item, use_cache=False) item_html = page.create_item_html(tabname, item, shared.html("extra-networks-card.html")) return JSONResponse({"html": item_html}) def add_pages_to_demo(app): app.add_api_route("/sd_extra_networks/thumb", fetch_file, methods=["GET"]) app.add_api_route("/sd_extra_networks/cover-images", fetch_cover_images, methods=["GET"]) app.add_api_route("/sd_extra_networks/metadata", get_metadata, methods=["GET"]) app.add_api_route("/sd_extra_networks/get-single-card", get_single_card, methods=["GET"]) def quote_js(s): s = s.replace('\\', '\\\\') s = s.replace('"', '\\"') return f'"{s}"' class ExtraNetworksPage: def __init__(self, title): self.title = title self.name = title.lower() # This is the actual name of the extra networks tab (not txt2img/img2img). self.extra_networks_tabname = self.name.replace(" ", "_") self.allow_prompt = True self.allow_negative_prompt = False self.metadata = {} self.items = {} self.lister = util.MassFileLister() # HTML Templates self.pane_tpl = shared.html("extra-networks-pane.html") self.pane_content_tree_tpl = shared.html("extra-networks-pane-tree.html") self.pane_content_dirs_tpl = shared.html("extra-networks-pane-dirs.html") self.card_tpl = shared.html("extra-networks-card.html") self.btn_tree_tpl = shared.html("extra-networks-tree-button.html") self.btn_copy_path_tpl = shared.html("extra-networks-copy-path-button.html") self.btn_metadata_tpl = shared.html("extra-networks-metadata-button.html") self.btn_edit_item_tpl = shared.html("extra-networks-edit-item-button.html") def refresh(self): pass def read_user_metadata(self, item, use_cache=True): filename = item.get("filename", None) metadata = extra_networks.get_user_metadata(filename, lister=self.lister if use_cache else None) desc = metadata.get("description", None) if desc is not None: item["description"] = desc item["user_metadata"] = metadata def link_preview(self, filename): quoted_filename = urllib.parse.quote(filename.replace('\\', '/')) mtime, _ = self.lister.mctime(filename) return f"./sd_extra_networks/thumb?filename={quoted_filename}&mtime={mtime}" def search_terms_from_path(self, filename, possible_directories=None): abspath = os.path.abspath(filename) for parentdir in (possible_directories if possible_directories is not None else self.allowed_directories_for_previews()): parentdir = os.path.dirname(os.path.abspath(parentdir)) if abspath.startswith(parentdir): return os.path.relpath(abspath, parentdir) return "" def create_item_html( self, tabname: str, item: dict, template: Optional[str] = None, ) -> Union[str, dict]: preview = item.get("preview", None) style_height = f"height: {shared.opts.extra_networks_card_height}px;" if shared.opts.extra_networks_card_height else '' style_width = f"width: {shared.opts.extra_networks_card_width}px;" if shared.opts.extra_networks_card_width else '' style_font_size = f"font-size: {shared.opts.extra_networks_card_text_scale*100}%;" card_style = style_height + style_width + style_font_size background_image = f'<img src="{html.escape(preview)}" class="preview" loading="lazy">' if preview else '' onclick = item.get("onclick", None) if onclick is None: # Don't quote prompt/neg_prompt since they are stored as js strings already. onclick_js_tpl = "cardClicked('{tabname}', {prompt}, {neg_prompt}, {allow_neg});" onclick = onclick_js_tpl.format( **{ "tabname": tabname, "prompt": item["prompt"], "neg_prompt": item.get("negative_prompt", "''"), "allow_neg": str(self.allow_negative_prompt).lower(), } ) onclick = html.escape(onclick) btn_copy_path = self.btn_copy_path_tpl.format(**{"filename": item["filename"]}) btn_metadata = "" metadata = item.get("metadata") if metadata: btn_metadata = self.btn_metadata_tpl.format( **{ "extra_networks_tabname": self.extra_networks_tabname, } ) btn_edit_item = self.btn_edit_item_tpl.format( **{ "tabname": tabname, "extra_networks_tabname": self.extra_networks_tabname, } ) local_path = "" filename = item.get("filename", "") for reldir in self.allowed_directories_for_previews(): absdir = os.path.abspath(reldir) if filename.startswith(absdir): local_path = filename[len(absdir):] # if this is true, the item must not be shown in the default view, and must instead only be # shown when searching for it if shared.opts.extra_networks_hidden_models == "Always": search_only = False else: search_only = "/." in local_path or "\\." in local_path if search_only and shared.opts.extra_networks_hidden_models == "Never": return "" sort_keys = " ".join( [ f'data-sort-{k}="{html.escape(str(v))}"' for k, v in item.get("sort_keys", {}).items() ] ).strip() search_terms_html = "" search_term_template = "<span class='hidden {class}'>{search_term}</span>" for search_term in item.get("search_terms", []): search_terms_html += search_term_template.format( **{ "class": f"search_terms{' search_only' if search_only else ''}", "search_term": search_term, } ) description = (item.get("description", "") or "" if shared.opts.extra_networks_card_show_desc else "") if not shared.opts.extra_networks_card_description_is_html: description = html.escape(description) # Some items here might not be used depending on HTML template used. args = { "background_image": background_image, "card_clicked": onclick, "copy_path_button": btn_copy_path, "description": description, "edit_button": btn_edit_item, "local_preview": quote_js(item["local_preview"]), "metadata_button": btn_metadata, "name": html.escape(item["name"]), "prompt": item.get("prompt", None), "save_card_preview": html.escape(f"return saveCardPreview(event, '{tabname}', '{item['local_preview']}');"), "search_only": " search_only" if search_only else "", "search_terms": search_terms_html, "sort_keys": sort_keys, "style": card_style, "tabname": tabname, "extra_networks_tabname": self.extra_networks_tabname, } if template: return template.format(**args) else: return args def create_tree_dir_item_html( self, tabname: str, dir_path: str, content: Optional[str] = None, ) -> Optional[str]: if not content: return None btn = self.btn_tree_tpl.format( **{ "search_terms": "", "subclass": "tree-list-content-dir", "tabname": tabname, "extra_networks_tabname": self.extra_networks_tabname, "onclick_extra": "", "data_path": dir_path, "data_hash": "", "action_list_item_action_leading": "<i class='tree-list-item-action-chevron'></i>", "action_list_item_visual_leading": "🗀", "action_list_item_label": os.path.basename(dir_path), "action_list_item_visual_trailing": "", "action_list_item_action_trailing": "", } ) ul = f"<ul class='tree-list tree-list--subgroup' hidden>{content}</ul>" return ( "<li class='tree-list-item tree-list-item--has-subitem' data-tree-entry-type='dir'>" f"{btn}{ul}" "</li>" ) def create_tree_file_item_html(self, tabname: str, file_path: str, item: dict) -> str: item_html_args = self.create_item_html(tabname, item) action_buttons = "".join( [ item_html_args["copy_path_button"], item_html_args["metadata_button"], item_html_args["edit_button"], ] ) action_buttons = f"<div class=\"button-row\">{action_buttons}</div>" btn = self.btn_tree_tpl.format( **{ "search_terms": "", "subclass": "tree-list-content-file", "tabname": tabname, "extra_networks_tabname": self.extra_networks_tabname, "onclick_extra": item_html_args["card_clicked"], "data_path": file_path, "data_hash": item["shorthash"], "action_list_item_action_leading": "<i class='tree-list-item-action-chevron'></i>", "action_list_item_visual_leading": "🗎", "action_list_item_label": item["name"], "action_list_item_visual_trailing": "", "action_list_item_action_trailing": action_buttons, } ) return ( "<li class='tree-list-item tree-list-item--subitem' data-tree-entry-type='file'>" f"{btn}" "</li>" ) def create_tree_view_html(self, tabname: str) -> str: res = "" # Setup the tree dictionary. roots = self.allowed_directories_for_previews() tree_items = {v["filename"]: ExtraNetworksItem(v) for v in self.items.values()} tree = get_tree([os.path.abspath(x) for x in roots], items=tree_items) if not tree: return res def _build_tree(data: Optional[dict[str, ExtraNetworksItem]] = None) -> Optional[str]: if not data: return None # Lists for storing <li> items html for directories and files separately. _dir_li = [] _file_li = [] for k, v in sorted(data.items(), key=lambda x: shared.natural_sort_key(x[0])): if isinstance(v, (ExtraNetworksItem,)): _file_li.append(self.create_tree_file_item_html(tabname, k, v.item)) else: _dir_li.append(self.create_tree_dir_item_html(tabname, k, _build_tree(v))) # Directories should always be displayed before files so we order them here. return "".join(_dir_li) + "".join(_file_li) # Add each root directory to the tree. for k, v in sorted(tree.items(), key=lambda x: shared.natural_sort_key(x[0])): item_html = self.create_tree_dir_item_html(tabname, k, _build_tree(v)) # Only add non-empty entries to the tree. if item_html is not None: res += item_html return f"<ul class='tree-list tree-list--tree'>{res}</ul>" def create_dirs_view_html(self, tabname: str) -> str: subdirs = {} for parentdir in [os.path.abspath(x) for x in self.allowed_directories_for_previews()]: for root, dirs, _ in sorted(os.walk(parentdir, followlinks=True), key=lambda x: shared.natural_sort_key(x[0])): for dirname in sorted(dirs, key=shared.natural_sort_key): x = os.path.join(root, dirname) if not os.path.isdir(x): continue subdir = os.path.abspath(x)[len(parentdir):] if shared.opts.extra_networks_dir_button_function: if not subdir.startswith(os.path.sep): subdir = os.path.sep + subdir else: while subdir.startswith(os.path.sep): subdir = subdir[1:] is_empty = len(os.listdir(x)) == 0 if not is_empty and not subdir.endswith(os.path.sep): subdir = subdir + os.path.sep if (os.path.sep + "." in subdir or subdir.startswith(".")) and not shared.opts.extra_networks_show_hidden_directories: continue subdirs[subdir] = 1 if subdirs: subdirs = {"": 1, **subdirs} subdirs_html = "".join([f""" <button class='lg secondary gradio-button custom-button{" search-all" if subdir == "" else ""}' onclick='extraNetworksSearchButton("{tabname}", "{self.extra_networks_tabname}", event)'> {html.escape(subdir if subdir != "" else "all")} </button> """ for subdir in subdirs]) return subdirs_html def create_card_view_html(self, tabname: str, *, none_message) -> str: res = [] for item in self.items.values(): res.append(self.create_item_html(tabname, item, self.card_tpl)) if not res: dirs = "".join([f"<li>{x}</li>" for x in self.allowed_directories_for_previews()]) res = [none_message or shared.html("extra-networks-no-cards.html").format(dirs=dirs)] return "".join(res) def create_html(self, tabname, *, empty=False): self.lister.reset() self.metadata = {} items_list = [] if empty else self.list_items() self.items = {x["name"]: x for x in items_list} # Populate the instance metadata for each item. for item in self.items.values(): metadata = item.get("metadata") if metadata: self.metadata[item["name"]] = metadata if "user_metadata" not in item: self.read_user_metadata(item) show_tree = shared.opts.extra_networks_tree_view_default_enabled page_params = { "tabname": tabname, "extra_networks_tabname": self.extra_networks_tabname, "data_sortdir": shared.opts.extra_networks_card_order, "sort_path_active": ' extra-network-control--enabled' if shared.opts.extra_networks_card_order_field == 'Path' else '', "sort_name_active": ' extra-network-control--enabled' if shared.opts.extra_networks_card_order_field == 'Name' else '', "sort_date_created_active": ' extra-network-control--enabled' if shared.opts.extra_networks_card_order_field == 'Date Created' else '', "sort_date_modified_active": ' extra-network-control--enabled' if shared.opts.extra_networks_card_order_field == 'Date Modified' else '', "tree_view_btn_extra_class": "extra-network-control--enabled" if show_tree else "", "items_html": self.create_card_view_html(tabname, none_message="Loading..." if empty else None), "extra_networks_tree_view_default_width": shared.opts.extra_networks_tree_view_default_width, "tree_view_div_default_display_class": "" if show_tree else "extra-network-dirs-hidden", } if shared.opts.extra_networks_tree_view_style == "Tree": pane_content = self.pane_content_tree_tpl.format(**page_params, tree_html=self.create_tree_view_html(tabname)) else: pane_content = self.pane_content_dirs_tpl.format(**page_params, dirs_html=self.create_dirs_view_html(tabname)) return self.pane_tpl.format(**page_params, pane_content=pane_content) def create_item(self, name, index=None): raise NotImplementedError() def list_items(self): raise NotImplementedError() def allowed_directories_for_previews(self): return [] def get_sort_keys(self, path): pth = Path(path) mtime, ctime = self.lister.mctime(path) return { "date_created": int(mtime), "date_modified": int(ctime), "name": pth.name.lower(), "path": str(pth).lower(), } def find_preview(self, path): potential_files = sum([[f"{path}.{ext}", f"{path}.preview.{ext}"] for ext in allowed_preview_extensions()], []) for file in potential_files: if self.lister.exists(file): return self.link_preview(file) return None def find_embedded_preview(self, path, name, metadata): file = f"{path}.safetensors" if self.lister.exists(file) and 'ssmd_cover_images' in metadata and len(list(filter(None, json.loads(metadata['ssmd_cover_images'])))) > 0: return f"./sd_extra_networks/cover-images?page={self.extra_networks_tabname}&item={name}" return None def find_description(self, path): for file in [f"{path}.txt", f"{path}.description.txt"]: if not self.lister.exists(file): continue try: with open(file, "r", encoding="utf-8", errors="replace") as f: return f.read() except OSError: pass return None def create_user_metadata_editor(self, ui, tabname): return ui_extra_networks_user_metadata.UserMetadataEditor(ui, tabname, self) def initialize(): extra_pages.clear() def register_default_pages(): from modules.ui_extra_networks_textual_inversion import ExtraNetworksPageTextualInversion from modules.ui_extra_networks_hypernets import ExtraNetworksPageHypernetworks from modules.ui_extra_networks_checkpoints import ExtraNetworksPageCheckpoints register_page(ExtraNetworksPageTextualInversion()) register_page(ExtraNetworksPageHypernetworks()) register_page(ExtraNetworksPageCheckpoints()) class ExtraNetworksUi: def __init__(self): self.pages = None """gradio HTML components related to extra networks' pages""" self.page_contents = None """HTML content of the above; empty initially, filled when extra pages have to be shown""" self.stored_extra_pages = None self.button_save_preview = None self.preview_target_filename = None self.tabname = None def pages_in_preferred_order(pages): tab_order = [x.lower().strip() for x in shared.opts.ui_extra_networks_tab_reorder.split(",")] def tab_name_score(name): name = name.lower() for i, possible_match in enumerate(tab_order): if possible_match in name: return i return len(pages) tab_scores = {page.name: (tab_name_score(page.name), original_index) for original_index, page in enumerate(pages)} return sorted(pages, key=lambda x: tab_scores[x.name]) def create_ui(interface: gr.Blocks, unrelated_tabs, tabname): ui = ExtraNetworksUi() ui.pages = [] ui.pages_contents = [] ui.user_metadata_editors = [] ui.stored_extra_pages = pages_in_preferred_order(extra_pages.copy()) ui.tabname = tabname related_tabs = [] for page in ui.stored_extra_pages: with gr.Tab(page.title, elem_id=f"{tabname}_{page.extra_networks_tabname}", elem_classes=["extra-page"]) as tab: with gr.Column(elem_id=f"{tabname}_{page.extra_networks_tabname}_prompts", elem_classes=["extra-page-prompts"]): pass elem_id = f"{tabname}_{page.extra_networks_tabname}_cards_html" page_elem = gr.HTML(page.create_html(tabname, empty=True), elem_id=elem_id) ui.pages.append(page_elem) editor = page.create_user_metadata_editor(ui, tabname) editor.create_ui() ui.user_metadata_editors.append(editor) related_tabs.append(tab) ui.button_save_preview = gr.Button('Save preview', elem_id=f"{tabname}_save_preview", visible=False) ui.preview_target_filename = gr.Textbox('Preview save filename', elem_id=f"{tabname}_preview_filename", visible=False) for tab in unrelated_tabs: tab.select(fn=None, _js=f"function(){{extraNetworksUnrelatedTabSelected('{tabname}');}}", inputs=[], outputs=[], show_progress=False) for page, tab in zip(ui.stored_extra_pages, related_tabs): jscode = ( "function(){{" f"extraNetworksTabSelected('{tabname}', '{tabname}_{page.extra_networks_tabname}_prompts', {str(page.allow_prompt).lower()}, {str(page.allow_negative_prompt).lower()}, '{tabname}_{page.extra_networks_tabname}');" f"applyExtraNetworkFilter('{tabname}_{page.extra_networks_tabname}');" "}}" ) tab.select(fn=None, _js=jscode, inputs=[], outputs=[], show_progress=False) def refresh(): for pg in ui.stored_extra_pages: pg.refresh() create_html() return ui.pages_contents button_refresh = gr.Button("Refresh", elem_id=f"{tabname}_{page.extra_networks_tabname}_extra_refresh_internal", visible=False) button_refresh.click(fn=refresh, inputs=[], outputs=ui.pages).then(fn=lambda: None, _js="function(){ " + f"applyExtraNetworkFilter('{tabname}_{page.extra_networks_tabname}');" + " }").then(fn=lambda: None, _js='setupAllResizeHandles') def create_html(): ui.pages_contents = [pg.create_html(ui.tabname) for pg in ui.stored_extra_pages] def pages_html(): if not ui.pages_contents: create_html() return ui.pages_contents interface.load(fn=pages_html, inputs=[], outputs=ui.pages).then(fn=lambda: None, _js='setupAllResizeHandles') return ui def path_is_parent(parent_path, child_path): parent_path = os.path.abspath(parent_path) child_path = os.path.abspath(child_path) return child_path.startswith(parent_path) def setup_ui(ui, gallery): def save_preview(index, images, filename): # this function is here for backwards compatibility and likely will be removed soon if len(images) == 0: print("There is no image in gallery to save as a preview.") return [page.create_html(ui.tabname) for page in ui.stored_extra_pages] index = int(index) index = 0 if index < 0 else index index = len(images) - 1 if index >= len(images) else index img_info = images[index if index >= 0 else 0] image = image_from_url_text(img_info) geninfo, items = read_info_from_image(image) is_allowed = False for extra_page in ui.stored_extra_pages: if any(path_is_parent(x, filename) for x in extra_page.allowed_directories_for_previews()): is_allowed = True break assert is_allowed, f'writing to {filename} is not allowed' save_image_with_geninfo(image, geninfo, filename) return [page.create_html(ui.tabname) for page in ui.stored_extra_pages] ui.button_save_preview.click( fn=save_preview, _js="function(x, y, z){return [selected_gallery_index(), y, z]}", inputs=[ui.preview_target_filename, gallery, ui.preview_target_filename], outputs=[*ui.pages] ) for editor in ui.user_metadata_editors: editor.setup_ui(gallery)
--- +++ @@ -1,721 +1,838 @@-import functools -import os.path -import urllib.parse -from base64 import b64decode -from io import BytesIO -from pathlib import Path -from typing import Optional, Union -from dataclasses import dataclass - -from modules import shared, ui_extra_networks_user_metadata, errors, extra_networks, util -from modules.images import read_info_from_image, save_image_with_geninfo -import gradio as gr -import json -import html -from fastapi.exceptions import HTTPException -from PIL import Image - -from modules.infotext_utils import image_from_url_text - -extra_pages = [] -allowed_dirs = set() -default_allowed_preview_extensions = ["png", "jpg", "jpeg", "webp", "gif"] - -@functools.cache -def allowed_preview_extensions_with_extra(extra_extensions=None): - return set(default_allowed_preview_extensions) | set(extra_extensions or []) - - -def allowed_preview_extensions(): - return allowed_preview_extensions_with_extra((shared.opts.samples_format, )) - - -@dataclass -class ExtraNetworksItem: - item: dict - - -def get_tree(paths: Union[str, list[str]], items: dict[str, ExtraNetworksItem]) -> dict: - if isinstance(paths, (str,)): - paths = [paths] - - def _get_tree(_paths: list[str], _root: str): - _res = {} - for path in _paths: - relpath = os.path.relpath(path, _root) - if os.path.isdir(path): - dir_items = os.listdir(path) - # Ignore empty directories. - if not dir_items: - continue - dir_tree = _get_tree([os.path.join(path, x) for x in dir_items], _root) - # We only want to store non-empty folders in the tree. - if dir_tree: - _res[relpath] = dir_tree - else: - if path not in items: - continue - # Add the ExtraNetworksItem to the result. - _res[relpath] = items[path] - return _res - - res = {} - # Handle each root directory separately. - # Each root WILL have a key/value at the root of the result dict though - # the value can be an empty dict if the directory is empty. We want these - # placeholders for empty dirs so we can inform the user later. - for path in paths: - root = os.path.dirname(path) - relpath = os.path.relpath(path, root) - # Wrap the path in a list since that is what the `_get_tree` expects. - res[relpath] = _get_tree([path], root) - if res[relpath]: - # We need to pull the inner path out one for these root dirs. - res[relpath] = res[relpath][relpath] - - return res - -def register_page(page): - - extra_pages.append(page) - allowed_dirs.clear() - allowed_dirs.update(set(sum([x.allowed_directories_for_previews() for x in extra_pages], []))) - - -def fetch_file(filename: str = ""): - from starlette.responses import FileResponse - - if not os.path.isfile(filename): - raise HTTPException(status_code=404, detail="File not found") - - if not any(Path(x).absolute() in Path(filename).absolute().parents for x in allowed_dirs): - raise ValueError(f"File cannot be fetched: {filename}. Must be in one of directories registered by extra pages.") - - ext = os.path.splitext(filename)[1].lower()[1:] - if ext not in allowed_preview_extensions(): - raise ValueError(f"File cannot be fetched: {filename}. Extensions allowed: {allowed_preview_extensions()}.") - - # would profit from returning 304 - return FileResponse(filename, headers={"Accept-Ranges": "bytes"}) - - -def fetch_cover_images(page: str = "", item: str = "", index: int = 0): - from starlette.responses import Response - - page = next(iter([x for x in extra_pages if x.name == page]), None) - if page is None: - raise HTTPException(status_code=404, detail="File not found") - - metadata = page.metadata.get(item) - if metadata is None: - raise HTTPException(status_code=404, detail="File not found") - - cover_images = json.loads(metadata.get('ssmd_cover_images', {})) - image = cover_images[index] if index < len(cover_images) else None - if not image: - raise HTTPException(status_code=404, detail="File not found") - - try: - image = Image.open(BytesIO(b64decode(image))) - buffer = BytesIO() - image.save(buffer, format=image.format) - return Response(content=buffer.getvalue(), media_type=image.get_format_mimetype()) - except Exception as err: - raise ValueError(f"File cannot be fetched: {item}. Failed to load cover image.") from err - - -def get_metadata(page: str = "", item: str = ""): - from starlette.responses import JSONResponse - - page = next(iter([x for x in extra_pages if x.name == page]), None) - if page is None: - return JSONResponse({}) - - metadata = page.metadata.get(item) - if metadata is None: - return JSONResponse({}) - - metadata = {i:metadata[i] for i in metadata if i != 'ssmd_cover_images'} # those are cover images, and they are too big to display in UI as text - - return JSONResponse({"metadata": json.dumps(metadata, indent=4, ensure_ascii=False)}) - - -def get_single_card(page: str = "", tabname: str = "", name: str = ""): - from starlette.responses import JSONResponse - - page = next(iter([x for x in extra_pages if x.name == page]), None) - - try: - item = page.create_item(name, enable_filter=False) - page.items[name] = item - except Exception as e: - errors.display(e, "creating item for extra network") - item = page.items.get(name) - - page.read_user_metadata(item, use_cache=False) - item_html = page.create_item_html(tabname, item, shared.html("extra-networks-card.html")) - - return JSONResponse({"html": item_html}) - - -def add_pages_to_demo(app): - app.add_api_route("/sd_extra_networks/thumb", fetch_file, methods=["GET"]) - app.add_api_route("/sd_extra_networks/cover-images", fetch_cover_images, methods=["GET"]) - app.add_api_route("/sd_extra_networks/metadata", get_metadata, methods=["GET"]) - app.add_api_route("/sd_extra_networks/get-single-card", get_single_card, methods=["GET"]) - - -def quote_js(s): - s = s.replace('\\', '\\\\') - s = s.replace('"', '\\"') - return f'"{s}"' - - -class ExtraNetworksPage: - def __init__(self, title): - self.title = title - self.name = title.lower() - # This is the actual name of the extra networks tab (not txt2img/img2img). - self.extra_networks_tabname = self.name.replace(" ", "_") - self.allow_prompt = True - self.allow_negative_prompt = False - self.metadata = {} - self.items = {} - self.lister = util.MassFileLister() - # HTML Templates - self.pane_tpl = shared.html("extra-networks-pane.html") - self.pane_content_tree_tpl = shared.html("extra-networks-pane-tree.html") - self.pane_content_dirs_tpl = shared.html("extra-networks-pane-dirs.html") - self.card_tpl = shared.html("extra-networks-card.html") - self.btn_tree_tpl = shared.html("extra-networks-tree-button.html") - self.btn_copy_path_tpl = shared.html("extra-networks-copy-path-button.html") - self.btn_metadata_tpl = shared.html("extra-networks-metadata-button.html") - self.btn_edit_item_tpl = shared.html("extra-networks-edit-item-button.html") - - def refresh(self): - pass - - def read_user_metadata(self, item, use_cache=True): - filename = item.get("filename", None) - metadata = extra_networks.get_user_metadata(filename, lister=self.lister if use_cache else None) - - desc = metadata.get("description", None) - if desc is not None: - item["description"] = desc - - item["user_metadata"] = metadata - - def link_preview(self, filename): - quoted_filename = urllib.parse.quote(filename.replace('\\', '/')) - mtime, _ = self.lister.mctime(filename) - return f"./sd_extra_networks/thumb?filename={quoted_filename}&mtime={mtime}" - - def search_terms_from_path(self, filename, possible_directories=None): - abspath = os.path.abspath(filename) - for parentdir in (possible_directories if possible_directories is not None else self.allowed_directories_for_previews()): - parentdir = os.path.dirname(os.path.abspath(parentdir)) - if abspath.startswith(parentdir): - return os.path.relpath(abspath, parentdir) - - return "" - - def create_item_html( - self, - tabname: str, - item: dict, - template: Optional[str] = None, - ) -> Union[str, dict]: - preview = item.get("preview", None) - style_height = f"height: {shared.opts.extra_networks_card_height}px;" if shared.opts.extra_networks_card_height else '' - style_width = f"width: {shared.opts.extra_networks_card_width}px;" if shared.opts.extra_networks_card_width else '' - style_font_size = f"font-size: {shared.opts.extra_networks_card_text_scale*100}%;" - card_style = style_height + style_width + style_font_size - background_image = f'<img src="{html.escape(preview)}" class="preview" loading="lazy">' if preview else '' - - onclick = item.get("onclick", None) - if onclick is None: - # Don't quote prompt/neg_prompt since they are stored as js strings already. - onclick_js_tpl = "cardClicked('{tabname}', {prompt}, {neg_prompt}, {allow_neg});" - onclick = onclick_js_tpl.format( - **{ - "tabname": tabname, - "prompt": item["prompt"], - "neg_prompt": item.get("negative_prompt", "''"), - "allow_neg": str(self.allow_negative_prompt).lower(), - } - ) - onclick = html.escape(onclick) - - btn_copy_path = self.btn_copy_path_tpl.format(**{"filename": item["filename"]}) - btn_metadata = "" - metadata = item.get("metadata") - if metadata: - btn_metadata = self.btn_metadata_tpl.format( - **{ - "extra_networks_tabname": self.extra_networks_tabname, - } - ) - btn_edit_item = self.btn_edit_item_tpl.format( - **{ - "tabname": tabname, - "extra_networks_tabname": self.extra_networks_tabname, - } - ) - - local_path = "" - filename = item.get("filename", "") - for reldir in self.allowed_directories_for_previews(): - absdir = os.path.abspath(reldir) - - if filename.startswith(absdir): - local_path = filename[len(absdir):] - - # if this is true, the item must not be shown in the default view, and must instead only be - # shown when searching for it - if shared.opts.extra_networks_hidden_models == "Always": - search_only = False - else: - search_only = "/." in local_path or "\\." in local_path - - if search_only and shared.opts.extra_networks_hidden_models == "Never": - return "" - - sort_keys = " ".join( - [ - f'data-sort-{k}="{html.escape(str(v))}"' - for k, v in item.get("sort_keys", {}).items() - ] - ).strip() - - search_terms_html = "" - search_term_template = "<span class='hidden {class}'>{search_term}</span>" - for search_term in item.get("search_terms", []): - search_terms_html += search_term_template.format( - **{ - "class": f"search_terms{' search_only' if search_only else ''}", - "search_term": search_term, - } - ) - - description = (item.get("description", "") or "" if shared.opts.extra_networks_card_show_desc else "") - if not shared.opts.extra_networks_card_description_is_html: - description = html.escape(description) - - # Some items here might not be used depending on HTML template used. - args = { - "background_image": background_image, - "card_clicked": onclick, - "copy_path_button": btn_copy_path, - "description": description, - "edit_button": btn_edit_item, - "local_preview": quote_js(item["local_preview"]), - "metadata_button": btn_metadata, - "name": html.escape(item["name"]), - "prompt": item.get("prompt", None), - "save_card_preview": html.escape(f"return saveCardPreview(event, '{tabname}', '{item['local_preview']}');"), - "search_only": " search_only" if search_only else "", - "search_terms": search_terms_html, - "sort_keys": sort_keys, - "style": card_style, - "tabname": tabname, - "extra_networks_tabname": self.extra_networks_tabname, - } - - if template: - return template.format(**args) - else: - return args - - def create_tree_dir_item_html( - self, - tabname: str, - dir_path: str, - content: Optional[str] = None, - ) -> Optional[str]: - if not content: - return None - - btn = self.btn_tree_tpl.format( - **{ - "search_terms": "", - "subclass": "tree-list-content-dir", - "tabname": tabname, - "extra_networks_tabname": self.extra_networks_tabname, - "onclick_extra": "", - "data_path": dir_path, - "data_hash": "", - "action_list_item_action_leading": "<i class='tree-list-item-action-chevron'></i>", - "action_list_item_visual_leading": "🗀", - "action_list_item_label": os.path.basename(dir_path), - "action_list_item_visual_trailing": "", - "action_list_item_action_trailing": "", - } - ) - ul = f"<ul class='tree-list tree-list--subgroup' hidden>{content}</ul>" - return ( - "<li class='tree-list-item tree-list-item--has-subitem' data-tree-entry-type='dir'>" - f"{btn}{ul}" - "</li>" - ) - - def create_tree_file_item_html(self, tabname: str, file_path: str, item: dict) -> str: - item_html_args = self.create_item_html(tabname, item) - action_buttons = "".join( - [ - item_html_args["copy_path_button"], - item_html_args["metadata_button"], - item_html_args["edit_button"], - ] - ) - action_buttons = f"<div class=\"button-row\">{action_buttons}</div>" - btn = self.btn_tree_tpl.format( - **{ - "search_terms": "", - "subclass": "tree-list-content-file", - "tabname": tabname, - "extra_networks_tabname": self.extra_networks_tabname, - "onclick_extra": item_html_args["card_clicked"], - "data_path": file_path, - "data_hash": item["shorthash"], - "action_list_item_action_leading": "<i class='tree-list-item-action-chevron'></i>", - "action_list_item_visual_leading": "🗎", - "action_list_item_label": item["name"], - "action_list_item_visual_trailing": "", - "action_list_item_action_trailing": action_buttons, - } - ) - return ( - "<li class='tree-list-item tree-list-item--subitem' data-tree-entry-type='file'>" - f"{btn}" - "</li>" - ) - - def create_tree_view_html(self, tabname: str) -> str: - res = "" - - # Setup the tree dictionary. - roots = self.allowed_directories_for_previews() - tree_items = {v["filename"]: ExtraNetworksItem(v) for v in self.items.values()} - tree = get_tree([os.path.abspath(x) for x in roots], items=tree_items) - - if not tree: - return res - - def _build_tree(data: Optional[dict[str, ExtraNetworksItem]] = None) -> Optional[str]: - if not data: - return None - - # Lists for storing <li> items html for directories and files separately. - _dir_li = [] - _file_li = [] - - for k, v in sorted(data.items(), key=lambda x: shared.natural_sort_key(x[0])): - if isinstance(v, (ExtraNetworksItem,)): - _file_li.append(self.create_tree_file_item_html(tabname, k, v.item)) - else: - _dir_li.append(self.create_tree_dir_item_html(tabname, k, _build_tree(v))) - - # Directories should always be displayed before files so we order them here. - return "".join(_dir_li) + "".join(_file_li) - - # Add each root directory to the tree. - for k, v in sorted(tree.items(), key=lambda x: shared.natural_sort_key(x[0])): - item_html = self.create_tree_dir_item_html(tabname, k, _build_tree(v)) - # Only add non-empty entries to the tree. - if item_html is not None: - res += item_html - - return f"<ul class='tree-list tree-list--tree'>{res}</ul>" - - def create_dirs_view_html(self, tabname: str) -> str: - - subdirs = {} - for parentdir in [os.path.abspath(x) for x in self.allowed_directories_for_previews()]: - for root, dirs, _ in sorted(os.walk(parentdir, followlinks=True), key=lambda x: shared.natural_sort_key(x[0])): - for dirname in sorted(dirs, key=shared.natural_sort_key): - x = os.path.join(root, dirname) - - if not os.path.isdir(x): - continue - - subdir = os.path.abspath(x)[len(parentdir):] - - if shared.opts.extra_networks_dir_button_function: - if not subdir.startswith(os.path.sep): - subdir = os.path.sep + subdir - else: - while subdir.startswith(os.path.sep): - subdir = subdir[1:] - - is_empty = len(os.listdir(x)) == 0 - if not is_empty and not subdir.endswith(os.path.sep): - subdir = subdir + os.path.sep - - if (os.path.sep + "." in subdir or subdir.startswith(".")) and not shared.opts.extra_networks_show_hidden_directories: - continue - - subdirs[subdir] = 1 - - if subdirs: - subdirs = {"": 1, **subdirs} - - subdirs_html = "".join([f""" - <button class='lg secondary gradio-button custom-button{" search-all" if subdir == "" else ""}' onclick='extraNetworksSearchButton("{tabname}", "{self.extra_networks_tabname}", event)'> - {html.escape(subdir if subdir != "" else "all")} - </button> - """ for subdir in subdirs]) - - return subdirs_html - - def create_card_view_html(self, tabname: str, *, none_message) -> str: - res = [] - for item in self.items.values(): - res.append(self.create_item_html(tabname, item, self.card_tpl)) - - if not res: - dirs = "".join([f"<li>{x}</li>" for x in self.allowed_directories_for_previews()]) - res = [none_message or shared.html("extra-networks-no-cards.html").format(dirs=dirs)] - - return "".join(res) - - def create_html(self, tabname, *, empty=False): - self.lister.reset() - self.metadata = {} - - items_list = [] if empty else self.list_items() - self.items = {x["name"]: x for x in items_list} - - # Populate the instance metadata for each item. - for item in self.items.values(): - metadata = item.get("metadata") - if metadata: - self.metadata[item["name"]] = metadata - - if "user_metadata" not in item: - self.read_user_metadata(item) - - show_tree = shared.opts.extra_networks_tree_view_default_enabled - - page_params = { - "tabname": tabname, - "extra_networks_tabname": self.extra_networks_tabname, - "data_sortdir": shared.opts.extra_networks_card_order, - "sort_path_active": ' extra-network-control--enabled' if shared.opts.extra_networks_card_order_field == 'Path' else '', - "sort_name_active": ' extra-network-control--enabled' if shared.opts.extra_networks_card_order_field == 'Name' else '', - "sort_date_created_active": ' extra-network-control--enabled' if shared.opts.extra_networks_card_order_field == 'Date Created' else '', - "sort_date_modified_active": ' extra-network-control--enabled' if shared.opts.extra_networks_card_order_field == 'Date Modified' else '', - "tree_view_btn_extra_class": "extra-network-control--enabled" if show_tree else "", - "items_html": self.create_card_view_html(tabname, none_message="Loading..." if empty else None), - "extra_networks_tree_view_default_width": shared.opts.extra_networks_tree_view_default_width, - "tree_view_div_default_display_class": "" if show_tree else "extra-network-dirs-hidden", - } - - if shared.opts.extra_networks_tree_view_style == "Tree": - pane_content = self.pane_content_tree_tpl.format(**page_params, tree_html=self.create_tree_view_html(tabname)) - else: - pane_content = self.pane_content_dirs_tpl.format(**page_params, dirs_html=self.create_dirs_view_html(tabname)) - - return self.pane_tpl.format(**page_params, pane_content=pane_content) - - def create_item(self, name, index=None): - raise NotImplementedError() - - def list_items(self): - raise NotImplementedError() - - def allowed_directories_for_previews(self): - return [] - - def get_sort_keys(self, path): - pth = Path(path) - mtime, ctime = self.lister.mctime(path) - return { - "date_created": int(mtime), - "date_modified": int(ctime), - "name": pth.name.lower(), - "path": str(pth).lower(), - } - - def find_preview(self, path): - - potential_files = sum([[f"{path}.{ext}", f"{path}.preview.{ext}"] for ext in allowed_preview_extensions()], []) - - for file in potential_files: - if self.lister.exists(file): - return self.link_preview(file) - - return None - - def find_embedded_preview(self, path, name, metadata): - - file = f"{path}.safetensors" - if self.lister.exists(file) and 'ssmd_cover_images' in metadata and len(list(filter(None, json.loads(metadata['ssmd_cover_images'])))) > 0: - return f"./sd_extra_networks/cover-images?page={self.extra_networks_tabname}&item={name}" - - return None - - def find_description(self, path): - for file in [f"{path}.txt", f"{path}.description.txt"]: - if not self.lister.exists(file): - continue - - try: - with open(file, "r", encoding="utf-8", errors="replace") as f: - return f.read() - except OSError: - pass - return None - - def create_user_metadata_editor(self, ui, tabname): - return ui_extra_networks_user_metadata.UserMetadataEditor(ui, tabname, self) - - -def initialize(): - extra_pages.clear() - - -def register_default_pages(): - from modules.ui_extra_networks_textual_inversion import ExtraNetworksPageTextualInversion - from modules.ui_extra_networks_hypernets import ExtraNetworksPageHypernetworks - from modules.ui_extra_networks_checkpoints import ExtraNetworksPageCheckpoints - register_page(ExtraNetworksPageTextualInversion()) - register_page(ExtraNetworksPageHypernetworks()) - register_page(ExtraNetworksPageCheckpoints()) - - -class ExtraNetworksUi: - def __init__(self): - self.pages = None - """gradio HTML components related to extra networks' pages""" - - self.page_contents = None - """HTML content of the above; empty initially, filled when extra pages have to be shown""" - - self.stored_extra_pages = None - - self.button_save_preview = None - self.preview_target_filename = None - - self.tabname = None - - -def pages_in_preferred_order(pages): - tab_order = [x.lower().strip() for x in shared.opts.ui_extra_networks_tab_reorder.split(",")] - - def tab_name_score(name): - name = name.lower() - for i, possible_match in enumerate(tab_order): - if possible_match in name: - return i - - return len(pages) - - tab_scores = {page.name: (tab_name_score(page.name), original_index) for original_index, page in enumerate(pages)} - - return sorted(pages, key=lambda x: tab_scores[x.name]) - - -def create_ui(interface: gr.Blocks, unrelated_tabs, tabname): - ui = ExtraNetworksUi() - ui.pages = [] - ui.pages_contents = [] - ui.user_metadata_editors = [] - ui.stored_extra_pages = pages_in_preferred_order(extra_pages.copy()) - ui.tabname = tabname - - related_tabs = [] - - for page in ui.stored_extra_pages: - with gr.Tab(page.title, elem_id=f"{tabname}_{page.extra_networks_tabname}", elem_classes=["extra-page"]) as tab: - with gr.Column(elem_id=f"{tabname}_{page.extra_networks_tabname}_prompts", elem_classes=["extra-page-prompts"]): - pass - - elem_id = f"{tabname}_{page.extra_networks_tabname}_cards_html" - page_elem = gr.HTML(page.create_html(tabname, empty=True), elem_id=elem_id) - ui.pages.append(page_elem) - editor = page.create_user_metadata_editor(ui, tabname) - editor.create_ui() - ui.user_metadata_editors.append(editor) - related_tabs.append(tab) - - ui.button_save_preview = gr.Button('Save preview', elem_id=f"{tabname}_save_preview", visible=False) - ui.preview_target_filename = gr.Textbox('Preview save filename', elem_id=f"{tabname}_preview_filename", visible=False) - - for tab in unrelated_tabs: - tab.select(fn=None, _js=f"function(){{extraNetworksUnrelatedTabSelected('{tabname}');}}", inputs=[], outputs=[], show_progress=False) - - for page, tab in zip(ui.stored_extra_pages, related_tabs): - jscode = ( - "function(){{" - f"extraNetworksTabSelected('{tabname}', '{tabname}_{page.extra_networks_tabname}_prompts', {str(page.allow_prompt).lower()}, {str(page.allow_negative_prompt).lower()}, '{tabname}_{page.extra_networks_tabname}');" - f"applyExtraNetworkFilter('{tabname}_{page.extra_networks_tabname}');" - "}}" - ) - tab.select(fn=None, _js=jscode, inputs=[], outputs=[], show_progress=False) - - def refresh(): - for pg in ui.stored_extra_pages: - pg.refresh() - create_html() - return ui.pages_contents - - button_refresh = gr.Button("Refresh", elem_id=f"{tabname}_{page.extra_networks_tabname}_extra_refresh_internal", visible=False) - button_refresh.click(fn=refresh, inputs=[], outputs=ui.pages).then(fn=lambda: None, _js="function(){ " + f"applyExtraNetworkFilter('{tabname}_{page.extra_networks_tabname}');" + " }").then(fn=lambda: None, _js='setupAllResizeHandles') - - def create_html(): - ui.pages_contents = [pg.create_html(ui.tabname) for pg in ui.stored_extra_pages] - - def pages_html(): - if not ui.pages_contents: - create_html() - return ui.pages_contents - - interface.load(fn=pages_html, inputs=[], outputs=ui.pages).then(fn=lambda: None, _js='setupAllResizeHandles') - - return ui - - -def path_is_parent(parent_path, child_path): - parent_path = os.path.abspath(parent_path) - child_path = os.path.abspath(child_path) - - return child_path.startswith(parent_path) - - -def setup_ui(ui, gallery): - def save_preview(index, images, filename): - # this function is here for backwards compatibility and likely will be removed soon - - if len(images) == 0: - print("There is no image in gallery to save as a preview.") - return [page.create_html(ui.tabname) for page in ui.stored_extra_pages] - - index = int(index) - index = 0 if index < 0 else index - index = len(images) - 1 if index >= len(images) else index - - img_info = images[index if index >= 0 else 0] - image = image_from_url_text(img_info) - geninfo, items = read_info_from_image(image) - - is_allowed = False - for extra_page in ui.stored_extra_pages: - if any(path_is_parent(x, filename) for x in extra_page.allowed_directories_for_previews()): - is_allowed = True - break - - assert is_allowed, f'writing to {filename} is not allowed' - - save_image_with_geninfo(image, geninfo, filename) - - return [page.create_html(ui.tabname) for page in ui.stored_extra_pages] - - ui.button_save_preview.click( - fn=save_preview, - _js="function(x, y, z){return [selected_gallery_index(), y, z]}", - inputs=[ui.preview_target_filename, gallery, ui.preview_target_filename], - outputs=[*ui.pages] - ) - - for editor in ui.user_metadata_editors: - editor.setup_ui(gallery)+import functools +import os.path +import urllib.parse +from base64 import b64decode +from io import BytesIO +from pathlib import Path +from typing import Optional, Union +from dataclasses import dataclass + +from modules import shared, ui_extra_networks_user_metadata, errors, extra_networks, util +from modules.images import read_info_from_image, save_image_with_geninfo +import gradio as gr +import json +import html +from fastapi.exceptions import HTTPException +from PIL import Image + +from modules.infotext_utils import image_from_url_text + +extra_pages = [] +allowed_dirs = set() +default_allowed_preview_extensions = ["png", "jpg", "jpeg", "webp", "gif"] + +@functools.cache +def allowed_preview_extensions_with_extra(extra_extensions=None): + return set(default_allowed_preview_extensions) | set(extra_extensions or []) + + +def allowed_preview_extensions(): + return allowed_preview_extensions_with_extra((shared.opts.samples_format, )) + + +@dataclass +class ExtraNetworksItem: + """Wrapper for dictionaries representing ExtraNetworks items.""" + item: dict + + +def get_tree(paths: Union[str, list[str]], items: dict[str, ExtraNetworksItem]) -> dict: + """Recursively builds a directory tree. + + Args: + paths: Path or list of paths to directories. These paths are treated as roots from which + the tree will be built. + items: A dictionary associating filepaths to an ExtraNetworksItem instance. + + Returns: + The result directory tree. + """ + if isinstance(paths, (str,)): + paths = [paths] + + def _get_tree(_paths: list[str], _root: str): + _res = {} + for path in _paths: + relpath = os.path.relpath(path, _root) + if os.path.isdir(path): + dir_items = os.listdir(path) + # Ignore empty directories. + if not dir_items: + continue + dir_tree = _get_tree([os.path.join(path, x) for x in dir_items], _root) + # We only want to store non-empty folders in the tree. + if dir_tree: + _res[relpath] = dir_tree + else: + if path not in items: + continue + # Add the ExtraNetworksItem to the result. + _res[relpath] = items[path] + return _res + + res = {} + # Handle each root directory separately. + # Each root WILL have a key/value at the root of the result dict though + # the value can be an empty dict if the directory is empty. We want these + # placeholders for empty dirs so we can inform the user later. + for path in paths: + root = os.path.dirname(path) + relpath = os.path.relpath(path, root) + # Wrap the path in a list since that is what the `_get_tree` expects. + res[relpath] = _get_tree([path], root) + if res[relpath]: + # We need to pull the inner path out one for these root dirs. + res[relpath] = res[relpath][relpath] + + return res + +def register_page(page): + """registers extra networks page for the UI; recommend doing it in on_before_ui() callback for extensions""" + + extra_pages.append(page) + allowed_dirs.clear() + allowed_dirs.update(set(sum([x.allowed_directories_for_previews() for x in extra_pages], []))) + + +def fetch_file(filename: str = ""): + from starlette.responses import FileResponse + + if not os.path.isfile(filename): + raise HTTPException(status_code=404, detail="File not found") + + if not any(Path(x).absolute() in Path(filename).absolute().parents for x in allowed_dirs): + raise ValueError(f"File cannot be fetched: {filename}. Must be in one of directories registered by extra pages.") + + ext = os.path.splitext(filename)[1].lower()[1:] + if ext not in allowed_preview_extensions(): + raise ValueError(f"File cannot be fetched: {filename}. Extensions allowed: {allowed_preview_extensions()}.") + + # would profit from returning 304 + return FileResponse(filename, headers={"Accept-Ranges": "bytes"}) + + +def fetch_cover_images(page: str = "", item: str = "", index: int = 0): + from starlette.responses import Response + + page = next(iter([x for x in extra_pages if x.name == page]), None) + if page is None: + raise HTTPException(status_code=404, detail="File not found") + + metadata = page.metadata.get(item) + if metadata is None: + raise HTTPException(status_code=404, detail="File not found") + + cover_images = json.loads(metadata.get('ssmd_cover_images', {})) + image = cover_images[index] if index < len(cover_images) else None + if not image: + raise HTTPException(status_code=404, detail="File not found") + + try: + image = Image.open(BytesIO(b64decode(image))) + buffer = BytesIO() + image.save(buffer, format=image.format) + return Response(content=buffer.getvalue(), media_type=image.get_format_mimetype()) + except Exception as err: + raise ValueError(f"File cannot be fetched: {item}. Failed to load cover image.") from err + + +def get_metadata(page: str = "", item: str = ""): + from starlette.responses import JSONResponse + + page = next(iter([x for x in extra_pages if x.name == page]), None) + if page is None: + return JSONResponse({}) + + metadata = page.metadata.get(item) + if metadata is None: + return JSONResponse({}) + + metadata = {i:metadata[i] for i in metadata if i != 'ssmd_cover_images'} # those are cover images, and they are too big to display in UI as text + + return JSONResponse({"metadata": json.dumps(metadata, indent=4, ensure_ascii=False)}) + + +def get_single_card(page: str = "", tabname: str = "", name: str = ""): + from starlette.responses import JSONResponse + + page = next(iter([x for x in extra_pages if x.name == page]), None) + + try: + item = page.create_item(name, enable_filter=False) + page.items[name] = item + except Exception as e: + errors.display(e, "creating item for extra network") + item = page.items.get(name) + + page.read_user_metadata(item, use_cache=False) + item_html = page.create_item_html(tabname, item, shared.html("extra-networks-card.html")) + + return JSONResponse({"html": item_html}) + + +def add_pages_to_demo(app): + app.add_api_route("/sd_extra_networks/thumb", fetch_file, methods=["GET"]) + app.add_api_route("/sd_extra_networks/cover-images", fetch_cover_images, methods=["GET"]) + app.add_api_route("/sd_extra_networks/metadata", get_metadata, methods=["GET"]) + app.add_api_route("/sd_extra_networks/get-single-card", get_single_card, methods=["GET"]) + + +def quote_js(s): + s = s.replace('\\', '\\\\') + s = s.replace('"', '\\"') + return f'"{s}"' + + +class ExtraNetworksPage: + def __init__(self, title): + self.title = title + self.name = title.lower() + # This is the actual name of the extra networks tab (not txt2img/img2img). + self.extra_networks_tabname = self.name.replace(" ", "_") + self.allow_prompt = True + self.allow_negative_prompt = False + self.metadata = {} + self.items = {} + self.lister = util.MassFileLister() + # HTML Templates + self.pane_tpl = shared.html("extra-networks-pane.html") + self.pane_content_tree_tpl = shared.html("extra-networks-pane-tree.html") + self.pane_content_dirs_tpl = shared.html("extra-networks-pane-dirs.html") + self.card_tpl = shared.html("extra-networks-card.html") + self.btn_tree_tpl = shared.html("extra-networks-tree-button.html") + self.btn_copy_path_tpl = shared.html("extra-networks-copy-path-button.html") + self.btn_metadata_tpl = shared.html("extra-networks-metadata-button.html") + self.btn_edit_item_tpl = shared.html("extra-networks-edit-item-button.html") + + def refresh(self): + pass + + def read_user_metadata(self, item, use_cache=True): + filename = item.get("filename", None) + metadata = extra_networks.get_user_metadata(filename, lister=self.lister if use_cache else None) + + desc = metadata.get("description", None) + if desc is not None: + item["description"] = desc + + item["user_metadata"] = metadata + + def link_preview(self, filename): + quoted_filename = urllib.parse.quote(filename.replace('\\', '/')) + mtime, _ = self.lister.mctime(filename) + return f"./sd_extra_networks/thumb?filename={quoted_filename}&mtime={mtime}" + + def search_terms_from_path(self, filename, possible_directories=None): + abspath = os.path.abspath(filename) + for parentdir in (possible_directories if possible_directories is not None else self.allowed_directories_for_previews()): + parentdir = os.path.dirname(os.path.abspath(parentdir)) + if abspath.startswith(parentdir): + return os.path.relpath(abspath, parentdir) + + return "" + + def create_item_html( + self, + tabname: str, + item: dict, + template: Optional[str] = None, + ) -> Union[str, dict]: + """Generates HTML for a single ExtraNetworks Item. + + Args: + tabname: The name of the active tab. + item: Dictionary containing item information. + template: Optional template string to use. + + Returns: + If a template is passed: HTML string generated for this item. + Can be empty if the item is not meant to be shown. + If no template is passed: A dictionary containing the generated item's attributes. + """ + preview = item.get("preview", None) + style_height = f"height: {shared.opts.extra_networks_card_height}px;" if shared.opts.extra_networks_card_height else '' + style_width = f"width: {shared.opts.extra_networks_card_width}px;" if shared.opts.extra_networks_card_width else '' + style_font_size = f"font-size: {shared.opts.extra_networks_card_text_scale*100}%;" + card_style = style_height + style_width + style_font_size + background_image = f'<img src="{html.escape(preview)}" class="preview" loading="lazy">' if preview else '' + + onclick = item.get("onclick", None) + if onclick is None: + # Don't quote prompt/neg_prompt since they are stored as js strings already. + onclick_js_tpl = "cardClicked('{tabname}', {prompt}, {neg_prompt}, {allow_neg});" + onclick = onclick_js_tpl.format( + **{ + "tabname": tabname, + "prompt": item["prompt"], + "neg_prompt": item.get("negative_prompt", "''"), + "allow_neg": str(self.allow_negative_prompt).lower(), + } + ) + onclick = html.escape(onclick) + + btn_copy_path = self.btn_copy_path_tpl.format(**{"filename": item["filename"]}) + btn_metadata = "" + metadata = item.get("metadata") + if metadata: + btn_metadata = self.btn_metadata_tpl.format( + **{ + "extra_networks_tabname": self.extra_networks_tabname, + } + ) + btn_edit_item = self.btn_edit_item_tpl.format( + **{ + "tabname": tabname, + "extra_networks_tabname": self.extra_networks_tabname, + } + ) + + local_path = "" + filename = item.get("filename", "") + for reldir in self.allowed_directories_for_previews(): + absdir = os.path.abspath(reldir) + + if filename.startswith(absdir): + local_path = filename[len(absdir):] + + # if this is true, the item must not be shown in the default view, and must instead only be + # shown when searching for it + if shared.opts.extra_networks_hidden_models == "Always": + search_only = False + else: + search_only = "/." in local_path or "\\." in local_path + + if search_only and shared.opts.extra_networks_hidden_models == "Never": + return "" + + sort_keys = " ".join( + [ + f'data-sort-{k}="{html.escape(str(v))}"' + for k, v in item.get("sort_keys", {}).items() + ] + ).strip() + + search_terms_html = "" + search_term_template = "<span class='hidden {class}'>{search_term}</span>" + for search_term in item.get("search_terms", []): + search_terms_html += search_term_template.format( + **{ + "class": f"search_terms{' search_only' if search_only else ''}", + "search_term": search_term, + } + ) + + description = (item.get("description", "") or "" if shared.opts.extra_networks_card_show_desc else "") + if not shared.opts.extra_networks_card_description_is_html: + description = html.escape(description) + + # Some items here might not be used depending on HTML template used. + args = { + "background_image": background_image, + "card_clicked": onclick, + "copy_path_button": btn_copy_path, + "description": description, + "edit_button": btn_edit_item, + "local_preview": quote_js(item["local_preview"]), + "metadata_button": btn_metadata, + "name": html.escape(item["name"]), + "prompt": item.get("prompt", None), + "save_card_preview": html.escape(f"return saveCardPreview(event, '{tabname}', '{item['local_preview']}');"), + "search_only": " search_only" if search_only else "", + "search_terms": search_terms_html, + "sort_keys": sort_keys, + "style": card_style, + "tabname": tabname, + "extra_networks_tabname": self.extra_networks_tabname, + } + + if template: + return template.format(**args) + else: + return args + + def create_tree_dir_item_html( + self, + tabname: str, + dir_path: str, + content: Optional[str] = None, + ) -> Optional[str]: + """Generates HTML for a directory item in the tree. + + The generated HTML is of the format: + ```html + <li class="tree-list-item tree-list-item--has-subitem"> + <div class="tree-list-content tree-list-content-dir"></div> + <ul class="tree-list tree-list--subgroup"> + {content} + </ul> + </li> + ``` + + Args: + tabname: The name of the active tab. + dir_path: Path to the directory for this item. + content: Optional HTML string that will be wrapped by this <ul>. + + Returns: + HTML formatted string. + """ + if not content: + return None + + btn = self.btn_tree_tpl.format( + **{ + "search_terms": "", + "subclass": "tree-list-content-dir", + "tabname": tabname, + "extra_networks_tabname": self.extra_networks_tabname, + "onclick_extra": "", + "data_path": dir_path, + "data_hash": "", + "action_list_item_action_leading": "<i class='tree-list-item-action-chevron'></i>", + "action_list_item_visual_leading": "🗀", + "action_list_item_label": os.path.basename(dir_path), + "action_list_item_visual_trailing": "", + "action_list_item_action_trailing": "", + } + ) + ul = f"<ul class='tree-list tree-list--subgroup' hidden>{content}</ul>" + return ( + "<li class='tree-list-item tree-list-item--has-subitem' data-tree-entry-type='dir'>" + f"{btn}{ul}" + "</li>" + ) + + def create_tree_file_item_html(self, tabname: str, file_path: str, item: dict) -> str: + """Generates HTML for a file item in the tree. + + The generated HTML is of the format: + ```html + <li class="tree-list-item tree-list-item--subitem"> + <span data-filterable-item-text hidden></span> + <div class="tree-list-content tree-list-content-file"></div> + </li> + ``` + + Args: + tabname: The name of the active tab. + file_path: The path to the file for this item. + item: Dictionary containing the item information. + + Returns: + HTML formatted string. + """ + item_html_args = self.create_item_html(tabname, item) + action_buttons = "".join( + [ + item_html_args["copy_path_button"], + item_html_args["metadata_button"], + item_html_args["edit_button"], + ] + ) + action_buttons = f"<div class=\"button-row\">{action_buttons}</div>" + btn = self.btn_tree_tpl.format( + **{ + "search_terms": "", + "subclass": "tree-list-content-file", + "tabname": tabname, + "extra_networks_tabname": self.extra_networks_tabname, + "onclick_extra": item_html_args["card_clicked"], + "data_path": file_path, + "data_hash": item["shorthash"], + "action_list_item_action_leading": "<i class='tree-list-item-action-chevron'></i>", + "action_list_item_visual_leading": "🗎", + "action_list_item_label": item["name"], + "action_list_item_visual_trailing": "", + "action_list_item_action_trailing": action_buttons, + } + ) + return ( + "<li class='tree-list-item tree-list-item--subitem' data-tree-entry-type='file'>" + f"{btn}" + "</li>" + ) + + def create_tree_view_html(self, tabname: str) -> str: + """Generates HTML for displaying folders in a tree view. + + Args: + tabname: The name of the active tab. + + Returns: + HTML string generated for this tree view. + """ + res = "" + + # Setup the tree dictionary. + roots = self.allowed_directories_for_previews() + tree_items = {v["filename"]: ExtraNetworksItem(v) for v in self.items.values()} + tree = get_tree([os.path.abspath(x) for x in roots], items=tree_items) + + if not tree: + return res + + def _build_tree(data: Optional[dict[str, ExtraNetworksItem]] = None) -> Optional[str]: + """Recursively builds HTML for a tree. + + Args: + data: Dictionary representing a directory tree. Can be NoneType. + Data keys should be absolute paths from the root and values + should be subdirectory trees or an ExtraNetworksItem. + + Returns: + If data is not None: HTML string + Else: None + """ + if not data: + return None + + # Lists for storing <li> items html for directories and files separately. + _dir_li = [] + _file_li = [] + + for k, v in sorted(data.items(), key=lambda x: shared.natural_sort_key(x[0])): + if isinstance(v, (ExtraNetworksItem,)): + _file_li.append(self.create_tree_file_item_html(tabname, k, v.item)) + else: + _dir_li.append(self.create_tree_dir_item_html(tabname, k, _build_tree(v))) + + # Directories should always be displayed before files so we order them here. + return "".join(_dir_li) + "".join(_file_li) + + # Add each root directory to the tree. + for k, v in sorted(tree.items(), key=lambda x: shared.natural_sort_key(x[0])): + item_html = self.create_tree_dir_item_html(tabname, k, _build_tree(v)) + # Only add non-empty entries to the tree. + if item_html is not None: + res += item_html + + return f"<ul class='tree-list tree-list--tree'>{res}</ul>" + + def create_dirs_view_html(self, tabname: str) -> str: + """Generates HTML for displaying folders.""" + + subdirs = {} + for parentdir in [os.path.abspath(x) for x in self.allowed_directories_for_previews()]: + for root, dirs, _ in sorted(os.walk(parentdir, followlinks=True), key=lambda x: shared.natural_sort_key(x[0])): + for dirname in sorted(dirs, key=shared.natural_sort_key): + x = os.path.join(root, dirname) + + if not os.path.isdir(x): + continue + + subdir = os.path.abspath(x)[len(parentdir):] + + if shared.opts.extra_networks_dir_button_function: + if not subdir.startswith(os.path.sep): + subdir = os.path.sep + subdir + else: + while subdir.startswith(os.path.sep): + subdir = subdir[1:] + + is_empty = len(os.listdir(x)) == 0 + if not is_empty and not subdir.endswith(os.path.sep): + subdir = subdir + os.path.sep + + if (os.path.sep + "." in subdir or subdir.startswith(".")) and not shared.opts.extra_networks_show_hidden_directories: + continue + + subdirs[subdir] = 1 + + if subdirs: + subdirs = {"": 1, **subdirs} + + subdirs_html = "".join([f""" + <button class='lg secondary gradio-button custom-button{" search-all" if subdir == "" else ""}' onclick='extraNetworksSearchButton("{tabname}", "{self.extra_networks_tabname}", event)'> + {html.escape(subdir if subdir != "" else "all")} + </button> + """ for subdir in subdirs]) + + return subdirs_html + + def create_card_view_html(self, tabname: str, *, none_message) -> str: + """Generates HTML for the network Card View section for a tab. + + This HTML goes into the `extra-networks-pane.html` <div> with + `id='{tabname}_{extra_networks_tabname}_cards`. + + Args: + tabname: The name of the active tab. + none_message: HTML text to show when there are no cards. + + Returns: + HTML formatted string. + """ + res = [] + for item in self.items.values(): + res.append(self.create_item_html(tabname, item, self.card_tpl)) + + if not res: + dirs = "".join([f"<li>{x}</li>" for x in self.allowed_directories_for_previews()]) + res = [none_message or shared.html("extra-networks-no-cards.html").format(dirs=dirs)] + + return "".join(res) + + def create_html(self, tabname, *, empty=False): + """Generates an HTML string for the current pane. + + The generated HTML uses `extra-networks-pane.html` as a template. + + Args: + tabname: The name of the active tab. + empty: create an empty HTML page with no items + + Returns: + HTML formatted string. + """ + self.lister.reset() + self.metadata = {} + + items_list = [] if empty else self.list_items() + self.items = {x["name"]: x for x in items_list} + + # Populate the instance metadata for each item. + for item in self.items.values(): + metadata = item.get("metadata") + if metadata: + self.metadata[item["name"]] = metadata + + if "user_metadata" not in item: + self.read_user_metadata(item) + + show_tree = shared.opts.extra_networks_tree_view_default_enabled + + page_params = { + "tabname": tabname, + "extra_networks_tabname": self.extra_networks_tabname, + "data_sortdir": shared.opts.extra_networks_card_order, + "sort_path_active": ' extra-network-control--enabled' if shared.opts.extra_networks_card_order_field == 'Path' else '', + "sort_name_active": ' extra-network-control--enabled' if shared.opts.extra_networks_card_order_field == 'Name' else '', + "sort_date_created_active": ' extra-network-control--enabled' if shared.opts.extra_networks_card_order_field == 'Date Created' else '', + "sort_date_modified_active": ' extra-network-control--enabled' if shared.opts.extra_networks_card_order_field == 'Date Modified' else '', + "tree_view_btn_extra_class": "extra-network-control--enabled" if show_tree else "", + "items_html": self.create_card_view_html(tabname, none_message="Loading..." if empty else None), + "extra_networks_tree_view_default_width": shared.opts.extra_networks_tree_view_default_width, + "tree_view_div_default_display_class": "" if show_tree else "extra-network-dirs-hidden", + } + + if shared.opts.extra_networks_tree_view_style == "Tree": + pane_content = self.pane_content_tree_tpl.format(**page_params, tree_html=self.create_tree_view_html(tabname)) + else: + pane_content = self.pane_content_dirs_tpl.format(**page_params, dirs_html=self.create_dirs_view_html(tabname)) + + return self.pane_tpl.format(**page_params, pane_content=pane_content) + + def create_item(self, name, index=None): + raise NotImplementedError() + + def list_items(self): + raise NotImplementedError() + + def allowed_directories_for_previews(self): + return [] + + def get_sort_keys(self, path): + """ + List of default keys used for sorting in the UI. + """ + pth = Path(path) + mtime, ctime = self.lister.mctime(path) + return { + "date_created": int(mtime), + "date_modified": int(ctime), + "name": pth.name.lower(), + "path": str(pth).lower(), + } + + def find_preview(self, path): + """ + Find a preview PNG for a given path (without extension) and call link_preview on it. + """ + + potential_files = sum([[f"{path}.{ext}", f"{path}.preview.{ext}"] for ext in allowed_preview_extensions()], []) + + for file in potential_files: + if self.lister.exists(file): + return self.link_preview(file) + + return None + + def find_embedded_preview(self, path, name, metadata): + """ + Find if embedded preview exists in safetensors metadata and return endpoint for it. + """ + + file = f"{path}.safetensors" + if self.lister.exists(file) and 'ssmd_cover_images' in metadata and len(list(filter(None, json.loads(metadata['ssmd_cover_images'])))) > 0: + return f"./sd_extra_networks/cover-images?page={self.extra_networks_tabname}&item={name}" + + return None + + def find_description(self, path): + """ + Find and read a description file for a given path (without extension). + """ + for file in [f"{path}.txt", f"{path}.description.txt"]: + if not self.lister.exists(file): + continue + + try: + with open(file, "r", encoding="utf-8", errors="replace") as f: + return f.read() + except OSError: + pass + return None + + def create_user_metadata_editor(self, ui, tabname): + return ui_extra_networks_user_metadata.UserMetadataEditor(ui, tabname, self) + + +def initialize(): + extra_pages.clear() + + +def register_default_pages(): + from modules.ui_extra_networks_textual_inversion import ExtraNetworksPageTextualInversion + from modules.ui_extra_networks_hypernets import ExtraNetworksPageHypernetworks + from modules.ui_extra_networks_checkpoints import ExtraNetworksPageCheckpoints + register_page(ExtraNetworksPageTextualInversion()) + register_page(ExtraNetworksPageHypernetworks()) + register_page(ExtraNetworksPageCheckpoints()) + + +class ExtraNetworksUi: + def __init__(self): + self.pages = None + """gradio HTML components related to extra networks' pages""" + + self.page_contents = None + """HTML content of the above; empty initially, filled when extra pages have to be shown""" + + self.stored_extra_pages = None + + self.button_save_preview = None + self.preview_target_filename = None + + self.tabname = None + + +def pages_in_preferred_order(pages): + tab_order = [x.lower().strip() for x in shared.opts.ui_extra_networks_tab_reorder.split(",")] + + def tab_name_score(name): + name = name.lower() + for i, possible_match in enumerate(tab_order): + if possible_match in name: + return i + + return len(pages) + + tab_scores = {page.name: (tab_name_score(page.name), original_index) for original_index, page in enumerate(pages)} + + return sorted(pages, key=lambda x: tab_scores[x.name]) + + +def create_ui(interface: gr.Blocks, unrelated_tabs, tabname): + ui = ExtraNetworksUi() + ui.pages = [] + ui.pages_contents = [] + ui.user_metadata_editors = [] + ui.stored_extra_pages = pages_in_preferred_order(extra_pages.copy()) + ui.tabname = tabname + + related_tabs = [] + + for page in ui.stored_extra_pages: + with gr.Tab(page.title, elem_id=f"{tabname}_{page.extra_networks_tabname}", elem_classes=["extra-page"]) as tab: + with gr.Column(elem_id=f"{tabname}_{page.extra_networks_tabname}_prompts", elem_classes=["extra-page-prompts"]): + pass + + elem_id = f"{tabname}_{page.extra_networks_tabname}_cards_html" + page_elem = gr.HTML(page.create_html(tabname, empty=True), elem_id=elem_id) + ui.pages.append(page_elem) + editor = page.create_user_metadata_editor(ui, tabname) + editor.create_ui() + ui.user_metadata_editors.append(editor) + related_tabs.append(tab) + + ui.button_save_preview = gr.Button('Save preview', elem_id=f"{tabname}_save_preview", visible=False) + ui.preview_target_filename = gr.Textbox('Preview save filename', elem_id=f"{tabname}_preview_filename", visible=False) + + for tab in unrelated_tabs: + tab.select(fn=None, _js=f"function(){{extraNetworksUnrelatedTabSelected('{tabname}');}}", inputs=[], outputs=[], show_progress=False) + + for page, tab in zip(ui.stored_extra_pages, related_tabs): + jscode = ( + "function(){{" + f"extraNetworksTabSelected('{tabname}', '{tabname}_{page.extra_networks_tabname}_prompts', {str(page.allow_prompt).lower()}, {str(page.allow_negative_prompt).lower()}, '{tabname}_{page.extra_networks_tabname}');" + f"applyExtraNetworkFilter('{tabname}_{page.extra_networks_tabname}');" + "}}" + ) + tab.select(fn=None, _js=jscode, inputs=[], outputs=[], show_progress=False) + + def refresh(): + for pg in ui.stored_extra_pages: + pg.refresh() + create_html() + return ui.pages_contents + + button_refresh = gr.Button("Refresh", elem_id=f"{tabname}_{page.extra_networks_tabname}_extra_refresh_internal", visible=False) + button_refresh.click(fn=refresh, inputs=[], outputs=ui.pages).then(fn=lambda: None, _js="function(){ " + f"applyExtraNetworkFilter('{tabname}_{page.extra_networks_tabname}');" + " }").then(fn=lambda: None, _js='setupAllResizeHandles') + + def create_html(): + ui.pages_contents = [pg.create_html(ui.tabname) for pg in ui.stored_extra_pages] + + def pages_html(): + if not ui.pages_contents: + create_html() + return ui.pages_contents + + interface.load(fn=pages_html, inputs=[], outputs=ui.pages).then(fn=lambda: None, _js='setupAllResizeHandles') + + return ui + + +def path_is_parent(parent_path, child_path): + parent_path = os.path.abspath(parent_path) + child_path = os.path.abspath(child_path) + + return child_path.startswith(parent_path) + + +def setup_ui(ui, gallery): + def save_preview(index, images, filename): + # this function is here for backwards compatibility and likely will be removed soon + + if len(images) == 0: + print("There is no image in gallery to save as a preview.") + return [page.create_html(ui.tabname) for page in ui.stored_extra_pages] + + index = int(index) + index = 0 if index < 0 else index + index = len(images) - 1 if index >= len(images) else index + + img_info = images[index if index >= 0 else 0] + image = image_from_url_text(img_info) + geninfo, items = read_info_from_image(image) + + is_allowed = False + for extra_page in ui.stored_extra_pages: + if any(path_is_parent(x, filename) for x in extra_page.allowed_directories_for_previews()): + is_allowed = True + break + + assert is_allowed, f'writing to {filename} is not allowed' + + save_image_with_geninfo(image, geninfo, filename) + + return [page.create_html(ui.tabname) for page in ui.stored_extra_pages] + + ui.button_save_preview.click( + fn=save_preview, + _js="function(x, y, z){return [selected_gallery_index(), y, z]}", + inputs=[ui.preview_target_filename, gallery, ui.preview_target_filename], + outputs=[*ui.pages] + ) + + for editor in ui.user_metadata_editors: + editor.setup_ui(gallery)
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/ui_extra_networks.py
Generate docstrings with parameter types
import gradio as gr class FormComponent: def get_expected_parent(self): return gr.components.Form gr.Dropdown.get_expected_parent = FormComponent.get_expected_parent class ToolButton(FormComponent, gr.Button): def __init__(self, *args, **kwargs): classes = kwargs.pop("elem_classes", []) super().__init__(*args, elem_classes=["tool", *classes], **kwargs) def get_block_name(self): return "button" class ResizeHandleRow(gr.Row): def __init__(self, **kwargs): super().__init__(**kwargs) self.elem_classes.append("resize-handle-row") def get_block_name(self): return "row" class FormRow(FormComponent, gr.Row): def get_block_name(self): return "row" class FormColumn(FormComponent, gr.Column): def get_block_name(self): return "column" class FormGroup(FormComponent, gr.Group): def get_block_name(self): return "group" class FormHTML(FormComponent, gr.HTML): def get_block_name(self): return "html" class FormColorPicker(FormComponent, gr.ColorPicker): def get_block_name(self): return "colorpicker" class DropdownMulti(FormComponent, gr.Dropdown): def __init__(self, **kwargs): super().__init__(multiselect=True, **kwargs) def get_block_name(self): return "dropdown" class DropdownEditable(FormComponent, gr.Dropdown): def __init__(self, **kwargs): super().__init__(allow_custom_value=True, **kwargs) def get_block_name(self): return "dropdown" class InputAccordion(gr.Checkbox): global_index = 0 def __init__(self, value, **kwargs): self.accordion_id = kwargs.get('elem_id') if self.accordion_id is None: self.accordion_id = f"input-accordion-{InputAccordion.global_index}" InputAccordion.global_index += 1 kwargs_checkbox = { **kwargs, "elem_id": f"{self.accordion_id}-checkbox", "visible": False, } super().__init__(value, **kwargs_checkbox) self.change(fn=None, _js='function(checked){ inputAccordionChecked("' + self.accordion_id + '", checked); }', inputs=[self]) kwargs_accordion = { **kwargs, "elem_id": self.accordion_id, "label": kwargs.get('label', 'Accordion'), "elem_classes": ['input-accordion'], "open": value, } self.accordion = gr.Accordion(**kwargs_accordion) def extra(self): return gr.Column(elem_id=self.accordion_id + '-extra', elem_classes='input-accordion-extra', min_width=0) def __enter__(self): self.accordion.__enter__() return self def __exit__(self, exc_type, exc_val, exc_tb): self.accordion.__exit__(exc_type, exc_val, exc_tb) def get_block_name(self): return "checkbox"
--- +++ @@ -1,119 +1,145 @@-import gradio as gr - - -class FormComponent: - def get_expected_parent(self): - return gr.components.Form - - -gr.Dropdown.get_expected_parent = FormComponent.get_expected_parent - - -class ToolButton(FormComponent, gr.Button): - - def __init__(self, *args, **kwargs): - classes = kwargs.pop("elem_classes", []) - super().__init__(*args, elem_classes=["tool", *classes], **kwargs) - - def get_block_name(self): - return "button" - - -class ResizeHandleRow(gr.Row): - - def __init__(self, **kwargs): - super().__init__(**kwargs) - - self.elem_classes.append("resize-handle-row") - - def get_block_name(self): - return "row" - - -class FormRow(FormComponent, gr.Row): - - def get_block_name(self): - return "row" - - -class FormColumn(FormComponent, gr.Column): - - def get_block_name(self): - return "column" - - -class FormGroup(FormComponent, gr.Group): - - def get_block_name(self): - return "group" - - -class FormHTML(FormComponent, gr.HTML): - - def get_block_name(self): - return "html" - - -class FormColorPicker(FormComponent, gr.ColorPicker): - - def get_block_name(self): - return "colorpicker" - - -class DropdownMulti(FormComponent, gr.Dropdown): - def __init__(self, **kwargs): - super().__init__(multiselect=True, **kwargs) - - def get_block_name(self): - return "dropdown" - - -class DropdownEditable(FormComponent, gr.Dropdown): - def __init__(self, **kwargs): - super().__init__(allow_custom_value=True, **kwargs) - - def get_block_name(self): - return "dropdown" - - -class InputAccordion(gr.Checkbox): - - global_index = 0 - - def __init__(self, value, **kwargs): - self.accordion_id = kwargs.get('elem_id') - if self.accordion_id is None: - self.accordion_id = f"input-accordion-{InputAccordion.global_index}" - InputAccordion.global_index += 1 - - kwargs_checkbox = { - **kwargs, - "elem_id": f"{self.accordion_id}-checkbox", - "visible": False, - } - super().__init__(value, **kwargs_checkbox) - - self.change(fn=None, _js='function(checked){ inputAccordionChecked("' + self.accordion_id + '", checked); }', inputs=[self]) - - kwargs_accordion = { - **kwargs, - "elem_id": self.accordion_id, - "label": kwargs.get('label', 'Accordion'), - "elem_classes": ['input-accordion'], - "open": value, - } - self.accordion = gr.Accordion(**kwargs_accordion) - - def extra(self): - - return gr.Column(elem_id=self.accordion_id + '-extra', elem_classes='input-accordion-extra', min_width=0) - - def __enter__(self): - self.accordion.__enter__() - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - self.accordion.__exit__(exc_type, exc_val, exc_tb) - - def get_block_name(self): - return "checkbox" +import gradio as gr + + +class FormComponent: + def get_expected_parent(self): + return gr.components.Form + + +gr.Dropdown.get_expected_parent = FormComponent.get_expected_parent + + +class ToolButton(FormComponent, gr.Button): + """Small button with single emoji as text, fits inside gradio forms""" + + def __init__(self, *args, **kwargs): + classes = kwargs.pop("elem_classes", []) + super().__init__(*args, elem_classes=["tool", *classes], **kwargs) + + def get_block_name(self): + return "button" + + +class ResizeHandleRow(gr.Row): + """Same as gr.Row but fits inside gradio forms""" + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + self.elem_classes.append("resize-handle-row") + + def get_block_name(self): + return "row" + + +class FormRow(FormComponent, gr.Row): + """Same as gr.Row but fits inside gradio forms""" + + def get_block_name(self): + return "row" + + +class FormColumn(FormComponent, gr.Column): + """Same as gr.Column but fits inside gradio forms""" + + def get_block_name(self): + return "column" + + +class FormGroup(FormComponent, gr.Group): + """Same as gr.Group but fits inside gradio forms""" + + def get_block_name(self): + return "group" + + +class FormHTML(FormComponent, gr.HTML): + """Same as gr.HTML but fits inside gradio forms""" + + def get_block_name(self): + return "html" + + +class FormColorPicker(FormComponent, gr.ColorPicker): + """Same as gr.ColorPicker but fits inside gradio forms""" + + def get_block_name(self): + return "colorpicker" + + +class DropdownMulti(FormComponent, gr.Dropdown): + """Same as gr.Dropdown but always multiselect""" + def __init__(self, **kwargs): + super().__init__(multiselect=True, **kwargs) + + def get_block_name(self): + return "dropdown" + + +class DropdownEditable(FormComponent, gr.Dropdown): + """Same as gr.Dropdown but allows editing value""" + def __init__(self, **kwargs): + super().__init__(allow_custom_value=True, **kwargs) + + def get_block_name(self): + return "dropdown" + + +class InputAccordion(gr.Checkbox): + """A gr.Accordion that can be used as an input - returns True if open, False if closed. + + Actually just a hidden checkbox, but creates an accordion that follows and is followed by the state of the checkbox. + """ + + global_index = 0 + + def __init__(self, value, **kwargs): + self.accordion_id = kwargs.get('elem_id') + if self.accordion_id is None: + self.accordion_id = f"input-accordion-{InputAccordion.global_index}" + InputAccordion.global_index += 1 + + kwargs_checkbox = { + **kwargs, + "elem_id": f"{self.accordion_id}-checkbox", + "visible": False, + } + super().__init__(value, **kwargs_checkbox) + + self.change(fn=None, _js='function(checked){ inputAccordionChecked("' + self.accordion_id + '", checked); }', inputs=[self]) + + kwargs_accordion = { + **kwargs, + "elem_id": self.accordion_id, + "label": kwargs.get('label', 'Accordion'), + "elem_classes": ['input-accordion'], + "open": value, + } + self.accordion = gr.Accordion(**kwargs_accordion) + + def extra(self): + """Allows you to put something into the label of the accordion. + + Use it like this: + + ``` + with InputAccordion(False, label="Accordion") as acc: + with acc.extra(): + FormHTML(value="hello", min_width=0) + + ... + ``` + """ + + return gr.Column(elem_id=self.accordion_id + '-extra', elem_classes='input-accordion-extra', min_width=0) + + def __enter__(self): + self.accordion.__enter__() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.accordion.__exit__(exc_type, exc_val, exc_tb) + + def get_block_name(self): + return "checkbox" +
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/ui_components.py
Generate consistent docstrings
import inspect from collections import namedtuple import numpy as np import torch from PIL import Image from modules import devices, images, sd_vae_approx, sd_samplers, sd_vae_taesd, shared, sd_models from modules.shared import opts, state import k_diffusion.sampling SamplerDataTuple = namedtuple('SamplerData', ['name', 'constructor', 'aliases', 'options']) class SamplerData(SamplerDataTuple): def total_steps(self, steps): if self.options.get("second_order", False): steps = steps * 2 return steps def setup_img2img_steps(p, steps=None): if opts.img2img_fix_steps or steps is not None: requested_steps = (steps or p.steps) steps = int(requested_steps / min(p.denoising_strength, 0.999)) if p.denoising_strength > 0 else 0 t_enc = requested_steps - 1 else: steps = p.steps t_enc = int(min(p.denoising_strength, 0.999) * steps) return steps, t_enc approximation_indexes = {"Full": 0, "Approx NN": 1, "Approx cheap": 2, "TAESD": 3} def samples_to_images_tensor(sample, approximation=None, model=None): if approximation is None or (shared.state.interrupted and opts.live_preview_fast_interrupt): approximation = approximation_indexes.get(opts.show_progress_type, 0) from modules import lowvram if approximation == 0 and lowvram.is_enabled(shared.sd_model) and not shared.opts.live_preview_allow_lowvram_full: approximation = 1 if approximation == 2: x_sample = sd_vae_approx.cheap_approximation(sample) elif approximation == 1: x_sample = sd_vae_approx.model()(sample.to(devices.device, devices.dtype)).detach() elif approximation == 3: x_sample = sd_vae_taesd.decoder_model()(sample.to(devices.device, devices.dtype)).detach() x_sample = x_sample * 2 - 1 else: if model is None: model = shared.sd_model with torch.no_grad(), devices.without_autocast(): # fixes an issue with unstable VAEs that are flaky even in fp32 x_sample = model.decode_first_stage(sample.to(model.first_stage_model.dtype)) return x_sample def single_sample_to_image(sample, approximation=None): x_sample = samples_to_images_tensor(sample.unsqueeze(0), approximation)[0] * 0.5 + 0.5 x_sample = torch.clamp(x_sample, min=0.0, max=1.0) x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2) x_sample = x_sample.astype(np.uint8) return Image.fromarray(x_sample) def decode_first_stage(model, x): x = x.to(devices.dtype_vae) approx_index = approximation_indexes.get(opts.sd_vae_decode_method, 0) return samples_to_images_tensor(x, approx_index, model) def sample_to_image(samples, index=0, approximation=None): return single_sample_to_image(samples[index], approximation) def samples_to_image_grid(samples, approximation=None): return images.image_grid([single_sample_to_image(sample, approximation) for sample in samples]) def images_tensor_to_samples(image, approximation=None, model=None): if approximation is None: approximation = approximation_indexes.get(opts.sd_vae_encode_method, 0) if approximation == 3: image = image.to(devices.device, devices.dtype) x_latent = sd_vae_taesd.encoder_model()(image) else: if model is None: model = shared.sd_model model.first_stage_model.to(devices.dtype_vae) image = image.to(shared.device, dtype=devices.dtype_vae) image = image * 2 - 1 if len(image) > 1: x_latent = torch.stack([ model.get_first_stage_encoding( model.encode_first_stage(torch.unsqueeze(img, 0)) )[0] for img in image ]) else: x_latent = model.get_first_stage_encoding(model.encode_first_stage(image)) return x_latent def store_latent(decoded): state.current_latent = decoded if opts.live_previews_enable and opts.show_progress_every_n_steps > 0 and shared.state.sampling_step % opts.show_progress_every_n_steps == 0: if not shared.parallel_processing_allowed: shared.state.assign_current_image(sample_to_image(decoded)) def is_sampler_using_eta_noise_seed_delta(p): sampler_config = sd_samplers.find_sampler_config(p.sampler_name) eta = p.eta if eta is None and p.sampler is not None: eta = p.sampler.eta if eta is None and sampler_config is not None: eta = 0 if sampler_config.options.get("default_eta_is_0", False) else 1.0 if eta == 0: return False return sampler_config.options.get("uses_ensd", False) class InterruptedException(BaseException): pass def replace_torchsde_browinan(): import torchsde._brownian.brownian_interval def torchsde_randn(size, dtype, device, seed): return devices.randn_local(seed, size).to(device=device, dtype=dtype) torchsde._brownian.brownian_interval._randn = torchsde_randn replace_torchsde_browinan() def apply_refiner(cfg_denoiser, sigma=None): if opts.refiner_switch_by_sample_steps or sigma is None: completed_ratio = cfg_denoiser.step / cfg_denoiser.total_steps cfg_denoiser.p.extra_generation_params["Refiner switch by sampling steps"] = True else: # torch.max(sigma) only to handle rare case where we might have different sigmas in the same batch try: timestep = torch.argmin(torch.abs(cfg_denoiser.inner_model.sigmas.to(sigma.device) - torch.max(sigma))) except AttributeError: # for samplers that don't use sigmas (DDIM) sigma is actually the timestep timestep = torch.max(sigma).to(dtype=int) completed_ratio = (999 - timestep) / 1000 refiner_switch_at = cfg_denoiser.p.refiner_switch_at refiner_checkpoint_info = cfg_denoiser.p.refiner_checkpoint_info if refiner_switch_at is not None and completed_ratio < refiner_switch_at: return False if refiner_checkpoint_info is None or shared.sd_model.sd_checkpoint_info == refiner_checkpoint_info: return False if getattr(cfg_denoiser.p, "enable_hr", False): is_second_pass = cfg_denoiser.p.is_hr_pass if opts.hires_fix_refiner_pass == "first pass" and is_second_pass: return False if opts.hires_fix_refiner_pass == "second pass" and not is_second_pass: return False if opts.hires_fix_refiner_pass != "second pass": cfg_denoiser.p.extra_generation_params['Hires refiner'] = opts.hires_fix_refiner_pass cfg_denoiser.p.extra_generation_params['Refiner'] = refiner_checkpoint_info.short_title cfg_denoiser.p.extra_generation_params['Refiner switch at'] = refiner_switch_at with sd_models.SkipWritingToConfig(): sd_models.reload_model_weights(info=refiner_checkpoint_info) devices.torch_gc() cfg_denoiser.p.setup_conds() cfg_denoiser.update_inner_model() return True class TorchHijack: def __init__(self, p): self.rng = p.rng def __getattr__(self, item): if item == 'randn_like': return self.randn_like if hasattr(torch, item): return getattr(torch, item) raise AttributeError(f"'{type(self).__name__}' object has no attribute '{item}'") def randn_like(self, x): return self.rng.next() class Sampler: def __init__(self, funcname): self.funcname = funcname self.func = funcname self.extra_params = [] self.sampler_noises = None self.stop_at = None self.eta = None self.config: SamplerData = None # set by the function calling the constructor self.last_latent = None self.s_min_uncond = None self.s_churn = 0.0 self.s_tmin = 0.0 self.s_tmax = float('inf') self.s_noise = 1.0 self.eta_option_field = 'eta_ancestral' self.eta_infotext_field = 'Eta' self.eta_default = 1.0 self.conditioning_key = getattr(shared.sd_model.model, 'conditioning_key', 'crossattn') self.p = None self.model_wrap_cfg = None self.sampler_extra_args = None self.options = {} def callback_state(self, d): step = d['i'] if self.stop_at is not None and step > self.stop_at: raise InterruptedException state.sampling_step = step shared.total_tqdm.update() def launch_sampling(self, steps, func): self.model_wrap_cfg.steps = steps self.model_wrap_cfg.total_steps = self.config.total_steps(steps) state.sampling_steps = steps state.sampling_step = 0 try: return func() except RecursionError: print( 'Encountered RecursionError during sampling, returning last latent. ' 'rho >5 with a polyexponential scheduler may cause this error. ' 'You should try to use a smaller rho value instead.' ) return self.last_latent except InterruptedException: return self.last_latent def number_of_needed_noises(self, p): return p.steps def initialize(self, p) -> dict: self.p = p self.model_wrap_cfg.p = p self.model_wrap_cfg.mask = p.mask if hasattr(p, 'mask') else None self.model_wrap_cfg.nmask = p.nmask if hasattr(p, 'nmask') else None self.model_wrap_cfg.step = 0 self.model_wrap_cfg.image_cfg_scale = getattr(p, 'image_cfg_scale', None) self.eta = p.eta if p.eta is not None else getattr(opts, self.eta_option_field, 0.0) self.s_min_uncond = getattr(p, 's_min_uncond', 0.0) k_diffusion.sampling.torch = TorchHijack(p) extra_params_kwargs = {} for param_name in self.extra_params: if hasattr(p, param_name) and param_name in inspect.signature(self.func).parameters: extra_params_kwargs[param_name] = getattr(p, param_name) if 'eta' in inspect.signature(self.func).parameters: if self.eta != self.eta_default: p.extra_generation_params[self.eta_infotext_field] = self.eta extra_params_kwargs['eta'] = self.eta if len(self.extra_params) > 0: s_churn = getattr(opts, 's_churn', p.s_churn) s_tmin = getattr(opts, 's_tmin', p.s_tmin) s_tmax = getattr(opts, 's_tmax', p.s_tmax) or self.s_tmax # 0 = inf s_noise = getattr(opts, 's_noise', p.s_noise) if 's_churn' in extra_params_kwargs and s_churn != self.s_churn: extra_params_kwargs['s_churn'] = s_churn p.s_churn = s_churn p.extra_generation_params['Sigma churn'] = s_churn if 's_tmin' in extra_params_kwargs and s_tmin != self.s_tmin: extra_params_kwargs['s_tmin'] = s_tmin p.s_tmin = s_tmin p.extra_generation_params['Sigma tmin'] = s_tmin if 's_tmax' in extra_params_kwargs and s_tmax != self.s_tmax: extra_params_kwargs['s_tmax'] = s_tmax p.s_tmax = s_tmax p.extra_generation_params['Sigma tmax'] = s_tmax if 's_noise' in extra_params_kwargs and s_noise != self.s_noise: extra_params_kwargs['s_noise'] = s_noise p.s_noise = s_noise p.extra_generation_params['Sigma noise'] = s_noise return extra_params_kwargs def create_noise_sampler(self, x, sigmas, p): if shared.opts.no_dpmpp_sde_batch_determinism: return None from k_diffusion.sampling import BrownianTreeNoiseSampler sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max() current_iter_seeds = p.all_seeds[p.iteration * p.batch_size:(p.iteration + 1) * p.batch_size] return BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=current_iter_seeds) def sample(self, p, x, conditioning, unconditional_conditioning, steps=None, image_conditioning=None): raise NotImplementedError() def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning, steps=None, image_conditioning=None): raise NotImplementedError() def add_infotext(self, p): if self.model_wrap_cfg.padded_cond_uncond: p.extra_generation_params["Pad conds"] = True if self.model_wrap_cfg.padded_cond_uncond_v0: p.extra_generation_params["Pad conds v0"] = True
--- +++ @@ -1,345 +1,355 @@-import inspect -from collections import namedtuple -import numpy as np -import torch -from PIL import Image -from modules import devices, images, sd_vae_approx, sd_samplers, sd_vae_taesd, shared, sd_models -from modules.shared import opts, state -import k_diffusion.sampling - - -SamplerDataTuple = namedtuple('SamplerData', ['name', 'constructor', 'aliases', 'options']) - - -class SamplerData(SamplerDataTuple): - def total_steps(self, steps): - if self.options.get("second_order", False): - steps = steps * 2 - - return steps - - -def setup_img2img_steps(p, steps=None): - if opts.img2img_fix_steps or steps is not None: - requested_steps = (steps or p.steps) - steps = int(requested_steps / min(p.denoising_strength, 0.999)) if p.denoising_strength > 0 else 0 - t_enc = requested_steps - 1 - else: - steps = p.steps - t_enc = int(min(p.denoising_strength, 0.999) * steps) - - return steps, t_enc - - -approximation_indexes = {"Full": 0, "Approx NN": 1, "Approx cheap": 2, "TAESD": 3} - - -def samples_to_images_tensor(sample, approximation=None, model=None): - - if approximation is None or (shared.state.interrupted and opts.live_preview_fast_interrupt): - approximation = approximation_indexes.get(opts.show_progress_type, 0) - - from modules import lowvram - if approximation == 0 and lowvram.is_enabled(shared.sd_model) and not shared.opts.live_preview_allow_lowvram_full: - approximation = 1 - - if approximation == 2: - x_sample = sd_vae_approx.cheap_approximation(sample) - elif approximation == 1: - x_sample = sd_vae_approx.model()(sample.to(devices.device, devices.dtype)).detach() - elif approximation == 3: - x_sample = sd_vae_taesd.decoder_model()(sample.to(devices.device, devices.dtype)).detach() - x_sample = x_sample * 2 - 1 - else: - if model is None: - model = shared.sd_model - with torch.no_grad(), devices.without_autocast(): # fixes an issue with unstable VAEs that are flaky even in fp32 - x_sample = model.decode_first_stage(sample.to(model.first_stage_model.dtype)) - - return x_sample - - -def single_sample_to_image(sample, approximation=None): - x_sample = samples_to_images_tensor(sample.unsqueeze(0), approximation)[0] * 0.5 + 0.5 - - x_sample = torch.clamp(x_sample, min=0.0, max=1.0) - x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2) - x_sample = x_sample.astype(np.uint8) - - return Image.fromarray(x_sample) - - -def decode_first_stage(model, x): - x = x.to(devices.dtype_vae) - approx_index = approximation_indexes.get(opts.sd_vae_decode_method, 0) - return samples_to_images_tensor(x, approx_index, model) - - -def sample_to_image(samples, index=0, approximation=None): - return single_sample_to_image(samples[index], approximation) - - -def samples_to_image_grid(samples, approximation=None): - return images.image_grid([single_sample_to_image(sample, approximation) for sample in samples]) - - -def images_tensor_to_samples(image, approximation=None, model=None): - if approximation is None: - approximation = approximation_indexes.get(opts.sd_vae_encode_method, 0) - - if approximation == 3: - image = image.to(devices.device, devices.dtype) - x_latent = sd_vae_taesd.encoder_model()(image) - else: - if model is None: - model = shared.sd_model - model.first_stage_model.to(devices.dtype_vae) - - image = image.to(shared.device, dtype=devices.dtype_vae) - image = image * 2 - 1 - if len(image) > 1: - x_latent = torch.stack([ - model.get_first_stage_encoding( - model.encode_first_stage(torch.unsqueeze(img, 0)) - )[0] - for img in image - ]) - else: - x_latent = model.get_first_stage_encoding(model.encode_first_stage(image)) - - return x_latent - - -def store_latent(decoded): - state.current_latent = decoded - - if opts.live_previews_enable and opts.show_progress_every_n_steps > 0 and shared.state.sampling_step % opts.show_progress_every_n_steps == 0: - if not shared.parallel_processing_allowed: - shared.state.assign_current_image(sample_to_image(decoded)) - - -def is_sampler_using_eta_noise_seed_delta(p): - - sampler_config = sd_samplers.find_sampler_config(p.sampler_name) - - eta = p.eta - - if eta is None and p.sampler is not None: - eta = p.sampler.eta - - if eta is None and sampler_config is not None: - eta = 0 if sampler_config.options.get("default_eta_is_0", False) else 1.0 - - if eta == 0: - return False - - return sampler_config.options.get("uses_ensd", False) - - -class InterruptedException(BaseException): - pass - - -def replace_torchsde_browinan(): - import torchsde._brownian.brownian_interval - - def torchsde_randn(size, dtype, device, seed): - return devices.randn_local(seed, size).to(device=device, dtype=dtype) - - torchsde._brownian.brownian_interval._randn = torchsde_randn - - -replace_torchsde_browinan() - - -def apply_refiner(cfg_denoiser, sigma=None): - if opts.refiner_switch_by_sample_steps or sigma is None: - completed_ratio = cfg_denoiser.step / cfg_denoiser.total_steps - cfg_denoiser.p.extra_generation_params["Refiner switch by sampling steps"] = True - - else: - # torch.max(sigma) only to handle rare case where we might have different sigmas in the same batch - try: - timestep = torch.argmin(torch.abs(cfg_denoiser.inner_model.sigmas.to(sigma.device) - torch.max(sigma))) - except AttributeError: # for samplers that don't use sigmas (DDIM) sigma is actually the timestep - timestep = torch.max(sigma).to(dtype=int) - completed_ratio = (999 - timestep) / 1000 - - refiner_switch_at = cfg_denoiser.p.refiner_switch_at - refiner_checkpoint_info = cfg_denoiser.p.refiner_checkpoint_info - - if refiner_switch_at is not None and completed_ratio < refiner_switch_at: - return False - - if refiner_checkpoint_info is None or shared.sd_model.sd_checkpoint_info == refiner_checkpoint_info: - return False - - if getattr(cfg_denoiser.p, "enable_hr", False): - is_second_pass = cfg_denoiser.p.is_hr_pass - - if opts.hires_fix_refiner_pass == "first pass" and is_second_pass: - return False - - if opts.hires_fix_refiner_pass == "second pass" and not is_second_pass: - return False - - if opts.hires_fix_refiner_pass != "second pass": - cfg_denoiser.p.extra_generation_params['Hires refiner'] = opts.hires_fix_refiner_pass - - cfg_denoiser.p.extra_generation_params['Refiner'] = refiner_checkpoint_info.short_title - cfg_denoiser.p.extra_generation_params['Refiner switch at'] = refiner_switch_at - - with sd_models.SkipWritingToConfig(): - sd_models.reload_model_weights(info=refiner_checkpoint_info) - - devices.torch_gc() - cfg_denoiser.p.setup_conds() - cfg_denoiser.update_inner_model() - - return True - - -class TorchHijack: - - def __init__(self, p): - self.rng = p.rng - - def __getattr__(self, item): - if item == 'randn_like': - return self.randn_like - - if hasattr(torch, item): - return getattr(torch, item) - - raise AttributeError(f"'{type(self).__name__}' object has no attribute '{item}'") - - def randn_like(self, x): - return self.rng.next() - - -class Sampler: - def __init__(self, funcname): - self.funcname = funcname - self.func = funcname - self.extra_params = [] - self.sampler_noises = None - self.stop_at = None - self.eta = None - self.config: SamplerData = None # set by the function calling the constructor - self.last_latent = None - self.s_min_uncond = None - self.s_churn = 0.0 - self.s_tmin = 0.0 - self.s_tmax = float('inf') - self.s_noise = 1.0 - - self.eta_option_field = 'eta_ancestral' - self.eta_infotext_field = 'Eta' - self.eta_default = 1.0 - - self.conditioning_key = getattr(shared.sd_model.model, 'conditioning_key', 'crossattn') - - self.p = None - self.model_wrap_cfg = None - self.sampler_extra_args = None - self.options = {} - - def callback_state(self, d): - step = d['i'] - - if self.stop_at is not None and step > self.stop_at: - raise InterruptedException - - state.sampling_step = step - shared.total_tqdm.update() - - def launch_sampling(self, steps, func): - self.model_wrap_cfg.steps = steps - self.model_wrap_cfg.total_steps = self.config.total_steps(steps) - state.sampling_steps = steps - state.sampling_step = 0 - - try: - return func() - except RecursionError: - print( - 'Encountered RecursionError during sampling, returning last latent. ' - 'rho >5 with a polyexponential scheduler may cause this error. ' - 'You should try to use a smaller rho value instead.' - ) - return self.last_latent - except InterruptedException: - return self.last_latent - - def number_of_needed_noises(self, p): - return p.steps - - def initialize(self, p) -> dict: - self.p = p - self.model_wrap_cfg.p = p - self.model_wrap_cfg.mask = p.mask if hasattr(p, 'mask') else None - self.model_wrap_cfg.nmask = p.nmask if hasattr(p, 'nmask') else None - self.model_wrap_cfg.step = 0 - self.model_wrap_cfg.image_cfg_scale = getattr(p, 'image_cfg_scale', None) - self.eta = p.eta if p.eta is not None else getattr(opts, self.eta_option_field, 0.0) - self.s_min_uncond = getattr(p, 's_min_uncond', 0.0) - - k_diffusion.sampling.torch = TorchHijack(p) - - extra_params_kwargs = {} - for param_name in self.extra_params: - if hasattr(p, param_name) and param_name in inspect.signature(self.func).parameters: - extra_params_kwargs[param_name] = getattr(p, param_name) - - if 'eta' in inspect.signature(self.func).parameters: - if self.eta != self.eta_default: - p.extra_generation_params[self.eta_infotext_field] = self.eta - - extra_params_kwargs['eta'] = self.eta - - if len(self.extra_params) > 0: - s_churn = getattr(opts, 's_churn', p.s_churn) - s_tmin = getattr(opts, 's_tmin', p.s_tmin) - s_tmax = getattr(opts, 's_tmax', p.s_tmax) or self.s_tmax # 0 = inf - s_noise = getattr(opts, 's_noise', p.s_noise) - - if 's_churn' in extra_params_kwargs and s_churn != self.s_churn: - extra_params_kwargs['s_churn'] = s_churn - p.s_churn = s_churn - p.extra_generation_params['Sigma churn'] = s_churn - if 's_tmin' in extra_params_kwargs and s_tmin != self.s_tmin: - extra_params_kwargs['s_tmin'] = s_tmin - p.s_tmin = s_tmin - p.extra_generation_params['Sigma tmin'] = s_tmin - if 's_tmax' in extra_params_kwargs and s_tmax != self.s_tmax: - extra_params_kwargs['s_tmax'] = s_tmax - p.s_tmax = s_tmax - p.extra_generation_params['Sigma tmax'] = s_tmax - if 's_noise' in extra_params_kwargs and s_noise != self.s_noise: - extra_params_kwargs['s_noise'] = s_noise - p.s_noise = s_noise - p.extra_generation_params['Sigma noise'] = s_noise - - return extra_params_kwargs - - def create_noise_sampler(self, x, sigmas, p): - if shared.opts.no_dpmpp_sde_batch_determinism: - return None - - from k_diffusion.sampling import BrownianTreeNoiseSampler - sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max() - current_iter_seeds = p.all_seeds[p.iteration * p.batch_size:(p.iteration + 1) * p.batch_size] - return BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=current_iter_seeds) - - def sample(self, p, x, conditioning, unconditional_conditioning, steps=None, image_conditioning=None): - raise NotImplementedError() - - def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning, steps=None, image_conditioning=None): - raise NotImplementedError() - - def add_infotext(self, p): - if self.model_wrap_cfg.padded_cond_uncond: - p.extra_generation_params["Pad conds"] = True - - if self.model_wrap_cfg.padded_cond_uncond_v0: - p.extra_generation_params["Pad conds v0"] = True+import inspect +from collections import namedtuple +import numpy as np +import torch +from PIL import Image +from modules import devices, images, sd_vae_approx, sd_samplers, sd_vae_taesd, shared, sd_models +from modules.shared import opts, state +import k_diffusion.sampling + + +SamplerDataTuple = namedtuple('SamplerData', ['name', 'constructor', 'aliases', 'options']) + + +class SamplerData(SamplerDataTuple): + def total_steps(self, steps): + if self.options.get("second_order", False): + steps = steps * 2 + + return steps + + +def setup_img2img_steps(p, steps=None): + if opts.img2img_fix_steps or steps is not None: + requested_steps = (steps or p.steps) + steps = int(requested_steps / min(p.denoising_strength, 0.999)) if p.denoising_strength > 0 else 0 + t_enc = requested_steps - 1 + else: + steps = p.steps + t_enc = int(min(p.denoising_strength, 0.999) * steps) + + return steps, t_enc + + +approximation_indexes = {"Full": 0, "Approx NN": 1, "Approx cheap": 2, "TAESD": 3} + + +def samples_to_images_tensor(sample, approximation=None, model=None): + """Transforms 4-channel latent space images into 3-channel RGB image tensors, with values in range [-1, 1].""" + + if approximation is None or (shared.state.interrupted and opts.live_preview_fast_interrupt): + approximation = approximation_indexes.get(opts.show_progress_type, 0) + + from modules import lowvram + if approximation == 0 and lowvram.is_enabled(shared.sd_model) and not shared.opts.live_preview_allow_lowvram_full: + approximation = 1 + + if approximation == 2: + x_sample = sd_vae_approx.cheap_approximation(sample) + elif approximation == 1: + x_sample = sd_vae_approx.model()(sample.to(devices.device, devices.dtype)).detach() + elif approximation == 3: + x_sample = sd_vae_taesd.decoder_model()(sample.to(devices.device, devices.dtype)).detach() + x_sample = x_sample * 2 - 1 + else: + if model is None: + model = shared.sd_model + with torch.no_grad(), devices.without_autocast(): # fixes an issue with unstable VAEs that are flaky even in fp32 + x_sample = model.decode_first_stage(sample.to(model.first_stage_model.dtype)) + + return x_sample + + +def single_sample_to_image(sample, approximation=None): + x_sample = samples_to_images_tensor(sample.unsqueeze(0), approximation)[0] * 0.5 + 0.5 + + x_sample = torch.clamp(x_sample, min=0.0, max=1.0) + x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2) + x_sample = x_sample.astype(np.uint8) + + return Image.fromarray(x_sample) + + +def decode_first_stage(model, x): + x = x.to(devices.dtype_vae) + approx_index = approximation_indexes.get(opts.sd_vae_decode_method, 0) + return samples_to_images_tensor(x, approx_index, model) + + +def sample_to_image(samples, index=0, approximation=None): + return single_sample_to_image(samples[index], approximation) + + +def samples_to_image_grid(samples, approximation=None): + return images.image_grid([single_sample_to_image(sample, approximation) for sample in samples]) + + +def images_tensor_to_samples(image, approximation=None, model=None): + '''image[0, 1] -> latent''' + if approximation is None: + approximation = approximation_indexes.get(opts.sd_vae_encode_method, 0) + + if approximation == 3: + image = image.to(devices.device, devices.dtype) + x_latent = sd_vae_taesd.encoder_model()(image) + else: + if model is None: + model = shared.sd_model + model.first_stage_model.to(devices.dtype_vae) + + image = image.to(shared.device, dtype=devices.dtype_vae) + image = image * 2 - 1 + if len(image) > 1: + x_latent = torch.stack([ + model.get_first_stage_encoding( + model.encode_first_stage(torch.unsqueeze(img, 0)) + )[0] + for img in image + ]) + else: + x_latent = model.get_first_stage_encoding(model.encode_first_stage(image)) + + return x_latent + + +def store_latent(decoded): + state.current_latent = decoded + + if opts.live_previews_enable and opts.show_progress_every_n_steps > 0 and shared.state.sampling_step % opts.show_progress_every_n_steps == 0: + if not shared.parallel_processing_allowed: + shared.state.assign_current_image(sample_to_image(decoded)) + + +def is_sampler_using_eta_noise_seed_delta(p): + """returns whether sampler from config will use eta noise seed delta for image creation""" + + sampler_config = sd_samplers.find_sampler_config(p.sampler_name) + + eta = p.eta + + if eta is None and p.sampler is not None: + eta = p.sampler.eta + + if eta is None and sampler_config is not None: + eta = 0 if sampler_config.options.get("default_eta_is_0", False) else 1.0 + + if eta == 0: + return False + + return sampler_config.options.get("uses_ensd", False) + + +class InterruptedException(BaseException): + pass + + +def replace_torchsde_browinan(): + import torchsde._brownian.brownian_interval + + def torchsde_randn(size, dtype, device, seed): + return devices.randn_local(seed, size).to(device=device, dtype=dtype) + + torchsde._brownian.brownian_interval._randn = torchsde_randn + + +replace_torchsde_browinan() + + +def apply_refiner(cfg_denoiser, sigma=None): + if opts.refiner_switch_by_sample_steps or sigma is None: + completed_ratio = cfg_denoiser.step / cfg_denoiser.total_steps + cfg_denoiser.p.extra_generation_params["Refiner switch by sampling steps"] = True + + else: + # torch.max(sigma) only to handle rare case where we might have different sigmas in the same batch + try: + timestep = torch.argmin(torch.abs(cfg_denoiser.inner_model.sigmas.to(sigma.device) - torch.max(sigma))) + except AttributeError: # for samplers that don't use sigmas (DDIM) sigma is actually the timestep + timestep = torch.max(sigma).to(dtype=int) + completed_ratio = (999 - timestep) / 1000 + + refiner_switch_at = cfg_denoiser.p.refiner_switch_at + refiner_checkpoint_info = cfg_denoiser.p.refiner_checkpoint_info + + if refiner_switch_at is not None and completed_ratio < refiner_switch_at: + return False + + if refiner_checkpoint_info is None or shared.sd_model.sd_checkpoint_info == refiner_checkpoint_info: + return False + + if getattr(cfg_denoiser.p, "enable_hr", False): + is_second_pass = cfg_denoiser.p.is_hr_pass + + if opts.hires_fix_refiner_pass == "first pass" and is_second_pass: + return False + + if opts.hires_fix_refiner_pass == "second pass" and not is_second_pass: + return False + + if opts.hires_fix_refiner_pass != "second pass": + cfg_denoiser.p.extra_generation_params['Hires refiner'] = opts.hires_fix_refiner_pass + + cfg_denoiser.p.extra_generation_params['Refiner'] = refiner_checkpoint_info.short_title + cfg_denoiser.p.extra_generation_params['Refiner switch at'] = refiner_switch_at + + with sd_models.SkipWritingToConfig(): + sd_models.reload_model_weights(info=refiner_checkpoint_info) + + devices.torch_gc() + cfg_denoiser.p.setup_conds() + cfg_denoiser.update_inner_model() + + return True + + +class TorchHijack: + """This is here to replace torch.randn_like of k-diffusion. + + k-diffusion has random_sampler argument for most samplers, but not for all, so + this is needed to properly replace every use of torch.randn_like. + + We need to replace to make images generated in batches to be same as images generated individually.""" + + def __init__(self, p): + self.rng = p.rng + + def __getattr__(self, item): + if item == 'randn_like': + return self.randn_like + + if hasattr(torch, item): + return getattr(torch, item) + + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{item}'") + + def randn_like(self, x): + return self.rng.next() + + +class Sampler: + def __init__(self, funcname): + self.funcname = funcname + self.func = funcname + self.extra_params = [] + self.sampler_noises = None + self.stop_at = None + self.eta = None + self.config: SamplerData = None # set by the function calling the constructor + self.last_latent = None + self.s_min_uncond = None + self.s_churn = 0.0 + self.s_tmin = 0.0 + self.s_tmax = float('inf') + self.s_noise = 1.0 + + self.eta_option_field = 'eta_ancestral' + self.eta_infotext_field = 'Eta' + self.eta_default = 1.0 + + self.conditioning_key = getattr(shared.sd_model.model, 'conditioning_key', 'crossattn') + + self.p = None + self.model_wrap_cfg = None + self.sampler_extra_args = None + self.options = {} + + def callback_state(self, d): + step = d['i'] + + if self.stop_at is not None and step > self.stop_at: + raise InterruptedException + + state.sampling_step = step + shared.total_tqdm.update() + + def launch_sampling(self, steps, func): + self.model_wrap_cfg.steps = steps + self.model_wrap_cfg.total_steps = self.config.total_steps(steps) + state.sampling_steps = steps + state.sampling_step = 0 + + try: + return func() + except RecursionError: + print( + 'Encountered RecursionError during sampling, returning last latent. ' + 'rho >5 with a polyexponential scheduler may cause this error. ' + 'You should try to use a smaller rho value instead.' + ) + return self.last_latent + except InterruptedException: + return self.last_latent + + def number_of_needed_noises(self, p): + return p.steps + + def initialize(self, p) -> dict: + self.p = p + self.model_wrap_cfg.p = p + self.model_wrap_cfg.mask = p.mask if hasattr(p, 'mask') else None + self.model_wrap_cfg.nmask = p.nmask if hasattr(p, 'nmask') else None + self.model_wrap_cfg.step = 0 + self.model_wrap_cfg.image_cfg_scale = getattr(p, 'image_cfg_scale', None) + self.eta = p.eta if p.eta is not None else getattr(opts, self.eta_option_field, 0.0) + self.s_min_uncond = getattr(p, 's_min_uncond', 0.0) + + k_diffusion.sampling.torch = TorchHijack(p) + + extra_params_kwargs = {} + for param_name in self.extra_params: + if hasattr(p, param_name) and param_name in inspect.signature(self.func).parameters: + extra_params_kwargs[param_name] = getattr(p, param_name) + + if 'eta' in inspect.signature(self.func).parameters: + if self.eta != self.eta_default: + p.extra_generation_params[self.eta_infotext_field] = self.eta + + extra_params_kwargs['eta'] = self.eta + + if len(self.extra_params) > 0: + s_churn = getattr(opts, 's_churn', p.s_churn) + s_tmin = getattr(opts, 's_tmin', p.s_tmin) + s_tmax = getattr(opts, 's_tmax', p.s_tmax) or self.s_tmax # 0 = inf + s_noise = getattr(opts, 's_noise', p.s_noise) + + if 's_churn' in extra_params_kwargs and s_churn != self.s_churn: + extra_params_kwargs['s_churn'] = s_churn + p.s_churn = s_churn + p.extra_generation_params['Sigma churn'] = s_churn + if 's_tmin' in extra_params_kwargs and s_tmin != self.s_tmin: + extra_params_kwargs['s_tmin'] = s_tmin + p.s_tmin = s_tmin + p.extra_generation_params['Sigma tmin'] = s_tmin + if 's_tmax' in extra_params_kwargs and s_tmax != self.s_tmax: + extra_params_kwargs['s_tmax'] = s_tmax + p.s_tmax = s_tmax + p.extra_generation_params['Sigma tmax'] = s_tmax + if 's_noise' in extra_params_kwargs and s_noise != self.s_noise: + extra_params_kwargs['s_noise'] = s_noise + p.s_noise = s_noise + p.extra_generation_params['Sigma noise'] = s_noise + + return extra_params_kwargs + + def create_noise_sampler(self, x, sigmas, p): + """For DPM++ SDE: manually create noise sampler to enable deterministic results across different batch sizes""" + if shared.opts.no_dpmpp_sde_batch_determinism: + return None + + from k_diffusion.sampling import BrownianTreeNoiseSampler + sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max() + current_iter_seeds = p.all_seeds[p.iteration * p.batch_size:(p.iteration + 1) * p.batch_size] + return BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=current_iter_seeds) + + def sample(self, p, x, conditioning, unconditional_conditioning, steps=None, image_conditioning=None): + raise NotImplementedError() + + def sample_img2img(self, p, x, noise, conditioning, unconditional_conditioning, steps=None, image_conditioning=None): + raise NotImplementedError() + + def add_infotext(self, p): + if self.model_wrap_cfg.padded_cond_uncond: + p.extra_generation_params["Pad conds"] = True + + if self.model_wrap_cfg.padded_cond_uncond_v0: + p.extra_generation_params["Pad conds v0"] = True
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_samplers_common.py
Add docstrings that explain logic
import csv import dataclasses import json import html import os from contextlib import nullcontext import gradio as gr from modules import call_queue, shared, ui_tempdir, util from modules.infotext_utils import image_from_url_text import modules.images from modules.ui_components import ToolButton import modules.infotext_utils as parameters_copypaste folder_symbol = '\U0001f4c2' # 📂 refresh_symbol = '\U0001f504' # 🔄 def update_generation_info(generation_info, html_info, img_index): try: generation_info = json.loads(generation_info) if img_index < 0 or img_index >= len(generation_info["infotexts"]): return html_info, gr.update() return plaintext_to_html(generation_info["infotexts"][img_index]), gr.update() except Exception: pass # if the json parse or anything else fails, just return the old html_info return html_info, gr.update() def plaintext_to_html(text, classname=None): content = "<br>\n".join(html.escape(x) for x in text.split('\n')) return f"<p class='{classname}'>{content}</p>" if classname else f"<p>{content}</p>" def update_logfile(logfile_path, fields): with open(logfile_path, "r", encoding="utf8", newline="") as file: reader = csv.reader(file) rows = list(reader) # blank file: leave it as is if not rows: return # file is already synced, do nothing if len(rows[0]) == len(fields): return rows[0] = fields # append new fields to each row as empty values for row in rows[1:]: while len(row) < len(fields): row.append("") with open(logfile_path, "w", encoding="utf8", newline="") as file: writer = csv.writer(file) writer.writerows(rows) def save_files(js_data, images, do_make_zip, index): filenames = [] fullfns = [] parsed_infotexts = [] # quick dictionary to class object conversion. Its necessary due apply_filename_pattern requiring it class MyObject: def __init__(self, d=None): if d is not None: for key, value in d.items(): setattr(self, key, value) data = json.loads(js_data) p = MyObject(data) path = shared.opts.outdir_save save_to_dirs = shared.opts.use_save_to_dirs_for_ui extension: str = shared.opts.samples_format start_index = 0 if index > -1 and shared.opts.save_selected_only and (index >= data["index_of_first_image"]): # ensures we are looking at a specific non-grid picture, and we have save_selected_only images = [images[index]] start_index = index os.makedirs(shared.opts.outdir_save, exist_ok=True) fields = [ "prompt", "seed", "width", "height", "sampler", "cfgs", "steps", "filename", "negative_prompt", "sd_model_name", "sd_model_hash", ] logfile_path = os.path.join(shared.opts.outdir_save, "log.csv") # NOTE: ensure csv integrity when fields are added by # updating headers and padding with delimiters where needed if shared.opts.save_write_log_csv and os.path.exists(logfile_path): update_logfile(logfile_path, fields) with (open(logfile_path, "a", encoding="utf8", newline='') if shared.opts.save_write_log_csv else nullcontext()) as file: if file: at_start = file.tell() == 0 writer = csv.writer(file) if at_start: writer.writerow(fields) for image_index, filedata in enumerate(images, start_index): image = image_from_url_text(filedata) is_grid = image_index < p.index_of_first_image p.batch_index = image_index-1 parameters = parameters_copypaste.parse_generation_parameters(data["infotexts"][image_index], []) parsed_infotexts.append(parameters) fullfn, txt_fullfn = modules.images.save_image(image, path, "", seed=parameters['Seed'], prompt=parameters['Prompt'], extension=extension, info=p.infotexts[image_index], grid=is_grid, p=p, save_to_dirs=save_to_dirs) filename = os.path.relpath(fullfn, path) filenames.append(filename) fullfns.append(fullfn) if txt_fullfn: filenames.append(os.path.basename(txt_fullfn)) fullfns.append(txt_fullfn) if file: writer.writerow([parsed_infotexts[0]['Prompt'], parsed_infotexts[0]['Seed'], data["width"], data["height"], data["sampler_name"], data["cfg_scale"], data["steps"], filenames[0], parsed_infotexts[0]['Negative prompt'], data["sd_model_name"], data["sd_model_hash"]]) # Make Zip if do_make_zip: p.all_seeds = [parameters['Seed'] for parameters in parsed_infotexts] namegen = modules.images.FilenameGenerator(p, parsed_infotexts[0]['Seed'], parsed_infotexts[0]['Prompt'], image, True) zip_filename = namegen.apply(shared.opts.grid_zip_filename_pattern or "[datetime]_[[model_name]]_[seed]-[seed_last]") zip_filepath = os.path.join(path, f"{zip_filename}.zip") from zipfile import ZipFile with ZipFile(zip_filepath, "w") as zip_file: for i in range(len(fullfns)): with open(fullfns[i], mode="rb") as f: zip_file.writestr(filenames[i], f.read()) fullfns.insert(0, zip_filepath) return gr.File.update(value=fullfns, visible=True), plaintext_to_html(f"Saved: {filenames[0]}") @dataclasses.dataclass class OutputPanel: gallery = None generation_info = None infotext = None html_log = None button_upscale = None def create_output_panel(tabname, outdir, toprow=None): res = OutputPanel() def open_folder(f, images=None, index=None): if shared.cmd_opts.hide_ui_dir_config: return try: if 'Sub' in shared.opts.open_dir_button_choice: image_dir = os.path.split(images[index]["name"].rsplit('?', 1)[0])[0] if 'temp' in shared.opts.open_dir_button_choice or not ui_tempdir.is_gradio_temp_path(image_dir): f = image_dir except Exception: pass util.open_folder(f) with gr.Column(elem_id=f"{tabname}_results"): if toprow: toprow.create_inline_toprow_image() with gr.Column(variant='panel', elem_id=f"{tabname}_results_panel"): with gr.Group(elem_id=f"{tabname}_gallery_container"): res.gallery = gr.Gallery(label='Output', show_label=False, elem_id=f"{tabname}_gallery", columns=4, preview=True, height=shared.opts.gallery_height or None) with gr.Row(elem_id=f"image_buttons_{tabname}", elem_classes="image-buttons"): open_folder_button = ToolButton(folder_symbol, elem_id=f'{tabname}_open_folder', visible=not shared.cmd_opts.hide_ui_dir_config, tooltip="Open images output directory.") if tabname != "extras": save = ToolButton('💾', elem_id=f'save_{tabname}', tooltip=f"Save the image to a dedicated directory ({shared.opts.outdir_save}).") save_zip = ToolButton('🗃️', elem_id=f'save_zip_{tabname}', tooltip=f"Save zip archive with images to a dedicated directory ({shared.opts.outdir_save})") buttons = { 'img2img': ToolButton('🖼️', elem_id=f'{tabname}_send_to_img2img', tooltip="Send image and generation parameters to img2img tab."), 'inpaint': ToolButton('🎨️', elem_id=f'{tabname}_send_to_inpaint', tooltip="Send image and generation parameters to img2img inpaint tab."), 'extras': ToolButton('📐', elem_id=f'{tabname}_send_to_extras', tooltip="Send image and generation parameters to extras tab.") } if tabname == 'txt2img': res.button_upscale = ToolButton('✨', elem_id=f'{tabname}_upscale', tooltip="Create an upscaled version of the current image using hires fix settings.") open_folder_button.click( fn=lambda images, index: open_folder(shared.opts.outdir_samples or outdir, images, index), _js="(y, w) => [y, selected_gallery_index()]", inputs=[ res.gallery, open_folder_button, # placeholder for index ], outputs=[], ) if tabname != "extras": download_files = gr.File(None, file_count="multiple", interactive=False, show_label=False, visible=False, elem_id=f'download_files_{tabname}') with gr.Group(): res.infotext = gr.HTML(elem_id=f'html_info_{tabname}', elem_classes="infotext") res.html_log = gr.HTML(elem_id=f'html_log_{tabname}', elem_classes="html-log") res.generation_info = gr.Textbox(visible=False, elem_id=f'generation_info_{tabname}') if tabname == 'txt2img' or tabname == 'img2img': generation_info_button = gr.Button(visible=False, elem_id=f"{tabname}_generation_info_button") generation_info_button.click( fn=update_generation_info, _js="function(x, y, z){ return [x, y, selected_gallery_index()] }", inputs=[res.generation_info, res.infotext, res.infotext], outputs=[res.infotext, res.infotext], show_progress=False, ) save.click( fn=call_queue.wrap_gradio_call_no_job(save_files), _js="(x, y, z, w) => [x, y, false, selected_gallery_index()]", inputs=[ res.generation_info, res.gallery, res.infotext, res.infotext, ], outputs=[ download_files, res.html_log, ], show_progress=False, ) save_zip.click( fn=call_queue.wrap_gradio_call_no_job(save_files), _js="(x, y, z, w) => [x, y, true, selected_gallery_index()]", inputs=[ res.generation_info, res.gallery, res.infotext, res.infotext, ], outputs=[ download_files, res.html_log, ] ) else: res.generation_info = gr.HTML(elem_id=f'html_info_x_{tabname}') res.infotext = gr.HTML(elem_id=f'html_info_{tabname}', elem_classes="infotext") res.html_log = gr.HTML(elem_id=f'html_log_{tabname}') paste_field_names = [] if tabname == "txt2img": paste_field_names = modules.scripts.scripts_txt2img.paste_field_names elif tabname == "img2img": paste_field_names = modules.scripts.scripts_img2img.paste_field_names for paste_tabname, paste_button in buttons.items(): parameters_copypaste.register_paste_params_button(parameters_copypaste.ParamBinding( paste_button=paste_button, tabname=paste_tabname, source_tabname="txt2img" if tabname == "txt2img" else None, source_image_component=res.gallery, paste_field_names=paste_field_names )) return res def create_refresh_button(refresh_component, refresh_method, refreshed_args, elem_id): refresh_components = refresh_component if isinstance(refresh_component, list) else [refresh_component] label = None for comp in refresh_components: label = getattr(comp, 'label', None) if label is not None: break def refresh(): refresh_method() args = refreshed_args() if callable(refreshed_args) else refreshed_args for k, v in args.items(): for comp in refresh_components: setattr(comp, k, v) return [gr.update(**(args or {})) for _ in refresh_components] if len(refresh_components) > 1 else gr.update(**(args or {})) refresh_button = ToolButton(value=refresh_symbol, elem_id=elem_id, tooltip=f"{label}: refresh" if label else "Refresh") refresh_button.click( fn=refresh, inputs=[], outputs=refresh_components ) return refresh_button def setup_dialog(button_show, dialog, *, button_close=None): dialog.visible = False button_show.click( fn=lambda: gr.update(visible=True), inputs=[], outputs=[dialog], ).then(fn=None, _js="function(){ popupId('" + dialog.elem_id + "'); }") if button_close: button_close.click(fn=None, _js="closePopup")
--- +++ @@ -1,322 +1,325 @@-import csv -import dataclasses -import json -import html -import os -from contextlib import nullcontext - -import gradio as gr - -from modules import call_queue, shared, ui_tempdir, util -from modules.infotext_utils import image_from_url_text -import modules.images -from modules.ui_components import ToolButton -import modules.infotext_utils as parameters_copypaste - -folder_symbol = '\U0001f4c2' # 📂 -refresh_symbol = '\U0001f504' # 🔄 - - -def update_generation_info(generation_info, html_info, img_index): - try: - generation_info = json.loads(generation_info) - if img_index < 0 or img_index >= len(generation_info["infotexts"]): - return html_info, gr.update() - return plaintext_to_html(generation_info["infotexts"][img_index]), gr.update() - except Exception: - pass - # if the json parse or anything else fails, just return the old html_info - return html_info, gr.update() - - -def plaintext_to_html(text, classname=None): - content = "<br>\n".join(html.escape(x) for x in text.split('\n')) - - return f"<p class='{classname}'>{content}</p>" if classname else f"<p>{content}</p>" - - -def update_logfile(logfile_path, fields): - with open(logfile_path, "r", encoding="utf8", newline="") as file: - reader = csv.reader(file) - rows = list(reader) - - # blank file: leave it as is - if not rows: - return - - # file is already synced, do nothing - if len(rows[0]) == len(fields): - return - - rows[0] = fields - - # append new fields to each row as empty values - for row in rows[1:]: - while len(row) < len(fields): - row.append("") - - with open(logfile_path, "w", encoding="utf8", newline="") as file: - writer = csv.writer(file) - writer.writerows(rows) - - -def save_files(js_data, images, do_make_zip, index): - filenames = [] - fullfns = [] - parsed_infotexts = [] - - # quick dictionary to class object conversion. Its necessary due apply_filename_pattern requiring it - class MyObject: - def __init__(self, d=None): - if d is not None: - for key, value in d.items(): - setattr(self, key, value) - - data = json.loads(js_data) - p = MyObject(data) - - path = shared.opts.outdir_save - save_to_dirs = shared.opts.use_save_to_dirs_for_ui - extension: str = shared.opts.samples_format - start_index = 0 - - if index > -1 and shared.opts.save_selected_only and (index >= data["index_of_first_image"]): # ensures we are looking at a specific non-grid picture, and we have save_selected_only - images = [images[index]] - start_index = index - - os.makedirs(shared.opts.outdir_save, exist_ok=True) - - fields = [ - "prompt", - "seed", - "width", - "height", - "sampler", - "cfgs", - "steps", - "filename", - "negative_prompt", - "sd_model_name", - "sd_model_hash", - ] - logfile_path = os.path.join(shared.opts.outdir_save, "log.csv") - - # NOTE: ensure csv integrity when fields are added by - # updating headers and padding with delimiters where needed - if shared.opts.save_write_log_csv and os.path.exists(logfile_path): - update_logfile(logfile_path, fields) - - with (open(logfile_path, "a", encoding="utf8", newline='') if shared.opts.save_write_log_csv else nullcontext()) as file: - if file: - at_start = file.tell() == 0 - writer = csv.writer(file) - if at_start: - writer.writerow(fields) - - for image_index, filedata in enumerate(images, start_index): - image = image_from_url_text(filedata) - - is_grid = image_index < p.index_of_first_image - - p.batch_index = image_index-1 - - parameters = parameters_copypaste.parse_generation_parameters(data["infotexts"][image_index], []) - parsed_infotexts.append(parameters) - fullfn, txt_fullfn = modules.images.save_image(image, path, "", seed=parameters['Seed'], prompt=parameters['Prompt'], extension=extension, info=p.infotexts[image_index], grid=is_grid, p=p, save_to_dirs=save_to_dirs) - - filename = os.path.relpath(fullfn, path) - filenames.append(filename) - fullfns.append(fullfn) - if txt_fullfn: - filenames.append(os.path.basename(txt_fullfn)) - fullfns.append(txt_fullfn) - - if file: - writer.writerow([parsed_infotexts[0]['Prompt'], parsed_infotexts[0]['Seed'], data["width"], data["height"], data["sampler_name"], data["cfg_scale"], data["steps"], filenames[0], parsed_infotexts[0]['Negative prompt'], data["sd_model_name"], data["sd_model_hash"]]) - - # Make Zip - if do_make_zip: - p.all_seeds = [parameters['Seed'] for parameters in parsed_infotexts] - namegen = modules.images.FilenameGenerator(p, parsed_infotexts[0]['Seed'], parsed_infotexts[0]['Prompt'], image, True) - zip_filename = namegen.apply(shared.opts.grid_zip_filename_pattern or "[datetime]_[[model_name]]_[seed]-[seed_last]") - zip_filepath = os.path.join(path, f"{zip_filename}.zip") - - from zipfile import ZipFile - with ZipFile(zip_filepath, "w") as zip_file: - for i in range(len(fullfns)): - with open(fullfns[i], mode="rb") as f: - zip_file.writestr(filenames[i], f.read()) - fullfns.insert(0, zip_filepath) - - return gr.File.update(value=fullfns, visible=True), plaintext_to_html(f"Saved: {filenames[0]}") - - -@dataclasses.dataclass -class OutputPanel: - gallery = None - generation_info = None - infotext = None - html_log = None - button_upscale = None - - -def create_output_panel(tabname, outdir, toprow=None): - res = OutputPanel() - - def open_folder(f, images=None, index=None): - if shared.cmd_opts.hide_ui_dir_config: - return - - try: - if 'Sub' in shared.opts.open_dir_button_choice: - image_dir = os.path.split(images[index]["name"].rsplit('?', 1)[0])[0] - if 'temp' in shared.opts.open_dir_button_choice or not ui_tempdir.is_gradio_temp_path(image_dir): - f = image_dir - except Exception: - pass - - util.open_folder(f) - - with gr.Column(elem_id=f"{tabname}_results"): - if toprow: - toprow.create_inline_toprow_image() - - with gr.Column(variant='panel', elem_id=f"{tabname}_results_panel"): - with gr.Group(elem_id=f"{tabname}_gallery_container"): - res.gallery = gr.Gallery(label='Output', show_label=False, elem_id=f"{tabname}_gallery", columns=4, preview=True, height=shared.opts.gallery_height or None) - - with gr.Row(elem_id=f"image_buttons_{tabname}", elem_classes="image-buttons"): - open_folder_button = ToolButton(folder_symbol, elem_id=f'{tabname}_open_folder', visible=not shared.cmd_opts.hide_ui_dir_config, tooltip="Open images output directory.") - - if tabname != "extras": - save = ToolButton('💾', elem_id=f'save_{tabname}', tooltip=f"Save the image to a dedicated directory ({shared.opts.outdir_save}).") - save_zip = ToolButton('🗃️', elem_id=f'save_zip_{tabname}', tooltip=f"Save zip archive with images to a dedicated directory ({shared.opts.outdir_save})") - - buttons = { - 'img2img': ToolButton('🖼️', elem_id=f'{tabname}_send_to_img2img', tooltip="Send image and generation parameters to img2img tab."), - 'inpaint': ToolButton('🎨️', elem_id=f'{tabname}_send_to_inpaint', tooltip="Send image and generation parameters to img2img inpaint tab."), - 'extras': ToolButton('📐', elem_id=f'{tabname}_send_to_extras', tooltip="Send image and generation parameters to extras tab.") - } - - if tabname == 'txt2img': - res.button_upscale = ToolButton('✨', elem_id=f'{tabname}_upscale', tooltip="Create an upscaled version of the current image using hires fix settings.") - - open_folder_button.click( - fn=lambda images, index: open_folder(shared.opts.outdir_samples or outdir, images, index), - _js="(y, w) => [y, selected_gallery_index()]", - inputs=[ - res.gallery, - open_folder_button, # placeholder for index - ], - outputs=[], - ) - - if tabname != "extras": - download_files = gr.File(None, file_count="multiple", interactive=False, show_label=False, visible=False, elem_id=f'download_files_{tabname}') - - with gr.Group(): - res.infotext = gr.HTML(elem_id=f'html_info_{tabname}', elem_classes="infotext") - res.html_log = gr.HTML(elem_id=f'html_log_{tabname}', elem_classes="html-log") - - res.generation_info = gr.Textbox(visible=False, elem_id=f'generation_info_{tabname}') - if tabname == 'txt2img' or tabname == 'img2img': - generation_info_button = gr.Button(visible=False, elem_id=f"{tabname}_generation_info_button") - generation_info_button.click( - fn=update_generation_info, - _js="function(x, y, z){ return [x, y, selected_gallery_index()] }", - inputs=[res.generation_info, res.infotext, res.infotext], - outputs=[res.infotext, res.infotext], - show_progress=False, - ) - - save.click( - fn=call_queue.wrap_gradio_call_no_job(save_files), - _js="(x, y, z, w) => [x, y, false, selected_gallery_index()]", - inputs=[ - res.generation_info, - res.gallery, - res.infotext, - res.infotext, - ], - outputs=[ - download_files, - res.html_log, - ], - show_progress=False, - ) - - save_zip.click( - fn=call_queue.wrap_gradio_call_no_job(save_files), - _js="(x, y, z, w) => [x, y, true, selected_gallery_index()]", - inputs=[ - res.generation_info, - res.gallery, - res.infotext, - res.infotext, - ], - outputs=[ - download_files, - res.html_log, - ] - ) - - else: - res.generation_info = gr.HTML(elem_id=f'html_info_x_{tabname}') - res.infotext = gr.HTML(elem_id=f'html_info_{tabname}', elem_classes="infotext") - res.html_log = gr.HTML(elem_id=f'html_log_{tabname}') - - paste_field_names = [] - if tabname == "txt2img": - paste_field_names = modules.scripts.scripts_txt2img.paste_field_names - elif tabname == "img2img": - paste_field_names = modules.scripts.scripts_img2img.paste_field_names - - for paste_tabname, paste_button in buttons.items(): - parameters_copypaste.register_paste_params_button(parameters_copypaste.ParamBinding( - paste_button=paste_button, tabname=paste_tabname, source_tabname="txt2img" if tabname == "txt2img" else None, source_image_component=res.gallery, - paste_field_names=paste_field_names - )) - - return res - - -def create_refresh_button(refresh_component, refresh_method, refreshed_args, elem_id): - refresh_components = refresh_component if isinstance(refresh_component, list) else [refresh_component] - - label = None - for comp in refresh_components: - label = getattr(comp, 'label', None) - if label is not None: - break - - def refresh(): - refresh_method() - args = refreshed_args() if callable(refreshed_args) else refreshed_args - - for k, v in args.items(): - for comp in refresh_components: - setattr(comp, k, v) - - return [gr.update(**(args or {})) for _ in refresh_components] if len(refresh_components) > 1 else gr.update(**(args or {})) - - refresh_button = ToolButton(value=refresh_symbol, elem_id=elem_id, tooltip=f"{label}: refresh" if label else "Refresh") - refresh_button.click( - fn=refresh, - inputs=[], - outputs=refresh_components - ) - return refresh_button - - -def setup_dialog(button_show, dialog, *, button_close=None): - - dialog.visible = False - - button_show.click( - fn=lambda: gr.update(visible=True), - inputs=[], - outputs=[dialog], - ).then(fn=None, _js="function(){ popupId('" + dialog.elem_id + "'); }") - - if button_close: - button_close.click(fn=None, _js="closePopup") +import csv +import dataclasses +import json +import html +import os +from contextlib import nullcontext + +import gradio as gr + +from modules import call_queue, shared, ui_tempdir, util +from modules.infotext_utils import image_from_url_text +import modules.images +from modules.ui_components import ToolButton +import modules.infotext_utils as parameters_copypaste + +folder_symbol = '\U0001f4c2' # 📂 +refresh_symbol = '\U0001f504' # 🔄 + + +def update_generation_info(generation_info, html_info, img_index): + try: + generation_info = json.loads(generation_info) + if img_index < 0 or img_index >= len(generation_info["infotexts"]): + return html_info, gr.update() + return plaintext_to_html(generation_info["infotexts"][img_index]), gr.update() + except Exception: + pass + # if the json parse or anything else fails, just return the old html_info + return html_info, gr.update() + + +def plaintext_to_html(text, classname=None): + content = "<br>\n".join(html.escape(x) for x in text.split('\n')) + + return f"<p class='{classname}'>{content}</p>" if classname else f"<p>{content}</p>" + + +def update_logfile(logfile_path, fields): + """Update a logfile from old format to new format to maintain CSV integrity.""" + with open(logfile_path, "r", encoding="utf8", newline="") as file: + reader = csv.reader(file) + rows = list(reader) + + # blank file: leave it as is + if not rows: + return + + # file is already synced, do nothing + if len(rows[0]) == len(fields): + return + + rows[0] = fields + + # append new fields to each row as empty values + for row in rows[1:]: + while len(row) < len(fields): + row.append("") + + with open(logfile_path, "w", encoding="utf8", newline="") as file: + writer = csv.writer(file) + writer.writerows(rows) + + +def save_files(js_data, images, do_make_zip, index): + filenames = [] + fullfns = [] + parsed_infotexts = [] + + # quick dictionary to class object conversion. Its necessary due apply_filename_pattern requiring it + class MyObject: + def __init__(self, d=None): + if d is not None: + for key, value in d.items(): + setattr(self, key, value) + + data = json.loads(js_data) + p = MyObject(data) + + path = shared.opts.outdir_save + save_to_dirs = shared.opts.use_save_to_dirs_for_ui + extension: str = shared.opts.samples_format + start_index = 0 + + if index > -1 and shared.opts.save_selected_only and (index >= data["index_of_first_image"]): # ensures we are looking at a specific non-grid picture, and we have save_selected_only + images = [images[index]] + start_index = index + + os.makedirs(shared.opts.outdir_save, exist_ok=True) + + fields = [ + "prompt", + "seed", + "width", + "height", + "sampler", + "cfgs", + "steps", + "filename", + "negative_prompt", + "sd_model_name", + "sd_model_hash", + ] + logfile_path = os.path.join(shared.opts.outdir_save, "log.csv") + + # NOTE: ensure csv integrity when fields are added by + # updating headers and padding with delimiters where needed + if shared.opts.save_write_log_csv and os.path.exists(logfile_path): + update_logfile(logfile_path, fields) + + with (open(logfile_path, "a", encoding="utf8", newline='') if shared.opts.save_write_log_csv else nullcontext()) as file: + if file: + at_start = file.tell() == 0 + writer = csv.writer(file) + if at_start: + writer.writerow(fields) + + for image_index, filedata in enumerate(images, start_index): + image = image_from_url_text(filedata) + + is_grid = image_index < p.index_of_first_image + + p.batch_index = image_index-1 + + parameters = parameters_copypaste.parse_generation_parameters(data["infotexts"][image_index], []) + parsed_infotexts.append(parameters) + fullfn, txt_fullfn = modules.images.save_image(image, path, "", seed=parameters['Seed'], prompt=parameters['Prompt'], extension=extension, info=p.infotexts[image_index], grid=is_grid, p=p, save_to_dirs=save_to_dirs) + + filename = os.path.relpath(fullfn, path) + filenames.append(filename) + fullfns.append(fullfn) + if txt_fullfn: + filenames.append(os.path.basename(txt_fullfn)) + fullfns.append(txt_fullfn) + + if file: + writer.writerow([parsed_infotexts[0]['Prompt'], parsed_infotexts[0]['Seed'], data["width"], data["height"], data["sampler_name"], data["cfg_scale"], data["steps"], filenames[0], parsed_infotexts[0]['Negative prompt'], data["sd_model_name"], data["sd_model_hash"]]) + + # Make Zip + if do_make_zip: + p.all_seeds = [parameters['Seed'] for parameters in parsed_infotexts] + namegen = modules.images.FilenameGenerator(p, parsed_infotexts[0]['Seed'], parsed_infotexts[0]['Prompt'], image, True) + zip_filename = namegen.apply(shared.opts.grid_zip_filename_pattern or "[datetime]_[[model_name]]_[seed]-[seed_last]") + zip_filepath = os.path.join(path, f"{zip_filename}.zip") + + from zipfile import ZipFile + with ZipFile(zip_filepath, "w") as zip_file: + for i in range(len(fullfns)): + with open(fullfns[i], mode="rb") as f: + zip_file.writestr(filenames[i], f.read()) + fullfns.insert(0, zip_filepath) + + return gr.File.update(value=fullfns, visible=True), plaintext_to_html(f"Saved: {filenames[0]}") + + +@dataclasses.dataclass +class OutputPanel: + gallery = None + generation_info = None + infotext = None + html_log = None + button_upscale = None + + +def create_output_panel(tabname, outdir, toprow=None): + res = OutputPanel() + + def open_folder(f, images=None, index=None): + if shared.cmd_opts.hide_ui_dir_config: + return + + try: + if 'Sub' in shared.opts.open_dir_button_choice: + image_dir = os.path.split(images[index]["name"].rsplit('?', 1)[0])[0] + if 'temp' in shared.opts.open_dir_button_choice or not ui_tempdir.is_gradio_temp_path(image_dir): + f = image_dir + except Exception: + pass + + util.open_folder(f) + + with gr.Column(elem_id=f"{tabname}_results"): + if toprow: + toprow.create_inline_toprow_image() + + with gr.Column(variant='panel', elem_id=f"{tabname}_results_panel"): + with gr.Group(elem_id=f"{tabname}_gallery_container"): + res.gallery = gr.Gallery(label='Output', show_label=False, elem_id=f"{tabname}_gallery", columns=4, preview=True, height=shared.opts.gallery_height or None) + + with gr.Row(elem_id=f"image_buttons_{tabname}", elem_classes="image-buttons"): + open_folder_button = ToolButton(folder_symbol, elem_id=f'{tabname}_open_folder', visible=not shared.cmd_opts.hide_ui_dir_config, tooltip="Open images output directory.") + + if tabname != "extras": + save = ToolButton('💾', elem_id=f'save_{tabname}', tooltip=f"Save the image to a dedicated directory ({shared.opts.outdir_save}).") + save_zip = ToolButton('🗃️', elem_id=f'save_zip_{tabname}', tooltip=f"Save zip archive with images to a dedicated directory ({shared.opts.outdir_save})") + + buttons = { + 'img2img': ToolButton('🖼️', elem_id=f'{tabname}_send_to_img2img', tooltip="Send image and generation parameters to img2img tab."), + 'inpaint': ToolButton('🎨️', elem_id=f'{tabname}_send_to_inpaint', tooltip="Send image and generation parameters to img2img inpaint tab."), + 'extras': ToolButton('📐', elem_id=f'{tabname}_send_to_extras', tooltip="Send image and generation parameters to extras tab.") + } + + if tabname == 'txt2img': + res.button_upscale = ToolButton('✨', elem_id=f'{tabname}_upscale', tooltip="Create an upscaled version of the current image using hires fix settings.") + + open_folder_button.click( + fn=lambda images, index: open_folder(shared.opts.outdir_samples or outdir, images, index), + _js="(y, w) => [y, selected_gallery_index()]", + inputs=[ + res.gallery, + open_folder_button, # placeholder for index + ], + outputs=[], + ) + + if tabname != "extras": + download_files = gr.File(None, file_count="multiple", interactive=False, show_label=False, visible=False, elem_id=f'download_files_{tabname}') + + with gr.Group(): + res.infotext = gr.HTML(elem_id=f'html_info_{tabname}', elem_classes="infotext") + res.html_log = gr.HTML(elem_id=f'html_log_{tabname}', elem_classes="html-log") + + res.generation_info = gr.Textbox(visible=False, elem_id=f'generation_info_{tabname}') + if tabname == 'txt2img' or tabname == 'img2img': + generation_info_button = gr.Button(visible=False, elem_id=f"{tabname}_generation_info_button") + generation_info_button.click( + fn=update_generation_info, + _js="function(x, y, z){ return [x, y, selected_gallery_index()] }", + inputs=[res.generation_info, res.infotext, res.infotext], + outputs=[res.infotext, res.infotext], + show_progress=False, + ) + + save.click( + fn=call_queue.wrap_gradio_call_no_job(save_files), + _js="(x, y, z, w) => [x, y, false, selected_gallery_index()]", + inputs=[ + res.generation_info, + res.gallery, + res.infotext, + res.infotext, + ], + outputs=[ + download_files, + res.html_log, + ], + show_progress=False, + ) + + save_zip.click( + fn=call_queue.wrap_gradio_call_no_job(save_files), + _js="(x, y, z, w) => [x, y, true, selected_gallery_index()]", + inputs=[ + res.generation_info, + res.gallery, + res.infotext, + res.infotext, + ], + outputs=[ + download_files, + res.html_log, + ] + ) + + else: + res.generation_info = gr.HTML(elem_id=f'html_info_x_{tabname}') + res.infotext = gr.HTML(elem_id=f'html_info_{tabname}', elem_classes="infotext") + res.html_log = gr.HTML(elem_id=f'html_log_{tabname}') + + paste_field_names = [] + if tabname == "txt2img": + paste_field_names = modules.scripts.scripts_txt2img.paste_field_names + elif tabname == "img2img": + paste_field_names = modules.scripts.scripts_img2img.paste_field_names + + for paste_tabname, paste_button in buttons.items(): + parameters_copypaste.register_paste_params_button(parameters_copypaste.ParamBinding( + paste_button=paste_button, tabname=paste_tabname, source_tabname="txt2img" if tabname == "txt2img" else None, source_image_component=res.gallery, + paste_field_names=paste_field_names + )) + + return res + + +def create_refresh_button(refresh_component, refresh_method, refreshed_args, elem_id): + refresh_components = refresh_component if isinstance(refresh_component, list) else [refresh_component] + + label = None + for comp in refresh_components: + label = getattr(comp, 'label', None) + if label is not None: + break + + def refresh(): + refresh_method() + args = refreshed_args() if callable(refreshed_args) else refreshed_args + + for k, v in args.items(): + for comp in refresh_components: + setattr(comp, k, v) + + return [gr.update(**(args or {})) for _ in refresh_components] if len(refresh_components) > 1 else gr.update(**(args or {})) + + refresh_button = ToolButton(value=refresh_symbol, elem_id=elem_id, tooltip=f"{label}: refresh" if label else "Refresh") + refresh_button.click( + fn=refresh, + inputs=[], + outputs=refresh_components + ) + return refresh_button + + +def setup_dialog(button_show, dialog, *, button_close=None): + """Sets up the UI so that the dialog (gr.Box) is invisible, and is only shown when buttons_show is clicked, in a fullscreen modal window.""" + + dialog.visible = False + + button_show.click( + fn=lambda: gr.update(visible=True), + inputs=[], + outputs=[dialog], + ).then(fn=None, _js="function(){ popupId('" + dialog.elem_id + "'); }") + + if button_close: + button_close.click(fn=None, _js="closePopup") +
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/ui_common.py
Turn comments into proper docstrings
import json import os import gradio as gr from modules import errors from modules.ui_components import ToolButton, InputAccordion def radio_choices(comp): # gradio 3.41 changes choices from list of values to list of pairs return [x[0] if isinstance(x, tuple) else x for x in getattr(comp, 'choices', [])] class UiLoadsave: def __init__(self, filename): self.filename = filename self.ui_settings = {} self.component_mapping = {} self.error_loading = False self.finalized_ui = False self.ui_defaults_view = None self.ui_defaults_apply = None self.ui_defaults_review = None try: self.ui_settings = self.read_from_file() except FileNotFoundError: pass except Exception as e: self.error_loading = True errors.display(e, "loading settings") def add_component(self, path, x): assert not self.finalized_ui def apply_field(obj, field, condition=None, init_field=None): key = f"{path}/{field}" if getattr(obj, 'custom_script_source', None) is not None: key = f"customscript/{obj.custom_script_source}/{key}" if getattr(obj, 'do_not_save_to_config', False): return saved_value = self.ui_settings.get(key, None) if isinstance(obj, gr.Accordion) and isinstance(x, InputAccordion) and field == 'value': field = 'open' if saved_value is None: self.ui_settings[key] = getattr(obj, field) elif condition and not condition(saved_value): pass else: if isinstance(obj, gr.Textbox) and field == 'value': # due to an undesirable behavior of gr.Textbox, if you give it an int value instead of str, everything dies saved_value = str(saved_value) elif isinstance(obj, gr.Number) and field == 'value': try: saved_value = float(saved_value) except ValueError: return setattr(obj, field, saved_value) if init_field is not None: init_field(saved_value) if field == 'value' and key not in self.component_mapping: self.component_mapping[key] = obj if type(x) in [gr.Slider, gr.Radio, gr.Checkbox, gr.Textbox, gr.Number, gr.Dropdown, ToolButton, gr.Button] and x.visible: apply_field(x, 'visible') if type(x) == gr.Slider: apply_field(x, 'value') apply_field(x, 'minimum') apply_field(x, 'maximum') apply_field(x, 'step') if type(x) == gr.Radio: apply_field(x, 'value', lambda val: val in radio_choices(x)) if type(x) == gr.Checkbox: apply_field(x, 'value') if type(x) == gr.Textbox: apply_field(x, 'value') if type(x) == gr.Number: apply_field(x, 'value') if type(x) == gr.Dropdown: def check_dropdown(val): choices = radio_choices(x) if getattr(x, 'multiselect', False): return all(value in choices for value in val) else: return val in choices apply_field(x, 'value', check_dropdown, getattr(x, 'init_field', None)) if type(x) == InputAccordion: if hasattr(x, 'custom_script_source'): x.accordion.custom_script_source = x.custom_script_source if x.accordion.visible: apply_field(x.accordion, 'visible') apply_field(x, 'value') apply_field(x.accordion, 'value') def check_tab_id(tab_id): tab_items = list(filter(lambda e: isinstance(e, gr.TabItem), x.children)) if type(tab_id) == str: tab_ids = [t.id for t in tab_items] return tab_id in tab_ids elif type(tab_id) == int: return 0 <= tab_id < len(tab_items) else: return False if type(x) == gr.Tabs: apply_field(x, 'selected', check_tab_id) def add_block(self, x, path=""): if hasattr(x, 'children'): if isinstance(x, gr.Tabs) and x.elem_id is not None: # Tabs element can't have a label, have to use elem_id instead self.add_component(f"{path}/Tabs@{x.elem_id}", x) for c in x.children: self.add_block(c, path) elif x.label is not None: self.add_component(f"{path}/{x.label}", x) elif isinstance(x, gr.Button) and x.value is not None: self.add_component(f"{path}/{x.value}", x) def read_from_file(self): with open(self.filename, "r", encoding="utf8") as file: return json.load(file) def write_to_file(self, current_ui_settings): with open(self.filename, "w", encoding="utf8") as file: json.dump(current_ui_settings, file, indent=4, ensure_ascii=False) def dump_defaults(self): if self.error_loading and os.path.exists(self.filename): return self.write_to_file(self.ui_settings) def iter_changes(self, current_ui_settings, values): for (path, component), new_value in zip(self.component_mapping.items(), values): old_value = current_ui_settings.get(path) choices = radio_choices(component) if isinstance(new_value, int) and choices: if new_value >= len(choices): continue new_value = choices[new_value] if isinstance(new_value, tuple): new_value = new_value[0] if new_value == old_value: continue if old_value is None and new_value == '' or new_value == []: continue yield path, old_value, new_value def ui_view(self, *values): text = ["<table><thead><tr><th>Path</th><th>Old value</th><th>New value</th></thead><tbody>"] for path, old_value, new_value in self.iter_changes(self.read_from_file(), values): if old_value is None: old_value = "<span class='ui-defaults-none'>None</span>" text.append(f"<tr><td>{path}</td><td>{old_value}</td><td>{new_value}</td></tr>") if len(text) == 1: text.append("<tr><td colspan=3>No changes</td></tr>") text.append("</tbody>") return "".join(text) def ui_apply(self, *values): num_changed = 0 current_ui_settings = self.read_from_file() for path, _, new_value in self.iter_changes(current_ui_settings.copy(), values): num_changed += 1 current_ui_settings[path] = new_value if num_changed == 0: return "No changes." self.write_to_file(current_ui_settings) return f"Wrote {num_changed} changes." def create_ui(self): gr.HTML( f"This page allows you to change default values in UI elements on other tabs.<br />" f"Make your changes, press 'View changes' to review the changed default values,<br />" f"then press 'Apply' to write them to {self.filename}.<br />" f"New defaults will apply after you restart the UI.<br />" ) with gr.Row(): self.ui_defaults_view = gr.Button(value='View changes', elem_id="ui_defaults_view", variant="secondary") self.ui_defaults_apply = gr.Button(value='Apply', elem_id="ui_defaults_apply", variant="primary") self.ui_defaults_review = gr.HTML("") def setup_ui(self): assert not self.finalized_ui self.finalized_ui = True self.ui_defaults_view.click(fn=self.ui_view, inputs=list(self.component_mapping.values()), outputs=[self.ui_defaults_review]) self.ui_defaults_apply.click(fn=self.ui_apply, inputs=list(self.component_mapping.values()), outputs=[self.ui_defaults_review])
--- +++ @@ -1,227 +1,238 @@-import json -import os - -import gradio as gr - -from modules import errors -from modules.ui_components import ToolButton, InputAccordion - - -def radio_choices(comp): # gradio 3.41 changes choices from list of values to list of pairs - return [x[0] if isinstance(x, tuple) else x for x in getattr(comp, 'choices', [])] - - -class UiLoadsave: - - def __init__(self, filename): - self.filename = filename - self.ui_settings = {} - self.component_mapping = {} - self.error_loading = False - self.finalized_ui = False - - self.ui_defaults_view = None - self.ui_defaults_apply = None - self.ui_defaults_review = None - - try: - self.ui_settings = self.read_from_file() - except FileNotFoundError: - pass - except Exception as e: - self.error_loading = True - errors.display(e, "loading settings") - - def add_component(self, path, x): - - assert not self.finalized_ui - - def apply_field(obj, field, condition=None, init_field=None): - key = f"{path}/{field}" - - if getattr(obj, 'custom_script_source', None) is not None: - key = f"customscript/{obj.custom_script_source}/{key}" - - if getattr(obj, 'do_not_save_to_config', False): - return - - saved_value = self.ui_settings.get(key, None) - - if isinstance(obj, gr.Accordion) and isinstance(x, InputAccordion) and field == 'value': - field = 'open' - - if saved_value is None: - self.ui_settings[key] = getattr(obj, field) - elif condition and not condition(saved_value): - pass - else: - if isinstance(obj, gr.Textbox) and field == 'value': # due to an undesirable behavior of gr.Textbox, if you give it an int value instead of str, everything dies - saved_value = str(saved_value) - elif isinstance(obj, gr.Number) and field == 'value': - try: - saved_value = float(saved_value) - except ValueError: - return - - setattr(obj, field, saved_value) - if init_field is not None: - init_field(saved_value) - - if field == 'value' and key not in self.component_mapping: - self.component_mapping[key] = obj - - if type(x) in [gr.Slider, gr.Radio, gr.Checkbox, gr.Textbox, gr.Number, gr.Dropdown, ToolButton, gr.Button] and x.visible: - apply_field(x, 'visible') - - if type(x) == gr.Slider: - apply_field(x, 'value') - apply_field(x, 'minimum') - apply_field(x, 'maximum') - apply_field(x, 'step') - - if type(x) == gr.Radio: - apply_field(x, 'value', lambda val: val in radio_choices(x)) - - if type(x) == gr.Checkbox: - apply_field(x, 'value') - - if type(x) == gr.Textbox: - apply_field(x, 'value') - - if type(x) == gr.Number: - apply_field(x, 'value') - - if type(x) == gr.Dropdown: - def check_dropdown(val): - choices = radio_choices(x) - if getattr(x, 'multiselect', False): - return all(value in choices for value in val) - else: - return val in choices - - apply_field(x, 'value', check_dropdown, getattr(x, 'init_field', None)) - - if type(x) == InputAccordion: - if hasattr(x, 'custom_script_source'): - x.accordion.custom_script_source = x.custom_script_source - if x.accordion.visible: - apply_field(x.accordion, 'visible') - apply_field(x, 'value') - apply_field(x.accordion, 'value') - - def check_tab_id(tab_id): - tab_items = list(filter(lambda e: isinstance(e, gr.TabItem), x.children)) - if type(tab_id) == str: - tab_ids = [t.id for t in tab_items] - return tab_id in tab_ids - elif type(tab_id) == int: - return 0 <= tab_id < len(tab_items) - else: - return False - - if type(x) == gr.Tabs: - apply_field(x, 'selected', check_tab_id) - - def add_block(self, x, path=""): - - if hasattr(x, 'children'): - if isinstance(x, gr.Tabs) and x.elem_id is not None: - # Tabs element can't have a label, have to use elem_id instead - self.add_component(f"{path}/Tabs@{x.elem_id}", x) - for c in x.children: - self.add_block(c, path) - elif x.label is not None: - self.add_component(f"{path}/{x.label}", x) - elif isinstance(x, gr.Button) and x.value is not None: - self.add_component(f"{path}/{x.value}", x) - - def read_from_file(self): - with open(self.filename, "r", encoding="utf8") as file: - return json.load(file) - - def write_to_file(self, current_ui_settings): - with open(self.filename, "w", encoding="utf8") as file: - json.dump(current_ui_settings, file, indent=4, ensure_ascii=False) - - def dump_defaults(self): - - if self.error_loading and os.path.exists(self.filename): - return - - self.write_to_file(self.ui_settings) - - def iter_changes(self, current_ui_settings, values): - - for (path, component), new_value in zip(self.component_mapping.items(), values): - old_value = current_ui_settings.get(path) - - choices = radio_choices(component) - if isinstance(new_value, int) and choices: - if new_value >= len(choices): - continue - - new_value = choices[new_value] - if isinstance(new_value, tuple): - new_value = new_value[0] - - if new_value == old_value: - continue - - if old_value is None and new_value == '' or new_value == []: - continue - - yield path, old_value, new_value - - def ui_view(self, *values): - text = ["<table><thead><tr><th>Path</th><th>Old value</th><th>New value</th></thead><tbody>"] - - for path, old_value, new_value in self.iter_changes(self.read_from_file(), values): - if old_value is None: - old_value = "<span class='ui-defaults-none'>None</span>" - - text.append(f"<tr><td>{path}</td><td>{old_value}</td><td>{new_value}</td></tr>") - - if len(text) == 1: - text.append("<tr><td colspan=3>No changes</td></tr>") - - text.append("</tbody>") - return "".join(text) - - def ui_apply(self, *values): - num_changed = 0 - - current_ui_settings = self.read_from_file() - - for path, _, new_value in self.iter_changes(current_ui_settings.copy(), values): - num_changed += 1 - current_ui_settings[path] = new_value - - if num_changed == 0: - return "No changes." - - self.write_to_file(current_ui_settings) - - return f"Wrote {num_changed} changes." - - def create_ui(self): - - gr.HTML( - f"This page allows you to change default values in UI elements on other tabs.<br />" - f"Make your changes, press 'View changes' to review the changed default values,<br />" - f"then press 'Apply' to write them to {self.filename}.<br />" - f"New defaults will apply after you restart the UI.<br />" - ) - - with gr.Row(): - self.ui_defaults_view = gr.Button(value='View changes', elem_id="ui_defaults_view", variant="secondary") - self.ui_defaults_apply = gr.Button(value='Apply', elem_id="ui_defaults_apply", variant="primary") - - self.ui_defaults_review = gr.HTML("") - - def setup_ui(self): - - assert not self.finalized_ui - self.finalized_ui = True - - self.ui_defaults_view.click(fn=self.ui_view, inputs=list(self.component_mapping.values()), outputs=[self.ui_defaults_review]) - self.ui_defaults_apply.click(fn=self.ui_apply, inputs=list(self.component_mapping.values()), outputs=[self.ui_defaults_review])+import json +import os + +import gradio as gr + +from modules import errors +from modules.ui_components import ToolButton, InputAccordion + + +def radio_choices(comp): # gradio 3.41 changes choices from list of values to list of pairs + return [x[0] if isinstance(x, tuple) else x for x in getattr(comp, 'choices', [])] + + +class UiLoadsave: + """allows saving and restoring default values for gradio components""" + + def __init__(self, filename): + self.filename = filename + self.ui_settings = {} + self.component_mapping = {} + self.error_loading = False + self.finalized_ui = False + + self.ui_defaults_view = None + self.ui_defaults_apply = None + self.ui_defaults_review = None + + try: + self.ui_settings = self.read_from_file() + except FileNotFoundError: + pass + except Exception as e: + self.error_loading = True + errors.display(e, "loading settings") + + def add_component(self, path, x): + """adds component to the registry of tracked components""" + + assert not self.finalized_ui + + def apply_field(obj, field, condition=None, init_field=None): + key = f"{path}/{field}" + + if getattr(obj, 'custom_script_source', None) is not None: + key = f"customscript/{obj.custom_script_source}/{key}" + + if getattr(obj, 'do_not_save_to_config', False): + return + + saved_value = self.ui_settings.get(key, None) + + if isinstance(obj, gr.Accordion) and isinstance(x, InputAccordion) and field == 'value': + field = 'open' + + if saved_value is None: + self.ui_settings[key] = getattr(obj, field) + elif condition and not condition(saved_value): + pass + else: + if isinstance(obj, gr.Textbox) and field == 'value': # due to an undesirable behavior of gr.Textbox, if you give it an int value instead of str, everything dies + saved_value = str(saved_value) + elif isinstance(obj, gr.Number) and field == 'value': + try: + saved_value = float(saved_value) + except ValueError: + return + + setattr(obj, field, saved_value) + if init_field is not None: + init_field(saved_value) + + if field == 'value' and key not in self.component_mapping: + self.component_mapping[key] = obj + + if type(x) in [gr.Slider, gr.Radio, gr.Checkbox, gr.Textbox, gr.Number, gr.Dropdown, ToolButton, gr.Button] and x.visible: + apply_field(x, 'visible') + + if type(x) == gr.Slider: + apply_field(x, 'value') + apply_field(x, 'minimum') + apply_field(x, 'maximum') + apply_field(x, 'step') + + if type(x) == gr.Radio: + apply_field(x, 'value', lambda val: val in radio_choices(x)) + + if type(x) == gr.Checkbox: + apply_field(x, 'value') + + if type(x) == gr.Textbox: + apply_field(x, 'value') + + if type(x) == gr.Number: + apply_field(x, 'value') + + if type(x) == gr.Dropdown: + def check_dropdown(val): + choices = radio_choices(x) + if getattr(x, 'multiselect', False): + return all(value in choices for value in val) + else: + return val in choices + + apply_field(x, 'value', check_dropdown, getattr(x, 'init_field', None)) + + if type(x) == InputAccordion: + if hasattr(x, 'custom_script_source'): + x.accordion.custom_script_source = x.custom_script_source + if x.accordion.visible: + apply_field(x.accordion, 'visible') + apply_field(x, 'value') + apply_field(x.accordion, 'value') + + def check_tab_id(tab_id): + tab_items = list(filter(lambda e: isinstance(e, gr.TabItem), x.children)) + if type(tab_id) == str: + tab_ids = [t.id for t in tab_items] + return tab_id in tab_ids + elif type(tab_id) == int: + return 0 <= tab_id < len(tab_items) + else: + return False + + if type(x) == gr.Tabs: + apply_field(x, 'selected', check_tab_id) + + def add_block(self, x, path=""): + """adds all components inside a gradio block x to the registry of tracked components""" + + if hasattr(x, 'children'): + if isinstance(x, gr.Tabs) and x.elem_id is not None: + # Tabs element can't have a label, have to use elem_id instead + self.add_component(f"{path}/Tabs@{x.elem_id}", x) + for c in x.children: + self.add_block(c, path) + elif x.label is not None: + self.add_component(f"{path}/{x.label}", x) + elif isinstance(x, gr.Button) and x.value is not None: + self.add_component(f"{path}/{x.value}", x) + + def read_from_file(self): + with open(self.filename, "r", encoding="utf8") as file: + return json.load(file) + + def write_to_file(self, current_ui_settings): + with open(self.filename, "w", encoding="utf8") as file: + json.dump(current_ui_settings, file, indent=4, ensure_ascii=False) + + def dump_defaults(self): + """saves default values to a file unless the file is present and there was an error loading default values at start""" + + if self.error_loading and os.path.exists(self.filename): + return + + self.write_to_file(self.ui_settings) + + def iter_changes(self, current_ui_settings, values): + """ + given a dictionary with defaults from a file and current values from gradio elements, returns + an iterator over tuples of values that are not the same between the file and the current; + tuple contents are: path, old value, new value + """ + + for (path, component), new_value in zip(self.component_mapping.items(), values): + old_value = current_ui_settings.get(path) + + choices = radio_choices(component) + if isinstance(new_value, int) and choices: + if new_value >= len(choices): + continue + + new_value = choices[new_value] + if isinstance(new_value, tuple): + new_value = new_value[0] + + if new_value == old_value: + continue + + if old_value is None and new_value == '' or new_value == []: + continue + + yield path, old_value, new_value + + def ui_view(self, *values): + text = ["<table><thead><tr><th>Path</th><th>Old value</th><th>New value</th></thead><tbody>"] + + for path, old_value, new_value in self.iter_changes(self.read_from_file(), values): + if old_value is None: + old_value = "<span class='ui-defaults-none'>None</span>" + + text.append(f"<tr><td>{path}</td><td>{old_value}</td><td>{new_value}</td></tr>") + + if len(text) == 1: + text.append("<tr><td colspan=3>No changes</td></tr>") + + text.append("</tbody>") + return "".join(text) + + def ui_apply(self, *values): + num_changed = 0 + + current_ui_settings = self.read_from_file() + + for path, _, new_value in self.iter_changes(current_ui_settings.copy(), values): + num_changed += 1 + current_ui_settings[path] = new_value + + if num_changed == 0: + return "No changes." + + self.write_to_file(current_ui_settings) + + return f"Wrote {num_changed} changes." + + def create_ui(self): + """creates ui elements for editing defaults UI, without adding any logic to them""" + + gr.HTML( + f"This page allows you to change default values in UI elements on other tabs.<br />" + f"Make your changes, press 'View changes' to review the changed default values,<br />" + f"then press 'Apply' to write them to {self.filename}.<br />" + f"New defaults will apply after you restart the UI.<br />" + ) + + with gr.Row(): + self.ui_defaults_view = gr.Button(value='View changes', elem_id="ui_defaults_view", variant="secondary") + self.ui_defaults_apply = gr.Button(value='Apply', elem_id="ui_defaults_apply", variant="primary") + + self.ui_defaults_review = gr.HTML("") + + def setup_ui(self): + """adds logic to elements created with create_ui; all add_block class must be made before this""" + + assert not self.finalized_ui + self.finalized_ui = True + + self.ui_defaults_view.click(fn=self.ui_view, inputs=list(self.component_mapping.values()), outputs=[self.ui_defaults_review]) + self.ui_defaults_apply.click(fn=self.ui_apply, inputs=list(self.component_mapping.values()), outputs=[self.ui_defaults_review])
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/ui_loadsave.py
Generate docstrings for each module
import os import tempfile from collections import namedtuple from pathlib import Path import gradio.components from PIL import PngImagePlugin from modules import shared Savedfile = namedtuple("Savedfile", ["name"]) def register_tmp_file(gradio, filename): if hasattr(gradio, 'temp_file_sets'): # gradio 3.15 gradio.temp_file_sets[0] = gradio.temp_file_sets[0] | {os.path.abspath(filename)} if hasattr(gradio, 'temp_dirs'): # gradio 3.9 gradio.temp_dirs = gradio.temp_dirs | {os.path.abspath(os.path.dirname(filename))} def check_tmp_file(gradio, filename): if hasattr(gradio, 'temp_file_sets'): return any(filename in fileset for fileset in gradio.temp_file_sets) if hasattr(gradio, 'temp_dirs'): return any(Path(temp_dir).resolve() in Path(filename).resolve().parents for temp_dir in gradio.temp_dirs) return False def save_pil_to_file(self, pil_image, dir=None, format="png"): already_saved_as = getattr(pil_image, 'already_saved_as', None) if already_saved_as and os.path.isfile(already_saved_as): register_tmp_file(shared.demo, already_saved_as) filename_with_mtime = f'{already_saved_as}?{os.path.getmtime(already_saved_as)}' register_tmp_file(shared.demo, filename_with_mtime) return filename_with_mtime if shared.opts.temp_dir != "": dir = shared.opts.temp_dir else: os.makedirs(dir, exist_ok=True) use_metadata = False metadata = PngImagePlugin.PngInfo() for key, value in pil_image.info.items(): if isinstance(key, str) and isinstance(value, str): metadata.add_text(key, value) use_metadata = True file_obj = tempfile.NamedTemporaryFile(delete=False, suffix=".png", dir=dir) pil_image.save(file_obj, pnginfo=(metadata if use_metadata else None)) return file_obj.name def install_ui_tempdir_override(): gradio.components.IOComponent.pil_to_temp_file = save_pil_to_file def on_tmpdir_changed(): if shared.opts.temp_dir == "" or shared.demo is None: return os.makedirs(shared.opts.temp_dir, exist_ok=True) register_tmp_file(shared.demo, os.path.join(shared.opts.temp_dir, "x")) def cleanup_tmpdr(): temp_dir = shared.opts.temp_dir if temp_dir == "" or not os.path.isdir(temp_dir): return for root, _, files in os.walk(temp_dir, topdown=False): for name in files: _, extension = os.path.splitext(name) if extension != ".png": continue filename = os.path.join(root, name) os.remove(filename) def is_gradio_temp_path(path): path = Path(path) if shared.opts.temp_dir and path.is_relative_to(shared.opts.temp_dir): return True if gradio_temp_dir := os.environ.get("GRADIO_TEMP_DIR"): if path.is_relative_to(gradio_temp_dir): return True if path.is_relative_to(Path(tempfile.gettempdir()) / "gradio"): return True return False
--- +++ @@ -1,96 +1,100 @@-import os -import tempfile -from collections import namedtuple -from pathlib import Path - -import gradio.components - -from PIL import PngImagePlugin - -from modules import shared - - -Savedfile = namedtuple("Savedfile", ["name"]) - - -def register_tmp_file(gradio, filename): - if hasattr(gradio, 'temp_file_sets'): # gradio 3.15 - gradio.temp_file_sets[0] = gradio.temp_file_sets[0] | {os.path.abspath(filename)} - - if hasattr(gradio, 'temp_dirs'): # gradio 3.9 - gradio.temp_dirs = gradio.temp_dirs | {os.path.abspath(os.path.dirname(filename))} - - -def check_tmp_file(gradio, filename): - if hasattr(gradio, 'temp_file_sets'): - return any(filename in fileset for fileset in gradio.temp_file_sets) - - if hasattr(gradio, 'temp_dirs'): - return any(Path(temp_dir).resolve() in Path(filename).resolve().parents for temp_dir in gradio.temp_dirs) - - return False - - -def save_pil_to_file(self, pil_image, dir=None, format="png"): - already_saved_as = getattr(pil_image, 'already_saved_as', None) - if already_saved_as and os.path.isfile(already_saved_as): - register_tmp_file(shared.demo, already_saved_as) - filename_with_mtime = f'{already_saved_as}?{os.path.getmtime(already_saved_as)}' - register_tmp_file(shared.demo, filename_with_mtime) - return filename_with_mtime - - if shared.opts.temp_dir != "": - dir = shared.opts.temp_dir - else: - os.makedirs(dir, exist_ok=True) - - use_metadata = False - metadata = PngImagePlugin.PngInfo() - for key, value in pil_image.info.items(): - if isinstance(key, str) and isinstance(value, str): - metadata.add_text(key, value) - use_metadata = True - - file_obj = tempfile.NamedTemporaryFile(delete=False, suffix=".png", dir=dir) - pil_image.save(file_obj, pnginfo=(metadata if use_metadata else None)) - return file_obj.name - - -def install_ui_tempdir_override(): - gradio.components.IOComponent.pil_to_temp_file = save_pil_to_file - - -def on_tmpdir_changed(): - if shared.opts.temp_dir == "" or shared.demo is None: - return - - os.makedirs(shared.opts.temp_dir, exist_ok=True) - - register_tmp_file(shared.demo, os.path.join(shared.opts.temp_dir, "x")) - - -def cleanup_tmpdr(): - temp_dir = shared.opts.temp_dir - if temp_dir == "" or not os.path.isdir(temp_dir): - return - - for root, _, files in os.walk(temp_dir, topdown=False): - for name in files: - _, extension = os.path.splitext(name) - if extension != ".png": - continue - - filename = os.path.join(root, name) - os.remove(filename) - - -def is_gradio_temp_path(path): - path = Path(path) - if shared.opts.temp_dir and path.is_relative_to(shared.opts.temp_dir): - return True - if gradio_temp_dir := os.environ.get("GRADIO_TEMP_DIR"): - if path.is_relative_to(gradio_temp_dir): - return True - if path.is_relative_to(Path(tempfile.gettempdir()) / "gradio"): - return True - return False+import os +import tempfile +from collections import namedtuple +from pathlib import Path + +import gradio.components + +from PIL import PngImagePlugin + +from modules import shared + + +Savedfile = namedtuple("Savedfile", ["name"]) + + +def register_tmp_file(gradio, filename): + if hasattr(gradio, 'temp_file_sets'): # gradio 3.15 + gradio.temp_file_sets[0] = gradio.temp_file_sets[0] | {os.path.abspath(filename)} + + if hasattr(gradio, 'temp_dirs'): # gradio 3.9 + gradio.temp_dirs = gradio.temp_dirs | {os.path.abspath(os.path.dirname(filename))} + + +def check_tmp_file(gradio, filename): + if hasattr(gradio, 'temp_file_sets'): + return any(filename in fileset for fileset in gradio.temp_file_sets) + + if hasattr(gradio, 'temp_dirs'): + return any(Path(temp_dir).resolve() in Path(filename).resolve().parents for temp_dir in gradio.temp_dirs) + + return False + + +def save_pil_to_file(self, pil_image, dir=None, format="png"): + already_saved_as = getattr(pil_image, 'already_saved_as', None) + if already_saved_as and os.path.isfile(already_saved_as): + register_tmp_file(shared.demo, already_saved_as) + filename_with_mtime = f'{already_saved_as}?{os.path.getmtime(already_saved_as)}' + register_tmp_file(shared.demo, filename_with_mtime) + return filename_with_mtime + + if shared.opts.temp_dir != "": + dir = shared.opts.temp_dir + else: + os.makedirs(dir, exist_ok=True) + + use_metadata = False + metadata = PngImagePlugin.PngInfo() + for key, value in pil_image.info.items(): + if isinstance(key, str) and isinstance(value, str): + metadata.add_text(key, value) + use_metadata = True + + file_obj = tempfile.NamedTemporaryFile(delete=False, suffix=".png", dir=dir) + pil_image.save(file_obj, pnginfo=(metadata if use_metadata else None)) + return file_obj.name + + +def install_ui_tempdir_override(): + """override save to file function so that it also writes PNG info""" + gradio.components.IOComponent.pil_to_temp_file = save_pil_to_file + + +def on_tmpdir_changed(): + if shared.opts.temp_dir == "" or shared.demo is None: + return + + os.makedirs(shared.opts.temp_dir, exist_ok=True) + + register_tmp_file(shared.demo, os.path.join(shared.opts.temp_dir, "x")) + + +def cleanup_tmpdr(): + temp_dir = shared.opts.temp_dir + if temp_dir == "" or not os.path.isdir(temp_dir): + return + + for root, _, files in os.walk(temp_dir, topdown=False): + for name in files: + _, extension = os.path.splitext(name) + if extension != ".png": + continue + + filename = os.path.join(root, name) + os.remove(filename) + + +def is_gradio_temp_path(path): + """ + Check if the path is a temp dir used by gradio + """ + path = Path(path) + if shared.opts.temp_dir and path.is_relative_to(shared.opts.temp_dir): + return True + if gradio_temp_dir := os.environ.get("GRADIO_TEMP_DIR"): + if path.is_relative_to(gradio_temp_dir): + return True + if path.is_relative_to(Path(tempfile.gettempdir()) / "gradio"): + return True + return False
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/ui_tempdir.py
Add docstrings that explain inputs and outputs
import os import re from modules import shared from modules.paths_internal import script_path, cwd def natural_sort_key(s, regex=re.compile('([0-9]+)')): return [int(text) if text.isdigit() else text.lower() for text in regex.split(s)] def listfiles(dirname): filenames = [os.path.join(dirname, x) for x in sorted(os.listdir(dirname), key=natural_sort_key) if not x.startswith(".")] return [file for file in filenames if os.path.isfile(file)] def html_path(filename): return os.path.join(script_path, "html", filename) def html(filename): path = html_path(filename) try: with open(path, encoding="utf8") as file: return file.read() except OSError: return "" def walk_files(path, allowed_extensions=None): if not os.path.exists(path): return if allowed_extensions is not None: allowed_extensions = set(allowed_extensions) items = list(os.walk(path, followlinks=True)) items = sorted(items, key=lambda x: natural_sort_key(x[0])) for root, _, files in items: for filename in sorted(files, key=natural_sort_key): if allowed_extensions is not None: _, ext = os.path.splitext(filename) if ext.lower() not in allowed_extensions: continue if not shared.opts.list_hidden_files and ("/." in root or "\\." in root): continue yield os.path.join(root, filename) def ldm_print(*args, **kwargs): if shared.opts.hide_ldm_prints: return print(*args, **kwargs) def truncate_path(target_path, base_path=cwd): abs_target, abs_base = os.path.abspath(target_path), os.path.abspath(base_path) try: if os.path.commonpath([abs_target, abs_base]) == abs_base: return os.path.relpath(abs_target, abs_base) except ValueError: pass return abs_target class MassFileListerCachedDir: def __init__(self, dirname): self.files = None self.files_cased = None self.dirname = dirname stats = ((x.name, x.stat(follow_symlinks=False)) for x in os.scandir(self.dirname)) files = [(n, s.st_mtime, s.st_ctime) for n, s in stats] self.files = {x[0].lower(): x for x in files} self.files_cased = {x[0]: x for x in files} def update_entry(self, filename): file_path = os.path.join(self.dirname, filename) try: stat = os.stat(file_path) entry = (filename, stat.st_mtime, stat.st_ctime) self.files[filename.lower()] = entry self.files_cased[filename] = entry except FileNotFoundError as e: print(f'MassFileListerCachedDir.add_entry: "{file_path}" {e}') class MassFileLister: def __init__(self): self.cached_dirs = {} def find(self, path): dirname, filename = os.path.split(path) cached_dir = self.cached_dirs.get(dirname) if cached_dir is None: cached_dir = MassFileListerCachedDir(dirname) self.cached_dirs[dirname] = cached_dir stats = cached_dir.files_cased.get(filename) if stats is not None: return stats stats = cached_dir.files.get(filename.lower()) if stats is None: return None try: os_stats = os.stat(path, follow_symlinks=False) return filename, os_stats.st_mtime, os_stats.st_ctime except Exception: return None def exists(self, path): return self.find(path) is not None def mctime(self, path): stats = self.find(path) return (0, 0) if stats is None else stats[1:3] def reset(self): self.cached_dirs.clear() def update_file_entry(self, path): dirname, filename = os.path.split(path) if cached_dir := self.cached_dirs.get(dirname): cached_dir.update_entry(filename) def topological_sort(dependencies): visited = {} result = [] def inner(name): visited[name] = True for dep in dependencies.get(name, []): if dep in dependencies and dep not in visited: inner(dep) result.append(name) for depname in dependencies: if depname not in visited: inner(depname) return result def open_folder(path): # import at function level to avoid potential issues import gradio as gr import platform import sys import subprocess if not os.path.exists(path): msg = f'Folder "{path}" does not exist. after you save an image, the folder will be created.' print(msg) gr.Info(msg) return elif not os.path.isdir(path): msg = f""" WARNING An open_folder request was made with an path that is not a folder. This could be an error or a malicious attempt to run code on your computer. Requested path was: {path} """ print(msg, file=sys.stderr) gr.Warning(msg) return path = os.path.normpath(path) if platform.system() == "Windows": os.startfile(path) elif platform.system() == "Darwin": subprocess.Popen(["open", path]) elif "microsoft-standard-WSL2" in platform.uname().release: subprocess.Popen(["explorer.exe", subprocess.check_output(["wslpath", "-w", path])]) else: subprocess.Popen(["xdg-open", path])
--- +++ @@ -1,191 +1,213 @@-import os -import re - -from modules import shared -from modules.paths_internal import script_path, cwd - - -def natural_sort_key(s, regex=re.compile('([0-9]+)')): - return [int(text) if text.isdigit() else text.lower() for text in regex.split(s)] - - -def listfiles(dirname): - filenames = [os.path.join(dirname, x) for x in sorted(os.listdir(dirname), key=natural_sort_key) if not x.startswith(".")] - return [file for file in filenames if os.path.isfile(file)] - - -def html_path(filename): - return os.path.join(script_path, "html", filename) - - -def html(filename): - path = html_path(filename) - - try: - with open(path, encoding="utf8") as file: - return file.read() - except OSError: - return "" - - -def walk_files(path, allowed_extensions=None): - if not os.path.exists(path): - return - - if allowed_extensions is not None: - allowed_extensions = set(allowed_extensions) - - items = list(os.walk(path, followlinks=True)) - items = sorted(items, key=lambda x: natural_sort_key(x[0])) - - for root, _, files in items: - for filename in sorted(files, key=natural_sort_key): - if allowed_extensions is not None: - _, ext = os.path.splitext(filename) - if ext.lower() not in allowed_extensions: - continue - - if not shared.opts.list_hidden_files and ("/." in root or "\\." in root): - continue - - yield os.path.join(root, filename) - - -def ldm_print(*args, **kwargs): - if shared.opts.hide_ldm_prints: - return - - print(*args, **kwargs) - - -def truncate_path(target_path, base_path=cwd): - abs_target, abs_base = os.path.abspath(target_path), os.path.abspath(base_path) - try: - if os.path.commonpath([abs_target, abs_base]) == abs_base: - return os.path.relpath(abs_target, abs_base) - except ValueError: - pass - return abs_target - - -class MassFileListerCachedDir: - - def __init__(self, dirname): - self.files = None - self.files_cased = None - self.dirname = dirname - - stats = ((x.name, x.stat(follow_symlinks=False)) for x in os.scandir(self.dirname)) - files = [(n, s.st_mtime, s.st_ctime) for n, s in stats] - self.files = {x[0].lower(): x for x in files} - self.files_cased = {x[0]: x for x in files} - - def update_entry(self, filename): - file_path = os.path.join(self.dirname, filename) - try: - stat = os.stat(file_path) - entry = (filename, stat.st_mtime, stat.st_ctime) - self.files[filename.lower()] = entry - self.files_cased[filename] = entry - except FileNotFoundError as e: - print(f'MassFileListerCachedDir.add_entry: "{file_path}" {e}') - - -class MassFileLister: - - def __init__(self): - self.cached_dirs = {} - - def find(self, path): - - dirname, filename = os.path.split(path) - - cached_dir = self.cached_dirs.get(dirname) - if cached_dir is None: - cached_dir = MassFileListerCachedDir(dirname) - self.cached_dirs[dirname] = cached_dir - - stats = cached_dir.files_cased.get(filename) - if stats is not None: - return stats - - stats = cached_dir.files.get(filename.lower()) - if stats is None: - return None - - try: - os_stats = os.stat(path, follow_symlinks=False) - return filename, os_stats.st_mtime, os_stats.st_ctime - except Exception: - return None - - def exists(self, path): - - return self.find(path) is not None - - def mctime(self, path): - - stats = self.find(path) - return (0, 0) if stats is None else stats[1:3] - - def reset(self): - self.cached_dirs.clear() - - def update_file_entry(self, path): - dirname, filename = os.path.split(path) - if cached_dir := self.cached_dirs.get(dirname): - cached_dir.update_entry(filename) - -def topological_sort(dependencies): - - visited = {} - result = [] - - def inner(name): - visited[name] = True - - for dep in dependencies.get(name, []): - if dep in dependencies and dep not in visited: - inner(dep) - - result.append(name) - - for depname in dependencies: - if depname not in visited: - inner(depname) - - return result - - -def open_folder(path): - # import at function level to avoid potential issues - import gradio as gr - import platform - import sys - import subprocess - - if not os.path.exists(path): - msg = f'Folder "{path}" does not exist. after you save an image, the folder will be created.' - print(msg) - gr.Info(msg) - return - elif not os.path.isdir(path): - msg = f""" -WARNING -An open_folder request was made with an path that is not a folder. -This could be an error or a malicious attempt to run code on your computer. -Requested path was: {path} -""" - print(msg, file=sys.stderr) - gr.Warning(msg) - return - - path = os.path.normpath(path) - if platform.system() == "Windows": - os.startfile(path) - elif platform.system() == "Darwin": - subprocess.Popen(["open", path]) - elif "microsoft-standard-WSL2" in platform.uname().release: - subprocess.Popen(["explorer.exe", subprocess.check_output(["wslpath", "-w", path])]) - else: - subprocess.Popen(["xdg-open", path])+import os +import re + +from modules import shared +from modules.paths_internal import script_path, cwd + + +def natural_sort_key(s, regex=re.compile('([0-9]+)')): + return [int(text) if text.isdigit() else text.lower() for text in regex.split(s)] + + +def listfiles(dirname): + filenames = [os.path.join(dirname, x) for x in sorted(os.listdir(dirname), key=natural_sort_key) if not x.startswith(".")] + return [file for file in filenames if os.path.isfile(file)] + + +def html_path(filename): + return os.path.join(script_path, "html", filename) + + +def html(filename): + path = html_path(filename) + + try: + with open(path, encoding="utf8") as file: + return file.read() + except OSError: + return "" + + +def walk_files(path, allowed_extensions=None): + if not os.path.exists(path): + return + + if allowed_extensions is not None: + allowed_extensions = set(allowed_extensions) + + items = list(os.walk(path, followlinks=True)) + items = sorted(items, key=lambda x: natural_sort_key(x[0])) + + for root, _, files in items: + for filename in sorted(files, key=natural_sort_key): + if allowed_extensions is not None: + _, ext = os.path.splitext(filename) + if ext.lower() not in allowed_extensions: + continue + + if not shared.opts.list_hidden_files and ("/." in root or "\\." in root): + continue + + yield os.path.join(root, filename) + + +def ldm_print(*args, **kwargs): + if shared.opts.hide_ldm_prints: + return + + print(*args, **kwargs) + + +def truncate_path(target_path, base_path=cwd): + abs_target, abs_base = os.path.abspath(target_path), os.path.abspath(base_path) + try: + if os.path.commonpath([abs_target, abs_base]) == abs_base: + return os.path.relpath(abs_target, abs_base) + except ValueError: + pass + return abs_target + + +class MassFileListerCachedDir: + """A class that caches file metadata for a specific directory.""" + + def __init__(self, dirname): + self.files = None + self.files_cased = None + self.dirname = dirname + + stats = ((x.name, x.stat(follow_symlinks=False)) for x in os.scandir(self.dirname)) + files = [(n, s.st_mtime, s.st_ctime) for n, s in stats] + self.files = {x[0].lower(): x for x in files} + self.files_cased = {x[0]: x for x in files} + + def update_entry(self, filename): + """Add a file to the cache""" + file_path = os.path.join(self.dirname, filename) + try: + stat = os.stat(file_path) + entry = (filename, stat.st_mtime, stat.st_ctime) + self.files[filename.lower()] = entry + self.files_cased[filename] = entry + except FileNotFoundError as e: + print(f'MassFileListerCachedDir.add_entry: "{file_path}" {e}') + + +class MassFileLister: + """A class that provides a way to check for the existence and mtime/ctile of files without doing more than one stat call per file.""" + + def __init__(self): + self.cached_dirs = {} + + def find(self, path): + """ + Find the metadata for a file at the given path. + + Returns: + tuple or None: A tuple of (name, mtime, ctime) if the file exists, or None if it does not. + """ + + dirname, filename = os.path.split(path) + + cached_dir = self.cached_dirs.get(dirname) + if cached_dir is None: + cached_dir = MassFileListerCachedDir(dirname) + self.cached_dirs[dirname] = cached_dir + + stats = cached_dir.files_cased.get(filename) + if stats is not None: + return stats + + stats = cached_dir.files.get(filename.lower()) + if stats is None: + return None + + try: + os_stats = os.stat(path, follow_symlinks=False) + return filename, os_stats.st_mtime, os_stats.st_ctime + except Exception: + return None + + def exists(self, path): + """Check if a file exists at the given path.""" + + return self.find(path) is not None + + def mctime(self, path): + """ + Get the modification and creation times for a file at the given path. + + Returns: + tuple: A tuple of (mtime, ctime) if the file exists, or (0, 0) if it does not. + """ + + stats = self.find(path) + return (0, 0) if stats is None else stats[1:3] + + def reset(self): + """Clear the cache of all directories.""" + self.cached_dirs.clear() + + def update_file_entry(self, path): + """Update the cache for a specific directory.""" + dirname, filename = os.path.split(path) + if cached_dir := self.cached_dirs.get(dirname): + cached_dir.update_entry(filename) + +def topological_sort(dependencies): + """Accepts a dictionary mapping name to its dependencies, returns a list of names ordered according to dependencies. + Ignores errors relating to missing dependencies or circular dependencies + """ + + visited = {} + result = [] + + def inner(name): + visited[name] = True + + for dep in dependencies.get(name, []): + if dep in dependencies and dep not in visited: + inner(dep) + + result.append(name) + + for depname in dependencies: + if depname not in visited: + inner(depname) + + return result + + +def open_folder(path): + """Open a folder in the file manager of the respect OS.""" + # import at function level to avoid potential issues + import gradio as gr + import platform + import sys + import subprocess + + if not os.path.exists(path): + msg = f'Folder "{path}" does not exist. after you save an image, the folder will be created.' + print(msg) + gr.Info(msg) + return + elif not os.path.isdir(path): + msg = f""" +WARNING +An open_folder request was made with an path that is not a folder. +This could be an error or a malicious attempt to run code on your computer. +Requested path was: {path} +""" + print(msg, file=sys.stderr) + gr.Warning(msg) + return + + path = os.path.normpath(path) + if platform.system() == "Windows": + os.startfile(path) + elif platform.system() == "Darwin": + subprocess.Popen(["open", path]) + elif "microsoft-standard-WSL2" in platform.uname().release: + subprocess.Popen(["explorer.exe", subprocess.check_output(["wslpath", "-w", path])]) + else: + subprocess.Popen(["xdg-open", path])
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/util.py
Write documentation strings for class attributes
import logging from typing import Callable import numpy as np import torch import tqdm from PIL import Image from modules import devices, images, shared, torch_utils logger = logging.getLogger(__name__) def pil_image_to_torch_bgr(img: Image.Image) -> torch.Tensor: img = np.array(img.convert("RGB")) img = img[:, :, ::-1] # flip RGB to BGR img = np.transpose(img, (2, 0, 1)) # HWC to CHW img = np.ascontiguousarray(img) / 255 # Rescale to [0, 1] return torch.from_numpy(img) def torch_bgr_to_pil_image(tensor: torch.Tensor) -> Image.Image: if tensor.ndim == 4: # If we're given a tensor with a batch dimension, squeeze it out # (but only if it's a batch of size 1). if tensor.shape[0] != 1: raise ValueError(f"{tensor.shape} does not describe a BCHW tensor") tensor = tensor.squeeze(0) assert tensor.ndim == 3, f"{tensor.shape} does not describe a CHW tensor" # TODO: is `tensor.float().cpu()...numpy()` the most efficient idiom? arr = tensor.float().cpu().clamp_(0, 1).numpy() # clamp arr = 255.0 * np.moveaxis(arr, 0, 2) # CHW to HWC, rescale arr = arr.round().astype(np.uint8) arr = arr[:, :, ::-1] # flip BGR to RGB return Image.fromarray(arr, "RGB") def upscale_pil_patch(model, img: Image.Image) -> Image.Image: param = torch_utils.get_param(model) with torch.inference_mode(): tensor = pil_image_to_torch_bgr(img).unsqueeze(0) # add batch dimension tensor = tensor.to(device=param.device, dtype=param.dtype) with devices.without_autocast(): return torch_bgr_to_pil_image(model(tensor)) def upscale_with_model( model: Callable[[torch.Tensor], torch.Tensor], img: Image.Image, *, tile_size: int, tile_overlap: int = 0, desc="tiled upscale", ) -> Image.Image: if tile_size <= 0: logger.debug("Upscaling %s without tiling", img) output = upscale_pil_patch(model, img) logger.debug("=> %s", output) return output grid = images.split_grid(img, tile_size, tile_size, tile_overlap) newtiles = [] with tqdm.tqdm(total=grid.tile_count, desc=desc, disable=not shared.opts.enable_upscale_progressbar) as p: for y, h, row in grid.tiles: newrow = [] for x, w, tile in row: if shared.state.interrupted: return img output = upscale_pil_patch(model, tile) scale_factor = output.width // tile.width newrow.append([x * scale_factor, w * scale_factor, output]) p.update(1) newtiles.append([y * scale_factor, h * scale_factor, newrow]) newgrid = images.Grid( newtiles, tile_w=grid.tile_w * scale_factor, tile_h=grid.tile_h * scale_factor, image_w=grid.image_w * scale_factor, image_h=grid.image_h * scale_factor, overlap=grid.overlap * scale_factor, ) return images.combine_grid(newgrid) def tiled_upscale_2( img: torch.Tensor, model, *, tile_size: int, tile_overlap: int, scale: int, device: torch.device, desc="Tiled upscale", ): # Alternative implementation of `upscale_with_model` originally used by # SwinIR and ScuNET. It differs from `upscale_with_model` in that tiling and # weighting is done in PyTorch space, as opposed to `images.Grid` doing it in # Pillow space without weighting. b, c, h, w = img.size() tile_size = min(tile_size, h, w) if tile_size <= 0: logger.debug("Upscaling %s without tiling", img.shape) return model(img) stride = tile_size - tile_overlap h_idx_list = list(range(0, h - tile_size, stride)) + [h - tile_size] w_idx_list = list(range(0, w - tile_size, stride)) + [w - tile_size] result = torch.zeros( b, c, h * scale, w * scale, device=device, dtype=img.dtype, ) weights = torch.zeros_like(result) logger.debug("Upscaling %s to %s with tiles", img.shape, result.shape) with tqdm.tqdm(total=len(h_idx_list) * len(w_idx_list), desc=desc, disable=not shared.opts.enable_upscale_progressbar) as pbar: for h_idx in h_idx_list: if shared.state.interrupted or shared.state.skipped: break for w_idx in w_idx_list: if shared.state.interrupted or shared.state.skipped: break # Only move this patch to the device if it's not already there. in_patch = img[ ..., h_idx : h_idx + tile_size, w_idx : w_idx + tile_size, ].to(device=device) out_patch = model(in_patch) result[ ..., h_idx * scale : (h_idx + tile_size) * scale, w_idx * scale : (w_idx + tile_size) * scale, ].add_(out_patch) out_patch_mask = torch.ones_like(out_patch) weights[ ..., h_idx * scale : (h_idx + tile_size) * scale, w_idx * scale : (w_idx + tile_size) * scale, ].add_(out_patch_mask) pbar.update(1) output = result.div_(weights) return output def upscale_2( img: Image.Image, model, *, tile_size: int, tile_overlap: int, scale: int, desc: str, ): param = torch_utils.get_param(model) tensor = pil_image_to_torch_bgr(img).to(dtype=param.dtype).unsqueeze(0) # add batch dimension with torch.no_grad(): output = tiled_upscale_2( tensor, model, tile_size=tile_size, tile_overlap=tile_overlap, scale=scale, desc=desc, device=param.device, ) return torch_bgr_to_pil_image(output)
--- +++ @@ -36,6 +36,9 @@ def upscale_pil_patch(model, img: Image.Image) -> Image.Image: + """ + Upscale a given PIL image using the given model. + """ param = torch_utils.get_param(model) with torch.inference_mode(): @@ -168,6 +171,9 @@ scale: int, desc: str, ): + """ + Convenience wrapper around `tiled_upscale_2` that handles PIL images. + """ param = torch_utils.get_param(model) tensor = pil_image_to_torch_bgr(img).to(dtype=param.dtype).unsqueeze(0) # add batch dimension @@ -181,4 +187,4 @@ desc=desc, device=param.device, ) - return torch_bgr_to_pil_image(output)+ return torch_bgr_to_pil_image(output)
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/upscaler_utils.py
Write docstrings for backend logic
from abc import ABC, abstractmethod from contextlib import AsyncExitStack from typing import Any from mcp import ClientSession, StdioServerParameters from mcp.client.sse import sse_client from mcp.client.stdio import stdio_client from mcp.client.streamable_http import streamablehttp_client class MCPConnection(ABC): def __init__(self): self.session = None self._stack = None @abstractmethod def _create_context(self): async def __aenter__(self): self._stack = AsyncExitStack() await self._stack.__aenter__() try: ctx = self._create_context() result = await self._stack.enter_async_context(ctx) if len(result) == 2: read, write = result elif len(result) == 3: read, write, _ = result else: raise ValueError(f"Unexpected context result: {result}") session_ctx = ClientSession(read, write) self.session = await self._stack.enter_async_context(session_ctx) await self.session.initialize() return self except BaseException: await self._stack.__aexit__(None, None, None) raise async def __aexit__(self, exc_type, exc_val, exc_tb): if self._stack: await self._stack.__aexit__(exc_type, exc_val, exc_tb) self.session = None self._stack = None async def list_tools(self) -> list[dict[str, Any]]: response = await self.session.list_tools() return [ { "name": tool.name, "description": tool.description, "input_schema": tool.inputSchema, } for tool in response.tools ] async def call_tool(self, tool_name: str, arguments: dict[str, Any]) -> Any: result = await self.session.call_tool(tool_name, arguments=arguments) return result.content class MCPConnectionStdio(MCPConnection): def __init__(self, command: str, args: list[str] = None, env: dict[str, str] = None): super().__init__() self.command = command self.args = args or [] self.env = env def _create_context(self): return stdio_client( StdioServerParameters(command=self.command, args=self.args, env=self.env) ) class MCPConnectionSSE(MCPConnection): def __init__(self, url: str, headers: dict[str, str] = None): super().__init__() self.url = url self.headers = headers or {} def _create_context(self): return sse_client(url=self.url, headers=self.headers) class MCPConnectionHTTP(MCPConnection): def __init__(self, url: str, headers: dict[str, str] = None): super().__init__() self.url = url self.headers = headers or {} def _create_context(self): return streamablehttp_client(url=self.url, headers=self.headers) def create_connection( transport: str, command: str = None, args: list[str] = None, env: dict[str, str] = None, url: str = None, headers: dict[str, str] = None, ) -> MCPConnection: transport = transport.lower() if transport == "stdio": if not command: raise ValueError("Command is required for stdio transport") return MCPConnectionStdio(command=command, args=args, env=env) elif transport == "sse": if not url: raise ValueError("URL is required for sse transport") return MCPConnectionSSE(url=url, headers=headers) elif transport in ["http", "streamable_http", "streamable-http"]: if not url: raise ValueError("URL is required for http transport") return MCPConnectionHTTP(url=url, headers=headers) else: raise ValueError(f"Unsupported transport type: {transport}. Use 'stdio', 'sse', or 'http'")
--- +++ @@ -1,3 +1,4 @@+"""Lightweight connection handling for MCP servers.""" from abc import ABC, abstractmethod from contextlib import AsyncExitStack @@ -10,6 +11,7 @@ class MCPConnection(ABC): + """Base class for MCP server connections.""" def __init__(self): self.session = None @@ -17,8 +19,10 @@ @abstractmethod def _create_context(self): + """Create the connection context based on connection type.""" async def __aenter__(self): + """Initialize MCP server connection.""" self._stack = AsyncExitStack() await self._stack.__aenter__() @@ -42,12 +46,14 @@ raise async def __aexit__(self, exc_type, exc_val, exc_tb): + """Clean up MCP server connection resources.""" if self._stack: await self._stack.__aexit__(exc_type, exc_val, exc_tb) self.session = None self._stack = None async def list_tools(self) -> list[dict[str, Any]]: + """Retrieve available tools from the MCP server.""" response = await self.session.list_tools() return [ { @@ -59,11 +65,13 @@ ] async def call_tool(self, tool_name: str, arguments: dict[str, Any]) -> Any: + """Call a tool on the MCP server with provided arguments.""" result = await self.session.call_tool(tool_name, arguments=arguments) return result.content class MCPConnectionStdio(MCPConnection): + """MCP connection using standard input/output.""" def __init__(self, command: str, args: list[str] = None, env: dict[str, str] = None): super().__init__() @@ -78,6 +86,7 @@ class MCPConnectionSSE(MCPConnection): + """MCP connection using Server-Sent Events.""" def __init__(self, url: str, headers: dict[str, str] = None): super().__init__() @@ -89,6 +98,7 @@ class MCPConnectionHTTP(MCPConnection): + """MCP connection using Streamable HTTP.""" def __init__(self, url: str, headers: dict[str, str] = None): super().__init__() @@ -107,6 +117,19 @@ url: str = None, headers: dict[str, str] = None, ) -> MCPConnection: + """Factory function to create the appropriate MCP connection. + + Args: + transport: Connection type ("stdio", "sse", or "http") + command: Command to run (stdio only) + args: Command arguments (stdio only) + env: Environment variables (stdio only) + url: Server URL (sse and http only) + headers: HTTP headers (sse and http only) + + Returns: + MCPConnection instance + """ transport = transport.lower() if transport == "stdio": @@ -125,4 +148,4 @@ return MCPConnectionHTTP(url=url, headers=headers) else: - raise ValueError(f"Unsupported transport type: {transport}. Use 'stdio', 'sse', or 'http'")+ raise ValueError(f"Unsupported transport type: {transport}. Use 'stdio', 'sse', or 'http'")
https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/mcp-builder/scripts/connections.py
Create structured documentation for my script
import math from dataclasses import dataclass from typing import Tuple, Optional, Literal import torch from torch import nn import torch.nn.functional as F import torch.distributed as dist from kernel import act_quant, weight_dequant, fp8_gemm world_size = 1 rank = 0 block_size = 128 gemm_impl: Literal["bf16", "fp8"] = "bf16" attn_impl: Literal["naive", "absorb"] = "absorb" @dataclass class ModelArgs: max_batch_size: int = 8 max_seq_len: int = 4096 * 4 dtype: Literal["bf16", "fp8"] = "bf16" scale_fmt: Optional[str] = None vocab_size: int = 102400 dim: int = 2048 inter_dim: int = 10944 moe_inter_dim: int = 1408 n_layers: int = 27 n_dense_layers: int = 1 n_heads: int = 16 # moe n_routed_experts: int = 64 n_shared_experts: int = 2 n_activated_experts: int = 6 n_expert_groups: int = 1 n_limited_groups: int = 1 score_func: Literal["softmax", "sigmoid"] = "softmax" route_scale: float = 1. # mla q_lora_rank: int = 0 kv_lora_rank: int = 512 qk_nope_head_dim: int = 128 qk_rope_head_dim: int = 64 v_head_dim: int = 128 # yarn original_seq_len: int = 4096 rope_theta: float = 10000.0 rope_factor: float = 40 beta_fast: int = 32 beta_slow: int = 1 mscale: float = 1. class ParallelEmbedding(nn.Module): def __init__(self, vocab_size: int, dim: int): super().__init__() self.vocab_size = vocab_size self.dim = dim assert vocab_size % world_size == 0, f"Vocabulary size must be divisible by world size (world_size={world_size})" self.part_vocab_size = (vocab_size // world_size) self.vocab_start_idx = rank * self.part_vocab_size self.vocab_end_idx = self.vocab_start_idx + self.part_vocab_size self.weight = nn.Parameter(torch.empty(self.part_vocab_size, self.dim)) def forward(self, x: torch.Tensor) -> torch.Tensor: if world_size > 1: mask = (x < self.vocab_start_idx) | (x >= self.vocab_end_idx) x = x - self.vocab_start_idx x[mask] = 0 y = F.embedding(x, self.weight) if world_size > 1: y[mask] = 0 dist.all_reduce(y) return y def linear(x: torch.Tensor, weight: torch.Tensor, bias: Optional[torch.Tensor] = None, scale_fmt: Optional[str] = None) -> torch.Tensor: if weight.element_size() > 1: return F.linear(x, weight, bias) elif gemm_impl == "bf16": weight = weight_dequant(weight, weight.scale) return F.linear(x, weight, bias) else: x, scale = act_quant(x, block_size, scale_fmt) y = fp8_gemm(x, scale, weight, weight.scale) if bias is not None: y += bias return y class Linear(nn.Module): dtype = torch.bfloat16 scale_fmt: Optional[str] = None def __init__(self, in_features: int, out_features: int, bias: bool = False, dtype = None): super().__init__() self.in_features = in_features self.out_features = out_features self.weight = nn.Parameter(torch.empty(out_features, in_features, dtype=dtype or Linear.dtype)) if self.weight.element_size() == 1: scale_out_features = (out_features + block_size - 1) // block_size scale_in_features = (in_features + block_size - 1) // block_size self.weight.scale = self.scale = nn.Parameter(torch.empty(scale_out_features, scale_in_features, dtype=torch.float32)) else: self.register_parameter("scale", None) if bias: self.bias = nn.Parameter(torch.empty(out_features)) else: self.register_parameter("bias", None) def forward(self, x: torch.Tensor) -> torch.Tensor: return linear(x, self.weight, self.bias, self.scale_fmt) class ColumnParallelLinear(Linear): def __init__(self, in_features: int, out_features: int, bias: bool = False, dtype = None): assert out_features % world_size == 0, f"Output features must be divisible by world size (world_size={world_size})" self.part_out_features = out_features // world_size super().__init__(in_features, self.part_out_features, bias, dtype) def forward(self, x: torch.Tensor) -> torch.Tensor: y = linear(x, self.weight, self.bias) return y class RowParallelLinear(Linear): def __init__(self, in_features: int, out_features: int, bias: bool = False, dtype = None): assert in_features % world_size == 0, f"Input features must be divisible by world size (world_size={world_size})" self.part_in_features = in_features // world_size super().__init__(self.part_in_features, out_features, bias, dtype) def forward(self, x: torch.Tensor) -> torch.Tensor: y = linear(x, self.weight) if world_size > 1: dist.all_reduce(y) if self.bias is not None: y += self.bias return y class RMSNorm(nn.Module): def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.dim = dim self.eps = eps self.weight = nn.Parameter(torch.ones(dim)) def forward(self, x: torch.Tensor): return F.rms_norm(x, (self.dim,), self.weight, self.eps) def precompute_freqs_cis(args: ModelArgs) -> torch.Tensor: dim = args.qk_rope_head_dim seqlen = args.max_seq_len beta_fast = args.beta_fast beta_slow = args.beta_slow base = args.rope_theta factor = args.rope_factor def find_correction_dim(num_rotations, dim, base, max_seq_len): return dim * math.log(max_seq_len / (num_rotations * 2 * math.pi)) / (2 * math.log(base)) def find_correction_range(low_rot, high_rot, dim, base, max_seq_len): low = math.floor(find_correction_dim(low_rot, dim, base, max_seq_len)) high = math.ceil(find_correction_dim(high_rot, dim, base, max_seq_len)) return max(low, 0), min(high, dim-1) def linear_ramp_factor(min, max, dim): if min == max: max += 0.001 linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min) ramp_func = torch.clamp(linear_func, 0, 1) return ramp_func freqs = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim)) if seqlen > args.original_seq_len: low, high = find_correction_range(beta_fast, beta_slow, dim, base, args.original_seq_len) smooth = 1 - linear_ramp_factor(low, high, dim // 2) freqs = freqs / factor * (1 - smooth) + freqs * smooth t = torch.arange(seqlen) freqs = torch.outer(t, freqs) freqs_cis = torch.polar(torch.ones_like(freqs), freqs) return freqs_cis def apply_rotary_emb(x: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor: dtype = x.dtype x = torch.view_as_complex(x.float().view(*x.shape[:-1], -1, 2)) freqs_cis = freqs_cis.view(1, x.size(1), 1, x.size(-1)) y = torch.view_as_real(x * freqs_cis).flatten(3) return y.to(dtype) class MLA(nn.Module): def __init__(self, args: ModelArgs): super().__init__() self.dim = args.dim self.n_heads = args.n_heads self.n_local_heads = args.n_heads // world_size self.q_lora_rank = args.q_lora_rank self.kv_lora_rank = args.kv_lora_rank self.qk_nope_head_dim = args.qk_nope_head_dim self.qk_rope_head_dim = args.qk_rope_head_dim self.qk_head_dim = args.qk_nope_head_dim + args.qk_rope_head_dim self.v_head_dim = args.v_head_dim if self.q_lora_rank == 0: self.wq = ColumnParallelLinear(self.dim, self.n_heads * self.qk_head_dim) else: self.wq_a = Linear(self.dim, self.q_lora_rank) self.q_norm = RMSNorm(self.q_lora_rank) self.wq_b = ColumnParallelLinear(self.q_lora_rank, self.n_heads * self.qk_head_dim) self.wkv_a = Linear(self.dim, self.kv_lora_rank + self.qk_rope_head_dim) self.kv_norm = RMSNorm(self.kv_lora_rank) self.wkv_b = ColumnParallelLinear(self.kv_lora_rank, self.n_heads * (self.qk_nope_head_dim + self.v_head_dim)) self.wo = RowParallelLinear(self.n_heads * self.v_head_dim, self.dim) self.softmax_scale = self.qk_head_dim ** -0.5 if args.max_seq_len > args.original_seq_len: mscale = 0.1 * args.mscale * math.log(args.rope_factor) + 1.0 self.softmax_scale = self.softmax_scale * mscale * mscale if attn_impl == "naive": self.register_buffer("k_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.n_local_heads, self.qk_head_dim), persistent=False) self.register_buffer("v_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.n_local_heads, self.v_head_dim), persistent=False) else: self.register_buffer("kv_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.kv_lora_rank), persistent=False) self.register_buffer("pe_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.qk_rope_head_dim), persistent=False) def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]): bsz, seqlen, _ = x.size() end_pos = start_pos + seqlen if self.q_lora_rank == 0: q = self.wq(x) else: q = self.wq_b(self.q_norm(self.wq_a(x))) q = q.view(bsz, seqlen, self.n_local_heads, self.qk_head_dim) q_nope, q_pe = torch.split(q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1) q_pe = apply_rotary_emb(q_pe, freqs_cis) kv = self.wkv_a(x) kv, k_pe = torch.split(kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1) k_pe = apply_rotary_emb(k_pe.unsqueeze(2), freqs_cis) if attn_impl == "naive": q = torch.cat([q_nope, q_pe], dim=-1) kv = self.wkv_b(self.kv_norm(kv)) kv = kv.view(bsz, seqlen, self.n_local_heads, self.qk_nope_head_dim + self.v_head_dim) k_nope, v = torch.split(kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1) k = torch.cat([k_nope, k_pe.expand(-1, -1, self.n_local_heads, -1)], dim=-1) self.k_cache[:bsz, start_pos:end_pos] = k self.v_cache[:bsz, start_pos:end_pos] = v scores = torch.einsum("bshd,bthd->bsht", q, self.k_cache[:bsz, :end_pos]) * self.softmax_scale else: wkv_b = self.wkv_b.weight if self.wkv_b.scale is None else weight_dequant(self.wkv_b.weight, self.wkv_b.scale, block_size) wkv_b = wkv_b.view(self.n_local_heads, -1, self.kv_lora_rank) q_nope = torch.einsum("bshd,hdc->bshc", q_nope, wkv_b[:, :self.qk_nope_head_dim]) self.kv_cache[:bsz, start_pos:end_pos] = self.kv_norm(kv) self.pe_cache[:bsz, start_pos:end_pos] = k_pe.squeeze(2) scores = (torch.einsum("bshc,btc->bsht", q_nope, self.kv_cache[:bsz, :end_pos]) + torch.einsum("bshr,btr->bsht", q_pe, self.pe_cache[:bsz, :end_pos])) * self.softmax_scale if mask is not None: scores += mask.unsqueeze(1) scores = scores.softmax(dim=-1, dtype=torch.float32).type_as(x) if attn_impl == "naive": x = torch.einsum("bsht,bthd->bshd", scores, self.v_cache[:bsz, :end_pos]) else: x = torch.einsum("bsht,btc->bshc", scores, self.kv_cache[:bsz, :end_pos]) x = torch.einsum("bshc,hdc->bshd", x, wkv_b[:, -self.v_head_dim:]) x = self.wo(x.flatten(2)) return x class MLP(nn.Module): def __init__(self, dim: int, inter_dim: int): super().__init__() self.w1 = ColumnParallelLinear(dim, inter_dim) self.w2 = RowParallelLinear(inter_dim, dim) self.w3 = ColumnParallelLinear(dim, inter_dim) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.w2(F.silu(self.w1(x)) * self.w3(x)) class Gate(nn.Module): def __init__(self, args: ModelArgs): super().__init__() self.dim = args.dim self.topk = args.n_activated_experts self.n_groups = args.n_expert_groups self.topk_groups = args.n_limited_groups self.score_func = args.score_func self.route_scale = args.route_scale self.weight = nn.Parameter(torch.empty(args.n_routed_experts, args.dim)) self.bias = nn.Parameter(torch.empty(args.n_routed_experts, dtype=torch.float32)) if self.dim == 7168 else None def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: scores = linear(x, self.weight) if self.score_func == "softmax": scores = scores.softmax(dim=-1, dtype=torch.float32) else: scores = scores.sigmoid() original_scores = scores if self.bias is not None: scores = scores + self.bias if self.n_groups > 1: scores = scores.view(x.size(0), self.n_groups, -1) if self.bias is None: group_scores = scores.amax(dim=-1) else: group_scores = scores.topk(2, dim=-1)[0].sum(dim=-1) indices = group_scores.topk(self.topk_groups, dim=-1)[1] mask = scores.new_ones(x.size(0), self.n_groups, dtype=bool).scatter_(1, indices, False) scores = scores.masked_fill_(mask.unsqueeze(-1), float("-inf")).flatten(1) indices = torch.topk(scores, self.topk, dim=-1)[1] weights = original_scores.gather(1, indices) if self.score_func == "sigmoid": weights /= weights.sum(dim=-1, keepdim=True) weights *= self.route_scale return weights.type_as(x), indices class Expert(nn.Module): def __init__(self, dim: int, inter_dim: int): super().__init__() self.w1 = Linear(dim, inter_dim) self.w2 = Linear(inter_dim, dim) self.w3 = Linear(dim, inter_dim) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.w2(F.silu(self.w1(x)) * self.w3(x)) class MoE(nn.Module): def __init__(self, args: ModelArgs): super().__init__() self.dim = args.dim assert args.n_routed_experts % world_size == 0, f"Number of experts must be divisible by world size (world_size={world_size})" self.n_routed_experts = args.n_routed_experts self.n_local_experts = args.n_routed_experts // world_size self.n_activated_experts = args.n_activated_experts self.experts_start_idx = rank * self.n_local_experts self.experts_end_idx = self.experts_start_idx + self.n_local_experts self.gate = Gate(args) self.experts = nn.ModuleList([Expert(args.dim, args.moe_inter_dim) if self.experts_start_idx <= i < self.experts_end_idx else None for i in range(self.n_routed_experts)]) self.shared_experts = MLP(args.dim, args.n_shared_experts * args.moe_inter_dim) def forward(self, x: torch.Tensor) -> torch.Tensor: shape = x.size() x = x.view(-1, self.dim) weights, indices = self.gate(x) y = torch.zeros_like(x) counts = torch.bincount(indices.flatten(), minlength=self.n_routed_experts).tolist() for i in range(self.experts_start_idx, self.experts_end_idx): if counts[i] == 0: continue expert = self.experts[i] idx, top = torch.where(indices == i) y[idx] += expert(x[idx]) * weights[idx, top, None] z = self.shared_experts(x) if world_size > 1: dist.all_reduce(y) return (y + z).view(shape) class Block(nn.Module): def __init__(self, layer_id: int, args: ModelArgs): super().__init__() self.attn = MLA(args) self.ffn = MLP(args.dim, args.inter_dim) if layer_id < args.n_dense_layers else MoE(args) self.attn_norm = RMSNorm(args.dim) self.ffn_norm = RMSNorm(args.dim) def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]) -> torch.Tensor: x = x + self.attn(self.attn_norm(x), start_pos, freqs_cis, mask) x = x + self.ffn(self.ffn_norm(x)) return x class Transformer(nn.Module): def __init__(self, args: ModelArgs): global world_size, rank world_size = dist.get_world_size() if dist.is_initialized() else 1 rank = dist.get_rank() if dist.is_initialized() else 0 Linear.dtype = torch.float8_e4m3fn if args.dtype == "fp8" else torch.bfloat16 Linear.scale_fmt = args.scale_fmt super().__init__() self.max_seq_len = args.max_seq_len self.embed = ParallelEmbedding(args.vocab_size, args.dim) self.layers = torch.nn.ModuleList() for layer_id in range(args.n_layers): self.layers.append(Block(layer_id, args)) self.norm = RMSNorm(args.dim) self.head = ColumnParallelLinear(args.dim, args.vocab_size, dtype=torch.get_default_dtype()) self.register_buffer("freqs_cis", precompute_freqs_cis(args), persistent=False) @torch.inference_mode() def forward(self, tokens: torch.Tensor, start_pos: int = 0): seqlen = tokens.size(1) h = self.embed(tokens) freqs_cis = self.freqs_cis[start_pos:start_pos+seqlen] mask = None if seqlen > 1: mask = torch.full((seqlen, seqlen), float("-inf"), device=tokens.device).triu_(1) for layer in self.layers: h = layer(h, start_pos, freqs_cis, mask) h = self.norm(h)[:, -1] logits = self.head(h) if world_size > 1: all_logits = [torch.empty_like(logits) for _ in range(world_size)] dist.all_gather(all_logits, logits) logits = torch.cat(all_logits, dim=-1) return logits if __name__ == "__main__": torch.set_default_dtype(torch.bfloat16) torch.set_default_device("cuda") torch.manual_seed(0) args = ModelArgs() x = torch.randint(0, args.vocab_size, (2, 128)) model = Transformer(args) print(model(x).size())
--- +++ @@ -18,6 +18,40 @@ @dataclass class ModelArgs: + """ + Data class for defining model arguments and hyperparameters. + + Attributes: + max_batch_size (int): Maximum batch size. + max_seq_len (int): Maximum sequence length. + dtype (Literal["bf16", "fp8"]): Data type for computations. + scale_fmt (Optional[str]): Format for quantization scale. + vocab_size (int): Vocabulary size. + dim (int): Model dimension. + inter_dim (int): Intermediate dimension for MLP layers. + moe_inter_dim (int): Intermediate dimension for MoE layers. + n_layers (int): Number of transformer layers. + n_dense_layers (int): Number of dense layers in the model. + n_heads (int): Number of attention heads. + n_routed_experts (int): Number of routed experts for MoE layers. + n_shared_experts (int): Number of shared experts for MoE layers. + n_activated_experts (int): Number of activated experts in MoE layers. + n_expert_groups (int): Number of expert groups. + n_limited_groups (int): Number of limited groups for MoE routing. + score_func (Literal["softmax", "sigmoid"]): Scoring function for MoE routing. + route_scale (float): Scaling factor for routing scores. + q_lora_rank (int): LoRA rank for query projections. + kv_lora_rank (int): LoRA rank for key-value projections. + qk_nope_head_dim (int): Dimension for query-key projections without positional embeddings. + qk_rope_head_dim (int): Dimension for query-key projections with rotary embeddings. + v_head_dim (int): Dimension for value projections. + original_seq_len (int): Original sequence length. + rope_theta (float): Base for rotary positional encoding. + rope_factor (float): Scaling factor for extended sequence lengths. + beta_fast (int): Fast beta correction factor. + beta_slow (int): Slow beta correction factor. + mscale (float): Scaling factor for extended attention. + """ max_batch_size: int = 8 max_seq_len: int = 4096 * 4 dtype: Literal["bf16", "fp8"] = "bf16" @@ -53,6 +87,13 @@ class ParallelEmbedding(nn.Module): + """ + Embedding layer with parallelism support across distributed processes. + + Args: + vocab_size (int): Vocabulary size. + dim (int): Embedding dimension. + """ def __init__(self, vocab_size: int, dim: int): super().__init__() self.vocab_size = vocab_size @@ -64,6 +105,18 @@ self.weight = nn.Parameter(torch.empty(self.part_vocab_size, self.dim)) def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Forward pass for parallel embedding layer. + + Args: + x (torch.Tensor): Input tensor containing token indices. + + Returns: + torch.Tensor: Embedded representations. + + Raises: + ValueError: If `world_size` is not defined. + """ if world_size > 1: mask = (x < self.vocab_start_idx) | (x >= self.vocab_end_idx) x = x - self.vocab_start_idx @@ -76,6 +129,27 @@ def linear(x: torch.Tensor, weight: torch.Tensor, bias: Optional[torch.Tensor] = None, scale_fmt: Optional[str] = None) -> torch.Tensor: + """ + Applies a linear transformation to the incoming data: y = xA^T + b. + This function supports specialized implementations based on quantization + and tensor formats. + + Args: + x (torch.Tensor): The input tensor. + weight (torch.Tensor): The weight tensor. It may be quantized and + requires dequantization for certain cases. + bias (Optional[torch.Tensor]): The bias tensor to be added. Default is None. + + Returns: + torch.Tensor: The result of the linear transformation, which may involve + quantization-aware computations depending on the input parameters. + + Notes: + - If `weight` is quantized (e.g., `element_size() == 1`), a dequantized version + is used for computation. + - If `gemm_impl == "bf16"`, dequantization and a `bf16` GEMM operation are applied. + - For other cases, the function applies quantization to `x` and uses `fp8_gemm` for computation. + """ if weight.element_size() > 1: return F.linear(x, weight, bias) elif gemm_impl == "bf16": @@ -90,6 +164,15 @@ class Linear(nn.Module): + """ + Custom linear layer with support for quantized weights and optional bias. + + Args: + in_features (int): Number of input features. + out_features (int): Number of output features. + bias (bool): Whether to include a bias term. Defaults to False. + dtype (optional): Data type for the layer. Defaults to `torch.bfloat16`. + """ dtype = torch.bfloat16 scale_fmt: Optional[str] = None @@ -110,27 +193,72 @@ self.register_parameter("bias", None) def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Forward pass for the custom linear layer. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + torch.Tensor: Transformed tensor after linear computation. + """ return linear(x, self.weight, self.bias, self.scale_fmt) class ColumnParallelLinear(Linear): + """ + Linear layer with column parallelism, splitting output features across distributed processes. + + Args: + in_features (int): Number of input features. + out_features (int): Total number of output features. + bias (bool): Whether to include a bias term. Defaults to False. + dtype (optional): Data type for the layer. Defaults to `torch.bfloat16`. + """ def __init__(self, in_features: int, out_features: int, bias: bool = False, dtype = None): assert out_features % world_size == 0, f"Output features must be divisible by world size (world_size={world_size})" self.part_out_features = out_features // world_size super().__init__(in_features, self.part_out_features, bias, dtype) def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Forward pass for column parallel linear layer. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + torch.Tensor: Transformed tensor with column-parallel computation. + """ y = linear(x, self.weight, self.bias) return y class RowParallelLinear(Linear): + """ + Linear layer with row parallelism, splitting input features across distributed processes. + + Args: + in_features (int): Total number of input features. + out_features (int): Number of output features. + bias (bool): Whether to include a bias term. Defaults to False. + dtype (optional): Data type for the layer. Defaults to `torch.bfloat16`. + """ def __init__(self, in_features: int, out_features: int, bias: bool = False, dtype = None): assert in_features % world_size == 0, f"Input features must be divisible by world size (world_size={world_size})" self.part_in_features = in_features // world_size super().__init__(self.part_in_features, out_features, bias, dtype) def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Forward pass for row parallel linear layer. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + torch.Tensor: Transformed tensor with row-parallel computation. + """ y = linear(x, self.weight) if world_size > 1: dist.all_reduce(y) @@ -140,6 +268,13 @@ class RMSNorm(nn.Module): + """ + Root Mean Square Layer Normalization (RMSNorm). + + Args: + dim (int): Dimension of the input tensor. + eps (float): Epsilon value for numerical stability. Defaults to 1e-6. + """ def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.dim = dim @@ -147,10 +282,28 @@ self.weight = nn.Parameter(torch.ones(dim)) def forward(self, x: torch.Tensor): + """ + Forward pass for RMSNorm. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + torch.Tensor: Normalized tensor with the same shape as input. + """ return F.rms_norm(x, (self.dim,), self.weight, self.eps) def precompute_freqs_cis(args: ModelArgs) -> torch.Tensor: + """ + Precomputes frequency-based complex exponential values for rotary positional embeddings. + + Args: + args (ModelArgs): Model arguments containing positional embedding parameters. + + Returns: + torch.Tensor: Precomputed complex exponential values for positional embeddings. + """ dim = args.qk_rope_head_dim seqlen = args.max_seq_len beta_fast = args.beta_fast @@ -159,14 +312,51 @@ factor = args.rope_factor def find_correction_dim(num_rotations, dim, base, max_seq_len): + """ + Computes the correction dimension for a given number of rotations in the rotary positional embedding. + + Args: + num_rotations (float): Number of rotations to compute the correction for. + dim (int): Dimensionality of the embedding space. + base (float): Base value for the exponential computation. + max_seq_len (int): Maximum sequence length. + + Returns: + float: The correction dimension based on the input parameters. + """ return dim * math.log(max_seq_len / (num_rotations * 2 * math.pi)) / (2 * math.log(base)) def find_correction_range(low_rot, high_rot, dim, base, max_seq_len): + """ + Computes the range of correction dimensions for rotary positional embeddings. + + Args: + low_rot (float): Lower bound for the number of rotations. + high_rot (float): Upper bound for the number of rotations. + dim (int): Dimensionality of the embedding space. + base (float): Base value for the exponential computation. + max_seq_len (int): Maximum sequence length. + + Returns: + Tuple[int, int]: The range of correction dimensions (low, high), clamped to valid indices. + """ low = math.floor(find_correction_dim(low_rot, dim, base, max_seq_len)) high = math.ceil(find_correction_dim(high_rot, dim, base, max_seq_len)) return max(low, 0), min(high, dim-1) def linear_ramp_factor(min, max, dim): + """ + Computes a linear ramp function used to smooth values between a minimum and maximum range. + + Args: + min (float): Minimum value for the ramp function. + max (float): Maximum value for the ramp function. + dim (int): Dimensionality of the ramp tensor. + + Returns: + torch.Tensor: A tensor of shape (dim,) with values linearly interpolated between 0 and 1, + clamped to the range [0, 1]. + """ if min == max: max += 0.001 linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min) @@ -186,6 +376,16 @@ def apply_rotary_emb(x: torch.Tensor, freqs_cis: torch.Tensor) -> torch.Tensor: + """ + Applies rotary positional embeddings to the input tensor. + + Args: + x (torch.Tensor): Input tensor with positional embeddings to be applied. + freqs_cis (torch.Tensor): Precomputed complex exponential values for positional embeddings. + + Returns: + torch.Tensor: Tensor with rotary embeddings applied. + """ dtype = x.dtype x = torch.view_as_complex(x.float().view(*x.shape[:-1], -1, 2)) freqs_cis = freqs_cis.view(1, x.size(1), 1, x.size(-1)) @@ -194,6 +394,21 @@ class MLA(nn.Module): + """ + Multi-Head Latent Attention (MLA) Layer. + + Attributes: + dim (int): Dimensionality of the input features. + n_heads (int): Number of attention heads. + n_local_heads (int): Number of local attention heads for distributed systems. + q_lora_rank (int): Rank for low-rank query projection. + kv_lora_rank (int): Rank for low-rank key/value projection. + qk_nope_head_dim (int): Dimensionality of non-positional query/key projections. + qk_rope_head_dim (int): Dimensionality of rotary-positional query/key projections. + qk_head_dim (int): Total dimensionality of query/key projections. + v_head_dim (int): Dimensionality of value projections. + softmax_scale (float): Scaling factor for softmax in attention computation. + """ def __init__(self, args: ModelArgs): super().__init__() self.dim = args.dim @@ -229,6 +444,18 @@ self.register_buffer("pe_cache", torch.zeros(args.max_batch_size, args.max_seq_len, self.qk_rope_head_dim), persistent=False) def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]): + """ + Forward pass for the Multi-Head Latent Attention (MLA) Layer. + + Args: + x (torch.Tensor): Input tensor of shape (batch_size, seq_len, dim). + start_pos (int): Starting position in the sequence for caching. + freqs_cis (torch.Tensor): Precomputed complex exponential values for rotary embeddings. + mask (Optional[torch.Tensor]): Mask tensor to exclude certain positions from attention. + + Returns: + torch.Tensor: Output tensor with the same shape as the input. + """ bsz, seqlen, _ = x.size() end_pos = start_pos + seqlen if self.q_lora_rank == 0: @@ -271,18 +498,61 @@ class MLP(nn.Module): + """ + Multi-Layer Perceptron (MLP) used as a feed-forward layer. + + Attributes: + w1 (nn.Module): Linear layer for input-to-hidden transformation. + w2 (nn.Module): Linear layer for hidden-to-output transformation. + w3 (nn.Module): Additional linear layer for feature transformation. + """ def __init__(self, dim: int, inter_dim: int): + """ + Initializes the MLP layer. + + Args: + dim (int): Input and output dimensionality. + inter_dim (int): Hidden layer dimensionality. + """ super().__init__() self.w1 = ColumnParallelLinear(dim, inter_dim) self.w2 = RowParallelLinear(inter_dim, dim) self.w3 = ColumnParallelLinear(dim, inter_dim) def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Forward pass for the MLP layer. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + torch.Tensor: Output tensor after MLP computation. + """ return self.w2(F.silu(self.w1(x)) * self.w3(x)) class Gate(nn.Module): + """ + Gating mechanism for routing inputs in a mixture-of-experts (MoE) model. + + Attributes: + dim (int): Dimensionality of input features. + topk (int): Number of top experts activated for each input. + n_groups (int): Number of groups for routing. + topk_groups (int): Number of groups to route inputs to. + score_func (str): Scoring function ('softmax' or 'sigmoid'). + route_scale (float): Scaling factor for routing weights. + weight (torch.nn.Parameter): Learnable weights for the gate. + bias (Optional[torch.nn.Parameter]): Optional bias term for the gate. + """ def __init__(self, args: ModelArgs): + """ + Initializes the Gate module. + + Args: + args (ModelArgs): Model arguments containing gating parameters. + """ super().__init__() self.dim = args.dim self.topk = args.n_activated_experts @@ -294,6 +564,15 @@ self.bias = nn.Parameter(torch.empty(args.n_routed_experts, dtype=torch.float32)) if self.dim == 7168 else None def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Forward pass for the gating mechanism. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + Tuple[torch.Tensor, torch.Tensor]: Routing weights and selected expert indices. + """ scores = linear(x, self.weight) if self.score_func == "softmax": scores = scores.softmax(dim=-1, dtype=torch.float32) @@ -320,18 +599,60 @@ class Expert(nn.Module): + """ + Expert layer for Mixture-of-Experts (MoE) models. + + Attributes: + w1 (nn.Module): Linear layer for input-to-hidden transformation. + w2 (nn.Module): Linear layer for hidden-to-output transformation. + w3 (nn.Module): Additional linear layer for feature transformation. + """ def __init__(self, dim: int, inter_dim: int): + """ + Initializes the Expert layer. + + Args: + dim (int): Input and output dimensionality. + inter_dim (int): Hidden layer dimensionality. + """ super().__init__() self.w1 = Linear(dim, inter_dim) self.w2 = Linear(inter_dim, dim) self.w3 = Linear(dim, inter_dim) def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Forward pass for the Expert layer. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + torch.Tensor: Output tensor after expert computation. + """ return self.w2(F.silu(self.w1(x)) * self.w3(x)) class MoE(nn.Module): + """ + Mixture-of-Experts (MoE) module. + + Attributes: + dim (int): Dimensionality of input features. + n_routed_experts (int): Total number of experts in the model. + n_local_experts (int): Number of experts handled locally in distributed systems. + n_activated_experts (int): Number of experts activated for each input. + gate (nn.Module): Gating mechanism to route inputs to experts. + experts (nn.ModuleList): List of expert modules. + shared_experts (nn.Module): Shared experts applied to all inputs. + """ def __init__(self, args: ModelArgs): + """ + Initializes the MoE module. + + Args: + args (ModelArgs): Model arguments containing MoE parameters. + """ super().__init__() self.dim = args.dim assert args.n_routed_experts % world_size == 0, f"Number of experts must be divisible by world size (world_size={world_size})" @@ -346,6 +667,15 @@ self.shared_experts = MLP(args.dim, args.n_shared_experts * args.moe_inter_dim) def forward(self, x: torch.Tensor) -> torch.Tensor: + """ + Forward pass for the MoE module. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + torch.Tensor: Output tensor after expert routing and computation. + """ shape = x.size() x = x.view(-1, self.dim) weights, indices = self.gate(x) @@ -364,7 +694,23 @@ class Block(nn.Module): + """ + Transformer block combining attention and feed-forward layers. + + Attributes: + attn (nn.Module): Attention layer (MLA). + ffn (nn.Module): Feed-forward network (MLP or MoE). + attn_norm (nn.Module): Layer normalization for attention. + ffn_norm (nn.Module): Layer normalization for feed-forward network. + """ def __init__(self, layer_id: int, args: ModelArgs): + """ + Initializes the Transformer block. + + Args: + layer_id (int): Layer index in the transformer. + args (ModelArgs): Model arguments containing block parameters. + """ super().__init__() self.attn = MLA(args) self.ffn = MLP(args.dim, args.inter_dim) if layer_id < args.n_dense_layers else MoE(args) @@ -372,13 +718,42 @@ self.ffn_norm = RMSNorm(args.dim) def forward(self, x: torch.Tensor, start_pos: int, freqs_cis: torch.Tensor, mask: Optional[torch.Tensor]) -> torch.Tensor: + """ + Forward pass for the Transformer block. + + Args: + x (torch.Tensor): Input tensor. + start_pos (int): Starting position in the sequence. + freqs_cis (torch.Tensor): Precomputed complex exponential values for rotary embeddings. + mask (Optional[torch.Tensor]): Mask tensor to exclude certain positions from attention. + + Returns: + torch.Tensor: Output tensor after block computation. + """ x = x + self.attn(self.attn_norm(x), start_pos, freqs_cis, mask) x = x + self.ffn(self.ffn_norm(x)) return x class Transformer(nn.Module): + """ + Transformer model with positional embeddings, multiple layers, and output projection. + + Attributes: + max_seq_len (int): Maximum sequence length for the transformer. + embed (nn.Module): Embedding layer for input tokens. + layers (torch.nn.ModuleList): List of transformer blocks. + norm (nn.Module): Layer normalization applied after all blocks. + head (nn.Module): Output projection layer mapping to vocabulary size. + freqs_cis (torch.Tensor): Precomputed complex exponential values for rotary embeddings. + """ def __init__(self, args: ModelArgs): + """ + Initializes the Transformer model. + + Args: + args (ModelArgs): Model arguments containing transformer parameters. + """ global world_size, rank world_size = dist.get_world_size() if dist.is_initialized() else 1 rank = dist.get_rank() if dist.is_initialized() else 0 @@ -396,6 +771,16 @@ @torch.inference_mode() def forward(self, tokens: torch.Tensor, start_pos: int = 0): + """ + Forward pass for the Transformer model. + + Args: + tokens (torch.Tensor): Input tensor of token IDs with shape (batch_size, seq_len). + start_pos (int, optional): Starting position in the sequence for rotary embeddings. Defaults to 0. + + Returns: + torch.Tensor: Logits tensor of shape (batch_size, vocab_size). + """ seqlen = tokens.size(1) h = self.embed(tokens) freqs_cis = self.freqs_cis[start_pos:start_pos+seqlen] @@ -420,4 +805,4 @@ args = ModelArgs() x = torch.randint(0, args.vocab_size, (2, 128)) model = Transformer(args) - print(model(x).size())+ print(model(x).size())
https://raw.githubusercontent.com/deepseek-ai/DeepSeek-V3/HEAD/inference/model.py
Annotate my code with docstrings
from collections import namedtuple from copy import copy from itertools import permutations, chain import random import csv import os.path from io import StringIO from PIL import Image import numpy as np import modules.scripts as scripts import gradio as gr from modules import images, sd_samplers, processing, sd_models, sd_vae, sd_schedulers, errors from modules.processing import process_images, Processed, StableDiffusionProcessingTxt2Img from modules.shared import opts, state import modules.shared as shared import modules.sd_samplers import modules.sd_models import modules.sd_vae import re from modules.ui_components import ToolButton fill_values_symbol = "\U0001f4d2" # 📒 AxisInfo = namedtuple('AxisInfo', ['axis', 'values']) def apply_field(field): def fun(p, x, xs): setattr(p, field, x) return fun def apply_prompt(p, x, xs): if xs[0] not in p.prompt and xs[0] not in p.negative_prompt: raise RuntimeError(f"Prompt S/R did not find {xs[0]} in prompt or negative prompt.") p.prompt = p.prompt.replace(xs[0], x) p.negative_prompt = p.negative_prompt.replace(xs[0], x) def apply_order(p, x, xs): token_order = [] # Initially grab the tokens from the prompt, so they can be replaced in order of earliest seen for token in x: token_order.append((p.prompt.find(token), token)) token_order.sort(key=lambda t: t[0]) prompt_parts = [] # Split the prompt up, taking out the tokens for _, token in token_order: n = p.prompt.find(token) prompt_parts.append(p.prompt[0:n]) p.prompt = p.prompt[n + len(token):] # Rebuild the prompt with the tokens in the order we want prompt_tmp = "" for idx, part in enumerate(prompt_parts): prompt_tmp += part prompt_tmp += x[idx] p.prompt = prompt_tmp + p.prompt def confirm_samplers(p, xs): for x in xs: if x.lower() not in sd_samplers.samplers_map: raise RuntimeError(f"Unknown sampler: {x}") def apply_checkpoint(p, x, xs): info = modules.sd_models.get_closet_checkpoint_match(x) if info is None: raise RuntimeError(f"Unknown checkpoint: {x}") p.override_settings['sd_model_checkpoint'] = info.name def confirm_checkpoints(p, xs): for x in xs: if modules.sd_models.get_closet_checkpoint_match(x) is None: raise RuntimeError(f"Unknown checkpoint: {x}") def confirm_checkpoints_or_none(p, xs): for x in xs: if x in (None, "", "None", "none"): continue if modules.sd_models.get_closet_checkpoint_match(x) is None: raise RuntimeError(f"Unknown checkpoint: {x}") def confirm_range(min_val, max_val, axis_label): def confirm_range_fun(p, xs): for x in xs: if not (max_val >= x >= min_val): raise ValueError(f'{axis_label} value "{x}" out of range [{min_val}, {max_val}]') return confirm_range_fun def apply_size(p, x: str, xs) -> None: try: width, _, height = x.partition('x') width = int(width.strip()) height = int(height.strip()) p.width = width p.height = height except ValueError: print(f"Invalid size in XYZ plot: {x}") def find_vae(name: str): if (name := name.strip().lower()) in ('auto', 'automatic'): return 'Automatic' elif name == 'none': return 'None' return next((k for k in modules.sd_vae.vae_dict if k.lower() == name), print(f'No VAE found for {name}; using Automatic') or 'Automatic') def apply_vae(p, x, xs): p.override_settings['sd_vae'] = find_vae(x) def apply_styles(p: StableDiffusionProcessingTxt2Img, x: str, _): p.styles.extend(x.split(',')) def apply_uni_pc_order(p, x, xs): p.override_settings['uni_pc_order'] = min(x, p.steps - 1) def apply_face_restore(p, opt, x): opt = opt.lower() if opt == 'codeformer': is_active = True p.face_restoration_model = 'CodeFormer' elif opt == 'gfpgan': is_active = True p.face_restoration_model = 'GFPGAN' else: is_active = opt in ('true', 'yes', 'y', '1') p.restore_faces = is_active def apply_override(field, boolean: bool = False): def fun(p, x, xs): if boolean: x = True if x.lower() == "true" else False p.override_settings[field] = x return fun def boolean_choice(reverse: bool = False): def choice(): return ["False", "True"] if reverse else ["True", "False"] return choice def format_value_add_label(p, opt, x): if type(x) == float: x = round(x, 8) return f"{opt.label}: {x}" def format_value(p, opt, x): if type(x) == float: x = round(x, 8) return x def format_value_join_list(p, opt, x): return ", ".join(x) def do_nothing(p, x, xs): pass def format_nothing(p, opt, x): return "" def format_remove_path(p, opt, x): return os.path.basename(x) def str_permutations(x): return x def list_to_csv_string(data_list): with StringIO() as o: csv.writer(o).writerow(data_list) return o.getvalue().strip() def csv_string_to_list_strip(data_str): return list(map(str.strip, chain.from_iterable(csv.reader(StringIO(data_str), skipinitialspace=True)))) class AxisOption: def __init__(self, label, type, apply, format_value=format_value_add_label, confirm=None, cost=0.0, choices=None, prepare=None): self.label = label self.type = type self.apply = apply self.format_value = format_value self.confirm = confirm self.cost = cost self.prepare = prepare self.choices = choices class AxisOptionImg2Img(AxisOption): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.is_img2img = True class AxisOptionTxt2Img(AxisOption): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.is_img2img = False axis_options = [ AxisOption("Nothing", str, do_nothing, format_value=format_nothing), AxisOption("Seed", int, apply_field("seed")), AxisOption("Var. seed", int, apply_field("subseed")), AxisOption("Var. strength", float, apply_field("subseed_strength")), AxisOption("Steps", int, apply_field("steps")), AxisOptionTxt2Img("Hires steps", int, apply_field("hr_second_pass_steps")), AxisOption("CFG Scale", float, apply_field("cfg_scale")), AxisOptionImg2Img("Image CFG Scale", float, apply_field("image_cfg_scale")), AxisOption("Prompt S/R", str, apply_prompt, format_value=format_value), AxisOption("Prompt order", str_permutations, apply_order, format_value=format_value_join_list), AxisOptionTxt2Img("Sampler", str, apply_field("sampler_name"), format_value=format_value, confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers if x.name not in opts.hide_samplers]), AxisOptionTxt2Img("Hires sampler", str, apply_field("hr_sampler_name"), confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers_for_img2img if x.name not in opts.hide_samplers]), AxisOptionImg2Img("Sampler", str, apply_field("sampler_name"), format_value=format_value, confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers_for_img2img if x.name not in opts.hide_samplers]), AxisOption("Checkpoint name", str, apply_checkpoint, format_value=format_remove_path, confirm=confirm_checkpoints, cost=1.0, choices=lambda: sorted(sd_models.checkpoints_list, key=str.casefold)), AxisOption("Negative Guidance minimum sigma", float, apply_field("s_min_uncond")), AxisOption("Sigma Churn", float, apply_field("s_churn")), AxisOption("Sigma min", float, apply_field("s_tmin")), AxisOption("Sigma max", float, apply_field("s_tmax")), AxisOption("Sigma noise", float, apply_field("s_noise")), AxisOption("Schedule type", str, apply_field("scheduler"), choices=lambda: [x.label for x in sd_schedulers.schedulers]), AxisOption("Schedule min sigma", float, apply_override("sigma_min")), AxisOption("Schedule max sigma", float, apply_override("sigma_max")), AxisOption("Schedule rho", float, apply_override("rho")), AxisOption("Beta schedule alpha", float, apply_override("beta_dist_alpha")), AxisOption("Beta schedule beta", float, apply_override("beta_dist_beta")), AxisOption("Eta", float, apply_field("eta")), AxisOption("Clip skip", int, apply_override('CLIP_stop_at_last_layers')), AxisOption("Denoising", float, apply_field("denoising_strength")), AxisOption("Initial noise multiplier", float, apply_field("initial_noise_multiplier")), AxisOption("Extra noise", float, apply_override("img2img_extra_noise")), AxisOptionTxt2Img("Hires upscaler", str, apply_field("hr_upscaler"), choices=lambda: [*shared.latent_upscale_modes, *[x.name for x in shared.sd_upscalers]]), AxisOptionImg2Img("Cond. Image Mask Weight", float, apply_field("inpainting_mask_weight")), AxisOption("VAE", str, apply_vae, cost=0.7, choices=lambda: ['Automatic', 'None'] + list(sd_vae.vae_dict)), AxisOption("Styles", str, apply_styles, choices=lambda: list(shared.prompt_styles.styles)), AxisOption("UniPC Order", int, apply_uni_pc_order, cost=0.5), AxisOption("Face restore", str, apply_face_restore, format_value=format_value), AxisOption("Token merging ratio", float, apply_override('token_merging_ratio')), AxisOption("Token merging ratio high-res", float, apply_override('token_merging_ratio_hr')), AxisOption("Always discard next-to-last sigma", str, apply_override('always_discard_next_to_last_sigma', boolean=True), choices=boolean_choice(reverse=True)), AxisOption("SGM noise multiplier", str, apply_override('sgm_noise_multiplier', boolean=True), choices=boolean_choice(reverse=True)), AxisOption("Refiner checkpoint", str, apply_field('refiner_checkpoint'), format_value=format_remove_path, confirm=confirm_checkpoints_or_none, cost=1.0, choices=lambda: ['None'] + sorted(sd_models.checkpoints_list, key=str.casefold)), AxisOption("Refiner switch at", float, apply_field('refiner_switch_at')), AxisOption("RNG source", str, apply_override("randn_source"), choices=lambda: ["GPU", "CPU", "NV"]), AxisOption("FP8 mode", str, apply_override("fp8_storage"), cost=0.9, choices=lambda: ["Disable", "Enable for SDXL", "Enable"]), AxisOption("Size", str, apply_size), ] def draw_xyz_grid(p, xs, ys, zs, x_labels, y_labels, z_labels, cell, draw_legend, include_lone_images, include_sub_grids, first_axes_processed, second_axes_processed, margin_size): hor_texts = [[images.GridAnnotation(x)] for x in x_labels] ver_texts = [[images.GridAnnotation(y)] for y in y_labels] title_texts = [[images.GridAnnotation(z)] for z in z_labels] list_size = (len(xs) * len(ys) * len(zs)) processed_result = None state.job_count = list_size * p.n_iter def process_cell(x, y, z, ix, iy, iz): nonlocal processed_result def index(ix, iy, iz): return ix + iy * len(xs) + iz * len(xs) * len(ys) state.job = f"{index(ix, iy, iz) + 1} out of {list_size}" processed: Processed = cell(x, y, z, ix, iy, iz) if processed_result is None: # Use our first processed result object as a template container to hold our full results processed_result = copy(processed) processed_result.images = [None] * list_size processed_result.all_prompts = [None] * list_size processed_result.all_seeds = [None] * list_size processed_result.infotexts = [None] * list_size processed_result.index_of_first_image = 1 idx = index(ix, iy, iz) if processed.images: # Non-empty list indicates some degree of success. processed_result.images[idx] = processed.images[0] processed_result.all_prompts[idx] = processed.prompt processed_result.all_seeds[idx] = processed.seed processed_result.infotexts[idx] = processed.infotexts[0] else: cell_mode = "P" cell_size = (processed_result.width, processed_result.height) if processed_result.images[0] is not None: cell_mode = processed_result.images[0].mode # This corrects size in case of batches: cell_size = processed_result.images[0].size processed_result.images[idx] = Image.new(cell_mode, cell_size) if first_axes_processed == 'x': for ix, x in enumerate(xs): if second_axes_processed == 'y': for iy, y in enumerate(ys): for iz, z in enumerate(zs): process_cell(x, y, z, ix, iy, iz) else: for iz, z in enumerate(zs): for iy, y in enumerate(ys): process_cell(x, y, z, ix, iy, iz) elif first_axes_processed == 'y': for iy, y in enumerate(ys): if second_axes_processed == 'x': for ix, x in enumerate(xs): for iz, z in enumerate(zs): process_cell(x, y, z, ix, iy, iz) else: for iz, z in enumerate(zs): for ix, x in enumerate(xs): process_cell(x, y, z, ix, iy, iz) elif first_axes_processed == 'z': for iz, z in enumerate(zs): if second_axes_processed == 'x': for ix, x in enumerate(xs): for iy, y in enumerate(ys): process_cell(x, y, z, ix, iy, iz) else: for iy, y in enumerate(ys): for ix, x in enumerate(xs): process_cell(x, y, z, ix, iy, iz) if not processed_result: # Should never happen, I've only seen it on one of four open tabs and it needed to refresh. print("Unexpected error: Processing could not begin, you may need to refresh the tab or restart the service.") return Processed(p, []) elif not any(processed_result.images): print("Unexpected error: draw_xyz_grid failed to return even a single processed image") return Processed(p, []) z_count = len(zs) for i in range(z_count): start_index = (i * len(xs) * len(ys)) + i end_index = start_index + len(xs) * len(ys) grid = images.image_grid(processed_result.images[start_index:end_index], rows=len(ys)) if draw_legend: grid_max_w, grid_max_h = map(max, zip(*(img.size for img in processed_result.images[start_index:end_index]))) grid = images.draw_grid_annotations(grid, grid_max_w, grid_max_h, hor_texts, ver_texts, margin_size) processed_result.images.insert(i, grid) processed_result.all_prompts.insert(i, processed_result.all_prompts[start_index]) processed_result.all_seeds.insert(i, processed_result.all_seeds[start_index]) processed_result.infotexts.insert(i, processed_result.infotexts[start_index]) z_grid = images.image_grid(processed_result.images[:z_count], rows=1) z_sub_grid_max_w, z_sub_grid_max_h = map(max, zip(*(img.size for img in processed_result.images[:z_count]))) if draw_legend: z_grid = images.draw_grid_annotations(z_grid, z_sub_grid_max_w, z_sub_grid_max_h, title_texts, [[images.GridAnnotation()]]) processed_result.images.insert(0, z_grid) # TODO: Deeper aspects of the program rely on grid info being misaligned between metadata arrays, which is not ideal. # processed_result.all_prompts.insert(0, processed_result.all_prompts[0]) # processed_result.all_seeds.insert(0, processed_result.all_seeds[0]) processed_result.infotexts.insert(0, processed_result.infotexts[0]) return processed_result class SharedSettingsStackHelper(object): def __enter__(self): pass def __exit__(self, exc_type, exc_value, tb): modules.sd_models.reload_model_weights() modules.sd_vae.reload_vae_weights() re_range = re.compile(r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\(([+-]\d+)\s*\))?\s*") re_range_float = re.compile(r"\s*([+-]?\s*\d+(?:.\d*)?)\s*-\s*([+-]?\s*\d+(?:.\d*)?)(?:\s*\(([+-]\d+(?:.\d*)?)\s*\))?\s*") re_range_count = re.compile(r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\[(\d+)\s*])?\s*") re_range_count_float = re.compile(r"\s*([+-]?\s*\d+(?:.\d*)?)\s*-\s*([+-]?\s*\d+(?:.\d*)?)(?:\s*\[(\d+(?:.\d*)?)\s*])?\s*") class Script(scripts.Script): def title(self): return "X/Y/Z plot" def ui(self, is_img2img): self.current_axis_options = [x for x in axis_options if type(x) == AxisOption or x.is_img2img == is_img2img] with gr.Row(): with gr.Column(scale=19): with gr.Row(): x_type = gr.Dropdown(label="X type", choices=[x.label for x in self.current_axis_options], value=self.current_axis_options[1].label, type="index", elem_id=self.elem_id("x_type")) x_values = gr.Textbox(label="X values", lines=1, elem_id=self.elem_id("x_values")) x_values_dropdown = gr.Dropdown(label="X values", visible=False, multiselect=True, interactive=True) fill_x_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_x_tool_button", visible=False) with gr.Row(): y_type = gr.Dropdown(label="Y type", choices=[x.label for x in self.current_axis_options], value=self.current_axis_options[0].label, type="index", elem_id=self.elem_id("y_type")) y_values = gr.Textbox(label="Y values", lines=1, elem_id=self.elem_id("y_values")) y_values_dropdown = gr.Dropdown(label="Y values", visible=False, multiselect=True, interactive=True) fill_y_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_y_tool_button", visible=False) with gr.Row(): z_type = gr.Dropdown(label="Z type", choices=[x.label for x in self.current_axis_options], value=self.current_axis_options[0].label, type="index", elem_id=self.elem_id("z_type")) z_values = gr.Textbox(label="Z values", lines=1, elem_id=self.elem_id("z_values")) z_values_dropdown = gr.Dropdown(label="Z values", visible=False, multiselect=True, interactive=True) fill_z_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_z_tool_button", visible=False) with gr.Row(variant="compact", elem_id="axis_options"): with gr.Column(): draw_legend = gr.Checkbox(label='Draw legend', value=True, elem_id=self.elem_id("draw_legend")) no_fixed_seeds = gr.Checkbox(label='Keep -1 for seeds', value=False, elem_id=self.elem_id("no_fixed_seeds")) with gr.Row(): vary_seeds_x = gr.Checkbox(label='Vary seeds for X', value=False, min_width=80, elem_id=self.elem_id("vary_seeds_x"), tooltip="Use different seeds for images along X axis.") vary_seeds_y = gr.Checkbox(label='Vary seeds for Y', value=False, min_width=80, elem_id=self.elem_id("vary_seeds_y"), tooltip="Use different seeds for images along Y axis.") vary_seeds_z = gr.Checkbox(label='Vary seeds for Z', value=False, min_width=80, elem_id=self.elem_id("vary_seeds_z"), tooltip="Use different seeds for images along Z axis.") with gr.Column(): include_lone_images = gr.Checkbox(label='Include Sub Images', value=False, elem_id=self.elem_id("include_lone_images")) include_sub_grids = gr.Checkbox(label='Include Sub Grids', value=False, elem_id=self.elem_id("include_sub_grids")) csv_mode = gr.Checkbox(label='Use text inputs instead of dropdowns', value=False, elem_id=self.elem_id("csv_mode")) with gr.Column(): margin_size = gr.Slider(label="Grid margins (px)", minimum=0, maximum=500, value=0, step=2, elem_id=self.elem_id("margin_size")) with gr.Row(variant="compact", elem_id="swap_axes"): swap_xy_axes_button = gr.Button(value="Swap X/Y axes", elem_id="xy_grid_swap_axes_button") swap_yz_axes_button = gr.Button(value="Swap Y/Z axes", elem_id="yz_grid_swap_axes_button") swap_xz_axes_button = gr.Button(value="Swap X/Z axes", elem_id="xz_grid_swap_axes_button") def swap_axes(axis1_type, axis1_values, axis1_values_dropdown, axis2_type, axis2_values, axis2_values_dropdown): return self.current_axis_options[axis2_type].label, axis2_values, axis2_values_dropdown, self.current_axis_options[axis1_type].label, axis1_values, axis1_values_dropdown xy_swap_args = [x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown] swap_xy_axes_button.click(swap_axes, inputs=xy_swap_args, outputs=xy_swap_args) yz_swap_args = [y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown] swap_yz_axes_button.click(swap_axes, inputs=yz_swap_args, outputs=yz_swap_args) xz_swap_args = [x_type, x_values, x_values_dropdown, z_type, z_values, z_values_dropdown] swap_xz_axes_button.click(swap_axes, inputs=xz_swap_args, outputs=xz_swap_args) def fill(axis_type, csv_mode): axis = self.current_axis_options[axis_type] if axis.choices: if csv_mode: return list_to_csv_string(axis.choices()), gr.update() else: return gr.update(), axis.choices() else: return gr.update(), gr.update() fill_x_button.click(fn=fill, inputs=[x_type, csv_mode], outputs=[x_values, x_values_dropdown]) fill_y_button.click(fn=fill, inputs=[y_type, csv_mode], outputs=[y_values, y_values_dropdown]) fill_z_button.click(fn=fill, inputs=[z_type, csv_mode], outputs=[z_values, z_values_dropdown]) def select_axis(axis_type, axis_values, axis_values_dropdown, csv_mode): axis_type = axis_type or 0 # if axle type is None set to 0 choices = self.current_axis_options[axis_type].choices has_choices = choices is not None if has_choices: choices = choices() if csv_mode: if axis_values_dropdown: axis_values = list_to_csv_string(list(filter(lambda x: x in choices, axis_values_dropdown))) axis_values_dropdown = [] else: if axis_values: axis_values_dropdown = list(filter(lambda x: x in choices, csv_string_to_list_strip(axis_values))) axis_values = "" return (gr.Button.update(visible=has_choices), gr.Textbox.update(visible=not has_choices or csv_mode, value=axis_values), gr.update(choices=choices if has_choices else None, visible=has_choices and not csv_mode, value=axis_values_dropdown)) x_type.change(fn=select_axis, inputs=[x_type, x_values, x_values_dropdown, csv_mode], outputs=[fill_x_button, x_values, x_values_dropdown]) y_type.change(fn=select_axis, inputs=[y_type, y_values, y_values_dropdown, csv_mode], outputs=[fill_y_button, y_values, y_values_dropdown]) z_type.change(fn=select_axis, inputs=[z_type, z_values, z_values_dropdown, csv_mode], outputs=[fill_z_button, z_values, z_values_dropdown]) def change_choice_mode(csv_mode, x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown): _fill_x_button, _x_values, _x_values_dropdown = select_axis(x_type, x_values, x_values_dropdown, csv_mode) _fill_y_button, _y_values, _y_values_dropdown = select_axis(y_type, y_values, y_values_dropdown, csv_mode) _fill_z_button, _z_values, _z_values_dropdown = select_axis(z_type, z_values, z_values_dropdown, csv_mode) return _fill_x_button, _x_values, _x_values_dropdown, _fill_y_button, _y_values, _y_values_dropdown, _fill_z_button, _z_values, _z_values_dropdown csv_mode.change(fn=change_choice_mode, inputs=[csv_mode, x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown], outputs=[fill_x_button, x_values, x_values_dropdown, fill_y_button, y_values, y_values_dropdown, fill_z_button, z_values, z_values_dropdown]) def get_dropdown_update_from_params(axis, params): val_key = f"{axis} Values" vals = params.get(val_key, "") valslist = csv_string_to_list_strip(vals) return gr.update(value=valslist) self.infotext_fields = ( (x_type, "X Type"), (x_values, "X Values"), (x_values_dropdown, lambda params: get_dropdown_update_from_params("X", params)), (y_type, "Y Type"), (y_values, "Y Values"), (y_values_dropdown, lambda params: get_dropdown_update_from_params("Y", params)), (z_type, "Z Type"), (z_values, "Z Values"), (z_values_dropdown, lambda params: get_dropdown_update_from_params("Z", params)), ) return [x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown, draw_legend, include_lone_images, include_sub_grids, no_fixed_seeds, vary_seeds_x, vary_seeds_y, vary_seeds_z, margin_size, csv_mode] def run(self, p, x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown, draw_legend, include_lone_images, include_sub_grids, no_fixed_seeds, vary_seeds_x, vary_seeds_y, vary_seeds_z, margin_size, csv_mode): x_type, y_type, z_type = x_type or 0, y_type or 0, z_type or 0 # if axle type is None set to 0 if not no_fixed_seeds: modules.processing.fix_seed(p) if not opts.return_grid: p.batch_size = 1 def process_axis(opt, vals, vals_dropdown): if opt.label == 'Nothing': return [0] if opt.choices is not None and not csv_mode: valslist = vals_dropdown elif opt.prepare is not None: valslist = opt.prepare(vals) else: valslist = csv_string_to_list_strip(vals) if opt.type == int: valslist_ext = [] for val in valslist: if val.strip() == '': continue m = re_range.fullmatch(val) mc = re_range_count.fullmatch(val) if m is not None: start = int(m.group(1)) end = int(m.group(2)) + 1 step = int(m.group(3)) if m.group(3) is not None else 1 valslist_ext += list(range(start, end, step)) elif mc is not None: start = int(mc.group(1)) end = int(mc.group(2)) num = int(mc.group(3)) if mc.group(3) is not None else 1 valslist_ext += [int(x) for x in np.linspace(start=start, stop=end, num=num).tolist()] else: valslist_ext.append(val) valslist = valslist_ext elif opt.type == float: valslist_ext = [] for val in valslist: if val.strip() == '': continue m = re_range_float.fullmatch(val) mc = re_range_count_float.fullmatch(val) if m is not None: start = float(m.group(1)) end = float(m.group(2)) step = float(m.group(3)) if m.group(3) is not None else 1 valslist_ext += np.arange(start, end + step, step).tolist() elif mc is not None: start = float(mc.group(1)) end = float(mc.group(2)) num = int(mc.group(3)) if mc.group(3) is not None else 1 valslist_ext += np.linspace(start=start, stop=end, num=num).tolist() else: valslist_ext.append(val) valslist = valslist_ext elif opt.type == str_permutations: valslist = list(permutations(valslist)) valslist = [opt.type(x) for x in valslist] # Confirm options are valid before starting if opt.confirm: opt.confirm(p, valslist) return valslist x_opt = self.current_axis_options[x_type] if x_opt.choices is not None and not csv_mode: x_values = list_to_csv_string(x_values_dropdown) xs = process_axis(x_opt, x_values, x_values_dropdown) y_opt = self.current_axis_options[y_type] if y_opt.choices is not None and not csv_mode: y_values = list_to_csv_string(y_values_dropdown) ys = process_axis(y_opt, y_values, y_values_dropdown) z_opt = self.current_axis_options[z_type] if z_opt.choices is not None and not csv_mode: z_values = list_to_csv_string(z_values_dropdown) zs = process_axis(z_opt, z_values, z_values_dropdown) # this could be moved to common code, but unlikely to be ever triggered anywhere else Image.MAX_IMAGE_PIXELS = None # disable check in Pillow and rely on check below to allow large custom image sizes grid_mp = round(len(xs) * len(ys) * len(zs) * p.width * p.height / 1000000) assert grid_mp < opts.img_max_size_mp, f'Error: Resulting grid would be too large ({grid_mp} MPixels) (max configured size is {opts.img_max_size_mp} MPixels)' def fix_axis_seeds(axis_opt, axis_list): if axis_opt.label in ['Seed', 'Var. seed']: return [int(random.randrange(4294967294)) if val is None or val == '' or val == -1 else val for val in axis_list] else: return axis_list if not no_fixed_seeds: xs = fix_axis_seeds(x_opt, xs) ys = fix_axis_seeds(y_opt, ys) zs = fix_axis_seeds(z_opt, zs) if x_opt.label == 'Steps': total_steps = sum(xs) * len(ys) * len(zs) elif y_opt.label == 'Steps': total_steps = sum(ys) * len(xs) * len(zs) elif z_opt.label == 'Steps': total_steps = sum(zs) * len(xs) * len(ys) else: total_steps = p.steps * len(xs) * len(ys) * len(zs) if isinstance(p, StableDiffusionProcessingTxt2Img) and p.enable_hr: if x_opt.label == "Hires steps": total_steps += sum(xs) * len(ys) * len(zs) elif y_opt.label == "Hires steps": total_steps += sum(ys) * len(xs) * len(zs) elif z_opt.label == "Hires steps": total_steps += sum(zs) * len(xs) * len(ys) elif p.hr_second_pass_steps: total_steps += p.hr_second_pass_steps * len(xs) * len(ys) * len(zs) else: total_steps *= 2 total_steps *= p.n_iter image_cell_count = p.n_iter * p.batch_size cell_console_text = f"; {image_cell_count} images per cell" if image_cell_count > 1 else "" plural_s = 's' if len(zs) > 1 else '' print(f"X/Y/Z plot will create {len(xs) * len(ys) * len(zs) * image_cell_count} images on {len(zs)} {len(xs)}x{len(ys)} grid{plural_s}{cell_console_text}. (Total steps to process: {total_steps})") shared.total_tqdm.updateTotal(total_steps) state.xyz_plot_x = AxisInfo(x_opt, xs) state.xyz_plot_y = AxisInfo(y_opt, ys) state.xyz_plot_z = AxisInfo(z_opt, zs) # If one of the axes is very slow to change between (like SD model # checkpoint), then make sure it is in the outer iteration of the nested # `for` loop. first_axes_processed = 'z' second_axes_processed = 'y' if x_opt.cost > y_opt.cost and x_opt.cost > z_opt.cost: first_axes_processed = 'x' if y_opt.cost > z_opt.cost: second_axes_processed = 'y' else: second_axes_processed = 'z' elif y_opt.cost > x_opt.cost and y_opt.cost > z_opt.cost: first_axes_processed = 'y' if x_opt.cost > z_opt.cost: second_axes_processed = 'x' else: second_axes_processed = 'z' elif z_opt.cost > x_opt.cost and z_opt.cost > y_opt.cost: first_axes_processed = 'z' if x_opt.cost > y_opt.cost: second_axes_processed = 'x' else: second_axes_processed = 'y' grid_infotext = [None] * (1 + len(zs)) def cell(x, y, z, ix, iy, iz): if shared.state.interrupted or state.stopping_generation: return Processed(p, [], p.seed, "") pc = copy(p) pc.styles = pc.styles[:] x_opt.apply(pc, x, xs) y_opt.apply(pc, y, ys) z_opt.apply(pc, z, zs) xdim = len(xs) if vary_seeds_x else 1 ydim = len(ys) if vary_seeds_y else 1 if vary_seeds_x: pc.seed += ix if vary_seeds_y: pc.seed += iy * xdim if vary_seeds_z: pc.seed += iz * xdim * ydim try: res = process_images(pc) except Exception as e: errors.display(e, "generating image for xyz plot") res = Processed(p, [], p.seed, "") # Sets subgrid infotexts subgrid_index = 1 + iz if grid_infotext[subgrid_index] is None and ix == 0 and iy == 0: pc.extra_generation_params = copy(pc.extra_generation_params) pc.extra_generation_params['Script'] = self.title() if x_opt.label != 'Nothing': pc.extra_generation_params["X Type"] = x_opt.label pc.extra_generation_params["X Values"] = x_values if x_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds: pc.extra_generation_params["Fixed X Values"] = ", ".join([str(x) for x in xs]) if y_opt.label != 'Nothing': pc.extra_generation_params["Y Type"] = y_opt.label pc.extra_generation_params["Y Values"] = y_values if y_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds: pc.extra_generation_params["Fixed Y Values"] = ", ".join([str(y) for y in ys]) grid_infotext[subgrid_index] = processing.create_infotext(pc, pc.all_prompts, pc.all_seeds, pc.all_subseeds) # Sets main grid infotext if grid_infotext[0] is None and ix == 0 and iy == 0 and iz == 0: pc.extra_generation_params = copy(pc.extra_generation_params) if z_opt.label != 'Nothing': pc.extra_generation_params["Z Type"] = z_opt.label pc.extra_generation_params["Z Values"] = z_values if z_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds: pc.extra_generation_params["Fixed Z Values"] = ", ".join([str(z) for z in zs]) grid_infotext[0] = processing.create_infotext(pc, pc.all_prompts, pc.all_seeds, pc.all_subseeds) return res with SharedSettingsStackHelper(): processed = draw_xyz_grid( p, xs=xs, ys=ys, zs=zs, x_labels=[x_opt.format_value(p, x_opt, x) for x in xs], y_labels=[y_opt.format_value(p, y_opt, y) for y in ys], z_labels=[z_opt.format_value(p, z_opt, z) for z in zs], cell=cell, draw_legend=draw_legend, include_lone_images=include_lone_images, include_sub_grids=include_sub_grids, first_axes_processed=first_axes_processed, second_axes_processed=second_axes_processed, margin_size=margin_size ) if not processed.images: # It broke, no further handling needed. return processed z_count = len(zs) # Set the grid infotexts to the real ones with extra_generation_params (1 main grid + z_count sub-grids) processed.infotexts[:1 + z_count] = grid_infotext[:1 + z_count] if not include_lone_images: # Don't need sub-images anymore, drop from list: processed.images = processed.images[:z_count + 1] if opts.grid_save: # Auto-save main and sub-grids: grid_count = z_count + 1 if z_count > 1 else 1 for g in range(grid_count): # TODO: See previous comment about intentional data misalignment. adj_g = g - 1 if g > 0 else g images.save_image(processed.images[g], p.outpath_grids, "xyz_grid", info=processed.infotexts[g], extension=opts.grid_format, prompt=processed.all_prompts[adj_g], seed=processed.all_seeds[adj_g], grid=True, p=processed) if not include_sub_grids: # if not include_sub_grids then skip saving after the first grid break if not include_sub_grids: # Done with sub-grids, drop all related information: for _ in range(z_count): del processed.images[1] del processed.all_prompts[1] del processed.all_seeds[1] del processed.infotexts[1] return processed
--- +++ @@ -1,815 +1,817 @@-from collections import namedtuple -from copy import copy -from itertools import permutations, chain -import random -import csv -import os.path -from io import StringIO -from PIL import Image -import numpy as np - -import modules.scripts as scripts -import gradio as gr - -from modules import images, sd_samplers, processing, sd_models, sd_vae, sd_schedulers, errors -from modules.processing import process_images, Processed, StableDiffusionProcessingTxt2Img -from modules.shared import opts, state -import modules.shared as shared -import modules.sd_samplers -import modules.sd_models -import modules.sd_vae -import re - -from modules.ui_components import ToolButton - -fill_values_symbol = "\U0001f4d2" # 📒 - -AxisInfo = namedtuple('AxisInfo', ['axis', 'values']) - - -def apply_field(field): - def fun(p, x, xs): - setattr(p, field, x) - - return fun - - -def apply_prompt(p, x, xs): - if xs[0] not in p.prompt and xs[0] not in p.negative_prompt: - raise RuntimeError(f"Prompt S/R did not find {xs[0]} in prompt or negative prompt.") - - p.prompt = p.prompt.replace(xs[0], x) - p.negative_prompt = p.negative_prompt.replace(xs[0], x) - - -def apply_order(p, x, xs): - token_order = [] - - # Initially grab the tokens from the prompt, so they can be replaced in order of earliest seen - for token in x: - token_order.append((p.prompt.find(token), token)) - - token_order.sort(key=lambda t: t[0]) - - prompt_parts = [] - - # Split the prompt up, taking out the tokens - for _, token in token_order: - n = p.prompt.find(token) - prompt_parts.append(p.prompt[0:n]) - p.prompt = p.prompt[n + len(token):] - - # Rebuild the prompt with the tokens in the order we want - prompt_tmp = "" - for idx, part in enumerate(prompt_parts): - prompt_tmp += part - prompt_tmp += x[idx] - p.prompt = prompt_tmp + p.prompt - - -def confirm_samplers(p, xs): - for x in xs: - if x.lower() not in sd_samplers.samplers_map: - raise RuntimeError(f"Unknown sampler: {x}") - - -def apply_checkpoint(p, x, xs): - info = modules.sd_models.get_closet_checkpoint_match(x) - if info is None: - raise RuntimeError(f"Unknown checkpoint: {x}") - p.override_settings['sd_model_checkpoint'] = info.name - - -def confirm_checkpoints(p, xs): - for x in xs: - if modules.sd_models.get_closet_checkpoint_match(x) is None: - raise RuntimeError(f"Unknown checkpoint: {x}") - - -def confirm_checkpoints_or_none(p, xs): - for x in xs: - if x in (None, "", "None", "none"): - continue - - if modules.sd_models.get_closet_checkpoint_match(x) is None: - raise RuntimeError(f"Unknown checkpoint: {x}") - - -def confirm_range(min_val, max_val, axis_label): - - def confirm_range_fun(p, xs): - for x in xs: - if not (max_val >= x >= min_val): - raise ValueError(f'{axis_label} value "{x}" out of range [{min_val}, {max_val}]') - - return confirm_range_fun - - -def apply_size(p, x: str, xs) -> None: - try: - width, _, height = x.partition('x') - width = int(width.strip()) - height = int(height.strip()) - p.width = width - p.height = height - except ValueError: - print(f"Invalid size in XYZ plot: {x}") - - -def find_vae(name: str): - if (name := name.strip().lower()) in ('auto', 'automatic'): - return 'Automatic' - elif name == 'none': - return 'None' - return next((k for k in modules.sd_vae.vae_dict if k.lower() == name), print(f'No VAE found for {name}; using Automatic') or 'Automatic') - - -def apply_vae(p, x, xs): - p.override_settings['sd_vae'] = find_vae(x) - - -def apply_styles(p: StableDiffusionProcessingTxt2Img, x: str, _): - p.styles.extend(x.split(',')) - - -def apply_uni_pc_order(p, x, xs): - p.override_settings['uni_pc_order'] = min(x, p.steps - 1) - - -def apply_face_restore(p, opt, x): - opt = opt.lower() - if opt == 'codeformer': - is_active = True - p.face_restoration_model = 'CodeFormer' - elif opt == 'gfpgan': - is_active = True - p.face_restoration_model = 'GFPGAN' - else: - is_active = opt in ('true', 'yes', 'y', '1') - - p.restore_faces = is_active - - -def apply_override(field, boolean: bool = False): - def fun(p, x, xs): - if boolean: - x = True if x.lower() == "true" else False - p.override_settings[field] = x - - return fun - - -def boolean_choice(reverse: bool = False): - def choice(): - return ["False", "True"] if reverse else ["True", "False"] - - return choice - - -def format_value_add_label(p, opt, x): - if type(x) == float: - x = round(x, 8) - - return f"{opt.label}: {x}" - - -def format_value(p, opt, x): - if type(x) == float: - x = round(x, 8) - return x - - -def format_value_join_list(p, opt, x): - return ", ".join(x) - - -def do_nothing(p, x, xs): - pass - - -def format_nothing(p, opt, x): - return "" - - -def format_remove_path(p, opt, x): - return os.path.basename(x) - - -def str_permutations(x): - return x - - -def list_to_csv_string(data_list): - with StringIO() as o: - csv.writer(o).writerow(data_list) - return o.getvalue().strip() - - -def csv_string_to_list_strip(data_str): - return list(map(str.strip, chain.from_iterable(csv.reader(StringIO(data_str), skipinitialspace=True)))) - - -class AxisOption: - def __init__(self, label, type, apply, format_value=format_value_add_label, confirm=None, cost=0.0, choices=None, prepare=None): - self.label = label - self.type = type - self.apply = apply - self.format_value = format_value - self.confirm = confirm - self.cost = cost - self.prepare = prepare - self.choices = choices - - -class AxisOptionImg2Img(AxisOption): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.is_img2img = True - - -class AxisOptionTxt2Img(AxisOption): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.is_img2img = False - - -axis_options = [ - AxisOption("Nothing", str, do_nothing, format_value=format_nothing), - AxisOption("Seed", int, apply_field("seed")), - AxisOption("Var. seed", int, apply_field("subseed")), - AxisOption("Var. strength", float, apply_field("subseed_strength")), - AxisOption("Steps", int, apply_field("steps")), - AxisOptionTxt2Img("Hires steps", int, apply_field("hr_second_pass_steps")), - AxisOption("CFG Scale", float, apply_field("cfg_scale")), - AxisOptionImg2Img("Image CFG Scale", float, apply_field("image_cfg_scale")), - AxisOption("Prompt S/R", str, apply_prompt, format_value=format_value), - AxisOption("Prompt order", str_permutations, apply_order, format_value=format_value_join_list), - AxisOptionTxt2Img("Sampler", str, apply_field("sampler_name"), format_value=format_value, confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers if x.name not in opts.hide_samplers]), - AxisOptionTxt2Img("Hires sampler", str, apply_field("hr_sampler_name"), confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers_for_img2img if x.name not in opts.hide_samplers]), - AxisOptionImg2Img("Sampler", str, apply_field("sampler_name"), format_value=format_value, confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers_for_img2img if x.name not in opts.hide_samplers]), - AxisOption("Checkpoint name", str, apply_checkpoint, format_value=format_remove_path, confirm=confirm_checkpoints, cost=1.0, choices=lambda: sorted(sd_models.checkpoints_list, key=str.casefold)), - AxisOption("Negative Guidance minimum sigma", float, apply_field("s_min_uncond")), - AxisOption("Sigma Churn", float, apply_field("s_churn")), - AxisOption("Sigma min", float, apply_field("s_tmin")), - AxisOption("Sigma max", float, apply_field("s_tmax")), - AxisOption("Sigma noise", float, apply_field("s_noise")), - AxisOption("Schedule type", str, apply_field("scheduler"), choices=lambda: [x.label for x in sd_schedulers.schedulers]), - AxisOption("Schedule min sigma", float, apply_override("sigma_min")), - AxisOption("Schedule max sigma", float, apply_override("sigma_max")), - AxisOption("Schedule rho", float, apply_override("rho")), - AxisOption("Beta schedule alpha", float, apply_override("beta_dist_alpha")), - AxisOption("Beta schedule beta", float, apply_override("beta_dist_beta")), - AxisOption("Eta", float, apply_field("eta")), - AxisOption("Clip skip", int, apply_override('CLIP_stop_at_last_layers')), - AxisOption("Denoising", float, apply_field("denoising_strength")), - AxisOption("Initial noise multiplier", float, apply_field("initial_noise_multiplier")), - AxisOption("Extra noise", float, apply_override("img2img_extra_noise")), - AxisOptionTxt2Img("Hires upscaler", str, apply_field("hr_upscaler"), choices=lambda: [*shared.latent_upscale_modes, *[x.name for x in shared.sd_upscalers]]), - AxisOptionImg2Img("Cond. Image Mask Weight", float, apply_field("inpainting_mask_weight")), - AxisOption("VAE", str, apply_vae, cost=0.7, choices=lambda: ['Automatic', 'None'] + list(sd_vae.vae_dict)), - AxisOption("Styles", str, apply_styles, choices=lambda: list(shared.prompt_styles.styles)), - AxisOption("UniPC Order", int, apply_uni_pc_order, cost=0.5), - AxisOption("Face restore", str, apply_face_restore, format_value=format_value), - AxisOption("Token merging ratio", float, apply_override('token_merging_ratio')), - AxisOption("Token merging ratio high-res", float, apply_override('token_merging_ratio_hr')), - AxisOption("Always discard next-to-last sigma", str, apply_override('always_discard_next_to_last_sigma', boolean=True), choices=boolean_choice(reverse=True)), - AxisOption("SGM noise multiplier", str, apply_override('sgm_noise_multiplier', boolean=True), choices=boolean_choice(reverse=True)), - AxisOption("Refiner checkpoint", str, apply_field('refiner_checkpoint'), format_value=format_remove_path, confirm=confirm_checkpoints_or_none, cost=1.0, choices=lambda: ['None'] + sorted(sd_models.checkpoints_list, key=str.casefold)), - AxisOption("Refiner switch at", float, apply_field('refiner_switch_at')), - AxisOption("RNG source", str, apply_override("randn_source"), choices=lambda: ["GPU", "CPU", "NV"]), - AxisOption("FP8 mode", str, apply_override("fp8_storage"), cost=0.9, choices=lambda: ["Disable", "Enable for SDXL", "Enable"]), - AxisOption("Size", str, apply_size), -] - - -def draw_xyz_grid(p, xs, ys, zs, x_labels, y_labels, z_labels, cell, draw_legend, include_lone_images, include_sub_grids, first_axes_processed, second_axes_processed, margin_size): - hor_texts = [[images.GridAnnotation(x)] for x in x_labels] - ver_texts = [[images.GridAnnotation(y)] for y in y_labels] - title_texts = [[images.GridAnnotation(z)] for z in z_labels] - - list_size = (len(xs) * len(ys) * len(zs)) - - processed_result = None - - state.job_count = list_size * p.n_iter - - def process_cell(x, y, z, ix, iy, iz): - nonlocal processed_result - - def index(ix, iy, iz): - return ix + iy * len(xs) + iz * len(xs) * len(ys) - - state.job = f"{index(ix, iy, iz) + 1} out of {list_size}" - - processed: Processed = cell(x, y, z, ix, iy, iz) - - if processed_result is None: - # Use our first processed result object as a template container to hold our full results - processed_result = copy(processed) - processed_result.images = [None] * list_size - processed_result.all_prompts = [None] * list_size - processed_result.all_seeds = [None] * list_size - processed_result.infotexts = [None] * list_size - processed_result.index_of_first_image = 1 - - idx = index(ix, iy, iz) - if processed.images: - # Non-empty list indicates some degree of success. - processed_result.images[idx] = processed.images[0] - processed_result.all_prompts[idx] = processed.prompt - processed_result.all_seeds[idx] = processed.seed - processed_result.infotexts[idx] = processed.infotexts[0] - else: - cell_mode = "P" - cell_size = (processed_result.width, processed_result.height) - if processed_result.images[0] is not None: - cell_mode = processed_result.images[0].mode - # This corrects size in case of batches: - cell_size = processed_result.images[0].size - processed_result.images[idx] = Image.new(cell_mode, cell_size) - - if first_axes_processed == 'x': - for ix, x in enumerate(xs): - if second_axes_processed == 'y': - for iy, y in enumerate(ys): - for iz, z in enumerate(zs): - process_cell(x, y, z, ix, iy, iz) - else: - for iz, z in enumerate(zs): - for iy, y in enumerate(ys): - process_cell(x, y, z, ix, iy, iz) - elif first_axes_processed == 'y': - for iy, y in enumerate(ys): - if second_axes_processed == 'x': - for ix, x in enumerate(xs): - for iz, z in enumerate(zs): - process_cell(x, y, z, ix, iy, iz) - else: - for iz, z in enumerate(zs): - for ix, x in enumerate(xs): - process_cell(x, y, z, ix, iy, iz) - elif first_axes_processed == 'z': - for iz, z in enumerate(zs): - if second_axes_processed == 'x': - for ix, x in enumerate(xs): - for iy, y in enumerate(ys): - process_cell(x, y, z, ix, iy, iz) - else: - for iy, y in enumerate(ys): - for ix, x in enumerate(xs): - process_cell(x, y, z, ix, iy, iz) - - if not processed_result: - # Should never happen, I've only seen it on one of four open tabs and it needed to refresh. - print("Unexpected error: Processing could not begin, you may need to refresh the tab or restart the service.") - return Processed(p, []) - elif not any(processed_result.images): - print("Unexpected error: draw_xyz_grid failed to return even a single processed image") - return Processed(p, []) - - z_count = len(zs) - - for i in range(z_count): - start_index = (i * len(xs) * len(ys)) + i - end_index = start_index + len(xs) * len(ys) - grid = images.image_grid(processed_result.images[start_index:end_index], rows=len(ys)) - if draw_legend: - grid_max_w, grid_max_h = map(max, zip(*(img.size for img in processed_result.images[start_index:end_index]))) - grid = images.draw_grid_annotations(grid, grid_max_w, grid_max_h, hor_texts, ver_texts, margin_size) - processed_result.images.insert(i, grid) - processed_result.all_prompts.insert(i, processed_result.all_prompts[start_index]) - processed_result.all_seeds.insert(i, processed_result.all_seeds[start_index]) - processed_result.infotexts.insert(i, processed_result.infotexts[start_index]) - - z_grid = images.image_grid(processed_result.images[:z_count], rows=1) - z_sub_grid_max_w, z_sub_grid_max_h = map(max, zip(*(img.size for img in processed_result.images[:z_count]))) - if draw_legend: - z_grid = images.draw_grid_annotations(z_grid, z_sub_grid_max_w, z_sub_grid_max_h, title_texts, [[images.GridAnnotation()]]) - processed_result.images.insert(0, z_grid) - # TODO: Deeper aspects of the program rely on grid info being misaligned between metadata arrays, which is not ideal. - # processed_result.all_prompts.insert(0, processed_result.all_prompts[0]) - # processed_result.all_seeds.insert(0, processed_result.all_seeds[0]) - processed_result.infotexts.insert(0, processed_result.infotexts[0]) - - return processed_result - - -class SharedSettingsStackHelper(object): - def __enter__(self): - pass - - def __exit__(self, exc_type, exc_value, tb): - modules.sd_models.reload_model_weights() - modules.sd_vae.reload_vae_weights() - - -re_range = re.compile(r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\(([+-]\d+)\s*\))?\s*") -re_range_float = re.compile(r"\s*([+-]?\s*\d+(?:.\d*)?)\s*-\s*([+-]?\s*\d+(?:.\d*)?)(?:\s*\(([+-]\d+(?:.\d*)?)\s*\))?\s*") - -re_range_count = re.compile(r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\[(\d+)\s*])?\s*") -re_range_count_float = re.compile(r"\s*([+-]?\s*\d+(?:.\d*)?)\s*-\s*([+-]?\s*\d+(?:.\d*)?)(?:\s*\[(\d+(?:.\d*)?)\s*])?\s*") - - -class Script(scripts.Script): - def title(self): - return "X/Y/Z plot" - - def ui(self, is_img2img): - self.current_axis_options = [x for x in axis_options if type(x) == AxisOption or x.is_img2img == is_img2img] - - with gr.Row(): - with gr.Column(scale=19): - with gr.Row(): - x_type = gr.Dropdown(label="X type", choices=[x.label for x in self.current_axis_options], value=self.current_axis_options[1].label, type="index", elem_id=self.elem_id("x_type")) - x_values = gr.Textbox(label="X values", lines=1, elem_id=self.elem_id("x_values")) - x_values_dropdown = gr.Dropdown(label="X values", visible=False, multiselect=True, interactive=True) - fill_x_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_x_tool_button", visible=False) - - with gr.Row(): - y_type = gr.Dropdown(label="Y type", choices=[x.label for x in self.current_axis_options], value=self.current_axis_options[0].label, type="index", elem_id=self.elem_id("y_type")) - y_values = gr.Textbox(label="Y values", lines=1, elem_id=self.elem_id("y_values")) - y_values_dropdown = gr.Dropdown(label="Y values", visible=False, multiselect=True, interactive=True) - fill_y_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_y_tool_button", visible=False) - - with gr.Row(): - z_type = gr.Dropdown(label="Z type", choices=[x.label for x in self.current_axis_options], value=self.current_axis_options[0].label, type="index", elem_id=self.elem_id("z_type")) - z_values = gr.Textbox(label="Z values", lines=1, elem_id=self.elem_id("z_values")) - z_values_dropdown = gr.Dropdown(label="Z values", visible=False, multiselect=True, interactive=True) - fill_z_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_z_tool_button", visible=False) - - with gr.Row(variant="compact", elem_id="axis_options"): - with gr.Column(): - draw_legend = gr.Checkbox(label='Draw legend', value=True, elem_id=self.elem_id("draw_legend")) - no_fixed_seeds = gr.Checkbox(label='Keep -1 for seeds', value=False, elem_id=self.elem_id("no_fixed_seeds")) - with gr.Row(): - vary_seeds_x = gr.Checkbox(label='Vary seeds for X', value=False, min_width=80, elem_id=self.elem_id("vary_seeds_x"), tooltip="Use different seeds for images along X axis.") - vary_seeds_y = gr.Checkbox(label='Vary seeds for Y', value=False, min_width=80, elem_id=self.elem_id("vary_seeds_y"), tooltip="Use different seeds for images along Y axis.") - vary_seeds_z = gr.Checkbox(label='Vary seeds for Z', value=False, min_width=80, elem_id=self.elem_id("vary_seeds_z"), tooltip="Use different seeds for images along Z axis.") - with gr.Column(): - include_lone_images = gr.Checkbox(label='Include Sub Images', value=False, elem_id=self.elem_id("include_lone_images")) - include_sub_grids = gr.Checkbox(label='Include Sub Grids', value=False, elem_id=self.elem_id("include_sub_grids")) - csv_mode = gr.Checkbox(label='Use text inputs instead of dropdowns', value=False, elem_id=self.elem_id("csv_mode")) - with gr.Column(): - margin_size = gr.Slider(label="Grid margins (px)", minimum=0, maximum=500, value=0, step=2, elem_id=self.elem_id("margin_size")) - - with gr.Row(variant="compact", elem_id="swap_axes"): - swap_xy_axes_button = gr.Button(value="Swap X/Y axes", elem_id="xy_grid_swap_axes_button") - swap_yz_axes_button = gr.Button(value="Swap Y/Z axes", elem_id="yz_grid_swap_axes_button") - swap_xz_axes_button = gr.Button(value="Swap X/Z axes", elem_id="xz_grid_swap_axes_button") - - def swap_axes(axis1_type, axis1_values, axis1_values_dropdown, axis2_type, axis2_values, axis2_values_dropdown): - return self.current_axis_options[axis2_type].label, axis2_values, axis2_values_dropdown, self.current_axis_options[axis1_type].label, axis1_values, axis1_values_dropdown - - xy_swap_args = [x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown] - swap_xy_axes_button.click(swap_axes, inputs=xy_swap_args, outputs=xy_swap_args) - yz_swap_args = [y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown] - swap_yz_axes_button.click(swap_axes, inputs=yz_swap_args, outputs=yz_swap_args) - xz_swap_args = [x_type, x_values, x_values_dropdown, z_type, z_values, z_values_dropdown] - swap_xz_axes_button.click(swap_axes, inputs=xz_swap_args, outputs=xz_swap_args) - - def fill(axis_type, csv_mode): - axis = self.current_axis_options[axis_type] - if axis.choices: - if csv_mode: - return list_to_csv_string(axis.choices()), gr.update() - else: - return gr.update(), axis.choices() - else: - return gr.update(), gr.update() - - fill_x_button.click(fn=fill, inputs=[x_type, csv_mode], outputs=[x_values, x_values_dropdown]) - fill_y_button.click(fn=fill, inputs=[y_type, csv_mode], outputs=[y_values, y_values_dropdown]) - fill_z_button.click(fn=fill, inputs=[z_type, csv_mode], outputs=[z_values, z_values_dropdown]) - - def select_axis(axis_type, axis_values, axis_values_dropdown, csv_mode): - axis_type = axis_type or 0 # if axle type is None set to 0 - - choices = self.current_axis_options[axis_type].choices - has_choices = choices is not None - - if has_choices: - choices = choices() - if csv_mode: - if axis_values_dropdown: - axis_values = list_to_csv_string(list(filter(lambda x: x in choices, axis_values_dropdown))) - axis_values_dropdown = [] - else: - if axis_values: - axis_values_dropdown = list(filter(lambda x: x in choices, csv_string_to_list_strip(axis_values))) - axis_values = "" - - return (gr.Button.update(visible=has_choices), gr.Textbox.update(visible=not has_choices or csv_mode, value=axis_values), - gr.update(choices=choices if has_choices else None, visible=has_choices and not csv_mode, value=axis_values_dropdown)) - - x_type.change(fn=select_axis, inputs=[x_type, x_values, x_values_dropdown, csv_mode], outputs=[fill_x_button, x_values, x_values_dropdown]) - y_type.change(fn=select_axis, inputs=[y_type, y_values, y_values_dropdown, csv_mode], outputs=[fill_y_button, y_values, y_values_dropdown]) - z_type.change(fn=select_axis, inputs=[z_type, z_values, z_values_dropdown, csv_mode], outputs=[fill_z_button, z_values, z_values_dropdown]) - - def change_choice_mode(csv_mode, x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown): - _fill_x_button, _x_values, _x_values_dropdown = select_axis(x_type, x_values, x_values_dropdown, csv_mode) - _fill_y_button, _y_values, _y_values_dropdown = select_axis(y_type, y_values, y_values_dropdown, csv_mode) - _fill_z_button, _z_values, _z_values_dropdown = select_axis(z_type, z_values, z_values_dropdown, csv_mode) - return _fill_x_button, _x_values, _x_values_dropdown, _fill_y_button, _y_values, _y_values_dropdown, _fill_z_button, _z_values, _z_values_dropdown - - csv_mode.change(fn=change_choice_mode, inputs=[csv_mode, x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown], outputs=[fill_x_button, x_values, x_values_dropdown, fill_y_button, y_values, y_values_dropdown, fill_z_button, z_values, z_values_dropdown]) - - def get_dropdown_update_from_params(axis, params): - val_key = f"{axis} Values" - vals = params.get(val_key, "") - valslist = csv_string_to_list_strip(vals) - return gr.update(value=valslist) - - self.infotext_fields = ( - (x_type, "X Type"), - (x_values, "X Values"), - (x_values_dropdown, lambda params: get_dropdown_update_from_params("X", params)), - (y_type, "Y Type"), - (y_values, "Y Values"), - (y_values_dropdown, lambda params: get_dropdown_update_from_params("Y", params)), - (z_type, "Z Type"), - (z_values, "Z Values"), - (z_values_dropdown, lambda params: get_dropdown_update_from_params("Z", params)), - ) - - return [x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown, draw_legend, include_lone_images, include_sub_grids, no_fixed_seeds, vary_seeds_x, vary_seeds_y, vary_seeds_z, margin_size, csv_mode] - - def run(self, p, x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown, draw_legend, include_lone_images, include_sub_grids, no_fixed_seeds, vary_seeds_x, vary_seeds_y, vary_seeds_z, margin_size, csv_mode): - x_type, y_type, z_type = x_type or 0, y_type or 0, z_type or 0 # if axle type is None set to 0 - - if not no_fixed_seeds: - modules.processing.fix_seed(p) - - if not opts.return_grid: - p.batch_size = 1 - - def process_axis(opt, vals, vals_dropdown): - if opt.label == 'Nothing': - return [0] - - if opt.choices is not None and not csv_mode: - valslist = vals_dropdown - elif opt.prepare is not None: - valslist = opt.prepare(vals) - else: - valslist = csv_string_to_list_strip(vals) - - if opt.type == int: - valslist_ext = [] - - for val in valslist: - if val.strip() == '': - continue - m = re_range.fullmatch(val) - mc = re_range_count.fullmatch(val) - if m is not None: - start = int(m.group(1)) - end = int(m.group(2)) + 1 - step = int(m.group(3)) if m.group(3) is not None else 1 - - valslist_ext += list(range(start, end, step)) - elif mc is not None: - start = int(mc.group(1)) - end = int(mc.group(2)) - num = int(mc.group(3)) if mc.group(3) is not None else 1 - - valslist_ext += [int(x) for x in np.linspace(start=start, stop=end, num=num).tolist()] - else: - valslist_ext.append(val) - - valslist = valslist_ext - elif opt.type == float: - valslist_ext = [] - - for val in valslist: - if val.strip() == '': - continue - m = re_range_float.fullmatch(val) - mc = re_range_count_float.fullmatch(val) - if m is not None: - start = float(m.group(1)) - end = float(m.group(2)) - step = float(m.group(3)) if m.group(3) is not None else 1 - - valslist_ext += np.arange(start, end + step, step).tolist() - elif mc is not None: - start = float(mc.group(1)) - end = float(mc.group(2)) - num = int(mc.group(3)) if mc.group(3) is not None else 1 - - valslist_ext += np.linspace(start=start, stop=end, num=num).tolist() - else: - valslist_ext.append(val) - - valslist = valslist_ext - elif opt.type == str_permutations: - valslist = list(permutations(valslist)) - - valslist = [opt.type(x) for x in valslist] - - # Confirm options are valid before starting - if opt.confirm: - opt.confirm(p, valslist) - - return valslist - - x_opt = self.current_axis_options[x_type] - if x_opt.choices is not None and not csv_mode: - x_values = list_to_csv_string(x_values_dropdown) - xs = process_axis(x_opt, x_values, x_values_dropdown) - - y_opt = self.current_axis_options[y_type] - if y_opt.choices is not None and not csv_mode: - y_values = list_to_csv_string(y_values_dropdown) - ys = process_axis(y_opt, y_values, y_values_dropdown) - - z_opt = self.current_axis_options[z_type] - if z_opt.choices is not None and not csv_mode: - z_values = list_to_csv_string(z_values_dropdown) - zs = process_axis(z_opt, z_values, z_values_dropdown) - - # this could be moved to common code, but unlikely to be ever triggered anywhere else - Image.MAX_IMAGE_PIXELS = None # disable check in Pillow and rely on check below to allow large custom image sizes - grid_mp = round(len(xs) * len(ys) * len(zs) * p.width * p.height / 1000000) - assert grid_mp < opts.img_max_size_mp, f'Error: Resulting grid would be too large ({grid_mp} MPixels) (max configured size is {opts.img_max_size_mp} MPixels)' - - def fix_axis_seeds(axis_opt, axis_list): - if axis_opt.label in ['Seed', 'Var. seed']: - return [int(random.randrange(4294967294)) if val is None or val == '' or val == -1 else val for val in axis_list] - else: - return axis_list - - if not no_fixed_seeds: - xs = fix_axis_seeds(x_opt, xs) - ys = fix_axis_seeds(y_opt, ys) - zs = fix_axis_seeds(z_opt, zs) - - if x_opt.label == 'Steps': - total_steps = sum(xs) * len(ys) * len(zs) - elif y_opt.label == 'Steps': - total_steps = sum(ys) * len(xs) * len(zs) - elif z_opt.label == 'Steps': - total_steps = sum(zs) * len(xs) * len(ys) - else: - total_steps = p.steps * len(xs) * len(ys) * len(zs) - - if isinstance(p, StableDiffusionProcessingTxt2Img) and p.enable_hr: - if x_opt.label == "Hires steps": - total_steps += sum(xs) * len(ys) * len(zs) - elif y_opt.label == "Hires steps": - total_steps += sum(ys) * len(xs) * len(zs) - elif z_opt.label == "Hires steps": - total_steps += sum(zs) * len(xs) * len(ys) - elif p.hr_second_pass_steps: - total_steps += p.hr_second_pass_steps * len(xs) * len(ys) * len(zs) - else: - total_steps *= 2 - - total_steps *= p.n_iter - - image_cell_count = p.n_iter * p.batch_size - cell_console_text = f"; {image_cell_count} images per cell" if image_cell_count > 1 else "" - plural_s = 's' if len(zs) > 1 else '' - print(f"X/Y/Z plot will create {len(xs) * len(ys) * len(zs) * image_cell_count} images on {len(zs)} {len(xs)}x{len(ys)} grid{plural_s}{cell_console_text}. (Total steps to process: {total_steps})") - shared.total_tqdm.updateTotal(total_steps) - - state.xyz_plot_x = AxisInfo(x_opt, xs) - state.xyz_plot_y = AxisInfo(y_opt, ys) - state.xyz_plot_z = AxisInfo(z_opt, zs) - - # If one of the axes is very slow to change between (like SD model - # checkpoint), then make sure it is in the outer iteration of the nested - # `for` loop. - first_axes_processed = 'z' - second_axes_processed = 'y' - if x_opt.cost > y_opt.cost and x_opt.cost > z_opt.cost: - first_axes_processed = 'x' - if y_opt.cost > z_opt.cost: - second_axes_processed = 'y' - else: - second_axes_processed = 'z' - elif y_opt.cost > x_opt.cost and y_opt.cost > z_opt.cost: - first_axes_processed = 'y' - if x_opt.cost > z_opt.cost: - second_axes_processed = 'x' - else: - second_axes_processed = 'z' - elif z_opt.cost > x_opt.cost and z_opt.cost > y_opt.cost: - first_axes_processed = 'z' - if x_opt.cost > y_opt.cost: - second_axes_processed = 'x' - else: - second_axes_processed = 'y' - - grid_infotext = [None] * (1 + len(zs)) - - def cell(x, y, z, ix, iy, iz): - if shared.state.interrupted or state.stopping_generation: - return Processed(p, [], p.seed, "") - - pc = copy(p) - pc.styles = pc.styles[:] - x_opt.apply(pc, x, xs) - y_opt.apply(pc, y, ys) - z_opt.apply(pc, z, zs) - - xdim = len(xs) if vary_seeds_x else 1 - ydim = len(ys) if vary_seeds_y else 1 - - if vary_seeds_x: - pc.seed += ix - if vary_seeds_y: - pc.seed += iy * xdim - if vary_seeds_z: - pc.seed += iz * xdim * ydim - - try: - res = process_images(pc) - except Exception as e: - errors.display(e, "generating image for xyz plot") - - res = Processed(p, [], p.seed, "") - - # Sets subgrid infotexts - subgrid_index = 1 + iz - if grid_infotext[subgrid_index] is None and ix == 0 and iy == 0: - pc.extra_generation_params = copy(pc.extra_generation_params) - pc.extra_generation_params['Script'] = self.title() - - if x_opt.label != 'Nothing': - pc.extra_generation_params["X Type"] = x_opt.label - pc.extra_generation_params["X Values"] = x_values - if x_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds: - pc.extra_generation_params["Fixed X Values"] = ", ".join([str(x) for x in xs]) - - if y_opt.label != 'Nothing': - pc.extra_generation_params["Y Type"] = y_opt.label - pc.extra_generation_params["Y Values"] = y_values - if y_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds: - pc.extra_generation_params["Fixed Y Values"] = ", ".join([str(y) for y in ys]) - - grid_infotext[subgrid_index] = processing.create_infotext(pc, pc.all_prompts, pc.all_seeds, pc.all_subseeds) - - # Sets main grid infotext - if grid_infotext[0] is None and ix == 0 and iy == 0 and iz == 0: - pc.extra_generation_params = copy(pc.extra_generation_params) - - if z_opt.label != 'Nothing': - pc.extra_generation_params["Z Type"] = z_opt.label - pc.extra_generation_params["Z Values"] = z_values - if z_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds: - pc.extra_generation_params["Fixed Z Values"] = ", ".join([str(z) for z in zs]) - - grid_infotext[0] = processing.create_infotext(pc, pc.all_prompts, pc.all_seeds, pc.all_subseeds) - - return res - - with SharedSettingsStackHelper(): - processed = draw_xyz_grid( - p, - xs=xs, - ys=ys, - zs=zs, - x_labels=[x_opt.format_value(p, x_opt, x) for x in xs], - y_labels=[y_opt.format_value(p, y_opt, y) for y in ys], - z_labels=[z_opt.format_value(p, z_opt, z) for z in zs], - cell=cell, - draw_legend=draw_legend, - include_lone_images=include_lone_images, - include_sub_grids=include_sub_grids, - first_axes_processed=first_axes_processed, - second_axes_processed=second_axes_processed, - margin_size=margin_size - ) - - if not processed.images: - # It broke, no further handling needed. - return processed - - z_count = len(zs) - - # Set the grid infotexts to the real ones with extra_generation_params (1 main grid + z_count sub-grids) - processed.infotexts[:1 + z_count] = grid_infotext[:1 + z_count] - - if not include_lone_images: - # Don't need sub-images anymore, drop from list: - processed.images = processed.images[:z_count + 1] - - if opts.grid_save: - # Auto-save main and sub-grids: - grid_count = z_count + 1 if z_count > 1 else 1 - for g in range(grid_count): - # TODO: See previous comment about intentional data misalignment. - adj_g = g - 1 if g > 0 else g - images.save_image(processed.images[g], p.outpath_grids, "xyz_grid", info=processed.infotexts[g], extension=opts.grid_format, prompt=processed.all_prompts[adj_g], seed=processed.all_seeds[adj_g], grid=True, p=processed) - if not include_sub_grids: # if not include_sub_grids then skip saving after the first grid - break - - if not include_sub_grids: - # Done with sub-grids, drop all related information: - for _ in range(z_count): - del processed.images[1] - del processed.all_prompts[1] - del processed.all_seeds[1] - del processed.infotexts[1] - - return processed+from collections import namedtuple +from copy import copy +from itertools import permutations, chain +import random +import csv +import os.path +from io import StringIO +from PIL import Image +import numpy as np + +import modules.scripts as scripts +import gradio as gr + +from modules import images, sd_samplers, processing, sd_models, sd_vae, sd_schedulers, errors +from modules.processing import process_images, Processed, StableDiffusionProcessingTxt2Img +from modules.shared import opts, state +import modules.shared as shared +import modules.sd_samplers +import modules.sd_models +import modules.sd_vae +import re + +from modules.ui_components import ToolButton + +fill_values_symbol = "\U0001f4d2" # 📒 + +AxisInfo = namedtuple('AxisInfo', ['axis', 'values']) + + +def apply_field(field): + def fun(p, x, xs): + setattr(p, field, x) + + return fun + + +def apply_prompt(p, x, xs): + if xs[0] not in p.prompt and xs[0] not in p.negative_prompt: + raise RuntimeError(f"Prompt S/R did not find {xs[0]} in prompt or negative prompt.") + + p.prompt = p.prompt.replace(xs[0], x) + p.negative_prompt = p.negative_prompt.replace(xs[0], x) + + +def apply_order(p, x, xs): + token_order = [] + + # Initially grab the tokens from the prompt, so they can be replaced in order of earliest seen + for token in x: + token_order.append((p.prompt.find(token), token)) + + token_order.sort(key=lambda t: t[0]) + + prompt_parts = [] + + # Split the prompt up, taking out the tokens + for _, token in token_order: + n = p.prompt.find(token) + prompt_parts.append(p.prompt[0:n]) + p.prompt = p.prompt[n + len(token):] + + # Rebuild the prompt with the tokens in the order we want + prompt_tmp = "" + for idx, part in enumerate(prompt_parts): + prompt_tmp += part + prompt_tmp += x[idx] + p.prompt = prompt_tmp + p.prompt + + +def confirm_samplers(p, xs): + for x in xs: + if x.lower() not in sd_samplers.samplers_map: + raise RuntimeError(f"Unknown sampler: {x}") + + +def apply_checkpoint(p, x, xs): + info = modules.sd_models.get_closet_checkpoint_match(x) + if info is None: + raise RuntimeError(f"Unknown checkpoint: {x}") + p.override_settings['sd_model_checkpoint'] = info.name + + +def confirm_checkpoints(p, xs): + for x in xs: + if modules.sd_models.get_closet_checkpoint_match(x) is None: + raise RuntimeError(f"Unknown checkpoint: {x}") + + +def confirm_checkpoints_or_none(p, xs): + for x in xs: + if x in (None, "", "None", "none"): + continue + + if modules.sd_models.get_closet_checkpoint_match(x) is None: + raise RuntimeError(f"Unknown checkpoint: {x}") + + +def confirm_range(min_val, max_val, axis_label): + """Generates a AxisOption.confirm() function that checks all values are within the specified range.""" + + def confirm_range_fun(p, xs): + for x in xs: + if not (max_val >= x >= min_val): + raise ValueError(f'{axis_label} value "{x}" out of range [{min_val}, {max_val}]') + + return confirm_range_fun + + +def apply_size(p, x: str, xs) -> None: + try: + width, _, height = x.partition('x') + width = int(width.strip()) + height = int(height.strip()) + p.width = width + p.height = height + except ValueError: + print(f"Invalid size in XYZ plot: {x}") + + +def find_vae(name: str): + if (name := name.strip().lower()) in ('auto', 'automatic'): + return 'Automatic' + elif name == 'none': + return 'None' + return next((k for k in modules.sd_vae.vae_dict if k.lower() == name), print(f'No VAE found for {name}; using Automatic') or 'Automatic') + + +def apply_vae(p, x, xs): + p.override_settings['sd_vae'] = find_vae(x) + + +def apply_styles(p: StableDiffusionProcessingTxt2Img, x: str, _): + p.styles.extend(x.split(',')) + + +def apply_uni_pc_order(p, x, xs): + p.override_settings['uni_pc_order'] = min(x, p.steps - 1) + + +def apply_face_restore(p, opt, x): + opt = opt.lower() + if opt == 'codeformer': + is_active = True + p.face_restoration_model = 'CodeFormer' + elif opt == 'gfpgan': + is_active = True + p.face_restoration_model = 'GFPGAN' + else: + is_active = opt in ('true', 'yes', 'y', '1') + + p.restore_faces = is_active + + +def apply_override(field, boolean: bool = False): + def fun(p, x, xs): + if boolean: + x = True if x.lower() == "true" else False + p.override_settings[field] = x + + return fun + + +def boolean_choice(reverse: bool = False): + def choice(): + return ["False", "True"] if reverse else ["True", "False"] + + return choice + + +def format_value_add_label(p, opt, x): + if type(x) == float: + x = round(x, 8) + + return f"{opt.label}: {x}" + + +def format_value(p, opt, x): + if type(x) == float: + x = round(x, 8) + return x + + +def format_value_join_list(p, opt, x): + return ", ".join(x) + + +def do_nothing(p, x, xs): + pass + + +def format_nothing(p, opt, x): + return "" + + +def format_remove_path(p, opt, x): + return os.path.basename(x) + + +def str_permutations(x): + """dummy function for specifying it in AxisOption's type when you want to get a list of permutations""" + return x + + +def list_to_csv_string(data_list): + with StringIO() as o: + csv.writer(o).writerow(data_list) + return o.getvalue().strip() + + +def csv_string_to_list_strip(data_str): + return list(map(str.strip, chain.from_iterable(csv.reader(StringIO(data_str), skipinitialspace=True)))) + + +class AxisOption: + def __init__(self, label, type, apply, format_value=format_value_add_label, confirm=None, cost=0.0, choices=None, prepare=None): + self.label = label + self.type = type + self.apply = apply + self.format_value = format_value + self.confirm = confirm + self.cost = cost + self.prepare = prepare + self.choices = choices + + +class AxisOptionImg2Img(AxisOption): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.is_img2img = True + + +class AxisOptionTxt2Img(AxisOption): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.is_img2img = False + + +axis_options = [ + AxisOption("Nothing", str, do_nothing, format_value=format_nothing), + AxisOption("Seed", int, apply_field("seed")), + AxisOption("Var. seed", int, apply_field("subseed")), + AxisOption("Var. strength", float, apply_field("subseed_strength")), + AxisOption("Steps", int, apply_field("steps")), + AxisOptionTxt2Img("Hires steps", int, apply_field("hr_second_pass_steps")), + AxisOption("CFG Scale", float, apply_field("cfg_scale")), + AxisOptionImg2Img("Image CFG Scale", float, apply_field("image_cfg_scale")), + AxisOption("Prompt S/R", str, apply_prompt, format_value=format_value), + AxisOption("Prompt order", str_permutations, apply_order, format_value=format_value_join_list), + AxisOptionTxt2Img("Sampler", str, apply_field("sampler_name"), format_value=format_value, confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers if x.name not in opts.hide_samplers]), + AxisOptionTxt2Img("Hires sampler", str, apply_field("hr_sampler_name"), confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers_for_img2img if x.name not in opts.hide_samplers]), + AxisOptionImg2Img("Sampler", str, apply_field("sampler_name"), format_value=format_value, confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers_for_img2img if x.name not in opts.hide_samplers]), + AxisOption("Checkpoint name", str, apply_checkpoint, format_value=format_remove_path, confirm=confirm_checkpoints, cost=1.0, choices=lambda: sorted(sd_models.checkpoints_list, key=str.casefold)), + AxisOption("Negative Guidance minimum sigma", float, apply_field("s_min_uncond")), + AxisOption("Sigma Churn", float, apply_field("s_churn")), + AxisOption("Sigma min", float, apply_field("s_tmin")), + AxisOption("Sigma max", float, apply_field("s_tmax")), + AxisOption("Sigma noise", float, apply_field("s_noise")), + AxisOption("Schedule type", str, apply_field("scheduler"), choices=lambda: [x.label for x in sd_schedulers.schedulers]), + AxisOption("Schedule min sigma", float, apply_override("sigma_min")), + AxisOption("Schedule max sigma", float, apply_override("sigma_max")), + AxisOption("Schedule rho", float, apply_override("rho")), + AxisOption("Beta schedule alpha", float, apply_override("beta_dist_alpha")), + AxisOption("Beta schedule beta", float, apply_override("beta_dist_beta")), + AxisOption("Eta", float, apply_field("eta")), + AxisOption("Clip skip", int, apply_override('CLIP_stop_at_last_layers')), + AxisOption("Denoising", float, apply_field("denoising_strength")), + AxisOption("Initial noise multiplier", float, apply_field("initial_noise_multiplier")), + AxisOption("Extra noise", float, apply_override("img2img_extra_noise")), + AxisOptionTxt2Img("Hires upscaler", str, apply_field("hr_upscaler"), choices=lambda: [*shared.latent_upscale_modes, *[x.name for x in shared.sd_upscalers]]), + AxisOptionImg2Img("Cond. Image Mask Weight", float, apply_field("inpainting_mask_weight")), + AxisOption("VAE", str, apply_vae, cost=0.7, choices=lambda: ['Automatic', 'None'] + list(sd_vae.vae_dict)), + AxisOption("Styles", str, apply_styles, choices=lambda: list(shared.prompt_styles.styles)), + AxisOption("UniPC Order", int, apply_uni_pc_order, cost=0.5), + AxisOption("Face restore", str, apply_face_restore, format_value=format_value), + AxisOption("Token merging ratio", float, apply_override('token_merging_ratio')), + AxisOption("Token merging ratio high-res", float, apply_override('token_merging_ratio_hr')), + AxisOption("Always discard next-to-last sigma", str, apply_override('always_discard_next_to_last_sigma', boolean=True), choices=boolean_choice(reverse=True)), + AxisOption("SGM noise multiplier", str, apply_override('sgm_noise_multiplier', boolean=True), choices=boolean_choice(reverse=True)), + AxisOption("Refiner checkpoint", str, apply_field('refiner_checkpoint'), format_value=format_remove_path, confirm=confirm_checkpoints_or_none, cost=1.0, choices=lambda: ['None'] + sorted(sd_models.checkpoints_list, key=str.casefold)), + AxisOption("Refiner switch at", float, apply_field('refiner_switch_at')), + AxisOption("RNG source", str, apply_override("randn_source"), choices=lambda: ["GPU", "CPU", "NV"]), + AxisOption("FP8 mode", str, apply_override("fp8_storage"), cost=0.9, choices=lambda: ["Disable", "Enable for SDXL", "Enable"]), + AxisOption("Size", str, apply_size), +] + + +def draw_xyz_grid(p, xs, ys, zs, x_labels, y_labels, z_labels, cell, draw_legend, include_lone_images, include_sub_grids, first_axes_processed, second_axes_processed, margin_size): + hor_texts = [[images.GridAnnotation(x)] for x in x_labels] + ver_texts = [[images.GridAnnotation(y)] for y in y_labels] + title_texts = [[images.GridAnnotation(z)] for z in z_labels] + + list_size = (len(xs) * len(ys) * len(zs)) + + processed_result = None + + state.job_count = list_size * p.n_iter + + def process_cell(x, y, z, ix, iy, iz): + nonlocal processed_result + + def index(ix, iy, iz): + return ix + iy * len(xs) + iz * len(xs) * len(ys) + + state.job = f"{index(ix, iy, iz) + 1} out of {list_size}" + + processed: Processed = cell(x, y, z, ix, iy, iz) + + if processed_result is None: + # Use our first processed result object as a template container to hold our full results + processed_result = copy(processed) + processed_result.images = [None] * list_size + processed_result.all_prompts = [None] * list_size + processed_result.all_seeds = [None] * list_size + processed_result.infotexts = [None] * list_size + processed_result.index_of_first_image = 1 + + idx = index(ix, iy, iz) + if processed.images: + # Non-empty list indicates some degree of success. + processed_result.images[idx] = processed.images[0] + processed_result.all_prompts[idx] = processed.prompt + processed_result.all_seeds[idx] = processed.seed + processed_result.infotexts[idx] = processed.infotexts[0] + else: + cell_mode = "P" + cell_size = (processed_result.width, processed_result.height) + if processed_result.images[0] is not None: + cell_mode = processed_result.images[0].mode + # This corrects size in case of batches: + cell_size = processed_result.images[0].size + processed_result.images[idx] = Image.new(cell_mode, cell_size) + + if first_axes_processed == 'x': + for ix, x in enumerate(xs): + if second_axes_processed == 'y': + for iy, y in enumerate(ys): + for iz, z in enumerate(zs): + process_cell(x, y, z, ix, iy, iz) + else: + for iz, z in enumerate(zs): + for iy, y in enumerate(ys): + process_cell(x, y, z, ix, iy, iz) + elif first_axes_processed == 'y': + for iy, y in enumerate(ys): + if second_axes_processed == 'x': + for ix, x in enumerate(xs): + for iz, z in enumerate(zs): + process_cell(x, y, z, ix, iy, iz) + else: + for iz, z in enumerate(zs): + for ix, x in enumerate(xs): + process_cell(x, y, z, ix, iy, iz) + elif first_axes_processed == 'z': + for iz, z in enumerate(zs): + if second_axes_processed == 'x': + for ix, x in enumerate(xs): + for iy, y in enumerate(ys): + process_cell(x, y, z, ix, iy, iz) + else: + for iy, y in enumerate(ys): + for ix, x in enumerate(xs): + process_cell(x, y, z, ix, iy, iz) + + if not processed_result: + # Should never happen, I've only seen it on one of four open tabs and it needed to refresh. + print("Unexpected error: Processing could not begin, you may need to refresh the tab or restart the service.") + return Processed(p, []) + elif not any(processed_result.images): + print("Unexpected error: draw_xyz_grid failed to return even a single processed image") + return Processed(p, []) + + z_count = len(zs) + + for i in range(z_count): + start_index = (i * len(xs) * len(ys)) + i + end_index = start_index + len(xs) * len(ys) + grid = images.image_grid(processed_result.images[start_index:end_index], rows=len(ys)) + if draw_legend: + grid_max_w, grid_max_h = map(max, zip(*(img.size for img in processed_result.images[start_index:end_index]))) + grid = images.draw_grid_annotations(grid, grid_max_w, grid_max_h, hor_texts, ver_texts, margin_size) + processed_result.images.insert(i, grid) + processed_result.all_prompts.insert(i, processed_result.all_prompts[start_index]) + processed_result.all_seeds.insert(i, processed_result.all_seeds[start_index]) + processed_result.infotexts.insert(i, processed_result.infotexts[start_index]) + + z_grid = images.image_grid(processed_result.images[:z_count], rows=1) + z_sub_grid_max_w, z_sub_grid_max_h = map(max, zip(*(img.size for img in processed_result.images[:z_count]))) + if draw_legend: + z_grid = images.draw_grid_annotations(z_grid, z_sub_grid_max_w, z_sub_grid_max_h, title_texts, [[images.GridAnnotation()]]) + processed_result.images.insert(0, z_grid) + # TODO: Deeper aspects of the program rely on grid info being misaligned between metadata arrays, which is not ideal. + # processed_result.all_prompts.insert(0, processed_result.all_prompts[0]) + # processed_result.all_seeds.insert(0, processed_result.all_seeds[0]) + processed_result.infotexts.insert(0, processed_result.infotexts[0]) + + return processed_result + + +class SharedSettingsStackHelper(object): + def __enter__(self): + pass + + def __exit__(self, exc_type, exc_value, tb): + modules.sd_models.reload_model_weights() + modules.sd_vae.reload_vae_weights() + + +re_range = re.compile(r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\(([+-]\d+)\s*\))?\s*") +re_range_float = re.compile(r"\s*([+-]?\s*\d+(?:.\d*)?)\s*-\s*([+-]?\s*\d+(?:.\d*)?)(?:\s*\(([+-]\d+(?:.\d*)?)\s*\))?\s*") + +re_range_count = re.compile(r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\[(\d+)\s*])?\s*") +re_range_count_float = re.compile(r"\s*([+-]?\s*\d+(?:.\d*)?)\s*-\s*([+-]?\s*\d+(?:.\d*)?)(?:\s*\[(\d+(?:.\d*)?)\s*])?\s*") + + +class Script(scripts.Script): + def title(self): + return "X/Y/Z plot" + + def ui(self, is_img2img): + self.current_axis_options = [x for x in axis_options if type(x) == AxisOption or x.is_img2img == is_img2img] + + with gr.Row(): + with gr.Column(scale=19): + with gr.Row(): + x_type = gr.Dropdown(label="X type", choices=[x.label for x in self.current_axis_options], value=self.current_axis_options[1].label, type="index", elem_id=self.elem_id("x_type")) + x_values = gr.Textbox(label="X values", lines=1, elem_id=self.elem_id("x_values")) + x_values_dropdown = gr.Dropdown(label="X values", visible=False, multiselect=True, interactive=True) + fill_x_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_x_tool_button", visible=False) + + with gr.Row(): + y_type = gr.Dropdown(label="Y type", choices=[x.label for x in self.current_axis_options], value=self.current_axis_options[0].label, type="index", elem_id=self.elem_id("y_type")) + y_values = gr.Textbox(label="Y values", lines=1, elem_id=self.elem_id("y_values")) + y_values_dropdown = gr.Dropdown(label="Y values", visible=False, multiselect=True, interactive=True) + fill_y_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_y_tool_button", visible=False) + + with gr.Row(): + z_type = gr.Dropdown(label="Z type", choices=[x.label for x in self.current_axis_options], value=self.current_axis_options[0].label, type="index", elem_id=self.elem_id("z_type")) + z_values = gr.Textbox(label="Z values", lines=1, elem_id=self.elem_id("z_values")) + z_values_dropdown = gr.Dropdown(label="Z values", visible=False, multiselect=True, interactive=True) + fill_z_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_z_tool_button", visible=False) + + with gr.Row(variant="compact", elem_id="axis_options"): + with gr.Column(): + draw_legend = gr.Checkbox(label='Draw legend', value=True, elem_id=self.elem_id("draw_legend")) + no_fixed_seeds = gr.Checkbox(label='Keep -1 for seeds', value=False, elem_id=self.elem_id("no_fixed_seeds")) + with gr.Row(): + vary_seeds_x = gr.Checkbox(label='Vary seeds for X', value=False, min_width=80, elem_id=self.elem_id("vary_seeds_x"), tooltip="Use different seeds for images along X axis.") + vary_seeds_y = gr.Checkbox(label='Vary seeds for Y', value=False, min_width=80, elem_id=self.elem_id("vary_seeds_y"), tooltip="Use different seeds for images along Y axis.") + vary_seeds_z = gr.Checkbox(label='Vary seeds for Z', value=False, min_width=80, elem_id=self.elem_id("vary_seeds_z"), tooltip="Use different seeds for images along Z axis.") + with gr.Column(): + include_lone_images = gr.Checkbox(label='Include Sub Images', value=False, elem_id=self.elem_id("include_lone_images")) + include_sub_grids = gr.Checkbox(label='Include Sub Grids', value=False, elem_id=self.elem_id("include_sub_grids")) + csv_mode = gr.Checkbox(label='Use text inputs instead of dropdowns', value=False, elem_id=self.elem_id("csv_mode")) + with gr.Column(): + margin_size = gr.Slider(label="Grid margins (px)", minimum=0, maximum=500, value=0, step=2, elem_id=self.elem_id("margin_size")) + + with gr.Row(variant="compact", elem_id="swap_axes"): + swap_xy_axes_button = gr.Button(value="Swap X/Y axes", elem_id="xy_grid_swap_axes_button") + swap_yz_axes_button = gr.Button(value="Swap Y/Z axes", elem_id="yz_grid_swap_axes_button") + swap_xz_axes_button = gr.Button(value="Swap X/Z axes", elem_id="xz_grid_swap_axes_button") + + def swap_axes(axis1_type, axis1_values, axis1_values_dropdown, axis2_type, axis2_values, axis2_values_dropdown): + return self.current_axis_options[axis2_type].label, axis2_values, axis2_values_dropdown, self.current_axis_options[axis1_type].label, axis1_values, axis1_values_dropdown + + xy_swap_args = [x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown] + swap_xy_axes_button.click(swap_axes, inputs=xy_swap_args, outputs=xy_swap_args) + yz_swap_args = [y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown] + swap_yz_axes_button.click(swap_axes, inputs=yz_swap_args, outputs=yz_swap_args) + xz_swap_args = [x_type, x_values, x_values_dropdown, z_type, z_values, z_values_dropdown] + swap_xz_axes_button.click(swap_axes, inputs=xz_swap_args, outputs=xz_swap_args) + + def fill(axis_type, csv_mode): + axis = self.current_axis_options[axis_type] + if axis.choices: + if csv_mode: + return list_to_csv_string(axis.choices()), gr.update() + else: + return gr.update(), axis.choices() + else: + return gr.update(), gr.update() + + fill_x_button.click(fn=fill, inputs=[x_type, csv_mode], outputs=[x_values, x_values_dropdown]) + fill_y_button.click(fn=fill, inputs=[y_type, csv_mode], outputs=[y_values, y_values_dropdown]) + fill_z_button.click(fn=fill, inputs=[z_type, csv_mode], outputs=[z_values, z_values_dropdown]) + + def select_axis(axis_type, axis_values, axis_values_dropdown, csv_mode): + axis_type = axis_type or 0 # if axle type is None set to 0 + + choices = self.current_axis_options[axis_type].choices + has_choices = choices is not None + + if has_choices: + choices = choices() + if csv_mode: + if axis_values_dropdown: + axis_values = list_to_csv_string(list(filter(lambda x: x in choices, axis_values_dropdown))) + axis_values_dropdown = [] + else: + if axis_values: + axis_values_dropdown = list(filter(lambda x: x in choices, csv_string_to_list_strip(axis_values))) + axis_values = "" + + return (gr.Button.update(visible=has_choices), gr.Textbox.update(visible=not has_choices or csv_mode, value=axis_values), + gr.update(choices=choices if has_choices else None, visible=has_choices and not csv_mode, value=axis_values_dropdown)) + + x_type.change(fn=select_axis, inputs=[x_type, x_values, x_values_dropdown, csv_mode], outputs=[fill_x_button, x_values, x_values_dropdown]) + y_type.change(fn=select_axis, inputs=[y_type, y_values, y_values_dropdown, csv_mode], outputs=[fill_y_button, y_values, y_values_dropdown]) + z_type.change(fn=select_axis, inputs=[z_type, z_values, z_values_dropdown, csv_mode], outputs=[fill_z_button, z_values, z_values_dropdown]) + + def change_choice_mode(csv_mode, x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown): + _fill_x_button, _x_values, _x_values_dropdown = select_axis(x_type, x_values, x_values_dropdown, csv_mode) + _fill_y_button, _y_values, _y_values_dropdown = select_axis(y_type, y_values, y_values_dropdown, csv_mode) + _fill_z_button, _z_values, _z_values_dropdown = select_axis(z_type, z_values, z_values_dropdown, csv_mode) + return _fill_x_button, _x_values, _x_values_dropdown, _fill_y_button, _y_values, _y_values_dropdown, _fill_z_button, _z_values, _z_values_dropdown + + csv_mode.change(fn=change_choice_mode, inputs=[csv_mode, x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown], outputs=[fill_x_button, x_values, x_values_dropdown, fill_y_button, y_values, y_values_dropdown, fill_z_button, z_values, z_values_dropdown]) + + def get_dropdown_update_from_params(axis, params): + val_key = f"{axis} Values" + vals = params.get(val_key, "") + valslist = csv_string_to_list_strip(vals) + return gr.update(value=valslist) + + self.infotext_fields = ( + (x_type, "X Type"), + (x_values, "X Values"), + (x_values_dropdown, lambda params: get_dropdown_update_from_params("X", params)), + (y_type, "Y Type"), + (y_values, "Y Values"), + (y_values_dropdown, lambda params: get_dropdown_update_from_params("Y", params)), + (z_type, "Z Type"), + (z_values, "Z Values"), + (z_values_dropdown, lambda params: get_dropdown_update_from_params("Z", params)), + ) + + return [x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown, draw_legend, include_lone_images, include_sub_grids, no_fixed_seeds, vary_seeds_x, vary_seeds_y, vary_seeds_z, margin_size, csv_mode] + + def run(self, p, x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown, draw_legend, include_lone_images, include_sub_grids, no_fixed_seeds, vary_seeds_x, vary_seeds_y, vary_seeds_z, margin_size, csv_mode): + x_type, y_type, z_type = x_type or 0, y_type or 0, z_type or 0 # if axle type is None set to 0 + + if not no_fixed_seeds: + modules.processing.fix_seed(p) + + if not opts.return_grid: + p.batch_size = 1 + + def process_axis(opt, vals, vals_dropdown): + if opt.label == 'Nothing': + return [0] + + if opt.choices is not None and not csv_mode: + valslist = vals_dropdown + elif opt.prepare is not None: + valslist = opt.prepare(vals) + else: + valslist = csv_string_to_list_strip(vals) + + if opt.type == int: + valslist_ext = [] + + for val in valslist: + if val.strip() == '': + continue + m = re_range.fullmatch(val) + mc = re_range_count.fullmatch(val) + if m is not None: + start = int(m.group(1)) + end = int(m.group(2)) + 1 + step = int(m.group(3)) if m.group(3) is not None else 1 + + valslist_ext += list(range(start, end, step)) + elif mc is not None: + start = int(mc.group(1)) + end = int(mc.group(2)) + num = int(mc.group(3)) if mc.group(3) is not None else 1 + + valslist_ext += [int(x) for x in np.linspace(start=start, stop=end, num=num).tolist()] + else: + valslist_ext.append(val) + + valslist = valslist_ext + elif opt.type == float: + valslist_ext = [] + + for val in valslist: + if val.strip() == '': + continue + m = re_range_float.fullmatch(val) + mc = re_range_count_float.fullmatch(val) + if m is not None: + start = float(m.group(1)) + end = float(m.group(2)) + step = float(m.group(3)) if m.group(3) is not None else 1 + + valslist_ext += np.arange(start, end + step, step).tolist() + elif mc is not None: + start = float(mc.group(1)) + end = float(mc.group(2)) + num = int(mc.group(3)) if mc.group(3) is not None else 1 + + valslist_ext += np.linspace(start=start, stop=end, num=num).tolist() + else: + valslist_ext.append(val) + + valslist = valslist_ext + elif opt.type == str_permutations: + valslist = list(permutations(valslist)) + + valslist = [opt.type(x) for x in valslist] + + # Confirm options are valid before starting + if opt.confirm: + opt.confirm(p, valslist) + + return valslist + + x_opt = self.current_axis_options[x_type] + if x_opt.choices is not None and not csv_mode: + x_values = list_to_csv_string(x_values_dropdown) + xs = process_axis(x_opt, x_values, x_values_dropdown) + + y_opt = self.current_axis_options[y_type] + if y_opt.choices is not None and not csv_mode: + y_values = list_to_csv_string(y_values_dropdown) + ys = process_axis(y_opt, y_values, y_values_dropdown) + + z_opt = self.current_axis_options[z_type] + if z_opt.choices is not None and not csv_mode: + z_values = list_to_csv_string(z_values_dropdown) + zs = process_axis(z_opt, z_values, z_values_dropdown) + + # this could be moved to common code, but unlikely to be ever triggered anywhere else + Image.MAX_IMAGE_PIXELS = None # disable check in Pillow and rely on check below to allow large custom image sizes + grid_mp = round(len(xs) * len(ys) * len(zs) * p.width * p.height / 1000000) + assert grid_mp < opts.img_max_size_mp, f'Error: Resulting grid would be too large ({grid_mp} MPixels) (max configured size is {opts.img_max_size_mp} MPixels)' + + def fix_axis_seeds(axis_opt, axis_list): + if axis_opt.label in ['Seed', 'Var. seed']: + return [int(random.randrange(4294967294)) if val is None or val == '' or val == -1 else val for val in axis_list] + else: + return axis_list + + if not no_fixed_seeds: + xs = fix_axis_seeds(x_opt, xs) + ys = fix_axis_seeds(y_opt, ys) + zs = fix_axis_seeds(z_opt, zs) + + if x_opt.label == 'Steps': + total_steps = sum(xs) * len(ys) * len(zs) + elif y_opt.label == 'Steps': + total_steps = sum(ys) * len(xs) * len(zs) + elif z_opt.label == 'Steps': + total_steps = sum(zs) * len(xs) * len(ys) + else: + total_steps = p.steps * len(xs) * len(ys) * len(zs) + + if isinstance(p, StableDiffusionProcessingTxt2Img) and p.enable_hr: + if x_opt.label == "Hires steps": + total_steps += sum(xs) * len(ys) * len(zs) + elif y_opt.label == "Hires steps": + total_steps += sum(ys) * len(xs) * len(zs) + elif z_opt.label == "Hires steps": + total_steps += sum(zs) * len(xs) * len(ys) + elif p.hr_second_pass_steps: + total_steps += p.hr_second_pass_steps * len(xs) * len(ys) * len(zs) + else: + total_steps *= 2 + + total_steps *= p.n_iter + + image_cell_count = p.n_iter * p.batch_size + cell_console_text = f"; {image_cell_count} images per cell" if image_cell_count > 1 else "" + plural_s = 's' if len(zs) > 1 else '' + print(f"X/Y/Z plot will create {len(xs) * len(ys) * len(zs) * image_cell_count} images on {len(zs)} {len(xs)}x{len(ys)} grid{plural_s}{cell_console_text}. (Total steps to process: {total_steps})") + shared.total_tqdm.updateTotal(total_steps) + + state.xyz_plot_x = AxisInfo(x_opt, xs) + state.xyz_plot_y = AxisInfo(y_opt, ys) + state.xyz_plot_z = AxisInfo(z_opt, zs) + + # If one of the axes is very slow to change between (like SD model + # checkpoint), then make sure it is in the outer iteration of the nested + # `for` loop. + first_axes_processed = 'z' + second_axes_processed = 'y' + if x_opt.cost > y_opt.cost and x_opt.cost > z_opt.cost: + first_axes_processed = 'x' + if y_opt.cost > z_opt.cost: + second_axes_processed = 'y' + else: + second_axes_processed = 'z' + elif y_opt.cost > x_opt.cost and y_opt.cost > z_opt.cost: + first_axes_processed = 'y' + if x_opt.cost > z_opt.cost: + second_axes_processed = 'x' + else: + second_axes_processed = 'z' + elif z_opt.cost > x_opt.cost and z_opt.cost > y_opt.cost: + first_axes_processed = 'z' + if x_opt.cost > y_opt.cost: + second_axes_processed = 'x' + else: + second_axes_processed = 'y' + + grid_infotext = [None] * (1 + len(zs)) + + def cell(x, y, z, ix, iy, iz): + if shared.state.interrupted or state.stopping_generation: + return Processed(p, [], p.seed, "") + + pc = copy(p) + pc.styles = pc.styles[:] + x_opt.apply(pc, x, xs) + y_opt.apply(pc, y, ys) + z_opt.apply(pc, z, zs) + + xdim = len(xs) if vary_seeds_x else 1 + ydim = len(ys) if vary_seeds_y else 1 + + if vary_seeds_x: + pc.seed += ix + if vary_seeds_y: + pc.seed += iy * xdim + if vary_seeds_z: + pc.seed += iz * xdim * ydim + + try: + res = process_images(pc) + except Exception as e: + errors.display(e, "generating image for xyz plot") + + res = Processed(p, [], p.seed, "") + + # Sets subgrid infotexts + subgrid_index = 1 + iz + if grid_infotext[subgrid_index] is None and ix == 0 and iy == 0: + pc.extra_generation_params = copy(pc.extra_generation_params) + pc.extra_generation_params['Script'] = self.title() + + if x_opt.label != 'Nothing': + pc.extra_generation_params["X Type"] = x_opt.label + pc.extra_generation_params["X Values"] = x_values + if x_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds: + pc.extra_generation_params["Fixed X Values"] = ", ".join([str(x) for x in xs]) + + if y_opt.label != 'Nothing': + pc.extra_generation_params["Y Type"] = y_opt.label + pc.extra_generation_params["Y Values"] = y_values + if y_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds: + pc.extra_generation_params["Fixed Y Values"] = ", ".join([str(y) for y in ys]) + + grid_infotext[subgrid_index] = processing.create_infotext(pc, pc.all_prompts, pc.all_seeds, pc.all_subseeds) + + # Sets main grid infotext + if grid_infotext[0] is None and ix == 0 and iy == 0 and iz == 0: + pc.extra_generation_params = copy(pc.extra_generation_params) + + if z_opt.label != 'Nothing': + pc.extra_generation_params["Z Type"] = z_opt.label + pc.extra_generation_params["Z Values"] = z_values + if z_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds: + pc.extra_generation_params["Fixed Z Values"] = ", ".join([str(z) for z in zs]) + + grid_infotext[0] = processing.create_infotext(pc, pc.all_prompts, pc.all_seeds, pc.all_subseeds) + + return res + + with SharedSettingsStackHelper(): + processed = draw_xyz_grid( + p, + xs=xs, + ys=ys, + zs=zs, + x_labels=[x_opt.format_value(p, x_opt, x) for x in xs], + y_labels=[y_opt.format_value(p, y_opt, y) for y in ys], + z_labels=[z_opt.format_value(p, z_opt, z) for z in zs], + cell=cell, + draw_legend=draw_legend, + include_lone_images=include_lone_images, + include_sub_grids=include_sub_grids, + first_axes_processed=first_axes_processed, + second_axes_processed=second_axes_processed, + margin_size=margin_size + ) + + if not processed.images: + # It broke, no further handling needed. + return processed + + z_count = len(zs) + + # Set the grid infotexts to the real ones with extra_generation_params (1 main grid + z_count sub-grids) + processed.infotexts[:1 + z_count] = grid_infotext[:1 + z_count] + + if not include_lone_images: + # Don't need sub-images anymore, drop from list: + processed.images = processed.images[:z_count + 1] + + if opts.grid_save: + # Auto-save main and sub-grids: + grid_count = z_count + 1 if z_count > 1 else 1 + for g in range(grid_count): + # TODO: See previous comment about intentional data misalignment. + adj_g = g - 1 if g > 0 else g + images.save_image(processed.images[g], p.outpath_grids, "xyz_grid", info=processed.infotexts[g], extension=opts.grid_format, prompt=processed.all_prompts[adj_g], seed=processed.all_seeds[adj_g], grid=True, p=processed) + if not include_sub_grids: # if not include_sub_grids then skip saving after the first grid + break + + if not include_sub_grids: + # Done with sub-grids, drop all related information: + for _ in range(z_count): + del processed.images[1] + del processed.all_prompts[1] + del processed.all_seeds[1] + del processed.infotexts[1] + + return processed
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/scripts/xyz_grid.py
Add docstrings that explain inputs and outputs
import argparse import asyncio import json import re import sys import time import traceback import xml.etree.ElementTree as ET from pathlib import Path from typing import Any from anthropic import Anthropic from connections import create_connection EVALUATION_PROMPT = """You are an AI assistant with access to tools. When given a task, you MUST: 1. Use the available tools to complete the task 2. Provide summary of each step in your approach, wrapped in <summary> tags 3. Provide feedback on the tools provided, wrapped in <feedback> tags 4. Provide your final response, wrapped in <response> tags Summary Requirements: - In your <summary> tags, you must explain: - The steps you took to complete the task - Which tools you used, in what order, and why - The inputs you provided to each tool - The outputs you received from each tool - A summary for how you arrived at the response Feedback Requirements: - In your <feedback> tags, provide constructive feedback on the tools: - Comment on tool names: Are they clear and descriptive? - Comment on input parameters: Are they well-documented? Are required vs optional parameters clear? - Comment on descriptions: Do they accurately describe what the tool does? - Comment on any errors encountered during tool usage: Did the tool fail to execute? Did the tool return too many tokens? - Identify specific areas for improvement and explain WHY they would help - Be specific and actionable in your suggestions Response Requirements: - Your response should be concise and directly address what was asked - Always wrap your final response in <response> tags - If you cannot solve the task return <response>NOT_FOUND</response> - For numeric responses, provide just the number - For IDs, provide just the ID - For names or text, provide the exact text requested - Your response should go last""" def parse_evaluation_file(file_path: Path) -> list[dict[str, Any]]: try: tree = ET.parse(file_path) root = tree.getroot() evaluations = [] for qa_pair in root.findall(".//qa_pair"): question_elem = qa_pair.find("question") answer_elem = qa_pair.find("answer") if question_elem is not None and answer_elem is not None: evaluations.append({ "question": (question_elem.text or "").strip(), "answer": (answer_elem.text or "").strip(), }) return evaluations except Exception as e: print(f"Error parsing evaluation file {file_path}: {e}") return [] def extract_xml_content(text: str, tag: str) -> str | None: pattern = rf"<{tag}>(.*?)</{tag}>" matches = re.findall(pattern, text, re.DOTALL) return matches[-1].strip() if matches else None async def agent_loop( client: Anthropic, model: str, question: str, tools: list[dict[str, Any]], connection: Any, ) -> tuple[str, dict[str, Any]]: messages = [{"role": "user", "content": question}] response = await asyncio.to_thread( client.messages.create, model=model, max_tokens=4096, system=EVALUATION_PROMPT, messages=messages, tools=tools, ) messages.append({"role": "assistant", "content": response.content}) tool_metrics = {} while response.stop_reason == "tool_use": tool_use = next(block for block in response.content if block.type == "tool_use") tool_name = tool_use.name tool_input = tool_use.input tool_start_ts = time.time() try: tool_result = await connection.call_tool(tool_name, tool_input) tool_response = json.dumps(tool_result) if isinstance(tool_result, (dict, list)) else str(tool_result) except Exception as e: tool_response = f"Error executing tool {tool_name}: {str(e)}\n" tool_response += traceback.format_exc() tool_duration = time.time() - tool_start_ts if tool_name not in tool_metrics: tool_metrics[tool_name] = {"count": 0, "durations": []} tool_metrics[tool_name]["count"] += 1 tool_metrics[tool_name]["durations"].append(tool_duration) messages.append({ "role": "user", "content": [{ "type": "tool_result", "tool_use_id": tool_use.id, "content": tool_response, }] }) response = await asyncio.to_thread( client.messages.create, model=model, max_tokens=4096, system=EVALUATION_PROMPT, messages=messages, tools=tools, ) messages.append({"role": "assistant", "content": response.content}) response_text = next( (block.text for block in response.content if hasattr(block, "text")), None, ) return response_text, tool_metrics async def evaluate_single_task( client: Anthropic, model: str, qa_pair: dict[str, Any], tools: list[dict[str, Any]], connection: Any, task_index: int, ) -> dict[str, Any]: start_time = time.time() print(f"Task {task_index + 1}: Running task with question: {qa_pair['question']}") response, tool_metrics = await agent_loop(client, model, qa_pair["question"], tools, connection) response_value = extract_xml_content(response, "response") summary = extract_xml_content(response, "summary") feedback = extract_xml_content(response, "feedback") duration_seconds = time.time() - start_time return { "question": qa_pair["question"], "expected": qa_pair["answer"], "actual": response_value, "score": int(response_value == qa_pair["answer"]) if response_value else 0, "total_duration": duration_seconds, "tool_calls": tool_metrics, "num_tool_calls": sum(len(metrics["durations"]) for metrics in tool_metrics.values()), "summary": summary, "feedback": feedback, } REPORT_HEADER = """ # Evaluation Report ## Summary - **Accuracy**: {correct}/{total} ({accuracy:.1f}%) - **Average Task Duration**: {average_duration_s:.2f}s - **Average Tool Calls per Task**: {average_tool_calls:.2f} - **Total Tool Calls**: {total_tool_calls} --- """ TASK_TEMPLATE = """ ### Task {task_num} **Question**: {question} **Ground Truth Answer**: `{expected_answer}` **Actual Answer**: `{actual_answer}` **Correct**: {correct_indicator} **Duration**: {total_duration:.2f}s **Tool Calls**: {tool_calls} **Summary** {summary} **Feedback** {feedback} --- """ async def run_evaluation( eval_path: Path, connection: Any, model: str = "claude-3-7-sonnet-20250219", ) -> str: print("🚀 Starting Evaluation") client = Anthropic() tools = await connection.list_tools() print(f"📋 Loaded {len(tools)} tools from MCP server") qa_pairs = parse_evaluation_file(eval_path) print(f"📋 Loaded {len(qa_pairs)} evaluation tasks") results = [] for i, qa_pair in enumerate(qa_pairs): print(f"Processing task {i + 1}/{len(qa_pairs)}") result = await evaluate_single_task(client, model, qa_pair, tools, connection, i) results.append(result) correct = sum(r["score"] for r in results) accuracy = (correct / len(results)) * 100 if results else 0 average_duration_s = sum(r["total_duration"] for r in results) / len(results) if results else 0 average_tool_calls = sum(r["num_tool_calls"] for r in results) / len(results) if results else 0 total_tool_calls = sum(r["num_tool_calls"] for r in results) report = REPORT_HEADER.format( correct=correct, total=len(results), accuracy=accuracy, average_duration_s=average_duration_s, average_tool_calls=average_tool_calls, total_tool_calls=total_tool_calls, ) report += "".join([ TASK_TEMPLATE.format( task_num=i + 1, question=qa_pair["question"], expected_answer=qa_pair["answer"], actual_answer=result["actual"] or "N/A", correct_indicator="✅" if result["score"] else "❌", total_duration=result["total_duration"], tool_calls=json.dumps(result["tool_calls"], indent=2), summary=result["summary"] or "N/A", feedback=result["feedback"] or "N/A", ) for i, (qa_pair, result) in enumerate(zip(qa_pairs, results)) ]) return report def parse_headers(header_list: list[str]) -> dict[str, str]: headers = {} if not header_list: return headers for header in header_list: if ":" in header: key, value = header.split(":", 1) headers[key.strip()] = value.strip() else: print(f"Warning: Ignoring malformed header: {header}") return headers def parse_env_vars(env_list: list[str]) -> dict[str, str]: env = {} if not env_list: return env for env_var in env_list: if "=" in env_var: key, value = env_var.split("=", 1) env[key.strip()] = value.strip() else: print(f"Warning: Ignoring malformed environment variable: {env_var}") return env async def main(): parser = argparse.ArgumentParser( description="Evaluate MCP servers using test questions", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: # Evaluate a local stdio MCP server python evaluation.py -t stdio -c python -a my_server.py eval.xml # Evaluate an SSE MCP server python evaluation.py -t sse -u https://example.com/mcp -H "Authorization: Bearer token" eval.xml # Evaluate an HTTP MCP server with custom model python evaluation.py -t http -u https://example.com/mcp -m claude-3-5-sonnet-20241022 eval.xml """, ) parser.add_argument("eval_file", type=Path, help="Path to evaluation XML file") parser.add_argument("-t", "--transport", choices=["stdio", "sse", "http"], default="stdio", help="Transport type (default: stdio)") parser.add_argument("-m", "--model", default="claude-3-7-sonnet-20250219", help="Claude model to use (default: claude-3-7-sonnet-20250219)") stdio_group = parser.add_argument_group("stdio options") stdio_group.add_argument("-c", "--command", help="Command to run MCP server (stdio only)") stdio_group.add_argument("-a", "--args", nargs="+", help="Arguments for the command (stdio only)") stdio_group.add_argument("-e", "--env", nargs="+", help="Environment variables in KEY=VALUE format (stdio only)") remote_group = parser.add_argument_group("sse/http options") remote_group.add_argument("-u", "--url", help="MCP server URL (sse/http only)") remote_group.add_argument("-H", "--header", nargs="+", dest="headers", help="HTTP headers in 'Key: Value' format (sse/http only)") parser.add_argument("-o", "--output", type=Path, help="Output file for evaluation report (default: stdout)") args = parser.parse_args() if not args.eval_file.exists(): print(f"Error: Evaluation file not found: {args.eval_file}") sys.exit(1) headers = parse_headers(args.headers) if args.headers else None env_vars = parse_env_vars(args.env) if args.env else None try: connection = create_connection( transport=args.transport, command=args.command, args=args.args, env=env_vars, url=args.url, headers=headers, ) except ValueError as e: print(f"Error: {e}") sys.exit(1) print(f"🔗 Connecting to MCP server via {args.transport}...") async with connection: print("✅ Connected successfully") report = await run_evaluation(args.eval_file, connection, args.model) if args.output: args.output.write_text(report) print(f"\n✅ Report saved to {args.output}") else: print("\n" + report) if __name__ == "__main__": asyncio.run(main())
--- +++ @@ -1,3 +1,7 @@+"""MCP Server Evaluation Harness + +This script evaluates MCP servers by running test questions against them using Claude. +""" import argparse import asyncio @@ -50,6 +54,7 @@ def parse_evaluation_file(file_path: Path) -> list[dict[str, Any]]: + """Parse XML evaluation file with qa_pair elements.""" try: tree = ET.parse(file_path) root = tree.getroot() @@ -72,6 +77,7 @@ def extract_xml_content(text: str, tag: str) -> str | None: + """Extract content from XML tags.""" pattern = rf"<{tag}>(.*?)</{tag}>" matches = re.findall(pattern, text, re.DOTALL) return matches[-1].strip() if matches else None @@ -84,6 +90,7 @@ tools: list[dict[str, Any]], connection: Any, ) -> tuple[str, dict[str, Any]]: + """Run the agent loop with MCP tools.""" messages = [{"role": "user", "content": question}] response = await asyncio.to_thread( @@ -152,6 +159,7 @@ connection: Any, task_index: int, ) -> dict[str, Any]: + """Evaluate a single QA pair with the given tools.""" start_time = time.time() print(f"Task {task_index + 1}: Running task with question: {qa_pair['question']}") @@ -214,6 +222,7 @@ connection: Any, model: str = "claude-3-7-sonnet-20250219", ) -> str: + """Run evaluation with MCP server tools.""" print("🚀 Starting Evaluation") client = Anthropic() @@ -264,6 +273,7 @@ def parse_headers(header_list: list[str]) -> dict[str, str]: + """Parse header strings in format 'Key: Value' into a dictionary.""" headers = {} if not header_list: return headers @@ -278,6 +288,7 @@ def parse_env_vars(env_list: list[str]) -> dict[str, str]: + """Parse environment variable strings in format 'KEY=VALUE' into a dictionary.""" env = {} if not env_list: return env @@ -359,4 +370,4 @@ if __name__ == "__main__": - asyncio.run(main())+ asyncio.run(main())
https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/mcp-builder/scripts/evaluation.py
Add docstrings to clarify complex logic
#!/usr/bin/env python3 import argparse import json import math import sys from datetime import datetime, timezone from pathlib import Path def calculate_stats(values: list[float]) -> dict: if not values: return {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0} n = len(values) mean = sum(values) / n if n > 1: variance = sum((x - mean) ** 2 for x in values) / (n - 1) stddev = math.sqrt(variance) else: stddev = 0.0 return { "mean": round(mean, 4), "stddev": round(stddev, 4), "min": round(min(values), 4), "max": round(max(values), 4) } def load_run_results(benchmark_dir: Path) -> dict: # Support both layouts: eval dirs directly under benchmark_dir, or under runs/ runs_dir = benchmark_dir / "runs" if runs_dir.exists(): search_dir = runs_dir elif list(benchmark_dir.glob("eval-*")): search_dir = benchmark_dir else: print(f"No eval directories found in {benchmark_dir} or {benchmark_dir / 'runs'}") return {} results: dict[str, list] = {} for eval_idx, eval_dir in enumerate(sorted(search_dir.glob("eval-*"))): metadata_path = eval_dir / "eval_metadata.json" if metadata_path.exists(): try: with open(metadata_path) as mf: eval_id = json.load(mf).get("eval_id", eval_idx) except (json.JSONDecodeError, OSError): eval_id = eval_idx else: try: eval_id = int(eval_dir.name.split("-")[1]) except ValueError: eval_id = eval_idx # Discover config directories dynamically rather than hardcoding names for config_dir in sorted(eval_dir.iterdir()): if not config_dir.is_dir(): continue # Skip non-config directories (inputs, outputs, etc.) if not list(config_dir.glob("run-*")): continue config = config_dir.name if config not in results: results[config] = [] for run_dir in sorted(config_dir.glob("run-*")): run_number = int(run_dir.name.split("-")[1]) grading_file = run_dir / "grading.json" if not grading_file.exists(): print(f"Warning: grading.json not found in {run_dir}") continue try: with open(grading_file) as f: grading = json.load(f) except json.JSONDecodeError as e: print(f"Warning: Invalid JSON in {grading_file}: {e}") continue # Extract metrics result = { "eval_id": eval_id, "run_number": run_number, "pass_rate": grading.get("summary", {}).get("pass_rate", 0.0), "passed": grading.get("summary", {}).get("passed", 0), "failed": grading.get("summary", {}).get("failed", 0), "total": grading.get("summary", {}).get("total", 0), } # Extract timing — check grading.json first, then sibling timing.json timing = grading.get("timing", {}) result["time_seconds"] = timing.get("total_duration_seconds", 0.0) timing_file = run_dir / "timing.json" if result["time_seconds"] == 0.0 and timing_file.exists(): try: with open(timing_file) as tf: timing_data = json.load(tf) result["time_seconds"] = timing_data.get("total_duration_seconds", 0.0) result["tokens"] = timing_data.get("total_tokens", 0) except json.JSONDecodeError: pass # Extract metrics if available metrics = grading.get("execution_metrics", {}) result["tool_calls"] = metrics.get("total_tool_calls", 0) if not result.get("tokens"): result["tokens"] = metrics.get("output_chars", 0) result["errors"] = metrics.get("errors_encountered", 0) # Extract expectations — viewer requires fields: text, passed, evidence raw_expectations = grading.get("expectations", []) for exp in raw_expectations: if "text" not in exp or "passed" not in exp: print(f"Warning: expectation in {grading_file} missing required fields (text, passed, evidence): {exp}") result["expectations"] = raw_expectations # Extract notes from user_notes_summary notes_summary = grading.get("user_notes_summary", {}) notes = [] notes.extend(notes_summary.get("uncertainties", [])) notes.extend(notes_summary.get("needs_review", [])) notes.extend(notes_summary.get("workarounds", [])) result["notes"] = notes results[config].append(result) return results def aggregate_results(results: dict) -> dict: run_summary = {} configs = list(results.keys()) for config in configs: runs = results.get(config, []) if not runs: run_summary[config] = { "pass_rate": {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0}, "time_seconds": {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0}, "tokens": {"mean": 0, "stddev": 0, "min": 0, "max": 0} } continue pass_rates = [r["pass_rate"] for r in runs] times = [r["time_seconds"] for r in runs] tokens = [r.get("tokens", 0) for r in runs] run_summary[config] = { "pass_rate": calculate_stats(pass_rates), "time_seconds": calculate_stats(times), "tokens": calculate_stats(tokens) } # Calculate delta between the first two configs (if two exist) if len(configs) >= 2: primary = run_summary.get(configs[0], {}) baseline = run_summary.get(configs[1], {}) else: primary = run_summary.get(configs[0], {}) if configs else {} baseline = {} delta_pass_rate = primary.get("pass_rate", {}).get("mean", 0) - baseline.get("pass_rate", {}).get("mean", 0) delta_time = primary.get("time_seconds", {}).get("mean", 0) - baseline.get("time_seconds", {}).get("mean", 0) delta_tokens = primary.get("tokens", {}).get("mean", 0) - baseline.get("tokens", {}).get("mean", 0) run_summary["delta"] = { "pass_rate": f"{delta_pass_rate:+.2f}", "time_seconds": f"{delta_time:+.1f}", "tokens": f"{delta_tokens:+.0f}" } return run_summary def generate_benchmark(benchmark_dir: Path, skill_name: str = "", skill_path: str = "") -> dict: results = load_run_results(benchmark_dir) run_summary = aggregate_results(results) # Build runs array for benchmark.json runs = [] for config in results: for result in results[config]: runs.append({ "eval_id": result["eval_id"], "configuration": config, "run_number": result["run_number"], "result": { "pass_rate": result["pass_rate"], "passed": result["passed"], "failed": result["failed"], "total": result["total"], "time_seconds": result["time_seconds"], "tokens": result.get("tokens", 0), "tool_calls": result.get("tool_calls", 0), "errors": result.get("errors", 0) }, "expectations": result["expectations"], "notes": result["notes"] }) # Determine eval IDs from results eval_ids = sorted(set( r["eval_id"] for config in results.values() for r in config )) benchmark = { "metadata": { "skill_name": skill_name or "<skill-name>", "skill_path": skill_path or "<path/to/skill>", "executor_model": "<model-name>", "analyzer_model": "<model-name>", "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "evals_run": eval_ids, "runs_per_configuration": 3 }, "runs": runs, "run_summary": run_summary, "notes": [] # To be filled by analyzer } return benchmark def generate_markdown(benchmark: dict) -> str: metadata = benchmark["metadata"] run_summary = benchmark["run_summary"] # Determine config names (excluding "delta") configs = [k for k in run_summary if k != "delta"] config_a = configs[0] if len(configs) >= 1 else "config_a" config_b = configs[1] if len(configs) >= 2 else "config_b" label_a = config_a.replace("_", " ").title() label_b = config_b.replace("_", " ").title() lines = [ f"# Skill Benchmark: {metadata['skill_name']}", "", f"**Model**: {metadata['executor_model']}", f"**Date**: {metadata['timestamp']}", f"**Evals**: {', '.join(map(str, metadata['evals_run']))} ({metadata['runs_per_configuration']} runs each per configuration)", "", "## Summary", "", f"| Metric | {label_a} | {label_b} | Delta |", "|--------|------------|---------------|-------|", ] a_summary = run_summary.get(config_a, {}) b_summary = run_summary.get(config_b, {}) delta = run_summary.get("delta", {}) # Format pass rate a_pr = a_summary.get("pass_rate", {}) b_pr = b_summary.get("pass_rate", {}) lines.append(f"| Pass Rate | {a_pr.get('mean', 0)*100:.0f}% ± {a_pr.get('stddev', 0)*100:.0f}% | {b_pr.get('mean', 0)*100:.0f}% ± {b_pr.get('stddev', 0)*100:.0f}% | {delta.get('pass_rate', '—')} |") # Format time a_time = a_summary.get("time_seconds", {}) b_time = b_summary.get("time_seconds", {}) lines.append(f"| Time | {a_time.get('mean', 0):.1f}s ± {a_time.get('stddev', 0):.1f}s | {b_time.get('mean', 0):.1f}s ± {b_time.get('stddev', 0):.1f}s | {delta.get('time_seconds', '—')}s |") # Format tokens a_tokens = a_summary.get("tokens", {}) b_tokens = b_summary.get("tokens", {}) lines.append(f"| Tokens | {a_tokens.get('mean', 0):.0f} ± {a_tokens.get('stddev', 0):.0f} | {b_tokens.get('mean', 0):.0f} ± {b_tokens.get('stddev', 0):.0f} | {delta.get('tokens', '—')} |") # Notes section if benchmark.get("notes"): lines.extend([ "", "## Notes", "" ]) for note in benchmark["notes"]: lines.append(f"- {note}") return "\n".join(lines) def main(): parser = argparse.ArgumentParser( description="Aggregate benchmark run results into summary statistics" ) parser.add_argument( "benchmark_dir", type=Path, help="Path to the benchmark directory" ) parser.add_argument( "--skill-name", default="", help="Name of the skill being benchmarked" ) parser.add_argument( "--skill-path", default="", help="Path to the skill being benchmarked" ) parser.add_argument( "--output", "-o", type=Path, help="Output path for benchmark.json (default: <benchmark_dir>/benchmark.json)" ) args = parser.parse_args() if not args.benchmark_dir.exists(): print(f"Directory not found: {args.benchmark_dir}") sys.exit(1) # Generate benchmark benchmark = generate_benchmark(args.benchmark_dir, args.skill_name, args.skill_path) # Determine output paths output_json = args.output or (args.benchmark_dir / "benchmark.json") output_md = output_json.with_suffix(".md") # Write benchmark.json with open(output_json, "w") as f: json.dump(benchmark, f, indent=2) print(f"Generated: {output_json}") # Write benchmark.md markdown = generate_markdown(benchmark) with open(output_md, "w") as f: f.write(markdown) print(f"Generated: {output_md}") # Print summary run_summary = benchmark["run_summary"] configs = [k for k in run_summary if k != "delta"] delta = run_summary.get("delta", {}) print(f"\nSummary:") for config in configs: pr = run_summary[config]["pass_rate"]["mean"] label = config.replace("_", " ").title() print(f" {label}: {pr*100:.1f}% pass rate") print(f" Delta: {delta.get('pass_rate', '—')}") if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,38 @@ #!/usr/bin/env python3 +""" +Aggregate individual run results into benchmark summary statistics. + +Reads grading.json files from run directories and produces: +- run_summary with mean, stddev, min, max for each metric +- delta between with_skill and without_skill configurations + +Usage: + python aggregate_benchmark.py <benchmark_dir> + +Example: + python aggregate_benchmark.py benchmarks/2026-01-15T10-30-00/ + +The script supports two directory layouts: + + Workspace layout (from skill-creator iterations): + <benchmark_dir>/ + └── eval-N/ + ├── with_skill/ + │ ├── run-1/grading.json + │ └── run-2/grading.json + └── without_skill/ + ├── run-1/grading.json + └── run-2/grading.json + + Legacy layout (with runs/ subdirectory): + <benchmark_dir>/ + └── runs/ + └── eval-N/ + ├── with_skill/ + │ └── run-1/grading.json + └── without_skill/ + └── run-1/grading.json +""" import argparse import json @@ -9,6 +43,7 @@ def calculate_stats(values: list[float]) -> dict: + """Calculate mean, stddev, min, max for a list of values.""" if not values: return {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0} @@ -30,6 +65,12 @@ def load_run_results(benchmark_dir: Path) -> dict: + """ + Load all run results from a benchmark directory. + + Returns dict keyed by config name (e.g. "with_skill"/"without_skill", + or "new_skill"/"old_skill"), each containing a list of run results. + """ # Support both layouts: eval dirs directly under benchmark_dir, or under runs/ runs_dir = benchmark_dir / "runs" if runs_dir.exists(): @@ -133,6 +174,11 @@ def aggregate_results(results: dict) -> dict: + """ + Aggregate run results into summary statistics. + + Returns run_summary with stats for each configuration and delta. + """ run_summary = {} configs = list(results.keys()) @@ -179,6 +225,9 @@ def generate_benchmark(benchmark_dir: Path, skill_name: str = "", skill_path: str = "") -> dict: + """ + Generate complete benchmark.json from run results. + """ results = load_run_results(benchmark_dir) run_summary = aggregate_results(results) @@ -230,6 +279,7 @@ def generate_markdown(benchmark: dict) -> str: + """Generate human-readable benchmark.md from benchmark data.""" metadata = benchmark["metadata"] run_summary = benchmark["run_summary"] @@ -348,4 +398,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/scripts/aggregate_benchmark.py
Create docstrings for all classes and functions
from pathlib import Path def parse_skill_md(skill_path: Path) -> tuple[str, str, str]: content = (skill_path / "SKILL.md").read_text() lines = content.split("\n") if lines[0].strip() != "---": raise ValueError("SKILL.md missing frontmatter (no opening ---)") end_idx = None for i, line in enumerate(lines[1:], start=1): if line.strip() == "---": end_idx = i break if end_idx is None: raise ValueError("SKILL.md missing frontmatter (no closing ---)") name = "" description = "" frontmatter_lines = lines[1:end_idx] i = 0 while i < len(frontmatter_lines): line = frontmatter_lines[i] if line.startswith("name:"): name = line[len("name:"):].strip().strip('"').strip("'") elif line.startswith("description:"): value = line[len("description:"):].strip() # Handle YAML multiline indicators (>, |, >-, |-) if value in (">", "|", ">-", "|-"): continuation_lines: list[str] = [] i += 1 while i < len(frontmatter_lines) and (frontmatter_lines[i].startswith(" ") or frontmatter_lines[i].startswith("\t")): continuation_lines.append(frontmatter_lines[i].strip()) i += 1 description = " ".join(continuation_lines) continue else: description = value.strip('"').strip("'") i += 1 return name, description, content
--- +++ @@ -1,9 +1,11 @@+"""Shared utilities for skill-creator scripts.""" from pathlib import Path def parse_skill_md(skill_path: Path) -> tuple[str, str, str]: + """Parse a SKILL.md file, returning (name, description, full_content).""" content = (skill_path / "SKILL.md").read_text() lines = content.split("\n") @@ -42,4 +44,4 @@ description = value.strip('"').strip("'") i += 1 - return name, description, content+ return name, description, content
https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/scripts/utils.py
Generate docstrings with parameter types
#!/usr/bin/env python3 import argparse import json import os import re import subprocess import sys from pathlib import Path from scripts.utils import parse_skill_md def _call_claude(prompt: str, model: str | None, timeout: int = 300) -> str: cmd = ["claude", "-p", "--output-format", "text"] if model: cmd.extend(["--model", model]) # Remove CLAUDECODE env var to allow nesting claude -p inside a # Claude Code session. The guard is for interactive terminal conflicts; # programmatic subprocess usage is safe. Same pattern as run_eval.py. env = {k: v for k, v in os.environ.items() if k != "CLAUDECODE"} result = subprocess.run( cmd, input=prompt, capture_output=True, text=True, env=env, timeout=timeout, ) if result.returncode != 0: raise RuntimeError( f"claude -p exited {result.returncode}\nstderr: {result.stderr}" ) return result.stdout def improve_description( skill_name: str, skill_content: str, current_description: str, eval_results: dict, history: list[dict], model: str, test_results: dict | None = None, log_dir: Path | None = None, iteration: int | None = None, ) -> str: failed_triggers = [ r for r in eval_results["results"] if r["should_trigger"] and not r["pass"] ] false_triggers = [ r for r in eval_results["results"] if not r["should_trigger"] and not r["pass"] ] # Build scores summary train_score = f"{eval_results['summary']['passed']}/{eval_results['summary']['total']}" if test_results: test_score = f"{test_results['summary']['passed']}/{test_results['summary']['total']}" scores_summary = f"Train: {train_score}, Test: {test_score}" else: scores_summary = f"Train: {train_score}" prompt = f"""You are optimizing a skill description for a Claude Code skill called "{skill_name}". A "skill" is sort of like a prompt, but with progressive disclosure -- there's a title and description that Claude sees when deciding whether to use the skill, and then if it does use the skill, it reads the .md file which has lots more details and potentially links to other resources in the skill folder like helper files and scripts and additional documentation or examples. The description appears in Claude's "available_skills" list. When a user sends a query, Claude decides whether to invoke the skill based solely on the title and on this description. Your goal is to write a description that triggers for relevant queries, and doesn't trigger for irrelevant ones. Here's the current description: <current_description> "{current_description}" </current_description> Current scores ({scores_summary}): <scores_summary> """ if failed_triggers: prompt += "FAILED TO TRIGGER (should have triggered but didn't):\n" for r in failed_triggers: prompt += f' - "{r["query"]}" (triggered {r["triggers"]}/{r["runs"]} times)\n' prompt += "\n" if false_triggers: prompt += "FALSE TRIGGERS (triggered but shouldn't have):\n" for r in false_triggers: prompt += f' - "{r["query"]}" (triggered {r["triggers"]}/{r["runs"]} times)\n' prompt += "\n" if history: prompt += "PREVIOUS ATTEMPTS (do NOT repeat these — try something structurally different):\n\n" for h in history: train_s = f"{h.get('train_passed', h.get('passed', 0))}/{h.get('train_total', h.get('total', 0))}" test_s = f"{h.get('test_passed', '?')}/{h.get('test_total', '?')}" if h.get('test_passed') is not None else None score_str = f"train={train_s}" + (f", test={test_s}" if test_s else "") prompt += f'<attempt {score_str}>\n' prompt += f'Description: "{h["description"]}"\n' if "results" in h: prompt += "Train results:\n" for r in h["results"]: status = "PASS" if r["pass"] else "FAIL" prompt += f' [{status}] "{r["query"][:80]}" (triggered {r["triggers"]}/{r["runs"]})\n' if h.get("note"): prompt += f'Note: {h["note"]}\n' prompt += "</attempt>\n\n" prompt += f"""</scores_summary> Skill content (for context on what the skill does): <skill_content> {skill_content} </skill_content> Based on the failures, write a new and improved description that is more likely to trigger correctly. When I say "based on the failures", it's a bit of a tricky line to walk because we don't want to overfit to the specific cases you're seeing. So what I DON'T want you to do is produce an ever-expanding list of specific queries that this skill should or shouldn't trigger for. Instead, try to generalize from the failures to broader categories of user intent and situations where this skill would be useful or not useful. The reason for this is twofold: 1. Avoid overfitting 2. The list might get loooong and it's injected into ALL queries and there might be a lot of skills, so we don't want to blow too much space on any given description. Concretely, your description should not be more than about 100-200 words, even if that comes at the cost of accuracy. There is a hard limit of 1024 characters — descriptions over that will be truncated, so stay comfortably under it. Here are some tips that we've found to work well in writing these descriptions: - The skill should be phrased in the imperative -- "Use this skill for" rather than "this skill does" - The skill description should focus on the user's intent, what they are trying to achieve, vs. the implementation details of how the skill works. - The description competes with other skills for Claude's attention — make it distinctive and immediately recognizable. - If you're getting lots of failures after repeated attempts, change things up. Try different sentence structures or wordings. I'd encourage you to be creative and mix up the style in different iterations since you'll have multiple opportunities to try different approaches and we'll just grab the highest-scoring one at the end. Please respond with only the new description text in <new_description> tags, nothing else.""" text = _call_claude(prompt, model) match = re.search(r"<new_description>(.*?)</new_description>", text, re.DOTALL) description = match.group(1).strip().strip('"') if match else text.strip().strip('"') transcript: dict = { "iteration": iteration, "prompt": prompt, "response": text, "parsed_description": description, "char_count": len(description), "over_limit": len(description) > 1024, } # Safety net: the prompt already states the 1024-char hard limit, but if # the model blew past it anyway, make one fresh single-turn call that # quotes the too-long version and asks for a shorter rewrite. (The old # SDK path did this as a true multi-turn; `claude -p` is one-shot, so we # inline the prior output into the new prompt instead.) if len(description) > 1024: shorten_prompt = ( f"{prompt}\n\n" f"---\n\n" f"A previous attempt produced this description, which at " f"{len(description)} characters is over the 1024-character hard limit:\n\n" f'"{description}"\n\n' f"Rewrite it to be under 1024 characters while keeping the most " f"important trigger words and intent coverage. Respond with only " f"the new description in <new_description> tags." ) shorten_text = _call_claude(shorten_prompt, model) match = re.search(r"<new_description>(.*?)</new_description>", shorten_text, re.DOTALL) shortened = match.group(1).strip().strip('"') if match else shorten_text.strip().strip('"') transcript["rewrite_prompt"] = shorten_prompt transcript["rewrite_response"] = shorten_text transcript["rewrite_description"] = shortened transcript["rewrite_char_count"] = len(shortened) description = shortened transcript["final_description"] = description if log_dir: log_dir.mkdir(parents=True, exist_ok=True) log_file = log_dir / f"improve_iter_{iteration or 'unknown'}.json" log_file.write_text(json.dumps(transcript, indent=2)) return description def main(): parser = argparse.ArgumentParser(description="Improve a skill description based on eval results") parser.add_argument("--eval-results", required=True, help="Path to eval results JSON (from run_eval.py)") parser.add_argument("--skill-path", required=True, help="Path to skill directory") parser.add_argument("--history", default=None, help="Path to history JSON (previous attempts)") parser.add_argument("--model", required=True, help="Model for improvement") parser.add_argument("--verbose", action="store_true", help="Print thinking to stderr") args = parser.parse_args() skill_path = Path(args.skill_path) if not (skill_path / "SKILL.md").exists(): print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr) sys.exit(1) eval_results = json.loads(Path(args.eval_results).read_text()) history = [] if args.history: history = json.loads(Path(args.history).read_text()) name, _, content = parse_skill_md(skill_path) current_description = eval_results["description"] if args.verbose: print(f"Current: {current_description}", file=sys.stderr) print(f"Score: {eval_results['summary']['passed']}/{eval_results['summary']['total']}", file=sys.stderr) new_description = improve_description( skill_name=name, skill_content=content, current_description=current_description, eval_results=eval_results, history=history, model=args.model, ) if args.verbose: print(f"Improved: {new_description}", file=sys.stderr) # Output as JSON with both the new description and updated history output = { "description": new_description, "history": history + [{ "description": current_description, "passed": eval_results["summary"]["passed"], "failed": eval_results["summary"]["failed"], "total": eval_results["summary"]["total"], "results": eval_results["results"], }], } print(json.dumps(output, indent=2)) if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3 +"""Improve a skill description based on eval results. + +Takes eval results (from run_eval.py) and generates an improved description +by calling `claude -p` as a subprocess (same auth pattern as run_eval.py — +uses the session's Claude Code auth, no separate ANTHROPIC_API_KEY needed). +""" import argparse import json @@ -12,6 +18,11 @@ def _call_claude(prompt: str, model: str | None, timeout: int = 300) -> str: + """Run `claude -p` with the prompt on stdin and return the text response. + + Prompt goes over stdin (not argv) because it embeds the full SKILL.md + body and can easily exceed comfortable argv length. + """ cmd = ["claude", "-p", "--output-format", "text"] if model: cmd.extend(["--model", model]) @@ -47,6 +58,7 @@ log_dir: Path | None = None, iteration: int | None = None, ) -> str: + """Call Claude to improve the description based on eval results.""" failed_triggers = [ r for r in eval_results["results"] if r["should_trigger"] and not r["pass"] @@ -232,4 +244,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/scripts/improve_description.py
Add professional docstrings to my codebase
#!/usr/bin/env python3 import argparse import base64 import json import mimetypes import os import re import signal import subprocess import sys import time import webbrowser from functools import partial from http.server import HTTPServer, BaseHTTPRequestHandler from pathlib import Path # Files to exclude from output listings METADATA_FILES = {"transcript.md", "user_notes.md", "metrics.json"} # Extensions we render as inline text TEXT_EXTENSIONS = { ".txt", ".md", ".json", ".csv", ".py", ".js", ".ts", ".tsx", ".jsx", ".yaml", ".yml", ".xml", ".html", ".css", ".sh", ".rb", ".go", ".rs", ".java", ".c", ".cpp", ".h", ".hpp", ".sql", ".r", ".toml", } # Extensions we render as inline images IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"} # MIME type overrides for common types MIME_OVERRIDES = { ".svg": "image/svg+xml", ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", } def get_mime_type(path: Path) -> str: ext = path.suffix.lower() if ext in MIME_OVERRIDES: return MIME_OVERRIDES[ext] mime, _ = mimetypes.guess_type(str(path)) return mime or "application/octet-stream" def find_runs(workspace: Path) -> list[dict]: runs: list[dict] = [] _find_runs_recursive(workspace, workspace, runs) runs.sort(key=lambda r: (r.get("eval_id", float("inf")), r["id"])) return runs def _find_runs_recursive(root: Path, current: Path, runs: list[dict]) -> None: if not current.is_dir(): return outputs_dir = current / "outputs" if outputs_dir.is_dir(): run = build_run(root, current) if run: runs.append(run) return skip = {"node_modules", ".git", "__pycache__", "skill", "inputs"} for child in sorted(current.iterdir()): if child.is_dir() and child.name not in skip: _find_runs_recursive(root, child, runs) def build_run(root: Path, run_dir: Path) -> dict | None: prompt = "" eval_id = None # Try eval_metadata.json for candidate in [run_dir / "eval_metadata.json", run_dir.parent / "eval_metadata.json"]: if candidate.exists(): try: metadata = json.loads(candidate.read_text()) prompt = metadata.get("prompt", "") eval_id = metadata.get("eval_id") except (json.JSONDecodeError, OSError): pass if prompt: break # Fall back to transcript.md if not prompt: for candidate in [run_dir / "transcript.md", run_dir / "outputs" / "transcript.md"]: if candidate.exists(): try: text = candidate.read_text() match = re.search(r"## Eval Prompt\n\n([\s\S]*?)(?=\n##|$)", text) if match: prompt = match.group(1).strip() except OSError: pass if prompt: break if not prompt: prompt = "(No prompt found)" run_id = str(run_dir.relative_to(root)).replace("/", "-").replace("\\", "-") # Collect output files outputs_dir = run_dir / "outputs" output_files: list[dict] = [] if outputs_dir.is_dir(): for f in sorted(outputs_dir.iterdir()): if f.is_file() and f.name not in METADATA_FILES: output_files.append(embed_file(f)) # Load grading if present grading = None for candidate in [run_dir / "grading.json", run_dir.parent / "grading.json"]: if candidate.exists(): try: grading = json.loads(candidate.read_text()) except (json.JSONDecodeError, OSError): pass if grading: break return { "id": run_id, "prompt": prompt, "eval_id": eval_id, "outputs": output_files, "grading": grading, } def embed_file(path: Path) -> dict: ext = path.suffix.lower() mime = get_mime_type(path) if ext in TEXT_EXTENSIONS: try: content = path.read_text(errors="replace") except OSError: content = "(Error reading file)" return { "name": path.name, "type": "text", "content": content, } elif ext in IMAGE_EXTENSIONS: try: raw = path.read_bytes() b64 = base64.b64encode(raw).decode("ascii") except OSError: return {"name": path.name, "type": "error", "content": "(Error reading file)"} return { "name": path.name, "type": "image", "mime": mime, "data_uri": f"data:{mime};base64,{b64}", } elif ext == ".pdf": try: raw = path.read_bytes() b64 = base64.b64encode(raw).decode("ascii") except OSError: return {"name": path.name, "type": "error", "content": "(Error reading file)"} return { "name": path.name, "type": "pdf", "data_uri": f"data:{mime};base64,{b64}", } elif ext == ".xlsx": try: raw = path.read_bytes() b64 = base64.b64encode(raw).decode("ascii") except OSError: return {"name": path.name, "type": "error", "content": "(Error reading file)"} return { "name": path.name, "type": "xlsx", "data_b64": b64, } else: # Binary / unknown — base64 download link try: raw = path.read_bytes() b64 = base64.b64encode(raw).decode("ascii") except OSError: return {"name": path.name, "type": "error", "content": "(Error reading file)"} return { "name": path.name, "type": "binary", "mime": mime, "data_uri": f"data:{mime};base64,{b64}", } def load_previous_iteration(workspace: Path) -> dict[str, dict]: result: dict[str, dict] = {} # Load feedback feedback_map: dict[str, str] = {} feedback_path = workspace / "feedback.json" if feedback_path.exists(): try: data = json.loads(feedback_path.read_text()) feedback_map = { r["run_id"]: r["feedback"] for r in data.get("reviews", []) if r.get("feedback", "").strip() } except (json.JSONDecodeError, OSError, KeyError): pass # Load runs (to get outputs) prev_runs = find_runs(workspace) for run in prev_runs: result[run["id"]] = { "feedback": feedback_map.get(run["id"], ""), "outputs": run.get("outputs", []), } # Also add feedback for run_ids that had feedback but no matching run for run_id, fb in feedback_map.items(): if run_id not in result: result[run_id] = {"feedback": fb, "outputs": []} return result def generate_html( runs: list[dict], skill_name: str, previous: dict[str, dict] | None = None, benchmark: dict | None = None, ) -> str: template_path = Path(__file__).parent / "viewer.html" template = template_path.read_text() # Build previous_feedback and previous_outputs maps for the template previous_feedback: dict[str, str] = {} previous_outputs: dict[str, list[dict]] = {} if previous: for run_id, data in previous.items(): if data.get("feedback"): previous_feedback[run_id] = data["feedback"] if data.get("outputs"): previous_outputs[run_id] = data["outputs"] embedded = { "skill_name": skill_name, "runs": runs, "previous_feedback": previous_feedback, "previous_outputs": previous_outputs, } if benchmark: embedded["benchmark"] = benchmark data_json = json.dumps(embedded) return template.replace("/*__EMBEDDED_DATA__*/", f"const EMBEDDED_DATA = {data_json};") # --------------------------------------------------------------------------- # HTTP server (stdlib only, zero dependencies) # --------------------------------------------------------------------------- def _kill_port(port: int) -> None: try: result = subprocess.run( ["lsof", "-ti", f":{port}"], capture_output=True, text=True, timeout=5, ) for pid_str in result.stdout.strip().split("\n"): if pid_str.strip(): try: os.kill(int(pid_str.strip()), signal.SIGTERM) except (ProcessLookupError, ValueError): pass if result.stdout.strip(): time.sleep(0.5) except subprocess.TimeoutExpired: pass except FileNotFoundError: print("Note: lsof not found, cannot check if port is in use", file=sys.stderr) class ReviewHandler(BaseHTTPRequestHandler): def __init__( self, workspace: Path, skill_name: str, feedback_path: Path, previous: dict[str, dict], benchmark_path: Path | None, *args, **kwargs, ): self.workspace = workspace self.skill_name = skill_name self.feedback_path = feedback_path self.previous = previous self.benchmark_path = benchmark_path super().__init__(*args, **kwargs) def do_GET(self) -> None: if self.path == "/" or self.path == "/index.html": # Regenerate HTML on each request (re-scans workspace for new outputs) runs = find_runs(self.workspace) benchmark = None if self.benchmark_path and self.benchmark_path.exists(): try: benchmark = json.loads(self.benchmark_path.read_text()) except (json.JSONDecodeError, OSError): pass html = generate_html(runs, self.skill_name, self.previous, benchmark) content = html.encode("utf-8") self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(content))) self.end_headers() self.wfile.write(content) elif self.path == "/api/feedback": data = b"{}" if self.feedback_path.exists(): data = self.feedback_path.read_bytes() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) else: self.send_error(404) def do_POST(self) -> None: if self.path == "/api/feedback": length = int(self.headers.get("Content-Length", 0)) body = self.rfile.read(length) try: data = json.loads(body) if not isinstance(data, dict) or "reviews" not in data: raise ValueError("Expected JSON object with 'reviews' key") self.feedback_path.write_text(json.dumps(data, indent=2) + "\n") resp = b'{"ok":true}' self.send_response(200) except (json.JSONDecodeError, OSError, ValueError) as e: resp = json.dumps({"error": str(e)}).encode() self.send_response(500) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(resp))) self.end_headers() self.wfile.write(resp) else: self.send_error(404) def log_message(self, format: str, *args: object) -> None: # Suppress request logging to keep terminal clean pass def main() -> None: parser = argparse.ArgumentParser(description="Generate and serve eval review") parser.add_argument("workspace", type=Path, help="Path to workspace directory") parser.add_argument("--port", "-p", type=int, default=3117, help="Server port (default: 3117)") parser.add_argument("--skill-name", "-n", type=str, default=None, help="Skill name for header") parser.add_argument( "--previous-workspace", type=Path, default=None, help="Path to previous iteration's workspace (shows old outputs and feedback as context)", ) parser.add_argument( "--benchmark", type=Path, default=None, help="Path to benchmark.json to show in the Benchmark tab", ) parser.add_argument( "--static", "-s", type=Path, default=None, help="Write standalone HTML to this path instead of starting a server", ) args = parser.parse_args() workspace = args.workspace.resolve() if not workspace.is_dir(): print(f"Error: {workspace} is not a directory", file=sys.stderr) sys.exit(1) runs = find_runs(workspace) if not runs: print(f"No runs found in {workspace}", file=sys.stderr) sys.exit(1) skill_name = args.skill_name or workspace.name.replace("-workspace", "") feedback_path = workspace / "feedback.json" previous: dict[str, dict] = {} if args.previous_workspace: previous = load_previous_iteration(args.previous_workspace.resolve()) benchmark_path = args.benchmark.resolve() if args.benchmark else None benchmark = None if benchmark_path and benchmark_path.exists(): try: benchmark = json.loads(benchmark_path.read_text()) except (json.JSONDecodeError, OSError): pass if args.static: html = generate_html(runs, skill_name, previous, benchmark) args.static.parent.mkdir(parents=True, exist_ok=True) args.static.write_text(html) print(f"\n Static viewer written to: {args.static}\n") sys.exit(0) # Kill any existing process on the target port port = args.port _kill_port(port) handler = partial(ReviewHandler, workspace, skill_name, feedback_path, previous, benchmark_path) try: server = HTTPServer(("127.0.0.1", port), handler) except OSError: # Port still in use after kill attempt — find a free one server = HTTPServer(("127.0.0.1", 0), handler) port = server.server_address[1] url = f"http://localhost:{port}" print(f"\n Eval Viewer") print(f" ─────────────────────────────────") print(f" URL: {url}") print(f" Workspace: {workspace}") print(f" Feedback: {feedback_path}") if previous: print(f" Previous: {args.previous_workspace} ({len(previous)} runs)") if benchmark_path: print(f" Benchmark: {benchmark_path}") print(f"\n Press Ctrl+C to stop.\n") webbrowser.open(url) try: server.serve_forever() except KeyboardInterrupt: print("\nStopped.") server.server_close() if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,16 @@ #!/usr/bin/env python3 +"""Generate and serve a review page for eval results. + +Reads the workspace directory, discovers runs (directories with outputs/), +embeds all output data into a self-contained HTML page, and serves it via +a tiny HTTP server. Feedback auto-saves to feedback.json in the workspace. + +Usage: + python generate_review.py <workspace-path> [--port PORT] [--skill-name NAME] + python generate_review.py <workspace-path> --previous-feedback /path/to/old/feedback.json + +No dependencies beyond the Python stdlib are required. +""" import argparse import base64 @@ -46,6 +58,7 @@ def find_runs(workspace: Path) -> list[dict]: + """Recursively find directories that contain an outputs/ subdirectory.""" runs: list[dict] = [] _find_runs_recursive(workspace, workspace, runs) runs.sort(key=lambda r: (r.get("eval_id", float("inf")), r["id"])) @@ -70,6 +83,7 @@ def build_run(root: Path, run_dir: Path) -> dict | None: + """Build a run dict with prompt, outputs, and grading data.""" prompt = "" eval_id = None @@ -133,6 +147,7 @@ def embed_file(path: Path) -> dict: + """Read a file and return an embedded representation.""" ext = path.suffix.lower() mime = get_mime_type(path) @@ -196,6 +211,10 @@ def load_previous_iteration(workspace: Path) -> dict[str, dict]: + """Load previous iteration's feedback and outputs. + + Returns a map of run_id -> {"feedback": str, "outputs": list[dict]}. + """ result: dict[str, dict] = {} # Load feedback @@ -234,6 +253,7 @@ previous: dict[str, dict] | None = None, benchmark: dict | None = None, ) -> str: + """Generate the complete standalone HTML page with embedded data.""" template_path = Path(__file__).parent / "viewer.html" template = template_path.read_text() @@ -266,6 +286,7 @@ # --------------------------------------------------------------------------- def _kill_port(port: int) -> None: + """Kill any process listening on the given port.""" try: result = subprocess.run( ["lsof", "-ti", f":{port}"], @@ -285,6 +306,11 @@ print("Note: lsof not found, cannot check if port is in use", file=sys.stderr) class ReviewHandler(BaseHTTPRequestHandler): + """Serves the review HTML and handles feedback saves. + + Regenerates the HTML on each page load so that refreshing the browser + picks up new eval outputs without restarting the server. + """ def __init__( self, @@ -442,4 +468,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/eval-viewer/generate_review.py
Add docstrings with type hints explained
#!/usr/bin/env python3 import argparse import json import random import sys import tempfile import time import webbrowser from pathlib import Path from scripts.generate_report import generate_html from scripts.improve_description import improve_description from scripts.run_eval import find_project_root, run_eval from scripts.utils import parse_skill_md def split_eval_set(eval_set: list[dict], holdout: float, seed: int = 42) -> tuple[list[dict], list[dict]]: random.seed(seed) # Separate by should_trigger trigger = [e for e in eval_set if e["should_trigger"]] no_trigger = [e for e in eval_set if not e["should_trigger"]] # Shuffle each group random.shuffle(trigger) random.shuffle(no_trigger) # Calculate split points n_trigger_test = max(1, int(len(trigger) * holdout)) n_no_trigger_test = max(1, int(len(no_trigger) * holdout)) # Split test_set = trigger[:n_trigger_test] + no_trigger[:n_no_trigger_test] train_set = trigger[n_trigger_test:] + no_trigger[n_no_trigger_test:] return train_set, test_set def run_loop( eval_set: list[dict], skill_path: Path, description_override: str | None, num_workers: int, timeout: int, max_iterations: int, runs_per_query: int, trigger_threshold: float, holdout: float, model: str, verbose: bool, live_report_path: Path | None = None, log_dir: Path | None = None, ) -> dict: project_root = find_project_root() name, original_description, content = parse_skill_md(skill_path) current_description = description_override or original_description # Split into train/test if holdout > 0 if holdout > 0: train_set, test_set = split_eval_set(eval_set, holdout) if verbose: print(f"Split: {len(train_set)} train, {len(test_set)} test (holdout={holdout})", file=sys.stderr) else: train_set = eval_set test_set = [] history = [] exit_reason = "unknown" for iteration in range(1, max_iterations + 1): if verbose: print(f"\n{'='*60}", file=sys.stderr) print(f"Iteration {iteration}/{max_iterations}", file=sys.stderr) print(f"Description: {current_description}", file=sys.stderr) print(f"{'='*60}", file=sys.stderr) # Evaluate train + test together in one batch for parallelism all_queries = train_set + test_set t0 = time.time() all_results = run_eval( eval_set=all_queries, skill_name=name, description=current_description, num_workers=num_workers, timeout=timeout, project_root=project_root, runs_per_query=runs_per_query, trigger_threshold=trigger_threshold, model=model, ) eval_elapsed = time.time() - t0 # Split results back into train/test by matching queries train_queries_set = {q["query"] for q in train_set} train_result_list = [r for r in all_results["results"] if r["query"] in train_queries_set] test_result_list = [r for r in all_results["results"] if r["query"] not in train_queries_set] train_passed = sum(1 for r in train_result_list if r["pass"]) train_total = len(train_result_list) train_summary = {"passed": train_passed, "failed": train_total - train_passed, "total": train_total} train_results = {"results": train_result_list, "summary": train_summary} if test_set: test_passed = sum(1 for r in test_result_list if r["pass"]) test_total = len(test_result_list) test_summary = {"passed": test_passed, "failed": test_total - test_passed, "total": test_total} test_results = {"results": test_result_list, "summary": test_summary} else: test_results = None test_summary = None history.append({ "iteration": iteration, "description": current_description, "train_passed": train_summary["passed"], "train_failed": train_summary["failed"], "train_total": train_summary["total"], "train_results": train_results["results"], "test_passed": test_summary["passed"] if test_summary else None, "test_failed": test_summary["failed"] if test_summary else None, "test_total": test_summary["total"] if test_summary else None, "test_results": test_results["results"] if test_results else None, # For backward compat with report generator "passed": train_summary["passed"], "failed": train_summary["failed"], "total": train_summary["total"], "results": train_results["results"], }) # Write live report if path provided if live_report_path: partial_output = { "original_description": original_description, "best_description": current_description, "best_score": "in progress", "iterations_run": len(history), "holdout": holdout, "train_size": len(train_set), "test_size": len(test_set), "history": history, } live_report_path.write_text(generate_html(partial_output, auto_refresh=True, skill_name=name)) if verbose: def print_eval_stats(label, results, elapsed): pos = [r for r in results if r["should_trigger"]] neg = [r for r in results if not r["should_trigger"]] tp = sum(r["triggers"] for r in pos) pos_runs = sum(r["runs"] for r in pos) fn = pos_runs - tp fp = sum(r["triggers"] for r in neg) neg_runs = sum(r["runs"] for r in neg) tn = neg_runs - fp total = tp + tn + fp + fn precision = tp / (tp + fp) if (tp + fp) > 0 else 1.0 recall = tp / (tp + fn) if (tp + fn) > 0 else 1.0 accuracy = (tp + tn) / total if total > 0 else 0.0 print(f"{label}: {tp+tn}/{total} correct, precision={precision:.0%} recall={recall:.0%} accuracy={accuracy:.0%} ({elapsed:.1f}s)", file=sys.stderr) for r in results: status = "PASS" if r["pass"] else "FAIL" rate_str = f"{r['triggers']}/{r['runs']}" print(f" [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:60]}", file=sys.stderr) print_eval_stats("Train", train_results["results"], eval_elapsed) if test_summary: print_eval_stats("Test ", test_results["results"], 0) if train_summary["failed"] == 0: exit_reason = f"all_passed (iteration {iteration})" if verbose: print(f"\nAll train queries passed on iteration {iteration}!", file=sys.stderr) break if iteration == max_iterations: exit_reason = f"max_iterations ({max_iterations})" if verbose: print(f"\nMax iterations reached ({max_iterations}).", file=sys.stderr) break # Improve the description based on train results if verbose: print(f"\nImproving description...", file=sys.stderr) t0 = time.time() # Strip test scores from history so improvement model can't see them blinded_history = [ {k: v for k, v in h.items() if not k.startswith("test_")} for h in history ] new_description = improve_description( skill_name=name, skill_content=content, current_description=current_description, eval_results=train_results, history=blinded_history, model=model, log_dir=log_dir, iteration=iteration, ) improve_elapsed = time.time() - t0 if verbose: print(f"Proposed ({improve_elapsed:.1f}s): {new_description}", file=sys.stderr) current_description = new_description # Find the best iteration by TEST score (or train if no test set) if test_set: best = max(history, key=lambda h: h["test_passed"] or 0) best_score = f"{best['test_passed']}/{best['test_total']}" else: best = max(history, key=lambda h: h["train_passed"]) best_score = f"{best['train_passed']}/{best['train_total']}" if verbose: print(f"\nExit reason: {exit_reason}", file=sys.stderr) print(f"Best score: {best_score} (iteration {best['iteration']})", file=sys.stderr) return { "exit_reason": exit_reason, "original_description": original_description, "best_description": best["description"], "best_score": best_score, "best_train_score": f"{best['train_passed']}/{best['train_total']}", "best_test_score": f"{best['test_passed']}/{best['test_total']}" if test_set else None, "final_description": current_description, "iterations_run": len(history), "holdout": holdout, "train_size": len(train_set), "test_size": len(test_set), "history": history, } def main(): parser = argparse.ArgumentParser(description="Run eval + improve loop") parser.add_argument("--eval-set", required=True, help="Path to eval set JSON file") parser.add_argument("--skill-path", required=True, help="Path to skill directory") parser.add_argument("--description", default=None, help="Override starting description") parser.add_argument("--num-workers", type=int, default=10, help="Number of parallel workers") parser.add_argument("--timeout", type=int, default=30, help="Timeout per query in seconds") parser.add_argument("--max-iterations", type=int, default=5, help="Max improvement iterations") parser.add_argument("--runs-per-query", type=int, default=3, help="Number of runs per query") parser.add_argument("--trigger-threshold", type=float, default=0.5, help="Trigger rate threshold") parser.add_argument("--holdout", type=float, default=0.4, help="Fraction of eval set to hold out for testing (0 to disable)") parser.add_argument("--model", required=True, help="Model for improvement") parser.add_argument("--verbose", action="store_true", help="Print progress to stderr") parser.add_argument("--report", default="auto", help="Generate HTML report at this path (default: 'auto' for temp file, 'none' to disable)") parser.add_argument("--results-dir", default=None, help="Save all outputs (results.json, report.html, log.txt) to a timestamped subdirectory here") args = parser.parse_args() eval_set = json.loads(Path(args.eval_set).read_text()) skill_path = Path(args.skill_path) if not (skill_path / "SKILL.md").exists(): print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr) sys.exit(1) name, _, _ = parse_skill_md(skill_path) # Set up live report path if args.report != "none": if args.report == "auto": timestamp = time.strftime("%Y%m%d_%H%M%S") live_report_path = Path(tempfile.gettempdir()) / f"skill_description_report_{skill_path.name}_{timestamp}.html" else: live_report_path = Path(args.report) # Open the report immediately so the user can watch live_report_path.write_text("<html><body><h1>Starting optimization loop...</h1><meta http-equiv='refresh' content='5'></body></html>") webbrowser.open(str(live_report_path)) else: live_report_path = None # Determine output directory (create before run_loop so logs can be written) if args.results_dir: timestamp = time.strftime("%Y-%m-%d_%H%M%S") results_dir = Path(args.results_dir) / timestamp results_dir.mkdir(parents=True, exist_ok=True) else: results_dir = None log_dir = results_dir / "logs" if results_dir else None output = run_loop( eval_set=eval_set, skill_path=skill_path, description_override=args.description, num_workers=args.num_workers, timeout=args.timeout, max_iterations=args.max_iterations, runs_per_query=args.runs_per_query, trigger_threshold=args.trigger_threshold, holdout=args.holdout, model=args.model, verbose=args.verbose, live_report_path=live_report_path, log_dir=log_dir, ) # Save JSON output json_output = json.dumps(output, indent=2) print(json_output) if results_dir: (results_dir / "results.json").write_text(json_output) # Write final HTML report (without auto-refresh) if live_report_path: live_report_path.write_text(generate_html(output, auto_refresh=False, skill_name=name)) print(f"\nReport: {live_report_path}", file=sys.stderr) if results_dir and live_report_path: (results_dir / "report.html").write_text(generate_html(output, auto_refresh=False, skill_name=name)) if results_dir: print(f"Results saved to: {results_dir}", file=sys.stderr) if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3 +"""Run the eval + improve loop until all pass or max iterations reached. + +Combines run_eval.py and improve_description.py in a loop, tracking history +and returning the best description found. Supports train/test split to prevent +overfitting. +""" import argparse import json @@ -16,6 +22,7 @@ def split_eval_set(eval_set: list[dict], holdout: float, seed: int = 42) -> tuple[list[dict], list[dict]]: + """Split eval set into train and test sets, stratified by should_trigger.""" random.seed(seed) # Separate by should_trigger @@ -52,6 +59,7 @@ live_report_path: Path | None = None, log_dir: Path | None = None, ) -> dict: + """Run the eval + improvement loop.""" project_root = find_project_root() name, original_description, content = parse_skill_md(skill_path) current_description = description_override or original_description @@ -317,4 +325,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/scripts/run_loop.py
Document helper functions with docstrings
import os import json from argparse import ArgumentParser from glob import glob from tqdm import tqdm import torch from safetensors.torch import load_file, save_file from kernel import weight_dequant def main(fp8_path, bf16_path): torch.set_default_dtype(torch.bfloat16) os.makedirs(bf16_path, exist_ok=True) model_index_file = os.path.join(fp8_path, "model.safetensors.index.json") with open(model_index_file, "r") as f: model_index = json.load(f) weight_map = model_index["weight_map"] # Cache for loaded safetensor files loaded_files = {} fp8_weight_names = [] # Helper function to get tensor from the correct file def get_tensor(tensor_name): file_name = weight_map[tensor_name] if file_name not in loaded_files: file_path = os.path.join(fp8_path, file_name) loaded_files[file_name] = load_file(file_path, device="cuda") return loaded_files[file_name][tensor_name] safetensor_files = list(glob(os.path.join(fp8_path, "*.safetensors"))) safetensor_files.sort() for safetensor_file in tqdm(safetensor_files): file_name = os.path.basename(safetensor_file) current_state_dict = load_file(safetensor_file, device="cuda") loaded_files[file_name] = current_state_dict new_state_dict = {} for weight_name, weight in current_state_dict.items(): if weight_name.endswith("_scale_inv"): continue elif weight.element_size() == 1: # FP8 weight scale_inv_name = f"{weight_name}_scale_inv" try: # Get scale_inv from the correct file scale_inv = get_tensor(scale_inv_name) fp8_weight_names.append(weight_name) new_state_dict[weight_name] = weight_dequant(weight, scale_inv) except KeyError: print(f"Warning: Missing scale_inv tensor for {weight_name}, skipping conversion") new_state_dict[weight_name] = weight else: new_state_dict[weight_name] = weight new_safetensor_file = os.path.join(bf16_path, file_name) save_file(new_state_dict, new_safetensor_file) # Memory management: keep only the 2 most recently used files if len(loaded_files) > 2: oldest_file = next(iter(loaded_files)) del loaded_files[oldest_file] torch.cuda.empty_cache() # Update model index new_model_index_file = os.path.join(bf16_path, "model.safetensors.index.json") for weight_name in fp8_weight_names: scale_inv_name = f"{weight_name}_scale_inv" if scale_inv_name in weight_map: weight_map.pop(scale_inv_name) with open(new_model_index_file, "w") as f: json.dump({"metadata": {}, "weight_map": weight_map}, f, indent=2) if __name__ == "__main__": parser = ArgumentParser() parser.add_argument("--input-fp8-hf-path", type=str, required=True) parser.add_argument("--output-bf16-hf-path", type=str, required=True) args = parser.parse_args() main(args.input_fp8_hf_path, args.output_bf16_hf_path)
--- +++ @@ -10,6 +10,25 @@ from kernel import weight_dequant def main(fp8_path, bf16_path): + """ + Converts FP8 weights to BF16 and saves the converted weights. + + This function reads FP8 weights from the specified directory, converts them to BF16, + and saves the converted weights to another specified directory. It also updates the + model index file to reflect the changes. + + Args: + fp8_path (str): The path to the directory containing the FP8 weights and model index file. + bf16_path (str): The path to the directory where the converted BF16 weights will be saved. + + Raises: + KeyError: If a required scale_inv tensor is missing for a weight. + + Notes: + - The function assumes that the FP8 weights are stored in safetensor files. + - The function caches loaded safetensor files to optimize memory usage. + - The function updates the model index file to remove references to scale_inv tensors. + """ torch.set_default_dtype(torch.bfloat16) os.makedirs(bf16_path, exist_ok=True) model_index_file = os.path.join(fp8_path, "model.safetensors.index.json") @@ -23,6 +42,18 @@ # Helper function to get tensor from the correct file def get_tensor(tensor_name): + """ + Retrieves a tensor from the cached safetensor files or loads it from disk if not cached. + + Args: + tensor_name (str): The name of the tensor to retrieve. + + Returns: + torch.Tensor: The retrieved tensor. + + Raises: + KeyError: If the tensor does not exist in the safetensor file. + """ file_name = weight_map[tensor_name] if file_name not in loaded_files: file_path = os.path.join(fp8_path, file_name) @@ -78,4 +109,4 @@ parser.add_argument("--output-bf16-hf-path", type=str, required=True) args = parser.parse_args() main(args.input_fp8_hf_path, args.output_bf16_hf_path) - +
https://raw.githubusercontent.com/deepseek-ai/DeepSeek-V3/HEAD/inference/fp8_cast_bf16.py
Create docstrings for API functions
#!/usr/bin/env python3 import fnmatch import sys import zipfile from pathlib import Path from scripts.quick_validate import validate_skill # Patterns to exclude when packaging skills. EXCLUDE_DIRS = {"__pycache__", "node_modules"} EXCLUDE_GLOBS = {"*.pyc"} EXCLUDE_FILES = {".DS_Store"} # Directories excluded only at the skill root (not when nested deeper). ROOT_EXCLUDE_DIRS = {"evals"} def should_exclude(rel_path: Path) -> bool: parts = rel_path.parts if any(part in EXCLUDE_DIRS for part in parts): return True # rel_path is relative to skill_path.parent, so parts[0] is the skill # folder name and parts[1] (if present) is the first subdir. if len(parts) > 1 and parts[1] in ROOT_EXCLUDE_DIRS: return True name = rel_path.name if name in EXCLUDE_FILES: return True return any(fnmatch.fnmatch(name, pat) for pat in EXCLUDE_GLOBS) def package_skill(skill_path, output_dir=None): skill_path = Path(skill_path).resolve() # Validate skill folder exists if not skill_path.exists(): print(f"❌ Error: Skill folder not found: {skill_path}") return None if not skill_path.is_dir(): print(f"❌ Error: Path is not a directory: {skill_path}") return None # Validate SKILL.md exists skill_md = skill_path / "SKILL.md" if not skill_md.exists(): print(f"❌ Error: SKILL.md not found in {skill_path}") return None # Run validation before packaging print("🔍 Validating skill...") valid, message = validate_skill(skill_path) if not valid: print(f"❌ Validation failed: {message}") print(" Please fix the validation errors before packaging.") return None print(f"✅ {message}\n") # Determine output location skill_name = skill_path.name if output_dir: output_path = Path(output_dir).resolve() output_path.mkdir(parents=True, exist_ok=True) else: output_path = Path.cwd() skill_filename = output_path / f"{skill_name}.skill" # Create the .skill file (zip format) try: with zipfile.ZipFile(skill_filename, 'w', zipfile.ZIP_DEFLATED) as zipf: # Walk through the skill directory, excluding build artifacts for file_path in skill_path.rglob('*'): if not file_path.is_file(): continue arcname = file_path.relative_to(skill_path.parent) if should_exclude(arcname): print(f" Skipped: {arcname}") continue zipf.write(file_path, arcname) print(f" Added: {arcname}") print(f"\n✅ Successfully packaged skill to: {skill_filename}") return skill_filename except Exception as e: print(f"❌ Error creating .skill file: {e}") return None def main(): if len(sys.argv) < 2: print("Usage: python utils/package_skill.py <path/to/skill-folder> [output-directory]") print("\nExample:") print(" python utils/package_skill.py skills/public/my-skill") print(" python utils/package_skill.py skills/public/my-skill ./dist") sys.exit(1) skill_path = sys.argv[1] output_dir = sys.argv[2] if len(sys.argv) > 2 else None print(f"📦 Packaging skill: {skill_path}") if output_dir: print(f" Output directory: {output_dir}") print() result = package_skill(skill_path, output_dir) if result: sys.exit(0) else: sys.exit(1) if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,14 @@ #!/usr/bin/env python3 +""" +Skill Packager - Creates a distributable .skill file of a skill folder + +Usage: + python utils/package_skill.py <path/to/skill-folder> [output-directory] + +Example: + python utils/package_skill.py skills/public/my-skill + python utils/package_skill.py skills/public/my-skill ./dist +""" import fnmatch import sys @@ -15,6 +25,7 @@ def should_exclude(rel_path: Path) -> bool: + """Check if a path should be excluded from packaging.""" parts = rel_path.parts if any(part in EXCLUDE_DIRS for part in parts): return True @@ -29,6 +40,16 @@ def package_skill(skill_path, output_dir=None): + """ + Package a skill folder into a .skill file. + + Args: + skill_path: Path to the skill folder + output_dir: Optional output directory for the .skill file (defaults to current directory) + + Returns: + Path to the created .skill file, or None if error + """ skill_path = Path(skill_path).resolve() # Validate skill folder exists @@ -112,4 +133,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/scripts/package_skill.py
Add docstrings to my Python code
#!/usr/bin/env python3 import argparse import json import os import select import subprocess import sys import time import uuid from concurrent.futures import ProcessPoolExecutor, as_completed from pathlib import Path from scripts.utils import parse_skill_md def find_project_root() -> Path: current = Path.cwd() for parent in [current, *current.parents]: if (parent / ".claude").is_dir(): return parent return current def run_single_query( query: str, skill_name: str, skill_description: str, timeout: int, project_root: str, model: str | None = None, ) -> bool: unique_id = uuid.uuid4().hex[:8] clean_name = f"{skill_name}-skill-{unique_id}" project_commands_dir = Path(project_root) / ".claude" / "commands" command_file = project_commands_dir / f"{clean_name}.md" try: project_commands_dir.mkdir(parents=True, exist_ok=True) # Use YAML block scalar to avoid breaking on quotes in description indented_desc = "\n ".join(skill_description.split("\n")) command_content = ( f"---\n" f"description: |\n" f" {indented_desc}\n" f"---\n\n" f"# {skill_name}\n\n" f"This skill handles: {skill_description}\n" ) command_file.write_text(command_content) cmd = [ "claude", "-p", query, "--output-format", "stream-json", "--verbose", "--include-partial-messages", ] if model: cmd.extend(["--model", model]) # Remove CLAUDECODE env var to allow nesting claude -p inside a # Claude Code session. The guard is for interactive terminal conflicts; # programmatic subprocess usage is safe. env = {k: v for k, v in os.environ.items() if k != "CLAUDECODE"} process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, cwd=project_root, env=env, ) triggered = False start_time = time.time() buffer = "" # Track state for stream event detection pending_tool_name = None accumulated_json = "" try: while time.time() - start_time < timeout: if process.poll() is not None: remaining = process.stdout.read() if remaining: buffer += remaining.decode("utf-8", errors="replace") break ready, _, _ = select.select([process.stdout], [], [], 1.0) if not ready: continue chunk = os.read(process.stdout.fileno(), 8192) if not chunk: break buffer += chunk.decode("utf-8", errors="replace") while "\n" in buffer: line, buffer = buffer.split("\n", 1) line = line.strip() if not line: continue try: event = json.loads(line) except json.JSONDecodeError: continue # Early detection via stream events if event.get("type") == "stream_event": se = event.get("event", {}) se_type = se.get("type", "") if se_type == "content_block_start": cb = se.get("content_block", {}) if cb.get("type") == "tool_use": tool_name = cb.get("name", "") if tool_name in ("Skill", "Read"): pending_tool_name = tool_name accumulated_json = "" else: return False elif se_type == "content_block_delta" and pending_tool_name: delta = se.get("delta", {}) if delta.get("type") == "input_json_delta": accumulated_json += delta.get("partial_json", "") if clean_name in accumulated_json: return True elif se_type in ("content_block_stop", "message_stop"): if pending_tool_name: return clean_name in accumulated_json if se_type == "message_stop": return False # Fallback: full assistant message elif event.get("type") == "assistant": message = event.get("message", {}) for content_item in message.get("content", []): if content_item.get("type") != "tool_use": continue tool_name = content_item.get("name", "") tool_input = content_item.get("input", {}) if tool_name == "Skill" and clean_name in tool_input.get("skill", ""): triggered = True elif tool_name == "Read" and clean_name in tool_input.get("file_path", ""): triggered = True return triggered elif event.get("type") == "result": return triggered finally: # Clean up process on any exit path (return, exception, timeout) if process.poll() is None: process.kill() process.wait() return triggered finally: if command_file.exists(): command_file.unlink() def run_eval( eval_set: list[dict], skill_name: str, description: str, num_workers: int, timeout: int, project_root: Path, runs_per_query: int = 1, trigger_threshold: float = 0.5, model: str | None = None, ) -> dict: results = [] with ProcessPoolExecutor(max_workers=num_workers) as executor: future_to_info = {} for item in eval_set: for run_idx in range(runs_per_query): future = executor.submit( run_single_query, item["query"], skill_name, description, timeout, str(project_root), model, ) future_to_info[future] = (item, run_idx) query_triggers: dict[str, list[bool]] = {} query_items: dict[str, dict] = {} for future in as_completed(future_to_info): item, _ = future_to_info[future] query = item["query"] query_items[query] = item if query not in query_triggers: query_triggers[query] = [] try: query_triggers[query].append(future.result()) except Exception as e: print(f"Warning: query failed: {e}", file=sys.stderr) query_triggers[query].append(False) for query, triggers in query_triggers.items(): item = query_items[query] trigger_rate = sum(triggers) / len(triggers) should_trigger = item["should_trigger"] if should_trigger: did_pass = trigger_rate >= trigger_threshold else: did_pass = trigger_rate < trigger_threshold results.append({ "query": query, "should_trigger": should_trigger, "trigger_rate": trigger_rate, "triggers": sum(triggers), "runs": len(triggers), "pass": did_pass, }) passed = sum(1 for r in results if r["pass"]) total = len(results) return { "skill_name": skill_name, "description": description, "results": results, "summary": { "total": total, "passed": passed, "failed": total - passed, }, } def main(): parser = argparse.ArgumentParser(description="Run trigger evaluation for a skill description") parser.add_argument("--eval-set", required=True, help="Path to eval set JSON file") parser.add_argument("--skill-path", required=True, help="Path to skill directory") parser.add_argument("--description", default=None, help="Override description to test") parser.add_argument("--num-workers", type=int, default=10, help="Number of parallel workers") parser.add_argument("--timeout", type=int, default=30, help="Timeout per query in seconds") parser.add_argument("--runs-per-query", type=int, default=3, help="Number of runs per query") parser.add_argument("--trigger-threshold", type=float, default=0.5, help="Trigger rate threshold") parser.add_argument("--model", default=None, help="Model to use for claude -p (default: user's configured model)") parser.add_argument("--verbose", action="store_true", help="Print progress to stderr") args = parser.parse_args() eval_set = json.loads(Path(args.eval_set).read_text()) skill_path = Path(args.skill_path) if not (skill_path / "SKILL.md").exists(): print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr) sys.exit(1) name, original_description, content = parse_skill_md(skill_path) description = args.description or original_description project_root = find_project_root() if args.verbose: print(f"Evaluating: {description}", file=sys.stderr) output = run_eval( eval_set=eval_set, skill_name=name, description=description, num_workers=args.num_workers, timeout=args.timeout, project_root=project_root, runs_per_query=args.runs_per_query, trigger_threshold=args.trigger_threshold, model=args.model, ) if args.verbose: summary = output["summary"] print(f"Results: {summary['passed']}/{summary['total']} passed", file=sys.stderr) for r in output["results"]: status = "PASS" if r["pass"] else "FAIL" rate_str = f"{r['triggers']}/{r['runs']}" print(f" [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:70]}", file=sys.stderr) print(json.dumps(output, indent=2)) if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +"""Run trigger evaluation for a skill description. + +Tests whether a skill's description causes Claude to trigger (read the skill) +for a set of queries. Outputs results as JSON. +""" import argparse import json @@ -15,6 +20,11 @@ def find_project_root() -> Path: + """Find the project root by walking up from cwd looking for .claude/. + + Mimics how Claude Code discovers its project root, so the command file + we create ends up where claude -p will look for it. + """ current = Path.cwd() for parent in [current, *current.parents]: if (parent / ".claude").is_dir(): @@ -30,6 +40,14 @@ project_root: str, model: str | None = None, ) -> bool: + """Run a single query and return whether the skill was triggered. + + Creates a command file in .claude/commands/ so it appears in Claude's + available_skills list, then runs `claude -p` with the raw query. + Uses --include-partial-messages to detect triggering early from + stream events (content_block_start) rather than waiting for the + full assistant message, which only arrives after tool execution. + """ unique_id = uuid.uuid4().hex[:8] clean_name = f"{skill_name}-skill-{unique_id}" project_commands_dir = Path(project_root) / ".claude" / "commands" @@ -174,6 +192,7 @@ trigger_threshold: float = 0.5, model: str | None = None, ) -> dict: + """Run the full eval set and return results.""" results = [] with ProcessPoolExecutor(max_workers=num_workers) as executor: @@ -288,4 +307,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/scripts/run_eval.py
Write docstrings describing functionality
import os import json from argparse import ArgumentParser from typing import List import torch import torch.distributed as dist from transformers import AutoTokenizer from safetensors.torch import load_model from model import Transformer, ModelArgs def sample(logits, temperature: float = 1.0): logits = logits / max(temperature, 1e-5) probs = torch.softmax(logits, dim=-1) return probs.div_(torch.empty_like(probs).exponential_(1)).argmax(dim=-1) @torch.inference_mode() def generate( model: Transformer, prompt_tokens: List[List[int]], max_new_tokens: int, eos_id: int, temperature: float = 1.0 ) -> List[List[int]]: prompt_lens = [len(t) for t in prompt_tokens] assert max(prompt_lens) <= model.max_seq_len, f"Prompt length exceeds model maximum sequence length (max_seq_len={model.max_seq_len})" total_len = min(model.max_seq_len, max_new_tokens + max(prompt_lens)) tokens = torch.full((len(prompt_tokens), total_len), -1, dtype=torch.long, device="cuda") for i, t in enumerate(prompt_tokens): tokens[i, :len(t)] = torch.tensor(t, dtype=torch.long, device="cuda") prev_pos = 0 finished = torch.tensor([False] * len(prompt_tokens), device="cuda") prompt_mask = tokens != -1 for cur_pos in range(min(prompt_lens), total_len): logits = model.forward(tokens[:, prev_pos:cur_pos], prev_pos) if temperature > 0: next_token = sample(logits, temperature) else: next_token = logits.argmax(dim=-1) next_token = torch.where(prompt_mask[:, cur_pos], tokens[:, cur_pos], next_token) tokens[:, cur_pos] = next_token finished |= torch.logical_and(~prompt_mask[:, cur_pos], next_token == eos_id) prev_pos = cur_pos if finished.all(): break completion_tokens = [] for i, toks in enumerate(tokens.tolist()): toks = toks[prompt_lens[i]:prompt_lens[i]+max_new_tokens] if eos_id in toks: toks = toks[:toks.index(eos_id)] completion_tokens.append(toks) return completion_tokens def main( ckpt_path: str, config: str, input_file: str = "", interactive: bool = True, max_new_tokens: int = 100, temperature: float = 1.0, ) -> None: world_size = int(os.getenv("WORLD_SIZE", "1")) rank = int(os.getenv("RANK", "0")) local_rank = int(os.getenv("LOCAL_RANK", "0")) if world_size > 1: dist.init_process_group("nccl") global print if rank != 0: print = lambda *_, **__: None torch.cuda.set_device(local_rank) torch.set_default_dtype(torch.bfloat16) torch.set_num_threads(8) torch.manual_seed(965) with open(config) as f: args = ModelArgs(**json.load(f)) print(args) with torch.device("cuda"): model = Transformer(args) tokenizer = AutoTokenizer.from_pretrained(ckpt_path) tokenizer.decode(generate(model, [tokenizer.encode("DeepSeek")], 2, -1, 1.)[0]) load_model(model, os.path.join(ckpt_path, f"model{rank}-mp{world_size}.safetensors")) if interactive: messages = [] while True: if world_size == 1: prompt = input(">>> ") elif rank == 0: prompt = input(">>> ") objects = [prompt] dist.broadcast_object_list(objects, 0) else: objects = [None] dist.broadcast_object_list(objects, 0) prompt = objects[0] if prompt == "/exit": break elif prompt == "/clear": messages.clear() continue messages.append({"role": "user", "content": prompt}) prompt_tokens = tokenizer.apply_chat_template(messages, add_generation_prompt=True) completion_tokens = generate(model, [prompt_tokens], max_new_tokens, tokenizer.eos_token_id, temperature) completion = tokenizer.decode(completion_tokens[0], skip_special_tokens=True) print(completion) messages.append({"role": "assistant", "content": completion}) else: with open(input_file) as f: prompts = [line.strip() for line in f.readlines()] assert len(prompts) <= args.max_batch_size, f"Number of prompts exceeds maximum batch size ({args.max_batch_size})" prompt_tokens = [tokenizer.apply_chat_template([{"role": "user", "content": prompt}], add_generation_prompt=True) for prompt in prompts] completion_tokens = generate(model, prompt_tokens, max_new_tokens, tokenizer.eos_token_id, temperature) completions = tokenizer.batch_decode(completion_tokens, skip_special_tokens=True) for prompt, completion in zip(prompts, completions): print("Prompt:", prompt) print("Completion:", completion) print() if world_size > 1: dist.destroy_process_group() if __name__ == "__main__": """ Command-line interface for distributed text generation. Arguments: --ckpt-path (str): Path to the model checkpoint directory. --config (str): Path to the model configuration file. --input-file (str, optional): File containing prompts for batch processing. --interactive (bool, optional): Enable interactive mode for generating text. --max-new-tokens (int, optional): Maximum number of new tokens to generate. Defaults to 200. --temperature (float, optional): Temperature for sampling. Defaults to 0.2. Raises: AssertionError: If neither input-file nor interactive mode is specified. """ parser = ArgumentParser() parser.add_argument("--ckpt-path", type=str, required=True) parser.add_argument("--config", type=str, required=True) parser.add_argument("--input-file", type=str, default="") parser.add_argument("--interactive", action="store_true") parser.add_argument("--max-new-tokens", type=int, default=200) parser.add_argument("--temperature", type=float, default=0.2) args = parser.parse_args() assert args.input_file or args.interactive, "Either input-file or interactive mode must be specified" main(args.ckpt_path, args.config, args.input_file, args.interactive, args.max_new_tokens, args.temperature)
--- +++ @@ -12,6 +12,16 @@ def sample(logits, temperature: float = 1.0): + """ + Samples a token from the logits using temperature scaling. + + Args: + logits (torch.Tensor): The logits tensor for token predictions. + temperature (float, optional): Temperature for scaling logits. Defaults to 1.0. + + Returns: + torch.Tensor: The sampled token. + """ logits = logits / max(temperature, 1e-5) probs = torch.softmax(logits, dim=-1) return probs.div_(torch.empty_like(probs).exponential_(1)).argmax(dim=-1) @@ -25,6 +35,19 @@ eos_id: int, temperature: float = 1.0 ) -> List[List[int]]: + """ + Generates new tokens based on the given prompt tokens using the specified model. + + Args: + model (Transformer): The transformer model used for token generation. + prompt_tokens (List[List[int]]): A list of lists containing the prompt tokens for each sequence. + max_new_tokens (int): The maximum number of new tokens to generate. + eos_id (int): The end-of-sequence token ID. + temperature (float, optional): The temperature value for sampling. Defaults to 1.0. + + Returns: + List[List[int]]: A list of lists containing the generated tokens for each sequence. + """ prompt_lens = [len(t) for t in prompt_tokens] assert max(prompt_lens) <= model.max_seq_len, f"Prompt length exceeds model maximum sequence length (max_seq_len={model.max_seq_len})" total_len = min(model.max_seq_len, max_new_tokens + max(prompt_lens)) @@ -63,6 +86,17 @@ max_new_tokens: int = 100, temperature: float = 1.0, ) -> None: + """ + Main function to load the model and perform interactive or batch text generation. + + Args: + ckpt_path (str): Path to the model checkpoint directory. + config (str): Path to the model configuration file. + input_file (str, optional): Path to a file containing input prompts. Defaults to "". + interactive (bool, optional): Whether to run in interactive mode. Defaults to True. + max_new_tokens (int, optional): Maximum number of new tokens to generate. Defaults to 100. + temperature (float, optional): Temperature for sampling. Defaults to 1.0. + """ world_size = int(os.getenv("WORLD_SIZE", "1")) rank = int(os.getenv("RANK", "0")) local_rank = int(os.getenv("LOCAL_RANK", "0")) @@ -148,4 +182,4 @@ parser.add_argument("--temperature", type=float, default=0.2) args = parser.parse_args() assert args.input_file or args.interactive, "Either input-file or interactive mode must be specified" - main(args.ckpt_path, args.config, args.input_file, args.interactive, args.max_new_tokens, args.temperature)+ main(args.ckpt_path, args.config, args.input_file, args.interactive, args.max_new_tokens, args.temperature)
https://raw.githubusercontent.com/deepseek-ai/DeepSeek-V3/HEAD/inference/generate.py
Create Google-style docstrings for my code
from typing import Tuple, Optional import torch import triton import triton.language as tl from triton import Config @triton.jit def act_quant_kernel(x_ptr, y_ptr, s_ptr, BLOCK_SIZE: tl.constexpr, scale_fmt: tl.constexpr): pid = tl.program_id(axis=0) offs = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) x = tl.load(x_ptr + offs).to(tl.float32) amax = tl.max(tl.abs(x)) # reduction amax = tl.maximum(amax, 1e-4) # clamp to 1e-4 s = amax / 448. if scale_fmt == "ue8m0": exp = tl.math.ceil(tl.math.log2(s)) s = tl.math.exp2(exp) y = x / s y = y.to(y_ptr.dtype.element_ty) tl.store(y_ptr + offs, y) tl.store(s_ptr + pid, s) def act_quant(x: torch.Tensor, block_size: int = 128, scale_fmt: Optional[str] = None) -> Tuple[torch.Tensor, torch.Tensor]: assert x.is_contiguous(), 'Input tensor must be contiguous' assert x.size(-1) % block_size == 0, f'Last dimension size must be divisible by block_size (block_size={block_size})' y = torch.empty_like(x, dtype=torch.float8_e4m3fn) s = x.new_empty(*x.size()[:-1], x.size(-1) // block_size, dtype=torch.float32) grid = lambda meta: (triton.cdiv(x.numel(), meta['BLOCK_SIZE']), ) act_quant_kernel[grid](x, y, s, BLOCK_SIZE=block_size, scale_fmt=scale_fmt) return y, s @triton.jit def weight_dequant_kernel(x_ptr, s_ptr, y_ptr, M, N, BLOCK_SIZE: tl.constexpr): pid_m = tl.program_id(axis=0) pid_n = tl.program_id(axis=1) n = tl.cdiv(N, BLOCK_SIZE) offs_m = pid_m * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) offs_n = pid_n * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) offs = offs_m[:, None] * N + offs_n[None, :] mask = (offs_m[:, None] < M) & (offs_n[None, :] < N) x = tl.load(x_ptr + offs, mask=mask).to(tl.float32) s = tl.load(s_ptr + pid_m * n + pid_n) y = x * s tl.store(y_ptr + offs, y, mask=mask) def weight_dequant(x: torch.Tensor, s: torch.Tensor, block_size: int = 128) -> torch.Tensor: assert x.is_contiguous() and s.is_contiguous(), 'Input tensors must be contiguous' assert x.dim() == 2 and s.dim() == 2, 'Input tensors must have 2 dimensions' M, N = x.size() y = torch.empty_like(x, dtype=torch.get_default_dtype()) grid = lambda meta: (triton.cdiv(M, meta['BLOCK_SIZE']), triton.cdiv(N, meta['BLOCK_SIZE'])) weight_dequant_kernel[grid](x, s, y, M, N, BLOCK_SIZE=block_size) return y fp8_gemm_configs = [ Config({'BLOCK_SIZE_M': block_m, 'BLOCK_SIZE_N': block_n, 'BLOCK_SIZE_K': 128}, num_stages=num_stages, num_warps=8) for block_m in [16, 32, 64] for block_n in [32, 64, 128] for num_stages in [3, 4, 5, 6] ] @triton.autotune(configs=fp8_gemm_configs, key=['N', 'K']) @triton.jit def fp8_gemm_kernel(a_ptr, b_ptr, c_ptr, a_s_ptr, b_s_ptr, M, N: tl.constexpr, K: tl.constexpr, BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr): pid_m = tl.program_id(axis=0) pid_n = tl.program_id(axis=1) k = tl.cdiv(K, BLOCK_SIZE_K) offs_m = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M offs_n = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N offs_k = tl.arange(0, BLOCK_SIZE_K) a_ptrs = a_ptr + offs_m[:, None] * K + offs_k[None, :] b_ptrs = b_ptr + offs_n[None, :] * K + offs_k[:, None] a_s_ptrs = a_s_ptr + offs_m * k b_s_ptrs = b_s_ptr + (offs_n // BLOCK_SIZE_K) * k accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32) for i in range(k): a = tl.load(a_ptrs, mask=offs_k[None, :] < K - i * BLOCK_SIZE_K, other=0.0) b = tl.load(b_ptrs, mask=offs_k[:, None] < K - i * BLOCK_SIZE_K, other=0.0) a_s = tl.load(a_s_ptrs) b_s = tl.load(b_s_ptrs) accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :] a_ptrs += BLOCK_SIZE_K b_ptrs += BLOCK_SIZE_K a_s_ptrs += 1 b_s_ptrs += 1 c = accumulator.to(c_ptr.dtype.element_ty) offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M) offs_n = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N) c_ptrs = c_ptr + offs_m[:, None] * N + offs_n[None, :] mask = (offs_m[:, None] < M) & (offs_n[None, :] < N) tl.store(c_ptrs, c, mask=mask) def fp8_gemm(a: torch.Tensor, a_s: torch.Tensor, b: torch.Tensor, b_s: torch.Tensor): assert a.is_contiguous() and b.is_contiguous(), 'Input tensors must be contiguous' assert a_s.is_contiguous() and b_s.is_contiguous(), 'Scaling factor tensors must be contiguous' K = a.size(-1) M = a.numel() // K N = b.size(0) c = a.new_empty(*a.size()[:-1], N, dtype=torch.get_default_dtype()) grid = lambda META: (triton.cdiv(M, META['BLOCK_SIZE_M']), triton.cdiv(N, META['BLOCK_SIZE_N'])) fp8_gemm_kernel[grid](a, b, c, a_s, b_s, M, N, K) return c
--- +++ @@ -8,6 +8,18 @@ @triton.jit def act_quant_kernel(x_ptr, y_ptr, s_ptr, BLOCK_SIZE: tl.constexpr, scale_fmt: tl.constexpr): + """ + Quantizes the input tensor `x_ptr` and stores the result in `y_ptr` and the scaling factor in `s_ptr`. + + Args: + x_ptr (triton.Pointer): Pointer to the input tensor. + y_ptr (triton.Pointer): Pointer to the output tensor where quantized values will be stored. + s_ptr (triton.Pointer): Pointer to the output tensor where scaling factors will be stored. + BLOCK_SIZE (tl.constexpr): The size of the block to be processed by each program instance. + + Returns: + None + """ pid = tl.program_id(axis=0) offs = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) x = tl.load(x_ptr + offs).to(tl.float32) @@ -24,6 +36,18 @@ def act_quant(x: torch.Tensor, block_size: int = 128, scale_fmt: Optional[str] = None) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Quantizes the input tensor `x` using block-wise quantization. + + Args: + x (torch.Tensor): The input tensor to be quantized. Must be contiguous and its last dimension size must be divisible by `block_size`. + block_size (int, optional): The size of the blocks to be used for quantization. Default is 128. + scale_fmt (Optional[str], optional): The format of the scale. Default is None. + Returns: + Tuple[torch.Tensor, torch.Tensor]: A tuple containing: + - The quantized tensor with dtype `torch.float8_e4m3fn`. + - A tensor of scaling factors with dtype `torch.float32`. + """ assert x.is_contiguous(), 'Input tensor must be contiguous' assert x.size(-1) % block_size == 0, f'Last dimension size must be divisible by block_size (block_size={block_size})' y = torch.empty_like(x, dtype=torch.float8_e4m3fn) @@ -35,6 +59,20 @@ @triton.jit def weight_dequant_kernel(x_ptr, s_ptr, y_ptr, M, N, BLOCK_SIZE: tl.constexpr): + """ + Dequantizes weights using the provided scaling factors and stores the result. + + Args: + x_ptr (tl.pointer): Pointer to the quantized weights. + s_ptr (tl.pointer): Pointer to the scaling factors. + y_ptr (tl.pointer): Pointer to the output buffer for dequantized weights. + M (int): Number of rows in the weight matrix. + N (int): Number of columns in the weight matrix. + BLOCK_SIZE (tl.constexpr): Size of the block for tiling. + + Returns: + None + """ pid_m = tl.program_id(axis=0) pid_n = tl.program_id(axis=1) n = tl.cdiv(N, BLOCK_SIZE) @@ -49,6 +87,20 @@ def weight_dequant(x: torch.Tensor, s: torch.Tensor, block_size: int = 128) -> torch.Tensor: + """ + Dequantizes the given weight tensor using the provided scale tensor. + + Args: + x (torch.Tensor): The quantized weight tensor of shape (M, N). + s (torch.Tensor): The scale tensor of shape (M//block_size, N//block_size). + block_size (int, optional): The block size to use for dequantization. Defaults to 128. + + Returns: + torch.Tensor: The dequantized weight tensor of the same shape as `x`. + + Raises: + AssertionError: If `x` or `s` are not contiguous or if their dimensions are not 2. + """ assert x.is_contiguous() and s.is_contiguous(), 'Input tensors must be contiguous' assert x.dim() == 2 and s.dim() == 2, 'Input tensors must have 2 dimensions' M, N = x.size() @@ -71,6 +123,25 @@ BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr): + """ + Performs a matrix multiplication operation on FP8 matrices with scaling factors. + + Args: + a_ptr (tl.tensor): Pointer to the first input matrix A. + b_ptr (tl.tensor): Pointer to the second input matrix B. + c_ptr (tl.tensor): Pointer to the output matrix C. + a_s_ptr (tl.tensor): Pointer to the scaling factors for matrix A. + b_s_ptr (tl.tensor): Pointer to the scaling factors for matrix B. + M (int): Number of rows in matrix A and C. + N (tl.constexpr): Number of columns in matrix B and C. + K (tl.constexpr): Number of columns in matrix A and rows in matrix B. + BLOCK_SIZE_M (tl.constexpr): Block size for the M dimension. + BLOCK_SIZE_N (tl.constexpr): Block size for the N dimension. + BLOCK_SIZE_K (tl.constexpr): Block size for the K dimension. + + Returns: + None + """ pid_m = tl.program_id(axis=0) pid_n = tl.program_id(axis=1) k = tl.cdiv(K, BLOCK_SIZE_K) @@ -102,6 +173,18 @@ def fp8_gemm(a: torch.Tensor, a_s: torch.Tensor, b: torch.Tensor, b_s: torch.Tensor): + """ + Perform a matrix multiplication using FP8 precision. + + Args: + a (torch.Tensor): The first input matrix, must be contiguous. + a_s (torch.Tensor): The scaling factor for the first input matrix, must be contiguous. + b (torch.Tensor): The second input matrix, must be contiguous. + b_s (torch.Tensor): The scaling factor for the second input matrix, must be contiguous. + + Returns: + torch.Tensor: The result of the matrix multiplication. + """ assert a.is_contiguous() and b.is_contiguous(), 'Input tensors must be contiguous' assert a_s.is_contiguous() and b_s.is_contiguous(), 'Scaling factor tensors must be contiguous' K = a.size(-1) @@ -110,4 +193,4 @@ c = a.new_empty(*a.size()[:-1], N, dtype=torch.get_default_dtype()) grid = lambda META: (triton.cdiv(M, META['BLOCK_SIZE_M']), triton.cdiv(N, META['BLOCK_SIZE_N'])) fp8_gemm_kernel[grid](a, b, c, a_s, b_s, M, N, K) - return c+ return c
https://raw.githubusercontent.com/deepseek-ai/DeepSeek-V3/HEAD/inference/kernel.py
Add docstrings following best practices
import os import torch import torch.nn as nn from modules import devices, paths_internal, shared sd_vae_taesd_models = {} def conv(n_in, n_out, **kwargs): return nn.Conv2d(n_in, n_out, 3, padding=1, **kwargs) class Clamp(nn.Module): @staticmethod def forward(x): return torch.tanh(x / 3) * 3 class Block(nn.Module): def __init__(self, n_in, n_out): super().__init__() self.conv = nn.Sequential(conv(n_in, n_out), nn.ReLU(), conv(n_out, n_out), nn.ReLU(), conv(n_out, n_out)) self.skip = nn.Conv2d(n_in, n_out, 1, bias=False) if n_in != n_out else nn.Identity() self.fuse = nn.ReLU() def forward(self, x): return self.fuse(self.conv(x) + self.skip(x)) def decoder(latent_channels=4): return nn.Sequential( Clamp(), conv(latent_channels, 64), nn.ReLU(), Block(64, 64), Block(64, 64), Block(64, 64), nn.Upsample(scale_factor=2), conv(64, 64, bias=False), Block(64, 64), Block(64, 64), Block(64, 64), nn.Upsample(scale_factor=2), conv(64, 64, bias=False), Block(64, 64), Block(64, 64), Block(64, 64), nn.Upsample(scale_factor=2), conv(64, 64, bias=False), Block(64, 64), conv(64, 3), ) def encoder(latent_channels=4): return nn.Sequential( conv(3, 64), Block(64, 64), conv(64, 64, stride=2, bias=False), Block(64, 64), Block(64, 64), Block(64, 64), conv(64, 64, stride=2, bias=False), Block(64, 64), Block(64, 64), Block(64, 64), conv(64, 64, stride=2, bias=False), Block(64, 64), Block(64, 64), Block(64, 64), conv(64, latent_channels), ) class TAESDDecoder(nn.Module): latent_magnitude = 3 latent_shift = 0.5 def __init__(self, decoder_path="taesd_decoder.pth", latent_channels=None): super().__init__() if latent_channels is None: latent_channels = 16 if "taesd3" in str(decoder_path) else 4 self.decoder = decoder(latent_channels) self.decoder.load_state_dict( torch.load(decoder_path, map_location='cpu' if devices.device.type != 'cuda' else None)) class TAESDEncoder(nn.Module): latent_magnitude = 3 latent_shift = 0.5 def __init__(self, encoder_path="taesd_encoder.pth", latent_channels=None): super().__init__() if latent_channels is None: latent_channels = 16 if "taesd3" in str(encoder_path) else 4 self.encoder = encoder(latent_channels) self.encoder.load_state_dict( torch.load(encoder_path, map_location='cpu' if devices.device.type != 'cuda' else None)) def download_model(model_path, model_url): if not os.path.exists(model_path): os.makedirs(os.path.dirname(model_path), exist_ok=True) print(f'Downloading TAESD model to: {model_path}') torch.hub.download_url_to_file(model_url, model_path) def decoder_model(): if shared.sd_model.is_sd3: model_name = "taesd3_decoder.pth" elif shared.sd_model.is_sdxl: model_name = "taesdxl_decoder.pth" else: model_name = "taesd_decoder.pth" loaded_model = sd_vae_taesd_models.get(model_name) if loaded_model is None: model_path = os.path.join(paths_internal.models_path, "VAE-taesd", model_name) download_model(model_path, 'https://github.com/madebyollin/taesd/raw/main/' + model_name) if os.path.exists(model_path): loaded_model = TAESDDecoder(model_path) loaded_model.eval() loaded_model.to(devices.device, devices.dtype) sd_vae_taesd_models[model_name] = loaded_model else: raise FileNotFoundError('TAESD model not found') return loaded_model.decoder def encoder_model(): if shared.sd_model.is_sd3: model_name = "taesd3_encoder.pth" elif shared.sd_model.is_sdxl: model_name = "taesdxl_encoder.pth" else: model_name = "taesd_encoder.pth" loaded_model = sd_vae_taesd_models.get(model_name) if loaded_model is None: model_path = os.path.join(paths_internal.models_path, "VAE-taesd", model_name) download_model(model_path, 'https://github.com/madebyollin/taesd/raw/main/' + model_name) if os.path.exists(model_path): loaded_model = TAESDEncoder(model_path) loaded_model.eval() loaded_model.to(devices.device, devices.dtype) sd_vae_taesd_models[model_name] = loaded_model else: raise FileNotFoundError('TAESD model not found') return loaded_model.encoder
--- +++ @@ -1,3 +1,9 @@+""" +Tiny AutoEncoder for Stable Diffusion +(DNN for encoding / decoding SD's latent space) + +https://github.com/madebyollin/taesd +""" import os import torch import torch.nn as nn @@ -53,6 +59,7 @@ latent_shift = 0.5 def __init__(self, decoder_path="taesd_decoder.pth", latent_channels=None): + """Initialize pretrained TAESD on the given device from the given checkpoints.""" super().__init__() if latent_channels is None: @@ -68,6 +75,7 @@ latent_shift = 0.5 def __init__(self, encoder_path="taesd_encoder.pth", latent_channels=None): + """Initialize pretrained TAESD on the given device from the given checkpoints.""" super().__init__() if latent_channels is None: @@ -133,4 +141,4 @@ else: raise FileNotFoundError('TAESD model not found') - return loaded_model.encoder+ return loaded_model.encoder
https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_vae_taesd.py
Add docstrings including usage examples
#!/usr/bin/env python3 import argparse import html import json import sys from pathlib import Path def generate_html(data: dict, auto_refresh: bool = False, skill_name: str = "") -> str: history = data.get("history", []) holdout = data.get("holdout", 0) title_prefix = html.escape(skill_name + " \u2014 ") if skill_name else "" # Get all unique queries from train and test sets, with should_trigger info train_queries: list[dict] = [] test_queries: list[dict] = [] if history: for r in history[0].get("train_results", history[0].get("results", [])): train_queries.append({"query": r["query"], "should_trigger": r.get("should_trigger", True)}) if history[0].get("test_results"): for r in history[0].get("test_results", []): test_queries.append({"query": r["query"], "should_trigger": r.get("should_trigger", True)}) refresh_tag = ' <meta http-equiv="refresh" content="5">\n' if auto_refresh else "" html_parts = ["""<!DOCTYPE html> <html> <head> <meta charset="utf-8"> """ + refresh_tag + """ <title>""" + title_prefix + """Skill Description Optimization</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500;600&family=Lora:wght@400;500&display=swap" rel="stylesheet"> <style> body { font-family: 'Lora', Georgia, serif; max-width: 100%; margin: 0 auto; padding: 20px; background: #faf9f5; color: #141413; } h1 { font-family: 'Poppins', sans-serif; color: #141413; } .explainer { background: white; padding: 15px; border-radius: 6px; margin-bottom: 20px; border: 1px solid #e8e6dc; color: #b0aea5; font-size: 0.875rem; line-height: 1.6; } .summary { background: white; padding: 15px; border-radius: 6px; margin-bottom: 20px; border: 1px solid #e8e6dc; } .summary p { margin: 5px 0; } .best { color: #788c5d; font-weight: bold; } .table-container { overflow-x: auto; width: 100%; } table { border-collapse: collapse; background: white; border: 1px solid #e8e6dc; border-radius: 6px; font-size: 12px; min-width: 100%; } th, td { padding: 8px; text-align: left; border: 1px solid #e8e6dc; white-space: normal; word-wrap: break-word; } th { font-family: 'Poppins', sans-serif; background: #141413; color: #faf9f5; font-weight: 500; } th.test-col { background: #6a9bcc; } th.query-col { min-width: 200px; } td.description { font-family: monospace; font-size: 11px; word-wrap: break-word; max-width: 400px; } td.result { text-align: center; font-size: 16px; min-width: 40px; } td.test-result { background: #f0f6fc; } .pass { color: #788c5d; } .fail { color: #c44; } .rate { font-size: 9px; color: #b0aea5; display: block; } tr:hover { background: #faf9f5; } .score { display: inline-block; padding: 2px 6px; border-radius: 4px; font-weight: bold; font-size: 11px; } .score-good { background: #eef2e8; color: #788c5d; } .score-ok { background: #fef3c7; color: #d97706; } .score-bad { background: #fceaea; color: #c44; } .train-label { color: #b0aea5; font-size: 10px; } .test-label { color: #6a9bcc; font-size: 10px; font-weight: bold; } .best-row { background: #f5f8f2; } th.positive-col { border-bottom: 3px solid #788c5d; } th.negative-col { border-bottom: 3px solid #c44; } th.test-col.positive-col { border-bottom: 3px solid #788c5d; } th.test-col.negative-col { border-bottom: 3px solid #c44; } .legend { font-family: 'Poppins', sans-serif; display: flex; gap: 20px; margin-bottom: 10px; font-size: 13px; align-items: center; } .legend-item { display: flex; align-items: center; gap: 6px; } .legend-swatch { width: 16px; height: 16px; border-radius: 3px; display: inline-block; } .swatch-positive { background: #141413; border-bottom: 3px solid #788c5d; } .swatch-negative { background: #141413; border-bottom: 3px solid #c44; } .swatch-test { background: #6a9bcc; } .swatch-train { background: #141413; } </style> </head> <body> <h1>""" + title_prefix + """Skill Description Optimization</h1> <div class="explainer"> <strong>Optimizing your skill's description.</strong> This page updates automatically as Claude tests different versions of your skill's description. Each row is an iteration — a new description attempt. The columns show test queries: green checkmarks mean the skill triggered correctly (or correctly didn't trigger), red crosses mean it got it wrong. The "Train" score shows performance on queries used to improve the description; the "Test" score shows performance on held-out queries the optimizer hasn't seen. When it's done, Claude will apply the best-performing description to your skill. </div> """] # Summary section best_test_score = data.get('best_test_score') best_train_score = data.get('best_train_score') html_parts.append(f""" <div class="summary"> <p><strong>Original:</strong> {html.escape(data.get('original_description', 'N/A'))}</p> <p class="best"><strong>Best:</strong> {html.escape(data.get('best_description', 'N/A'))}</p> <p><strong>Best Score:</strong> {data.get('best_score', 'N/A')} {'(test)' if best_test_score else '(train)'}</p> <p><strong>Iterations:</strong> {data.get('iterations_run', 0)} | <strong>Train:</strong> {data.get('train_size', '?')} | <strong>Test:</strong> {data.get('test_size', '?')}</p> </div> """) # Legend html_parts.append(""" <div class="legend"> <span style="font-weight:600">Query columns:</span> <span class="legend-item"><span class="legend-swatch swatch-positive"></span> Should trigger</span> <span class="legend-item"><span class="legend-swatch swatch-negative"></span> Should NOT trigger</span> <span class="legend-item"><span class="legend-swatch swatch-train"></span> Train</span> <span class="legend-item"><span class="legend-swatch swatch-test"></span> Test</span> </div> """) # Table header html_parts.append(""" <div class="table-container"> <table> <thead> <tr> <th>Iter</th> <th>Train</th> <th>Test</th> <th class="query-col">Description</th> """) # Add column headers for train queries for qinfo in train_queries: polarity = "positive-col" if qinfo["should_trigger"] else "negative-col" html_parts.append(f' <th class="{polarity}">{html.escape(qinfo["query"])}</th>\n') # Add column headers for test queries (different color) for qinfo in test_queries: polarity = "positive-col" if qinfo["should_trigger"] else "negative-col" html_parts.append(f' <th class="test-col {polarity}">{html.escape(qinfo["query"])}</th>\n') html_parts.append(""" </tr> </thead> <tbody> """) # Find best iteration for highlighting if test_queries: best_iter = max(history, key=lambda h: h.get("test_passed") or 0).get("iteration") else: best_iter = max(history, key=lambda h: h.get("train_passed", h.get("passed", 0))).get("iteration") # Add rows for each iteration for h in history: iteration = h.get("iteration", "?") train_passed = h.get("train_passed", h.get("passed", 0)) train_total = h.get("train_total", h.get("total", 0)) test_passed = h.get("test_passed") test_total = h.get("test_total") description = h.get("description", "") train_results = h.get("train_results", h.get("results", [])) test_results = h.get("test_results", []) # Create lookups for results by query train_by_query = {r["query"]: r for r in train_results} test_by_query = {r["query"]: r for r in test_results} if test_results else {} # Compute aggregate correct/total runs across all retries def aggregate_runs(results: list[dict]) -> tuple[int, int]: correct = 0 total = 0 for r in results: runs = r.get("runs", 0) triggers = r.get("triggers", 0) total += runs if r.get("should_trigger", True): correct += triggers else: correct += runs - triggers return correct, total train_correct, train_runs = aggregate_runs(train_results) test_correct, test_runs = aggregate_runs(test_results) # Determine score classes def score_class(correct: int, total: int) -> str: if total > 0: ratio = correct / total if ratio >= 0.8: return "score-good" elif ratio >= 0.5: return "score-ok" return "score-bad" train_class = score_class(train_correct, train_runs) test_class = score_class(test_correct, test_runs) row_class = "best-row" if iteration == best_iter else "" html_parts.append(f""" <tr class="{row_class}"> <td>{iteration}</td> <td><span class="score {train_class}">{train_correct}/{train_runs}</span></td> <td><span class="score {test_class}">{test_correct}/{test_runs}</span></td> <td class="description">{html.escape(description)}</td> """) # Add result for each train query for qinfo in train_queries: r = train_by_query.get(qinfo["query"], {}) did_pass = r.get("pass", False) triggers = r.get("triggers", 0) runs = r.get("runs", 0) icon = "✓" if did_pass else "✗" css_class = "pass" if did_pass else "fail" html_parts.append(f' <td class="result {css_class}">{icon}<span class="rate">{triggers}/{runs}</span></td>\n') # Add result for each test query (with different background) for qinfo in test_queries: r = test_by_query.get(qinfo["query"], {}) did_pass = r.get("pass", False) triggers = r.get("triggers", 0) runs = r.get("runs", 0) icon = "✓" if did_pass else "✗" css_class = "pass" if did_pass else "fail" html_parts.append(f' <td class="result test-result {css_class}">{icon}<span class="rate">{triggers}/{runs}</span></td>\n') html_parts.append(" </tr>\n") html_parts.append(""" </tbody> </table> </div> """) html_parts.append(""" </body> </html> """) return "".join(html_parts) def main(): parser = argparse.ArgumentParser(description="Generate HTML report from run_loop output") parser.add_argument("input", help="Path to JSON output from run_loop.py (or - for stdin)") parser.add_argument("-o", "--output", default=None, help="Output HTML file (default: stdout)") parser.add_argument("--skill-name", default="", help="Skill name to include in the report title") args = parser.parse_args() if args.input == "-": data = json.load(sys.stdin) else: data = json.loads(Path(args.input).read_text()) html_output = generate_html(data, skill_name=args.skill_name) if args.output: Path(args.output).write_text(html_output) print(f"Report written to {args.output}", file=sys.stderr) else: print(html_output) if __name__ == "__main__": main()
--- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3 +"""Generate an HTML report from run_loop.py output. + +Takes the JSON output from run_loop.py and generates a visual HTML report +showing each description attempt with check/x for each test case. +Distinguishes between train and test queries. +""" import argparse import html @@ -8,6 +14,7 @@ def generate_html(data: dict, auto_refresh: bool = False, skill_name: str = "") -> str: + """Generate HTML report from loop output data. If auto_refresh is True, adds a meta refresh tag.""" history = data.get("history", []) holdout = data.get("holdout", 0) title_prefix = html.escape(skill_name + " \u2014 ") if skill_name else "" @@ -316,4 +323,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/scripts/generate_report.py
Add docstrings including usage examples
#!/usr/bin/env python # -*- coding:utf-8 -*- # # Author : XueWeiHan # E-mail : 595666367@qq.com # Date : 16/8/30 下午10:43 # Desc : Github Bot import os import logging import smtplib import datetime from operator import itemgetter from email.mime.text import MIMEText from email.header import Header import requests logging.basicConfig( level=logging.WARNING, filename=os.path.join(os.path.dirname(__file__), 'bot_log.txt'), filemode='a', format='%(name)s %(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s' ) logger = logging.getLogger('Bot') # 设置log名称 # github帐号 ACCOUNT = { 'username': '', 'password': '' } API = { 'events': 'https://api.github.com/users/{username}/received_events'.format(username=ACCOUNT['username']) } # 发送邮件,邮箱的信息 MAIL = { 'mail': '', # 发送邮件的邮箱地址 'username': '', 'password': '', 'host': 'smtp.qq.com', 'port': 465 } # 接收邮件的邮箱地址 RECEIVERS = [] # 几天前 DAY = 1 # 项目stars临界值 STARS = 100 # qq邮件服务文档:http://service.mail.qq.com/cgi-bin/help?id=28 CONTENT_FORMAT = """ <table border="2" align="center"> <tr> <th>头像</th> <th>用户名</th> <th>项目名</th> <th>starred 日期</th> <th>项目 star 数量</th> </tr> {project_info_string} </table> """ def get_data(page=1): args = '?page={page}'.format(page=page) response = requests.get(API['events']+args, auth=(ACCOUNT['username'], ACCOUNT['password'])) status_code = response.status_code if status_code == 200: resp_json = response.json() return resp_json else: logging.error('请求 event api 失败:', status_code) return [] def get_all_data(): all_data_list = [] for i in range(10): response_json = get_data(i+1) if response_json: all_data_list.extend(response_json) return all_data_list def check_condition(data): create_time = datetime.datetime.strptime( data['created_at'], "%Y-%m-%dT%H:%M:%SZ") + datetime.timedelta(hours=8) date_condition = create_time >= (datetime.datetime.now() - datetime.timedelta(days=DAY)) if (data['type'] == 'WatchEvent') and date_condition: # 不统计自己项目的star事件 if data['payload']['action'] == 'started' and \ ACCOUNT['username'] not in data['repo']['name']: data['date_time'] = create_time.strftime("%Y-%m-%d %H:%M:%S") return True else: return False def analyze(json_data): result_data = [] for fi_data in json_data: if check_condition(fi_data): result_data.append(fi_data) return result_data def get_stars(data): project_info_list = [] for fi_data in data: project_info = dict() project_info['user'] = fi_data['actor']['login'] project_info['user_url'] = 'https://github.com/' + project_info['user'] project_info['avatar_url'] = fi_data['actor']['avatar_url'] project_info['repo_name'] = fi_data['repo']['name'] project_info['repo_url'] = 'https://github.com/' + project_info['repo_name'] project_info['date_time'] = fi_data['date_time'] try: repo_stars = requests.get(fi_data['repo']['url'], timeout=2).json() if repo_stars: project_info['repo_stars'] = int(repo_stars['stargazers_count']) else: project_info['repo_stars'] = -1 except Exception as e: project_info['repo_stars'] = -1 logger.warning(u'获取:{} 项目星数失败——{}'.format( project_info['repo_name'], e)) finally: if project_info['repo_stars'] >= STARS or project_info['repo_stars'] == -1: # 过滤掉star数量低于临界值的项目 project_info_list.append(project_info) project_info_list = sorted(project_info_list, key=itemgetter('repo_stars'), reverse=True) return project_info_list def make_content(): json_data = get_all_data() data = analyze(json_data) content = [] project_info_list = get_stars(data) for project_info in project_info_list: project_info_string = """<tr> <td><img src={avatar_url} width=32px></img></td> <td><a href={user_url}>{user}</a></td> <td><a href={repo_url}>{repo_name}</a></td> <td>{date_time}</td> <td>{repo_stars}</td> </tr> """.format(**project_info) content.append(project_info_string) return content def send_email(receivers, email_content): sender = MAIL['mail'] # 发送邮件的邮箱 receivers = receivers # 接收邮件的邮箱,可设置多个 # 三个参数:第一个为文本内容,第二个 html 设置文本格式,第三个 utf-8 设置编码 message = MIMEText( CONTENT_FORMAT.format(project_info_string=''.join(email_content)), 'html', 'utf-8' ) message['From'] = Header(u'GitHub 机器人', 'utf-8') message['To'] = Header(u'削微寒', 'utf-8') subject = u'今日 GitHub 热点' # 设置邮件主题 message['Subject'] = Header(subject, 'utf-8') try: smtp_obj = smtplib.SMTP_SSL() # qq邮箱要求是https连接,所以需要用SMTP_SSL smtp_obj.connect(MAIL['host'], MAIL['port']) # 设置SMTP地址和端口号 smtp_obj.login(MAIL['username'], MAIL['password']) smtp_obj.sendmail(sender, receivers, message.as_string()) except smtplib.SMTPException as e: logger.error(u"无法发送邮件: {}".format(e)) if __name__ == '__main__': content = make_content() send_email(RECEIVERS, content)
--- +++ @@ -68,6 +68,11 @@ def get_data(page=1): + """ + 从目标源获取数据 + https://developer.github.com/v3/activity/events/ + GitHub 规定:默认每页 30 条,最多 300 条目 + """ args = '?page={page}'.format(page=page) @@ -83,6 +88,11 @@ def get_all_data(): + """ + 获取全部 300 条的数据 + https://developer.github.com/v3/activity/events/ + GitHub 规定:默认每页 30 条,最多 300 条目 + """ all_data_list = [] for i in range(10): response_json = get_data(i+1) @@ -92,6 +102,9 @@ def check_condition(data): + """ + 过滤条件 + """ create_time = datetime.datetime.strptime( data['created_at'], "%Y-%m-%dT%H:%M:%SZ") + datetime.timedelta(hours=8) date_condition = create_time >= (datetime.datetime.now() @@ -107,6 +120,10 @@ def analyze(json_data): + """ + 分析获取的数据 + :return 符合过滤条件的数据 + """ result_data = [] for fi_data in json_data: if check_condition(fi_data): @@ -115,6 +132,9 @@ def get_stars(data): + """ + 获取stars数量,同时过滤掉stars数量少的项目 + """ project_info_list = [] for fi_data in data: project_info = dict() @@ -143,6 +163,9 @@ def make_content(): + """ + 生成发布邮件的内容 + """ json_data = get_all_data() data = analyze(json_data) content = [] @@ -161,6 +184,9 @@ def send_email(receivers, email_content): + """ + 发送邮件 + """ sender = MAIL['mail'] # 发送邮件的邮箱 receivers = receivers # 接收邮件的邮箱,可设置多个 @@ -184,4 +210,4 @@ if __name__ == '__main__': content = make_content() - send_email(RECEIVERS, content)+ send_email(RECEIVERS, content)
https://raw.githubusercontent.com/521xueweihan/HelloGitHub/HEAD/script/github_bot/github_bot.py
Add inline docstrings for readability
#!/usr/bin/env python3 from typing import Optional import numpy as np from PIL import Image, ImageDraw, ImageFont def create_blank_frame( width: int, height: int, color: tuple[int, int, int] = (255, 255, 255) ) -> Image.Image: return Image.new("RGB", (width, height), color) def draw_circle( frame: Image.Image, center: tuple[int, int], radius: int, fill_color: Optional[tuple[int, int, int]] = None, outline_color: Optional[tuple[int, int, int]] = None, outline_width: int = 1, ) -> Image.Image: draw = ImageDraw.Draw(frame) x, y = center bbox = [x - radius, y - radius, x + radius, y + radius] draw.ellipse(bbox, fill=fill_color, outline=outline_color, width=outline_width) return frame def draw_text( frame: Image.Image, text: str, position: tuple[int, int], color: tuple[int, int, int] = (0, 0, 0), centered: bool = False, ) -> Image.Image: draw = ImageDraw.Draw(frame) # Uses Pillow's default font. # If the font should be changed for the emoji, add additional logic here. font = ImageFont.load_default() if centered: bbox = draw.textbbox((0, 0), text, font=font) text_width = bbox[2] - bbox[0] text_height = bbox[3] - bbox[1] x = position[0] - text_width // 2 y = position[1] - text_height // 2 position = (x, y) draw.text(position, text, fill=color, font=font) return frame def create_gradient_background( width: int, height: int, top_color: tuple[int, int, int], bottom_color: tuple[int, int, int], ) -> Image.Image: frame = Image.new("RGB", (width, height)) draw = ImageDraw.Draw(frame) # Calculate color step for each row r1, g1, b1 = top_color r2, g2, b2 = bottom_color for y in range(height): # Interpolate color ratio = y / height r = int(r1 * (1 - ratio) + r2 * ratio) g = int(g1 * (1 - ratio) + g2 * ratio) b = int(b1 * (1 - ratio) + b2 * ratio) # Draw horizontal line draw.line([(0, y), (width, y)], fill=(r, g, b)) return frame def draw_star( frame: Image.Image, center: tuple[int, int], size: int, fill_color: tuple[int, int, int], outline_color: Optional[tuple[int, int, int]] = None, outline_width: int = 1, ) -> Image.Image: import math draw = ImageDraw.Draw(frame) x, y = center # Calculate star points points = [] for i in range(10): angle = (i * 36 - 90) * math.pi / 180 # 36 degrees per point, start at top radius = size if i % 2 == 0 else size * 0.4 # Alternate between outer and inner px = x + radius * math.cos(angle) py = y + radius * math.sin(angle) points.append((px, py)) # Draw star draw.polygon(points, fill=fill_color, outline=outline_color, width=outline_width) return frame
--- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3 +""" +Frame Composer - Utilities for composing visual elements into frames. + +Provides functions for drawing shapes, text, emojis, and compositing elements +together to create animation frames. +""" from typing import Optional @@ -9,6 +15,17 @@ def create_blank_frame( width: int, height: int, color: tuple[int, int, int] = (255, 255, 255) ) -> Image.Image: + """ + Create a blank frame with solid color background. + + Args: + width: Frame width + height: Frame height + color: RGB color tuple (default: white) + + Returns: + PIL Image + """ return Image.new("RGB", (width, height), color) @@ -20,6 +37,20 @@ outline_color: Optional[tuple[int, int, int]] = None, outline_width: int = 1, ) -> Image.Image: + """ + Draw a circle on a frame. + + Args: + frame: PIL Image to draw on + center: (x, y) center position + radius: Circle radius + fill_color: RGB fill color (None for no fill) + outline_color: RGB outline color (None for no outline) + outline_width: Outline width in pixels + + Returns: + Modified frame + """ draw = ImageDraw.Draw(frame) x, y = center bbox = [x - radius, y - radius, x + radius, y + radius] @@ -34,6 +65,19 @@ color: tuple[int, int, int] = (0, 0, 0), centered: bool = False, ) -> Image.Image: + """ + Draw text on a frame. + + Args: + frame: PIL Image to draw on + text: Text to draw + position: (x, y) position (top-left unless centered=True) + color: RGB text color + centered: If True, center text at position + + Returns: + Modified frame + """ draw = ImageDraw.Draw(frame) # Uses Pillow's default font. @@ -58,6 +102,18 @@ top_color: tuple[int, int, int], bottom_color: tuple[int, int, int], ) -> Image.Image: + """ + Create a vertical gradient background. + + Args: + width: Frame width + height: Frame height + top_color: RGB color at top + bottom_color: RGB color at bottom + + Returns: + PIL Image with gradient + """ frame = Image.new("RGB", (width, height)) draw = ImageDraw.Draw(frame) @@ -86,6 +142,20 @@ outline_color: Optional[tuple[int, int, int]] = None, outline_width: int = 1, ) -> Image.Image: + """ + Draw a 5-pointed star. + + Args: + frame: PIL Image to draw on + center: (x, y) center position + size: Star size (outer radius) + fill_color: RGB fill color + outline_color: RGB outline color (None for no outline) + outline_width: Outline width + + Returns: + Modified frame + """ import math draw = ImageDraw.Draw(frame) @@ -103,4 +173,4 @@ # Draw star draw.polygon(points, fill=fill_color, outline=outline_color, width=outline_width) - return frame+ return frame
https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/slack-gif-creator/core/frame_composer.py
Expand my code with proper documentation strings
#!/usr/bin/env python3 from pathlib import Path def validate_gif( gif_path: str | Path, is_emoji: bool = True, verbose: bool = True ) -> tuple[bool, dict]: from PIL import Image gif_path = Path(gif_path) if not gif_path.exists(): return False, {"error": f"File not found: {gif_path}"} # Get file size size_bytes = gif_path.stat().st_size size_kb = size_bytes / 1024 size_mb = size_kb / 1024 # Get dimensions and frame info try: with Image.open(gif_path) as img: width, height = img.size # Count frames frame_count = 0 try: while True: img.seek(frame_count) frame_count += 1 except EOFError: pass # Get duration try: duration_ms = img.info.get("duration", 100) total_duration = (duration_ms * frame_count) / 1000 fps = frame_count / total_duration if total_duration > 0 else 0 except: total_duration = None fps = None except Exception as e: return False, {"error": f"Failed to read GIF: {e}"} # Validate dimensions if is_emoji: optimal = width == height == 128 acceptable = width == height and 64 <= width <= 128 dim_pass = acceptable else: aspect_ratio = ( max(width, height) / min(width, height) if min(width, height) > 0 else float("inf") ) dim_pass = aspect_ratio <= 2.0 and 320 <= min(width, height) <= 640 results = { "file": str(gif_path), "passes": dim_pass, "width": width, "height": height, "size_kb": size_kb, "size_mb": size_mb, "frame_count": frame_count, "duration_seconds": total_duration, "fps": fps, "is_emoji": is_emoji, "optimal": optimal if is_emoji else None, } # Print if verbose if verbose: print(f"\nValidating {gif_path.name}:") print( f" Dimensions: {width}x{height}" + ( f" ({'optimal' if optimal else 'acceptable'})" if is_emoji and acceptable else "" ) ) print( f" Size: {size_kb:.1f} KB" + (f" ({size_mb:.2f} MB)" if size_mb >= 1.0 else "") ) print( f" Frames: {frame_count}" + (f" @ {fps:.1f} fps ({total_duration:.1f}s)" if fps else "") ) if not dim_pass: print( f" Note: {'Emoji should be 128x128' if is_emoji else 'Unusual dimensions for Slack'}" ) if size_mb > 5.0: print(f" Note: Large file size - consider fewer frames/colors") return dim_pass, results def is_slack_ready( gif_path: str | Path, is_emoji: bool = True, verbose: bool = True ) -> bool: passes, _ = validate_gif(gif_path, is_emoji, verbose) return passes
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +""" +Validators - Check if GIFs meet Slack's requirements. + +These validators help ensure your GIFs meet Slack's size and dimension constraints. +""" from pathlib import Path @@ -6,6 +11,17 @@ def validate_gif( gif_path: str | Path, is_emoji: bool = True, verbose: bool = True ) -> tuple[bool, dict]: + """ + Validate GIF for Slack (dimensions, size, frame count). + + Args: + gif_path: Path to GIF file + is_emoji: True for emoji (128x128 recommended), False for message GIF + verbose: Print validation details + + Returns: + Tuple of (passes: bool, results: dict with all details) + """ from PIL import Image gif_path = Path(gif_path) @@ -105,5 +121,16 @@ def is_slack_ready( gif_path: str | Path, is_emoji: bool = True, verbose: bool = True ) -> bool: + """ + Quick check if GIF is ready for Slack. + + Args: + gif_path: Path to GIF file + is_emoji: True for emoji GIF, False for message GIF + verbose: Print feedback + + Returns: + True if dimensions are acceptable + """ passes, _ = validate_gif(gif_path, is_emoji, verbose) - return passes+ return passes
https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/slack-gif-creator/core/validators.py
Add docstrings to improve collaboration
#!/usr/bin/env python3 import math def linear(t: float) -> float: return t def ease_in_quad(t: float) -> float: return t * t def ease_out_quad(t: float) -> float: return t * (2 - t) def ease_in_out_quad(t: float) -> float: if t < 0.5: return 2 * t * t return -1 + (4 - 2 * t) * t def ease_in_cubic(t: float) -> float: return t * t * t def ease_out_cubic(t: float) -> float: return (t - 1) * (t - 1) * (t - 1) + 1 def ease_in_out_cubic(t: float) -> float: if t < 0.5: return 4 * t * t * t return (t - 1) * (2 * t - 2) * (2 * t - 2) + 1 def ease_in_bounce(t: float) -> float: return 1 - ease_out_bounce(1 - t) def ease_out_bounce(t: float) -> float: if t < 1 / 2.75: return 7.5625 * t * t elif t < 2 / 2.75: t -= 1.5 / 2.75 return 7.5625 * t * t + 0.75 elif t < 2.5 / 2.75: t -= 2.25 / 2.75 return 7.5625 * t * t + 0.9375 else: t -= 2.625 / 2.75 return 7.5625 * t * t + 0.984375 def ease_in_out_bounce(t: float) -> float: if t < 0.5: return ease_in_bounce(t * 2) * 0.5 return ease_out_bounce(t * 2 - 1) * 0.5 + 0.5 def ease_in_elastic(t: float) -> float: if t == 0 or t == 1: return t return -math.pow(2, 10 * (t - 1)) * math.sin((t - 1.1) * 5 * math.pi) def ease_out_elastic(t: float) -> float: if t == 0 or t == 1: return t return math.pow(2, -10 * t) * math.sin((t - 0.1) * 5 * math.pi) + 1 def ease_in_out_elastic(t: float) -> float: if t == 0 or t == 1: return t t = t * 2 - 1 if t < 0: return -0.5 * math.pow(2, 10 * t) * math.sin((t - 0.1) * 5 * math.pi) return math.pow(2, -10 * t) * math.sin((t - 0.1) * 5 * math.pi) * 0.5 + 1 # Convenience mapping EASING_FUNCTIONS = { "linear": linear, "ease_in": ease_in_quad, "ease_out": ease_out_quad, "ease_in_out": ease_in_out_quad, "bounce_in": ease_in_bounce, "bounce_out": ease_out_bounce, "bounce": ease_in_out_bounce, "elastic_in": ease_in_elastic, "elastic_out": ease_out_elastic, "elastic": ease_in_out_elastic, } def get_easing(name: str = "linear"): return EASING_FUNCTIONS.get(name, linear) def interpolate(start: float, end: float, t: float, easing: str = "linear") -> float: ease_func = get_easing(easing) eased_t = ease_func(t) return start + (end - start) * eased_t def ease_back_in(t: float) -> float: c1 = 1.70158 c3 = c1 + 1 return c3 * t * t * t - c1 * t * t def ease_back_out(t: float) -> float: c1 = 1.70158 c3 = c1 + 1 return 1 + c3 * pow(t - 1, 3) + c1 * pow(t - 1, 2) def ease_back_in_out(t: float) -> float: c1 = 1.70158 c2 = c1 * 1.525 if t < 0.5: return (pow(2 * t, 2) * ((c2 + 1) * 2 * t - c2)) / 2 return (pow(2 * t - 2, 2) * ((c2 + 1) * (t * 2 - 2) + c2) + 2) / 2 def apply_squash_stretch( base_scale: tuple[float, float], intensity: float, direction: str = "vertical" ) -> tuple[float, float]: width_scale, height_scale = base_scale if direction == "vertical": # Compress vertically, expand horizontally (preserve volume) height_scale *= 1 - intensity * 0.5 width_scale *= 1 + intensity * 0.5 elif direction == "horizontal": # Compress horizontally, expand vertically width_scale *= 1 - intensity * 0.5 height_scale *= 1 + intensity * 0.5 elif direction == "both": # General squash (both dimensions) width_scale *= 1 - intensity * 0.3 height_scale *= 1 - intensity * 0.3 return (width_scale, height_scale) def calculate_arc_motion( start: tuple[float, float], end: tuple[float, float], height: float, t: float ) -> tuple[float, float]: x1, y1 = start x2, y2 = end # Linear interpolation for x x = x1 + (x2 - x1) * t # Parabolic interpolation for y # y = start + progress * (end - start) + arc_offset # Arc offset peaks at t=0.5 arc_offset = 4 * height * t * (1 - t) y = y1 + (y2 - y1) * t - arc_offset return (x, y) # Add new easing functions to the convenience mapping EASING_FUNCTIONS.update( { "back_in": ease_back_in, "back_out": ease_back_out, "back_in_out": ease_back_in_out, "anticipate": ease_back_in, # Alias "overshoot": ease_back_out, # Alias } )
--- +++ @@ -1,45 +1,60 @@ #!/usr/bin/env python3 +""" +Easing Functions - Timing functions for smooth animations. + +Provides various easing functions for natural motion and timing. +All functions take a value t (0.0 to 1.0) and return eased value (0.0 to 1.0). +""" import math def linear(t: float) -> float: + """Linear interpolation (no easing).""" return t def ease_in_quad(t: float) -> float: + """Quadratic ease-in (slow start, accelerating).""" return t * t def ease_out_quad(t: float) -> float: + """Quadratic ease-out (fast start, decelerating).""" return t * (2 - t) def ease_in_out_quad(t: float) -> float: + """Quadratic ease-in-out (slow start and end).""" if t < 0.5: return 2 * t * t return -1 + (4 - 2 * t) * t def ease_in_cubic(t: float) -> float: + """Cubic ease-in (slow start).""" return t * t * t def ease_out_cubic(t: float) -> float: + """Cubic ease-out (fast start).""" return (t - 1) * (t - 1) * (t - 1) + 1 def ease_in_out_cubic(t: float) -> float: + """Cubic ease-in-out.""" if t < 0.5: return 4 * t * t * t return (t - 1) * (2 * t - 2) * (2 * t - 2) + 1 def ease_in_bounce(t: float) -> float: + """Bounce ease-in (bouncy start).""" return 1 - ease_out_bounce(1 - t) def ease_out_bounce(t: float) -> float: + """Bounce ease-out (bouncy end).""" if t < 1 / 2.75: return 7.5625 * t * t elif t < 2 / 2.75: @@ -54,24 +69,28 @@ def ease_in_out_bounce(t: float) -> float: + """Bounce ease-in-out.""" if t < 0.5: return ease_in_bounce(t * 2) * 0.5 return ease_out_bounce(t * 2 - 1) * 0.5 + 0.5 def ease_in_elastic(t: float) -> float: + """Elastic ease-in (spring effect).""" if t == 0 or t == 1: return t return -math.pow(2, 10 * (t - 1)) * math.sin((t - 1.1) * 5 * math.pi) def ease_out_elastic(t: float) -> float: + """Elastic ease-out (spring effect).""" if t == 0 or t == 1: return t return math.pow(2, -10 * t) * math.sin((t - 0.1) * 5 * math.pi) + 1 def ease_in_out_elastic(t: float) -> float: + """Elastic ease-in-out.""" if t == 0 or t == 1: return t t = t * 2 - 1 @@ -96,28 +115,44 @@ def get_easing(name: str = "linear"): + """Get easing function by name.""" return EASING_FUNCTIONS.get(name, linear) def interpolate(start: float, end: float, t: float, easing: str = "linear") -> float: + """ + Interpolate between two values with easing. + + Args: + start: Start value + end: End value + t: Progress from 0.0 to 1.0 + easing: Name of easing function + + Returns: + Interpolated value + """ ease_func = get_easing(easing) eased_t = ease_func(t) return start + (end - start) * eased_t def ease_back_in(t: float) -> float: + """Back ease-in (slight overshoot backward before forward motion).""" c1 = 1.70158 c3 = c1 + 1 return c3 * t * t * t - c1 * t * t def ease_back_out(t: float) -> float: + """Back ease-out (overshoot forward then settle back).""" c1 = 1.70158 c3 = c1 + 1 return 1 + c3 * pow(t - 1, 3) + c1 * pow(t - 1, 2) def ease_back_in_out(t: float) -> float: + """Back ease-in-out (overshoot at both ends).""" c1 = 1.70158 c2 = c1 * 1.525 if t < 0.5: @@ -128,6 +163,17 @@ def apply_squash_stretch( base_scale: tuple[float, float], intensity: float, direction: str = "vertical" ) -> tuple[float, float]: + """ + Calculate squash and stretch scales for more dynamic animation. + + Args: + base_scale: (width_scale, height_scale) base scales + intensity: Squash/stretch intensity (0.0-1.0) + direction: 'vertical', 'horizontal', or 'both' + + Returns: + (width_scale, height_scale) with squash/stretch applied + """ width_scale, height_scale = base_scale if direction == "vertical": @@ -149,6 +195,18 @@ def calculate_arc_motion( start: tuple[float, float], end: tuple[float, float], height: float, t: float ) -> tuple[float, float]: + """ + Calculate position along a parabolic arc (natural motion path). + + Args: + start: (x, y) starting position + end: (x, y) ending position + height: Arc height at midpoint (positive = upward) + t: Progress (0.0-1.0) + + Returns: + (x, y) position along arc + """ x1, y1 = start x2, y2 = end @@ -173,4 +231,4 @@ "anticipate": ease_back_in, # Alias "overshoot": ease_back_out, # Alias } -)+)
https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/slack-gif-creator/core/easing.py
Add docstrings to make code maintainable
#!/usr/bin/env python3 from pathlib import Path from typing import Optional import imageio.v3 as imageio import numpy as np from PIL import Image class GIFBuilder: def __init__(self, width: int = 480, height: int = 480, fps: int = 15): self.width = width self.height = height self.fps = fps self.frames: list[np.ndarray] = [] def add_frame(self, frame: np.ndarray | Image.Image): if isinstance(frame, Image.Image): frame = np.array(frame.convert("RGB")) # Ensure frame is correct size if frame.shape[:2] != (self.height, self.width): pil_frame = Image.fromarray(frame) pil_frame = pil_frame.resize( (self.width, self.height), Image.Resampling.LANCZOS ) frame = np.array(pil_frame) self.frames.append(frame) def add_frames(self, frames: list[np.ndarray | Image.Image]): for frame in frames: self.add_frame(frame) def optimize_colors( self, num_colors: int = 128, use_global_palette: bool = True ) -> list[np.ndarray]: optimized = [] if use_global_palette and len(self.frames) > 1: # Create a global palette from all frames # Sample frames to build palette sample_size = min(5, len(self.frames)) sample_indices = [ int(i * len(self.frames) / sample_size) for i in range(sample_size) ] sample_frames = [self.frames[i] for i in sample_indices] # Combine sample frames into a single image for palette generation # Flatten each frame to get all pixels, then stack them all_pixels = np.vstack( [f.reshape(-1, 3) for f in sample_frames] ) # (total_pixels, 3) # Create a properly-shaped RGB image from the pixel data # We'll make a roughly square image from all the pixels total_pixels = len(all_pixels) width = min(512, int(np.sqrt(total_pixels))) # Reasonable width, max 512 height = (total_pixels + width - 1) // width # Ceiling division # Pad if necessary to fill the rectangle pixels_needed = width * height if pixels_needed > total_pixels: padding = np.zeros((pixels_needed - total_pixels, 3), dtype=np.uint8) all_pixels = np.vstack([all_pixels, padding]) # Reshape to proper RGB image format (H, W, 3) img_array = ( all_pixels[:pixels_needed].reshape(height, width, 3).astype(np.uint8) ) combined_img = Image.fromarray(img_array, mode="RGB") # Generate global palette global_palette = combined_img.quantize(colors=num_colors, method=2) # Apply global palette to all frames for frame in self.frames: pil_frame = Image.fromarray(frame) quantized = pil_frame.quantize(palette=global_palette, dither=1) optimized.append(np.array(quantized.convert("RGB"))) else: # Use per-frame quantization for frame in self.frames: pil_frame = Image.fromarray(frame) quantized = pil_frame.quantize(colors=num_colors, method=2, dither=1) optimized.append(np.array(quantized.convert("RGB"))) return optimized def deduplicate_frames(self, threshold: float = 0.9995) -> int: if len(self.frames) < 2: return 0 deduplicated = [self.frames[0]] removed_count = 0 for i in range(1, len(self.frames)): # Compare with previous frame prev_frame = np.array(deduplicated[-1], dtype=np.float32) curr_frame = np.array(self.frames[i], dtype=np.float32) # Calculate similarity (normalized) diff = np.abs(prev_frame - curr_frame) similarity = 1.0 - (np.mean(diff) / 255.0) # Keep frame if sufficiently different # High threshold (0.9995+) means only remove nearly identical frames if similarity < threshold: deduplicated.append(self.frames[i]) else: removed_count += 1 self.frames = deduplicated return removed_count def save( self, output_path: str | Path, num_colors: int = 128, optimize_for_emoji: bool = False, remove_duplicates: bool = False, ) -> dict: if not self.frames: raise ValueError("No frames to save. Add frames with add_frame() first.") output_path = Path(output_path) # Remove duplicate frames to reduce file size if remove_duplicates: removed = self.deduplicate_frames(threshold=0.9995) if removed > 0: print( f" Removed {removed} nearly identical frames (preserved subtle animations)" ) # Optimize for emoji if requested if optimize_for_emoji: if self.width > 128 or self.height > 128: print( f" Resizing from {self.width}x{self.height} to 128x128 for emoji" ) self.width = 128 self.height = 128 # Resize all frames resized_frames = [] for frame in self.frames: pil_frame = Image.fromarray(frame) pil_frame = pil_frame.resize((128, 128), Image.Resampling.LANCZOS) resized_frames.append(np.array(pil_frame)) self.frames = resized_frames num_colors = min(num_colors, 48) # More aggressive color limit for emoji # More aggressive FPS reduction for emoji if len(self.frames) > 12: print( f" Reducing frames from {len(self.frames)} to ~12 for emoji size" ) # Keep every nth frame to get close to 12 frames keep_every = max(1, len(self.frames) // 12) self.frames = [ self.frames[i] for i in range(0, len(self.frames), keep_every) ] # Optimize colors with global palette optimized_frames = self.optimize_colors(num_colors, use_global_palette=True) # Calculate frame duration in milliseconds frame_duration = 1000 / self.fps # Save GIF imageio.imwrite( output_path, optimized_frames, duration=frame_duration, loop=0, # Infinite loop ) # Get file info file_size_kb = output_path.stat().st_size / 1024 file_size_mb = file_size_kb / 1024 info = { "path": str(output_path), "size_kb": file_size_kb, "size_mb": file_size_mb, "dimensions": f"{self.width}x{self.height}", "frame_count": len(optimized_frames), "fps": self.fps, "duration_seconds": len(optimized_frames) / self.fps, "colors": num_colors, } # Print info print(f"\n✓ GIF created successfully!") print(f" Path: {output_path}") print(f" Size: {file_size_kb:.1f} KB ({file_size_mb:.2f} MB)") print(f" Dimensions: {self.width}x{self.height}") print(f" Frames: {len(optimized_frames)} @ {self.fps} fps") print(f" Duration: {info['duration_seconds']:.1f}s") print(f" Colors: {num_colors}") # Size info if optimize_for_emoji: print(f" Optimized for emoji (128x128, reduced colors)") if file_size_mb > 1.0: print(f"\n Note: Large file size ({file_size_kb:.1f} KB)") print(" Consider: fewer frames, smaller dimensions, or fewer colors") return info def clear(self): self.frames = []
--- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3 +""" +GIF Builder - Core module for assembling frames into GIFs optimized for Slack. + +This module provides the main interface for creating GIFs from programmatically +generated frames, with automatic optimization for Slack's requirements. +""" from pathlib import Path from typing import Optional @@ -9,14 +15,29 @@ class GIFBuilder: + """Builder for creating optimized GIFs from frames.""" def __init__(self, width: int = 480, height: int = 480, fps: int = 15): + """ + Initialize GIF builder. + + Args: + width: Frame width in pixels + height: Frame height in pixels + fps: Frames per second + """ self.width = width self.height = height self.fps = fps self.frames: list[np.ndarray] = [] def add_frame(self, frame: np.ndarray | Image.Image): + """ + Add a frame to the GIF. + + Args: + frame: Frame as numpy array or PIL Image (will be converted to RGB) + """ if isinstance(frame, Image.Image): frame = np.array(frame.convert("RGB")) @@ -31,12 +52,23 @@ self.frames.append(frame) def add_frames(self, frames: list[np.ndarray | Image.Image]): + """Add multiple frames at once.""" for frame in frames: self.add_frame(frame) def optimize_colors( self, num_colors: int = 128, use_global_palette: bool = True ) -> list[np.ndarray]: + """ + Reduce colors in all frames using quantization. + + Args: + num_colors: Target number of colors (8-256) + use_global_palette: Use a single palette for all frames (better compression) + + Returns: + List of color-optimized frames + """ optimized = [] if use_global_palette and len(self.frames) > 1: @@ -90,6 +122,16 @@ return optimized def deduplicate_frames(self, threshold: float = 0.9995) -> int: + """ + Remove duplicate or near-duplicate consecutive frames. + + Args: + threshold: Similarity threshold (0.0-1.0). Higher = more strict (0.9995 = nearly identical). + Use 0.9995+ to preserve subtle animations, 0.98 for aggressive removal. + + Returns: + Number of frames removed + """ if len(self.frames) < 2: return 0 @@ -122,6 +164,18 @@ optimize_for_emoji: bool = False, remove_duplicates: bool = False, ) -> dict: + """ + Save frames as optimized GIF for Slack. + + Args: + output_path: Where to save the GIF + num_colors: Number of colors to use (fewer = smaller file) + optimize_for_emoji: If True, optimize for emoji size (128x128, fewer colors) + remove_duplicates: If True, remove duplicate consecutive frames (opt-in) + + Returns: + Dictionary with file info (path, size, dimensions, frame_count) + """ if not self.frames: raise ValueError("No frames to save. Add frames with add_frame() first.") @@ -211,4 +265,5 @@ return info def clear(self): - self.frames = []+ """Clear all frames (useful for creating multiple GIFs).""" + self.frames = []
https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/slack-gif-creator/core/gif_builder.py
Add docstrings that explain logic
from collections.abc import Callable from typing import Annotated, Any from annotated_doc import Doc from starlette.background import BackgroundTasks as StarletteBackgroundTasks from typing_extensions import ParamSpec P = ParamSpec("P") class BackgroundTasks(StarletteBackgroundTasks): def add_task( self, func: Annotated[ Callable[P, Any], Doc( """ The function to call after the response is sent. It can be a regular `def` function or an `async def` function. """ ), ], *args: P.args, **kwargs: P.kwargs, ) -> None: return super().add_task(func, *args, **kwargs)
--- +++ @@ -9,6 +9,33 @@ class BackgroundTasks(StarletteBackgroundTasks): + """ + A collection of background tasks that will be called after a response has been + sent to the client. + + Read more about it in the + [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). + + ## Example + + ```python + from fastapi import BackgroundTasks, FastAPI + + app = FastAPI() + + + def write_notification(email: str, message=""): + with open("log.txt", mode="w") as email_file: + content = f"notification for {email}: {message}" + email_file.write(content) + + + @app.post("/send-notification/{email}") + async def send_notification(email: str, background_tasks: BackgroundTasks): + background_tasks.add_task(write_notification, email, message="some notification") + return {"message": "Notification sent in the background"} + ``` + """ def add_task( self, @@ -25,4 +52,10 @@ *args: P.args, **kwargs: P.kwargs, ) -> None: - return super().add_task(func, *args, **kwargs)+ """ + Add a function to be called in the background after the response is sent. + + Read more about it in the + [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). + """ + return super().add_task(func, *args, **kwargs)
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/background.py
Add missing documentation to my Python functions
from collections.abc import Mapping, Sequence from typing import Annotated, Any, TypedDict from annotated_doc import Doc from pydantic import BaseModel, create_model from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.exceptions import WebSocketException as StarletteWebSocketException class EndpointContext(TypedDict, total=False): function: str path: str file: str line: int class HTTPException(StarletteHTTPException): def __init__( self, status_code: Annotated[ int, Doc( """ HTTP status code to send to the client. Read more about it in the [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception) """ ), ], detail: Annotated[ Any, Doc( """ Any data to be sent to the client in the `detail` key of the JSON response. Read more about it in the [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-httpexception) """ ), ] = None, headers: Annotated[ Mapping[str, str] | None, Doc( """ Any headers to send to the client in the response. Read more about it in the [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/#add-custom-headers) """ ), ] = None, ) -> None: super().__init__(status_code=status_code, detail=detail, headers=headers) class WebSocketException(StarletteWebSocketException): def __init__( self, code: Annotated[ int, Doc( """ A closing code from the [valid codes defined in the specification](https://datatracker.ietf.org/doc/html/rfc6455#section-7.4.1). """ ), ], reason: Annotated[ str | None, Doc( """ The reason to close the WebSocket connection. It is UTF-8-encoded data. The interpretation of the reason is up to the application, it is not specified by the WebSocket specification. It could contain text that could be human-readable or interpretable by the client code, etc. """ ), ] = None, ) -> None: super().__init__(code=code, reason=reason) RequestErrorModel: type[BaseModel] = create_model("Request") WebSocketErrorModel: type[BaseModel] = create_model("WebSocket") class FastAPIError(RuntimeError): class DependencyScopeError(FastAPIError): class ValidationException(Exception): def __init__( self, errors: Sequence[Any], *, endpoint_ctx: EndpointContext | None = None, ) -> None: self._errors = errors self.endpoint_ctx = endpoint_ctx ctx = endpoint_ctx or {} self.endpoint_function = ctx.get("function") self.endpoint_path = ctx.get("path") self.endpoint_file = ctx.get("file") self.endpoint_line = ctx.get("line") def errors(self) -> Sequence[Any]: return self._errors def _format_endpoint_context(self) -> str: if not (self.endpoint_file and self.endpoint_line and self.endpoint_function): if self.endpoint_path: return f"\n Endpoint: {self.endpoint_path}" return "" context = f'\n File "{self.endpoint_file}", line {self.endpoint_line}, in {self.endpoint_function}' if self.endpoint_path: context += f"\n {self.endpoint_path}" return context def __str__(self) -> str: message = f"{len(self._errors)} validation error{'s' if len(self._errors) != 1 else ''}:\n" for err in self._errors: message += f" {err}\n" message += self._format_endpoint_context() return message.rstrip() class RequestValidationError(ValidationException): def __init__( self, errors: Sequence[Any], *, body: Any = None, endpoint_ctx: EndpointContext | None = None, ) -> None: super().__init__(errors, endpoint_ctx=endpoint_ctx) self.body = body class WebSocketRequestValidationError(ValidationException): def __init__( self, errors: Sequence[Any], *, endpoint_ctx: EndpointContext | None = None, ) -> None: super().__init__(errors, endpoint_ctx=endpoint_ctx) class ResponseValidationError(ValidationException): def __init__( self, errors: Sequence[Any], *, body: Any = None, endpoint_ctx: EndpointContext | None = None, ) -> None: super().__init__(errors, endpoint_ctx=endpoint_ctx) self.body = body class PydanticV1NotSupportedError(FastAPIError): class FastAPIDeprecationWarning(UserWarning):
--- +++ @@ -15,6 +15,32 @@ class HTTPException(StarletteHTTPException): + """ + An HTTP exception you can raise in your own code to show errors to the client. + + This is for client errors, invalid authentication, invalid data, etc. Not for server + errors in your code. + + Read more about it in the + [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). + + ## Example + + ```python + from fastapi import FastAPI, HTTPException + + app = FastAPI() + + items = {"foo": "The Foo Wrestlers"} + + + @app.get("/items/{item_id}") + async def read_item(item_id: str): + if item_id not in items: + raise HTTPException(status_code=404, detail="Item not found") + return {"item": items[item_id]} + ``` + """ def __init__( self, @@ -58,6 +84,46 @@ class WebSocketException(StarletteWebSocketException): + """ + A WebSocket exception you can raise in your own code to show errors to the client. + + This is for client errors, invalid authentication, invalid data, etc. Not for server + errors in your code. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import ( + Cookie, + FastAPI, + WebSocket, + WebSocketException, + status, + ) + + app = FastAPI() + + @app.websocket("/items/{item_id}/ws") + async def websocket_endpoint( + *, + websocket: WebSocket, + session: Annotated[str | None, Cookie()] = None, + item_id: str, + ): + if session is None: + raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION) + await websocket.accept() + while True: + data = await websocket.receive_text() + await websocket.send_text(f"Session cookie is: {session}") + await websocket.send_text(f"Message text was: {data}, for item ID: {item_id}") + ``` + """ def __init__( self, @@ -93,9 +159,16 @@ class FastAPIError(RuntimeError): + """ + A generic, FastAPI-specific error. + """ class DependencyScopeError(FastAPIError): + """ + A dependency declared that it depends on another dependency with an invalid + (narrower) scope. + """ class ValidationException(Exception): @@ -171,6 +244,13 @@ class PydanticV1NotSupportedError(FastAPIError): - - -class FastAPIDeprecationWarning(UserWarning):+ """ + A pydantic.v1 model is used, which is no longer supported. + """ + + +class FastAPIDeprecationWarning(UserWarning): + """ + A custom deprecation warning as DeprecationWarning is ignored + Ref: https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries + """
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/exceptions.py
Auto-generate documentation strings for this file
from collections.abc import Callable, Mapping from typing import ( Annotated, Any, BinaryIO, TypeVar, cast, ) from annotated_doc import Doc from pydantic import GetJsonSchemaHandler from starlette.datastructures import URL as URL # noqa: F401 from starlette.datastructures import Address as Address # noqa: F401 from starlette.datastructures import FormData as FormData # noqa: F401 from starlette.datastructures import Headers as Headers # noqa: F401 from starlette.datastructures import QueryParams as QueryParams # noqa: F401 from starlette.datastructures import State as State # noqa: F401 from starlette.datastructures import UploadFile as StarletteUploadFile class UploadFile(StarletteUploadFile): file: Annotated[ BinaryIO, Doc("The standard Python file object (non-async)."), ] filename: Annotated[str | None, Doc("The original file name.")] size: Annotated[int | None, Doc("The size of the file in bytes.")] headers: Annotated[Headers, Doc("The headers of the request.")] content_type: Annotated[ str | None, Doc("The content type of the request, from the headers.") ] async def write( self, data: Annotated[ bytes, Doc( """ The bytes to write to the file. """ ), ], ) -> None: return await super().write(data) async def read( self, size: Annotated[ int, Doc( """ The number of bytes to read from the file. """ ), ] = -1, ) -> bytes: return await super().read(size) async def seek( self, offset: Annotated[ int, Doc( """ The position in bytes to seek to in the file. """ ), ], ) -> None: return await super().seek(offset) async def close(self) -> None: return await super().close() @classmethod def _validate(cls, __input_value: Any, _: Any) -> "UploadFile": if not isinstance(__input_value, StarletteUploadFile): raise ValueError(f"Expected UploadFile, received: {type(__input_value)}") return cast(UploadFile, __input_value) @classmethod def __get_pydantic_json_schema__( cls, core_schema: Mapping[str, Any], handler: GetJsonSchemaHandler ) -> dict[str, Any]: return {"type": "string", "contentMediaType": "application/octet-stream"} @classmethod def __get_pydantic_core_schema__( cls, source: type[Any], handler: Callable[[Any], Mapping[str, Any]] ) -> Mapping[str, Any]: from ._compat.v2 import with_info_plain_validator_function return with_info_plain_validator_function(cls._validate) class DefaultPlaceholder: def __init__(self, value: Any): self.value = value def __bool__(self) -> bool: return bool(self.value) def __eq__(self, o: object) -> bool: return isinstance(o, DefaultPlaceholder) and o.value == self.value DefaultType = TypeVar("DefaultType") def Default(value: DefaultType) -> DefaultType: return DefaultPlaceholder(value) # type: ignore # Sentinel for "parameter not provided" in Param/FieldInfo. # Typed as None to satisfy ty _Unset = Default(None)
--- +++ @@ -19,6 +19,38 @@ class UploadFile(StarletteUploadFile): + """ + A file uploaded in a request. + + Define it as a *path operation function* (or dependency) parameter. + + If you are using a regular `def` function, you can use the `upload_file.file` + attribute to access the raw standard Python file (blocking, not async), useful and + needed for non-async code. + + Read more about it in the + [FastAPI docs for Request Files](https://fastapi.tiangolo.com/tutorial/request-files/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import FastAPI, File, UploadFile + + app = FastAPI() + + + @app.post("/files/") + async def create_file(file: Annotated[bytes, File()]): + return {"file_size": len(file)} + + + @app.post("/uploadfile/") + async def create_upload_file(file: UploadFile): + return {"filename": file.filename} + ``` + """ file: Annotated[ BinaryIO, @@ -42,6 +74,13 @@ ), ], ) -> None: + """ + Write some bytes to the file. + + You normally wouldn't use this from a file you read in a request. + + To be awaitable, compatible with async, this is run in threadpool. + """ return await super().write(data) async def read( @@ -55,6 +94,11 @@ ), ] = -1, ) -> bytes: + """ + Read some bytes from the file. + + To be awaitable, compatible with async, this is run in threadpool. + """ return await super().read(size) async def seek( @@ -68,9 +112,21 @@ ), ], ) -> None: + """ + Move to a position in the file. + + Any next read or write will be done from that position. + + To be awaitable, compatible with async, this is run in threadpool. + """ return await super().seek(offset) async def close(self) -> None: + """ + Close the file. + + To be awaitable, compatible with async, this is run in threadpool. + """ return await super().close() @classmethod @@ -95,6 +151,12 @@ class DefaultPlaceholder: + """ + You shouldn't use this class directly. + + It's used internally to recognize when a default value has been overwritten, even + if the overridden default value was truthy. + """ def __init__(self, value: Any): self.value = value @@ -110,9 +172,15 @@ def Default(value: DefaultType) -> DefaultType: + """ + You shouldn't use this function directly. + + It's used internally to recognize when a default value has been overwritten, even + if the overridden default value was truthy. + """ return DefaultPlaceholder(value) # type: ignore # Sentinel for "parameter not provided" in Param/FieldInfo. # Typed as None to satisfy ty -_Unset = Default(None)+_Unset = Default(None)
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/datastructures.py
Expand my code with proper documentation strings
from collections.abc import Awaitable, Callable, Coroutine, Sequence from enum import Enum from typing import Annotated, Any, TypeVar from annotated_doc import Doc from fastapi import routing from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.exception_handlers import ( http_exception_handler, request_validation_exception_handler, websocket_request_validation_exception_handler, ) from fastapi.exceptions import RequestValidationError, WebSocketRequestValidationError from fastapi.logger import logger from fastapi.middleware.asyncexitstack import AsyncExitStackMiddleware from fastapi.openapi.docs import ( get_redoc_html, get_swagger_ui_html, get_swagger_ui_oauth2_redirect_html, ) from fastapi.openapi.utils import get_openapi from fastapi.params import Depends from fastapi.types import DecoratedCallable, IncEx from fastapi.utils import generate_unique_id from starlette.applications import Starlette from starlette.datastructures import State from starlette.exceptions import HTTPException from starlette.middleware import Middleware from starlette.middleware.base import BaseHTTPMiddleware from starlette.middleware.errors import ServerErrorMiddleware from starlette.middleware.exceptions import ExceptionMiddleware from starlette.requests import Request from starlette.responses import HTMLResponse, JSONResponse, Response from starlette.routing import BaseRoute from starlette.types import ASGIApp, ExceptionHandler, Lifespan, Receive, Scope, Send from typing_extensions import deprecated AppType = TypeVar("AppType", bound="FastAPI") class FastAPI(Starlette): def __init__( self: AppType, *, debug: Annotated[ bool, Doc( """ Boolean indicating if debug tracebacks should be returned on server errors. Read more in the [Starlette docs for Applications](https://www.starlette.dev/applications/#instantiating-the-application). """ ), ] = False, routes: Annotated[ list[BaseRoute] | None, Doc( """ **Note**: you probably shouldn't use this parameter, it is inherited from Starlette and supported for compatibility. --- A list of routes to serve incoming HTTP and WebSocket requests. """ ), deprecated( """ You normally wouldn't use this parameter with FastAPI, it is inherited from Starlette and supported for compatibility. In FastAPI, you normally would use the *path operation methods*, like `app.get()`, `app.post()`, etc. """ ), ] = None, title: Annotated[ str, Doc( """ The title of the API. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). **Example** ```python from fastapi import FastAPI app = FastAPI(title="ChimichangApp") ``` """ ), ] = "FastAPI", summary: Annotated[ str | None, Doc( """ A short summary of the API. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). **Example** ```python from fastapi import FastAPI app = FastAPI(summary="Deadpond's favorite app. Nuff said.") ``` """ ), ] = None, description: Annotated[ str, Doc( ''' A description of the API. Supports Markdown (using [CommonMark syntax](https://commonmark.org/)). It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). **Example** ```python from fastapi import FastAPI app = FastAPI( description=""" ChimichangApp API helps you do awesome stuff. 🚀 ## Items You can **read items**. ## Users You will be able to: * **Create users** (_not implemented_). * **Read users** (_not implemented_). """ ) ``` ''' ), ] = "", version: Annotated[ str, Doc( """ The version of the API. **Note** This is the version of your application, not the version of the OpenAPI specification nor the version of FastAPI being used. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). **Example** ```python from fastapi import FastAPI app = FastAPI(version="0.0.1") ``` """ ), ] = "0.1.0", openapi_url: Annotated[ str | None, Doc( """ The URL where the OpenAPI schema will be served from. If you set it to `None`, no OpenAPI schema will be served publicly, and the default automatic endpoints `/docs` and `/redoc` will also be disabled. Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url). **Example** ```python from fastapi import FastAPI app = FastAPI(openapi_url="/api/v1/openapi.json") ``` """ ), ] = "/openapi.json", openapi_tags: Annotated[ list[dict[str, Any]] | None, Doc( """ A list of tags used by OpenAPI, these are the same `tags` you can set in the *path operations*, like: * `@app.get("/users/", tags=["users"])` * `@app.get("/items/", tags=["items"])` The order of the tags can be used to specify the order shown in tools like Swagger UI, used in the automatic path `/docs`. It's not required to specify all the tags used. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. The value of each item is a `dict` containing: * `name`: The name of the tag. * `description`: A short description of the tag. [CommonMark syntax](https://commonmark.org/) MAY be used for rich text representation. * `externalDocs`: Additional external documentation for this tag. If provided, it would contain a `dict` with: * `description`: A short description of the target documentation. [CommonMark syntax](https://commonmark.org/) MAY be used for rich text representation. * `url`: The URL for the target documentation. Value MUST be in the form of a URL. Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags). **Example** ```python from fastapi import FastAPI tags_metadata = [ { "name": "users", "description": "Operations with users. The **login** logic is also here.", }, { "name": "items", "description": "Manage items. So _fancy_ they have their own docs.", "externalDocs": { "description": "Items external docs", "url": "https://fastapi.tiangolo.com/", }, }, ] app = FastAPI(openapi_tags=tags_metadata) ``` """ ), ] = None, servers: Annotated[ list[dict[str, str | Any]] | None, Doc( """ A `list` of `dict`s with connectivity information to a target server. You would use it, for example, if your application is served from different domains and you want to use the same Swagger UI in the browser to interact with each of them (instead of having multiple browser tabs open). Or if you want to leave fixed the possible URLs. If the servers `list` is not provided, or is an empty `list`, the `servers` property in the generated OpenAPI will be: * a `dict` with a `url` value of the application's mounting point (`root_path`) if it's different from `/`. * otherwise, the `servers` property will be omitted from the OpenAPI schema. Each item in the `list` is a `dict` containing: * `url`: A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in `{`brackets`}`. * `description`: An optional string describing the host designated by the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for rich text representation. * `variables`: A `dict` between a variable name and its value. The value is used for substitution in the server's URL template. Read more in the [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers). **Example** ```python from fastapi import FastAPI app = FastAPI( servers=[ {"url": "https://stag.example.com", "description": "Staging environment"}, {"url": "https://prod.example.com", "description": "Production environment"}, ] ) ``` """ ), ] = None, dependencies: Annotated[ Sequence[Depends] | None, Doc( """ A list of global dependencies, they will be applied to each *path operation*, including in sub-routers. Read more about it in the [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/). **Example** ```python from fastapi import Depends, FastAPI from .dependencies import func_dep_1, func_dep_2 app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)]) ``` """ ), ] = None, default_response_class: Annotated[ type[Response], Doc( """ The default response class to be used. Read more in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). **Example** ```python from fastapi import FastAPI from fastapi.responses import ORJSONResponse app = FastAPI(default_response_class=ORJSONResponse) ``` """ ), ] = Default(JSONResponse), redirect_slashes: Annotated[ bool, Doc( """ Whether to detect and redirect slashes in URLs when the client doesn't use the same format. **Example** ```python from fastapi import FastAPI app = FastAPI(redirect_slashes=True) # the default @app.get("/items/") async def read_items(): return [{"item_id": "Foo"}] ``` With this app, if a client goes to `/items` (without a trailing slash), they will be automatically redirected with an HTTP status code of 307 to `/items/`. """ ), ] = True, docs_url: Annotated[ str | None, Doc( """ The path to the automatic interactive API documentation. It is handled in the browser by Swagger UI. The default URL is `/docs`. You can disable it by setting it to `None`. If `openapi_url` is set to `None`, this will be automatically disabled. Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls). **Example** ```python from fastapi import FastAPI app = FastAPI(docs_url="/documentation", redoc_url=None) ``` """ ), ] = "/docs", redoc_url: Annotated[ str | None, Doc( """ The path to the alternative automatic interactive API documentation provided by ReDoc. The default URL is `/redoc`. You can disable it by setting it to `None`. If `openapi_url` is set to `None`, this will be automatically disabled. Read more in the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls). **Example** ```python from fastapi import FastAPI app = FastAPI(docs_url="/documentation", redoc_url="redocumentation") ``` """ ), ] = "/redoc", swagger_ui_oauth2_redirect_url: Annotated[ str | None, Doc( """ The OAuth2 redirect endpoint for the Swagger UI. By default it is `/docs/oauth2-redirect`. This is only used if you use OAuth2 (with the "Authorize" button) with Swagger UI. """ ), ] = "/docs/oauth2-redirect", swagger_ui_init_oauth: Annotated[ dict[str, Any] | None, Doc( """ OAuth2 configuration for the Swagger UI, by default shown at `/docs`. Read more about the available configuration options in the [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/). """ ), ] = None, middleware: Annotated[ Sequence[Middleware] | None, Doc( """ List of middleware to be added when creating the application. In FastAPI you would normally do this with `app.add_middleware()` instead. Read more in the [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/). """ ), ] = None, exception_handlers: Annotated[ dict[ int | type[Exception], Callable[[Request, Any], Coroutine[Any, Any, Response]], ] | None, Doc( """ A dictionary with handlers for exceptions. In FastAPI, you would normally use the decorator `@app.exception_handler()`. Read more in the [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). """ ), ] = None, on_startup: Annotated[ Sequence[Callable[[], Any]] | None, Doc( """ A list of startup event handler functions. You should instead use the `lifespan` handlers. Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). """ ), ] = None, on_shutdown: Annotated[ Sequence[Callable[[], Any]] | None, Doc( """ A list of shutdown event handler functions. You should instead use the `lifespan` handlers. Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). """ ), ] = None, lifespan: Annotated[ Lifespan[AppType] | None, Doc( """ A `Lifespan` context manager handler. This replaces `startup` and `shutdown` functions with a single context manager. Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). """ ), ] = None, terms_of_service: Annotated[ str | None, Doc( """ A URL to the Terms of Service for your API. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more at the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). **Example** ```python app = FastAPI(terms_of_service="http://example.com/terms/") ``` """ ), ] = None, contact: Annotated[ dict[str, str | Any] | None, Doc( """ A dictionary with the contact information for the exposed API. It can contain several fields. * `name`: (`str`) The name of the contact person/organization. * `url`: (`str`) A URL pointing to the contact information. MUST be in the format of a URL. * `email`: (`str`) The email address of the contact person/organization. MUST be in the format of an email address. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more at the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). **Example** ```python app = FastAPI( contact={ "name": "Deadpoolio the Amazing", "url": "http://x-force.example.com/contact/", "email": "dp@x-force.example.com", } ) ``` """ ), ] = None, license_info: Annotated[ dict[str, str | Any] | None, Doc( """ A dictionary with the license information for the exposed API. It can contain several fields. * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The license name used for the API. * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression for the API. The `identifier` field is mutually exclusive of the `url` field. Available since OpenAPI 3.1.0, FastAPI 0.99.0. * `url`: (`str`) A URL to the license used for the API. This MUST be the format of a URL. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more at the [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api). **Example** ```python app = FastAPI( license_info={ "name": "Apache 2.0", "url": "https://www.apache.org/licenses/LICENSE-2.0.html", } ) ``` """ ), ] = None, openapi_prefix: Annotated[ str, Doc( """ A URL prefix for the OpenAPI URL. """ ), deprecated( """ "openapi_prefix" has been deprecated in favor of "root_path", which follows more closely the ASGI standard, is simpler, and more automatic. """ ), ] = "", root_path: Annotated[ str, Doc( """ A path prefix handled by a proxy that is not seen by the application but is seen by external clients, which affects things like Swagger UI. Read more about it at the [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/). **Example** ```python from fastapi import FastAPI app = FastAPI(root_path="/api/v1") ``` """ ), ] = "", root_path_in_servers: Annotated[ bool, Doc( """ To disable automatically generating the URLs in the `servers` field in the autogenerated OpenAPI using the `root_path`. Read more about it in the [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root-path). **Example** ```python from fastapi import FastAPI app = FastAPI(root_path_in_servers=False) ``` """ ), ] = True, responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses to be shown in OpenAPI. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). And in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ OpenAPI callbacks that should apply to all *path operations*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, webhooks: Annotated[ routing.APIRouter | None, Doc( """ Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't depend on specific *path operations*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0. Read more about it in the [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark all *path operations* as deprecated. You probably don't need it, but it's available. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#deprecate-a-path-operation). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) all the *path operations* in the generated OpenAPI. You probably don't need it, but it's available. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, swagger_ui_parameters: Annotated[ dict[str, Any] | None, Doc( """ Parameters to configure Swagger UI, the autogenerated interactive API documentation (by default at `/docs`). Read more about it in the [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[routing.APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), separate_input_output_schemas: Annotated[ bool, Doc( """ Whether to generate separate OpenAPI schemas for request body and response body when the results would be more precise. This is particularly useful when automatically generating clients. For example, if you have a model like: ```python from pydantic import BaseModel class Item(BaseModel): name: str tags: list[str] = [] ``` When `Item` is used for input, a request body, `tags` is not required, the client doesn't have to provide it. But when using `Item` for output, for a response body, `tags` is always available because it has a default value, even if it's just an empty list. So, the client should be able to always expect it. In this case, there would be two different schemas, one for input and another one for output. Read more about it in the [FastAPI docs about how to separate schemas for input and output](https://fastapi.tiangolo.com/how-to/separate-openapi-schemas) """ ), ] = True, openapi_external_docs: Annotated[ dict[str, Any] | None, Doc( """ This field allows you to provide additional external documentation links. If provided, it must be a dictionary containing: * `description`: A brief description of the external documentation. * `url`: The URL pointing to the external documentation. The value **MUST** be a valid URL format. **Example**: ```python from fastapi import FastAPI external_docs = { "description": "Detailed API Reference", "url": "https://example.com/api-docs", } app = FastAPI(openapi_external_docs=external_docs) ``` """ ), ] = None, strict_content_type: Annotated[ bool, Doc( """ Enable strict checking for request Content-Type headers. When `True` (the default), requests with a body that do not include a `Content-Type` header will **not** be parsed as JSON. This prevents potential cross-site request forgery (CSRF) attacks that exploit the browser's ability to send requests without a Content-Type header, bypassing CORS preflight checks. In particular applicable for apps that need to be run locally (in localhost). When `False`, requests without a `Content-Type` header will have their body parsed as JSON, which maintains compatibility with certain clients that don't send `Content-Type` headers. Read more about it in the [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/). """ ), ] = True, **extra: Annotated[ Any, Doc( """ Extra keyword arguments to be stored in the app, not used by FastAPI anywhere. """ ), ], ) -> None: self.debug = debug self.title = title self.summary = summary self.description = description self.version = version self.terms_of_service = terms_of_service self.contact = contact self.license_info = license_info self.openapi_url = openapi_url self.openapi_tags = openapi_tags self.root_path_in_servers = root_path_in_servers self.docs_url = docs_url self.redoc_url = redoc_url self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url self.swagger_ui_init_oauth = swagger_ui_init_oauth self.swagger_ui_parameters = swagger_ui_parameters self.servers = servers or [] self.separate_input_output_schemas = separate_input_output_schemas self.openapi_external_docs = openapi_external_docs self.extra = extra self.openapi_version: Annotated[ str, Doc( """ The version string of OpenAPI. FastAPI will generate OpenAPI version 3.1.0, and will output that as the OpenAPI version. But some tools, even though they might be compatible with OpenAPI 3.1.0, might not recognize it as a valid. So you could override this value to trick those tools into using the generated OpenAPI. Have in mind that this is a hack. But if you avoid using features added in OpenAPI 3.1.0, it might work for your use case. This is not passed as a parameter to the `FastAPI` class to avoid giving the false idea that FastAPI would generate a different OpenAPI schema. It is only available as an attribute. **Example** ```python from fastapi import FastAPI app = FastAPI() app.openapi_version = "3.0.2" ``` """ ), ] = "3.1.0" self.openapi_schema: dict[str, Any] | None = None if self.openapi_url: assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'" assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'" # TODO: remove when discarding the openapi_prefix parameter if openapi_prefix: logger.warning( '"openapi_prefix" has been deprecated in favor of "root_path", which ' "follows more closely the ASGI standard, is simpler, and more " "automatic. Check the docs at " "https://fastapi.tiangolo.com/advanced/sub-applications/" ) self.webhooks: Annotated[ routing.APIRouter, Doc( """ The `app.webhooks` attribute is an `APIRouter` with the *path operations* that will be used just for documentation of webhooks. Read more about it in the [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/). """ ), ] = webhooks or routing.APIRouter() self.root_path = root_path or openapi_prefix self.state: Annotated[ State, Doc( """ A state object for the application. This is the same object for the entire application, it doesn't change from request to request. You normally wouldn't use this in FastAPI, for most of the cases you would instead use FastAPI dependencies. This is simply inherited from Starlette. Read more about it in the [Starlette docs for Applications](https://www.starlette.dev/applications/#storing-state-on-the-app-instance). """ ), ] = State() self.dependency_overrides: Annotated[ dict[Callable[..., Any], Callable[..., Any]], Doc( """ A dictionary with overrides for the dependencies. Each key is the original dependency callable, and the value is the actual dependency that should be called. This is for testing, to replace expensive dependencies with testing versions. Read more about it in the [FastAPI docs for Testing Dependencies with Overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/). """ ), ] = {} self.router: routing.APIRouter = routing.APIRouter( routes=routes, redirect_slashes=redirect_slashes, dependency_overrides_provider=self, on_startup=on_startup, on_shutdown=on_shutdown, lifespan=lifespan, default_response_class=default_response_class, dependencies=dependencies, callbacks=callbacks, deprecated=deprecated, include_in_schema=include_in_schema, responses=responses, generate_unique_id_function=generate_unique_id_function, strict_content_type=strict_content_type, ) self.exception_handlers: dict[ Any, Callable[[Request, Any], Response | Awaitable[Response]] ] = {} if exception_handlers is None else dict(exception_handlers) self.exception_handlers.setdefault(HTTPException, http_exception_handler) self.exception_handlers.setdefault( RequestValidationError, request_validation_exception_handler ) # Starlette still has incorrect type specification for the handlers self.exception_handlers.setdefault( WebSocketRequestValidationError, websocket_request_validation_exception_handler, # type: ignore[arg-type] # ty: ignore[unused-ignore-comment] ) # ty: ignore[no-matching-overload] self.user_middleware: list[Middleware] = ( [] if middleware is None else list(middleware) ) self.middleware_stack: ASGIApp | None = None self.setup() def build_middleware_stack(self) -> ASGIApp: # Duplicate/override from Starlette to add AsyncExitStackMiddleware # inside of ExceptionMiddleware, inside of custom user middlewares debug = self.debug error_handler = None exception_handlers: dict[Any, ExceptionHandler] = {} for key, value in self.exception_handlers.items(): if key in (500, Exception): error_handler = value else: exception_handlers[key] = value middleware = ( [Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)] # ty: ignore[invalid-argument-type] + self.user_middleware + [ Middleware( ExceptionMiddleware, # ty: ignore[invalid-argument-type] handlers=exception_handlers, debug=debug, ), # Add FastAPI-specific AsyncExitStackMiddleware for closing files. # Before this was also used for closing dependencies with yield but # those now have their own AsyncExitStack, to properly support # streaming responses while keeping compatibility with the previous # versions (as of writing 0.117.1) that allowed doing # except HTTPException inside a dependency with yield. # This needs to happen after user middlewares because those create a # new contextvars context copy by using a new AnyIO task group. # This AsyncExitStack preserves the context for contextvars, not # strictly necessary for closing files but it was one of the original # intentions. # If the AsyncExitStack lived outside of the custom middlewares and # contextvars were set, for example in a dependency with 'yield' # in that internal contextvars context, the values would not be # available in the outer context of the AsyncExitStack. # By placing the middleware and the AsyncExitStack here, inside all # user middlewares, the same context is used. # This is currently not needed, only for closing files, but used to be # important when dependencies with yield were closed here. Middleware(AsyncExitStackMiddleware), # ty: ignore[invalid-argument-type] ] ) app = self.router for cls, args, kwargs in reversed(middleware): app = cls(app, *args, **kwargs) return app def openapi(self) -> dict[str, Any]: if not self.openapi_schema: self.openapi_schema = get_openapi( title=self.title, version=self.version, openapi_version=self.openapi_version, summary=self.summary, description=self.description, terms_of_service=self.terms_of_service, contact=self.contact, license_info=self.license_info, routes=self.routes, webhooks=self.webhooks.routes, tags=self.openapi_tags, servers=self.servers, separate_input_output_schemas=self.separate_input_output_schemas, external_docs=self.openapi_external_docs, ) return self.openapi_schema def setup(self) -> None: if self.openapi_url: async def openapi(req: Request) -> JSONResponse: root_path = req.scope.get("root_path", "").rstrip("/") schema = self.openapi() if root_path and self.root_path_in_servers: server_urls = {s.get("url") for s in schema.get("servers", [])} if root_path not in server_urls: schema = dict(schema) schema["servers"] = [{"url": root_path}] + schema.get( "servers", [] ) return JSONResponse(schema) self.add_route(self.openapi_url, openapi, include_in_schema=False) if self.openapi_url and self.docs_url: async def swagger_ui_html(req: Request) -> HTMLResponse: root_path = req.scope.get("root_path", "").rstrip("/") openapi_url = root_path + self.openapi_url oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url if oauth2_redirect_url: oauth2_redirect_url = root_path + oauth2_redirect_url return get_swagger_ui_html( openapi_url=openapi_url, title=f"{self.title} - Swagger UI", oauth2_redirect_url=oauth2_redirect_url, init_oauth=self.swagger_ui_init_oauth, swagger_ui_parameters=self.swagger_ui_parameters, ) self.add_route(self.docs_url, swagger_ui_html, include_in_schema=False) if self.swagger_ui_oauth2_redirect_url: async def swagger_ui_redirect(req: Request) -> HTMLResponse: return get_swagger_ui_oauth2_redirect_html() self.add_route( self.swagger_ui_oauth2_redirect_url, swagger_ui_redirect, include_in_schema=False, ) if self.openapi_url and self.redoc_url: async def redoc_html(req: Request) -> HTMLResponse: root_path = req.scope.get("root_path", "").rstrip("/") openapi_url = root_path + self.openapi_url return get_redoc_html( openapi_url=openapi_url, title=f"{self.title} - ReDoc" ) self.add_route(self.redoc_url, redoc_html, include_in_schema=False) async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if self.root_path: scope["root_path"] = self.root_path await super().__call__(scope, receive, send) def add_api_route( self, path: str, endpoint: Callable[..., Any], *, response_model: Any = Default(None), status_code: int | None = None, tags: list[str | Enum] | None = None, dependencies: Sequence[Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = "Successful Response", responses: dict[int | str, dict[str, Any]] | None = None, deprecated: bool | None = None, methods: list[str] | None = None, operation_id: str | None = None, response_model_include: IncEx | None = None, response_model_exclude: IncEx | None = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse), name: str | None = None, openapi_extra: dict[str, Any] | None = None, generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( generate_unique_id ), ) -> None: self.router.add_api_route( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: int | None = None, tags: list[str | Enum] | None = None, dependencies: Sequence[Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = "Successful Response", responses: dict[int | str, dict[str, Any]] | None = None, deprecated: bool | None = None, methods: list[str] | None = None, operation_id: str | None = None, response_model_include: IncEx | None = None, response_model_exclude: IncEx | None = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: type[Response] = Default(JSONResponse), name: str | None = None, openapi_extra: dict[str, Any] | None = None, generate_unique_id_function: Callable[[routing.APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.router.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: str | None = None, *, dependencies: Sequence[Depends] | None = None, ) -> None: self.router.add_api_websocket_route( path, endpoint, name=name, dependencies=dependencies, ) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ str | None, Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Sequence[Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies, ) return func return decorator def include_router( self, router: Annotated[routing.APIRouter, Doc("The `APIRouter` to include.")], *, prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to all the *path operations* in this router. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, dependencies: Annotated[ Sequence[Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to all the *path operations* in this router. Read more about it in the [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). **Example** ```python from fastapi import Depends, FastAPI from .dependencies import get_token_header from .internal import admin app = FastAPI() app.include_router( admin.router, dependencies=[Depends(get_token_header)], ) ``` """ ), ] = None, responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses to be shown in OpenAPI. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). And in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark all the *path operations* in this router as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). **Example** ```python from fastapi import FastAPI from .internal import old_api app = FastAPI() app.include_router( old_api.router, deprecated=True, ) ``` """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). **Example** ```python from fastapi import FastAPI from .internal import old_api app = FastAPI() app.include_router( old_api.router, include_in_schema=False, ) ``` """ ), ] = True, default_response_class: Annotated[ type[Response], Doc( """ Default response class to be used for the *path operations* in this router. Read more in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). **Example** ```python from fastapi import FastAPI from fastapi.responses import ORJSONResponse from .internal import old_api app = FastAPI() app.include_router( old_api.router, default_response_class=ORJSONResponse, ) ``` """ ), ] = Default(JSONResponse), callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[routing.APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> None: self.router.include_router( router, prefix=prefix, tags=tags, dependencies=dependencies, responses=responses, deprecated=deprecated, include_in_schema=include_in_schema, default_response_class=default_response_class, callbacks=callbacks, generate_unique_id_function=generate_unique_id_function, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[routing.APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.get( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[routing.APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.put( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[routing.APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.post( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[routing.APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.delete( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[routing.APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.options( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[routing.APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.head( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[routing.APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.patch( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[routing.APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.trace( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def websocket_route( self, path: str, name: str | None = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.router.add_websocket_route(path, func, name=name) return func return decorator @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.on_event(event_type) # ty: ignore[deprecated] def middleware( self, middleware_type: Annotated[ str, Doc( """ The type of middleware. Currently only supports `http`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_middleware(BaseHTTPMiddleware, dispatch=func) # ty: ignore[invalid-argument-type] return func return decorator def exception_handler( self, exc_class_or_status_code: Annotated[ int | type[Exception], Doc( """ The Exception class this would handle, or a status code. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_exception_handler(exc_class_or_status_code, func) return func return decorator
--- +++ @@ -39,6 +39,20 @@ class FastAPI(Starlette): + """ + `FastAPI` app class, the main entrypoint to use FastAPI. + + Read more in the + [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/). + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + ``` + """ def __init__( self: AppType, @@ -1052,6 +1066,19 @@ return app def openapi(self) -> dict[str, Any]: + """ + Generate the OpenAPI schema of the application. This is called by FastAPI + internally. + + The first time it is called it stores the result in the attribute + `app.openapi_schema`, and next times it is called, it just returns that same + result. To avoid the cost of generating the schema every time. + + If you need to modify the generated OpenAPI schema, you could modify it. + + Read more in the + [FastAPI docs for OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/). + """ if not self.openapi_schema: self.openapi_schema = get_openapi( title=self.title, @@ -1295,6 +1322,27 @@ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Decorate a WebSocket function. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + + **Example** + + ```python + from fastapi import FastAPI, WebSocket + + app = FastAPI() + + @app.websocket("/ws") + async def websocket_endpoint(websocket: WebSocket): + await websocket.accept() + while True: + data = await websocket.receive_text() + await websocket.send_text(f"Message text was: {data}") + ``` + """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( @@ -1481,6 +1529,24 @@ ), ] = Default(generate_unique_id), ) -> None: + """ + Include an `APIRouter` in the same app. + + Read more about it in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). + + ## Example + + ```python + from fastapi import FastAPI + + from .users import users_router + + app = FastAPI() + + app.include_router(users_router) + ``` + """ self.router.include_router( router, prefix=prefix, @@ -1826,6 +1892,21 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP GET operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.get("/items/") + def read_items(): + return [{"name": "Empanada"}, {"name": "Arepa"}] + ``` + """ return self.router.get( path, response_model=response_model, @@ -2184,6 +2265,26 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PUT operation. + + ## Example + + ```python + from fastapi import FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + + @app.put("/items/{item_id}") + def replace_item(item_id: str, item: Item): + return {"message": "Item replaced", "id": item_id} + ``` + """ return self.router.put( path, response_model=response_model, @@ -2542,6 +2643,26 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP POST operation. + + ## Example + + ```python + from fastapi import FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + + @app.post("/items/") + def create_item(item: Item): + return {"message": "Item created"} + ``` + """ return self.router.post( path, response_model=response_model, @@ -2900,6 +3021,21 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP DELETE operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.delete("/items/{item_id}") + def delete_item(item_id: str): + return {"message": "Item deleted"} + ``` + """ return self.router.delete( path, response_model=response_model, @@ -3258,6 +3394,21 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP OPTIONS operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.options("/items/") + def get_item_options(): + return {"additions": ["Aji", "Guacamole"]} + ``` + """ return self.router.options( path, response_model=response_model, @@ -3616,6 +3767,21 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP HEAD operation. + + ## Example + + ```python + from fastapi import FastAPI, Response + + app = FastAPI() + + @app.head("/items/", status_code=204) + def get_items_headers(response: Response): + response.headers["X-Cat-Dog"] = "Alone in the world" + ``` + """ return self.router.head( path, response_model=response_model, @@ -3974,6 +4140,26 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PATCH operation. + + ## Example + + ```python + from fastapi import FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + + @app.patch("/items/") + def update_item(item: Item): + return {"message": "Item updated in place"} + ``` + """ return self.router.patch( path, response_model=response_model, @@ -4332,6 +4518,21 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP TRACE operation. + + ## Example + + ```python + from fastapi import FastAPI + + app = FastAPI() + + @app.trace("/items/{item_id}") + def trace_item(item_id: str): + return None + ``` + """ return self.router.trace( path, response_model=response_model, @@ -4386,6 +4587,14 @@ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add an event handler for the application. + + `on_event` is deprecated, use `lifespan` event handlers instead. + + Read more about it in the + [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). + """ return self.router.on_event(event_type) # ty: ignore[deprecated] def middleware( @@ -4399,6 +4608,34 @@ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a middleware to the application. + + Read more about it in the + [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/). + + ## Example + + ```python + import time + from typing import Awaitable, Callable + + from fastapi import FastAPI, Request, Response + + app = FastAPI() + + + @app.middleware("http") + async def add_process_time_header( + request: Request, call_next: Callable[[Request], Awaitable[Response]] + ) -> Response: + start_time = time.time() + response = await call_next(request) + process_time = time.time() - start_time + response.headers["X-Process-Time"] = str(process_time) + return response + ``` + """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_middleware(BaseHTTPMiddleware, dispatch=func) # ty: ignore[invalid-argument-type] @@ -4417,9 +4654,38 @@ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add an exception handler to the app. + + Read more about it in the + [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/). + + ## Example + + ```python + from fastapi import FastAPI, Request + from fastapi.responses import JSONResponse + + + class UnicornException(Exception): + def __init__(self, name: str): + self.name = name + + + app = FastAPI() + + + @app.exception_handler(UnicornException) + async def unicorn_exception_handler(request: Request, exc: UnicornException): + return JSONResponse( + status_code=418, + content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."}, + ) + ``` + """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_exception_handler(exc_class_or_status_code, func) return func - return decorator+ return decorator
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/applications.py
Add documentation for all methods
import dataclasses import inspect import sys from collections.abc import ( AsyncGenerator, AsyncIterable, AsyncIterator, Callable, Generator, Iterable, Iterator, Mapping, Sequence, ) from contextlib import AsyncExitStack, contextmanager from copy import copy, deepcopy from dataclasses import dataclass from typing import ( Annotated, Any, ForwardRef, Literal, Union, cast, get_args, get_origin, ) from fastapi import params from fastapi._compat import ( ModelField, RequiredParam, Undefined, copy_field_info, create_body_model, evaluate_forwardref, # ty: ignore[deprecated] field_annotation_is_scalar, field_annotation_is_scalar_sequence, field_annotation_is_sequence, get_cached_model_fields, get_missing_field_error, is_bytes_or_nonable_bytes_annotation, is_bytes_sequence_annotation, is_scalar_field, is_uploadfile_or_nonable_uploadfile_annotation, is_uploadfile_sequence_annotation, lenient_issubclass, sequence_types, serialize_sequence_value, value_is_sequence, ) from fastapi.background import BackgroundTasks from fastapi.concurrency import ( asynccontextmanager, contextmanager_in_threadpool, ) from fastapi.dependencies.models import Dependant from fastapi.exceptions import DependencyScopeError from fastapi.logger import logger from fastapi.security.oauth2 import SecurityScopes from fastapi.types import DependencyCacheKey from fastapi.utils import create_model_field, get_path_param_names from pydantic import BaseModel, Json from pydantic.fields import FieldInfo from starlette.background import BackgroundTasks as StarletteBackgroundTasks from starlette.concurrency import run_in_threadpool from starlette.datastructures import ( FormData, Headers, ImmutableMultiDict, QueryParams, UploadFile, ) from starlette.requests import HTTPConnection, Request from starlette.responses import Response from starlette.websockets import WebSocket from typing_inspection.typing_objects import is_typealiastype multipart_not_installed_error = ( 'Form data requires "python-multipart" to be installed. \n' 'You can install "python-multipart" with: \n\n' "pip install python-multipart\n" ) multipart_incorrect_install_error = ( 'Form data requires "python-multipart" to be installed. ' 'It seems you installed "multipart" instead. \n' 'You can remove "multipart" with: \n\n' "pip uninstall multipart\n\n" 'And then install "python-multipart" with: \n\n' "pip install python-multipart\n" ) def ensure_multipart_is_installed() -> None: try: from python_multipart import __version__ # Import an attribute that can be mocked/deleted in testing assert __version__ > "0.0.12" except (ImportError, AssertionError): try: # __version__ is available in both multiparts, and can be mocked from multipart import ( # type: ignore[no-redef,import-untyped] # ty: ignore[unused-ignore-comment] __version__, ) assert __version__ try: # parse_options_header is only available in the right multipart from multipart.multipart import ( # type: ignore[import-untyped] # ty: ignore[unused-ignore-comment] parse_options_header, ) assert parse_options_header except ImportError: logger.error(multipart_incorrect_install_error) raise RuntimeError(multipart_incorrect_install_error) from None except ImportError: logger.error(multipart_not_installed_error) raise RuntimeError(multipart_not_installed_error) from None def get_parameterless_sub_dependant(*, depends: params.Depends, path: str) -> Dependant: assert callable(depends.dependency), ( "A parameter-less dependency must have a callable dependency" ) own_oauth_scopes: list[str] = [] if isinstance(depends, params.Security) and depends.scopes: own_oauth_scopes.extend(depends.scopes) return get_dependant( path=path, call=depends.dependency, scope=depends.scope, own_oauth_scopes=own_oauth_scopes, ) def get_flat_dependant( dependant: Dependant, *, skip_repeats: bool = False, visited: list[DependencyCacheKey] | None = None, parent_oauth_scopes: list[str] | None = None, ) -> Dependant: if visited is None: visited = [] visited.append(dependant.cache_key) use_parent_oauth_scopes = (parent_oauth_scopes or []) + ( dependant.oauth_scopes or [] ) flat_dependant = Dependant( path_params=dependant.path_params.copy(), query_params=dependant.query_params.copy(), header_params=dependant.header_params.copy(), cookie_params=dependant.cookie_params.copy(), body_params=dependant.body_params.copy(), name=dependant.name, call=dependant.call, request_param_name=dependant.request_param_name, websocket_param_name=dependant.websocket_param_name, http_connection_param_name=dependant.http_connection_param_name, response_param_name=dependant.response_param_name, background_tasks_param_name=dependant.background_tasks_param_name, security_scopes_param_name=dependant.security_scopes_param_name, own_oauth_scopes=dependant.own_oauth_scopes, parent_oauth_scopes=use_parent_oauth_scopes, use_cache=dependant.use_cache, path=dependant.path, scope=dependant.scope, ) for sub_dependant in dependant.dependencies: if skip_repeats and sub_dependant.cache_key in visited: continue flat_sub = get_flat_dependant( sub_dependant, skip_repeats=skip_repeats, visited=visited, parent_oauth_scopes=flat_dependant.oauth_scopes, ) flat_dependant.dependencies.append(flat_sub) flat_dependant.path_params.extend(flat_sub.path_params) flat_dependant.query_params.extend(flat_sub.query_params) flat_dependant.header_params.extend(flat_sub.header_params) flat_dependant.cookie_params.extend(flat_sub.cookie_params) flat_dependant.body_params.extend(flat_sub.body_params) flat_dependant.dependencies.extend(flat_sub.dependencies) return flat_dependant def _get_flat_fields_from_params(fields: list[ModelField]) -> list[ModelField]: if not fields: return fields first_field = fields[0] if len(fields) == 1 and lenient_issubclass( first_field.field_info.annotation, BaseModel ): fields_to_extract = get_cached_model_fields(first_field.field_info.annotation) return fields_to_extract return fields def get_flat_params(dependant: Dependant) -> list[ModelField]: flat_dependant = get_flat_dependant(dependant, skip_repeats=True) path_params = _get_flat_fields_from_params(flat_dependant.path_params) query_params = _get_flat_fields_from_params(flat_dependant.query_params) header_params = _get_flat_fields_from_params(flat_dependant.header_params) cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params) return path_params + query_params + header_params + cookie_params def _get_signature(call: Callable[..., Any]) -> inspect.Signature: try: signature = inspect.signature(call, eval_str=True) except NameError: # Handle type annotations with if TYPE_CHECKING, not used by FastAPI # e.g. dependency return types if sys.version_info >= (3, 14): from annotationlib import Format signature = inspect.signature(call, annotation_format=Format.FORWARDREF) else: signature = inspect.signature(call) return signature def get_typed_signature(call: Callable[..., Any]) -> inspect.Signature: signature = _get_signature(call) unwrapped = inspect.unwrap(call) globalns = getattr(unwrapped, "__globals__", {}) typed_params = [ inspect.Parameter( name=param.name, kind=param.kind, default=param.default, annotation=get_typed_annotation(param.annotation, globalns), ) for param in signature.parameters.values() ] typed_signature = inspect.Signature(typed_params) return typed_signature def get_typed_annotation(annotation: Any, globalns: dict[str, Any]) -> Any: if isinstance(annotation, str): annotation = ForwardRef(annotation) annotation = evaluate_forwardref(annotation, globalns, globalns) # ty: ignore[deprecated] if annotation is type(None): return None return annotation def get_typed_return_annotation(call: Callable[..., Any]) -> Any: signature = _get_signature(call) unwrapped = inspect.unwrap(call) annotation = signature.return_annotation if annotation is inspect.Signature.empty: return None globalns = getattr(unwrapped, "__globals__", {}) return get_typed_annotation(annotation, globalns) _STREAM_ORIGINS = { AsyncIterable, AsyncIterator, AsyncGenerator, Iterable, Iterator, Generator, } def get_stream_item_type(annotation: Any) -> Any | None: origin = get_origin(annotation) if origin is not None and origin in _STREAM_ORIGINS: type_args = get_args(annotation) if type_args: return type_args[0] return Any return None def get_dependant( *, path: str, call: Callable[..., Any], name: str | None = None, own_oauth_scopes: list[str] | None = None, parent_oauth_scopes: list[str] | None = None, use_cache: bool = True, scope: Literal["function", "request"] | None = None, ) -> Dependant: dependant = Dependant( call=call, name=name, path=path, use_cache=use_cache, scope=scope, own_oauth_scopes=own_oauth_scopes, parent_oauth_scopes=parent_oauth_scopes, ) current_scopes = (parent_oauth_scopes or []) + (own_oauth_scopes or []) path_param_names = get_path_param_names(path) endpoint_signature = get_typed_signature(call) signature_params = endpoint_signature.parameters for param_name, param in signature_params.items(): is_path_param = param_name in path_param_names param_details = analyze_param( param_name=param_name, annotation=param.annotation, value=param.default, is_path_param=is_path_param, ) if param_details.depends is not None: assert param_details.depends.dependency if ( (dependant.is_gen_callable or dependant.is_async_gen_callable) and dependant.computed_scope == "request" and param_details.depends.scope == "function" ): assert dependant.call call_name = getattr(dependant.call, "__name__", "<unnamed_callable>") raise DependencyScopeError( f'The dependency "{call_name}" has a scope of ' '"request", it cannot depend on dependencies with scope "function".' ) sub_own_oauth_scopes: list[str] = [] if isinstance(param_details.depends, params.Security): if param_details.depends.scopes: sub_own_oauth_scopes = list(param_details.depends.scopes) sub_dependant = get_dependant( path=path, call=param_details.depends.dependency, name=param_name, own_oauth_scopes=sub_own_oauth_scopes, parent_oauth_scopes=current_scopes, use_cache=param_details.depends.use_cache, scope=param_details.depends.scope, ) dependant.dependencies.append(sub_dependant) continue if add_non_field_param_to_dependency( param_name=param_name, type_annotation=param_details.type_annotation, dependant=dependant, ): assert param_details.field is None, ( f"Cannot specify multiple FastAPI annotations for {param_name!r}" ) continue assert param_details.field is not None if isinstance(param_details.field.field_info, params.Body): dependant.body_params.append(param_details.field) else: add_param_to_fields(field=param_details.field, dependant=dependant) return dependant def add_non_field_param_to_dependency( *, param_name: str, type_annotation: Any, dependant: Dependant ) -> bool | None: if lenient_issubclass(type_annotation, Request): dependant.request_param_name = param_name return True elif lenient_issubclass(type_annotation, WebSocket): dependant.websocket_param_name = param_name return True elif lenient_issubclass(type_annotation, HTTPConnection): dependant.http_connection_param_name = param_name return True elif lenient_issubclass(type_annotation, Response): dependant.response_param_name = param_name return True elif lenient_issubclass(type_annotation, StarletteBackgroundTasks): dependant.background_tasks_param_name = param_name return True elif lenient_issubclass(type_annotation, SecurityScopes): dependant.security_scopes_param_name = param_name return True return None @dataclass class ParamDetails: type_annotation: Any depends: params.Depends | None field: ModelField | None def analyze_param( *, param_name: str, annotation: Any, value: Any, is_path_param: bool, ) -> ParamDetails: field_info = None depends = None type_annotation: Any = Any use_annotation: Any = Any if is_typealiastype(annotation): # unpack in case PEP 695 type syntax is used annotation = annotation.__value__ if annotation is not inspect.Signature.empty: use_annotation = annotation type_annotation = annotation # Extract Annotated info if get_origin(use_annotation) is Annotated: annotated_args = get_args(annotation) type_annotation = annotated_args[0] fastapi_annotations = [ arg for arg in annotated_args[1:] if isinstance(arg, (FieldInfo, params.Depends)) ] fastapi_specific_annotations = [ arg for arg in fastapi_annotations if isinstance( arg, ( params.Param, params.Body, params.Depends, ), ) ] if fastapi_specific_annotations: fastapi_annotation: FieldInfo | params.Depends | None = ( fastapi_specific_annotations[-1] ) else: fastapi_annotation = None # Set default for Annotated FieldInfo if isinstance(fastapi_annotation, FieldInfo): # Copy `field_info` because we mutate `field_info.default` below. field_info = copy_field_info( field_info=fastapi_annotation, annotation=use_annotation, ) assert ( field_info.default == Undefined or field_info.default == RequiredParam ), ( f"`{field_info.__class__.__name__}` default value cannot be set in" f" `Annotated` for {param_name!r}. Set the default value with `=` instead." ) if value is not inspect.Signature.empty: assert not is_path_param, "Path parameters cannot have default values" field_info.default = value else: field_info.default = RequiredParam # Get Annotated Depends elif isinstance(fastapi_annotation, params.Depends): depends = fastapi_annotation # Get Depends from default value if isinstance(value, params.Depends): assert depends is None, ( "Cannot specify `Depends` in `Annotated` and default value" f" together for {param_name!r}" ) assert field_info is None, ( "Cannot specify a FastAPI annotation in `Annotated` and `Depends` as a" f" default value together for {param_name!r}" ) depends = value # Get FieldInfo from default value elif isinstance(value, FieldInfo): assert field_info is None, ( "Cannot specify FastAPI annotations in `Annotated` and default value" f" together for {param_name!r}" ) field_info = value if isinstance(field_info, FieldInfo): field_info.annotation = type_annotation # Get Depends from type annotation if depends is not None and depends.dependency is None: # Copy `depends` before mutating it depends = copy(depends) depends = dataclasses.replace(depends, dependency=type_annotation) # Handle non-param type annotations like Request # Only apply special handling when there's no explicit Depends - if there's a Depends, # the dependency will be called and its return value used instead of the special injection if depends is None and lenient_issubclass( type_annotation, ( Request, WebSocket, HTTPConnection, Response, StarletteBackgroundTasks, SecurityScopes, ), ): assert field_info is None, ( f"Cannot specify FastAPI annotation for type {type_annotation!r}" ) # Handle default assignations, neither field_info nor depends was not found in Annotated nor default value elif field_info is None and depends is None: default_value = value if value is not inspect.Signature.empty else RequiredParam if is_path_param: # We might check here that `default_value is RequiredParam`, but the fact is that the same # parameter might sometimes be a path parameter and sometimes not. See # `tests/test_infer_param_optionality.py` for an example. field_info = params.Path(annotation=use_annotation) elif is_uploadfile_or_nonable_uploadfile_annotation( type_annotation ) or is_uploadfile_sequence_annotation(type_annotation): field_info = params.File(annotation=use_annotation, default=default_value) elif not field_annotation_is_scalar(annotation=type_annotation): field_info = params.Body(annotation=use_annotation, default=default_value) else: field_info = params.Query(annotation=use_annotation, default=default_value) field = None # It's a field_info, not a dependency if field_info is not None: # Handle field_info.in_ if is_path_param: assert isinstance(field_info, params.Path), ( f"Cannot use `{field_info.__class__.__name__}` for path param" f" {param_name!r}" ) elif ( isinstance(field_info, params.Param) and getattr(field_info, "in_", None) is None ): field_info.in_ = params.ParamTypes.query use_annotation_from_field_info = use_annotation if isinstance(field_info, params.Form): ensure_multipart_is_installed() if not field_info.alias and getattr(field_info, "convert_underscores", None): alias = param_name.replace("_", "-") else: alias = field_info.alias or param_name field_info.alias = alias field = create_model_field( name=param_name, type_=use_annotation_from_field_info, default=field_info.default, alias=alias, field_info=field_info, ) if is_path_param: assert is_scalar_field(field=field), ( "Path params must be of one of the supported types" ) elif isinstance(field_info, params.Query): assert ( is_scalar_field(field) or field_annotation_is_scalar_sequence(field.field_info.annotation) or lenient_issubclass(field.field_info.annotation, BaseModel) ), f"Query parameter {param_name!r} must be one of the supported types" return ParamDetails(type_annotation=type_annotation, depends=depends, field=field) def add_param_to_fields(*, field: ModelField, dependant: Dependant) -> None: field_info = field.field_info field_info_in = getattr(field_info, "in_", None) if field_info_in == params.ParamTypes.path: dependant.path_params.append(field) elif field_info_in == params.ParamTypes.query: dependant.query_params.append(field) elif field_info_in == params.ParamTypes.header: dependant.header_params.append(field) else: assert field_info_in == params.ParamTypes.cookie, ( f"non-body parameters must be in path, query, header or cookie: {field.name}" ) dependant.cookie_params.append(field) async def _solve_generator( *, dependant: Dependant, stack: AsyncExitStack, sub_values: dict[str, Any] ) -> Any: assert dependant.call if dependant.is_async_gen_callable: cm = asynccontextmanager(dependant.call)(**sub_values) elif dependant.is_gen_callable: cm = contextmanager_in_threadpool(contextmanager(dependant.call)(**sub_values)) return await stack.enter_async_context(cm) @dataclass class SolvedDependency: values: dict[str, Any] errors: list[Any] background_tasks: StarletteBackgroundTasks | None response: Response dependency_cache: dict[DependencyCacheKey, Any] async def solve_dependencies( *, request: Request | WebSocket, dependant: Dependant, body: dict[str, Any] | FormData | bytes | None = None, background_tasks: StarletteBackgroundTasks | None = None, response: Response | None = None, dependency_overrides_provider: Any | None = None, dependency_cache: dict[DependencyCacheKey, Any] | None = None, # TODO: remove this parameter later, no longer used, not removing it yet as some # people might be monkey patching this function (although that's not supported) async_exit_stack: AsyncExitStack, embed_body_fields: bool, ) -> SolvedDependency: request_astack = request.scope.get("fastapi_inner_astack") assert isinstance(request_astack, AsyncExitStack), ( "fastapi_inner_astack not found in request scope" ) function_astack = request.scope.get("fastapi_function_astack") assert isinstance(function_astack, AsyncExitStack), ( "fastapi_function_astack not found in request scope" ) values: dict[str, Any] = {} errors: list[Any] = [] if response is None: response = Response() del response.headers["content-length"] response.status_code = None # type: ignore # ty: ignore[unused-ignore-comment] if dependency_cache is None: dependency_cache = {} for sub_dependant in dependant.dependencies: sub_dependant.call = cast(Callable[..., Any], sub_dependant.call) call = sub_dependant.call use_sub_dependant = sub_dependant if ( dependency_overrides_provider and dependency_overrides_provider.dependency_overrides ): original_call = sub_dependant.call call = getattr( dependency_overrides_provider, "dependency_overrides", {} ).get(original_call, original_call) use_path: str = sub_dependant.path # type: ignore use_sub_dependant = get_dependant( path=use_path, call=call, name=sub_dependant.name, parent_oauth_scopes=sub_dependant.oauth_scopes, scope=sub_dependant.scope, ) solved_result = await solve_dependencies( request=request, dependant=use_sub_dependant, body=body, background_tasks=background_tasks, response=response, dependency_overrides_provider=dependency_overrides_provider, dependency_cache=dependency_cache, async_exit_stack=async_exit_stack, embed_body_fields=embed_body_fields, ) background_tasks = solved_result.background_tasks if solved_result.errors: errors.extend(solved_result.errors) continue if sub_dependant.use_cache and sub_dependant.cache_key in dependency_cache: solved = dependency_cache[sub_dependant.cache_key] elif ( use_sub_dependant.is_gen_callable or use_sub_dependant.is_async_gen_callable ): use_astack = request_astack if sub_dependant.scope == "function": use_astack = function_astack solved = await _solve_generator( dependant=use_sub_dependant, stack=use_astack, sub_values=solved_result.values, ) elif use_sub_dependant.is_coroutine_callable: solved = await call(**solved_result.values) else: solved = await run_in_threadpool(call, **solved_result.values) if sub_dependant.name is not None: values[sub_dependant.name] = solved if sub_dependant.cache_key not in dependency_cache: dependency_cache[sub_dependant.cache_key] = solved path_values, path_errors = request_params_to_args( dependant.path_params, request.path_params ) query_values, query_errors = request_params_to_args( dependant.query_params, request.query_params ) header_values, header_errors = request_params_to_args( dependant.header_params, request.headers ) cookie_values, cookie_errors = request_params_to_args( dependant.cookie_params, request.cookies ) values.update(path_values) values.update(query_values) values.update(header_values) values.update(cookie_values) errors += path_errors + query_errors + header_errors + cookie_errors if dependant.body_params: ( body_values, body_errors, ) = await request_body_to_args( # body_params checked above body_fields=dependant.body_params, received_body=body, embed_body_fields=embed_body_fields, ) values.update(body_values) errors.extend(body_errors) if dependant.http_connection_param_name: values[dependant.http_connection_param_name] = request if dependant.request_param_name and isinstance(request, Request): values[dependant.request_param_name] = request elif dependant.websocket_param_name and isinstance(request, WebSocket): values[dependant.websocket_param_name] = request if dependant.background_tasks_param_name: if background_tasks is None: background_tasks = BackgroundTasks() values[dependant.background_tasks_param_name] = background_tasks if dependant.response_param_name: values[dependant.response_param_name] = response if dependant.security_scopes_param_name: values[dependant.security_scopes_param_name] = SecurityScopes( scopes=dependant.oauth_scopes ) return SolvedDependency( values=values, errors=errors, background_tasks=background_tasks, response=response, dependency_cache=dependency_cache, ) def _validate_value_with_model_field( *, field: ModelField, value: Any, values: dict[str, Any], loc: tuple[str, ...] ) -> tuple[Any, list[Any]]: if value is None: if field.field_info.is_required(): return None, [get_missing_field_error(loc=loc)] else: return deepcopy(field.default), [] return field.validate(value, values, loc=loc) def _is_json_field(field: ModelField) -> bool: return any(type(item) is Json for item in field.field_info.metadata) def _get_multidict_value( field: ModelField, values: Mapping[str, Any], alias: str | None = None ) -> Any: alias = alias or get_validation_alias(field) if ( (not _is_json_field(field)) and field_annotation_is_sequence(field.field_info.annotation) and isinstance(values, (ImmutableMultiDict, Headers)) ): value = values.getlist(alias) else: value = values.get(alias, None) if ( value is None or ( isinstance(field.field_info, params.Form) and isinstance(value, str) # For type checks and value == "" ) or ( field_annotation_is_sequence(field.field_info.annotation) and len(value) == 0 ) ): if field.field_info.is_required(): return else: return deepcopy(field.default) return value def request_params_to_args( fields: Sequence[ModelField], received_params: Mapping[str, Any] | QueryParams | Headers, ) -> tuple[dict[str, Any], list[Any]]: values: dict[str, Any] = {} errors: list[dict[str, Any]] = [] if not fields: return values, errors first_field = fields[0] fields_to_extract = fields single_not_embedded_field = False default_convert_underscores = True if len(fields) == 1 and lenient_issubclass( first_field.field_info.annotation, BaseModel ): fields_to_extract = get_cached_model_fields(first_field.field_info.annotation) single_not_embedded_field = True # If headers are in a Pydantic model, the way to disable convert_underscores # would be with Header(convert_underscores=False) at the Pydantic model level default_convert_underscores = getattr( first_field.field_info, "convert_underscores", True ) params_to_process: dict[str, Any] = {} processed_keys = set() for field in fields_to_extract: alias = None if isinstance(received_params, Headers): # Handle fields extracted from a Pydantic Model for a header, each field # doesn't have a FieldInfo of type Header with the default convert_underscores=True convert_underscores = getattr( field.field_info, "convert_underscores", default_convert_underscores ) if convert_underscores: alias = get_validation_alias(field) if alias == field.name: alias = alias.replace("_", "-") value = _get_multidict_value(field, received_params, alias=alias) if value is not None: params_to_process[get_validation_alias(field)] = value processed_keys.add(alias or get_validation_alias(field)) for key in received_params.keys(): if key not in processed_keys: if isinstance(received_params, (ImmutableMultiDict, Headers)): value = received_params.getlist(key) if isinstance(value, list) and (len(value) == 1): params_to_process[key] = value[0] else: params_to_process[key] = value else: params_to_process[key] = received_params.get(key) if single_not_embedded_field: field_info = first_field.field_info assert isinstance(field_info, params.Param), ( "Params must be subclasses of Param" ) loc: tuple[str, ...] = (field_info.in_.value,) v_, errors_ = _validate_value_with_model_field( field=first_field, value=params_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in fields: value = _get_multidict_value(field, received_params) field_info = field.field_info assert isinstance(field_info, params.Param), ( "Params must be subclasses of Param" ) loc = (field_info.in_.value, get_validation_alias(field)) v_, errors_ = _validate_value_with_model_field( field=field, value=value, values=values, loc=loc ) if errors_: errors.extend(errors_) else: values[field.name] = v_ return values, errors def is_union_of_base_models(field_type: Any) -> bool: from fastapi.types import UnionType origin = get_origin(field_type) # Check if it's a Union type (covers both typing.Union and types.UnionType in Python 3.10+) if origin is not Union and origin is not UnionType: return False union_args = get_args(field_type) for arg in union_args: if not lenient_issubclass(arg, BaseModel): return False return True def _should_embed_body_fields(fields: list[ModelField]) -> bool: if not fields: return False # More than one dependency could have the same field, it would show up as multiple # fields but it's the same one, so count them by name body_param_names_set = {field.name for field in fields} # A top level field has to be a single field, not multiple if len(body_param_names_set) > 1: return True first_field = fields[0] # If it explicitly specifies it is embedded, it has to be embedded if getattr(first_field.field_info, "embed", None): return True # If it's a Form (or File) field, it has to be a BaseModel (or a union of BaseModels) to be top level # otherwise it has to be embedded, so that the key value pair can be extracted if ( isinstance(first_field.field_info, params.Form) and not lenient_issubclass(first_field.field_info.annotation, BaseModel) and not is_union_of_base_models(first_field.field_info.annotation) ): return True return False async def _extract_form_body( body_fields: list[ModelField], received_body: FormData, ) -> dict[str, Any]: values = {} for field in body_fields: value = _get_multidict_value(field, received_body) field_info = field.field_info if ( isinstance(field_info, params.File) and is_bytes_or_nonable_bytes_annotation(field.field_info.annotation) and isinstance(value, UploadFile) ): value = await value.read() elif ( is_bytes_sequence_annotation(field.field_info.annotation) and isinstance(field_info, params.File) and value_is_sequence(value) ): # For types assert isinstance(value, sequence_types) results: list[bytes | str] = [] for sub_value in value: results.append(await sub_value.read()) value = serialize_sequence_value(field=field, value=results) if value is not None: values[get_validation_alias(field)] = value field_aliases = {get_validation_alias(field) for field in body_fields} for key in received_body.keys(): if key not in field_aliases: param_values = received_body.getlist(key) if len(param_values) == 1: values[key] = param_values[0] else: values[key] = param_values return values async def request_body_to_args( body_fields: list[ModelField], received_body: dict[str, Any] | FormData | bytes | None, embed_body_fields: bool, ) -> tuple[dict[str, Any], list[dict[str, Any]]]: values: dict[str, Any] = {} errors: list[dict[str, Any]] = [] assert body_fields, "request_body_to_args() should be called with fields" single_not_embedded_field = len(body_fields) == 1 and not embed_body_fields first_field = body_fields[0] body_to_process = received_body fields_to_extract: list[ModelField] = body_fields if ( single_not_embedded_field and lenient_issubclass(first_field.field_info.annotation, BaseModel) and isinstance(received_body, FormData) ): fields_to_extract = get_cached_model_fields(first_field.field_info.annotation) if isinstance(received_body, FormData): body_to_process = await _extract_form_body(fields_to_extract, received_body) if single_not_embedded_field: loc: tuple[str, ...] = ("body",) v_, errors_ = _validate_value_with_model_field( field=first_field, value=body_to_process, values=values, loc=loc ) return {first_field.name: v_}, errors_ for field in body_fields: loc = ("body", get_validation_alias(field)) value: Any | None = None if body_to_process is not None and not isinstance(body_to_process, bytes): try: value = body_to_process.get(get_validation_alias(field)) # If the received body is a list, not a dict except AttributeError: errors.append(get_missing_field_error(loc)) continue v_, errors_ = _validate_value_with_model_field( field=field, value=value, values=values, loc=loc ) if errors_: errors.extend(errors_) else: values[field.name] = v_ return values, errors def get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> ModelField | None: if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] if not embed_body_fields: return first_param model_name = "Body_" + name BodyModel = create_body_model( fields=flat_dependant.body_params, model_name=model_name ) required = any( True for f in flat_dependant.body_params if f.field_info.is_required() ) BodyFieldInfo_kwargs: dict[str, Any] = { "annotation": BodyModel, "alias": "body", } if not required: BodyFieldInfo_kwargs["default"] = None if any(isinstance(f.field_info, params.File) for f in flat_dependant.body_params): BodyFieldInfo: type[params.Body] = params.File elif any(isinstance(f.field_info, params.Form) for f in flat_dependant.body_params): BodyFieldInfo = params.Form else: BodyFieldInfo = params.Body body_param_media_types = [ f.field_info.media_type for f in flat_dependant.body_params if isinstance(f.field_info, params.Body) ] if len(set(body_param_media_types)) == 1: BodyFieldInfo_kwargs["media_type"] = body_param_media_types[0] final_field = create_model_field( name="body", type_=BodyModel, alias="body", field_info=BodyFieldInfo(**BodyFieldInfo_kwargs), ) return final_field def get_validation_alias(field: ModelField) -> str: va = getattr(field, "validation_alias", None) return va or field.alias
--- +++ @@ -867,6 +867,7 @@ def is_union_of_base_models(field_type: Any) -> bool: + """Check if field type is a Union where all members are BaseModel subclasses.""" from fastapi.types import UnionType origin = get_origin(field_type) @@ -1000,6 +1001,16 @@ def get_body_field( *, flat_dependant: Dependant, name: str, embed_body_fields: bool ) -> ModelField | None: + """ + Get a ModelField representing the request body for a path operation, combining + all body parameters into a single field if necessary. + + Used to check if it's form data (with `isinstance(body_field, params.Form)`) + or JSON and to generate the JSON Schema for a request body. + + This is **not** used to validate/parse the request body, that's done with each + individual body parameter. + """ if not flat_dependant.body_params: return None first_param = flat_dependant.body_params[0] @@ -1043,4 +1054,4 @@ def get_validation_alias(field: ModelField) -> str: va = getattr(field, "validation_alias", None) - return va or field.alias+ return va or field.alias
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/dependencies/utils.py
Generate descriptive docstrings automatically
import dataclasses import datetime from collections import defaultdict, deque from collections.abc import Callable from decimal import Decimal from enum import Enum from ipaddress import ( IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network, ) from pathlib import Path, PurePath from re import Pattern from types import GeneratorType from typing import Annotated, Any from uuid import UUID from annotated_doc import Doc from fastapi.exceptions import PydanticV1NotSupportedError from fastapi.types import IncEx from pydantic import BaseModel from pydantic.color import Color # ty: ignore[deprecated] from pydantic.networks import AnyUrl, NameEmail from pydantic.types import SecretBytes, SecretStr from pydantic_core import PydanticUndefinedType from ._compat import ( Url, is_pydantic_v1_model_instance, ) # Taken from Pydantic v1 as is def isoformat(o: datetime.date | datetime.time) -> str: return o.isoformat() # Adapted from Pydantic v1 # TODO: pv2 should this return strings instead? def decimal_encoder(dec_value: Decimal) -> int | float: exponent = dec_value.as_tuple().exponent if isinstance(exponent, int) and exponent >= 0: return int(dec_value) else: return float(dec_value) ENCODERS_BY_TYPE: dict[type[Any], Callable[[Any], Any]] = { bytes: lambda o: o.decode(), Color: str, # ty: ignore[deprecated] datetime.date: isoformat, datetime.datetime: isoformat, datetime.time: isoformat, datetime.timedelta: lambda td: td.total_seconds(), Decimal: decimal_encoder, Enum: lambda o: o.value, frozenset: list, deque: list, GeneratorType: list, IPv4Address: str, IPv4Interface: str, IPv4Network: str, IPv6Address: str, IPv6Interface: str, IPv6Network: str, NameEmail: str, Path: str, Pattern: lambda o: o.pattern, SecretBytes: str, SecretStr: str, set: list, UUID: str, Url: str, AnyUrl: str, } def generate_encoders_by_class_tuples( type_encoder_map: dict[Any, Callable[[Any], Any]], ) -> dict[Callable[[Any], Any], tuple[Any, ...]]: encoders_by_class_tuples: dict[Callable[[Any], Any], tuple[Any, ...]] = defaultdict( tuple ) for type_, encoder in type_encoder_map.items(): encoders_by_class_tuples[encoder] += (type_,) return encoders_by_class_tuples encoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE) def jsonable_encoder( obj: Annotated[ Any, Doc( """ The input object to convert to JSON. """ ), ], include: Annotated[ IncEx | None, Doc( """ Pydantic's `include` parameter, passed to Pydantic models to set the fields to include. """ ), ] = None, exclude: Annotated[ IncEx | None, Doc( """ Pydantic's `exclude` parameter, passed to Pydantic models to set the fields to exclude. """ ), ] = None, by_alias: Annotated[ bool, Doc( """ Pydantic's `by_alias` parameter, passed to Pydantic models to define if the output should use the alias names (when provided) or the Python attribute names. In an API, if you set an alias, it's probably because you want to use it in the result, so you probably want to leave this set to `True`. """ ), ] = True, exclude_unset: Annotated[ bool, Doc( """ Pydantic's `exclude_unset` parameter, passed to Pydantic models to define if it should exclude from the output the fields that were not explicitly set (and that only had their default values). """ ), ] = False, exclude_defaults: Annotated[ bool, Doc( """ Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define if it should exclude from the output the fields that had the same default value, even when they were explicitly set. """ ), ] = False, exclude_none: Annotated[ bool, Doc( """ Pydantic's `exclude_none` parameter, passed to Pydantic models to define if it should exclude from the output any fields that have a `None` value. """ ), ] = False, custom_encoder: Annotated[ dict[Any, Callable[[Any], Any]] | None, Doc( """ Pydantic's `custom_encoder` parameter, passed to Pydantic models to define a custom encoder. """ ), ] = None, sqlalchemy_safe: Annotated[ bool, Doc( """ Exclude from the output any fields that start with the name `_sa`. This is mainly a hack for compatibility with SQLAlchemy objects, they store internal SQLAlchemy-specific state in attributes named with `_sa`, and those objects can't (and shouldn't be) serialized to JSON. """ ), ] = True, ) -> Any: custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: return custom_encoder[type(obj)](obj) else: for encoder_type, encoder_instance in custom_encoder.items(): if isinstance(obj, encoder_type): return encoder_instance(obj) if include is not None and not isinstance(include, (set, dict)): include = set(include) # type: ignore[assignment] # ty: ignore[unused-ignore-comment] if exclude is not None and not isinstance(exclude, (set, dict)): exclude = set(exclude) # type: ignore[assignment] # ty: ignore[unused-ignore-comment] if isinstance(obj, BaseModel): obj_dict = obj.model_dump( mode="json", include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_none=exclude_none, exclude_defaults=exclude_defaults, ) return jsonable_encoder( obj_dict, exclude_none=exclude_none, exclude_defaults=exclude_defaults, sqlalchemy_safe=sqlalchemy_safe, ) if dataclasses.is_dataclass(obj): assert not isinstance(obj, type) obj_dict = dataclasses.asdict(obj) return jsonable_encoder( obj_dict, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) if isinstance(obj, Enum): return obj.value if isinstance(obj, PurePath): return str(obj) if isinstance(obj, (str, int, float, type(None))): return obj if isinstance(obj, PydanticUndefinedType): return None if isinstance(obj, dict): encoded_dict = {} allowed_keys = set(obj.keys()) if include is not None: allowed_keys &= set(include) if exclude is not None: allowed_keys -= set(exclude) for key, value in obj.items(): if ( ( not sqlalchemy_safe or (not isinstance(key, str)) or (not key.startswith("_sa")) ) and (value is not None or not exclude_none) and key in allowed_keys ): encoded_key = jsonable_encoder( key, by_alias=by_alias, exclude_unset=exclude_unset, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) encoded_value = jsonable_encoder( value, by_alias=by_alias, exclude_unset=exclude_unset, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) encoded_dict[encoded_key] = encoded_value return encoded_dict if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)): encoded_list = [] for item in obj: encoded_list.append( jsonable_encoder( item, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, ) ) return encoded_list if type(obj) in ENCODERS_BY_TYPE: return ENCODERS_BY_TYPE[type(obj)](obj) for encoder, classes_tuple in encoders_by_class_tuples.items(): if isinstance(obj, classes_tuple): return encoder(obj) if is_pydantic_v1_model_instance(obj): raise PydanticV1NotSupportedError( "pydantic.v1 models are no longer supported by FastAPI." f" Please update the model {obj!r}." ) try: data = dict(obj) except Exception as e: errors: list[Exception] = [] errors.append(e) try: data = vars(obj) except Exception as e: errors.append(e) raise ValueError(errors) from e return jsonable_encoder( data, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, )
--- +++ @@ -41,6 +41,23 @@ # Adapted from Pydantic v1 # TODO: pv2 should this return strings instead? def decimal_encoder(dec_value: Decimal) -> int | float: + """ + Encodes a Decimal as int if there's no exponent, otherwise float + + This is useful when we use ConstrainedDecimal to represent Numeric(x,0) + where an integer (but not int typed) is used. Encoding this as a float + results in failed round-tripping between encode and parse. + Our Id type is a prime example of this. + + >>> decimal_encoder(Decimal("1.0")) + 1.0 + + >>> decimal_encoder(Decimal("1")) + 1 + + >>> decimal_encoder(Decimal("NaN")) + nan + """ exponent = dec_value.as_tuple().exponent if isinstance(exponent, int) and exponent >= 0: return int(dec_value) @@ -182,6 +199,18 @@ ), ] = True, ) -> Any: + """ + Convert any object to something that can be encoded in JSON. + + This is used internally by FastAPI to make sure anything you return can be + encoded as JSON before it is sent to the client. + + You can also use it yourself, for example to convert objects before saving them + in a database that supports only JSON. + + Read more about it in the + [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/). + """ custom_encoder = custom_encoder or {} if custom_encoder: if type(obj) in custom_encoder: @@ -315,4 +344,4 @@ exclude_none=exclude_none, custom_encoder=custom_encoder, sqlalchemy_safe=sqlalchemy_safe, - )+ )
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/encoders.py
Add well-formatted docstrings
import json from typing import Annotated, Any from annotated_doc import Doc from fastapi.encoders import jsonable_encoder from starlette.responses import HTMLResponse def _html_safe_json(value: Any) -> str: return ( json.dumps(value) .replace("<", "\\u003c") .replace(">", "\\u003e") .replace("&", "\\u0026") ) swagger_ui_default_parameters: Annotated[ dict[str, Any], Doc( """ Default configurations for Swagger UI. You can use it as a template to add any other configurations needed. """ ), ] = { "dom_id": "#swagger-ui", "layout": "BaseLayout", "deepLinking": True, "showExtensions": True, "showCommonExtensions": True, } def get_swagger_ui_html( *, openapi_url: Annotated[ str, Doc( """ The OpenAPI URL that Swagger UI should load and use. This is normally done automatically by FastAPI using the default URL `/openapi.json`. Read more about it in the [FastAPI docs for Conditional OpenAPI](https://fastapi.tiangolo.com/how-to/conditional-openapi/#conditional-openapi-from-settings-and-env-vars) """ ), ], title: Annotated[ str, Doc( """ The HTML `<title>` content, normally shown in the browser tab. Read more about it in the [FastAPI docs for Custom Docs UI Static Assets](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/) """ ), ], swagger_js_url: Annotated[ str, Doc( """ The URL to use to load the Swagger UI JavaScript. It is normally set to a CDN URL. Read more about it in the [FastAPI docs for Custom Docs UI Static Assets](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/) """ ), ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js", swagger_css_url: Annotated[ str, Doc( """ The URL to use to load the Swagger UI CSS. It is normally set to a CDN URL. Read more about it in the [FastAPI docs for Custom Docs UI Static Assets](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/) """ ), ] = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css", swagger_favicon_url: Annotated[ str, Doc( """ The URL of the favicon to use. It is normally shown in the browser tab. """ ), ] = "https://fastapi.tiangolo.com/img/favicon.png", oauth2_redirect_url: Annotated[ str | None, Doc( """ The OAuth2 redirect URL, it is normally automatically handled by FastAPI. Read more about it in the [FastAPI docs for Custom Docs UI Static Assets](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/) """ ), ] = None, init_oauth: Annotated[ dict[str, Any] | None, Doc( """ A dictionary with Swagger UI OAuth2 initialization configurations. Read more about the available configuration options in the [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/). """ ), ] = None, swagger_ui_parameters: Annotated[ dict[str, Any] | None, Doc( """ Configuration parameters for Swagger UI. It defaults to [swagger_ui_default_parameters][fastapi.openapi.docs.swagger_ui_default_parameters]. Read more about it in the [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/). """ ), ] = None, ) -> HTMLResponse: current_swagger_ui_parameters = swagger_ui_default_parameters.copy() if swagger_ui_parameters: current_swagger_ui_parameters.update(swagger_ui_parameters) html = f""" <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link type="text/css" rel="stylesheet" href="{swagger_css_url}"> <link rel="shortcut icon" href="{swagger_favicon_url}"> <title>{title}</title> </head> <body> <div id="swagger-ui"> </div> <script src="{swagger_js_url}"></script> <!-- `SwaggerUIBundle` is now available on the page --> <script> const ui = SwaggerUIBundle({{ url: '{openapi_url}', """ for key, value in current_swagger_ui_parameters.items(): html += f"{_html_safe_json(key)}: {_html_safe_json(jsonable_encoder(value))},\n" if oauth2_redirect_url: html += f"oauth2RedirectUrl: window.location.origin + '{oauth2_redirect_url}'," html += """ presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], })""" if init_oauth: html += f""" ui.initOAuth({_html_safe_json(jsonable_encoder(init_oauth))}) """ html += """ </script> </body> </html> """ return HTMLResponse(html) def get_redoc_html( *, openapi_url: Annotated[ str, Doc( """ The OpenAPI URL that ReDoc should load and use. This is normally done automatically by FastAPI using the default URL `/openapi.json`. Read more about it in the [FastAPI docs for Conditional OpenAPI](https://fastapi.tiangolo.com/how-to/conditional-openapi/#conditional-openapi-from-settings-and-env-vars) """ ), ], title: Annotated[ str, Doc( """ The HTML `<title>` content, normally shown in the browser tab. Read more about it in the [FastAPI docs for Custom Docs UI Static Assets](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/) """ ), ], redoc_js_url: Annotated[ str, Doc( """ The URL to use to load the ReDoc JavaScript. It is normally set to a CDN URL. Read more about it in the [FastAPI docs for Custom Docs UI Static Assets](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/) """ ), ] = "https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js", redoc_favicon_url: Annotated[ str, Doc( """ The URL of the favicon to use. It is normally shown in the browser tab. """ ), ] = "https://fastapi.tiangolo.com/img/favicon.png", with_google_fonts: Annotated[ bool, Doc( """ Load and use Google Fonts. """ ), ] = True, ) -> HTMLResponse: html = f""" <!DOCTYPE html> <html> <head> <title>{title}</title> <!-- needed for adaptive design --> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"> """ if with_google_fonts: html += """ <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet"> """ html += f""" <link rel="shortcut icon" href="{redoc_favicon_url}"> <!-- ReDoc doesn't change outer page styles --> <style> body {{ margin: 0; padding: 0; }} </style> </head> <body> <noscript> ReDoc requires Javascript to function. Please enable it to browse the documentation. </noscript> <redoc spec-url="{openapi_url}"></redoc> <script src="{redoc_js_url}"> </script> </body> </html> """ return HTMLResponse(html) def get_swagger_ui_oauth2_redirect_html() -> HTMLResponse: # copied from https://github.com/swagger-api/swagger-ui/blob/v4.14.0/dist/oauth2-redirect.html html = """ <!doctype html> <html lang="en-US"> <head> <title>Swagger UI: OAuth2 Redirect</title> </head> <body> <script> 'use strict'; function run () { var oauth2 = window.opener.swaggerUIRedirectOauth2; var sentState = oauth2.state; var redirectUrl = oauth2.redirectUrl; var isValid, qp, arr; if (/code|token|error/.test(window.location.hash)) { qp = window.location.hash.substring(1).replace('?', '&'); } else { qp = location.search.substring(1); } arr = qp.split("&"); arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';}); qp = qp ? JSON.parse('{' + arr.join() + '}', function (key, value) { return key === "" ? value : decodeURIComponent(value); } ) : {}; isValid = qp.state === sentState; if (( oauth2.auth.schema.get("flow") === "accessCode" || oauth2.auth.schema.get("flow") === "authorizationCode" || oauth2.auth.schema.get("flow") === "authorization_code" ) && !oauth2.auth.code) { if (!isValid) { oauth2.errCb({ authId: oauth2.auth.name, source: "auth", level: "warning", message: "Authorization may be unsafe, passed state was changed in server. The passed state wasn't returned from auth server." }); } if (qp.code) { delete oauth2.state; oauth2.auth.code = qp.code; oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl}); } else { let oauthErrorMsg; if (qp.error) { oauthErrorMsg = "["+qp.error+"]: " + (qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") + (qp.error_uri ? "More info: "+qp.error_uri : ""); } oauth2.errCb({ authId: oauth2.auth.name, source: "auth", level: "error", message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server." }); } } else { oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl}); } window.close(); } if (document.readyState !== 'loading') { run(); } else { document.addEventListener('DOMContentLoaded', function () { run(); }); } </script> </body> </html> """ return HTMLResponse(content=html)
--- +++ @@ -7,6 +7,10 @@ def _html_safe_json(value: Any) -> str: + """Serialize a value to JSON with HTML special characters escaped. + + This prevents injection when the JSON is embedded inside a <script> tag. + """ return ( json.dumps(value) .replace("<", "\\u003c") @@ -130,6 +134,17 @@ ), ] = None, ) -> HTMLResponse: + """ + Generate and return the HTML that loads Swagger UI for the interactive + API docs (normally served at `/docs`). + + You would only call this function yourself if you needed to override some parts, + for example the URLs to use to load Swagger UI's JavaScript and CSS. + + Read more about it in the + [FastAPI docs for Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/) + and the [FastAPI docs for Custom Docs UI Static Assets (Self-Hosting)](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/). + """ current_swagger_ui_parameters = swagger_ui_default_parameters.copy() if swagger_ui_parameters: current_swagger_ui_parameters.update(swagger_ui_parameters) @@ -236,6 +251,16 @@ ), ] = True, ) -> HTMLResponse: + """ + Generate and return the HTML response that loads ReDoc for the alternative + API docs (normally served at `/redoc`). + + You would only call this function yourself if you needed to override some parts, + for example the URLs to use to load ReDoc's JavaScript and CSS. + + Read more about it in the + [FastAPI docs for Custom Docs UI Static Assets (Self-Hosting)](https://fastapi.tiangolo.com/how-to/custom-docs-ui-assets/). + """ html = f""" <!DOCTYPE html> <html> @@ -274,6 +299,11 @@ def get_swagger_ui_oauth2_redirect_html() -> HTMLResponse: + """ + Generate the HTML response with the OAuth2 redirection for Swagger UI. + + You normally don't need to use or change this. + """ # copied from https://github.com/swagger-api/swagger-ui/blob/v4.14.0/dist/oauth2-redirect.html html = """ <!doctype html> @@ -356,4 +386,4 @@ </body> </html> """ - return HTMLResponse(content=html)+ return HTMLResponse(content=html)
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/openapi/docs.py
Generate docstrings for each module
from collections.abc import Callable, Sequence from typing import Annotated, Any, Literal from annotated_doc import Doc from fastapi import params from fastapi._compat import Undefined from fastapi.datastructures import _Unset from fastapi.openapi.models import Example from pydantic import AliasChoices, AliasPath from typing_extensions import deprecated def Path( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = ..., *, default_factory: Annotated[ Callable[[], Any] | None, Doc( """ A callable to generate the default value. This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, alias: Annotated[ str | None, Doc( """ An alternative name for the parameter field. This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ int | None, Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, validation_alias: Annotated[ str | AliasPath | AliasChoices | None, Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ str | None, Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, title: Annotated[ str | None, Doc( """ Human-readable title. Read more about it in the [FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#declare-metadata) """ ), ] = None, description: Annotated[ str | None, Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ float | None, Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. Read more about it in the [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) """ ), ] = None, ge: Annotated[ float | None, Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. Read more about it in the [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) """ ), ] = None, lt: Annotated[ float | None, Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. Read more about it in the [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) """ ), ] = None, le: Annotated[ float | None, Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. Read more about it in the [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) """ ), ] = None, min_length: Annotated[ int | None, Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ int | None, Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ str | None, Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ str | None, Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ str | None, Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ bool | None, Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ float | None, Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ bool | None, Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ int | None, Doc( """ Maximum number of digits allowed for decimal values. """ ), ] = _Unset, decimal_places: Annotated[ int | None, Doc( """ Maximum number of decimal places allowed for decimal values. """ ), ] = _Unset, examples: Annotated[ list[Any] | None, Doc( """ Example values for this field. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) """ ), ] = None, example: Annotated[ Any | None, deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Annotated[ dict[str, Example] | None, Doc( """ OpenAPI-specific examples. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ deprecated | str | bool | None, Doc( """ Mark this parameter field as deprecated. It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ dict[str, Any] | None, Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ], ) -> Any: return params.Path( default=default, default_factory=default_factory, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) def Query( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. Read more about it in the [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#alternative-old-query-as-the-default-value) """ ), ] = Undefined, *, default_factory: Annotated[ Callable[[], Any] | None, Doc( """ A callable to generate the default value. This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, alias: Annotated[ str | None, Doc( """ An alternative name for the parameter field. This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. Read more about it in the [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#alias-parameters) """ ), ] = None, alias_priority: Annotated[ int | None, Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, validation_alias: Annotated[ str | AliasPath | AliasChoices | None, Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ str | None, Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, title: Annotated[ str | None, Doc( """ Human-readable title. Read more about it in the [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#declare-more-metadata) """ ), ] = None, description: Annotated[ str | None, Doc( """ Human-readable description. Read more about it in the [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#declare-more-metadata) """ ), ] = None, gt: Annotated[ float | None, Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. Read more about it in the [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) """ ), ] = None, ge: Annotated[ float | None, Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. Read more about it in the [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) """ ), ] = None, lt: Annotated[ float | None, Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. Read more about it in the [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) """ ), ] = None, le: Annotated[ float | None, Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. Read more about it in the [FastAPI docs about Path parameters numeric validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#number-validations-greater-than-and-less-than-or-equal) """ ), ] = None, min_length: Annotated[ int | None, Doc( """ Minimum length for strings. Read more about it in the [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/) """ ), ] = None, max_length: Annotated[ int | None, Doc( """ Maximum length for strings. Read more about it in the [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/) """ ), ] = None, pattern: Annotated[ str | None, Doc( """ RegEx pattern for strings. Read more about it in the [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#add-regular-expressions """ ), ] = None, regex: Annotated[ str | None, Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ str | None, Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ bool | None, Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ float | None, Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ bool | None, Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ int | None, Doc( """ Maximum number of digits allowed for decimal values. """ ), ] = _Unset, decimal_places: Annotated[ int | None, Doc( """ Maximum number of decimal places allowed for decimal values. """ ), ] = _Unset, examples: Annotated[ list[Any] | None, Doc( """ Example values for this field. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) """ ), ] = None, example: Annotated[ Any | None, deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Annotated[ dict[str, Example] | None, Doc( """ OpenAPI-specific examples. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ deprecated | str | bool | None, Doc( """ Mark this parameter field as deprecated. It will affect the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#deprecating-parameters) """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs about Query parameters](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi """ ), ] = True, json_schema_extra: Annotated[ dict[str, Any] | None, Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ], ) -> Any: return params.Query( default=default, default_factory=default_factory, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) def Header( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. """ ), ] = Undefined, *, default_factory: Annotated[ Callable[[], Any] | None, Doc( """ A callable to generate the default value. This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, alias: Annotated[ str | None, Doc( """ An alternative name for the parameter field. This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ int | None, Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, validation_alias: Annotated[ str | AliasPath | AliasChoices | None, Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ str | None, Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, convert_underscores: Annotated[ bool, Doc( """ Automatically convert underscores to hyphens in the parameter field name. Read more about it in the [FastAPI docs for Header Parameters](https://fastapi.tiangolo.com/tutorial/header-params/#automatic-conversion) """ ), ] = True, title: Annotated[ str | None, Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ str | None, Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ float | None, Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ float | None, Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ float | None, Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ float | None, Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ int | None, Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ int | None, Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ str | None, Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ str | None, Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ str | None, Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ bool | None, Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ float | None, Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ bool | None, Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ int | None, Doc( """ Maximum number of digits allowed for decimal values. """ ), ] = _Unset, decimal_places: Annotated[ int | None, Doc( """ Maximum number of decimal places allowed for decimal values. """ ), ] = _Unset, examples: Annotated[ list[Any] | None, Doc( """ Example values for this field. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) """ ), ] = None, example: Annotated[ Any | None, deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Annotated[ dict[str, Example] | None, Doc( """ OpenAPI-specific examples. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ deprecated | str | bool | None, Doc( """ Mark this parameter field as deprecated. It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ dict[str, Any] | None, Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ], ) -> Any: return params.Header( default=default, default_factory=default_factory, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, convert_underscores=convert_underscores, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) def Cookie( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. """ ), ] = Undefined, *, default_factory: Annotated[ Callable[[], Any] | None, Doc( """ A callable to generate the default value. This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, alias: Annotated[ str | None, Doc( """ An alternative name for the parameter field. This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ int | None, Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, validation_alias: Annotated[ str | AliasPath | AliasChoices | None, Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ str | None, Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, title: Annotated[ str | None, Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ str | None, Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ float | None, Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ float | None, Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ float | None, Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ float | None, Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ int | None, Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ int | None, Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ str | None, Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ str | None, Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ str | None, Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ bool | None, Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ float | None, Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ bool | None, Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ int | None, Doc( """ Maximum number of digits allowed for decimal values. """ ), ] = _Unset, decimal_places: Annotated[ int | None, Doc( """ Maximum number of decimal places allowed for decimal values. """ ), ] = _Unset, examples: Annotated[ list[Any] | None, Doc( """ Example values for this field. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) """ ), ] = None, example: Annotated[ Any | None, deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Annotated[ dict[str, Example] | None, Doc( """ OpenAPI-specific examples. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ deprecated | str | bool | None, Doc( """ Mark this parameter field as deprecated. It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ dict[str, Any] | None, Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ], ) -> Any: return params.Cookie( default=default, default_factory=default_factory, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) def Body( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. """ ), ] = Undefined, *, default_factory: Annotated[ Callable[[], Any] | None, Doc( """ A callable to generate the default value. This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, embed: Annotated[ bool | None, Doc( """ When `embed` is `True`, the parameter will be expected in a JSON body as a key instead of being the JSON body itself. This happens automatically when more than one `Body` parameter is declared. Read more about it in the [FastAPI docs for Body - Multiple Parameters](https://fastapi.tiangolo.com/tutorial/body-multiple-params/#embed-a-single-body-parameter). """ ), ] = None, media_type: Annotated[ str, Doc( """ The media type of this parameter field. Changing it would affect the generated OpenAPI, but currently it doesn't affect the parsing of the data. """ ), ] = "application/json", alias: Annotated[ str | None, Doc( """ An alternative name for the parameter field. This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ int | None, Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, validation_alias: Annotated[ str | AliasPath | AliasChoices | None, Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ str | None, Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, title: Annotated[ str | None, Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ str | None, Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ float | None, Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ float | None, Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ float | None, Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ float | None, Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ int | None, Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ int | None, Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ str | None, Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ str | None, Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ str | None, Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ bool | None, Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ float | None, Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ bool | None, Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ int | None, Doc( """ Maximum number of digits allowed for decimal values. """ ), ] = _Unset, decimal_places: Annotated[ int | None, Doc( """ Maximum number of decimal places allowed for decimal values. """ ), ] = _Unset, examples: Annotated[ list[Any] | None, Doc( """ Example values for this field. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) """ ), ] = None, example: Annotated[ Any | None, deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Annotated[ dict[str, Example] | None, Doc( """ OpenAPI-specific examples. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ deprecated | str | bool | None, Doc( """ Mark this parameter field as deprecated. It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ dict[str, Any] | None, Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ], ) -> Any: return params.Body( default=default, default_factory=default_factory, embed=embed, media_type=media_type, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) def Form( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. """ ), ] = Undefined, *, default_factory: Annotated[ Callable[[], Any] | None, Doc( """ A callable to generate the default value. This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, media_type: Annotated[ str, Doc( """ The media type of this parameter field. Changing it would affect the generated OpenAPI, but currently it doesn't affect the parsing of the data. """ ), ] = "application/x-www-form-urlencoded", alias: Annotated[ str | None, Doc( """ An alternative name for the parameter field. This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ int | None, Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, validation_alias: Annotated[ str | AliasPath | AliasChoices | None, Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ str | None, Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, title: Annotated[ str | None, Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ str | None, Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ float | None, Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ float | None, Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ float | None, Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ float | None, Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ int | None, Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ int | None, Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ str | None, Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ str | None, Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ str | None, Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ bool | None, Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ float | None, Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ bool | None, Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ int | None, Doc( """ Maximum number of digits allowed for decimal values. """ ), ] = _Unset, decimal_places: Annotated[ int | None, Doc( """ Maximum number of decimal places allowed for decimal values. """ ), ] = _Unset, examples: Annotated[ list[Any] | None, Doc( """ Example values for this field. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) """ ), ] = None, example: Annotated[ Any | None, deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Annotated[ dict[str, Example] | None, Doc( """ OpenAPI-specific examples. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ deprecated | str | bool | None, Doc( """ Mark this parameter field as deprecated. It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ dict[str, Any] | None, Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ], ) -> Any: return params.Form( default=default, default_factory=default_factory, media_type=media_type, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) def File( # noqa: N802 default: Annotated[ Any, Doc( """ Default value if the parameter field is not set. """ ), ] = Undefined, *, default_factory: Annotated[ Callable[[], Any] | None, Doc( """ A callable to generate the default value. This doesn't affect `Path` parameters as the value is always required. The parameter is available only for compatibility. """ ), ] = _Unset, media_type: Annotated[ str, Doc( """ The media type of this parameter field. Changing it would affect the generated OpenAPI, but currently it doesn't affect the parsing of the data. """ ), ] = "multipart/form-data", alias: Annotated[ str | None, Doc( """ An alternative name for the parameter field. This will be used to extract the data and for the generated OpenAPI. It is particularly useful when you can't use the name you want because it is a Python reserved keyword or similar. """ ), ] = None, alias_priority: Annotated[ int | None, Doc( """ Priority of the alias. This affects whether an alias generator is used. """ ), ] = _Unset, validation_alias: Annotated[ str | AliasPath | AliasChoices | None, Doc( """ 'Whitelist' validation step. The parameter field will be the single one allowed by the alias or set of aliases defined. """ ), ] = None, serialization_alias: Annotated[ str | None, Doc( """ 'Blacklist' validation step. The vanilla parameter field will be the single one of the alias' or set of aliases' fields and all the other fields will be ignored at serialization time. """ ), ] = None, title: Annotated[ str | None, Doc( """ Human-readable title. """ ), ] = None, description: Annotated[ str | None, Doc( """ Human-readable description. """ ), ] = None, gt: Annotated[ float | None, Doc( """ Greater than. If set, value must be greater than this. Only applicable to numbers. """ ), ] = None, ge: Annotated[ float | None, Doc( """ Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. """ ), ] = None, lt: Annotated[ float | None, Doc( """ Less than. If set, value must be less than this. Only applicable to numbers. """ ), ] = None, le: Annotated[ float | None, Doc( """ Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. """ ), ] = None, min_length: Annotated[ int | None, Doc( """ Minimum length for strings. """ ), ] = None, max_length: Annotated[ int | None, Doc( """ Maximum length for strings. """ ), ] = None, pattern: Annotated[ str | None, Doc( """ RegEx pattern for strings. """ ), ] = None, regex: Annotated[ str | None, Doc( """ RegEx pattern for strings. """ ), deprecated( "Deprecated in FastAPI 0.100.0 and Pydantic v2, use `pattern` instead." ), ] = None, discriminator: Annotated[ str | None, Doc( """ Parameter field name for discriminating the type in a tagged union. """ ), ] = None, strict: Annotated[ bool | None, Doc( """ If `True`, strict validation is applied to the field. """ ), ] = _Unset, multiple_of: Annotated[ float | None, Doc( """ Value must be a multiple of this. Only applicable to numbers. """ ), ] = _Unset, allow_inf_nan: Annotated[ bool | None, Doc( """ Allow `inf`, `-inf`, `nan`. Only applicable to numbers. """ ), ] = _Unset, max_digits: Annotated[ int | None, Doc( """ Maximum number of digits allowed for decimal values. """ ), ] = _Unset, decimal_places: Annotated[ int | None, Doc( """ Maximum number of decimal places allowed for decimal values. """ ), ] = _Unset, examples: Annotated[ list[Any] | None, Doc( """ Example values for this field. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/) """ ), ] = None, example: Annotated[ Any | None, deprecated( "Deprecated in OpenAPI 3.1.0 that now uses JSON Schema 2020-12, " "although still supported. Use examples instead." ), ] = _Unset, openapi_examples: Annotated[ dict[str, Example] | None, Doc( """ OpenAPI-specific examples. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Swagger UI (that provides the `/docs` interface) has better support for the OpenAPI-specific examples than the JSON Schema `examples`, that's the main use case for this. Read more about it in the [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter). """ ), ] = None, deprecated: Annotated[ deprecated | str | bool | None, Doc( """ Mark this parameter field as deprecated. It will affect the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) this parameter field in the generated OpenAPI. You probably don't need it, but it's available. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, json_schema_extra: Annotated[ dict[str, Any] | None, Doc( """ Any additional JSON schema data. """ ), ] = None, **extra: Annotated[ Any, Doc( """ Include extra fields used by the JSON Schema. """ ), deprecated( """ The `extra` kwargs is deprecated. Use `json_schema_extra` instead. """ ), ], ) -> Any: return params.File( default=default, default_factory=default_factory, media_type=media_type, alias=alias, alias_priority=alias_priority, validation_alias=validation_alias, serialization_alias=serialization_alias, title=title, description=description, gt=gt, ge=ge, lt=lt, le=le, min_length=min_length, max_length=max_length, pattern=pattern, regex=regex, discriminator=discriminator, strict=strict, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan, max_digits=max_digits, decimal_places=decimal_places, example=example, examples=examples, openapi_examples=openapi_examples, deprecated=deprecated, include_in_schema=include_in_schema, json_schema_extra=json_schema_extra, **extra, ) def Depends( # noqa: N802 dependency: Annotated[ Callable[..., Any] | None, Doc( """ A "dependable" callable (like a function). Don't call it directly, FastAPI will call it for you, just pass the object directly. Read more about it in the [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/) """ ), ] = None, *, use_cache: Annotated[ bool, Doc( """ By default, after a dependency is called the first time in a request, if the dependency is declared again for the rest of the request (for example if the dependency is needed by several dependencies), the value will be re-used for the rest of the request. Set `use_cache` to `False` to disable this behavior and ensure the dependency is called again (if declared more than once) in the same request. Read more about it in the [FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times) """ ), ] = True, scope: Annotated[ Literal["function", "request"] | None, Doc( """ Mainly for dependencies with `yield`, define when the dependency function should start (the code before `yield`) and when it should end (the code after `yield`). * `"function"`: start the dependency before the *path operation function* that handles the request, end the dependency after the *path operation function* ends, but **before** the response is sent back to the client. So, the dependency function will be executed **around** the *path operation **function***. * `"request"`: start the dependency before the *path operation function* that handles the request (similar to when using `"function"`), but end **after** the response is sent back to the client. So, the dependency function will be executed **around** the **request** and response cycle. Read more about it in the [FastAPI docs for FastAPI Dependencies with yield](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#early-exit-and-scope) """ ), ] = None, ) -> Any: return params.Depends(dependency=dependency, use_cache=use_cache, scope=scope) def Security( # noqa: N802 dependency: Annotated[ Callable[..., Any] | None, Doc( """ A "dependable" callable (like a function). Don't call it directly, FastAPI will call it for you, just pass the object directly. Read more about it in the [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/) """ ), ] = None, *, scopes: Annotated[ Sequence[str] | None, Doc( """ OAuth2 scopes required for the *path operation* that uses this Security dependency. The term "scope" comes from the OAuth2 specification, it seems to be intentionally vague and interpretable. It normally refers to permissions, in cases to roles. These scopes are integrated with OpenAPI (and the API docs at `/docs`). So they are visible in the OpenAPI specification. Read more about it in the [FastAPI docs about OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/) """ ), ] = None, use_cache: Annotated[ bool, Doc( """ By default, after a dependency is called the first time in a request, if the dependency is declared again for the rest of the request (for example if the dependency is needed by several dependencies), the value will be re-used for the rest of the request. Set `use_cache` to `False` to disable this behavior and ensure the dependency is called again (if declared more than once) in the same request. Read more about it in the [FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times) """ ), ] = True, ) -> Any: return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache)
--- +++ @@ -300,6 +300,27 @@ ), ], ) -> Any: + """ + Declare a path parameter for a *path operation*. + + Read more about it in the + [FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/). + + ```python + from typing import Annotated + + from fastapi import FastAPI, Path + + app = FastAPI() + + + @app.get("/items/{item_id}") + async def read_items( + item_id: Annotated[int, Path(title="The ID of the item to get")], + ): + return {"item_id": item_id} + ``` + """ return params.Path( default=default, default_factory=default_factory, @@ -2316,6 +2337,35 @@ ), ] = None, ) -> Any: + """ + Declare a FastAPI dependency. + + It takes a single "dependable" callable (like a function). + + Don't call it directly, FastAPI will call it for you. + + Read more about it in the + [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/). + + **Example** + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + + app = FastAPI() + + + async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100): + return {"q": q, "skip": skip, "limit": limit} + + + @app.get("/items/") + async def read_items(commons: Annotated[dict, Depends(common_parameters)]): + return commons + ``` + """ return params.Depends(dependency=dependency, use_cache=use_cache, scope=scope) @@ -2372,4 +2422,39 @@ ), ] = True, ) -> Any: - return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache)+ """ + Declare a FastAPI Security dependency. + + The only difference with a regular dependency is that it can declare OAuth2 + scopes that will be integrated with OpenAPI and the automatic UI docs (by default + at `/docs`). + + It takes a single "dependable" callable (like a function). + + Don't call it directly, FastAPI will call it for you. + + Read more about it in the + [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/) and + in the + [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/). + + **Example** + + ```python + from typing import Annotated + + from fastapi import Security, FastAPI + + from .db import User + from .security import get_current_active_user + + app = FastAPI() + + @app.get("/users/me/items/") + async def read_own_items( + current_user: Annotated[User, Security(get_current_active_user, scopes=["items"])] + ): + return [{"item_id": "Foo", "owner": current_user.username}] + ``` + """ + return params.Security(dependency=dependency, scopes=scopes, use_cache=use_cache)
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/param_functions.py
Generate descriptive docstrings automatically
from typing import Any from fastapi.exceptions import FastAPIDeprecationWarning from fastapi.sse import EventSourceResponse as EventSourceResponse # noqa from starlette.responses import FileResponse as FileResponse # noqa from starlette.responses import HTMLResponse as HTMLResponse # noqa from starlette.responses import JSONResponse as JSONResponse # noqa from starlette.responses import PlainTextResponse as PlainTextResponse # noqa from starlette.responses import RedirectResponse as RedirectResponse # noqa from starlette.responses import Response as Response # noqa from starlette.responses import StreamingResponse as StreamingResponse # noqa from typing_extensions import deprecated try: import ujson except ImportError: # pragma: nocover ujson = None # type: ignore try: import orjson except ImportError: # pragma: nocover orjson = None # type: ignore @deprecated( "UJSONResponse is deprecated, FastAPI now serializes data directly to JSON " "bytes via Pydantic when a return type or response model is set, which is " "faster and doesn't need a custom response class. Read more in the FastAPI " "docs: https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model " "and https://fastapi.tiangolo.com/tutorial/response-model/", category=FastAPIDeprecationWarning, stacklevel=2, ) class UJSONResponse(JSONResponse): def render(self, content: Any) -> bytes: assert ujson is not None, "ujson must be installed to use UJSONResponse" return ujson.dumps(content, ensure_ascii=False).encode("utf-8") @deprecated( "ORJSONResponse is deprecated, FastAPI now serializes data directly to JSON " "bytes via Pydantic when a return type or response model is set, which is " "faster and doesn't need a custom response class. Read more in the FastAPI " "docs: https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model " "and https://fastapi.tiangolo.com/tutorial/response-model/", category=FastAPIDeprecationWarning, stacklevel=2, ) class ORJSONResponse(JSONResponse): def render(self, content: Any) -> bytes: assert orjson is not None, "orjson must be installed to use ORJSONResponse" return orjson.dumps( content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY )
--- +++ @@ -33,6 +33,20 @@ stacklevel=2, ) class UJSONResponse(JSONResponse): + """JSON response using the ujson library to serialize data to JSON. + + **Deprecated**: `UJSONResponse` is deprecated. FastAPI now serializes data + directly to JSON bytes via Pydantic when a return type or response model is + set, which is faster and doesn't need a custom response class. + + Read more in the + [FastAPI docs for Custom Response](https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model) + and the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + + **Note**: `ujson` is not included with FastAPI and must be installed + separately, e.g. `pip install ujson`. + """ def render(self, content: Any) -> bytes: assert ujson is not None, "ujson must be installed to use UJSONResponse" @@ -49,9 +63,23 @@ stacklevel=2, ) class ORJSONResponse(JSONResponse): + """JSON response using the orjson library to serialize data to JSON. + + **Deprecated**: `ORJSONResponse` is deprecated. FastAPI now serializes data + directly to JSON bytes via Pydantic when a return type or response model is + set, which is faster and doesn't need a custom response class. + + Read more in the + [FastAPI docs for Custom Response](https://fastapi.tiangolo.com/advanced/custom-response/#orjson-or-response-model) + and the + [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). + + **Note**: `orjson` is not included with FastAPI and must be installed + separately, e.g. `pip install orjson`. + """ def render(self, content: Any) -> bytes: assert orjson is not None, "orjson must be installed to use ORJSONResponse" return orjson.dumps( content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY - )+ )
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/responses.py
Generate consistent docstrings
import contextlib import email.message import functools import inspect import json import types from collections.abc import ( AsyncIterator, Awaitable, Callable, Collection, Coroutine, Generator, Iterator, Mapping, Sequence, ) from contextlib import ( AbstractAsyncContextManager, AbstractContextManager, AsyncExitStack, asynccontextmanager, ) from enum import Enum, IntEnum from typing import ( Annotated, Any, TypeVar, cast, ) import anyio from annotated_doc import Doc from anyio.abc import ObjectReceiveStream from fastapi import params from fastapi._compat import ( ModelField, Undefined, lenient_issubclass, ) from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.dependencies.models import Dependant from fastapi.dependencies.utils import ( _should_embed_body_fields, get_body_field, get_dependant, get_flat_dependant, get_parameterless_sub_dependant, get_stream_item_type, get_typed_return_annotation, solve_dependencies, ) from fastapi.encoders import jsonable_encoder from fastapi.exceptions import ( EndpointContext, FastAPIError, RequestValidationError, ResponseValidationError, WebSocketRequestValidationError, ) from fastapi.sse import ( _PING_INTERVAL, KEEPALIVE_COMMENT, EventSourceResponse, ServerSentEvent, format_sse_event, ) from fastapi.types import DecoratedCallable, IncEx from fastapi.utils import ( create_model_field, generate_unique_id, get_value_or_default, is_body_allowed_for_status_code, ) from starlette import routing from starlette._exception_handler import wrap_app_handling_exceptions from starlette._utils import is_async_callable from starlette.concurrency import iterate_in_threadpool, run_in_threadpool from starlette.datastructures import FormData from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.responses import JSONResponse, Response, StreamingResponse from starlette.routing import ( BaseRoute, Match, compile_path, get_name, ) from starlette.routing import Mount as Mount # noqa from starlette.types import AppType, ASGIApp, Lifespan, Receive, Scope, Send from starlette.websockets import WebSocket from typing_extensions import deprecated # Copy of starlette.routing.request_response modified to include the # dependencies' AsyncExitStack def request_response( func: Callable[[Request], Awaitable[Response] | Response], ) -> ASGIApp: f: Callable[[Request], Awaitable[Response]] = ( func # type: ignore[assignment] # ty: ignore[unused-ignore-comment] if is_async_callable(func) else functools.partial(run_in_threadpool, func) # type: ignore[call-arg] # ty: ignore[unused-ignore-comment] ) # ty: ignore[invalid-assignment] async def app(scope: Scope, receive: Receive, send: Send) -> None: request = Request(scope, receive, send) async def app(scope: Scope, receive: Receive, send: Send) -> None: # Starts customization response_awaited = False async with AsyncExitStack() as request_stack: scope["fastapi_inner_astack"] = request_stack async with AsyncExitStack() as function_stack: scope["fastapi_function_astack"] = function_stack response = await f(request) await response(scope, receive, send) # Continues customization response_awaited = True if not response_awaited: raise FastAPIError( "Response not awaited. There's a high chance that the " "application code is raising an exception and a dependency with yield " "has a block with a bare except, or a block with except Exception, " "and is not raising the exception again. Read more about it in the " "docs: https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-except" ) # Same as in Starlette await wrap_app_handling_exceptions(app, request)(scope, receive, send) return app # Copy of starlette.routing.websocket_session modified to include the # dependencies' AsyncExitStack def websocket_session( func: Callable[[WebSocket], Awaitable[None]], ) -> ASGIApp: # assert asyncio.iscoroutinefunction(func), "WebSocket endpoints must be async" async def app(scope: Scope, receive: Receive, send: Send) -> None: session = WebSocket(scope, receive=receive, send=send) async def app(scope: Scope, receive: Receive, send: Send) -> None: async with AsyncExitStack() as request_stack: scope["fastapi_inner_astack"] = request_stack async with AsyncExitStack() as function_stack: scope["fastapi_function_astack"] = function_stack await func(session) # Same as in Starlette await wrap_app_handling_exceptions(app, session)(scope, receive, send) return app _T = TypeVar("_T") # Vendored from starlette.routing to avoid importing private symbols class _AsyncLiftContextManager(AbstractAsyncContextManager[_T]): def __init__(self, cm: AbstractContextManager[_T]) -> None: self._cm = cm async def __aenter__(self) -> _T: return self._cm.__enter__() async def __aexit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: types.TracebackType | None, ) -> bool | None: return self._cm.__exit__(exc_type, exc_value, traceback) # Vendored from starlette.routing to avoid importing private symbols def _wrap_gen_lifespan_context( lifespan_context: Callable[[Any], Generator[Any, Any, Any]], ) -> Callable[[Any], AbstractAsyncContextManager[Any]]: cmgr = contextlib.contextmanager(lifespan_context) @functools.wraps(cmgr) def wrapper(app: Any) -> _AsyncLiftContextManager[Any]: return _AsyncLiftContextManager(cmgr(app)) return wrapper def _merge_lifespan_context( original_context: Lifespan[Any], nested_context: Lifespan[Any] ) -> Lifespan[Any]: @asynccontextmanager async def merged_lifespan( app: AppType, ) -> AsyncIterator[Mapping[str, Any] | None]: async with original_context(app) as maybe_original_state: async with nested_context(app) as maybe_nested_state: if maybe_nested_state is None and maybe_original_state is None: yield None # old ASGI compatibility else: yield {**(maybe_nested_state or {}), **(maybe_original_state or {})} return merged_lifespan # type: ignore[return-value] class _DefaultLifespan: def __init__(self, router: "APIRouter") -> None: self._router = router async def __aenter__(self) -> None: await self._router._startup() async def __aexit__(self, *exc_info: object) -> None: await self._router._shutdown() def __call__(self: _T, app: object) -> _T: return self # Cache for endpoint context to avoid re-extracting on every request _endpoint_context_cache: dict[int, EndpointContext] = {} def _extract_endpoint_context(func: Any) -> EndpointContext: func_id = id(func) if func_id in _endpoint_context_cache: return _endpoint_context_cache[func_id] try: ctx: EndpointContext = {} if (source_file := inspect.getsourcefile(func)) is not None: ctx["file"] = source_file if (line_number := inspect.getsourcelines(func)[1]) is not None: ctx["line"] = line_number if (func_name := getattr(func, "__name__", None)) is not None: ctx["function"] = func_name except Exception: ctx = EndpointContext() _endpoint_context_cache[func_id] = ctx return ctx async def serialize_response( *, field: ModelField | None = None, response_content: Any, include: IncEx | None = None, exclude: IncEx | None = None, by_alias: bool = True, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, is_coroutine: bool = True, endpoint_ctx: EndpointContext | None = None, dump_json: bool = False, ) -> Any: if field: if is_coroutine: value, errors = field.validate(response_content, {}, loc=("response",)) else: value, errors = await run_in_threadpool( field.validate, response_content, {}, loc=("response",) ) if errors: ctx = endpoint_ctx or EndpointContext() raise ResponseValidationError( errors=errors, body=response_content, endpoint_ctx=ctx, ) serializer = field.serialize_json if dump_json else field.serialize return serializer( value, include=include, exclude=exclude, by_alias=by_alias, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, exclude_none=exclude_none, ) else: return jsonable_encoder(response_content) async def run_endpoint_function( *, dependant: Dependant, values: dict[str, Any], is_coroutine: bool ) -> Any: # Only called by get_request_handler. Has been split into its own function to # facilitate profiling endpoints, since inner functions are harder to profile. assert dependant.call is not None, "dependant.call must be a function" if is_coroutine: return await dependant.call(**values) else: return await run_in_threadpool(dependant.call, **values) def _build_response_args( *, status_code: int | None, solved_result: Any ) -> dict[str, Any]: response_args: dict[str, Any] = { "background": solved_result.background_tasks, } # If status_code was set, use it, otherwise use the default from the # response class, in the case of redirect it's 307 current_status_code = ( status_code if status_code else solved_result.response.status_code ) if current_status_code is not None: response_args["status_code"] = current_status_code if solved_result.response.status_code: response_args["status_code"] = solved_result.response.status_code return response_args def get_request_handler( dependant: Dependant, body_field: ModelField | None = None, status_code: int | None = None, response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse), response_field: ModelField | None = None, response_model_include: IncEx | None = None, response_model_exclude: IncEx | None = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, dependency_overrides_provider: Any | None = None, embed_body_fields: bool = False, strict_content_type: bool | DefaultPlaceholder = Default(True), stream_item_field: ModelField | None = None, is_json_stream: bool = False, ) -> Callable[[Request], Coroutine[Any, Any, Response]]: assert dependant.call is not None, "dependant.call must be a function" is_coroutine = dependant.is_coroutine_callable is_body_form = body_field and isinstance(body_field.field_info, params.Form) if isinstance(response_class, DefaultPlaceholder): actual_response_class: type[Response] = response_class.value else: actual_response_class = response_class is_sse_stream = lenient_issubclass(actual_response_class, EventSourceResponse) if isinstance(strict_content_type, DefaultPlaceholder): actual_strict_content_type: bool = strict_content_type.value else: actual_strict_content_type = strict_content_type async def app(request: Request) -> Response: response: Response | None = None file_stack = request.scope.get("fastapi_middleware_astack") assert isinstance(file_stack, AsyncExitStack), ( "fastapi_middleware_astack not found in request scope" ) # Extract endpoint context for error messages endpoint_ctx = ( _extract_endpoint_context(dependant.call) if dependant.call else EndpointContext() ) if dependant.path: # For mounted sub-apps, include the mount path prefix mount_path = request.scope.get("root_path", "").rstrip("/") endpoint_ctx["path"] = f"{request.method} {mount_path}{dependant.path}" # Read body and auto-close files try: body: Any = None if body_field: if is_body_form: body = await request.form() file_stack.push_async_callback(body.close) else: body_bytes = await request.body() if body_bytes: json_body: Any = Undefined content_type_value = request.headers.get("content-type") if not content_type_value: if not actual_strict_content_type: json_body = await request.json() else: message = email.message.Message() message["content-type"] = content_type_value if message.get_content_maintype() == "application": subtype = message.get_content_subtype() if subtype == "json" or subtype.endswith("+json"): json_body = await request.json() if json_body != Undefined: body = json_body else: body = body_bytes except json.JSONDecodeError as e: validation_error = RequestValidationError( [ { "type": "json_invalid", "loc": ("body", e.pos), "msg": "JSON decode error", "input": {}, "ctx": {"error": e.msg}, } ], body=e.doc, endpoint_ctx=endpoint_ctx, ) raise validation_error from e except HTTPException: # If a middleware raises an HTTPException, it should be raised again raise except Exception as e: http_error = HTTPException( status_code=400, detail="There was an error parsing the body" ) raise http_error from e # Solve dependencies and run path operation function, auto-closing dependencies errors: list[Any] = [] async_exit_stack = request.scope.get("fastapi_inner_astack") assert isinstance(async_exit_stack, AsyncExitStack), ( "fastapi_inner_astack not found in request scope" ) solved_result = await solve_dependencies( request=request, dependant=dependant, body=cast(dict[str, Any] | FormData | bytes | None, body), dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, embed_body_fields=embed_body_fields, ) errors = solved_result.errors assert dependant.call # For types if not errors: # Shared serializer for stream items (JSONL and SSE). # Validates against stream_item_field when set, then # serializes to JSON bytes. def _serialize_data(data: Any) -> bytes: if stream_item_field: value, errors_ = stream_item_field.validate( data, {}, loc=("response",) ) if errors_: ctx = endpoint_ctx or EndpointContext() raise ResponseValidationError( errors=errors_, body=data, endpoint_ctx=ctx, ) return stream_item_field.serialize_json( value, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, exclude_unset=response_model_exclude_unset, exclude_defaults=response_model_exclude_defaults, exclude_none=response_model_exclude_none, ) else: data = jsonable_encoder(data) return json.dumps(data).encode("utf-8") if is_sse_stream: # Generator endpoint: stream as Server-Sent Events gen = dependant.call(**solved_result.values) def _serialize_sse_item(item: Any) -> bytes: if isinstance(item, ServerSentEvent): # User controls the event structure. # Serialize the data payload if present. # For ServerSentEvent items we skip stream_item_field # validation (the user may mix types intentionally). if item.raw_data is not None: data_str: str | None = item.raw_data elif item.data is not None: if hasattr(item.data, "model_dump_json"): data_str = item.data.model_dump_json() else: data_str = json.dumps(jsonable_encoder(item.data)) else: data_str = None return format_sse_event( data_str=data_str, event=item.event, id=item.id, retry=item.retry, comment=item.comment, ) else: # Plain object: validate + serialize via # stream_item_field (if set) and wrap in data field return format_sse_event( data_str=_serialize_data(item).decode("utf-8") ) if dependant.is_async_gen_callable: sse_aiter: AsyncIterator[Any] = gen.__aiter__() else: sse_aiter = iterate_in_threadpool(gen) @asynccontextmanager async def _sse_producer_cm() -> AsyncIterator[ ObjectReceiveStream[bytes] ]: # Use a memory stream to decouple generator iteration # from the keepalive timer. A producer task pulls items # from the generator independently, so # `anyio.fail_after` never wraps the generator's # `__anext__` directly - avoiding CancelledError that # would finalize the generator and also working for sync # generators running in a thread pool. # # This context manager is entered on the request-scoped # AsyncExitStack so its __aexit__ (which cancels the # task group) is called by the exit stack after the # streaming response completes — not by async generator # finalization via GeneratorExit. # Ref: https://peps.python.org/pep-0789/ send_stream, receive_stream = anyio.create_memory_object_stream[ bytes ](max_buffer_size=1) async def _producer() -> None: async with send_stream: async for raw_item in sse_aiter: await send_stream.send(_serialize_sse_item(raw_item)) send_keepalive, receive_keepalive = ( anyio.create_memory_object_stream[bytes](max_buffer_size=1) ) async def _keepalive_inserter() -> None: async with send_keepalive, receive_stream: try: while True: try: with anyio.fail_after(_PING_INTERVAL): data = await receive_stream.receive() await send_keepalive.send(data) except TimeoutError: await send_keepalive.send(KEEPALIVE_COMMENT) except anyio.EndOfStream: pass async with anyio.create_task_group() as tg: tg.start_soon(_producer) tg.start_soon(_keepalive_inserter) yield receive_keepalive tg.cancel_scope.cancel() # Enter the SSE context manager on the request-scoped # exit stack. The stack outlives the streaming response, # so __aexit__ runs via proper structured teardown, not # via GeneratorExit thrown into an async generator. sse_receive_stream = await async_exit_stack.enter_async_context( _sse_producer_cm() ) # Ensure the receive stream is closed when the exit stack # unwinds, preventing ResourceWarning from __del__. async_exit_stack.push_async_callback(sse_receive_stream.aclose) async def _sse_with_checkpoints( stream: ObjectReceiveStream[bytes], ) -> AsyncIterator[bytes]: async for data in stream: yield data # Guarantee a checkpoint so cancellation can be # delivered even when the producer is faster than # the consumer and receive() never suspends. await anyio.sleep(0) sse_stream_content: AsyncIterator[bytes] | Iterator[bytes] = ( _sse_with_checkpoints(sse_receive_stream) ) response = StreamingResponse( sse_stream_content, media_type="text/event-stream", background=solved_result.background_tasks, ) response.headers["Cache-Control"] = "no-cache" # For Nginx proxies to not buffer server sent events response.headers["X-Accel-Buffering"] = "no" response.headers.raw.extend(solved_result.response.headers.raw) elif is_json_stream: # Generator endpoint: stream as JSONL gen = dependant.call(**solved_result.values) def _serialize_item(item: Any) -> bytes: return _serialize_data(item) + b"\n" if dependant.is_async_gen_callable: async def _async_stream_jsonl() -> AsyncIterator[bytes]: async for item in gen: yield _serialize_item(item) # To allow for cancellation to trigger # Ref: https://github.com/fastapi/fastapi/issues/14680 await anyio.sleep(0) jsonl_stream_content: AsyncIterator[bytes] | Iterator[bytes] = ( _async_stream_jsonl() ) else: def _sync_stream_jsonl() -> Iterator[bytes]: for item in gen: # ty: ignore[not-iterable] yield _serialize_item(item) jsonl_stream_content = _sync_stream_jsonl() response = StreamingResponse( jsonl_stream_content, media_type="application/jsonl", background=solved_result.background_tasks, ) response.headers.raw.extend(solved_result.response.headers.raw) elif dependant.is_async_gen_callable or dependant.is_gen_callable: # Raw streaming with explicit response_class (e.g. StreamingResponse) gen = dependant.call(**solved_result.values) if dependant.is_async_gen_callable: async def _async_stream_raw( async_gen: AsyncIterator[Any], ) -> AsyncIterator[Any]: async for chunk in async_gen: yield chunk # To allow for cancellation to trigger # Ref: https://github.com/fastapi/fastapi/issues/14680 await anyio.sleep(0) gen = _async_stream_raw(gen) response_args = _build_response_args( status_code=status_code, solved_result=solved_result ) response = actual_response_class(content=gen, **response_args) response.headers.raw.extend(solved_result.response.headers.raw) else: raw_response = await run_endpoint_function( dependant=dependant, values=solved_result.values, is_coroutine=is_coroutine, ) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = solved_result.background_tasks response = raw_response else: response_args = _build_response_args( status_code=status_code, solved_result=solved_result ) # Use the fast path (dump_json) when no custom response # class was set and a response field with a TypeAdapter # exists. Serializes directly to JSON bytes via Pydantic's # Rust core, skipping the intermediate Python dict + # json.dumps() step. use_dump_json = response_field is not None and isinstance( response_class, DefaultPlaceholder ) content = await serialize_response( field=response_field, response_content=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, exclude_unset=response_model_exclude_unset, exclude_defaults=response_model_exclude_defaults, exclude_none=response_model_exclude_none, is_coroutine=is_coroutine, endpoint_ctx=endpoint_ctx, dump_json=use_dump_json, ) if use_dump_json: response = Response( content=content, media_type="application/json", **response_args, ) else: response = actual_response_class(content, **response_args) if not is_body_allowed_for_status_code(response.status_code): response.body = b"" response.headers.raw.extend(solved_result.response.headers.raw) if errors: validation_error = RequestValidationError( errors, body=body, endpoint_ctx=endpoint_ctx ) raise validation_error # Return response assert response return response return app def get_websocket_app( dependant: Dependant, dependency_overrides_provider: Any | None = None, embed_body_fields: bool = False, ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]: async def app(websocket: WebSocket) -> None: endpoint_ctx = ( _extract_endpoint_context(dependant.call) if dependant.call else EndpointContext() ) if dependant.path: # For mounted sub-apps, include the mount path prefix mount_path = websocket.scope.get("root_path", "").rstrip("/") endpoint_ctx["path"] = f"WS {mount_path}{dependant.path}" async_exit_stack = websocket.scope.get("fastapi_inner_astack") assert isinstance(async_exit_stack, AsyncExitStack), ( "fastapi_inner_astack not found in request scope" ) solved_result = await solve_dependencies( request=websocket, dependant=dependant, dependency_overrides_provider=dependency_overrides_provider, async_exit_stack=async_exit_stack, embed_body_fields=embed_body_fields, ) if solved_result.errors: raise WebSocketRequestValidationError( solved_result.errors, endpoint_ctx=endpoint_ctx, ) assert dependant.call is not None, "dependant.call must be a function" await dependant.call(**solved_result.values) return app class APIWebSocketRoute(routing.WebSocketRoute): def __init__( self, path: str, endpoint: Callable[..., Any], *, name: str | None = None, dependencies: Sequence[params.Depends] | None = None, dependency_overrides_provider: Any | None = None, ) -> None: self.path = path self.endpoint = endpoint self.name = get_name(endpoint) if name is None else name self.dependencies = list(dependencies or []) self.path_regex, self.path_format, self.param_convertors = compile_path(path) self.dependant = get_dependant( path=self.path_format, call=self.endpoint, scope="function" ) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=self.path_format), ) self._flat_dependant = get_flat_dependant(self.dependant) self._embed_body_fields = _should_embed_body_fields( self._flat_dependant.body_params ) self.app = websocket_session( get_websocket_app( dependant=self.dependant, dependency_overrides_provider=dependency_overrides_provider, embed_body_fields=self._embed_body_fields, ) ) def matches(self, scope: Scope) -> tuple[Match, Scope]: match, child_scope = super().matches(scope) if match != Match.NONE: child_scope["route"] = self return match, child_scope class APIRoute(routing.Route): def __init__( self, path: str, endpoint: Callable[..., Any], *, response_model: Any = Default(None), status_code: int | None = None, tags: list[str | Enum] | None = None, dependencies: Sequence[params.Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = "Successful Response", responses: dict[int | str, dict[str, Any]] | None = None, deprecated: bool | None = None, name: str | None = None, methods: set[str] | list[str] | None = None, operation_id: str | None = None, response_model_include: IncEx | None = None, response_model_exclude: IncEx | None = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse), dependency_overrides_provider: Any | None = None, callbacks: list[BaseRoute] | None = None, openapi_extra: dict[str, Any] | None = None, generate_unique_id_function: Callable[["APIRoute"], str] | DefaultPlaceholder = Default(generate_unique_id), strict_content_type: bool | DefaultPlaceholder = Default(True), ) -> None: self.path = path self.endpoint = endpoint self.stream_item_type: Any | None = None if isinstance(response_model, DefaultPlaceholder): return_annotation = get_typed_return_annotation(endpoint) if lenient_issubclass(return_annotation, Response): response_model = None else: stream_item = get_stream_item_type(return_annotation) if stream_item is not None: # Extract item type for JSONL or SSE streaming when # response_class is DefaultPlaceholder (JSONL) or # EventSourceResponse (SSE). # ServerSentEvent is excluded: it's a transport # wrapper, not a data model, so it shouldn't feed # into validation or OpenAPI schema generation. if ( isinstance(response_class, DefaultPlaceholder) or lenient_issubclass(response_class, EventSourceResponse) ) and not lenient_issubclass(stream_item, ServerSentEvent): self.stream_item_type = stream_item response_model = None else: response_model = return_annotation self.response_model = response_model self.summary = summary self.response_description = response_description self.deprecated = deprecated self.operation_id = operation_id self.response_model_include = response_model_include self.response_model_exclude = response_model_exclude self.response_model_by_alias = response_model_by_alias self.response_model_exclude_unset = response_model_exclude_unset self.response_model_exclude_defaults = response_model_exclude_defaults self.response_model_exclude_none = response_model_exclude_none self.include_in_schema = include_in_schema self.response_class = response_class self.dependency_overrides_provider = dependency_overrides_provider self.callbacks = callbacks self.openapi_extra = openapi_extra self.generate_unique_id_function = generate_unique_id_function self.strict_content_type = strict_content_type self.tags = tags or [] self.responses = responses or {} self.name = get_name(endpoint) if name is None else name self.path_regex, self.path_format, self.param_convertors = compile_path(path) if methods is None: methods = ["GET"] self.methods: set[str] = {method.upper() for method in methods} if isinstance(generate_unique_id_function, DefaultPlaceholder): current_generate_unique_id: Callable[[APIRoute], str] = ( generate_unique_id_function.value ) else: current_generate_unique_id = generate_unique_id_function self.unique_id = self.operation_id or current_generate_unique_id(self) # normalize enums e.g. http.HTTPStatus if isinstance(status_code, IntEnum): status_code = int(status_code) self.status_code = status_code if self.response_model: assert is_body_allowed_for_status_code(status_code), ( f"Status code {status_code} must not have a response body" ) response_name = "Response_" + self.unique_id self.response_field = create_model_field( name=response_name, type_=self.response_model, mode="serialization", ) else: self.response_field = None # type: ignore # ty: ignore[unused-ignore-comment] if self.stream_item_type: stream_item_name = "StreamItem_" + self.unique_id self.stream_item_field: ModelField | None = create_model_field( name=stream_item_name, type_=self.stream_item_type, mode="serialization", ) else: self.stream_item_field = None self.dependencies = list(dependencies or []) self.description = description or inspect.cleandoc(self.endpoint.__doc__ or "") # if a "form feed" character (page break) is found in the description text, # truncate description text to the content preceding the first "form feed" self.description = self.description.split("\f")[0].strip() response_fields = {} for additional_status_code, response in self.responses.items(): assert isinstance(response, dict), "An additional response must be a dict" model = response.get("model") if model: assert is_body_allowed_for_status_code(additional_status_code), ( f"Status code {additional_status_code} must not have a response body" ) response_name = f"Response_{additional_status_code}_{self.unique_id}" response_field = create_model_field( name=response_name, type_=model, mode="serialization" ) response_fields[additional_status_code] = response_field if response_fields: self.response_fields: dict[int | str, ModelField] = response_fields else: self.response_fields = {} assert callable(endpoint), "An endpoint must be a callable" self.dependant = get_dependant( path=self.path_format, call=self.endpoint, scope="function" ) for depends in self.dependencies[::-1]: self.dependant.dependencies.insert( 0, get_parameterless_sub_dependant(depends=depends, path=self.path_format), ) self._flat_dependant = get_flat_dependant(self.dependant) self._embed_body_fields = _should_embed_body_fields( self._flat_dependant.body_params ) self.body_field = get_body_field( flat_dependant=self._flat_dependant, name=self.unique_id, embed_body_fields=self._embed_body_fields, ) # Detect generator endpoints that should stream as JSONL or SSE is_generator = ( self.dependant.is_async_gen_callable or self.dependant.is_gen_callable ) self.is_sse_stream = is_generator and lenient_issubclass( response_class, EventSourceResponse ) self.is_json_stream = is_generator and isinstance( response_class, DefaultPlaceholder ) self.app = request_response(self.get_route_handler()) def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: return get_request_handler( dependant=self.dependant, body_field=self.body_field, status_code=self.status_code, response_class=self.response_class, response_field=self.response_field, response_model_include=self.response_model_include, response_model_exclude=self.response_model_exclude, response_model_by_alias=self.response_model_by_alias, response_model_exclude_unset=self.response_model_exclude_unset, response_model_exclude_defaults=self.response_model_exclude_defaults, response_model_exclude_none=self.response_model_exclude_none, dependency_overrides_provider=self.dependency_overrides_provider, embed_body_fields=self._embed_body_fields, strict_content_type=self.strict_content_type, stream_item_field=self.stream_item_field, is_json_stream=self.is_json_stream, ) def matches(self, scope: Scope) -> tuple[Match, Scope]: match, child_scope = super().matches(scope) if match != Match.NONE: child_scope["route"] = self return match, child_scope class APIRouter(routing.Router): def __init__( self, *, prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to all the *path operations* in this router. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, dependencies: Annotated[ Sequence[params.Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to all the *path operations* in this router. Read more about it in the [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). """ ), ] = None, default_response_class: Annotated[ type[Response], Doc( """ The default response class to be used. Read more in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). """ ), ] = Default(JSONResponse), responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses to be shown in OpenAPI. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). And in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ OpenAPI callbacks that should apply to all *path operations* in this router. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, routes: Annotated[ list[BaseRoute] | None, Doc( """ **Note**: you probably shouldn't use this parameter, it is inherited from Starlette and supported for compatibility. --- A list of routes to serve incoming HTTP and WebSocket requests. """ ), deprecated( """ You normally wouldn't use this parameter with FastAPI, it is inherited from Starlette and supported for compatibility. In FastAPI, you normally would use the *path operation methods*, like `router.get()`, `router.post()`, etc. """ ), ] = None, redirect_slashes: Annotated[ bool, Doc( """ Whether to detect and redirect slashes in URLs when the client doesn't use the same format. """ ), ] = True, default: Annotated[ ASGIApp | None, Doc( """ Default function handler for this router. Used to handle 404 Not Found errors. """ ), ] = None, dependency_overrides_provider: Annotated[ Any | None, Doc( """ Only used internally by FastAPI to handle dependency overrides. You shouldn't need to use it. It normally points to the `FastAPI` app object. """ ), ] = None, route_class: Annotated[ type[APIRoute], Doc( """ Custom route (*path operation*) class to be used by this router. Read more about it in the [FastAPI docs for Custom Request and APIRoute class](https://fastapi.tiangolo.com/how-to/custom-request-and-route/#custom-apiroute-class-in-a-router). """ ), ] = APIRoute, on_startup: Annotated[ Sequence[Callable[[], Any]] | None, Doc( """ A list of startup event handler functions. You should instead use the `lifespan` handlers. Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). """ ), ] = None, on_shutdown: Annotated[ Sequence[Callable[[], Any]] | None, Doc( """ A list of shutdown event handler functions. You should instead use the `lifespan` handlers. Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). """ ), ] = None, # the generic to Lifespan[AppType] is the type of the top level application # which the router cannot know statically, so we use typing.Any lifespan: Annotated[ Lifespan[Any] | None, Doc( """ A `Lifespan` context manager handler. This replaces `startup` and `shutdown` functions with a single context manager. Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark all *path operations* in this router as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ To include (or not) all the *path operations* in this router in the generated OpenAPI. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), strict_content_type: Annotated[ bool, Doc( """ Enable strict checking for request Content-Type headers. When `True` (the default), requests with a body that do not include a `Content-Type` header will **not** be parsed as JSON. This prevents potential cross-site request forgery (CSRF) attacks that exploit the browser's ability to send requests without a Content-Type header, bypassing CORS preflight checks. In particular applicable for apps that need to be run locally (in localhost). When `False`, requests without a `Content-Type` header will have their body parsed as JSON, which maintains compatibility with certain clients that don't send `Content-Type` headers. Read more about it in the [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/). """ ), ] = Default(True), ) -> None: # Determine the lifespan context to use if lifespan is None: # Use the default lifespan that runs on_startup/on_shutdown handlers lifespan_context: Lifespan[Any] = _DefaultLifespan(self) elif inspect.isasyncgenfunction(lifespan): lifespan_context = asynccontextmanager(lifespan) elif inspect.isgeneratorfunction(lifespan): lifespan_context = _wrap_gen_lifespan_context(lifespan) else: lifespan_context = lifespan self.lifespan_context = lifespan_context super().__init__( routes=routes, redirect_slashes=redirect_slashes, default=default, lifespan=lifespan_context, ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith("/"), ( "A path prefix must not end with '/', as the routes will start with '/'" ) # Handle on_startup/on_shutdown locally since Starlette removed support # Ref: https://github.com/Kludex/starlette/pull/3117 # TODO: deprecate this once the lifespan (or alternative) interface is improved self.on_startup: list[Callable[[], Any]] = ( [] if on_startup is None else list(on_startup) ) self.on_shutdown: list[Callable[[], Any]] = ( [] if on_shutdown is None else list(on_shutdown) ) self.prefix = prefix self.tags: list[str | Enum] = tags or [] self.dependencies = list(dependencies or []) self.deprecated = deprecated self.include_in_schema = include_in_schema self.responses = responses or {} self.callbacks = callbacks or [] self.dependency_overrides_provider = dependency_overrides_provider self.route_class = route_class self.default_response_class = default_response_class self.generate_unique_id_function = generate_unique_id_function self.strict_content_type = strict_content_type def route( self, path: str, methods: Collection[str] | None = None, name: str | None = None, include_in_schema: bool = True, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator def add_api_route( self, path: str, endpoint: Callable[..., Any], *, response_model: Any = Default(None), status_code: int | None = None, tags: list[str | Enum] | None = None, dependencies: Sequence[params.Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = "Successful Response", responses: dict[int | str, dict[str, Any]] | None = None, deprecated: bool | None = None, methods: set[str] | list[str] | None = None, operation_id: str | None = None, response_model_include: IncEx | None = None, response_model_exclude: IncEx | None = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: type[Response] | DefaultPlaceholder = Default(JSONResponse), name: str | None = None, route_class_override: type[APIRoute] | None = None, callbacks: list[BaseRoute] | None = None, openapi_extra: dict[str, Any] | None = None, generate_unique_id_function: Callable[[APIRoute], str] | DefaultPlaceholder = Default(generate_unique_id), strict_content_type: bool | DefaultPlaceholder = Default(True), ) -> None: route_class = route_class_override or self.route_class responses = responses or {} combined_responses = {**self.responses, **responses} current_response_class = get_value_or_default( response_class, self.default_response_class ) current_tags = self.tags.copy() if tags: current_tags.extend(tags) current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) current_callbacks = self.callbacks.copy() if callbacks: current_callbacks.extend(callbacks) current_generate_unique_id = get_value_or_default( generate_unique_id_function, self.generate_unique_id_function ) route = route_class( self.prefix + path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=current_tags, dependencies=current_dependencies, summary=summary, description=description, response_description=response_description, responses=combined_responses, deprecated=deprecated or self.deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema and self.include_in_schema, response_class=current_response_class, name=name, dependency_overrides_provider=self.dependency_overrides_provider, callbacks=current_callbacks, openapi_extra=openapi_extra, generate_unique_id_function=current_generate_unique_id, strict_content_type=get_value_or_default( strict_content_type, self.strict_content_type ), ) self.routes.append(route) def api_route( self, path: str, *, response_model: Any = Default(None), status_code: int | None = None, tags: list[str | Enum] | None = None, dependencies: Sequence[params.Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = "Successful Response", responses: dict[int | str, dict[str, Any]] | None = None, deprecated: bool | None = None, methods: list[str] | None = None, operation_id: str | None = None, response_model_include: IncEx | None = None, response_model_exclude: IncEx | None = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: type[Response] = Default(JSONResponse), name: str | None = None, callbacks: list[BaseRoute] | None = None, openapi_extra: dict[str, Any] | None = None, generate_unique_id_function: Callable[[APIRoute], str] = Default( generate_unique_id ), ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) return func return decorator def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: str | None = None, *, dependencies: Sequence[params.Depends] | None = None, ) -> None: current_dependencies = self.dependencies.copy() if dependencies: current_dependencies.extend(dependencies) route = APIWebSocketRoute( self.prefix + path, endpoint=endpoint, name=name, dependencies=current_dependencies, dependency_overrides_provider=self.dependency_overrides_provider, ) self.routes.append(route) def websocket( self, path: Annotated[ str, Doc( """ WebSocket path. """ ), ], name: Annotated[ str | None, Doc( """ A name for the WebSocket. Only used internally. """ ), ] = None, *, dependencies: Annotated[ Sequence[params.Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be used for this WebSocket. Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). """ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( path, func, name=name, dependencies=dependencies ) return func return decorator def websocket_route( self, path: str, name: str | None = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_websocket_route(path, func, name=name) return func return decorator def include_router( self, router: Annotated["APIRouter", Doc("The `APIRouter` to include.")], *, prefix: Annotated[str, Doc("An optional path prefix for the router.")] = "", tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to all the *path operations* in this router. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, dependencies: Annotated[ Sequence[params.Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to all the *path operations* in this router. Read more about it in the [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). """ ), ] = None, default_response_class: Annotated[ type[Response], Doc( """ The default response class to be used. Read more in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class). """ ), ] = Default(JSONResponse), responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses to be shown in OpenAPI. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/). And in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies). """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ OpenAPI callbacks that should apply to all *path operations* in this router. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark all *path operations* in this router as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, include_in_schema: Annotated[ bool, Doc( """ Include (or not) all the *path operations* in this router in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = True, generate_unique_id_function: Annotated[ Callable[[APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> None: assert self is not router, ( "Cannot include the same APIRouter instance into itself. " "Did you mean to include a different router?" ) if prefix: assert prefix.startswith("/"), "A path prefix must start with '/'" assert not prefix.endswith("/"), ( "A path prefix must not end with '/', as the routes will start with '/'" ) else: for r in router.routes: path = getattr(r, "path") # noqa: B009 name = getattr(r, "name", "unknown") if path is not None and not path: raise FastAPIError( f"Prefix and path cannot be both empty (path operation: {name})" ) if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): combined_responses = {**responses, **route.responses} use_response_class = get_value_or_default( route.response_class, router.default_response_class, default_response_class, self.default_response_class, ) current_tags = [] if tags: current_tags.extend(tags) if route.tags: current_tags.extend(route.tags) current_dependencies: list[params.Depends] = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) current_callbacks = [] if callbacks: current_callbacks.extend(callbacks) if route.callbacks: current_callbacks.extend(route.callbacks) current_generate_unique_id = get_value_or_default( route.generate_unique_id_function, router.generate_unique_id_function, generate_unique_id_function, self.generate_unique_id_function, ) self.add_api_route( prefix + route.path, route.endpoint, response_model=route.response_model, status_code=route.status_code, tags=current_tags, dependencies=current_dependencies, summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated or deprecated or self.deprecated, methods=route.methods, operation_id=route.operation_id, response_model_include=route.response_model_include, response_model_exclude=route.response_model_exclude, response_model_by_alias=route.response_model_by_alias, response_model_exclude_unset=route.response_model_exclude_unset, response_model_exclude_defaults=route.response_model_exclude_defaults, response_model_exclude_none=route.response_model_exclude_none, include_in_schema=route.include_in_schema and self.include_in_schema and include_in_schema, response_class=use_response_class, name=route.name, route_class_override=type(route), callbacks=current_callbacks, openapi_extra=route.openapi_extra, generate_unique_id_function=current_generate_unique_id, strict_content_type=get_value_or_default( route.strict_content_type, router.strict_content_type, self.strict_content_type, ), ) elif isinstance(route, routing.Route): methods = list(route.methods or []) self.add_route( prefix + route.path, route.endpoint, methods=methods, include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, APIWebSocketRoute): current_dependencies = [] if dependencies: current_dependencies.extend(dependencies) if route.dependencies: current_dependencies.extend(route.dependencies) self.add_api_websocket_route( prefix + route.path, route.endpoint, dependencies=current_dependencies, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route.name ) for handler in router.on_startup: self.add_event_handler("startup", handler) for handler in router.on_shutdown: self.add_event_handler("shutdown", handler) self.lifespan_context = _merge_lifespan_context( self.lifespan_context, router.lifespan_context, ) def get( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[params.Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["GET"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def put( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[params.Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PUT"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def post( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[params.Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["POST"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def delete( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[params.Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["DELETE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def options( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[params.Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["OPTIONS"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def head( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[params.Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["HEAD"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def patch( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[params.Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["PATCH"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) def trace( self, path: Annotated[ str, Doc( """ The URL path to be used for this *path operation*. For example, in `http://example.com/items`, the path is `/items`. """ ), ], *, response_model: Annotated[ Any, Doc( """ The type to use for the response. It could be any valid Pydantic *field* type. So, it doesn't have to be a Pydantic model, it could be other things, like a `list`, `dict`, etc. It will be used for: * Documentation: the generated OpenAPI (and the UI at `/docs`) will show it as the response (JSON Schema). * Serialization: you could return an arbitrary object and the `response_model` would be used to serialize that object into the corresponding JSON. * Filtering: the JSON sent to the client will only contain the data (fields) defined in the `response_model`. If you returned an object that contains an attribute `password` but the `response_model` does not include that field, the JSON sent to the client would not have that `password`. * Validation: whatever you return will be serialized with the `response_model`, converting any data as necessary to generate the corresponding JSON. But if the data in the object returned is not valid, that would mean a violation of the contract with the client, so it's an error from the API developer. So, FastAPI will raise an error and return a 500 error code (Internal Server Error). Read more about it in the [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/). """ ), ] = Default(None), status_code: Annotated[ int | None, Doc( """ The default status code to be used for the response. You could override the status code by returning a response directly. Read more about it in the [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/). """ ), ] = None, tags: Annotated[ list[str | Enum] | None, Doc( """ A list of tags to be applied to the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags). """ ), ] = None, dependencies: Annotated[ Sequence[params.Depends] | None, Doc( """ A list of dependencies (using `Depends()`) to be applied to the *path operation*. Read more about it in the [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/). """ ), ] = None, summary: Annotated[ str | None, Doc( """ A summary for the *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, description: Annotated[ str | None, Doc( """ A description for the *path operation*. If not provided, it will be extracted automatically from the docstring of the *path operation function*. It can contain Markdown. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/). """ ), ] = None, response_description: Annotated[ str, Doc( """ The description for the default response. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = "Successful Response", responses: Annotated[ dict[int | str, dict[str, Any]] | None, Doc( """ Additional responses that could be returned by this *path operation*. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, deprecated: Annotated[ bool | None, Doc( """ Mark this *path operation* as deprecated. It will be added to the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, operation_id: Annotated[ str | None, Doc( """ Custom operation ID to be used by this *path operation*. By default, it is generated automatically. If you provide a custom operation ID, you need to make sure it is unique for the whole API. You can customize the operation ID generation with the parameter `generate_unique_id_function` in the `FastAPI` class. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = None, response_model_include: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to include only certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_exclude: Annotated[ IncEx | None, Doc( """ Configuration passed to Pydantic to exclude certain fields in the response data. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = None, response_model_by_alias: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response model should be serialized by alias when an alias is used. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude). """ ), ] = True, response_model_exclude_unset: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that were not set and have their default values. This is different from `response_model_exclude_defaults` in that if the fields are set, they will be included in the response, even if the value is the same as the default. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_defaults: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should have all the fields, including the ones that have the same value as the default. This is different from `response_model_exclude_unset` in that if the fields are set but contain the same default values, they will be excluded from the response. When `True`, default values are omitted from the response. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter). """ ), ] = False, response_model_exclude_none: Annotated[ bool, Doc( """ Configuration passed to Pydantic to define if the response data should exclude fields set to `None`. This is much simpler (less smart) than `response_model_exclude_unset` and `response_model_exclude_defaults`. You probably want to use one of those two instead of this one, as those allow returning `None` values when it makes sense. Read more about it in the [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none). """ ), ] = False, include_in_schema: Annotated[ bool, Doc( """ Include this *path operation* in the generated OpenAPI schema. This affects the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi). """ ), ] = True, response_class: Annotated[ type[Response], Doc( """ Response class to be used for this *path operation*. This will not be used if you return a response directly. Read more about it in the [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse). """ ), ] = Default(JSONResponse), name: Annotated[ str | None, Doc( """ Name for this *path operation*. Only used internally. """ ), ] = None, callbacks: Annotated[ list[BaseRoute] | None, Doc( """ List of *path operations* that will be used as OpenAPI callbacks. This is only for OpenAPI documentation, the callbacks won't be used directly. It will be added to the generated OpenAPI (e.g. visible at `/docs`). Read more about it in the [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/). """ ), ] = None, openapi_extra: Annotated[ dict[str, Any] | None, Doc( """ Extra metadata to be included in the OpenAPI schema for this *path operation*. Read more about it in the [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema). """ ), ] = None, generate_unique_id_function: Annotated[ Callable[[APIRoute], str], Doc( """ Customize the function used to generate unique IDs for the *path operations* shown in the generated OpenAPI. This is particularly useful when automatically generating clients or SDKs for your API. Read more about it in the [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function). """ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.api_route( path=path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=["TRACE"], operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, generate_unique_id_function=generate_unique_id_function, ) # TODO: remove this once the lifespan (or alternative) interface is improved async def _startup(self) -> None: for handler in self.on_startup: if is_async_callable(handler): await handler() else: handler() # TODO: remove this once the lifespan (or alternative) interface is improved async def _shutdown(self) -> None: for handler in self.on_shutdown: if is_async_callable(handler): await handler() else: handler() # TODO: remove this once the lifespan (or alternative) interface is improved def add_event_handler( self, event_type: str, func: Callable[[], Any], ) -> None: assert event_type in ("startup", "shutdown") if event_type == "startup": self.on_startup.append(func) else: self.on_shutdown.append(func) @deprecated( """ on_event is deprecated, use lifespan event handlers instead. Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/). """ ) def on_event( self, event_type: Annotated[ str, Doc( """ The type of event. `startup` or `shutdown`. """ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func return decorator
--- +++ @@ -97,6 +97,10 @@ def request_response( func: Callable[[Request], Awaitable[Response] | Response], ) -> ASGIApp: + """ + Takes a function or coroutine `func(request) -> response`, + and returns an ASGI application. + """ f: Callable[[Request], Awaitable[Response]] = ( func # type: ignore[assignment] # ty: ignore[unused-ignore-comment] if is_async_callable(func) @@ -137,6 +141,9 @@ def websocket_session( func: Callable[[WebSocket], Awaitable[None]], ) -> ASGIApp: + """ + Takes a coroutine `func(session)`, and returns an ASGI application. + """ # assert asyncio.iscoroutinefunction(func), "WebSocket endpoints must be async" async def app(scope: Scope, receive: Receive, send: Send) -> None: @@ -160,6 +167,11 @@ # Vendored from starlette.routing to avoid importing private symbols class _AsyncLiftContextManager(AbstractAsyncContextManager[_T]): + """ + Wraps a synchronous context manager to make it async. + + This is vendored from Starlette to avoid importing private symbols. + """ def __init__(self, cm: AbstractContextManager[_T]) -> None: self._cm = cm @@ -180,6 +192,11 @@ def _wrap_gen_lifespan_context( lifespan_context: Callable[[Any], Generator[Any, Any, Any]], ) -> Callable[[Any], AbstractAsyncContextManager[Any]]: + """ + Wrap a generator-based lifespan context into an async context manager. + + This is vendored from Starlette to avoid importing private symbols. + """ cmgr = contextlib.contextmanager(lifespan_context) @functools.wraps(cmgr) @@ -207,6 +224,15 @@ class _DefaultLifespan: + """ + Default lifespan context manager that runs on_startup and on_shutdown handlers. + + This is a copy of the Starlette _DefaultLifespan class that was removed + in Starlette. FastAPI keeps it to maintain backward compatibility with + on_startup and on_shutdown event handlers. + + Ref: https://github.com/Kludex/starlette/pull/3117 + """ def __init__(self, router: "APIRouter") -> None: self._router = router @@ -226,6 +252,7 @@ def _extract_endpoint_context(func: Any) -> EndpointContext: + """Extract endpoint context with caching to avoid repeated file I/O.""" func_id = id(func) if func_id in _endpoint_context_cache: @@ -536,6 +563,8 @@ ) async def _keepalive_inserter() -> None: + """Read from the producer and forward to the output, + inserting keepalive comments on timeout.""" async with send_keepalive, receive_stream: try: while True: @@ -974,6 +1003,31 @@ class APIRouter(routing.Router): + """ + `APIRouter` class, used to group *path operations*, for example to structure + an app in multiple files. It would then be included in the `FastAPI` app, or + in another `APIRouter` (ultimately included in the app). + + Read more about it in the + [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/). + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + + @router.get("/users/", tags=["users"]) + async def read_users(): + return [{"username": "Rick"}, {"username": "Morty"}] + + + app.include_router(router) + ``` + """ def __init__( self, @@ -1477,6 +1531,32 @@ ), ] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Decorate a WebSocket function. + + Read more about it in the + [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/). + + **Example** + + ## Example + + ```python + from fastapi import APIRouter, FastAPI, WebSocket + + app = FastAPI() + router = APIRouter() + + @router.websocket("/ws") + async def websocket_endpoint(websocket: WebSocket): + await websocket.accept() + while True: + data = await websocket.receive_text() + await websocket.send_text(f"Message text was: {data}") + + app.include_router(router) + ``` + """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route( @@ -1607,6 +1687,29 @@ ), ] = Default(generate_unique_id), ) -> None: + """ + Include another `APIRouter` in the same current `APIRouter`. + + Read more about it in the + [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/). + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + internal_router = APIRouter() + users_router = APIRouter() + + @users_router.get("/users/") + def read_users(): + return [{"name": "Rick"}, {"name": "Morty"}] + + internal_router.include_router(users_router) + app.include_router(internal_router) + ``` + """ assert self is not router, ( "Cannot include the same APIRouter instance into itself. " "Did you mean to include a different router?" @@ -2057,6 +2160,24 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP GET operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + @router.get("/items/") + def read_items(): + return [{"name": "Empanada"}, {"name": "Arepa"}] + + app.include_router(router) + ``` + """ return self.api_route( path=path, response_model=response_model, @@ -2416,6 +2537,29 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PUT operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.put("/items/{item_id}") + def replace_item(item_id: str, item: Item): + return {"message": "Item replaced", "id": item_id} + + app.include_router(router) + ``` + """ return self.api_route( path=path, response_model=response_model, @@ -2775,6 +2919,29 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP POST operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.post("/items/") + def create_item(item: Item): + return {"message": "Item created"} + + app.include_router(router) + ``` + """ return self.api_route( path=path, response_model=response_model, @@ -3134,6 +3301,24 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP DELETE operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + @router.delete("/items/{item_id}") + def delete_item(item_id: str): + return {"message": "Item deleted"} + + app.include_router(router) + ``` + """ return self.api_route( path=path, response_model=response_model, @@ -3493,6 +3678,24 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP OPTIONS operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + + app = FastAPI() + router = APIRouter() + + @router.options("/items/") + def get_item_options(): + return {"additions": ["Aji", "Guacamole"]} + + app.include_router(router) + ``` + """ return self.api_route( path=path, response_model=response_model, @@ -3852,6 +4055,29 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP HEAD operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.head("/items/", status_code=204) + def get_items_headers(response: Response): + response.headers["X-Cat-Dog"] = "Alone in the world" + + app.include_router(router) + ``` + """ return self.api_route( path=path, response_model=response_model, @@ -4211,6 +4437,29 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP PATCH operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.patch("/items/") + def update_item(item: Item): + return {"message": "Item updated in place"} + + app.include_router(router) + ``` + """ return self.api_route( path=path, response_model=response_model, @@ -4570,6 +4819,29 @@ ), ] = Default(generate_unique_id), ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add a *path operation* using an HTTP TRACE operation. + + ## Example + + ```python + from fastapi import APIRouter, FastAPI + from pydantic import BaseModel + + class Item(BaseModel): + name: str + description: str | None = None + + app = FastAPI() + router = APIRouter() + + @router.trace("/items/{item_id}") + def trace_item(item_id: str): + return None + + app.include_router(router) + ``` + """ return self.api_route( path=path, response_model=response_model, @@ -4599,6 +4871,14 @@ # TODO: remove this once the lifespan (or alternative) interface is improved async def _startup(self) -> None: + """ + Run any `.on_startup` event handlers. + + This method is kept for backward compatibility after Starlette removed + support for on_startup/on_shutdown handlers. + + Ref: https://github.com/Kludex/starlette/pull/3117 + """ for handler in self.on_startup: if is_async_callable(handler): await handler() @@ -4607,6 +4887,14 @@ # TODO: remove this once the lifespan (or alternative) interface is improved async def _shutdown(self) -> None: + """ + Run any `.on_shutdown` event handlers. + + This method is kept for backward compatibility after Starlette removed + support for on_startup/on_shutdown handlers. + + Ref: https://github.com/Kludex/starlette/pull/3117 + """ for handler in self.on_shutdown: if is_async_callable(handler): await handler() @@ -4619,6 +4907,14 @@ event_type: str, func: Callable[[], Any], ) -> None: + """ + Add an event handler function for startup or shutdown. + + This method is kept for backward compatibility after Starlette removed + support for on_startup/on_shutdown handlers. + + Ref: https://github.com/Kludex/starlette/pull/3117 + """ assert event_type in ("startup", "shutdown") if event_type == "startup": self.on_startup.append(func) @@ -4644,9 +4940,17 @@ ), ], ) -> Callable[[DecoratedCallable], DecoratedCallable]: + """ + Add an event handler for the router. + + `on_event` is deprecated, use `lifespan` event handlers instead. + + Read more about it in the + [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated). + """ def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_event_handler(event_type, func) return func - return decorator+ return decorator
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/routing.py
Add detailed documentation for each class
from typing import Annotated from annotated_doc import Doc from fastapi.openapi.models import APIKey, APIKeyIn from fastapi.security.base import SecurityBase from starlette.exceptions import HTTPException from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED class APIKeyBase(SecurityBase): model: APIKey def __init__( self, location: APIKeyIn, name: str, description: str | None, scheme_name: str | None, auto_error: bool, ): self.auto_error = auto_error self.model: APIKey = APIKey( **{"in": location}, # ty: ignore[invalid-argument-type] name=name, description=description, ) self.scheme_name = scheme_name or self.__class__.__name__ def make_not_authenticated_error(self) -> HTTPException: return HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated", headers={"WWW-Authenticate": "APIKey"}, ) def check_api_key(self, api_key: str | None) -> str | None: if not api_key: if self.auto_error: raise self.make_not_authenticated_error() return None return api_key class APIKeyQuery(APIKeyBase): def __init__( self, *, name: Annotated[ str, Doc("Query parameter name."), ], scheme_name: Annotated[ str | None, Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ str | None, Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if the query parameter is not provided, `APIKeyQuery` will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the query parameter is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in a query parameter or in an HTTP Bearer token). """ ), ] = True, ): super().__init__( location=APIKeyIn.query, name=name, scheme_name=scheme_name, description=description, auto_error=auto_error, ) async def __call__(self, request: Request) -> str | None: api_key = request.query_params.get(self.model.name) return self.check_api_key(api_key) class APIKeyHeader(APIKeyBase): def __init__( self, *, name: Annotated[str, Doc("Header name.")], scheme_name: Annotated[ str | None, Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ str | None, Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if the header is not provided, `APIKeyHeader` will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the header is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in a header or in an HTTP Bearer token). """ ), ] = True, ): super().__init__( location=APIKeyIn.header, name=name, scheme_name=scheme_name, description=description, auto_error=auto_error, ) async def __call__(self, request: Request) -> str | None: api_key = request.headers.get(self.model.name) return self.check_api_key(api_key) class APIKeyCookie(APIKeyBase): def __init__( self, *, name: Annotated[str, Doc("Cookie name.")], scheme_name: Annotated[ str | None, Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ str | None, Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if the cookie is not provided, `APIKeyCookie` will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the cookie is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in a cookie or in an HTTP Bearer token). """ ), ] = True, ): super().__init__( location=APIKeyIn.cookie, name=name, scheme_name=scheme_name, description=description, auto_error=auto_error, ) async def __call__(self, request: Request) -> str | None: api_key = request.cookies.get(self.model.name) return self.check_api_key(api_key)
--- +++ @@ -29,6 +29,15 @@ self.scheme_name = scheme_name or self.__class__.__name__ def make_not_authenticated_error(self) -> HTTPException: + """ + The WWW-Authenticate header is not standardized for API Key authentication but + the HTTP specification requires that an error of 401 "Unauthorized" must + include a WWW-Authenticate header. + + Ref: https://datatracker.ietf.org/doc/html/rfc9110#name-401-unauthorized + + For this, this method sends a custom challenge `APIKey`. + """ return HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated", @@ -44,6 +53,36 @@ class APIKeyQuery(APIKeyBase): + """ + API key authentication using a query parameter. + + This defines the name of the query parameter that should be provided in the request + with the API key and integrates that into the OpenAPI documentation. It extracts + the key value sent in the query parameter automatically and provides it as the + dependency result. But it doesn't define how to send that API key to the client. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be a string containing the key value. + + ## Example + + ```python + from fastapi import Depends, FastAPI + from fastapi.security import APIKeyQuery + + app = FastAPI() + + query_scheme = APIKeyQuery(name="api_key") + + + @app.get("/items/") + async def read_items(api_key: str = Depends(query_scheme)): + return {"api_key": api_key} + ``` + """ def __init__( self, @@ -106,6 +145,36 @@ class APIKeyHeader(APIKeyBase): + """ + API key authentication using a header. + + This defines the name of the header that should be provided in the request with + the API key and integrates that into the OpenAPI documentation. It extracts + the key value sent in the header automatically and provides it as the dependency + result. But it doesn't define how to send that key to the client. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be a string containing the key value. + + ## Example + + ```python + from fastapi import Depends, FastAPI + from fastapi.security import APIKeyHeader + + app = FastAPI() + + header_scheme = APIKeyHeader(name="x-key") + + + @app.get("/items/") + async def read_items(key: str = Depends(header_scheme)): + return {"key": key} + ``` + """ def __init__( self, @@ -164,6 +233,36 @@ class APIKeyCookie(APIKeyBase): + """ + API key authentication using a cookie. + + This defines the name of the cookie that should be provided in the request with + the API key and integrates that into the OpenAPI documentation. It extracts + the key value sent in the cookie automatically and provides it as the dependency + result. But it doesn't define how to set that cookie. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be a string containing the key value. + + ## Example + + ```python + from fastapi import Depends, FastAPI + from fastapi.security import APIKeyCookie + + app = FastAPI() + + cookie_scheme = APIKeyCookie(name="session") + + + @app.get("/items/") + async def read_items(session: str = Depends(cookie_scheme)): + return {"session": session} + ``` + """ def __init__( self, @@ -218,4 +317,4 @@ async def __call__(self, request: Request) -> str | None: api_key = request.cookies.get(self.model.name) - return self.check_api_key(api_key)+ return self.check_api_key(api_key)
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/security/api_key.py
Add inline docstrings for readability
from typing import Annotated, Any, cast from annotated_doc import Doc from fastapi.exceptions import HTTPException from fastapi.openapi.models import OAuth2 as OAuth2Model from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel from fastapi.param_functions import Form from fastapi.security.base import SecurityBase from fastapi.security.utils import get_authorization_scheme_param from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED class OAuth2PasswordRequestForm: def __init__( self, *, grant_type: Annotated[ str | None, Form(pattern="^password$"), Doc( """ The OAuth2 spec says it is required and MUST be the fixed string "password". Nevertheless, this dependency class is permissive and allows not passing it. If you want to enforce it, use instead the `OAuth2PasswordRequestFormStrict` dependency. Read more about it in the [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). """ ), ] = None, username: Annotated[ str, Form(), Doc( """ `username` string. The OAuth2 spec requires the exact field name `username`. Read more about it in the [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). """ ), ], password: Annotated[ str, Form(json_schema_extra={"format": "password"}), Doc( """ `password` string. The OAuth2 spec requires the exact field name `password`. Read more about it in the [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). """ ), ], scope: Annotated[ str, Form(), Doc( """ A single string with actually several scopes separated by spaces. Each scope is also a string. For example, a single string with: ```python "items:read items:write users:read profile openid" ```` would represent the scopes: * `items:read` * `items:write` * `users:read` * `profile` * `openid` Read more about it in the [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). """ ), ] = "", client_id: Annotated[ str | None, Form(), Doc( """ If there's a `client_id`, it can be sent as part of the form fields. But the OAuth2 specification recommends sending the `client_id` and `client_secret` (if any) using HTTP Basic auth. """ ), ] = None, client_secret: Annotated[ str | None, Form(json_schema_extra={"format": "password"}), Doc( """ If there's a `client_password` (and a `client_id`), they can be sent as part of the form fields. But the OAuth2 specification recommends sending the `client_id` and `client_secret` (if any) using HTTP Basic auth. """ ), ] = None, ): self.grant_type = grant_type self.username = username self.password = password self.scopes = scope.split() self.client_id = client_id self.client_secret = client_secret class OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm): def __init__( self, grant_type: Annotated[ str, Form(pattern="^password$"), Doc( """ The OAuth2 spec says it is required and MUST be the fixed string "password". This dependency is strict about it. If you want to be permissive, use instead the `OAuth2PasswordRequestForm` dependency class. Read more about it in the [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). """ ), ], username: Annotated[ str, Form(), Doc( """ `username` string. The OAuth2 spec requires the exact field name `username`. Read more about it in the [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). """ ), ], password: Annotated[ str, Form(), Doc( """ `password` string. The OAuth2 spec requires the exact field name `password`. Read more about it in the [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). """ ), ], scope: Annotated[ str, Form(), Doc( """ A single string with actually several scopes separated by spaces. Each scope is also a string. For example, a single string with: ```python "items:read items:write users:read profile openid" ```` would represent the scopes: * `items:read` * `items:write` * `users:read` * `profile` * `openid` Read more about it in the [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). """ ), ] = "", client_id: Annotated[ str | None, Form(), Doc( """ If there's a `client_id`, it can be sent as part of the form fields. But the OAuth2 specification recommends sending the `client_id` and `client_secret` (if any) using HTTP Basic auth. """ ), ] = None, client_secret: Annotated[ str | None, Form(), Doc( """ If there's a `client_password` (and a `client_id`), they can be sent as part of the form fields. But the OAuth2 specification recommends sending the `client_id` and `client_secret` (if any) using HTTP Basic auth. """ ), ] = None, ): super().__init__( grant_type=grant_type, username=username, password=password, scope=scope, client_id=client_id, client_secret=client_secret, ) class OAuth2(SecurityBase): def __init__( self, *, flows: Annotated[ OAuthFlowsModel | dict[str, dict[str, Any]], Doc( """ The dictionary of OAuth2 flows. """ ), ] = OAuthFlowsModel(), scheme_name: Annotated[ str | None, Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ str | None, Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if no HTTP Authorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Authorization header is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, with OAuth2 or in a cookie). """ ), ] = True, ): self.model = OAuth2Model( flows=cast(OAuthFlowsModel, flows), description=description ) self.scheme_name = scheme_name or self.__class__.__name__ self.auto_error = auto_error def make_not_authenticated_error(self) -> HTTPException: return HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated", headers={"WWW-Authenticate": "Bearer"}, ) async def __call__(self, request: Request) -> str | None: authorization = request.headers.get("Authorization") if not authorization: if self.auto_error: raise self.make_not_authenticated_error() else: return None return authorization class OAuth2PasswordBearer(OAuth2): def __init__( self, tokenUrl: Annotated[ str, Doc( """ The URL to obtain the OAuth2 token. This would be the *path operation* that has `OAuth2PasswordRequestForm` as a dependency. Read more about it in the [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). """ ), ], scheme_name: Annotated[ str | None, Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, scopes: Annotated[ dict[str, str] | None, Doc( """ The OAuth2 scopes that would be required by the *path operations* that use this dependency. Read more about it in the [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). """ ), ] = None, description: Annotated[ str | None, Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if no HTTP Authorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Authorization header is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, with OAuth2 or in a cookie). """ ), ] = True, refreshUrl: Annotated[ str | None, Doc( """ The URL to refresh the token and obtain a new one. """ ), ] = None, ): if not scopes: scopes = {} flows = OAuthFlowsModel( password=cast( Any, { "tokenUrl": tokenUrl, "refreshUrl": refreshUrl, "scopes": scopes, }, ) ) super().__init__( flows=flows, scheme_name=scheme_name, description=description, auto_error=auto_error, ) async def __call__(self, request: Request) -> str | None: authorization = request.headers.get("Authorization") scheme, param = get_authorization_scheme_param(authorization) if not authorization or scheme.lower() != "bearer": if self.auto_error: raise self.make_not_authenticated_error() else: return None return param class OAuth2AuthorizationCodeBearer(OAuth2): def __init__( self, authorizationUrl: str, tokenUrl: Annotated[ str, Doc( """ The URL to obtain the OAuth2 token. """ ), ], refreshUrl: Annotated[ str | None, Doc( """ The URL to refresh the token and obtain a new one. """ ), ] = None, scheme_name: Annotated[ str | None, Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, scopes: Annotated[ dict[str, str] | None, Doc( """ The OAuth2 scopes that would be required by the *path operations* that use this dependency. """ ), ] = None, description: Annotated[ str | None, Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if no HTTP Authorization header is provided, required for OAuth2 authentication, it will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Authorization header is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, with OAuth2 or in a cookie). """ ), ] = True, ): if not scopes: scopes = {} flows = OAuthFlowsModel( authorizationCode=cast( Any, { "authorizationUrl": authorizationUrl, "tokenUrl": tokenUrl, "refreshUrl": refreshUrl, "scopes": scopes, }, ) ) super().__init__( flows=flows, scheme_name=scheme_name, description=description, auto_error=auto_error, ) async def __call__(self, request: Request) -> str | None: authorization = request.headers.get("Authorization") scheme, param = get_authorization_scheme_param(authorization) if not authorization or scheme.lower() != "bearer": if self.auto_error: raise self.make_not_authenticated_error() else: return None # pragma: nocover return param class SecurityScopes: def __init__( self, scopes: Annotated[ list[str] | None, Doc( """ This will be filled by FastAPI. """ ), ] = None, ): self.scopes: Annotated[ list[str], Doc( """ The list of all the scopes required by dependencies. """ ), ] = scopes or [] self.scope_str: Annotated[ str, Doc( """ All the scopes required by all the dependencies in a single string separated by spaces, as defined in the OAuth2 specification. """ ), ] = " ".join(self.scopes)
--- +++ @@ -12,6 +12,49 @@ class OAuth2PasswordRequestForm: + """ + This is a dependency class to collect the `username` and `password` as form data + for an OAuth2 password flow. + + The OAuth2 specification dictates that for a password flow the data should be + collected using form data (instead of JSON) and that it should have the specific + fields `username` and `password`. + + All the initialization parameters are extracted from the request. + + Read more about it in the + [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + from fastapi.security import OAuth2PasswordRequestForm + + app = FastAPI() + + + @app.post("/login") + def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): + data = {} + data["scopes"] = [] + for scope in form_data.scopes: + data["scopes"].append(scope) + if form_data.client_id: + data["client_id"] = form_data.client_id + if form_data.client_secret: + data["client_secret"] = form_data.client_secret + return data + ``` + + Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. + You could have custom internal logic to separate it by colon characters (`:`) or + similar, and get the two parts `items` and `read`. Many applications do that to + group and organize permissions, you could do it as well in your application, just + know that it is application specific, it's not part of the specification. + """ def __init__( self, @@ -117,6 +160,68 @@ class OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm): + """ + This is a dependency class to collect the `username` and `password` as form data + for an OAuth2 password flow. + + The OAuth2 specification dictates that for a password flow the data should be + collected using form data (instead of JSON) and that it should have the specific + fields `username` and `password`. + + All the initialization parameters are extracted from the request. + + The only difference between `OAuth2PasswordRequestFormStrict` and + `OAuth2PasswordRequestForm` is that `OAuth2PasswordRequestFormStrict` requires the + client to send the form field `grant_type` with the value `"password"`, which + is required in the OAuth2 specification (it seems that for no particular reason), + while for `OAuth2PasswordRequestForm` `grant_type` is optional. + + Read more about it in the + [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + from fastapi.security import OAuth2PasswordRequestForm + + app = FastAPI() + + + @app.post("/login") + def login(form_data: Annotated[OAuth2PasswordRequestFormStrict, Depends()]): + data = {} + data["scopes"] = [] + for scope in form_data.scopes: + data["scopes"].append(scope) + if form_data.client_id: + data["client_id"] = form_data.client_id + if form_data.client_secret: + data["client_secret"] = form_data.client_secret + return data + ``` + + Note that for OAuth2 the scope `items:read` is a single scope in an opaque string. + You could have custom internal logic to separate it by colon characters (`:`) or + similar, and get the two parts `items` and `read`. Many applications do that to + group and organize permissions, you could do it as well in your application, just + know that it is application specific, it's not part of the specification. + + + grant_type: the OAuth2 spec says it is required and MUST be the fixed string "password". + This dependency is strict about it. If you want to be permissive, use instead the + OAuth2PasswordRequestForm dependency class. + username: username string. The OAuth2 spec requires the exact field name "username". + password: password string. The OAuth2 spec requires the exact field name "password". + scope: Optional string. Several scopes (each one a string) separated by spaces. E.g. + "items:read items:write users:read profile openid" + client_id: optional string. OAuth2 recommends sending the client_id and client_secret (if any) + using HTTP Basic auth, as: client_id:client_secret + client_secret: optional string. OAuth2 recommends sending the client_id and client_secret (if any) + using HTTP Basic auth, as: client_id:client_secret + """ def __init__( self, @@ -223,6 +328,17 @@ class OAuth2(SecurityBase): + """ + This is the base class for OAuth2 authentication, an instance of it would be used + as a dependency. All other OAuth2 classes inherit from it and customize it for + each OAuth2 flow. + + You normally would not create a new class inheriting from it but use one of the + existing subclasses, and maybe compose them if you want to support multiple flows. + + Read more about it in the + [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/). + """ def __init__( self, @@ -283,6 +399,21 @@ self.auto_error = auto_error def make_not_authenticated_error(self) -> HTTPException: + """ + The OAuth 2 specification doesn't define the challenge that should be used, + because a `Bearer` token is not really the only option to authenticate. + + But declaring any other authentication challenge would be application-specific + as it's not defined in the specification. + + For practical reasons, this method uses the `Bearer` challenge by default, as + it's probably the most common one. + + If you are implementing an OAuth2 authentication scheme other than the provided + ones in FastAPI (based on bearer tokens), you might want to override this. + + Ref: https://datatracker.ietf.org/doc/html/rfc6749 + """ return HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated", @@ -300,6 +431,13 @@ class OAuth2PasswordBearer(OAuth2): + """ + OAuth2 flow for authentication using a bearer token obtained with a password. + An instance of it would be used as a dependency. + + Read more about it in the + [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/). + """ def __init__( self, @@ -407,6 +545,10 @@ class OAuth2AuthorizationCodeBearer(OAuth2): + """ + OAuth2 flow for authentication using a bearer token obtained with an OAuth2 code + flow. An instance of it would be used as a dependency. + """ def __init__( self, @@ -509,6 +651,17 @@ class SecurityScopes: + """ + This is a special class that you can define in a parameter in a dependency to + obtain the OAuth2 scopes required by all the dependencies in the same chain. + + This way, multiple dependencies can have different scopes, even when used in the + same *path operation*. And with this, you can access all the scopes required in + all those dependencies in a single place. + + Read more about it in the + [FastAPI docs for OAuth2 scopes](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/). + """ def __init__( self, @@ -537,4 +690,4 @@ separated by spaces, as defined in the OAuth2 specification. """ ), - ] = " ".join(self.scopes)+ ] = " ".join(self.scopes)
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/security/oauth2.py
Write docstrings for this repository
import json import logging import os import re import shutil import subprocess from html.parser import HTMLParser from http.server import HTTPServer, SimpleHTTPRequestHandler from multiprocessing import Pool from pathlib import Path from typing import Any import mkdocs.utils import typer import yaml from jinja2 import Template from ruff.__main__ import find_ruff_bin from slugify import slugify as py_slugify logging.basicConfig(level=logging.INFO) SUPPORTED_LANGS = { "de", "en", "es", "fr", "ja", "ko", "pt", "ru", "tr", "uk", "zh", "zh-hant", } app = typer.Typer() mkdocs_name = "mkdocs.yml" missing_translation_snippet = """ {!../../docs/missing-translation.md!} """ non_translated_sections = ( f"reference{os.sep}", "release-notes.md", "fastapi-people.md", "external-links.md", "newsletter.md", "management-tasks.md", "management.md", "contributing.md", ) docs_path = Path("docs") en_docs_path = Path("docs/en") en_config_path: Path = en_docs_path / mkdocs_name site_path = Path("site").absolute() build_site_path = Path("site_build").absolute() header_pattern = re.compile(r"^(#{1,6}) (.+?)(?:\s*\{\s*(#.*)\s*\})?\s*$") header_with_permalink_pattern = re.compile(r"^(#{1,6}) (.+?)(\s*\{\s*#.*\s*\})\s*$") code_block3_pattern = re.compile(r"^\s*```") code_block4_pattern = re.compile(r"^\s*````") # Pattern to match markdown links: [text](url) → text md_link_pattern = re.compile(r"\[([^\]]+)\]\([^)]+\)") def strip_markdown_links(text: str) -> str: return md_link_pattern.sub(r"\1", text) class VisibleTextExtractor(HTMLParser): def __init__(self): super().__init__() self.text_parts = [] def handle_data(self, data): self.text_parts.append(data) def extract_visible_text(self, html: str) -> str: self.reset() self.text_parts = [] self.feed(html) return "".join(self.text_parts).strip() def slugify(text: str) -> str: return py_slugify( text, replacements=[ ("`", ""), # `dict`s -> dicts ("'s", "s"), # it's -> its ("'t", "t"), # don't -> dont ("**", ""), # **FastAPI**s -> FastAPIs ], ) def get_en_config() -> dict[str, Any]: return mkdocs.utils.yaml_load(en_config_path.read_text(encoding="utf-8")) def get_lang_paths() -> list[Path]: return sorted(docs_path.iterdir()) def lang_callback(lang: str | None) -> str | None: if lang is None: return None lang = lang.lower() return lang def complete_existing_lang(incomplete: str): lang_path: Path for lang_path in get_lang_paths(): if lang_path.is_dir() and lang_path.name.startswith(incomplete): yield lang_path.name @app.callback() def callback() -> None: # For MacOS with Cairo os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = "/opt/homebrew/lib" @app.command() def new_lang(lang: str = typer.Argument(..., callback=lang_callback)): new_path: Path = Path("docs") / lang if new_path.exists(): typer.echo(f"The language was already created: {lang}") raise typer.Abort() new_path.mkdir() new_config_path: Path = Path(new_path) / mkdocs_name new_config_path.write_text("INHERIT: ../en/mkdocs.yml\n", encoding="utf-8") new_llm_prompt_path: Path = new_path / "llm-prompt.md" new_llm_prompt_path.write_text("", encoding="utf-8") print(f"Successfully initialized: {new_path}") update_languages() @app.command() def build_lang( lang: str = typer.Argument( ..., callback=lang_callback, autocompletion=complete_existing_lang ), ) -> None: lang_path: Path = Path("docs") / lang if not lang_path.is_dir(): typer.echo(f"The language translation doesn't seem to exist yet: {lang}") raise typer.Abort() typer.echo(f"Building docs for: {lang}") build_site_dist_path = build_site_path / lang if lang == "en": dist_path = site_path # Don't remove en dist_path as it might already contain other languages. # When running build_all(), that function already removes site_path. # All this is only relevant locally, on GitHub Actions all this is done through # artifacts and multiple workflows, so it doesn't matter if directories are # removed or not. else: dist_path = site_path / lang shutil.rmtree(dist_path, ignore_errors=True) current_dir = os.getcwd() os.chdir(lang_path) shutil.rmtree(build_site_dist_path, ignore_errors=True) subprocess.run(["mkdocs", "build", "--site-dir", build_site_dist_path], check=True) shutil.copytree(build_site_dist_path, dist_path, dirs_exist_ok=True) os.chdir(current_dir) typer.secho(f"Successfully built docs for: {lang}", color=typer.colors.GREEN) index_sponsors_template = """ ### Keystone Sponsor {% for sponsor in sponsors.keystone -%} <a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a> {% endfor %} ### Gold and Silver Sponsors {% for sponsor in sponsors.gold -%} <a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a> {% endfor -%} {%- for sponsor in sponsors.silver -%} <a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}"></a> {% endfor %} """ def remove_header_permalinks(content: str): lines: list[str] = [] for line in content.split("\n"): match = header_with_permalink_pattern.match(line) if match: hashes, title, *_ = match.groups() line = f"{hashes} {title}" lines.append(line) return "\n".join(lines) def generate_readme_content() -> str: en_index = en_docs_path / "docs" / "index.md" content = en_index.read_text("utf-8") content = remove_header_permalinks(content) # remove permalinks from headers match_pre = re.search(r"</style>\n\n", content) match_start = re.search(r"<!-- sponsors -->", content) match_end = re.search(r"<!-- /sponsors -->", content) sponsors_data_path = en_docs_path / "data" / "sponsors.yml" sponsors = mkdocs.utils.yaml_load(sponsors_data_path.read_text(encoding="utf-8")) if not (match_start and match_end): raise RuntimeError("Couldn't auto-generate sponsors section") if not match_pre: raise RuntimeError("Couldn't find pre section (<style>) in index.md") frontmatter_end = match_pre.end() pre_end = match_start.end() post_start = match_end.start() template = Template(index_sponsors_template) message = template.render(sponsors=sponsors) pre_content = content[frontmatter_end:pre_end] post_content = content[post_start:] new_content = pre_content + message + post_content # Remove content between <!-- only-mkdocs --> and <!-- /only-mkdocs --> new_content = re.sub( r"<!-- only-mkdocs -->.*?<!-- /only-mkdocs -->", "", new_content, flags=re.DOTALL, ) return new_content @app.command() def generate_readme() -> None: readme_path = Path("README.md") old_content = readme_path.read_text("utf-8") new_content = generate_readme_content() if new_content != old_content: print("README.md outdated from the latest index.md") print("Updating README.md") readme_path.write_text(new_content, encoding="utf-8") raise typer.Exit(1) print("README.md is up to date ✅") @app.command() def build_all() -> None: update_languages() shutil.rmtree(site_path, ignore_errors=True) langs = [ lang.name for lang in get_lang_paths() if (lang.is_dir() and lang.name in SUPPORTED_LANGS) ] cpu_count = os.cpu_count() or 1 process_pool_size = cpu_count * 4 typer.echo(f"Using process pool size: {process_pool_size}") with Pool(process_pool_size) as p: p.map(build_lang, langs) @app.command() def update_languages() -> None: old_config = get_en_config() updated_config = get_updated_config_content() if old_config != updated_config: print("docs/en/mkdocs.yml outdated") print("Updating docs/en/mkdocs.yml") en_config_path.write_text( yaml.dump(updated_config, sort_keys=False, width=200, allow_unicode=True), encoding="utf-8", ) raise typer.Exit(1) print("docs/en/mkdocs.yml is up to date ✅") @app.command() def serve() -> None: typer.echo("Warning: this is a very simple server.") typer.echo("For development, use the command live instead.") typer.echo("This is here only to preview a site with translations already built.") typer.echo("Make sure you run the build-all command first.") os.chdir("site") server_address = ("", 8008) server = HTTPServer(server_address, SimpleHTTPRequestHandler) typer.echo("Serving at: http://127.0.0.1:8008") server.serve_forever() @app.command() def live( lang: str = typer.Argument( None, callback=lang_callback, autocompletion=complete_existing_lang ), dirty: bool = False, ) -> None: # Enable line numbers during local development to make it easier to highlight if lang is None: lang = "en" lang_path: Path = docs_path / lang # Enable line numbers during local development to make it easier to highlight args = ["mkdocs", "serve", "--dev-addr", "127.0.0.1:8008"] if dirty: args.append("--dirty") subprocess.run( args, env={**os.environ, "LINENUMS": "true"}, cwd=lang_path, check=True ) def get_updated_config_content() -> dict[str, Any]: config = get_en_config() languages = [{"en": "/"}] new_alternate: list[dict[str, str]] = [] # Language names sourced from https://quickref.me/iso-639-1 # Contributors may wish to update or change these, e.g. to fix capitalization. language_names_path = Path(__file__).parent / "../docs/language_names.yml" local_language_names: dict[str, str] = mkdocs.utils.yaml_load( language_names_path.read_text(encoding="utf-8") ) for lang_path in get_lang_paths(): if lang_path.name in {"en", "em"} or not lang_path.is_dir(): continue if lang_path.name not in SUPPORTED_LANGS: # Skip languages that are not yet ready continue code = lang_path.name languages.append({code: f"/{code}/"}) for lang_dict in languages: code = list(lang_dict.keys())[0] url = lang_dict[code] if code not in local_language_names: print( f"Missing language name for: {code}, " "update it in docs/language_names.yml" ) raise typer.Abort() use_name = f"{code} - {local_language_names[code]}" new_alternate.append({"link": url, "name": use_name}) config["extra"]["alternate"] = new_alternate return config @app.command() def ensure_non_translated() -> None: print("Ensuring no non translated pages") lang_paths = get_lang_paths() error_paths = [] for lang in lang_paths: if lang.name == "en": continue for non_translatable in non_translated_sections: non_translatable_path = lang / "docs" / non_translatable if non_translatable_path.exists(): error_paths.append(non_translatable_path) if error_paths: print("Non-translated pages found, removing them:") for error_path in error_paths: print(error_path) if error_path.is_file(): error_path.unlink() else: shutil.rmtree(error_path) raise typer.Exit(1) print("No non-translated pages found ✅") @app.command() def langs_json(): langs = [] for lang_path in get_lang_paths(): if lang_path.is_dir() and lang_path.name in SUPPORTED_LANGS: langs.append(lang_path.name) print(json.dumps(langs)) @app.command() def generate_docs_src_versions_for_file(file_path: Path) -> None: target_versions = ["py39", "py310"] full_path_str = str(file_path) for target_version in target_versions: if f"_{target_version}" in full_path_str: logging.info( f"Skipping {file_path}, already a version file for {target_version}" ) return base_content = file_path.read_text(encoding="utf-8") previous_content = {base_content} for target_version in target_versions: version_result = subprocess.run( [ find_ruff_bin(), "check", "--target-version", target_version, "--fix", "--unsafe-fixes", "-", ], input=base_content.encode("utf-8"), capture_output=True, ) content_target = version_result.stdout.decode("utf-8") format_result = subprocess.run( [find_ruff_bin(), "format", "-"], input=content_target.encode("utf-8"), capture_output=True, ) content_format = format_result.stdout.decode("utf-8") if content_format in previous_content: continue previous_content.add(content_format) # Determine where the version label should go: in the parent directory # name or in the file name, matching the source structure. label_in_parent = False for v in target_versions: if f"_{v}" in file_path.parent.name: label_in_parent = True break if label_in_parent: parent_name = file_path.parent.name for v in target_versions: parent_name = parent_name.replace(f"_{v}", "") new_parent = file_path.parent.parent / f"{parent_name}_{target_version}" new_parent.mkdir(parents=True, exist_ok=True) version_file = new_parent / file_path.name else: base_name = file_path.stem for v in target_versions: if base_name.endswith(f"_{v}"): base_name = base_name[: -len(f"_{v}")] break version_file = file_path.with_name(f"{base_name}_{target_version}.py") logging.info(f"Writing to {version_file}") version_file.write_text(content_format, encoding="utf-8") @app.command() def generate_docs_src_versions() -> None: docs_src_path = Path("docs_src") for py_file in sorted(docs_src_path.rglob("*.py")): generate_docs_src_versions_for_file(py_file) @app.command() def copy_py39_to_py310() -> None: docs_src_path = Path("docs_src") # Handle directory-level labels (e.g. app_b_an_py39/) for dir_path in sorted(docs_src_path.rglob("*_py39")): if not dir_path.is_dir(): continue py310_dir = dir_path.parent / dir_path.name.replace("_py39", "_py310") if py310_dir.exists(): continue logging.info(f"Copying directory {dir_path} -> {py310_dir}") shutil.copytree(dir_path, py310_dir) # Handle file-level labels (e.g. tutorial001_py39.py) for file_path in sorted(docs_src_path.rglob("*_py39.py")): if not file_path.is_file(): continue # Skip files inside _py39 directories (already handled above) if "_py39" in file_path.parent.name: continue py310_file = file_path.with_name( file_path.name.replace("_py39.py", "_py310.py") ) if py310_file.exists(): continue logging.info(f"Copying file {file_path} -> {py310_file}") shutil.copy2(file_path, py310_file) @app.command() def update_docs_includes_py39_to_py310() -> None: include_pattern = re.compile(r"\{[^}]*docs_src/[^}]*_py39[^}]*\.py[^}]*\}") count = 0 for md_file in sorted(en_docs_path.rglob("*.md")): content = md_file.read_text(encoding="utf-8") if "_py39" not in content: continue new_content = include_pattern.sub( lambda m: m.group(0).replace("_py39", "_py310"), content ) if new_content != content: md_file.write_text(new_content, encoding="utf-8") count += 1 logging.info(f"Updated includes in {md_file}") print(f"Updated {count} file(s) ✅") @app.command() def remove_unused_docs_src() -> None: docs_src_path = Path("docs_src") # Collect all docs .md content referencing docs_src all_docs_content = "" for md_file in docs_path.rglob("*.md"): all_docs_content += md_file.read_text(encoding="utf-8") # Build a set of directory-based package roots (e.g. docs_src/bigger_applications/app_py39) # where at least one file is referenced in docs. All files in these directories # should be kept since they may be internally imported by the referenced files. used_package_dirs: set[Path] = set() for py_file in docs_src_path.rglob("*.py"): if py_file.name == "__init__.py": continue rel_path = str(py_file) if rel_path in all_docs_content: # Walk up from the file's parent to find the package root # (a subdirectory under docs_src/<topic>/) parts = py_file.relative_to(docs_src_path).parts if len(parts) > 2: # File is inside a sub-package like docs_src/topic/app_xxx/... package_root = docs_src_path / parts[0] / parts[1] used_package_dirs.add(package_root) removed = 0 for py_file in sorted(docs_src_path.rglob("*.py")): if py_file.name == "__init__.py": continue # Build the relative path as it appears in includes (e.g. docs_src/first_steps/tutorial001.py) rel_path = str(py_file) if rel_path in all_docs_content: continue # If this file is inside a directory-based package where any sibling is # referenced, keep it (it's likely imported internally). parts = py_file.relative_to(docs_src_path).parts if len(parts) > 2: package_root = docs_src_path / parts[0] / parts[1] if package_root in used_package_dirs: continue # Check if the _an counterpart (or non-_an counterpart) is referenced. # If either variant is included, keep both. # Handle both file-level _an (tutorial001_an.py) and directory-level _an # (app_an/main.py) counterpart_found = False full_path_str = str(py_file) if "_an" in py_file.stem: # This is an _an file, check if the non-_an version is referenced counterpart = full_path_str.replace( f"/{py_file.stem}", f"/{py_file.stem.replace('_an', '', 1)}" ) if counterpart in all_docs_content: counterpart_found = True else: # This is a non-_an file, check if there's an _an version referenced # Insert _an before any version suffix or at the end of the stem stem = py_file.stem for suffix in ("_py39", "_py310"): if suffix in stem: an_stem = stem.replace(suffix, f"_an{suffix}", 1) break else: an_stem = f"{stem}_an" counterpart = full_path_str.replace(f"/{stem}.", f"/{an_stem}.") if counterpart in all_docs_content: counterpart_found = True # Also check directory-level _an counterparts if not counterpart_found: parent_name = py_file.parent.name if "_an" in parent_name: counterpart_parent = parent_name.replace("_an", "", 1) counterpart_dir = str(py_file).replace( f"/{parent_name}/", f"/{counterpart_parent}/" ) if counterpart_dir in all_docs_content: counterpart_found = True else: # Try inserting _an into parent directory name for suffix in ("_py39", "_py310"): if suffix in parent_name: an_parent = parent_name.replace(suffix, f"_an{suffix}", 1) break else: an_parent = f"{parent_name}_an" counterpart_dir = str(py_file).replace( f"/{parent_name}/", f"/{an_parent}/" ) if counterpart_dir in all_docs_content: counterpart_found = True if counterpart_found: continue logging.info(f"Removing unused file: {py_file}") py_file.unlink() removed += 1 # Clean up directories that are empty or only contain __init__.py / __pycache__ for dir_path in sorted(docs_src_path.rglob("*"), reverse=True): if not dir_path.is_dir(): continue remaining = [ f for f in dir_path.iterdir() if f.name != "__pycache__" and f.name != "__init__.py" ] if not remaining: logging.info(f"Removing empty/init-only directory: {dir_path}") shutil.rmtree(dir_path) print(f"Removed {removed} unused file(s) ✅") @app.command() def add_permalinks_page(path: Path, update_existing: bool = False): if not path.is_relative_to(en_docs_path / "docs"): raise RuntimeError(f"Path must be inside {en_docs_path}") rel_path = path.relative_to(en_docs_path / "docs") # Skip excluded sections if str(rel_path).startswith(non_translated_sections): return visible_text_extractor = VisibleTextExtractor() updated_lines = [] in_code_block3 = False in_code_block4 = False permalinks = set() with path.open("r", encoding="utf-8") as f: lines = f.readlines() for line in lines: # Handle codeblocks start and end if not (in_code_block3 or in_code_block4): if code_block4_pattern.match(line): in_code_block4 = True elif code_block3_pattern.match(line): in_code_block3 = True else: if in_code_block4 and code_block4_pattern.match(line): in_code_block4 = False elif in_code_block3 and code_block3_pattern.match(line): in_code_block3 = False # Process Headers only outside codeblocks if not (in_code_block3 or in_code_block4): match = header_pattern.match(line) if match: hashes, title, _permalink = match.groups() if (not _permalink) or update_existing: slug = slugify( visible_text_extractor.extract_visible_text( strip_markdown_links(title) ) ) if slug in permalinks: # If the slug is already used, append a number to make it unique count = 1 original_slug = slug while slug in permalinks: slug = f"{original_slug}_{count}" count += 1 permalinks.add(slug) line = f"{hashes} {title} {{ #{slug} }}\n" updated_lines.append(line) with path.open("w", encoding="utf-8") as f: f.writelines(updated_lines) @app.command() def add_permalinks_pages(pages: list[Path], update_existing: bool = False) -> None: for md_file in pages: add_permalinks_page(md_file, update_existing=update_existing) @app.command() def add_permalinks(update_existing: bool = False) -> None: for md_file in en_docs_path.rglob("*.md"): add_permalinks_page(md_file, update_existing=update_existing) if __name__ == "__main__": app()
--- +++ @@ -71,10 +71,12 @@ def strip_markdown_links(text: str) -> str: + """Replace markdown links with just their visible text.""" return md_link_pattern.sub(r"\1", text) class VisibleTextExtractor(HTMLParser): + """Extract visible text from a string with HTML tags.""" def __init__(self): super().__init__() @@ -132,6 +134,9 @@ @app.command() def new_lang(lang: str = typer.Argument(..., callback=lang_callback)): + """ + Generate a new docs translation directory for the language LANG. + """ new_path: Path = Path("docs") / lang if new_path.exists(): typer.echo(f"The language was already created: {lang}") @@ -151,6 +156,9 @@ ..., callback=lang_callback, autocompletion=complete_existing_lang ), ) -> None: + """ + Build the docs for a language. + """ lang_path: Path = Path("docs") / lang if not lang_path.is_dir(): typer.echo(f"The language translation doesn't seem to exist yet: {lang}") @@ -238,6 +246,9 @@ @app.command() def generate_readme() -> None: + """ + Generate README.md content from main index.md + """ readme_path = Path("README.md") old_content = readme_path.read_text("utf-8") new_content = generate_readme_content() @@ -251,6 +262,10 @@ @app.command() def build_all() -> None: + """ + Build mkdocs site for en, and then build each language inside, end result is located + at directory ./site/ with each language inside. + """ update_languages() shutil.rmtree(site_path, ignore_errors=True) langs = [ @@ -267,6 +282,9 @@ @app.command() def update_languages() -> None: + """ + Update the mkdocs.yml file Languages section including all the available languages. + """ old_config = get_en_config() updated_config = get_updated_config_content() if old_config != updated_config: @@ -282,6 +300,15 @@ @app.command() def serve() -> None: + """ + A quick server to preview a built site with translations. + + For development, prefer the command live (or just mkdocs serve). + + This is here only to preview a site with translations already built. + + Make sure you run the build-all command first. + """ typer.echo("Warning: this is a very simple server.") typer.echo("For development, use the command live instead.") typer.echo("This is here only to preview a site with translations already built.") @@ -300,6 +327,15 @@ ), dirty: bool = False, ) -> None: + """ + Serve with livereload a docs site for a specific language. + + This only shows the actual translated files, not the placeholders created with + build-all. + + Takes an optional LANG argument with the name of the language to serve, by default + en. + """ # Enable line numbers during local development to make it easier to highlight if lang is None: lang = "en" @@ -348,6 +384,9 @@ @app.command() def ensure_non_translated() -> None: + """ + Ensure there are no files in the non translatable pages. + """ print("Ensuring no non translated pages") lang_paths = get_lang_paths() error_paths = [] @@ -442,6 +481,9 @@ @app.command() def generate_docs_src_versions() -> None: + """ + Generate Python version-specific files for all .py files in docs_src. + """ docs_src_path = Path("docs_src") for py_file in sorted(docs_src_path.rglob("*.py")): generate_docs_src_versions_for_file(py_file) @@ -449,6 +491,10 @@ @app.command() def copy_py39_to_py310() -> None: + """ + For each docs_src file/directory with a _py39 label that has no _py310 + counterpart, copy it with the _py310 label. + """ docs_src_path = Path("docs_src") # Handle directory-level labels (e.g. app_b_an_py39/) for dir_path in sorted(docs_src_path.rglob("*_py39")): @@ -477,6 +523,12 @@ @app.command() def update_docs_includes_py39_to_py310() -> None: + """ + Update .md files in docs/en/ to replace _py39 includes with _py310 versions. + + For each include line referencing a _py39 file or directory in docs_src, replace + the _py39 label with _py310. + """ include_pattern = re.compile(r"\{[^}]*docs_src/[^}]*_py39[^}]*\.py[^}]*\}") count = 0 for md_file in sorted(en_docs_path.rglob("*.md")): @@ -495,6 +547,9 @@ @app.command() def remove_unused_docs_src() -> None: + """ + Delete .py files in docs_src that are not included in any .md file under docs/. + """ docs_src_path = Path("docs_src") # Collect all docs .md content referencing docs_src all_docs_content = "" @@ -602,6 +657,9 @@ @app.command() def add_permalinks_page(path: Path, update_existing: bool = False): + """ + Add or update header permalinks in specific page of En docs. + """ if not path.is_relative_to(en_docs_path / "docs"): raise RuntimeError(f"Path must be inside {en_docs_path}") @@ -663,15 +721,21 @@ @app.command() def add_permalinks_pages(pages: list[Path], update_existing: bool = False) -> None: + """ + Add or update header permalinks in specific pages of En docs. + """ for md_file in pages: add_permalinks_page(md_file, update_existing=update_existing) @app.command() def add_permalinks(update_existing: bool = False) -> None: + """ + Add or update header permalinks in all pages of En docs. + """ for md_file in en_docs_path.rglob("*.md"): add_permalinks_page(md_file, update_existing=update_existing) if __name__ == "__main__": - app()+ app()
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/scripts/docs.py
Generate docstrings with parameter types
import re from typing import TypedDict CODE_INCLUDE_RE = re.compile(r"^\{\*\s*(\S+)\s*(.*)\*\}$") CODE_INCLUDE_PLACEHOLDER = "<CODE_INCLUDE>" HEADER_WITH_PERMALINK_RE = re.compile(r"^(#{1,6}) (.+?)(\s*\{\s*#.*\s*\})?\s*$") HEADER_LINE_RE = re.compile(r"^(#{1,6}) (.+?)(?:\s*\{\s*(#.*)\s*\})?\s*$") TIANGOLO_COM = "https://fastapi.tiangolo.com" ASSETS_URL_PREFIXES = ("/img/", "/css/", "/js/") MARKDOWN_LINK_RE = re.compile( r"(?<!\\)(?<!\!)" # not an image ![...] and not escaped \[...] r"\[(?P<text>.*?)\]" # link text (non-greedy) r"\(" r"(?P<url>[^)\s]+)" # url (no spaces and `)`) r'(?:\s+["\'](?P<title>.*?)["\'])?' # optional title in "" or '' r"\)" r"(?:\s*\{(?P<attrs>[^}]*)\})?" # optional attributes in {} ) HTML_LINK_RE = re.compile(r"<a\s+[^>]*>.*?</a>") HTML_LINK_TEXT_RE = re.compile(r"<a\b([^>]*)>(.*?)</a>") HTML_LINK_OPEN_TAG_RE = re.compile(r"<a\b([^>]*)>") HTML_ATTR_RE = re.compile(r'(\w+)\s*=\s*([\'"])(.*?)\2') CODE_BLOCK_LANG_RE = re.compile(r"^`{3,4}([\w-]*)", re.MULTILINE) SLASHES_COMMENT_RE = re.compile( r"^(?P<code>.*?)(?P<comment>(?:(?<= )// .*)|(?:^// .*))?$" ) HASH_COMMENT_RE = re.compile(r"^(?P<code>.*?)(?P<comment>(?:(?<= )# .*)|(?:^# .*))?$") class CodeIncludeInfo(TypedDict): line_no: int line: str class HeaderPermalinkInfo(TypedDict): line_no: int hashes: str title: str permalink: str class MarkdownLinkInfo(TypedDict): line_no: int url: str text: str title: str | None attributes: str | None full_match: str class HTMLLinkAttribute(TypedDict): name: str quote: str value: str class HtmlLinkInfo(TypedDict): line_no: int full_tag: str attributes: list[HTMLLinkAttribute] text: str class MultilineCodeBlockInfo(TypedDict): lang: str start_line_no: int content: list[str] # Code includes # -------------------------------------------------------------------------------------- def extract_code_includes(lines: list[str]) -> list[CodeIncludeInfo]: includes: list[CodeIncludeInfo] = [] for line_no, line in enumerate(lines, start=1): if CODE_INCLUDE_RE.match(line): includes.append(CodeIncludeInfo(line_no=line_no, line=line)) return includes def replace_code_includes_with_placeholders(text: list[str]) -> list[str]: modified_text = text.copy() includes = extract_code_includes(text) for include in includes: modified_text[include["line_no"] - 1] = CODE_INCLUDE_PLACEHOLDER return modified_text def replace_placeholders_with_code_includes( text: list[str], original_includes: list[CodeIncludeInfo] ) -> list[str]: code_include_lines = [ line_no for line_no, line in enumerate(text) if line.strip() == CODE_INCLUDE_PLACEHOLDER ] if len(code_include_lines) != len(original_includes): raise ValueError( "Number of code include placeholders does not match the number of code includes " "in the original document " f"({len(code_include_lines)} vs {len(original_includes)})" ) modified_text = text.copy() for i, line_no in enumerate(code_include_lines): modified_text[line_no] = original_includes[i]["line"] return modified_text # Header permalinks # -------------------------------------------------------------------------------------- def extract_header_permalinks(lines: list[str]) -> list[HeaderPermalinkInfo]: headers: list[HeaderPermalinkInfo] = [] in_code_block3 = False in_code_block4 = False for line_no, line in enumerate(lines, start=1): if not (in_code_block3 or in_code_block4): if line.startswith("```"): count = len(line) - len(line.lstrip("`")) if count == 3: in_code_block3 = True continue elif count >= 4: in_code_block4 = True continue header_match = HEADER_WITH_PERMALINK_RE.match(line) if header_match: hashes, title, permalink = header_match.groups() headers.append( HeaderPermalinkInfo( hashes=hashes, line_no=line_no, permalink=permalink, title=title ) ) elif in_code_block3: if line.startswith("```"): count = len(line) - len(line.lstrip("`")) if count == 3: in_code_block3 = False continue elif in_code_block4: if line.startswith("````"): count = len(line) - len(line.lstrip("`")) if count >= 4: in_code_block4 = False continue return headers def remove_header_permalinks(lines: list[str]) -> list[str]: modified_lines: list[str] = [] for line in lines: header_match = HEADER_WITH_PERMALINK_RE.match(line) if header_match: hashes, title, _permalink = header_match.groups() modified_line = f"{hashes} {title}" modified_lines.append(modified_line) else: modified_lines.append(line) return modified_lines def replace_header_permalinks( text: list[str], header_permalinks: list[HeaderPermalinkInfo], original_header_permalinks: list[HeaderPermalinkInfo], ) -> list[str]: modified_text: list[str] = text.copy() if len(header_permalinks) != len(original_header_permalinks): raise ValueError( "Number of headers with permalinks does not match the number in the " "original document " f"({len(header_permalinks)} vs {len(original_header_permalinks)})" ) for header_no in range(len(header_permalinks)): header_info = header_permalinks[header_no] original_header_info = original_header_permalinks[header_no] if header_info["hashes"] != original_header_info["hashes"]: raise ValueError( "Header levels do not match between document and original document" f" (found {header_info['hashes']}, expected {original_header_info['hashes']})" f" for header №{header_no + 1} in line {header_info['line_no']}" ) line_no = header_info["line_no"] - 1 hashes = header_info["hashes"] title = header_info["title"] permalink = original_header_info["permalink"] modified_text[line_no] = f"{hashes} {title}{permalink}" return modified_text # Markdown links # -------------------------------------------------------------------------------------- def extract_markdown_links(lines: list[str]) -> list[MarkdownLinkInfo]: links: list[MarkdownLinkInfo] = [] for line_no, line in enumerate(lines, start=1): for m in MARKDOWN_LINK_RE.finditer(line): links.append( MarkdownLinkInfo( line_no=line_no, url=m.group("url"), text=m.group("text"), title=m.group("title"), attributes=m.group("attrs"), full_match=m.group(0), ) ) return links def _add_lang_code_to_url(url: str, lang_code: str) -> str: if url.startswith(TIANGOLO_COM): rel_url = url[len(TIANGOLO_COM) :] if not rel_url.startswith(ASSETS_URL_PREFIXES): url = url.replace(TIANGOLO_COM, f"{TIANGOLO_COM}/{lang_code}") return url def _construct_markdown_link( url: str, text: str, title: str | None, attributes: str | None, lang_code: str, ) -> str: url = _add_lang_code_to_url(url, lang_code) if title: link = f'[{text}]({url} "{title}")' else: link = f"[{text}]({url})" if attributes: link += f"{{{attributes}}}" return link def replace_markdown_links( text: list[str], links: list[MarkdownLinkInfo], original_links: list[MarkdownLinkInfo], lang_code: str, ) -> list[str]: if len(links) != len(original_links): raise ValueError( "Number of markdown links does not match the number in the " "original document " f"({len(links)} vs {len(original_links)})" ) modified_text = text.copy() for i, link_info in enumerate(links): link_text = link_info["text"] link_title = link_info["title"] original_link_info = original_links[i] # Replace replacement_link = _construct_markdown_link( url=original_link_info["url"], text=link_text, title=link_title, attributes=original_link_info["attributes"], lang_code=lang_code, ) line_no = link_info["line_no"] - 1 modified_line = modified_text[line_no] modified_line = modified_line.replace( link_info["full_match"], replacement_link, 1 ) modified_text[line_no] = modified_line return modified_text # HTML links # -------------------------------------------------------------------------------------- def extract_html_links(lines: list[str]) -> list[HtmlLinkInfo]: links = [] for line_no, line in enumerate(lines, start=1): for html_link in HTML_LINK_RE.finditer(line): link_str = html_link.group(0) link_text_match = HTML_LINK_TEXT_RE.match(link_str) assert link_text_match is not None link_text = link_text_match.group(2) assert isinstance(link_text, str) link_open_tag_match = HTML_LINK_OPEN_TAG_RE.match(link_str) assert link_open_tag_match is not None link_open_tag = link_open_tag_match.group(1) assert isinstance(link_open_tag, str) attributes: list[HTMLLinkAttribute] = [] for attr_name, attr_quote, attr_value in re.findall( HTML_ATTR_RE, link_open_tag ): assert isinstance(attr_name, str) assert isinstance(attr_quote, str) assert isinstance(attr_value, str) attributes.append( HTMLLinkAttribute( name=attr_name, quote=attr_quote, value=attr_value ) ) links.append( HtmlLinkInfo( line_no=line_no, full_tag=link_str, attributes=attributes, text=link_text, ) ) return links def _construct_html_link( link_text: str, attributes: list[HTMLLinkAttribute], lang_code: str, ) -> str: attributes_upd: list[HTMLLinkAttribute] = [] for attribute in attributes: if attribute["name"] == "href": original_url = attribute["value"] url = _add_lang_code_to_url(original_url, lang_code) attributes_upd.append( HTMLLinkAttribute(name="href", quote=attribute["quote"], value=url) ) else: attributes_upd.append(attribute) attrs_str = " ".join( f"{attribute['name']}={attribute['quote']}{attribute['value']}{attribute['quote']}" for attribute in attributes_upd ) return f"<a {attrs_str}>{link_text}</a>" def replace_html_links( text: list[str], links: list[HtmlLinkInfo], original_links: list[HtmlLinkInfo], lang_code: str, ) -> list[str]: if len(links) != len(original_links): raise ValueError( "Number of HTML links does not match the number in the " "original document " f"({len(links)} vs {len(original_links)})" ) modified_text = text.copy() for link_index, link in enumerate(links): original_link_info = original_links[link_index] # Replace in the document text replacement_link = _construct_html_link( link_text=link["text"], attributes=original_link_info["attributes"], lang_code=lang_code, ) line_no = link["line_no"] - 1 modified_text[line_no] = modified_text[line_no].replace( link["full_tag"], replacement_link, 1 ) return modified_text # Multiline code blocks # -------------------------------------------------------------------------------------- def get_code_block_lang(line: str) -> str: match = CODE_BLOCK_LANG_RE.match(line) if match: return match.group(1) return "" def extract_multiline_code_blocks(text: list[str]) -> list[MultilineCodeBlockInfo]: blocks: list[MultilineCodeBlockInfo] = [] in_code_block3 = False in_code_block4 = False current_block_lang = "" current_block_start_line = -1 current_block_lines = [] for line_no, line in enumerate(text, start=1): stripped = line.lstrip() # --- Detect opening fence --- if not (in_code_block3 or in_code_block4): if stripped.startswith("```"): current_block_start_line = line_no count = len(stripped) - len(stripped.lstrip("`")) if count == 3: in_code_block3 = True current_block_lang = get_code_block_lang(stripped) current_block_lines = [line] continue elif count >= 4: in_code_block4 = True current_block_lang = get_code_block_lang(stripped) current_block_lines = [line] continue # --- Detect closing fence --- elif in_code_block3: if stripped.startswith("```"): count = len(stripped) - len(stripped.lstrip("`")) if count == 3: current_block_lines.append(line) blocks.append( MultilineCodeBlockInfo( lang=current_block_lang, start_line_no=current_block_start_line, content=current_block_lines, ) ) in_code_block3 = False current_block_lang = "" current_block_start_line = -1 current_block_lines = [] continue current_block_lines.append(line) elif in_code_block4: if stripped.startswith("````"): count = len(stripped) - len(stripped.lstrip("`")) if count >= 4: current_block_lines.append(line) blocks.append( MultilineCodeBlockInfo( lang=current_block_lang, start_line_no=current_block_start_line, content=current_block_lines, ) ) in_code_block4 = False current_block_lang = "" current_block_start_line = -1 current_block_lines = [] continue current_block_lines.append(line) return blocks def _split_hash_comment(line: str) -> tuple[str, str | None]: match = HASH_COMMENT_RE.match(line) if match: code = match.group("code").rstrip() comment = match.group("comment") return code, comment return line.rstrip(), None def _split_slashes_comment(line: str) -> tuple[str, str | None]: match = SLASHES_COMMENT_RE.match(line) if match: code = match.group("code").rstrip() comment = match.group("comment") return code, comment return line, None def replace_multiline_code_block( block_a: MultilineCodeBlockInfo, block_b: MultilineCodeBlockInfo ) -> list[str]: start_line = block_a["start_line_no"] end_line_no = start_line + len(block_a["content"]) - 1 if block_a["lang"] != block_b["lang"]: raise ValueError( f"Code block (lines {start_line}-{end_line_no}) " "has different language than the original block " f"('{block_a['lang']}' vs '{block_b['lang']}')" ) if len(block_a["content"]) != len(block_b["content"]): raise ValueError( f"Code block (lines {start_line}-{end_line_no}) " "has different number of lines than the original block " f"({len(block_a['content'])} vs {len(block_b['content'])})" ) block_language = block_a["lang"].lower() if block_language in {"mermaid"}: if block_a != block_b: print( f"Skipping mermaid code block replacement (lines {start_line}-{end_line_no}). " "This should be checked manually." ) return block_a["content"].copy() # We don't handle mermaid code blocks for now code_block: list[str] = [] for line_a, line_b in zip(block_a["content"], block_b["content"], strict=False): line_a_comment: str | None = None line_b_comment: str | None = None # Handle comments based on language if block_language in { "python", "py", "sh", "bash", "dockerfile", "requirements", "gitignore", "toml", "yaml", "yml", "hash-style-comments", }: _line_a_code, line_a_comment = _split_hash_comment(line_a) _line_b_code, line_b_comment = _split_hash_comment(line_b) res_line = line_b if line_b_comment: res_line = res_line.replace(line_b_comment, line_a_comment, 1) code_block.append(res_line) elif block_language in {"console", "json", "slash-style-comments"}: _line_a_code, line_a_comment = _split_slashes_comment(line_a) _line_b_code, line_b_comment = _split_slashes_comment(line_b) res_line = line_b if line_b_comment: res_line = res_line.replace(line_b_comment, line_a_comment, 1) code_block.append(res_line) else: code_block.append(line_b) return code_block def replace_multiline_code_blocks_in_text( text: list[str], code_blocks: list[MultilineCodeBlockInfo], original_code_blocks: list[MultilineCodeBlockInfo], ) -> list[str]: if len(code_blocks) != len(original_code_blocks): raise ValueError( "Number of code blocks does not match the number in the original document " f"({len(code_blocks)} vs {len(original_code_blocks)})" ) modified_text = text.copy() for block, original_block in zip(code_blocks, original_code_blocks, strict=True): updated_content = replace_multiline_code_block(block, original_block) start_line_index = block["start_line_no"] - 1 for i, updated_line in enumerate(updated_content): modified_text[start_line_index + i] = updated_line return modified_text # All checks # -------------------------------------------------------------------------------------- def check_translation( doc_lines: list[str], en_doc_lines: list[str], lang_code: str, auto_fix: bool, path: str, ) -> list[str]: # Fix code includes en_code_includes = extract_code_includes(en_doc_lines) doc_lines_with_placeholders = replace_code_includes_with_placeholders(doc_lines) fixed_doc_lines = replace_placeholders_with_code_includes( doc_lines_with_placeholders, en_code_includes ) if auto_fix and (fixed_doc_lines != doc_lines): print(f"Fixing code includes in: {path}") doc_lines = fixed_doc_lines # Fix permalinks en_permalinks = extract_header_permalinks(en_doc_lines) doc_permalinks = extract_header_permalinks(doc_lines) fixed_doc_lines = replace_header_permalinks( doc_lines, doc_permalinks, en_permalinks ) if auto_fix and (fixed_doc_lines != doc_lines): print(f"Fixing header permalinks in: {path}") doc_lines = fixed_doc_lines # Fix markdown links en_markdown_links = extract_markdown_links(en_doc_lines) doc_markdown_links = extract_markdown_links(doc_lines) fixed_doc_lines = replace_markdown_links( doc_lines, doc_markdown_links, en_markdown_links, lang_code ) if auto_fix and (fixed_doc_lines != doc_lines): print(f"Fixing markdown links in: {path}") doc_lines = fixed_doc_lines # Fix HTML links en_html_links = extract_html_links(en_doc_lines) doc_html_links = extract_html_links(doc_lines) fixed_doc_lines = replace_html_links( doc_lines, doc_html_links, en_html_links, lang_code ) if auto_fix and (fixed_doc_lines != doc_lines): print(f"Fixing HTML links in: {path}") doc_lines = fixed_doc_lines # Fix multiline code blocks en_code_blocks = extract_multiline_code_blocks(en_doc_lines) doc_code_blocks = extract_multiline_code_blocks(doc_lines) fixed_doc_lines = replace_multiline_code_blocks_in_text( doc_lines, doc_code_blocks, en_code_blocks ) if auto_fix and (fixed_doc_lines != doc_lines): print(f"Fixing multiline code blocks in: {path}") doc_lines = fixed_doc_lines return doc_lines
--- +++ @@ -79,6 +79,13 @@ def extract_code_includes(lines: list[str]) -> list[CodeIncludeInfo]: + """ + Extract lines that contain code includes. + + Return list of CodeIncludeInfo, where each dict contains: + - `line_no` - line number (1-based) + - `line` - text of the line + """ includes: list[CodeIncludeInfo] = [] for line_no, line in enumerate(lines, start=1): @@ -88,6 +95,9 @@ def replace_code_includes_with_placeholders(text: list[str]) -> list[str]: + """ + Replace code includes with placeholders. + """ modified_text = text.copy() includes = extract_code_includes(text) @@ -99,6 +109,10 @@ def replace_placeholders_with_code_includes( text: list[str], original_includes: list[CodeIncludeInfo] ) -> list[str]: + """ + Replace code includes placeholders with actual code includes from the original (English) document. + Fail if the number of placeholders does not match the number of original includes. + """ code_include_lines = [ line_no @@ -125,6 +139,14 @@ def extract_header_permalinks(lines: list[str]) -> list[HeaderPermalinkInfo]: + """ + Extract list of header permalinks from the given lines. + + Return list of HeaderPermalinkInfo, where each dict contains: + - `line_no` - line number (1-based) + - `hashes` - string of hashes representing header level (e.g., "###") + - `permalink` - permalink string (e.g., "{#permalink}") + """ headers: list[HeaderPermalinkInfo] = [] in_code_block3 = False @@ -168,6 +190,9 @@ def remove_header_permalinks(lines: list[str]) -> list[str]: + """ + Remove permalinks from headers in the given lines. + """ modified_lines: list[str] = [] for line in lines: @@ -186,6 +211,11 @@ header_permalinks: list[HeaderPermalinkInfo], original_header_permalinks: list[HeaderPermalinkInfo], ) -> list[str]: + """ + Replace permalinks in the given text with the permalinks from the original document. + + Fail if the number or level of headers does not match the original. + """ modified_text: list[str] = text.copy() @@ -220,6 +250,15 @@ def extract_markdown_links(lines: list[str]) -> list[MarkdownLinkInfo]: + """ + Extract all markdown links from the given lines. + + Return list of MarkdownLinkInfo, where each dict contains: + - `line_no` - line number (1-based) + - `url` - link URL + - `text` - link text + - `title` - link title (if any) + """ links: list[MarkdownLinkInfo] = [] for line_no, line in enumerate(lines, start=1): @@ -252,6 +291,9 @@ attributes: str | None, lang_code: str, ) -> str: + """ + Construct a markdown link, adjusting the URL for the given language code if needed. + """ url = _add_lang_code_to_url(url, lang_code) if title: @@ -271,6 +313,11 @@ original_links: list[MarkdownLinkInfo], lang_code: str, ) -> list[str]: + """ + Replace markdown links in the given text with the original links. + + Fail if the number of links does not match the original. + """ if len(links) != len(original_links): raise ValueError( @@ -308,6 +355,15 @@ def extract_html_links(lines: list[str]) -> list[HtmlLinkInfo]: + """ + Extract all HTML links from the given lines. + + Return list of HtmlLinkInfo, where each dict contains: + - `line_no` - line number (1-based) + - `full_tag` - full HTML link tag + - `attributes` - list of HTMLLinkAttribute (name, quote, value) + - `text` - link text + """ links = [] for line_no, line in enumerate(lines, start=1): @@ -352,6 +408,9 @@ attributes: list[HTMLLinkAttribute], lang_code: str, ) -> str: + """ + Reconstruct HTML link, adjusting the URL for the given language code if needed. + """ attributes_upd: list[HTMLLinkAttribute] = [] for attribute in attributes: @@ -377,6 +436,12 @@ original_links: list[HtmlLinkInfo], lang_code: str, ) -> list[str]: + """ + Replace HTML links in the given text with the links from the original document. + + Adjust URLs for the given language code. + Fail if the number of links does not match the original. + """ if len(links) != len(original_links): raise ValueError( @@ -505,6 +570,12 @@ def replace_multiline_code_block( block_a: MultilineCodeBlockInfo, block_b: MultilineCodeBlockInfo ) -> list[str]: + """ + Replace multiline code block `a` with block `b` leaving comments intact. + + Syntax of comments depends on the language of the code block. + Raises ValueError if the blocks are not compatible (different languages or different number of lines). + """ start_line = block_a["start_line_no"] end_line_no = start_line + len(block_a["content"]) - 1 @@ -574,6 +645,12 @@ code_blocks: list[MultilineCodeBlockInfo], original_code_blocks: list[MultilineCodeBlockInfo], ) -> list[str]: + """ + Update each code block in `text` with the corresponding code block from + `original_code_blocks` with comments taken from `code_blocks`. + + Raises ValueError if the number, language, or shape of code blocks do not match. + """ if len(code_blocks) != len(original_code_blocks): raise ValueError( @@ -653,4 +730,4 @@ print(f"Fixing multiline code blocks in: {path}") doc_lines = fixed_doc_lines - return doc_lines+ return doc_lines
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/scripts/doc_parsing_utils.py
Add verbose docstrings with examples
import binascii from base64 import b64decode from typing import Annotated from annotated_doc import Doc from fastapi.exceptions import HTTPException from fastapi.openapi.models import HTTPBase as HTTPBaseModel from fastapi.openapi.models import HTTPBearer as HTTPBearerModel from fastapi.security.base import SecurityBase from fastapi.security.utils import get_authorization_scheme_param from pydantic import BaseModel from starlette.requests import Request from starlette.status import HTTP_401_UNAUTHORIZED class HTTPBasicCredentials(BaseModel): username: Annotated[str, Doc("The HTTP Basic username.")] password: Annotated[str, Doc("The HTTP Basic password.")] class HTTPAuthorizationCredentials(BaseModel): scheme: Annotated[ str, Doc( """ The HTTP authorization scheme extracted from the header value. """ ), ] credentials: Annotated[ str, Doc( """ The HTTP authorization credentials extracted from the header value. """ ), ] class HTTPBase(SecurityBase): model: HTTPBaseModel def __init__( self, *, scheme: str, scheme_name: str | None = None, description: str | None = None, auto_error: bool = True, ): self.model = HTTPBaseModel(scheme=scheme, description=description) self.scheme_name = scheme_name or self.__class__.__name__ self.auto_error = auto_error def make_authenticate_headers(self) -> dict[str, str]: return {"WWW-Authenticate": f"{self.model.scheme.title()}"} def make_not_authenticated_error(self) -> HTTPException: return HTTPException( status_code=HTTP_401_UNAUTHORIZED, detail="Not authenticated", headers=self.make_authenticate_headers(), ) async def __call__(self, request: Request) -> HTTPAuthorizationCredentials | None: authorization = request.headers.get("Authorization") scheme, credentials = get_authorization_scheme_param(authorization) if not (authorization and scheme and credentials): if self.auto_error: raise self.make_not_authenticated_error() else: return None return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials) class HTTPBasic(HTTPBase): def __init__( self, *, scheme_name: Annotated[ str | None, Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, realm: Annotated[ str | None, Doc( """ HTTP Basic authentication realm. """ ), ] = None, description: Annotated[ str | None, Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if the HTTP Basic authentication is not provided (a header), `HTTPBasic` will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Basic authentication is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in HTTP Basic authentication or in an HTTP Bearer token). """ ), ] = True, ): self.model = HTTPBaseModel(scheme="basic", description=description) self.scheme_name = scheme_name or self.__class__.__name__ self.realm = realm self.auto_error = auto_error def make_authenticate_headers(self) -> dict[str, str]: if self.realm: return {"WWW-Authenticate": f'Basic realm="{self.realm}"'} return {"WWW-Authenticate": "Basic"} async def __call__( # type: ignore self, request: Request ) -> HTTPBasicCredentials | None: authorization = request.headers.get("Authorization") scheme, param = get_authorization_scheme_param(authorization) if not authorization or scheme.lower() != "basic": if self.auto_error: raise self.make_not_authenticated_error() else: return None try: data = b64decode(param).decode("ascii") except (ValueError, UnicodeDecodeError, binascii.Error) as e: raise self.make_not_authenticated_error() from e username, separator, password = data.partition(":") if not separator: raise self.make_not_authenticated_error() return HTTPBasicCredentials(username=username, password=password) class HTTPBearer(HTTPBase): def __init__( self, *, bearerFormat: Annotated[str | None, Doc("Bearer token format.")] = None, scheme_name: Annotated[ str | None, Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ str | None, Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if the HTTP Bearer token is not provided (in an `Authorization` header), `HTTPBearer` will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Bearer token is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in an HTTP Bearer token or in a cookie). """ ), ] = True, ): self.model = HTTPBearerModel(bearerFormat=bearerFormat, description=description) self.scheme_name = scheme_name or self.__class__.__name__ self.auto_error = auto_error async def __call__(self, request: Request) -> HTTPAuthorizationCredentials | None: authorization = request.headers.get("Authorization") scheme, credentials = get_authorization_scheme_param(authorization) if not (authorization and scheme and credentials): if self.auto_error: raise self.make_not_authenticated_error() else: return None if scheme.lower() != "bearer": if self.auto_error: raise self.make_not_authenticated_error() else: return None return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials) class HTTPDigest(HTTPBase): def __init__( self, *, scheme_name: Annotated[ str | None, Doc( """ Security scheme name. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, description: Annotated[ str | None, Doc( """ Security scheme description. It will be included in the generated OpenAPI (e.g. visible at `/docs`). """ ), ] = None, auto_error: Annotated[ bool, Doc( """ By default, if the HTTP Digest is not provided, `HTTPDigest` will automatically cancel the request and send the client an error. If `auto_error` is set to `False`, when the HTTP Digest is not available, instead of erroring out, the dependency result will be `None`. This is useful when you want to have optional authentication. It is also useful when you want to have authentication that can be provided in one of multiple optional ways (for example, in HTTP Digest or in a cookie). """ ), ] = True, ): self.model = HTTPBaseModel(scheme="digest", description=description) self.scheme_name = scheme_name or self.__class__.__name__ self.auto_error = auto_error async def __call__(self, request: Request) -> HTTPAuthorizationCredentials | None: authorization = request.headers.get("Authorization") scheme, credentials = get_authorization_scheme_param(authorization) if not (authorization and scheme and credentials): if self.auto_error: raise self.make_not_authenticated_error() else: return None if scheme.lower() != "digest": if self.auto_error: raise self.make_not_authenticated_error() else: return None return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
--- +++ @@ -14,12 +14,39 @@ class HTTPBasicCredentials(BaseModel): + """ + The HTTP Basic credentials given as the result of using `HTTPBasic` in a + dependency. + + Read more about it in the + [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/). + """ username: Annotated[str, Doc("The HTTP Basic username.")] password: Annotated[str, Doc("The HTTP Basic password.")] class HTTPAuthorizationCredentials(BaseModel): + """ + The HTTP authorization credentials in the result of using `HTTPBearer` or + `HTTPDigest` in a dependency. + + The HTTP authorization header value is split by the first space. + + The first part is the `scheme`, the second part is the `credentials`. + + For example, in an HTTP Bearer token scheme, the client will send a header + like: + + ``` + Authorization: Bearer deadbeef12346 + ``` + + In this case: + + * `scheme` will have the value `"Bearer"` + * `credentials` will have the value `"deadbeef12346"` + """ scheme: Annotated[ str, @@ -76,6 +103,39 @@ class HTTPBasic(HTTPBase): + """ + HTTP Basic authentication. + + Ref: https://datatracker.ietf.org/doc/html/rfc7617 + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be an `HTTPBasicCredentials` object containing the + `username` and the `password`. + + Read more about it in the + [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/). + + ## Example + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + from fastapi.security import HTTPBasic, HTTPBasicCredentials + + app = FastAPI() + + security = HTTPBasic() + + + @app.get("/users/me") + def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]): + return {"username": credentials.username, "password": credentials.password} + ``` + """ def __init__( self, @@ -160,6 +220,36 @@ class HTTPBearer(HTTPBase): + """ + HTTP Bearer token authentication. + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be an `HTTPAuthorizationCredentials` object containing + the `scheme` and the `credentials`. + + ## Example + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer + + app = FastAPI() + + security = HTTPBearer() + + + @app.get("/users/me") + def read_current_user( + credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)] + ): + return {"scheme": credentials.scheme, "credentials": credentials.credentials} + ``` + """ def __init__( self, @@ -227,6 +317,42 @@ class HTTPDigest(HTTPBase): + """ + HTTP Digest authentication. + + **Warning**: this is only a stub to connect the components with OpenAPI in FastAPI, + but it doesn't implement the full Digest scheme, you would need to subclass it + and implement it in your code. + + Ref: https://datatracker.ietf.org/doc/html/rfc7616 + + ## Usage + + Create an instance object and use that object as the dependency in `Depends()`. + + The dependency result will be an `HTTPAuthorizationCredentials` object containing + the `scheme` and the `credentials`. + + ## Example + + ```python + from typing import Annotated + + from fastapi import Depends, FastAPI + from fastapi.security import HTTPAuthorizationCredentials, HTTPDigest + + app = FastAPI() + + security = HTTPDigest() + + + @app.get("/users/me") + def read_current_user( + credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)] + ): + return {"scheme": credentials.scheme, "credentials": credentials.credentials} + ``` + """ def __init__( self, @@ -288,4 +414,4 @@ raise self.make_not_authenticated_error() else: return None - return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)+ return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/security/http.py
Document all public functions with docstrings
from typing import Annotated, Any from annotated_doc import Doc from pydantic import AfterValidator, BaseModel, Field, model_validator from starlette.responses import StreamingResponse # Canonical SSE event schema matching the OpenAPI 3.2 spec # (Section 4.14.4 "Special Considerations for Server-Sent Events") _SSE_EVENT_SCHEMA: dict[str, Any] = { "type": "object", "properties": { "data": {"type": "string"}, "event": {"type": "string"}, "id": {"type": "string"}, "retry": {"type": "integer", "minimum": 0}, }, } class EventSourceResponse(StreamingResponse): media_type = "text/event-stream" def _check_id_no_null(v: str | None) -> str | None: if v is not None and "\0" in v: raise ValueError("SSE 'id' must not contain null characters") return v class ServerSentEvent(BaseModel): data: Annotated[ Any, Doc( """ The event payload. Can be any JSON-serializable value: a Pydantic model, dict, list, string, number, etc. It is **always** serialized to JSON: strings are quoted (`"hello"` becomes `data: "hello"` on the wire). Mutually exclusive with `raw_data`. """ ), ] = None raw_data: Annotated[ str | None, Doc( """ Raw string to send as the `data:` field **without** JSON encoding. Use this when you need to send pre-formatted text, HTML fragments, CSV lines, or any non-JSON payload. The string is placed directly into the `data:` field as-is. Mutually exclusive with `data`. """ ), ] = None event: Annotated[ str | None, Doc( """ Optional event type name. Maps to `addEventListener(event, ...)` on the browser. When omitted, the browser dispatches on the generic `message` event. """ ), ] = None id: Annotated[ str | None, AfterValidator(_check_id_no_null), Doc( """ Optional event ID. The browser sends this value back as the `Last-Event-ID` header on automatic reconnection. **Must not contain null (`\\0`) characters.** """ ), ] = None retry: Annotated[ int | None, Field(ge=0), Doc( """ Optional reconnection time in **milliseconds**. Tells the browser how long to wait before reconnecting after the connection is lost. Must be a non-negative integer. """ ), ] = None comment: Annotated[ str | None, Doc( """ Optional comment line(s). Comment lines start with `:` in the SSE wire format and are ignored by `EventSource` clients. Useful for keep-alive pings to prevent proxy/load-balancer timeouts. """ ), ] = None @model_validator(mode="after") def _check_data_exclusive(self) -> "ServerSentEvent": if self.data is not None and self.raw_data is not None: raise ValueError( "Cannot set both 'data' and 'raw_data' on the same " "ServerSentEvent. Use 'data' for JSON-serialized payloads " "or 'raw_data' for pre-formatted strings." ) return self def format_sse_event( *, data_str: Annotated[ str | None, Doc( """ Pre-serialized data string to use as the `data:` field. """ ), ] = None, event: Annotated[ str | None, Doc( """ Optional event type name (`event:` field). """ ), ] = None, id: Annotated[ str | None, Doc( """ Optional event ID (`id:` field). """ ), ] = None, retry: Annotated[ int | None, Doc( """ Optional reconnection time in milliseconds (`retry:` field). """ ), ] = None, comment: Annotated[ str | None, Doc( """ Optional comment line(s) (`:` prefix). """ ), ] = None, ) -> bytes: lines: list[str] = [] if comment is not None: for line in comment.splitlines(): lines.append(f": {line}") if event is not None: lines.append(f"event: {event}") if data_str is not None: for line in data_str.splitlines(): lines.append(f"data: {line}") if id is not None: lines.append(f"id: {id}") if retry is not None: lines.append(f"retry: {retry}") lines.append("") lines.append("") return "\n".join(lines).encode("utf-8") # Keep-alive comment, per the SSE spec recommendation KEEPALIVE_COMMENT = b": ping\n\n" # Seconds between keep-alive pings when a generator is idle. # Private but importable so tests can monkeypatch it. _PING_INTERVAL: float = 15.0
--- +++ @@ -18,6 +18,17 @@ class EventSourceResponse(StreamingResponse): + """Streaming response with `text/event-stream` media type. + + Use as `response_class=EventSourceResponse` on a *path operation* that uses `yield` + to enable Server Sent Events (SSE) responses. + + Works with **any HTTP method** (`GET`, `POST`, etc.), which makes it compatible + with protocols like MCP that stream SSE over `POST`. + + The actual encoding logic lives in the FastAPI routing layer. This class + serves mainly as a marker and sets the correct `Content-Type`. + """ media_type = "text/event-stream" @@ -29,6 +40,21 @@ class ServerSentEvent(BaseModel): + """Represents a single Server-Sent Event. + + When `yield`ed from a *path operation function* that uses + `response_class=EventSourceResponse`, each `ServerSentEvent` is encoded + into the [SSE wire format](https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream) + (`text/event-stream`). + + If you yield a plain object (dict, Pydantic model, etc.) instead, it is + automatically JSON-encoded and sent as the `data:` field. + + All `data` values **including plain strings** are JSON-serialized. + + For example, `data="hello"` produces `data: "hello"` on the wire (with + quotes). + """ data: Annotated[ Any, @@ -160,6 +186,10 @@ ), ] = None, ) -> bytes: + """Build SSE wire-format bytes from **pre-serialized** data. + + The result always ends with `\n\n` (the event terminator). + """ lines: list[str] = [] if comment is not None: @@ -189,4 +219,4 @@ # Seconds between keep-alive pings when a generator is idle. # Private but importable so tests can monkeypatch it. -_PING_INTERVAL: float = 15.0+_PING_INTERVAL: float = 15.0
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/sse.py
Document all endpoints with docstrings
import os from collections.abc import Iterable from pathlib import Path from typing import Annotated import typer from scripts.doc_parsing_utils import check_translation non_translated_sections = ( f"reference{os.sep}", "release-notes.md", "fastapi-people.md", "external-links.md", "newsletter.md", "management-tasks.md", "management.md", "contributing.md", ) cli = typer.Typer() @cli.callback() def callback(): pass def iter_all_lang_paths(lang_path_root: Path) -> Iterable[Path]: first_dirs = [ lang_path_root / "learn", lang_path_root / "tutorial", lang_path_root / "advanced", lang_path_root / "about", lang_path_root / "how-to", ] first_parent = lang_path_root yield from first_parent.glob("*.md") for dir_path in first_dirs: yield from dir_path.rglob("*.md") first_dirs_str = tuple(str(d) for d in first_dirs) for path in lang_path_root.rglob("*.md"): if str(path).startswith(first_dirs_str): continue if path.parent == first_parent: continue yield path def get_all_paths(lang: str): res: list[str] = [] lang_docs_root = Path("docs") / lang / "docs" for path in iter_all_lang_paths(lang_docs_root): relpath = path.relative_to(lang_docs_root) if not str(relpath).startswith(non_translated_sections): res.append(str(relpath)) return res def process_one_page(path: Path) -> bool: try: lang_code = path.parts[1] if lang_code == "en": print(f"Skipping English document: {path}") return True en_doc_path = Path("docs") / "en" / Path(*path.parts[2:]) doc_lines = path.read_text(encoding="utf-8").splitlines() en_doc_lines = en_doc_path.read_text(encoding="utf-8").splitlines() doc_lines = check_translation( doc_lines=doc_lines, en_doc_lines=en_doc_lines, lang_code=lang_code, auto_fix=True, path=str(path), ) # Write back the fixed document doc_lines.append("") # Ensure file ends with a newline path.write_text("\n".join(doc_lines), encoding="utf-8") except ValueError as e: print(f"Error processing {path}: {e}") return False return True @cli.command() def fix_all(ctx: typer.Context, language: str): docs = get_all_paths(language) all_good = True for page in docs: doc_path = Path("docs") / language / "docs" / page res = process_one_page(doc_path) all_good = all_good and res if not all_good: raise typer.Exit(code=1) @cli.command() def fix_pages( doc_paths: Annotated[ list[Path], typer.Argument(help="List of paths to documents."), ], ): all_good = True for path in doc_paths: res = process_one_page(path) all_good = all_good and res if not all_good: raise typer.Exit(code=1) if __name__ == "__main__": cli()
--- +++ @@ -28,6 +28,9 @@ def iter_all_lang_paths(lang_path_root: Path) -> Iterable[Path]: + """ + Iterate on the markdown files to translate in order of priority. + """ first_dirs = [ lang_path_root / "learn", @@ -60,6 +63,11 @@ def process_one_page(path: Path) -> bool: + """ + Fix one translated document by comparing it to the English version. + + Returns True if processed successfully, False otherwise. + """ try: lang_code = path.parts[1] @@ -121,4 +129,4 @@ if __name__ == "__main__": - cli()+ cli()
https://raw.githubusercontent.com/fastapi/fastapi/HEAD/scripts/translation_fixer.py
Help me add docstrings to my project
import os from functools import lru_cache from subprocess import CalledProcessError, run from typing import Optional, Union import numpy as np import torch import torch.nn.functional as F from .utils import exact_div # hard-coded audio hyperparameters SAMPLE_RATE = 16000 N_FFT = 400 HOP_LENGTH = 160 CHUNK_LENGTH = 30 N_SAMPLES = CHUNK_LENGTH * SAMPLE_RATE # 480000 samples in a 30-second chunk N_FRAMES = exact_div(N_SAMPLES, HOP_LENGTH) # 3000 frames in a mel spectrogram input N_SAMPLES_PER_TOKEN = HOP_LENGTH * 2 # the initial convolutions has stride 2 FRAMES_PER_SECOND = exact_div(SAMPLE_RATE, HOP_LENGTH) # 10ms per audio frame TOKENS_PER_SECOND = exact_div(SAMPLE_RATE, N_SAMPLES_PER_TOKEN) # 20ms per audio token def load_audio(file: str, sr: int = SAMPLE_RATE): # This launches a subprocess to decode audio while down-mixing # and resampling as necessary. Requires the ffmpeg CLI in PATH. # fmt: off cmd = [ "ffmpeg", "-nostdin", "-threads", "0", "-i", file, "-f", "s16le", "-ac", "1", "-acodec", "pcm_s16le", "-ar", str(sr), "-" ] # fmt: on try: out = run(cmd, capture_output=True, check=True).stdout except CalledProcessError as e: raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}") from e return np.frombuffer(out, np.int16).flatten().astype(np.float32) / 32768.0 def pad_or_trim(array, length: int = N_SAMPLES, *, axis: int = -1): if torch.is_tensor(array): if array.shape[axis] > length: array = array.index_select( dim=axis, index=torch.arange(length, device=array.device) ) if array.shape[axis] < length: pad_widths = [(0, 0)] * array.ndim pad_widths[axis] = (0, length - array.shape[axis]) array = F.pad(array, [pad for sizes in pad_widths[::-1] for pad in sizes]) else: if array.shape[axis] > length: array = array.take(indices=range(length), axis=axis) if array.shape[axis] < length: pad_widths = [(0, 0)] * array.ndim pad_widths[axis] = (0, length - array.shape[axis]) array = np.pad(array, pad_widths) return array @lru_cache(maxsize=None) def mel_filters(device, n_mels: int) -> torch.Tensor: assert n_mels in {80, 128}, f"Unsupported n_mels: {n_mels}" filters_path = os.path.join(os.path.dirname(__file__), "assets", "mel_filters.npz") with np.load(filters_path, allow_pickle=False) as f: return torch.from_numpy(f[f"mel_{n_mels}"]).to(device) def log_mel_spectrogram( audio: Union[str, np.ndarray, torch.Tensor], n_mels: int = 80, padding: int = 0, device: Optional[Union[str, torch.device]] = None, ): if not torch.is_tensor(audio): if isinstance(audio, str): audio = load_audio(audio) audio = torch.from_numpy(audio) if device is not None: audio = audio.to(device) if padding > 0: audio = F.pad(audio, (0, padding)) window = torch.hann_window(N_FFT).to(audio.device) stft = torch.stft(audio, N_FFT, HOP_LENGTH, window=window, return_complex=True) magnitudes = stft[..., :-1].abs() ** 2 filters = mel_filters(audio.device, n_mels) mel_spec = filters @ magnitudes log_spec = torch.clamp(mel_spec, min=1e-10).log10() log_spec = torch.maximum(log_spec, log_spec.max() - 8.0) log_spec = (log_spec + 4.0) / 4.0 return log_spec
--- +++ @@ -23,6 +23,21 @@ def load_audio(file: str, sr: int = SAMPLE_RATE): + """ + Open an audio file and read as mono waveform, resampling as necessary + + Parameters + ---------- + file: str + The audio file to open + + sr: int + The sample rate to resample the audio if necessary + + Returns + ------- + A NumPy array containing the audio waveform, in float32 dtype. + """ # This launches a subprocess to decode audio while down-mixing # and resampling as necessary. Requires the ffmpeg CLI in PATH. @@ -48,6 +63,9 @@ def pad_or_trim(array, length: int = N_SAMPLES, *, axis: int = -1): + """ + Pad or trim the audio array to N_SAMPLES, as expected by the encoder. + """ if torch.is_tensor(array): if array.shape[axis] > length: array = array.index_select( @@ -72,6 +90,16 @@ @lru_cache(maxsize=None) def mel_filters(device, n_mels: int) -> torch.Tensor: + """ + load the mel filterbank matrix for projecting STFT into a Mel spectrogram. + Allows decoupling librosa dependency; saved using: + + np.savez_compressed( + "mel_filters.npz", + mel_80=librosa.filters.mel(sr=16000, n_fft=400, n_mels=80), + mel_128=librosa.filters.mel(sr=16000, n_fft=400, n_mels=128), + ) + """ assert n_mels in {80, 128}, f"Unsupported n_mels: {n_mels}" filters_path = os.path.join(os.path.dirname(__file__), "assets", "mel_filters.npz") @@ -85,6 +113,28 @@ padding: int = 0, device: Optional[Union[str, torch.device]] = None, ): + """ + Compute the log-Mel spectrogram of + + Parameters + ---------- + audio: Union[str, np.ndarray, torch.Tensor], shape = (*) + The path to audio or either a NumPy array or Tensor containing the audio waveform in 16 kHz + + n_mels: int + The number of Mel-frequency filters, only 80 and 128 are supported + + padding: int + Number of zero samples to pad to the right + + device: Optional[Union[str, torch.device]] + If given, the audio tensor is moved to this device before STFT + + Returns + ------- + torch.Tensor, shape = (n_mels, n_frames) + A Tensor that contains the Mel spectrogram + """ if not torch.is_tensor(audio): if isinstance(audio, str): audio = load_audio(audio) @@ -104,4 +154,4 @@ log_spec = torch.clamp(mel_spec, min=1e-10).log10() log_spec = torch.maximum(log_spec, log_spec.max() - 8.0) log_spec = (log_spec + 4.0) / 4.0 - return log_spec+ return log_spec
https://raw.githubusercontent.com/openai/whisper/HEAD/whisper/audio.py
Add docstrings that explain logic
import base64 import os import string from dataclasses import dataclass, field from functools import cached_property, lru_cache from typing import Dict, List, Optional, Tuple import tiktoken LANGUAGES = { "en": "english", "zh": "chinese", "de": "german", "es": "spanish", "ru": "russian", "ko": "korean", "fr": "french", "ja": "japanese", "pt": "portuguese", "tr": "turkish", "pl": "polish", "ca": "catalan", "nl": "dutch", "ar": "arabic", "sv": "swedish", "it": "italian", "id": "indonesian", "hi": "hindi", "fi": "finnish", "vi": "vietnamese", "he": "hebrew", "uk": "ukrainian", "el": "greek", "ms": "malay", "cs": "czech", "ro": "romanian", "da": "danish", "hu": "hungarian", "ta": "tamil", "no": "norwegian", "th": "thai", "ur": "urdu", "hr": "croatian", "bg": "bulgarian", "lt": "lithuanian", "la": "latin", "mi": "maori", "ml": "malayalam", "cy": "welsh", "sk": "slovak", "te": "telugu", "fa": "persian", "lv": "latvian", "bn": "bengali", "sr": "serbian", "az": "azerbaijani", "sl": "slovenian", "kn": "kannada", "et": "estonian", "mk": "macedonian", "br": "breton", "eu": "basque", "is": "icelandic", "hy": "armenian", "ne": "nepali", "mn": "mongolian", "bs": "bosnian", "kk": "kazakh", "sq": "albanian", "sw": "swahili", "gl": "galician", "mr": "marathi", "pa": "punjabi", "si": "sinhala", "km": "khmer", "sn": "shona", "yo": "yoruba", "so": "somali", "af": "afrikaans", "oc": "occitan", "ka": "georgian", "be": "belarusian", "tg": "tajik", "sd": "sindhi", "gu": "gujarati", "am": "amharic", "yi": "yiddish", "lo": "lao", "uz": "uzbek", "fo": "faroese", "ht": "haitian creole", "ps": "pashto", "tk": "turkmen", "nn": "nynorsk", "mt": "maltese", "sa": "sanskrit", "lb": "luxembourgish", "my": "myanmar", "bo": "tibetan", "tl": "tagalog", "mg": "malagasy", "as": "assamese", "tt": "tatar", "haw": "hawaiian", "ln": "lingala", "ha": "hausa", "ba": "bashkir", "jw": "javanese", "su": "sundanese", "yue": "cantonese", } # language code lookup by name, with a few language aliases TO_LANGUAGE_CODE = { **{language: code for code, language in LANGUAGES.items()}, "burmese": "my", "valencian": "ca", "flemish": "nl", "haitian": "ht", "letzeburgesch": "lb", "pushto": "ps", "panjabi": "pa", "moldavian": "ro", "moldovan": "ro", "sinhalese": "si", "castilian": "es", "mandarin": "zh", } @dataclass class Tokenizer: encoding: tiktoken.Encoding num_languages: int language: Optional[str] = None task: Optional[str] = None sot_sequence: Tuple[int] = () special_tokens: Dict[str, int] = field(default_factory=dict) def __post_init__(self): for special in self.encoding.special_tokens_set: special_token = self.encoding.encode_single_token(special) self.special_tokens[special] = special_token sot: int = self.special_tokens["<|startoftranscript|>"] translate: int = self.special_tokens["<|translate|>"] transcribe: int = self.special_tokens["<|transcribe|>"] langs = tuple(LANGUAGES.keys())[: self.num_languages] sot_sequence = [sot] if self.language is not None: sot_sequence.append(sot + 1 + langs.index(self.language)) if self.task is not None: task_token: int = transcribe if self.task == "transcribe" else translate sot_sequence.append(task_token) self.sot_sequence = tuple(sot_sequence) def encode(self, text, **kwargs): return self.encoding.encode(text, **kwargs) def decode(self, token_ids: List[int], **kwargs) -> str: token_ids = [t for t in token_ids if t < self.timestamp_begin] return self.encoding.decode(token_ids, **kwargs) def decode_with_timestamps(self, token_ids: List[int], **kwargs) -> str: return self.encoding.decode(token_ids, **kwargs) @cached_property def eot(self) -> int: return self.encoding.eot_token @cached_property def transcribe(self) -> int: return self.special_tokens["<|transcribe|>"] @cached_property def translate(self) -> int: return self.special_tokens["<|translate|>"] @cached_property def sot(self) -> int: return self.special_tokens["<|startoftranscript|>"] @cached_property def sot_lm(self) -> int: return self.special_tokens["<|startoflm|>"] @cached_property def sot_prev(self) -> int: return self.special_tokens["<|startofprev|>"] @cached_property def no_speech(self) -> int: return self.special_tokens["<|nospeech|>"] @cached_property def no_timestamps(self) -> int: return self.special_tokens["<|notimestamps|>"] @cached_property def timestamp_begin(self) -> int: return self.special_tokens["<|0.00|>"] @cached_property def language_token(self) -> int: if self.language is None: raise ValueError("This tokenizer does not have language token configured") return self.to_language_token(self.language) def to_language_token(self, language): if token := self.special_tokens.get(f"<|{language}|>", None): return token raise KeyError(f"Language {language} not found in tokenizer.") @cached_property def all_language_tokens(self) -> Tuple[int]: result = [] for token, token_id in self.special_tokens.items(): if token.strip("<|>") in LANGUAGES: result.append(token_id) return tuple(result)[: self.num_languages] @cached_property def all_language_codes(self) -> Tuple[str]: return tuple(self.decode([_l]).strip("<|>") for _l in self.all_language_tokens) @cached_property def sot_sequence_including_notimestamps(self) -> Tuple[int]: return tuple(list(self.sot_sequence) + [self.no_timestamps]) @cached_property def non_speech_tokens(self) -> Tuple[int]: symbols = list('"#()*+/:;<=>@[\\]^_`{|}~「」『』') symbols += ( "<< >> <<< >>> -- --- -( -[ (' (\" (( )) ((( ))) [[ ]] {{ }} ♪♪ ♪♪♪".split() ) # symbols that may be a single token or multiple tokens depending on the tokenizer. # In case they're multiple tokens, suppress the first token, which is safe because: # These are between U+2640 and U+267F miscellaneous symbols that are okay to suppress # in generations, and in the 3-byte UTF-8 representation they share the first two bytes. miscellaneous = set("♩♪♫♬♭♮♯") assert all(0x2640 <= ord(c) <= 0x267F for c in miscellaneous) # allow hyphens "-" and single quotes "'" between words, but not at the beginning of a word result = {self.encoding.encode(" -")[0], self.encoding.encode(" '")[0]} for symbol in symbols + list(miscellaneous): for tokens in [ self.encoding.encode(symbol), self.encoding.encode(" " + symbol), ]: if len(tokens) == 1 or symbol in miscellaneous: result.add(tokens[0]) return tuple(sorted(result)) def split_to_word_tokens(self, tokens: List[int]): if self.language in {"zh", "ja", "th", "lo", "my", "yue"}: # These languages don't typically use spaces, so it is difficult to split words # without morpheme analysis. Here, we instead split words at any # position where the tokens are decoded as valid unicode points return self.split_tokens_on_unicode(tokens) return self.split_tokens_on_spaces(tokens) def split_tokens_on_unicode(self, tokens: List[int]): decoded_full = self.decode_with_timestamps(tokens) replacement_char = "\ufffd" words = [] word_tokens = [] current_tokens = [] unicode_offset = 0 for token in tokens: current_tokens.append(token) decoded = self.decode_with_timestamps(current_tokens) if ( replacement_char not in decoded or decoded_full[unicode_offset + decoded.index(replacement_char)] == replacement_char ): words.append(decoded) word_tokens.append(current_tokens) current_tokens = [] unicode_offset += len(decoded) return words, word_tokens def split_tokens_on_spaces(self, tokens: List[int]): subwords, subword_tokens_list = self.split_tokens_on_unicode(tokens) words = [] word_tokens = [] for subword, subword_tokens in zip(subwords, subword_tokens_list): special = subword_tokens[0] >= self.eot with_space = subword.startswith(" ") punctuation = subword.strip() in string.punctuation if special or with_space or punctuation or len(words) == 0: words.append(subword) word_tokens.append(subword_tokens) else: words[-1] = words[-1] + subword word_tokens[-1].extend(subword_tokens) return words, word_tokens @lru_cache(maxsize=None) def get_encoding(name: str = "gpt2", num_languages: int = 99): vocab_path = os.path.join(os.path.dirname(__file__), "assets", f"{name}.tiktoken") ranks = { base64.b64decode(token): int(rank) for token, rank in (line.split() for line in open(vocab_path) if line) } n_vocab = len(ranks) special_tokens = {} specials = [ "<|endoftext|>", "<|startoftranscript|>", *[f"<|{lang}|>" for lang in list(LANGUAGES.keys())[:num_languages]], "<|translate|>", "<|transcribe|>", "<|startoflm|>", "<|startofprev|>", "<|nospeech|>", "<|notimestamps|>", *[f"<|{i * 0.02:.2f}|>" for i in range(1501)], ] for token in specials: special_tokens[token] = n_vocab n_vocab += 1 return tiktoken.Encoding( name=os.path.basename(vocab_path), explicit_n_vocab=n_vocab, pat_str=r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""", mergeable_ranks=ranks, special_tokens=special_tokens, ) @lru_cache(maxsize=None) def get_tokenizer( multilingual: bool, *, num_languages: int = 99, language: Optional[str] = None, task: Optional[str] = None, # Literal["transcribe", "translate", None] ) -> Tokenizer: if language is not None: language = language.lower() if language not in LANGUAGES: if language in TO_LANGUAGE_CODE: language = TO_LANGUAGE_CODE[language] else: raise ValueError(f"Unsupported language: {language}") if multilingual: encoding_name = "multilingual" language = language or "en" task = task or "transcribe" else: encoding_name = "gpt2" language = None task = None encoding = get_encoding(name=encoding_name, num_languages=num_languages) return Tokenizer( encoding=encoding, num_languages=num_languages, language=language, task=task )
--- +++ @@ -130,6 +130,7 @@ @dataclass class Tokenizer: + """A thin wrapper around `tiktoken` providing quick access to special tokens""" encoding: tiktoken.Encoding num_languages: int @@ -165,6 +166,10 @@ return self.encoding.decode(token_ids, **kwargs) def decode_with_timestamps(self, token_ids: List[int], **kwargs) -> str: + """ + Timestamp tokens are above other special tokens' id range and are ignored by `decode()`. + This method decodes given tokens with timestamps tokens annotated, e.g. "<|1.08|>". + """ return self.encoding.decode(token_ids, **kwargs) @cached_property @@ -205,6 +210,7 @@ @cached_property def language_token(self) -> int: + """Returns the token id corresponding to the value of the `language` field""" if self.language is None: raise ValueError("This tokenizer does not have language token configured") @@ -234,6 +240,16 @@ @cached_property def non_speech_tokens(self) -> Tuple[int]: + """ + Returns the list of tokens to suppress in order to avoid any speaker tags or non-speech + annotations, to prevent sampling texts that are not actually spoken in the audio, e.g. + + - ♪♪♪ + - ( SPEAKING FOREIGN LANGUAGE ) + - [DAVID] Hey there, + + keeping basic punctuations like commas, periods, question marks, exclamation points, etc. + """ symbols = list('"#()*+/:;<=>@[\\]^_`{|}~「」『』') symbols += ( "<< >> <<< >>> -- --- -( -[ (' (\" (( )) ((( ))) [[ ]] {{ }} ♪♪ ♪♪♪".split() @@ -376,4 +392,4 @@ return Tokenizer( encoding=encoding, num_languages=num_languages, language=language, task=task - )+ )
https://raw.githubusercontent.com/openai/whisper/HEAD/whisper/tokenizer.py
Add documentation for all methods
import hashlib import io import os import urllib import warnings from typing import List, Optional, Union import torch from tqdm import tqdm from .audio import load_audio, log_mel_spectrogram, pad_or_trim from .decoding import DecodingOptions, DecodingResult, decode, detect_language from .model import ModelDimensions, Whisper from .transcribe import transcribe from .version import __version__ _MODELS = { "tiny.en": "https://openaipublic.azureedge.net/main/whisper/models/d3dd57d32accea0b295c96e26691aa14d8822fac7d9d27d5dc00b4ca2826dd03/tiny.en.pt", "tiny": "https://openaipublic.azureedge.net/main/whisper/models/65147644a518d12f04e32d6f3b26facc3f8dd46e5390956a9424a650c0ce22b9/tiny.pt", "base.en": "https://openaipublic.azureedge.net/main/whisper/models/25a8566e1d0c1e2231d1c762132cd20e0f96a85d16145c3a00adf5d1ac670ead/base.en.pt", "base": "https://openaipublic.azureedge.net/main/whisper/models/ed3a0b6b1c0edf879ad9b11b1af5a0e6ab5db9205f891f668f8b0e6c6326e34e/base.pt", "small.en": "https://openaipublic.azureedge.net/main/whisper/models/f953ad0fd29cacd07d5a9eda5624af0f6bcf2258be67c92b79389873d91e0872/small.en.pt", "small": "https://openaipublic.azureedge.net/main/whisper/models/9ecf779972d90ba49c06d968637d720dd632c55bbf19d441fb42bf17a411e794/small.pt", "medium.en": "https://openaipublic.azureedge.net/main/whisper/models/d7440d1dc186f76616474e0ff0b3b6b879abc9d1a4926b7adfa41db2d497ab4f/medium.en.pt", "medium": "https://openaipublic.azureedge.net/main/whisper/models/345ae4da62f9b3d59415adc60127b97c714f32e89e936602e85993674d08dcb1/medium.pt", "large-v1": "https://openaipublic.azureedge.net/main/whisper/models/e4b87e7e0bf463eb8e6956e646f1e277e901512310def2c24bf0e11bd3c28e9a/large-v1.pt", "large-v2": "https://openaipublic.azureedge.net/main/whisper/models/81f7c96c852ee8fc832187b0132e569d6c3065a3252ed18e56effd0b6a73e524/large-v2.pt", "large-v3": "https://openaipublic.azureedge.net/main/whisper/models/e5b1a55b89c1367dacf97e3e19bfd829a01529dbfdeefa8caeb59b3f1b81dadb/large-v3.pt", "large": "https://openaipublic.azureedge.net/main/whisper/models/e5b1a55b89c1367dacf97e3e19bfd829a01529dbfdeefa8caeb59b3f1b81dadb/large-v3.pt", "large-v3-turbo": "https://openaipublic.azureedge.net/main/whisper/models/aff26ae408abcba5fbf8813c21e62b0941638c5f6eebfb145be0c9839262a19a/large-v3-turbo.pt", "turbo": "https://openaipublic.azureedge.net/main/whisper/models/aff26ae408abcba5fbf8813c21e62b0941638c5f6eebfb145be0c9839262a19a/large-v3-turbo.pt", } # base85-encoded (n_layers, n_heads) boolean arrays indicating the cross-attention heads that are # highly correlated to the word-level timing, i.e. the alignment between audio and text tokens. _ALIGNMENT_HEADS = { "tiny.en": b"ABzY8J1N>@0{>%R00Bk>$p{7v037`oCl~+#00", "tiny": b"ABzY8bu8Lr0{>%RKn9Fp%m@SkK7Kt=7ytkO", "base.en": b"ABzY8;40c<0{>%RzzG;p*o+Vo09|#PsxSZm00", "base": b"ABzY8KQ!870{>%RzyTQH3`Q^yNP!>##QT-<FaQ7m", "small.en": b"ABzY8>?_)10{>%RpeA61k&I|OI3I$65C{;;pbCHh0B{qLQ;+}v00", "small": b"ABzY8DmU6=0{>%Rpa?J`kvJ6qF(V^F86#Xh7JUGMK}P<N0000", "medium.en": b"ABzY8usPae0{>%R7<zz_OvQ{)4kMa0BMw6u5rT}kRKX;$NfYBv00*Hl@qhsU00", "medium": b"ABzY8B0Jh+0{>%R7}kK1fFL7w6%<-Pf*t^=N)Qr&0RR9", "large-v1": b"ABzY8r9j$a0{>%R7#4sLmoOs{s)o3~84-RPdcFk!JR<kSfC2yj", "large-v2": b"ABzY8zd+h!0{>%R7=D0pU<_bnWW*tkYAhobTNnu$jnkEkXqp)j;w1Tzk)UH3X%SZd&fFZ2fC2yj", "large-v3": b"ABzY8gWO1E0{>%R7(9S+Kn!D~%ngiGaR?*L!iJG9p-nab0JQ=-{D1-g00", "large": b"ABzY8gWO1E0{>%R7(9S+Kn!D~%ngiGaR?*L!iJG9p-nab0JQ=-{D1-g00", "large-v3-turbo": b"ABzY8j^C+e0{>%RARaKHP%t(lGR*)0g!tONPyhe`", "turbo": b"ABzY8j^C+e0{>%RARaKHP%t(lGR*)0g!tONPyhe`", } def _download(url: str, root: str, in_memory: bool) -> Union[bytes, str]: os.makedirs(root, exist_ok=True) expected_sha256 = url.split("/")[-2] download_target = os.path.join(root, os.path.basename(url)) if os.path.exists(download_target) and not os.path.isfile(download_target): raise RuntimeError(f"{download_target} exists and is not a regular file") if os.path.isfile(download_target): with open(download_target, "rb") as f: model_bytes = f.read() if hashlib.sha256(model_bytes).hexdigest() == expected_sha256: return model_bytes if in_memory else download_target else: warnings.warn( f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file" ) with urllib.request.urlopen(url) as source, open(download_target, "wb") as output: with tqdm( total=int(source.info().get("Content-Length")), ncols=80, unit="iB", unit_scale=True, unit_divisor=1024, ) as loop: while True: buffer = source.read(8192) if not buffer: break output.write(buffer) loop.update(len(buffer)) model_bytes = open(download_target, "rb").read() if hashlib.sha256(model_bytes).hexdigest() != expected_sha256: raise RuntimeError( "Model has been downloaded but the SHA256 checksum does not not match. Please retry loading the model." ) return model_bytes if in_memory else download_target def available_models() -> List[str]: return list(_MODELS.keys()) def load_model( name: str, device: Optional[Union[str, torch.device]] = None, download_root: str = None, in_memory: bool = False, ) -> Whisper: if device is None: device = "cuda" if torch.cuda.is_available() else "cpu" if download_root is None: default = os.path.join(os.path.expanduser("~"), ".cache") download_root = os.path.join(os.getenv("XDG_CACHE_HOME", default), "whisper") if name in _MODELS: checkpoint_file = _download(_MODELS[name], download_root, in_memory) alignment_heads = _ALIGNMENT_HEADS[name] elif os.path.isfile(name): checkpoint_file = open(name, "rb").read() if in_memory else name alignment_heads = None else: raise RuntimeError( f"Model {name} not found; available models = {available_models()}" ) with ( io.BytesIO(checkpoint_file) if in_memory else open(checkpoint_file, "rb") ) as fp: kwargs = {"weights_only": True} if torch.__version__ >= "1.13" else {} checkpoint = torch.load(fp, map_location=device, **kwargs) del checkpoint_file dims = ModelDimensions(**checkpoint["dims"]) model = Whisper(dims) model.load_state_dict(checkpoint["model_state_dict"]) if alignment_heads is not None: model.set_alignment_heads(alignment_heads) return model.to(device)
--- +++ @@ -96,6 +96,7 @@ def available_models() -> List[str]: + """Returns the names of available models""" return list(_MODELS.keys()) @@ -105,6 +106,26 @@ download_root: str = None, in_memory: bool = False, ) -> Whisper: + """ + Load a Whisper ASR model + + Parameters + ---------- + name : str + one of the official model names listed by `whisper.available_models()`, or + path to a model checkpoint containing the model dimensions and the model state_dict. + device : Union[str, torch.device] + the PyTorch device to put the model into + download_root: str + path to download the model files; by default, it uses "~/.cache/whisper" + in_memory: bool + whether to preload the model weights into host memory + + Returns + ------- + model : Whisper + The Whisper ASR model instance + """ if device is None: device = "cuda" if torch.cuda.is_available() else "cpu" @@ -137,4 +158,4 @@ if alignment_heads is not None: model.set_alignment_heads(alignment_heads) - return model.to(device)+ return model.to(device)
https://raw.githubusercontent.com/openai/whisper/HEAD/whisper/__init__.py
Add minimal docstrings for each function
import base64 import gzip from contextlib import contextmanager from dataclasses import dataclass from typing import Dict, Iterable, Optional, Tuple import numpy as np import torch import torch.nn.functional as F from torch import Tensor, nn from .decoding import decode as decode_function from .decoding import detect_language as detect_language_function from .transcribe import transcribe as transcribe_function try: from torch.nn.functional import scaled_dot_product_attention SDPA_AVAILABLE = True except (ImportError, RuntimeError, OSError): scaled_dot_product_attention = None SDPA_AVAILABLE = False @dataclass class ModelDimensions: n_mels: int n_audio_ctx: int n_audio_state: int n_audio_head: int n_audio_layer: int n_vocab: int n_text_ctx: int n_text_state: int n_text_head: int n_text_layer: int class LayerNorm(nn.LayerNorm): def forward(self, x: Tensor) -> Tensor: return super().forward(x.float()).type(x.dtype) class Linear(nn.Linear): def forward(self, x: Tensor) -> Tensor: return F.linear( x, self.weight.to(x.dtype), None if self.bias is None else self.bias.to(x.dtype), ) class Conv1d(nn.Conv1d): def _conv_forward( self, x: Tensor, weight: Tensor, bias: Optional[Tensor] ) -> Tensor: return super()._conv_forward( x, weight.to(x.dtype), None if bias is None else bias.to(x.dtype) ) def sinusoids(length, channels, max_timescale=10000): assert channels % 2 == 0 log_timescale_increment = np.log(max_timescale) / (channels // 2 - 1) inv_timescales = torch.exp(-log_timescale_increment * torch.arange(channels // 2)) scaled_time = torch.arange(length)[:, np.newaxis] * inv_timescales[np.newaxis, :] return torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=1) @contextmanager def disable_sdpa(): prev_state = MultiHeadAttention.use_sdpa try: MultiHeadAttention.use_sdpa = False yield finally: MultiHeadAttention.use_sdpa = prev_state class MultiHeadAttention(nn.Module): use_sdpa = True def __init__(self, n_state: int, n_head: int): super().__init__() self.n_head = n_head self.query = Linear(n_state, n_state) self.key = Linear(n_state, n_state, bias=False) self.value = Linear(n_state, n_state) self.out = Linear(n_state, n_state) def forward( self, x: Tensor, xa: Optional[Tensor] = None, mask: Optional[Tensor] = None, kv_cache: Optional[dict] = None, ): q = self.query(x) if kv_cache is None or xa is None or self.key not in kv_cache: # hooks, if installed (i.e. kv_cache is not None), will prepend the cached kv tensors; # otherwise, perform key/value projections for self- or cross-attention as usual. k = self.key(x if xa is None else xa) v = self.value(x if xa is None else xa) else: # for cross-attention, calculate keys and values once and reuse in subsequent calls. k = kv_cache[self.key] v = kv_cache[self.value] wv, qk = self.qkv_attention(q, k, v, mask) return self.out(wv), qk def qkv_attention( self, q: Tensor, k: Tensor, v: Tensor, mask: Optional[Tensor] = None ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: n_batch, n_ctx, n_state = q.shape scale = (n_state // self.n_head) ** -0.25 q = q.view(*q.shape[:2], self.n_head, -1).permute(0, 2, 1, 3) k = k.view(*k.shape[:2], self.n_head, -1).permute(0, 2, 1, 3) v = v.view(*v.shape[:2], self.n_head, -1).permute(0, 2, 1, 3) if SDPA_AVAILABLE and MultiHeadAttention.use_sdpa: a = scaled_dot_product_attention( q, k, v, is_causal=mask is not None and n_ctx > 1 ) out = a.permute(0, 2, 1, 3).flatten(start_dim=2) qk = None else: qk = (q * scale) @ (k * scale).transpose(-1, -2) if mask is not None: qk = qk + mask[:n_ctx, :n_ctx] qk = qk.float() w = F.softmax(qk, dim=-1).to(q.dtype) out = (w @ v).permute(0, 2, 1, 3).flatten(start_dim=2) qk = qk.detach() return out, qk class ResidualAttentionBlock(nn.Module): def __init__(self, n_state: int, n_head: int, cross_attention: bool = False): super().__init__() self.attn = MultiHeadAttention(n_state, n_head) self.attn_ln = LayerNorm(n_state) self.cross_attn = ( MultiHeadAttention(n_state, n_head) if cross_attention else None ) self.cross_attn_ln = LayerNorm(n_state) if cross_attention else None n_mlp = n_state * 4 self.mlp = nn.Sequential( Linear(n_state, n_mlp), nn.GELU(), Linear(n_mlp, n_state) ) self.mlp_ln = LayerNorm(n_state) def forward( self, x: Tensor, xa: Optional[Tensor] = None, mask: Optional[Tensor] = None, kv_cache: Optional[dict] = None, ): x = x + self.attn(self.attn_ln(x), mask=mask, kv_cache=kv_cache)[0] if self.cross_attn: x = x + self.cross_attn(self.cross_attn_ln(x), xa, kv_cache=kv_cache)[0] x = x + self.mlp(self.mlp_ln(x)) return x class AudioEncoder(nn.Module): def __init__( self, n_mels: int, n_ctx: int, n_state: int, n_head: int, n_layer: int ): super().__init__() self.conv1 = Conv1d(n_mels, n_state, kernel_size=3, padding=1) self.conv2 = Conv1d(n_state, n_state, kernel_size=3, stride=2, padding=1) self.register_buffer("positional_embedding", sinusoids(n_ctx, n_state)) self.blocks: Iterable[ResidualAttentionBlock] = nn.ModuleList( [ResidualAttentionBlock(n_state, n_head) for _ in range(n_layer)] ) self.ln_post = LayerNorm(n_state) def forward(self, x: Tensor): x = F.gelu(self.conv1(x)) x = F.gelu(self.conv2(x)) x = x.permute(0, 2, 1) assert x.shape[1:] == self.positional_embedding.shape, "incorrect audio shape" x = (x + self.positional_embedding).to(x.dtype) for block in self.blocks: x = block(x) x = self.ln_post(x) return x class TextDecoder(nn.Module): def __init__( self, n_vocab: int, n_ctx: int, n_state: int, n_head: int, n_layer: int ): super().__init__() self.token_embedding = nn.Embedding(n_vocab, n_state) self.positional_embedding = nn.Parameter(torch.empty(n_ctx, n_state)) self.blocks: Iterable[ResidualAttentionBlock] = nn.ModuleList( [ ResidualAttentionBlock(n_state, n_head, cross_attention=True) for _ in range(n_layer) ] ) self.ln = LayerNorm(n_state) mask = torch.empty(n_ctx, n_ctx).fill_(-np.inf).triu_(1) self.register_buffer("mask", mask, persistent=False) def forward(self, x: Tensor, xa: Tensor, kv_cache: Optional[dict] = None): offset = next(iter(kv_cache.values())).shape[1] if kv_cache else 0 x = ( self.token_embedding(x) + self.positional_embedding[offset : offset + x.shape[-1]] ) x = x.to(xa.dtype) for block in self.blocks: x = block(x, xa, mask=self.mask, kv_cache=kv_cache) x = self.ln(x) logits = ( x @ torch.transpose(self.token_embedding.weight.to(x.dtype), 0, 1) ).float() return logits class Whisper(nn.Module): def __init__(self, dims: ModelDimensions): super().__init__() self.dims = dims self.encoder = AudioEncoder( self.dims.n_mels, self.dims.n_audio_ctx, self.dims.n_audio_state, self.dims.n_audio_head, self.dims.n_audio_layer, ) self.decoder = TextDecoder( self.dims.n_vocab, self.dims.n_text_ctx, self.dims.n_text_state, self.dims.n_text_head, self.dims.n_text_layer, ) # use the last half among the decoder layers for time alignment by default; # to use a specific set of heads, see `set_alignment_heads()` below. all_heads = torch.zeros( self.dims.n_text_layer, self.dims.n_text_head, dtype=torch.bool ) all_heads[self.dims.n_text_layer // 2 :] = True self.register_buffer("alignment_heads", all_heads.to_sparse(), persistent=False) def set_alignment_heads(self, dump: bytes): array = np.frombuffer( gzip.decompress(base64.b85decode(dump)), dtype=bool ).copy() mask = torch.from_numpy(array).reshape( self.dims.n_text_layer, self.dims.n_text_head ) self.register_buffer("alignment_heads", mask.to_sparse(), persistent=False) def embed_audio(self, mel: torch.Tensor): return self.encoder(mel) def logits(self, tokens: torch.Tensor, audio_features: torch.Tensor): return self.decoder(tokens, audio_features) def forward( self, mel: torch.Tensor, tokens: torch.Tensor ) -> Dict[str, torch.Tensor]: return self.decoder(tokens, self.encoder(mel)) @property def device(self): return next(self.parameters()).device @property def is_multilingual(self): return self.dims.n_vocab >= 51865 @property def num_languages(self): return self.dims.n_vocab - 51765 - int(self.is_multilingual) def install_kv_cache_hooks(self, cache: Optional[dict] = None): cache = {**cache} if cache is not None else {} hooks = [] def save_to_cache(module, _, output): if module not in cache or output.shape[1] > self.dims.n_text_ctx: # save as-is, for the first token or cross attention cache[module] = output else: cache[module] = torch.cat([cache[module], output], dim=1).detach() return cache[module] def install_hooks(layer: nn.Module): if isinstance(layer, MultiHeadAttention): hooks.append(layer.key.register_forward_hook(save_to_cache)) hooks.append(layer.value.register_forward_hook(save_to_cache)) self.decoder.apply(install_hooks) return cache, hooks detect_language = detect_language_function transcribe = transcribe_function decode = decode_function
--- +++ @@ -60,6 +60,7 @@ def sinusoids(length, channels, max_timescale=10000): + """Returns sinusoids for positional embedding""" assert channels % 2 == 0 log_timescale_increment = np.log(max_timescale) / (channels // 2 - 1) inv_timescales = torch.exp(-log_timescale_increment * torch.arange(channels // 2)) @@ -185,6 +186,10 @@ self.ln_post = LayerNorm(n_state) def forward(self, x: Tensor): + """ + x : torch.Tensor, shape = (batch_size, n_mels, n_ctx) + the mel spectrogram of the audio + """ x = F.gelu(self.conv1(x)) x = F.gelu(self.conv2(x)) x = x.permute(0, 2, 1) @@ -220,6 +225,12 @@ self.register_buffer("mask", mask, persistent=False) def forward(self, x: Tensor, xa: Tensor, kv_cache: Optional[dict] = None): + """ + x : torch.LongTensor, shape = (batch_size, <= n_ctx) + the text tokens + xa : torch.Tensor, shape = (batch_size, n_audio_ctx, n_audio_state) + the encoded audio features to be attended on + """ offset = next(iter(kv_cache.values())).shape[1] if kv_cache else 0 x = ( self.token_embedding(x) @@ -297,6 +308,19 @@ return self.dims.n_vocab - 51765 - int(self.is_multilingual) def install_kv_cache_hooks(self, cache: Optional[dict] = None): + """ + The `MultiHeadAttention` module optionally accepts `kv_cache` which stores the key and value + tensors calculated for the previous positions. This method returns a dictionary that stores + all caches, and the necessary hooks for the key and value projection modules that save the + intermediate tensors to be reused during later calculations. + + Returns + ------- + cache : Dict[nn.Module, torch.Tensor] + A dictionary object mapping the key/value projection modules to its cache + hooks : List[RemovableHandle] + List of PyTorch RemovableHandle objects to stop the hooks to be called + """ cache = {**cache} if cache is not None else {} hooks = [] @@ -318,4 +342,4 @@ detect_language = detect_language_function transcribe = transcribe_function - decode = decode_function+ decode = decode_function
https://raw.githubusercontent.com/openai/whisper/HEAD/whisper/model.py
Improve documentation using docstrings
from dataclasses import dataclass, field, replace from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Sequence, Tuple, Union import numpy as np import torch import torch.nn.functional as F from torch import Tensor from torch.distributions import Categorical from .audio import CHUNK_LENGTH from .tokenizer import Tokenizer, get_tokenizer from .utils import compression_ratio if TYPE_CHECKING: from .model import Whisper @torch.no_grad() def detect_language( model: "Whisper", mel: Tensor, tokenizer: Tokenizer = None ) -> Tuple[Tensor, List[dict]]: if tokenizer is None: tokenizer = get_tokenizer( model.is_multilingual, num_languages=model.num_languages ) if ( tokenizer.language is None or tokenizer.language_token not in tokenizer.sot_sequence ): raise ValueError( "This model doesn't have language tokens so it can't perform lang id" ) single = mel.ndim == 2 if single: mel = mel.unsqueeze(0) # skip encoder forward pass if already-encoded audio features were given if mel.shape[-2:] != (model.dims.n_audio_ctx, model.dims.n_audio_state): mel = model.encoder(mel) # forward pass using a single token, startoftranscript n_audio = mel.shape[0] x = torch.tensor([[tokenizer.sot]] * n_audio).to(mel.device) # [n_audio, 1] logits = model.logits(x, mel)[:, 0] # collect detected languages; suppress all non-language tokens mask = torch.ones(logits.shape[-1], dtype=torch.bool) mask[list(tokenizer.all_language_tokens)] = False logits[:, mask] = -np.inf language_tokens = logits.argmax(dim=-1) language_token_probs = logits.softmax(dim=-1).cpu() language_probs = [ { c: language_token_probs[i, j].item() for j, c in zip(tokenizer.all_language_tokens, tokenizer.all_language_codes) } for i in range(n_audio) ] if single: language_tokens = language_tokens[0] language_probs = language_probs[0] return language_tokens, language_probs @dataclass(frozen=True) class DecodingOptions: # whether to perform X->X "transcribe" or X->English "translate" task: str = "transcribe" # language that the audio is in; uses detected language if None language: Optional[str] = None # sampling-related options temperature: float = 0.0 sample_len: Optional[int] = None # maximum number of tokens to sample best_of: Optional[int] = None # number of independent sample trajectories, if t > 0 beam_size: Optional[int] = None # number of beams in beam search, if t == 0 patience: Optional[float] = None # patience in beam search (arxiv:2204.05424) # "alpha" in Google NMT, or None for length norm, when ranking generations # to select which to return among the beams or best-of-N samples length_penalty: Optional[float] = None # text or tokens to feed as the prompt or the prefix; for more info: # https://github.com/openai/whisper/discussions/117#discussioncomment-3727051 prompt: Optional[Union[str, List[int]]] = None # for the previous context prefix: Optional[Union[str, List[int]]] = None # to prefix the current context # list of tokens ids (or comma-separated token ids) to suppress # "-1" will suppress a set of symbols as defined in `tokenizer.non_speech_tokens()` suppress_tokens: Optional[Union[str, Iterable[int]]] = "-1" suppress_blank: bool = True # this will suppress blank outputs # timestamp sampling options without_timestamps: bool = False # use <|notimestamps|> to sample text tokens only max_initial_timestamp: Optional[float] = 1.0 # implementation details fp16: bool = True # use fp16 for most of the calculation @dataclass(frozen=True) class DecodingResult: audio_features: Tensor language: str language_probs: Optional[Dict[str, float]] = None tokens: List[int] = field(default_factory=list) text: str = "" avg_logprob: float = np.nan no_speech_prob: float = np.nan temperature: float = np.nan compression_ratio: float = np.nan class Inference: def logits(self, tokens: Tensor, audio_features: Tensor) -> Tensor: raise NotImplementedError def rearrange_kv_cache(self, source_indices) -> None: raise NotImplementedError def cleanup_caching(self) -> None: pass class PyTorchInference(Inference): def __init__(self, model: "Whisper", initial_token_length: int): self.model: "Whisper" = model self.initial_token_length = initial_token_length self.kv_cache = {} self.hooks = [] key_modules = [block.attn.key for block in self.model.decoder.blocks] value_modules = [block.attn.value for block in self.model.decoder.blocks] self.kv_modules = key_modules + value_modules def logits(self, tokens: Tensor, audio_features: Tensor) -> Tensor: if not self.kv_cache: self.kv_cache, self.hooks = self.model.install_kv_cache_hooks() if tokens.shape[-1] > self.initial_token_length: # only need to use the last token except in the first forward pass tokens = tokens[:, -1:] return self.model.decoder(tokens, audio_features, kv_cache=self.kv_cache) def cleanup_caching(self): for hook in self.hooks: hook.remove() self.kv_cache = {} self.hooks = [] def rearrange_kv_cache(self, source_indices): if source_indices != list(range(len(source_indices))): for module in self.kv_modules: # update the key/value cache to contain the selected sequences self.kv_cache[module] = self.kv_cache[module][source_indices].detach() class SequenceRanker: def rank( self, tokens: List[List[Tensor]], sum_logprobs: List[List[float]] ) -> List[int]: raise NotImplementedError class MaximumLikelihoodRanker(SequenceRanker): def __init__(self, length_penalty: Optional[float]): self.length_penalty = length_penalty def rank(self, tokens: List[List[Tensor]], sum_logprobs: List[List[float]]): def scores(logprobs, lengths): result = [] for logprob, length in zip(logprobs, lengths): if self.length_penalty is None: penalty = length else: # from the Google NMT paper penalty = ((5 + length) / 6) ** self.length_penalty result.append(logprob / penalty) return result # get the sequence with the highest score lengths = [[len(t) for t in s] for s in tokens] return [np.argmax(scores(p, l)) for p, l in zip(sum_logprobs, lengths)] class TokenDecoder: def reset(self): def update( self, tokens: Tensor, logits: Tensor, sum_logprobs: Tensor ) -> Tuple[Tensor, bool]: raise NotImplementedError def finalize( self, tokens: Tensor, sum_logprobs: Tensor ) -> Tuple[Sequence[Sequence[Tensor]], List[List[float]]]: raise NotImplementedError class GreedyDecoder(TokenDecoder): def __init__(self, temperature: float, eot: int): self.temperature = temperature self.eot = eot def update( self, tokens: Tensor, logits: Tensor, sum_logprobs: Tensor ) -> Tuple[Tensor, bool]: if self.temperature == 0: next_tokens = logits.argmax(dim=-1) else: next_tokens = Categorical(logits=logits / self.temperature).sample() logprobs = F.log_softmax(logits.float(), dim=-1) current_logprobs = logprobs[torch.arange(logprobs.shape[0]), next_tokens] sum_logprobs += current_logprobs * (tokens[:, -1] != self.eot) next_tokens[tokens[:, -1] == self.eot] = self.eot tokens = torch.cat([tokens, next_tokens[:, None]], dim=-1) completed = (tokens[:, -1] == self.eot).all() return tokens, completed def finalize(self, tokens: Tensor, sum_logprobs: Tensor): # make sure each sequence has at least one EOT token at the end tokens = F.pad(tokens, (0, 1), value=self.eot) return tokens, sum_logprobs.tolist() class BeamSearchDecoder(TokenDecoder): def __init__( self, beam_size: int, eot: int, inference: Inference, patience: Optional[float] = None, ): self.beam_size = beam_size self.eot = eot self.inference = inference self.patience = patience or 1.0 self.max_candidates: int = round(beam_size * self.patience) self.finished_sequences = None assert ( self.max_candidates > 0 ), f"Invalid beam size ({beam_size}) or patience ({patience})" def reset(self): self.finished_sequences = None def update( self, tokens: Tensor, logits: Tensor, sum_logprobs: Tensor ) -> Tuple[Tensor, bool]: if tokens.shape[0] % self.beam_size != 0: raise ValueError(f"{tokens.shape}[0] % {self.beam_size} != 0") n_audio = tokens.shape[0] // self.beam_size if self.finished_sequences is None: # for the first update self.finished_sequences = [{} for _ in range(n_audio)] logprobs = F.log_softmax(logits.float(), dim=-1) next_tokens, source_indices, finished_sequences = [], [], [] for i in range(n_audio): scores, sources, finished = {}, {}, {} # STEP 1: calculate the cumulative log probabilities for possible candidates for j in range(self.beam_size): idx = i * self.beam_size + j prefix = tokens[idx].tolist() for logprob, token in zip(*logprobs[idx].topk(self.beam_size + 1)): new_logprob = (sum_logprobs[idx] + logprob).item() sequence = tuple(prefix + [token.item()]) scores[sequence] = new_logprob sources[sequence] = idx # STEP 2: rank the candidates and keep the top beam_size sequences for each audio saved = 0 for sequence in sorted(scores, key=scores.get, reverse=True): if sequence[-1] == self.eot: finished[sequence] = scores[sequence] else: sum_logprobs[len(next_tokens)] = scores[sequence] next_tokens.append(sequence) source_indices.append(sources[sequence]) saved += 1 if saved == self.beam_size: break finished_sequences.append(finished) tokens = torch.tensor(next_tokens, device=tokens.device) self.inference.rearrange_kv_cache(source_indices) # add newly finished sequences to self.finished_sequences assert len(self.finished_sequences) == len(finished_sequences) for previously_finished, newly_finished in zip( self.finished_sequences, finished_sequences ): for seq in sorted(newly_finished, key=newly_finished.get, reverse=True): if len(previously_finished) >= self.max_candidates: break # the candidate list is full previously_finished[seq] = newly_finished[seq] # mark as completed if all audio has enough number of samples completed = all( len(sequences) >= self.max_candidates for sequences in self.finished_sequences ) return tokens, completed def finalize(self, preceding_tokens: Tensor, sum_logprobs: Tensor): # collect all finished sequences, including patience, and add unfinished ones if not enough sum_logprobs = sum_logprobs.cpu() for i, sequences in enumerate(self.finished_sequences): if ( len(sequences) < self.beam_size ): # when not enough sequences are finished for j in list(np.argsort(sum_logprobs[i]))[::-1]: sequence = preceding_tokens[i, j].tolist() + [self.eot] sequences[tuple(sequence)] = sum_logprobs[i][j].item() if len(sequences) >= self.beam_size: break tokens: List[List[Tensor]] = [ [torch.tensor(seq) for seq in sequences.keys()] for sequences in self.finished_sequences ] sum_logprobs: List[List[float]] = [ list(sequences.values()) for sequences in self.finished_sequences ] return tokens, sum_logprobs class LogitFilter: def apply(self, logits: Tensor, tokens: Tensor) -> None: raise NotImplementedError class SuppressBlank(LogitFilter): def __init__(self, tokenizer: Tokenizer, sample_begin: int): self.tokenizer = tokenizer self.sample_begin = sample_begin def apply(self, logits: Tensor, tokens: Tensor): if tokens.shape[1] == self.sample_begin: logits[:, self.tokenizer.encode(" ") + [self.tokenizer.eot]] = -np.inf class SuppressTokens(LogitFilter): def __init__(self, suppress_tokens: Sequence[int]): self.suppress_tokens = list(suppress_tokens) def apply(self, logits: Tensor, tokens: Tensor): logits[:, self.suppress_tokens] = -np.inf class ApplyTimestampRules(LogitFilter): def __init__( self, tokenizer: Tokenizer, sample_begin: int, max_initial_timestamp_index: Optional[int], ): self.tokenizer = tokenizer self.sample_begin = sample_begin self.max_initial_timestamp_index = max_initial_timestamp_index def apply(self, logits: Tensor, tokens: Tensor): # suppress <|notimestamps|> which is handled by without_timestamps if self.tokenizer.no_timestamps is not None: logits[:, self.tokenizer.no_timestamps] = -np.inf # timestamps have to appear in pairs, except directly before EOT; mask logits accordingly for k in range(tokens.shape[0]): sampled_tokens = tokens[k, self.sample_begin :] seq = [t for t in sampled_tokens.tolist()] last_was_timestamp = ( len(seq) >= 1 and seq[-1] >= self.tokenizer.timestamp_begin ) penultimate_was_timestamp = ( len(seq) < 2 or seq[-2] >= self.tokenizer.timestamp_begin ) if last_was_timestamp: if penultimate_was_timestamp: # has to be non-timestamp logits[k, self.tokenizer.timestamp_begin :] = -np.inf else: # cannot be normal text tokens logits[k, : self.tokenizer.eot] = -np.inf timestamps = sampled_tokens[ sampled_tokens.ge(self.tokenizer.timestamp_begin) ] if timestamps.numel() > 0: # timestamps shouldn't decrease; forbid timestamp tokens smaller than the last # also force each segment to have a nonzero length, to prevent infinite looping if last_was_timestamp and not penultimate_was_timestamp: timestamp_last = timestamps[-1] else: timestamp_last = timestamps[-1] + 1 logits[k, self.tokenizer.timestamp_begin : timestamp_last] = -np.inf if tokens.shape[1] == self.sample_begin: # suppress generating non-timestamp tokens at the beginning logits[:, : self.tokenizer.timestamp_begin] = -np.inf # apply the `max_initial_timestamp` option if self.max_initial_timestamp_index is not None: last_allowed = ( self.tokenizer.timestamp_begin + self.max_initial_timestamp_index ) logits[:, last_allowed + 1 :] = -np.inf # if sum of probability over timestamps is above any other token, sample timestamp logprobs = F.log_softmax(logits.float(), dim=-1) for k in range(tokens.shape[0]): timestamp_logprob = logprobs[k, self.tokenizer.timestamp_begin :].logsumexp( dim=-1 ) max_text_token_logprob = logprobs[k, : self.tokenizer.timestamp_begin].max() if timestamp_logprob > max_text_token_logprob: logits[k, : self.tokenizer.timestamp_begin] = -np.inf class DecodingTask: inference: Inference sequence_ranker: SequenceRanker decoder: TokenDecoder logit_filters: List[LogitFilter] def __init__(self, model: "Whisper", options: DecodingOptions): self.model = model language = options.language or "en" tokenizer = get_tokenizer( model.is_multilingual, num_languages=model.num_languages, language=language, task=options.task, ) self.tokenizer: Tokenizer = tokenizer self.options: DecodingOptions = self._verify_options(options) self.n_group: int = options.beam_size or options.best_of or 1 self.n_ctx: int = model.dims.n_text_ctx self.sample_len: int = options.sample_len or model.dims.n_text_ctx // 2 self.sot_sequence: Tuple[int] = tokenizer.sot_sequence if self.options.without_timestamps: self.sot_sequence = tokenizer.sot_sequence_including_notimestamps self.initial_tokens: Tuple[int] = self._get_initial_tokens() self.sample_begin: int = len(self.initial_tokens) self.sot_index: int = self.initial_tokens.index(tokenizer.sot) # inference: implements the forward pass through the decoder, including kv caching self.inference = PyTorchInference(model, len(self.initial_tokens)) # sequence ranker: implements how to rank a group of sampled sequences self.sequence_ranker = MaximumLikelihoodRanker(options.length_penalty) # decoder: implements how to select the next tokens, given the autoregressive distribution if options.beam_size is not None: self.decoder = BeamSearchDecoder( options.beam_size, tokenizer.eot, self.inference, options.patience ) else: self.decoder = GreedyDecoder(options.temperature, tokenizer.eot) # logit filters: applies various rules to suppress or penalize certain tokens self.logit_filters = [] if self.options.suppress_blank: self.logit_filters.append(SuppressBlank(self.tokenizer, self.sample_begin)) if self.options.suppress_tokens: self.logit_filters.append(SuppressTokens(self._get_suppress_tokens())) if not options.without_timestamps: precision = CHUNK_LENGTH / model.dims.n_audio_ctx # usually 0.02 seconds max_initial_timestamp_index = None if options.max_initial_timestamp: max_initial_timestamp_index = round( self.options.max_initial_timestamp / precision ) self.logit_filters.append( ApplyTimestampRules( tokenizer, self.sample_begin, max_initial_timestamp_index ) ) def _verify_options(self, options: DecodingOptions) -> DecodingOptions: if options.beam_size is not None and options.best_of is not None: raise ValueError("beam_size and best_of can't be given together") if options.temperature == 0: if options.best_of is not None: raise ValueError("best_of with greedy sampling (T=0) is not compatible") if options.patience is not None and options.beam_size is None: raise ValueError("patience requires beam_size to be given") if options.length_penalty is not None and not ( 0 <= options.length_penalty <= 1 ): raise ValueError("length_penalty (alpha) should be a value between 0 and 1") return options def _get_initial_tokens(self) -> Tuple[int]: tokens = list(self.sot_sequence) if prefix := self.options.prefix: prefix_tokens = ( self.tokenizer.encode(" " + prefix.strip()) if isinstance(prefix, str) else prefix ) if self.sample_len is not None: max_prefix_len = self.n_ctx // 2 - self.sample_len prefix_tokens = prefix_tokens[-max_prefix_len:] tokens = tokens + prefix_tokens if prompt := self.options.prompt: prompt_tokens = ( self.tokenizer.encode(" " + prompt.strip()) if isinstance(prompt, str) else prompt ) tokens = ( [self.tokenizer.sot_prev] + prompt_tokens[-(self.n_ctx // 2 - 1) :] + tokens ) return tuple(tokens) def _get_suppress_tokens(self) -> Tuple[int]: suppress_tokens = self.options.suppress_tokens if isinstance(suppress_tokens, str): suppress_tokens = [int(t) for t in suppress_tokens.split(",")] if -1 in suppress_tokens: suppress_tokens = [t for t in suppress_tokens if t >= 0] suppress_tokens.extend(self.tokenizer.non_speech_tokens) elif suppress_tokens is None or len(suppress_tokens) == 0: suppress_tokens = [] # interpret empty string as an empty list else: assert isinstance(suppress_tokens, list), "suppress_tokens must be a list" suppress_tokens.extend( [ self.tokenizer.transcribe, self.tokenizer.translate, self.tokenizer.sot, self.tokenizer.sot_prev, self.tokenizer.sot_lm, ] ) if self.tokenizer.no_speech is not None: # no-speech probability is collected separately suppress_tokens.append(self.tokenizer.no_speech) return tuple(sorted(set(suppress_tokens))) def _get_audio_features(self, mel: Tensor): if self.options.fp16: mel = mel.half() if mel.shape[-2:] == ( self.model.dims.n_audio_ctx, self.model.dims.n_audio_state, ): # encoded audio features are given; skip audio encoding audio_features = mel else: audio_features = self.model.encoder(mel) if audio_features.dtype != ( torch.float16 if self.options.fp16 else torch.float32 ): return TypeError( f"audio_features has an incorrect dtype: {audio_features.dtype}" ) return audio_features def _detect_language(self, audio_features: Tensor, tokens: Tensor): languages = [self.options.language] * audio_features.shape[0] lang_probs = None if self.options.language is None or self.options.task == "lang_id": lang_tokens, lang_probs = self.model.detect_language( audio_features, self.tokenizer ) languages = [max(probs, key=probs.get) for probs in lang_probs] if self.options.language is None: tokens[:, self.sot_index + 1] = lang_tokens # write language tokens return languages, lang_probs def _main_loop(self, audio_features: Tensor, tokens: Tensor): n_batch = tokens.shape[0] sum_logprobs: Tensor = torch.zeros(n_batch, device=audio_features.device) no_speech_probs = [np.nan] * n_batch try: for i in range(self.sample_len): logits = self.inference.logits(tokens, audio_features) if ( i == 0 and self.tokenizer.no_speech is not None ): # save no_speech_probs probs_at_sot = logits[:, self.sot_index].float().softmax(dim=-1) no_speech_probs = probs_at_sot[:, self.tokenizer.no_speech].tolist() # now we need to consider the logits at the last token only logits = logits[:, -1] # apply the logit filters, e.g. for suppressing or applying penalty to for logit_filter in self.logit_filters: logit_filter.apply(logits, tokens) # expand the tokens tensor with the selected next tokens tokens, completed = self.decoder.update(tokens, logits, sum_logprobs) if completed or tokens.shape[-1] > self.n_ctx: break finally: self.inference.cleanup_caching() return tokens, sum_logprobs, no_speech_probs @torch.no_grad() def run(self, mel: Tensor) -> List[DecodingResult]: self.decoder.reset() tokenizer: Tokenizer = self.tokenizer n_audio: int = mel.shape[0] audio_features: Tensor = self._get_audio_features(mel) # encoder forward pass tokens: Tensor = torch.tensor([self.initial_tokens]).repeat(n_audio, 1) # detect language if requested, overwriting the language token languages, language_probs = self._detect_language(audio_features, tokens) if self.options.task == "lang_id": return [ DecodingResult( audio_features=features, language=language, language_probs=probs ) for features, language, probs in zip( audio_features, languages, language_probs ) ] # repeat text tensors by the group size, for beam search or best-of-n sampling tokens = tokens.repeat_interleave(self.n_group, dim=0).to(audio_features.device) # call the main sampling loop tokens, sum_logprobs, no_speech_probs = self._main_loop(audio_features, tokens) # reshape the tensors to have (n_audio, n_group) as the first two dimensions audio_features = audio_features[:: self.n_group] no_speech_probs = no_speech_probs[:: self.n_group] assert audio_features.shape[0] == len(no_speech_probs) == n_audio tokens = tokens.reshape(n_audio, self.n_group, -1) sum_logprobs = sum_logprobs.reshape(n_audio, self.n_group) # get the final candidates for each group, and slice between the first sampled token and EOT tokens, sum_logprobs = self.decoder.finalize(tokens, sum_logprobs) tokens: List[List[Tensor]] = [ [t[self.sample_begin : (t == tokenizer.eot).nonzero()[0, 0]] for t in s] for s in tokens ] # select the top-ranked sample in each group selected = self.sequence_ranker.rank(tokens, sum_logprobs) tokens: List[List[int]] = [t[i].tolist() for i, t in zip(selected, tokens)] texts: List[str] = [tokenizer.decode(t).strip() for t in tokens] sum_logprobs: List[float] = [lp[i] for i, lp in zip(selected, sum_logprobs)] avg_logprobs: List[float] = [ lp / (len(t) + 1) for t, lp in zip(tokens, sum_logprobs) ] fields = ( texts, languages, tokens, audio_features, avg_logprobs, no_speech_probs, ) if len(set(map(len, fields))) != 1: raise RuntimeError(f"inconsistent result lengths: {list(map(len, fields))}") return [ DecodingResult( audio_features=features, language=language, tokens=tokens, text=text, avg_logprob=avg_logprob, no_speech_prob=no_speech_prob, temperature=self.options.temperature, compression_ratio=compression_ratio(text), ) for text, language, tokens, features, avg_logprob, no_speech_prob in zip( *fields ) ] @torch.no_grad() def decode( model: "Whisper", mel: Tensor, options: DecodingOptions = DecodingOptions(), **kwargs, ) -> Union[DecodingResult, List[DecodingResult]]: if single := mel.ndim == 2: mel = mel.unsqueeze(0) if kwargs: options = replace(options, **kwargs) result = DecodingTask(model, options).run(mel) return result[0] if single else result
--- +++ @@ -19,6 +19,18 @@ def detect_language( model: "Whisper", mel: Tensor, tokenizer: Tokenizer = None ) -> Tuple[Tensor, List[dict]]: + """ + Detect the spoken language in the audio, and return them as list of strings, along with the ids + of the most probable language tokens and the probability distribution over all language tokens. + This is performed outside the main decode loop in order to not interfere with kv-caching. + + Returns + ------- + language_tokens : Tensor, shape = (n_audio,) + ids of the most probable language tokens, which appears after the startoftranscript token. + language_probs : List[Dict[str, float]], length = n_audio + list of dictionaries containing the probability distribution over all languages. + """ if tokenizer is None: tokenizer = get_tokenizer( model.is_multilingual, num_languages=model.num_languages @@ -117,12 +129,15 @@ class Inference: def logits(self, tokens: Tensor, audio_features: Tensor) -> Tensor: + """Perform a forward pass on the decoder and return per-token logits""" raise NotImplementedError def rearrange_kv_cache(self, source_indices) -> None: + """Update the key-value cache according to the updated beams""" raise NotImplementedError def cleanup_caching(self) -> None: + """Clean up any resources or hooks after decoding is finished""" pass @@ -165,10 +180,18 @@ def rank( self, tokens: List[List[Tensor]], sum_logprobs: List[List[float]] ) -> List[int]: + """ + Given a list of groups of samples and their cumulative log probabilities, + return the indices of the samples in each group to select as the final result + """ raise NotImplementedError class MaximumLikelihoodRanker(SequenceRanker): + """ + Select the sample with the highest log probabilities, penalized using either + a simple length normalization or Google NMT paper's length penalty + """ def __init__(self, length_penalty: Optional[float]): self.length_penalty = length_penalty @@ -192,15 +215,57 @@ class TokenDecoder: def reset(self): + """Initialize any stateful variables for decoding a new sequence""" def update( self, tokens: Tensor, logits: Tensor, sum_logprobs: Tensor ) -> Tuple[Tensor, bool]: + """Specify how to select the next token, based on the current trace and logits + + Parameters + ---------- + tokens : Tensor, shape = (n_batch, current_sequence_length) + all tokens in the context so far, including the prefix and sot_sequence tokens + + logits : Tensor, shape = (n_batch, vocab_size) + per-token logits of the probability distribution at the current step + + sum_logprobs : Tensor, shape = (n_batch) + cumulative log probabilities for each sequence + + Returns + ------- + tokens : Tensor, shape = (n_batch, current_sequence_length + 1) + the tokens, appended with the selected next token + + completed : bool + True if all sequences has reached the end of text + + """ raise NotImplementedError def finalize( self, tokens: Tensor, sum_logprobs: Tensor ) -> Tuple[Sequence[Sequence[Tensor]], List[List[float]]]: + """Finalize search and return the final candidate sequences + + Parameters + ---------- + tokens : Tensor, shape = (n_audio, n_group, current_sequence_length) + all tokens in the context so far, including the prefix and sot_sequence + + sum_logprobs : Tensor, shape = (n_audio, n_group) + cumulative log probabilities for each sequence + + Returns + ------- + tokens : Sequence[Sequence[Tensor]], length = n_audio + sequence of Tensors containing candidate token sequences, for each audio input + + sum_logprobs : List[List[float]], length = n_audio + sequence of cumulative log probabilities corresponding to the above + + """ raise NotImplementedError @@ -341,6 +406,17 @@ class LogitFilter: def apply(self, logits: Tensor, tokens: Tensor) -> None: + """Apply any filtering or masking to logits in-place + + Parameters + ---------- + logits : Tensor, shape = (n_batch, vocab_size) + per-token logits of the probability distribution at the current step + + tokens : Tensor, shape = (n_batch, current_sequence_length) + all tokens in the context so far, including the prefix and sot_sequence tokens + + """ raise NotImplementedError @@ -720,6 +796,25 @@ options: DecodingOptions = DecodingOptions(), **kwargs, ) -> Union[DecodingResult, List[DecodingResult]]: + """ + Performs decoding of 30-second audio segment(s), provided as Mel spectrogram(s). + + Parameters + ---------- + model: Whisper + the Whisper model instance + + mel: torch.Tensor, shape = (80, 3000) or (*, 80, 3000) + A tensor containing the Mel spectrogram(s) + + options: DecodingOptions + A dataclass that contains all necessary options for decoding 30-second segments + + Returns + ------- + result: Union[DecodingResult, List[DecodingResult]] + The result(s) of decoding contained in `DecodingResult` dataclass instance(s) + """ if single := mel.ndim == 2: mel = mel.unsqueeze(0) @@ -728,4 +823,4 @@ result = DecodingTask(model, options).run(mel) - return result[0] if single else result+ return result[0] if single else result
https://raw.githubusercontent.com/openai/whisper/HEAD/whisper/decoding.py
Document all public functions with docstrings
import json import os import re from fractions import Fraction from typing import Iterator, List, Match, Optional, Union from more_itertools import windowed from .basic import remove_symbols_and_diacritics class EnglishNumberNormalizer: def __init__(self): super().__init__() self.zeros = {"o", "oh", "zero"} self.ones = { name: i for i, name in enumerate( [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ], start=1, ) } self.ones_plural = { "sixes" if name == "six" else name + "s": (value, "s") for name, value in self.ones.items() } self.ones_ordinal = { "zeroth": (0, "th"), "first": (1, "st"), "second": (2, "nd"), "third": (3, "rd"), "fifth": (5, "th"), "twelfth": (12, "th"), **{ name + ("h" if name.endswith("t") else "th"): (value, "th") for name, value in self.ones.items() if value > 3 and value != 5 and value != 12 }, } self.ones_suffixed = {**self.ones_plural, **self.ones_ordinal} self.tens = { "twenty": 20, "thirty": 30, "forty": 40, "fifty": 50, "sixty": 60, "seventy": 70, "eighty": 80, "ninety": 90, } self.tens_plural = { name.replace("y", "ies"): (value, "s") for name, value in self.tens.items() } self.tens_ordinal = { name.replace("y", "ieth"): (value, "th") for name, value in self.tens.items() } self.tens_suffixed = {**self.tens_plural, **self.tens_ordinal} self.multipliers = { "hundred": 100, "thousand": 1_000, "million": 1_000_000, "billion": 1_000_000_000, "trillion": 1_000_000_000_000, "quadrillion": 1_000_000_000_000_000, "quintillion": 1_000_000_000_000_000_000, "sextillion": 1_000_000_000_000_000_000_000, "septillion": 1_000_000_000_000_000_000_000_000, "octillion": 1_000_000_000_000_000_000_000_000_000, "nonillion": 1_000_000_000_000_000_000_000_000_000_000, "decillion": 1_000_000_000_000_000_000_000_000_000_000_000, } self.multipliers_plural = { name + "s": (value, "s") for name, value in self.multipliers.items() } self.multipliers_ordinal = { name + "th": (value, "th") for name, value in self.multipliers.items() } self.multipliers_suffixed = { **self.multipliers_plural, **self.multipliers_ordinal, } self.decimals = {*self.ones, *self.tens, *self.zeros} self.preceding_prefixers = { "minus": "-", "negative": "-", "plus": "+", "positive": "+", } self.following_prefixers = { "pound": "£", "pounds": "£", "euro": "€", "euros": "€", "dollar": "$", "dollars": "$", "cent": "¢", "cents": "¢", } self.prefixes = set( list(self.preceding_prefixers.values()) + list(self.following_prefixers.values()) ) self.suffixers = { "per": {"cent": "%"}, "percent": "%", } self.specials = {"and", "double", "triple", "point"} self.words = set( [ key for mapping in [ self.zeros, self.ones, self.ones_suffixed, self.tens, self.tens_suffixed, self.multipliers, self.multipliers_suffixed, self.preceding_prefixers, self.following_prefixers, self.suffixers, self.specials, ] for key in mapping ] ) self.literal_words = {"one", "ones"} def process_words(self, words: List[str]) -> Iterator[str]: prefix: Optional[str] = None value: Optional[Union[str, int]] = None skip = False def to_fraction(s: str): try: return Fraction(s) except ValueError: return None def output(result: Union[str, int]): nonlocal prefix, value result = str(result) if prefix is not None: result = prefix + result value = None prefix = None return result if len(words) == 0: return for prev, current, next in windowed([None] + words + [None], 3): if skip: skip = False continue next_is_numeric = next is not None and re.match(r"^\d+(\.\d+)?$", next) has_prefix = current[0] in self.prefixes current_without_prefix = current[1:] if has_prefix else current if re.match(r"^\d+(\.\d+)?$", current_without_prefix): # arabic numbers (potentially with signs and fractions) f = to_fraction(current_without_prefix) assert f is not None if value is not None: if isinstance(value, str) and value.endswith("."): # concatenate decimals / ip address components value = str(value) + str(current) continue else: yield output(value) prefix = current[0] if has_prefix else prefix if f.denominator == 1: value = f.numerator # store integers as int else: value = current_without_prefix elif current not in self.words: # non-numeric words if value is not None: yield output(value) yield output(current) elif current in self.zeros: value = str(value or "") + "0" elif current in self.ones: ones = self.ones[current] if value is None: value = ones elif isinstance(value, str) or prev in self.ones: if ( prev in self.tens and ones < 10 ): # replace the last zero with the digit assert value[-1] == "0" value = value[:-1] + str(ones) else: value = str(value) + str(ones) elif ones < 10: if value % 10 == 0: value += ones else: value = str(value) + str(ones) else: # eleven to nineteen if value % 100 == 0: value += ones else: value = str(value) + str(ones) elif current in self.ones_suffixed: # ordinal or cardinal; yield the number right away ones, suffix = self.ones_suffixed[current] if value is None: yield output(str(ones) + suffix) elif isinstance(value, str) or prev in self.ones: if prev in self.tens and ones < 10: assert value[-1] == "0" yield output(value[:-1] + str(ones) + suffix) else: yield output(str(value) + str(ones) + suffix) elif ones < 10: if value % 10 == 0: yield output(str(value + ones) + suffix) else: yield output(str(value) + str(ones) + suffix) else: # eleven to nineteen if value % 100 == 0: yield output(str(value + ones) + suffix) else: yield output(str(value) + str(ones) + suffix) value = None elif current in self.tens: tens = self.tens[current] if value is None: value = tens elif isinstance(value, str): value = str(value) + str(tens) else: if value % 100 == 0: value += tens else: value = str(value) + str(tens) elif current in self.tens_suffixed: # ordinal or cardinal; yield the number right away tens, suffix = self.tens_suffixed[current] if value is None: yield output(str(tens) + suffix) elif isinstance(value, str): yield output(str(value) + str(tens) + suffix) else: if value % 100 == 0: yield output(str(value + tens) + suffix) else: yield output(str(value) + str(tens) + suffix) elif current in self.multipliers: multiplier = self.multipliers[current] if value is None: value = multiplier elif isinstance(value, str) or value == 0: f = to_fraction(value) p = f * multiplier if f is not None else None if f is not None and p.denominator == 1: value = p.numerator else: yield output(value) value = multiplier else: before = value // 1000 * 1000 residual = value % 1000 value = before + residual * multiplier elif current in self.multipliers_suffixed: multiplier, suffix = self.multipliers_suffixed[current] if value is None: yield output(str(multiplier) + suffix) elif isinstance(value, str): f = to_fraction(value) p = f * multiplier if f is not None else None if f is not None and p.denominator == 1: yield output(str(p.numerator) + suffix) else: yield output(value) yield output(str(multiplier) + suffix) else: # int before = value // 1000 * 1000 residual = value % 1000 value = before + residual * multiplier yield output(str(value) + suffix) value = None elif current in self.preceding_prefixers: # apply prefix (positive, minus, etc.) if it precedes a number if value is not None: yield output(value) if next in self.words or next_is_numeric: prefix = self.preceding_prefixers[current] else: yield output(current) elif current in self.following_prefixers: # apply prefix (dollars, cents, etc.) only after a number if value is not None: prefix = self.following_prefixers[current] yield output(value) else: yield output(current) elif current in self.suffixers: # apply suffix symbols (percent -> '%') if value is not None: suffix = self.suffixers[current] if isinstance(suffix, dict): if next in suffix: yield output(str(value) + suffix[next]) skip = True else: yield output(value) yield output(current) else: yield output(str(value) + suffix) else: yield output(current) elif current in self.specials: if next not in self.words and not next_is_numeric: # apply special handling only if the next word can be numeric if value is not None: yield output(value) yield output(current) elif current == "and": # ignore "and" after hundreds, thousands, etc. if prev not in self.multipliers: if value is not None: yield output(value) yield output(current) elif current == "double" or current == "triple": if next in self.ones or next in self.zeros: repeats = 2 if current == "double" else 3 ones = self.ones.get(next, 0) value = str(value or "") + str(ones) * repeats skip = True else: if value is not None: yield output(value) yield output(current) elif current == "point": if next in self.decimals or next_is_numeric: value = str(value or "") + "." else: # should all have been covered at this point raise ValueError(f"Unexpected token: {current}") else: # all should have been covered at this point raise ValueError(f"Unexpected token: {current}") if value is not None: yield output(value) def preprocess(self, s: str): # replace "<number> and a half" with "<number> point five" results = [] segments = re.split(r"\band\s+a\s+half\b", s) for i, segment in enumerate(segments): if len(segment.strip()) == 0: continue if i == len(segments) - 1: results.append(segment) else: results.append(segment) last_word = segment.rsplit(maxsplit=2)[-1] if last_word in self.decimals or last_word in self.multipliers: results.append("point five") else: results.append("and a half") s = " ".join(results) # put a space at number/letter boundary s = re.sub(r"([a-z])([0-9])", r"\1 \2", s) s = re.sub(r"([0-9])([a-z])", r"\1 \2", s) # but remove spaces which could be a suffix s = re.sub(r"([0-9])\s+(st|nd|rd|th|s)\b", r"\1\2", s) return s def postprocess(self, s: str): def combine_cents(m: Match): try: currency = m.group(1) integer = m.group(2) cents = int(m.group(3)) return f"{currency}{integer}.{cents:02d}" except ValueError: return m.string def extract_cents(m: Match): try: return f"¢{int(m.group(1))}" except ValueError: return m.string # apply currency postprocessing; "$2 and ¢7" -> "$2.07" s = re.sub(r"([€£$])([0-9]+) (?:and )?¢([0-9]{1,2})\b", combine_cents, s) s = re.sub(r"[€£$]0.([0-9]{1,2})\b", extract_cents, s) # write "one(s)" instead of "1(s)", just for the readability s = re.sub(r"\b1(s?)\b", r"one\1", s) return s def __call__(self, s: str): s = self.preprocess(s) s = " ".join(word for word in self.process_words(s.split()) if word is not None) s = self.postprocess(s) return s class EnglishSpellingNormalizer: def __init__(self): mapping_path = os.path.join(os.path.dirname(__file__), "english.json") self.mapping = json.load(open(mapping_path)) def __call__(self, s: str): return " ".join(self.mapping.get(word, word) for word in s.split()) class EnglishTextNormalizer: def __init__(self): self.ignore_patterns = r"\b(hmm|mm|mhm|mmm|uh|um)\b" self.replacers = { # common contractions r"\bwon't\b": "will not", r"\bcan't\b": "can not", r"\blet's\b": "let us", r"\bain't\b": "aint", r"\by'all\b": "you all", r"\bwanna\b": "want to", r"\bgotta\b": "got to", r"\bgonna\b": "going to", r"\bi'ma\b": "i am going to", r"\bimma\b": "i am going to", r"\bwoulda\b": "would have", r"\bcoulda\b": "could have", r"\bshoulda\b": "should have", r"\bma'am\b": "madam", # contractions in titles/prefixes r"\bmr\b": "mister ", r"\bmrs\b": "missus ", r"\bst\b": "saint ", r"\bdr\b": "doctor ", r"\bprof\b": "professor ", r"\bcapt\b": "captain ", r"\bgov\b": "governor ", r"\bald\b": "alderman ", r"\bgen\b": "general ", r"\bsen\b": "senator ", r"\brep\b": "representative ", r"\bpres\b": "president ", r"\brev\b": "reverend ", r"\bhon\b": "honorable ", r"\basst\b": "assistant ", r"\bassoc\b": "associate ", r"\blt\b": "lieutenant ", r"\bcol\b": "colonel ", r"\bjr\b": "junior ", r"\bsr\b": "senior ", r"\besq\b": "esquire ", # prefect tenses, ideally it should be any past participles, but it's harder.. r"'d been\b": " had been", r"'s been\b": " has been", r"'d gone\b": " had gone", r"'s gone\b": " has gone", r"'d done\b": " had done", # "'s done" is ambiguous r"'s got\b": " has got", # general contractions r"n't\b": " not", r"'re\b": " are", r"'s\b": " is", r"'d\b": " would", r"'ll\b": " will", r"'t\b": " not", r"'ve\b": " have", r"'m\b": " am", } self.standardize_numbers = EnglishNumberNormalizer() self.standardize_spellings = EnglishSpellingNormalizer() def __call__(self, s: str): s = s.lower() s = re.sub(r"[<\[][^>\]]*[>\]]", "", s) # remove words between brackets s = re.sub(r"\(([^)]+?)\)", "", s) # remove words between parenthesis s = re.sub(self.ignore_patterns, "", s) s = re.sub(r"\s+'", "'", s) # when there's a space before an apostrophe for pattern, replacement in self.replacers.items(): s = re.sub(pattern, replacement, s) s = re.sub(r"(\d),(\d)", r"\1\2", s) # remove commas between digits s = re.sub(r"\.([^0-9]|$)", r" \1", s) # remove periods not followed by numbers s = remove_symbols_and_diacritics(s, keep=".%$¢€£") # keep numeric symbols s = self.standardize_numbers(s) s = self.standardize_spellings(s) # now remove prefix/suffix symbols that are not preceded/followed by numbers s = re.sub(r"[.$¢€£]([^0-9])", r" \1", s) s = re.sub(r"([^0-9])%", r"\1 ", s) s = re.sub(r"\s+", " ", s) # replace any successive whitespaces with a space return s
--- +++ @@ -10,6 +10,15 @@ class EnglishNumberNormalizer: + """ + Convert any spelled-out numbers into arabic numbers, while handling: + + - remove any commas + - keep the suffixes such as: `1960s`, `274th`, `32nd`, etc. + - spell out currency symbols after the number. e.g. `$20 million` -> `20000000 dollars` + - spell out `one` and `ones` + - interpret successive single-digit numbers as nominal: `one oh one` -> `101` + """ def __init__(self): super().__init__() @@ -439,6 +448,11 @@ class EnglishSpellingNormalizer: + """ + Applies British-American spelling mappings as listed in [1]. + + [1] https://www.tysto.com/uk-us-spelling-list.html + """ def __init__(self): mapping_path = os.path.join(os.path.dirname(__file__), "english.json") @@ -533,4 +547,4 @@ s = re.sub(r"\s+", " ", s) # replace any successive whitespaces with a space - return s+ return s
https://raw.githubusercontent.com/openai/whisper/HEAD/whisper/normalizers/english.py
Add structured docstrings to improve clarity
import re import unicodedata import regex # non-ASCII letters that are not separated by "NFKD" normalization ADDITIONAL_DIACRITICS = { "œ": "oe", "Œ": "OE", "ø": "o", "Ø": "O", "æ": "ae", "Æ": "AE", "ß": "ss", "ẞ": "SS", "đ": "d", "Đ": "D", "ð": "d", "Ð": "D", "þ": "th", "Þ": "th", "ł": "l", "Ł": "L", } def remove_symbols_and_diacritics(s: str, keep=""): return "".join( ( c if c in keep else ( ADDITIONAL_DIACRITICS[c] if c in ADDITIONAL_DIACRITICS else ( "" if unicodedata.category(c) == "Mn" else " " if unicodedata.category(c)[0] in "MSP" else c ) ) ) for c in unicodedata.normalize("NFKD", s) ) def remove_symbols(s: str): return "".join( " " if unicodedata.category(c)[0] in "MSP" else c for c in unicodedata.normalize("NFKC", s) ) class BasicTextNormalizer: def __init__(self, remove_diacritics: bool = False, split_letters: bool = False): self.clean = ( remove_symbols_and_diacritics if remove_diacritics else remove_symbols ) self.split_letters = split_letters def __call__(self, s: str): s = s.lower() s = re.sub(r"[<\[][^>\]]*[>\]]", "", s) # remove words between brackets s = re.sub(r"\(([^)]+?)\)", "", s) # remove words between parenthesis s = self.clean(s).lower() if self.split_letters: s = " ".join(regex.findall(r"\X", s, regex.U)) s = re.sub( r"\s+", " ", s ) # replace any successive whitespace characters with a space return s
--- +++ @@ -25,6 +25,10 @@ def remove_symbols_and_diacritics(s: str, keep=""): + """ + Replace any other markers, symbols, and punctuations with a space, + and drop any diacritics (category 'Mn' and some manual mappings) + """ return "".join( ( c @@ -44,6 +48,9 @@ def remove_symbols(s: str): + """ + Replace any other markers, symbols, punctuations with a space, keeping diacritics + """ return "".join( " " if unicodedata.category(c)[0] in "MSP" else c for c in unicodedata.normalize("NFKC", s) @@ -70,4 +77,4 @@ r"\s+", " ", s ) # replace any successive whitespace characters with a space - return s+ return s
https://raw.githubusercontent.com/openai/whisper/HEAD/whisper/normalizers/basic.py
Fully document this Python code with docstrings
# Copyright (c) 2016, Aaron Christianson # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED # TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from setuptools.command import easy_install import re TEMPLATE = r'''\ # -*- coding: utf-8 -*- # EASY-INSTALL-ENTRY-SCRIPT: '{3}','{4}','{5}' __requires__ = '{3}' import re import sys from {0} import {1} if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit({2}())''' @classmethod def get_args(cls, dist, header=None): if header is None: header = cls.get_header() spec = str(dist.as_requirement()) for type_ in 'console', 'gui': group = type_ + '_scripts' for name, ep in dist.get_entry_map(group).items(): # ensure_safe_name if re.search(r'[\\/]', name): raise ValueError("Path separators not allowed in script names") script_text = TEMPLATE.format( ep.module_name, ep.attrs[0], '.'.join(ep.attrs), spec, group, name) args = cls._get_script_args(type_, name, header, script_text) for res in args: yield res easy_install.ScriptWriter.get_args = get_args def main(): import os import re import shutil import sys dests = sys.argv[1:] or ['.'] filename = re.sub(r'\.pyc$', '.py', __file__) for dst in dests: shutil.copy(filename, dst) manifest_path = os.path.join(dst, 'MANIFEST.in') setup_path = os.path.join(dst, 'setup.py') # Insert the include statement to MANIFEST.in if not present with open(manifest_path, 'a+') as manifest: manifest.seek(0) manifest_content = manifest.read() if not 'include fastentrypoints.py' in manifest_content: manifest.write(('\n' if manifest_content else '') + 'include fastentrypoints.py') # Insert the import statement to setup.py if not present with open(setup_path, 'a+') as setup: setup.seek(0) setup_content = setup.read() if not 'import fastentrypoints' in setup_content: setup.seek(0) setup.truncate() setup.write('import fastentrypoints\n' + setup_content) print(__name__)
--- +++ @@ -23,6 +23,18 @@ # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +''' +Monkey patch setuptools to write faster console_scripts with this format: + + import sys + from mymodule import entry_function + sys.exit(entry_function()) + +This is better. + +(c) 2016, Aaron Christianson +http://github.com/ninjaaron/fast-entry_points +''' from setuptools.command import easy_install import re TEMPLATE = r'''\ @@ -41,6 +53,10 @@ @classmethod def get_args(cls, dist, header=None): + """ + Yield write_script() argument tuples for a distribution's + console_scripts and gui_scripts entry points. + """ if header is None: header = cls.get_header() spec = str(dist.as_requirement()) @@ -91,4 +107,4 @@ setup.truncate() setup.write('import fastentrypoints\n' + setup_content) -print(__name__)+print(__name__)
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/fastentrypoints.py
Insert docstrings into my code
import json import os import socket try: from shutil import get_terminal_size except ImportError: from backports.shutil_get_terminal_size import get_terminal_size import pyte from .. import const, logs def _get_socket_path(): return os.environ.get(const.SHELL_LOGGER_SOCKET_ENV) def is_available(): path = _get_socket_path() if not path: return False return os.path.exists(path) def _get_last_n(n): with socket.socket(socket.AF_UNIX) as client: client.connect(_get_socket_path()) request = json.dumps({ "type": "list", "count": n, }) + '\n' client.sendall(request.encode('utf-8')) response = client.makefile().readline() return json.loads(response)['commands'] def _get_output_lines(output): lines = output.split('\n') screen = pyte.Screen(get_terminal_size().columns, len(lines)) stream = pyte.Stream(screen) stream.feed('\n'.join(lines)) return screen.display def get_output(script): with logs.debug_time(u'Read output from external shell logger'): commands = _get_last_n(const.SHELL_LOGGER_LIMIT) for command in commands: if command['command'] == script: lines = _get_output_lines(command['output']) output = '\n'.join(lines).strip() return output else: logs.warn("Output isn't available in shell logger") return None
--- +++ @@ -14,6 +14,11 @@ def is_available(): + """Returns `True` if shell logger socket available. + + :rtype: book + + """ path = _get_socket_path() if not path: return False @@ -42,6 +47,7 @@ def get_output(script): + """Gets command output from shell logger.""" with logs.debug_time(u'Read output from external shell logger'): commands = _get_last_n(const.SHELL_LOGGER_LIMIT) for command in commands: @@ -51,4 +57,4 @@ return output else: logs.warn("Output isn't available in shell logger") - return None+ return None
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/output_readers/shell_logger.py
Document this code for team use
import os import sys from warnings import warn from six import text_type from . import const from .system import Path try: import importlib.util def load_source(name, pathname, _file=None): module_spec = importlib.util.spec_from_file_location(name, pathname) module = importlib.util.module_from_spec(module_spec) module_spec.loader.exec_module(module) return module except ImportError: from imp import load_source class Settings(dict): def __getattr__(self, item): return self.get(item) def __setattr__(self, key, value): self[key] = value def init(self, args=None): from .logs import exception self._setup_user_dir() self._init_settings_file() try: self.update(self._settings_from_file()) except Exception: exception("Can't load settings from file", sys.exc_info()) try: self.update(self._settings_from_env()) except Exception: exception("Can't load settings from env", sys.exc_info()) self.update(self._settings_from_args(args)) def _init_settings_file(self): settings_path = self.user_dir.joinpath('settings.py') if not settings_path.is_file(): with settings_path.open(mode='w') as settings_file: settings_file.write(const.SETTINGS_HEADER) for setting in const.DEFAULT_SETTINGS.items(): settings_file.write(u'# {} = {}\n'.format(*setting)) def _get_user_dir_path(self): xdg_config_home = os.environ.get('XDG_CONFIG_HOME', '~/.config') user_dir = Path(xdg_config_home, 'thefuck').expanduser() legacy_user_dir = Path('~', '.thefuck').expanduser() # For backward compatibility use legacy '~/.thefuck' if it exists: if legacy_user_dir.is_dir(): warn(u'Config path {} is deprecated. Please move to {}'.format( legacy_user_dir, user_dir)) return legacy_user_dir else: return user_dir def _setup_user_dir(self): user_dir = self._get_user_dir_path() rules_dir = user_dir.joinpath('rules') if not rules_dir.is_dir(): rules_dir.mkdir(parents=True) self.user_dir = user_dir def _settings_from_file(self): settings = load_source( 'settings', text_type(self.user_dir.joinpath('settings.py'))) return {key: getattr(settings, key) for key in const.DEFAULT_SETTINGS.keys() if hasattr(settings, key)} def _rules_from_env(self, val): val = val.split(':') if 'DEFAULT_RULES' in val: val = const.DEFAULT_RULES + [rule for rule in val if rule != 'DEFAULT_RULES'] return val def _priority_from_env(self, val): for part in val.split(':'): try: rule, priority = part.split('=') yield rule, int(priority) except ValueError: continue def _val_from_env(self, env, attr): val = os.environ[env] if attr in ('rules', 'exclude_rules'): return self._rules_from_env(val) elif attr == 'priority': return dict(self._priority_from_env(val)) elif attr in ('wait_command', 'history_limit', 'wait_slow_command', 'num_close_matches'): return int(val) elif attr in ('require_confirmation', 'no_colors', 'debug', 'alter_history', 'instant_mode'): return val.lower() == 'true' elif attr in ('slow_commands', 'excluded_search_path_prefixes'): return val.split(':') else: return val def _settings_from_env(self): return {attr: self._val_from_env(env, attr) for env, attr in const.ENV_TO_ATTR.items() if env in os.environ} def _settings_from_args(self, args): if not args: return {} from_args = {} if args.yes: from_args['require_confirmation'] = not args.yes if args.debug: from_args['debug'] = args.debug if args.repeat: from_args['repeat'] = args.repeat return from_args settings = Settings(const.DEFAULT_SETTINGS)
--- +++ @@ -25,6 +25,7 @@ self[key] = value def init(self, args=None): + """Fills `settings` with values from `settings.py` and env.""" from .logs import exception self._setup_user_dir() @@ -51,6 +52,7 @@ settings_file.write(u'# {} = {}\n'.format(*setting)) def _get_user_dir_path(self): + """Returns Path object representing the user config resource""" xdg_config_home = os.environ.get('XDG_CONFIG_HOME', '~/.config') user_dir = Path(xdg_config_home, 'thefuck').expanduser() legacy_user_dir = Path('~', '.thefuck').expanduser() @@ -64,6 +66,7 @@ return user_dir def _setup_user_dir(self): + """Returns user config dir, create it when it doesn't exist.""" user_dir = self._get_user_dir_path() rules_dir = user_dir.joinpath('rules') @@ -72,6 +75,7 @@ self.user_dir = user_dir def _settings_from_file(self): + """Loads settings from file.""" settings = load_source( 'settings', text_type(self.user_dir.joinpath('settings.py'))) return {key: getattr(settings, key) @@ -79,12 +83,14 @@ if hasattr(settings, key)} def _rules_from_env(self, val): + """Transforms rules list from env-string to python.""" val = val.split(':') if 'DEFAULT_RULES' in val: val = const.DEFAULT_RULES + [rule for rule in val if rule != 'DEFAULT_RULES'] return val def _priority_from_env(self, val): + """Gets priority pairs from env.""" for part in val.split(':'): try: rule, priority = part.split('=') @@ -93,6 +99,7 @@ continue def _val_from_env(self, env, attr): + """Transforms env-strings to python.""" val = os.environ[env] if attr in ('rules', 'exclude_rules'): return self._rules_from_env(val) @@ -110,11 +117,13 @@ return val def _settings_from_env(self): + """Loads settings from env.""" return {attr: self._val_from_env(env, attr) for env, attr in const.ENV_TO_ATTR.items() if env in os.environ} def _settings_from_args(self, args): + """Loads settings from args.""" if not args: return {} @@ -128,4 +137,4 @@ return from_args -settings = Settings(const.DEFAULT_SETTINGS)+settings = Settings(const.DEFAULT_SETTINGS)
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/conf.py
Document my Python code with docstrings
import array import fcntl from functools import partial import mmap import os import pty import signal import sys import termios import tty from .. import logs, const def _read(f, fd): data = os.read(fd, 1024) try: f.write(data) except ValueError: position = const.LOG_SIZE_IN_BYTES - const.LOG_SIZE_TO_CLEAN f.move(0, const.LOG_SIZE_TO_CLEAN, position) f.seek(position) f.write(b'\x00' * const.LOG_SIZE_TO_CLEAN) f.seek(position) return data def _set_pty_size(master_fd): buf = array.array('h', [0, 0, 0, 0]) fcntl.ioctl(pty.STDOUT_FILENO, termios.TIOCGWINSZ, buf, True) fcntl.ioctl(master_fd, termios.TIOCSWINSZ, buf) def _spawn(shell, master_read): pid, master_fd = pty.fork() if pid == pty.CHILD: os.execlp(shell, shell) try: mode = tty.tcgetattr(pty.STDIN_FILENO) tty.setraw(pty.STDIN_FILENO) restore = True except tty.error: # This is the same as termios.error restore = False _set_pty_size(master_fd) signal.signal(signal.SIGWINCH, lambda *_: _set_pty_size(master_fd)) try: pty._copy(master_fd, master_read, pty._read) except OSError: if restore: tty.tcsetattr(pty.STDIN_FILENO, tty.TCSAFLUSH, mode) os.close(master_fd) return os.waitpid(pid, 0)[1] def shell_logger(output): if not os.environ.get('SHELL'): logs.warn("Shell logger doesn't support your platform.") sys.exit(1) fd = os.open(output, os.O_CREAT | os.O_TRUNC | os.O_RDWR) os.write(fd, b'\x00' * const.LOG_SIZE_IN_BYTES) buffer = mmap.mmap(fd, const.LOG_SIZE_IN_BYTES, mmap.MAP_SHARED, mmap.PROT_WRITE) return_code = _spawn(os.environ['SHELL'], partial(_read, buffer)) sys.exit(return_code)
--- +++ @@ -31,6 +31,11 @@ def _spawn(shell, master_read): + """Create a spawned process. + + Modified version of pty.spawn with terminal size support. + + """ pid, master_fd = pty.fork() if pid == pty.CHILD: @@ -57,6 +62,11 @@ def shell_logger(output): + """Logs shell output to the `output`. + + Works like unix script command with `-f` flag. + + """ if not os.environ.get('SHELL'): logs.warn("Shell logger doesn't support your platform.") sys.exit(1) @@ -66,4 +76,4 @@ buffer = mmap.mmap(fd, const.LOG_SIZE_IN_BYTES, mmap.MAP_SHARED, mmap.PROT_WRITE) return_code = _spawn(os.environ['SHELL'], partial(_read, buffer)) - sys.exit(return_code)+ sys.exit(return_code)
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/entrypoints/shell_logger.py
Generate docstrings for each module
# Initialize output before importing any module, that can use colorama. from ..system import init_output init_output() import getpass # noqa: E402 import os # noqa: E402 import json # noqa: E402 from tempfile import gettempdir # noqa: E402 import time # noqa: E402 import six # noqa: E402 from psutil import Process # noqa: E402 from .. import logs, const # noqa: E402 from ..shells import shell # noqa: E402 from ..conf import settings # noqa: E402 from ..system import Path # noqa: E402 def _get_shell_pid(): proc = Process(os.getpid()) try: return proc.parent().pid except TypeError: return proc.parent.pid def _get_not_configured_usage_tracker_path(): return Path(gettempdir()).joinpath(u'thefuck.last_not_configured_run_{}'.format( getpass.getuser(), )) def _record_first_run(): info = {'pid': _get_shell_pid(), 'time': time.time()} mode = 'wb' if six.PY2 else 'w' with _get_not_configured_usage_tracker_path().open(mode) as tracker: json.dump(info, tracker) def _get_previous_command(): history = shell.get_history() if history: return history[-1] else: return None def _is_second_run(): tracker_path = _get_not_configured_usage_tracker_path() if not tracker_path.exists(): return False current_pid = _get_shell_pid() with tracker_path.open('r') as tracker: try: info = json.load(tracker) except ValueError: return False if not (isinstance(info, dict) and info.get('pid') == current_pid): return False return (_get_previous_command() == 'fuck' or time.time() - info.get('time', 0) < const.CONFIGURATION_TIMEOUT) def _is_already_configured(configuration_details): path = Path(configuration_details.path).expanduser() with path.open('r') as shell_config: return configuration_details.content in shell_config.read() def _configure(configuration_details): path = Path(configuration_details.path).expanduser() with path.open('a') as shell_config: shell_config.write(u'\n') shell_config.write(configuration_details.content) shell_config.write(u'\n') def main(): settings.init() configuration_details = shell.how_to_configure() if ( configuration_details and configuration_details.can_configure_automatically ): if _is_already_configured(configuration_details): logs.already_configured(configuration_details) return elif _is_second_run(): _configure(configuration_details) logs.configured_successfully(configuration_details) return else: _record_first_run() logs.how_to_configure_alias(configuration_details)
--- +++ @@ -17,6 +17,7 @@ def _get_shell_pid(): + """Returns parent process pid.""" proc = Process(os.getpid()) try: @@ -26,12 +27,14 @@ def _get_not_configured_usage_tracker_path(): + """Returns path of special file where we store latest shell pid.""" return Path(gettempdir()).joinpath(u'thefuck.last_not_configured_run_{}'.format( getpass.getuser(), )) def _record_first_run(): + """Records shell pid to tracker file.""" info = {'pid': _get_shell_pid(), 'time': time.time()} @@ -50,6 +53,7 @@ def _is_second_run(): + """Returns `True` when we know that `fuck` called second time.""" tracker_path = _get_not_configured_usage_tracker_path() if not tracker_path.exists(): return False @@ -69,12 +73,14 @@ def _is_already_configured(configuration_details): + """Returns `True` when alias already in shell config.""" path = Path(configuration_details.path).expanduser() with path.open('r') as shell_config: return configuration_details.content in shell_config.read() def _configure(configuration_details): + """Adds alias to shell config.""" path = Path(configuration_details.path).expanduser() with path.open('a') as shell_config: shell_config.write(u'\n') @@ -83,6 +89,12 @@ def main(): + """Shows useful information about how-to configure alias on a first run + and configure automatically on a second. + + It'll be only visible when user type fuck and when alias isn't configured. + + """ settings.init() configuration_details = shell.how_to_configure() if ( @@ -99,4 +111,4 @@ else: _record_first_run() - logs.how_to_configure_alias(configuration_details)+ logs.how_to_configure_alias(configuration_details)
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/entrypoints/not_configured.py
Add docstrings that explain purpose and usage
import sys from .conf import settings from .types import Rule from .system import Path from . import logs def get_loaded_rules(rules_paths): for path in rules_paths: if path.name != '__init__.py': rule = Rule.from_path(path) if rule and rule.is_enabled: yield rule def get_rules_import_paths(): # Bundled rules: yield Path(__file__).parent.joinpath('rules') # Rules defined by user: yield settings.user_dir.joinpath('rules') # Packages with third-party rules: for path in sys.path: for contrib_module in Path(path).glob('thefuck_contrib_*'): contrib_rules = contrib_module.joinpath('rules') if contrib_rules.is_dir(): yield contrib_rules def get_rules(): paths = [rule_path for path in get_rules_import_paths() for rule_path in sorted(path.glob('*.py'))] return sorted(get_loaded_rules(paths), key=lambda rule: rule.priority) def organize_commands(corrected_commands): try: first_command = next(corrected_commands) yield first_command except StopIteration: return without_duplicates = { command for command in sorted( corrected_commands, key=lambda command: command.priority) if command != first_command} sorted_commands = sorted( without_duplicates, key=lambda corrected_command: corrected_command.priority) logs.debug(u'Corrected commands: {}'.format( ', '.join(u'{}'.format(cmd) for cmd in [first_command] + sorted_commands))) for command in sorted_commands: yield command def get_corrected_commands(command): corrected_commands = ( corrected for rule in get_rules() if rule.is_match(command) for corrected in rule.get_corrected_commands(command)) return organize_commands(corrected_commands)
--- +++ @@ -6,6 +6,12 @@ def get_loaded_rules(rules_paths): + """Yields all available rules. + + :type rules_paths: [Path] + :rtype: Iterable[Rule] + + """ for path in rules_paths: if path.name != '__init__.py': rule = Rule.from_path(path) @@ -14,6 +20,11 @@ def get_rules_import_paths(): + """Yields all rules import paths. + + :rtype: Iterable[Path] + + """ # Bundled rules: yield Path(__file__).parent.joinpath('rules') # Rules defined by user: @@ -27,6 +38,11 @@ def get_rules(): + """Returns all enabled rules. + + :rtype: [Rule] + + """ paths = [rule_path for path in get_rules_import_paths() for rule_path in sorted(path.glob('*.py'))] return sorted(get_loaded_rules(paths), @@ -34,6 +50,12 @@ def organize_commands(corrected_commands): + """Yields sorted commands without duplicates. + + :type corrected_commands: Iterable[thefuck.types.CorrectedCommand] + :rtype: Iterable[thefuck.types.CorrectedCommand] + + """ try: first_command = next(corrected_commands) yield first_command @@ -57,8 +79,14 @@ def get_corrected_commands(command): + """Returns generator with sorted and unique corrected commands. + + :type command: thefuck.types.Command + :rtype: Iterable[thefuck.types.CorrectedCommand] + + """ corrected_commands = ( corrected for rule in get_rules() if rule.is_match(command) for corrected in rule.get_corrected_commands(command)) - return organize_commands(corrected_commands)+ return organize_commands(corrected_commands)
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/corrector.py
Generate missing documentation strings
from thefuck.utils import for_app from thefuck.shells import shell @for_app('docker') def match(command): return 'image is being used by running container' in command.output def get_new_command(command): container_id = command.output.strip().split(' ') return shell.and_('docker container rm -f {}', '{}').format(container_id[-1], command.script)
--- +++ @@ -4,9 +4,17 @@ @for_app('docker') def match(command): + ''' + Matches a command's output with docker's output + warning you that you need to remove a container before removing an image. + ''' return 'image is being used by running container' in command.output def get_new_command(command): + ''' + Prepends docker container rm -f {container ID} to + the previous docker image rm {image ID} command + ''' container_id = command.output.strip().split(' ') - return shell.and_('docker container rm -f {}', '{}').format(container_id[-1], command.script)+ return shell.and_('docker container rm -f {}', '{}').format(container_id[-1], command.script)
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/rules/docker_image_being_used_by_container.py
Write docstrings for algorithm functions
class EmptyCommand(Exception): class NoRuleMatched(Exception): class ScriptNotInLog(Exception):
--- +++ @@ -1,7 +1,10 @@ class EmptyCommand(Exception): + """Raised when empty command passed to `thefuck`.""" class NoRuleMatched(Exception): + """Raised when no rule matched for some command.""" -class ScriptNotInLog(Exception):+class ScriptNotInLog(Exception): + """Script not found in log."""
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/exceptions.py
Help me document legacy Python code
import sys from argparse import ArgumentParser, SUPPRESS from .const import ARGUMENT_PLACEHOLDER from .utils import get_alias class Parser(object): def __init__(self): self._parser = ArgumentParser(prog='thefuck', add_help=False) self._add_arguments() def _add_arguments(self): self._parser.add_argument( '-v', '--version', action='store_true', help="show program's version number and exit") self._parser.add_argument( '-a', '--alias', nargs='?', const=get_alias(), help='[custom-alias-name] prints alias for current shell') self._parser.add_argument( '-l', '--shell-logger', action='store', help='log shell output to the file') self._parser.add_argument( '--enable-experimental-instant-mode', action='store_true', help='enable experimental instant mode, use on your own risk') self._parser.add_argument( '-h', '--help', action='store_true', help='show this help message and exit') self._add_conflicting_arguments() self._parser.add_argument( '-d', '--debug', action='store_true', help='enable debug output') self._parser.add_argument( '--force-command', action='store', help=SUPPRESS) self._parser.add_argument( 'command', nargs='*', help='command that should be fixed') def _add_conflicting_arguments(self): group = self._parser.add_mutually_exclusive_group() group.add_argument( '-y', '--yes', '--yeah', '--hard', action='store_true', help='execute fixed command without confirmation') group.add_argument( '-r', '--repeat', action='store_true', help='repeat on failure') def _prepare_arguments(self, argv): if ARGUMENT_PLACEHOLDER in argv: index = argv.index(ARGUMENT_PLACEHOLDER) return argv[index + 1:] + ['--'] + argv[:index] elif argv and not argv[0].startswith('-') and argv[0] != '--': return ['--'] + argv else: return argv def parse(self, argv): arguments = self._prepare_arguments(argv[1:]) return self._parser.parse_args(arguments) def print_usage(self): self._parser.print_usage(sys.stderr) def print_help(self): self._parser.print_help(sys.stderr)
--- +++ @@ -5,12 +5,17 @@ class Parser(object): + """Argument parser that can handle arguments with our special + placeholder. + + """ def __init__(self): self._parser = ArgumentParser(prog='thefuck', add_help=False) self._add_arguments() def _add_arguments(self): + """Adds arguments to parser.""" self._parser.add_argument( '-v', '--version', action='store_true', @@ -47,6 +52,7 @@ help='command that should be fixed') def _add_conflicting_arguments(self): + """It's too dangerous to use `-y` and `-r` together.""" group = self._parser.add_mutually_exclusive_group() group.add_argument( '-y', '--yes', '--yeah', '--hard', @@ -58,6 +64,15 @@ help='repeat on failure') def _prepare_arguments(self, argv): + """Prepares arguments by: + + - removing placeholder and moving arguments after it to beginning, + we need this to distinguish arguments from `command` with ours; + + - adding `--` before `command`, so our parse would ignore arguments + of `command`. + + """ if ARGUMENT_PLACEHOLDER in argv: index = argv.index(ARGUMENT_PLACEHOLDER) return argv[index + 1:] + ['--'] + argv[:index] @@ -74,4 +89,4 @@ self._parser.print_usage(sys.stderr) def print_help(self): - self._parser.print_help(sys.stderr)+ self._parser.print_help(sys.stderr)
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/argument_parser.py
Improve documentation using docstrings
import os import re from thefuck.utils import get_closest, replace_command from thefuck.specific.brew import get_brew_path_prefix, brew_available BREW_CMD_PATH = '/Homebrew/Library/Homebrew/cmd' TAP_PATH = '/Homebrew/Library/Taps' TAP_CMD_PATH = '/%s/%s/cmd' enabled_by_default = brew_available def _get_brew_commands(brew_path_prefix): brew_cmd_path = brew_path_prefix + BREW_CMD_PATH return [name[:-3] for name in os.listdir(brew_cmd_path) if name.endswith(('.rb', '.sh'))] def _get_brew_tap_specific_commands(brew_path_prefix): commands = [] brew_taps_path = brew_path_prefix + TAP_PATH for user in _get_directory_names_only(brew_taps_path): taps = _get_directory_names_only(brew_taps_path + '/%s' % user) # Brew Taps's naming rule # https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/brew-tap.md#naming-conventions-and-limitations taps = (tap for tap in taps if tap.startswith('homebrew-')) for tap in taps: tap_cmd_path = brew_taps_path + TAP_CMD_PATH % (user, tap) if os.path.isdir(tap_cmd_path): commands += (name.replace('brew-', '').replace('.rb', '') for name in os.listdir(tap_cmd_path) if _is_brew_tap_cmd_naming(name)) return commands def _is_brew_tap_cmd_naming(name): return name.startswith('brew-') and name.endswith('.rb') def _get_directory_names_only(path): return [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))] def _brew_commands(): brew_path_prefix = get_brew_path_prefix() if brew_path_prefix: try: return (_get_brew_commands(brew_path_prefix) + _get_brew_tap_specific_commands(brew_path_prefix)) except OSError: pass # Failback commands for testing (Based on Homebrew 0.9.5) return ['info', 'home', 'options', 'install', 'uninstall', 'search', 'list', 'update', 'upgrade', 'pin', 'unpin', 'doctor', 'create', 'edit', 'cask'] def match(command): is_proper_command = ('brew' in command.script and 'Unknown command' in command.output) if is_proper_command: broken_cmd = re.findall(r'Error: Unknown command: ([a-z]+)', command.output)[0] return bool(get_closest(broken_cmd, _brew_commands())) return False def get_new_command(command): broken_cmd = re.findall(r'Error: Unknown command: ([a-z]+)', command.output)[0] return replace_command(command, broken_cmd, _brew_commands())
--- +++ @@ -11,6 +11,7 @@ def _get_brew_commands(brew_path_prefix): + """To get brew default commands on local environment""" brew_cmd_path = brew_path_prefix + BREW_CMD_PATH return [name[:-3] for name in os.listdir(brew_cmd_path) @@ -18,6 +19,8 @@ def _get_brew_tap_specific_commands(brew_path_prefix): + """To get tap's specific commands + https://github.com/Homebrew/homebrew/blob/master/Library/brew.rb#L115""" commands = [] brew_taps_path = brew_path_prefix + TAP_PATH @@ -76,4 +79,4 @@ def get_new_command(command): broken_cmd = re.findall(r'Error: Unknown command: ([a-z]+)', command.output)[0] - return replace_command(command, broken_cmd, _brew_commands())+ return replace_command(command, broken_cmd, _brew_commands())
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/rules/brew_unknown_command.py
Add docstrings to existing functions
import os import shlex import six from subprocess import Popen, PIPE, STDOUT from psutil import AccessDenied, Process, TimeoutExpired from .. import logs from ..conf import settings def _kill_process(proc): try: proc.kill() except AccessDenied: logs.debug(u'Rerun: process PID {} ({}) could not be terminated'.format( proc.pid, proc.exe())) def _wait_output(popen, is_slow): proc = Process(popen.pid) try: proc.wait(settings.wait_slow_command if is_slow else settings.wait_command) return True except TimeoutExpired: for child in proc.children(recursive=True): _kill_process(child) _kill_process(proc) return False def get_output(script, expanded): env = dict(os.environ) env.update(settings.env) if six.PY2: expanded = expanded.encode('utf-8') split_expand = shlex.split(expanded) is_slow = split_expand[0] in settings.slow_commands if split_expand else False with logs.debug_time(u'Call: {}; with env: {}; is slow: {}'.format( script, env, is_slow)): result = Popen(expanded, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, env=env) if _wait_output(result, is_slow): output = result.stdout.read().decode('utf-8', errors='replace') logs.debug(u'Received output: {}'.format(output)) return output else: logs.debug(u'Execution timed out!') return None
--- +++ @@ -8,6 +8,12 @@ def _kill_process(proc): + """Tries to kill the process otherwise just logs a debug message, the + process will be killed when thefuck terminates. + + :type proc: Process + + """ try: proc.kill() except AccessDenied: @@ -16,6 +22,15 @@ def _wait_output(popen, is_slow): + """Returns `True` if we can get output of the command in the + `settings.wait_command` time. + + Command will be killed if it wasn't finished in the time. + + :type popen: Popen + :rtype: bool + + """ proc = Process(popen.pid) try: proc.wait(settings.wait_slow_command if is_slow @@ -29,6 +44,13 @@ def get_output(script, expanded): + """Runs the script and obtains stdin/stderr. + + :type script: str + :type expanded: str + :rtype: str | None + + """ env = dict(os.environ) env.update(settings.env) @@ -47,4 +69,4 @@ return output else: logs.debug(u'Execution timed out!') - return None+ return None
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/output_readers/rerun.py
Write docstrings for data processing functions
import os import six from thefuck.specific.sudo import sudo_support from thefuck.rules import cd_mkdir from thefuck.utils import for_app, get_close_matches __author__ = "mmussomele" MAX_ALLOWED_DIFF = 0.6 def _get_sub_dirs(parent): return [child for child in os.listdir(parent) if os.path.isdir(os.path.join(parent, child))] @sudo_support @for_app('cd') def match(command): return ( command.script.startswith('cd ') and any(( 'no such file or directory' in command.output.lower(), 'cd: can\'t cd to' in command.output.lower(), 'does not exist' in command.output.lower() ))) @sudo_support def get_new_command(command): dest = command.script_parts[1].split(os.sep) if dest[-1] == '': dest = dest[:-1] if dest[0] == '': cwd = os.sep dest = dest[1:] elif six.PY2: cwd = os.getcwdu() else: cwd = os.getcwd() for directory in dest: if directory == ".": continue elif directory == "..": cwd = os.path.split(cwd)[0] continue best_matches = get_close_matches(directory, _get_sub_dirs(cwd), cutoff=MAX_ALLOWED_DIFF) if best_matches: cwd = os.path.join(cwd, best_matches[0]) else: return cd_mkdir.get_new_command(command) return u'cd "{0}"'.format(cwd)
--- +++ @@ -1,3 +1,4 @@+"""Attempts to spellcheck and correct failed cd commands""" import os import six @@ -11,12 +12,14 @@ def _get_sub_dirs(parent): + """Returns a list of the child directories of the given parent directory""" return [child for child in os.listdir(parent) if os.path.isdir(os.path.join(parent, child))] @sudo_support @for_app('cd') def match(command): + """Match function copied from cd_mkdir.py""" return ( command.script.startswith('cd ') and any(( 'no such file or directory' in command.output.lower(), @@ -27,6 +30,12 @@ @sudo_support def get_new_command(command): + """ + Attempt to rebuild the path string by spellchecking the directories. + If it fails (i.e. no directories are a close enough match), then it + defaults to the rules of cd_mkdir. + Change sensitivity by changing MAX_ALLOWED_DIFF. Default value is 0.6 + """ dest = command.script_parts[1].split(os.sep) if dest[-1] == '': dest = dest[:-1] @@ -49,4 +58,4 @@ cwd = os.path.join(cwd, best_matches[0]) else: return cd_mkdir.get_new_command(command) - return u'cd "{0}"'.format(cwd)+ return u'cd "{0}"'.format(cwd)
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/rules/cd_correction.py
Create docstrings for all classes and functions
from subprocess import Popen, PIPE from time import time import os import sys import six from .. import logs from ..conf import settings from ..const import ARGUMENT_PLACEHOLDER from ..utils import DEVNULL, cache from .generic import Generic @cache('~/.config/fish/config.fish', '~/.config/fish/functions') def _get_functions(overridden): proc = Popen(['fish', '-ic', 'functions'], stdout=PIPE, stderr=DEVNULL) functions = proc.stdout.read().decode('utf-8').strip().split('\n') return {func: func for func in functions if func not in overridden} @cache('~/.config/fish/config.fish') def _get_aliases(overridden): aliases = {} proc = Popen(['fish', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL) alias_out = proc.stdout.read().decode('utf-8').strip() if not alias_out: return aliases for alias in alias_out.split('\n'): for separator in (' ', '='): split_alias = alias.replace('alias ', '', 1).split(separator, 1) if len(split_alias) == 2: name, value = split_alias break else: continue if name not in overridden: aliases[name] = value return aliases class Fish(Generic): friendly_name = 'Fish Shell' def _get_overridden_aliases(self): overridden = os.environ.get('THEFUCK_OVERRIDDEN_ALIASES', os.environ.get('TF_OVERRIDDEN_ALIASES', '')) default = {'cd', 'grep', 'ls', 'man', 'open'} for alias in overridden.split(','): default.add(alias.strip()) return sorted(default) def app_alias(self, alias_name): if settings.alter_history: alter_history = (' builtin history delete --exact' ' --case-sensitive -- $fucked_up_command\n' ' builtin history merge\n') else: alter_history = '' # It is VERY important to have the variables declared WITHIN the alias return ('function {0} -d "Correct your previous console command"\n' ' set -l fucked_up_command $history[1]\n' ' env TF_SHELL=fish TF_ALIAS={0} PYTHONIOENCODING=utf-8' ' thefuck $fucked_up_command {2} $argv | read -l unfucked_command\n' ' if [ "$unfucked_command" != "" ]\n' ' eval $unfucked_command\n{1}' ' end\n' 'end').format(alias_name, alter_history, ARGUMENT_PLACEHOLDER) def get_aliases(self): overridden = self._get_overridden_aliases() functions = _get_functions(overridden) raw_aliases = _get_aliases(overridden) functions.update(raw_aliases) return functions def _expand_aliases(self, command_script): aliases = self.get_aliases() binary = command_script.split(' ')[0] if binary in aliases and aliases[binary] != binary: return command_script.replace(binary, aliases[binary], 1) elif binary in aliases: return u'fish -ic "{}"'.format(command_script.replace('"', r'\"')) else: return command_script def _get_history_file_name(self): return os.path.expanduser('~/.config/fish/fish_history') def _get_history_line(self, command_script): return u'- cmd: {}\n when: {}\n'.format(command_script, int(time())) def _script_from_history(self, line): if '- cmd: ' in line: return line.split('- cmd: ', 1)[1] else: return '' def and_(self, *commands): return u'; and '.join(commands) def or_(self, *commands): return u'; or '.join(commands) def how_to_configure(self): return self._create_shell_configuration( content=u"thefuck --alias | source", path='~/.config/fish/config.fish', reload='fish') def _get_version(self): proc = Popen(['fish', '--version'], stdout=PIPE, stderr=DEVNULL) return proc.stdout.read().decode('utf-8').split()[-1] def put_to_history(self, command): try: return self._put_to_history(command) except IOError: logs.exception("Can't update history", sys.exc_info()) def _put_to_history(self, command_script): history_file_name = self._get_history_file_name() if os.path.isfile(history_file_name): with open(history_file_name, 'a') as history: entry = self._get_history_line(command_script) if six.PY2: history.write(entry.encode('utf-8')) else: history.write(entry)
--- +++ @@ -107,6 +107,7 @@ reload='fish') def _get_version(self): + """Returns the version of the current shell""" proc = Popen(['fish', '--version'], stdout=PIPE, stderr=DEVNULL) return proc.stdout.read().decode('utf-8').split()[-1] @@ -117,6 +118,7 @@ logs.exception("Can't update history", sys.exc_info()) def _put_to_history(self, command_script): + """Puts command script to shell history.""" history_file_name = self._get_history_file_name() if os.path.isfile(history_file_name): with open(history_file_name, 'a') as history: @@ -124,4 +126,4 @@ if six.PY2: history.write(entry.encode('utf-8')) else: - history.write(entry)+ history.write(entry)
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/shells/fish.py
Create documentation strings for testing functions
import io import os import shlex import six from collections import namedtuple from ..logs import warn from ..utils import memoize from ..conf import settings from ..system import Path ShellConfiguration = namedtuple('ShellConfiguration', ( 'content', 'path', 'reload', 'can_configure_automatically')) class Generic(object): friendly_name = 'Generic Shell' def get_aliases(self): return {} def _expand_aliases(self, command_script): aliases = self.get_aliases() binary = command_script.split(' ')[0] if binary in aliases: return command_script.replace(binary, aliases[binary], 1) else: return command_script def from_shell(self, command_script): return self._expand_aliases(command_script) def to_shell(self, command_script): return command_script def app_alias(self, alias_name): return """alias {0}='eval "$(TF_ALIAS={0} PYTHONIOENCODING=utf-8 """ \ """thefuck "$(fc -ln -1)")"'""".format(alias_name) def instant_mode_alias(self, alias_name): warn("Instant mode not supported by your shell") return self.app_alias(alias_name) def _get_history_file_name(self): return '' def _get_history_line(self, command_script): return '' @memoize def get_history(self): return list(self._get_history_lines()) def _get_history_lines(self): history_file_name = self._get_history_file_name() if os.path.isfile(history_file_name): with io.open(history_file_name, 'r', encoding='utf-8', errors='ignore') as history_file: lines = history_file.readlines() if settings.history_limit: lines = lines[-settings.history_limit:] for line in lines: prepared = self._script_from_history(line) \ .strip() if prepared: yield prepared def and_(self, *commands): return u' && '.join(commands) def or_(self, *commands): return u' || '.join(commands) def how_to_configure(self): return def split_command(self, command): encoded = self.encode_utf8(command) try: splitted = [s.replace("??", "\\ ") for s in shlex.split(encoded.replace('\\ ', '??'))] except ValueError: splitted = encoded.split(' ') return self.decode_utf8(splitted) def encode_utf8(self, command): if six.PY2: return command.encode('utf8') return command def decode_utf8(self, command_parts): if six.PY2: return [s.decode('utf8') for s in command_parts] return command_parts def quote(self, s): if six.PY2: from pipes import quote else: from shlex import quote return quote(s) def _script_from_history(self, line): return line def put_to_history(self, command): def get_builtin_commands(self): return ['alias', 'bg', 'bind', 'break', 'builtin', 'case', 'cd', 'command', 'compgen', 'complete', 'continue', 'declare', 'dirs', 'disown', 'echo', 'enable', 'eval', 'exec', 'exit', 'export', 'fc', 'fg', 'getopts', 'hash', 'help', 'history', 'if', 'jobs', 'kill', 'let', 'local', 'logout', 'popd', 'printf', 'pushd', 'pwd', 'read', 'readonly', 'return', 'set', 'shift', 'shopt', 'source', 'suspend', 'test', 'times', 'trap', 'type', 'typeset', 'ulimit', 'umask', 'unalias', 'unset', 'until', 'wait', 'while'] def _get_version(self): return '' def info(self): try: version = self._get_version() except Exception as e: warn(u'Could not determine shell version: {}'.format(e)) version = '' return u'{} {}'.format(self.friendly_name, version).rstrip() def _create_shell_configuration(self, content, path, reload): return ShellConfiguration( content=content, path=path, reload=reload, can_configure_automatically=Path(path).expanduser().exists())
--- +++ @@ -28,9 +28,11 @@ return command_script def from_shell(self, command_script): + """Prepares command before running in app.""" return self._expand_aliases(command_script) def to_shell(self, command_script): + """Prepares command for running in shell.""" return command_script def app_alias(self, alias_name): @@ -52,6 +54,7 @@ return list(self._get_history_lines()) def _get_history_lines(self): + """Returns list of history entries.""" history_file_name = self._get_history_file_name() if os.path.isfile(history_file_name): with io.open(history_file_name, 'r', @@ -77,6 +80,7 @@ return def split_command(self, command): + """Split the command using shell-like syntax.""" encoded = self.encode_utf8(command) try: @@ -97,6 +101,7 @@ return command_parts def quote(self, s): + """Return a shell-escaped version of the string s.""" if six.PY2: from pipes import quote @@ -109,8 +114,15 @@ return line def put_to_history(self, command): + """Adds fixed command to shell history. + + In most of shells we change history on shell-level, but not + all shells support it (Fish). + + """ def get_builtin_commands(self): + """Returns shells builtin commands.""" return ['alias', 'bg', 'bind', 'break', 'builtin', 'case', 'cd', 'command', 'compgen', 'complete', 'continue', 'declare', 'dirs', 'disown', 'echo', 'enable', 'eval', 'exec', 'exit', @@ -122,9 +134,11 @@ 'until', 'wait', 'while'] def _get_version(self): + """Returns the version of the current shell""" return '' def info(self): + """Returns the name and version of the current shell""" try: version = self._get_version() except Exception as e: @@ -137,4 +151,4 @@ content=content, path=path, reload=reload, - can_configure_automatically=Path(path).expanduser().exists())+ can_configure_automatically=Path(path).expanduser().exists())
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/shells/generic.py
Document all endpoints with docstrings
import subprocess from .. import utils @utils.memoize def get_pkgfile(command): try: command = command.strip() if command.startswith('sudo '): command = command[5:] command = command.split(" ")[0] packages = subprocess.check_output( ['pkgfile', '-b', '-v', command], universal_newlines=True, stderr=utils.DEVNULL ).splitlines() return [package.split()[0] for package in packages] except subprocess.CalledProcessError as err: if err.returncode == 1 and err.output == "": return [] else: raise err def archlinux_env(): if utils.which('yay'): pacman = 'yay' elif utils.which('pikaur'): pacman = 'pikaur' elif utils.which('yaourt'): pacman = 'yaourt' elif utils.which('pacman'): pacman = 'sudo pacman' else: return False, None enabled_by_default = utils.which('pkgfile') return enabled_by_default, pacman
--- +++ @@ -1,9 +1,15 @@+""" This file provide some utility functions for Arch Linux specific rules.""" import subprocess from .. import utils @utils.memoize def get_pkgfile(command): + """ Gets the packages that provide the given command using `pkgfile`. + + If the command is of the form `sudo foo`, searches for the `foo` command + instead. + """ try: command = command.strip() @@ -39,4 +45,4 @@ enabled_by_default = utils.which('pkgfile') - return enabled_by_default, pacman+ return enabled_by_default, pacman
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/specific/archlinux.py
Help me write clear docstrings
from typing import Any from markitdown import MarkItDown from ._ocr_service import LLMVisionOCRService from ._pdf_converter_with_ocr import PdfConverterWithOCR from ._docx_converter_with_ocr import DocxConverterWithOCR from ._pptx_converter_with_ocr import PptxConverterWithOCR from ._xlsx_converter_with_ocr import XlsxConverterWithOCR __plugin_interface_version__ = 1 def register_converters(markitdown: MarkItDown, **kwargs: Any) -> None: # Create OCR service — reads the same llm_client/llm_model kwargs # that MarkItDown itself already accepts for image descriptions llm_client = kwargs.get("llm_client") llm_model = kwargs.get("llm_model") llm_prompt = kwargs.get("llm_prompt") ocr_service: LLMVisionOCRService | None = None if llm_client and llm_model: ocr_service = LLMVisionOCRService( client=llm_client, model=llm_model, default_prompt=llm_prompt, ) # Register converters with priority -1.0 (before built-ins at 0.0) # This effectively "replaces" the built-in converters when plugin is installed # Pass the OCR service to each converter's constructor PRIORITY_OCR_ENHANCED = -1.0 markitdown.register_converter( PdfConverterWithOCR(ocr_service=ocr_service), priority=PRIORITY_OCR_ENHANCED ) markitdown.register_converter( DocxConverterWithOCR(ocr_service=ocr_service), priority=PRIORITY_OCR_ENHANCED ) markitdown.register_converter( PptxConverterWithOCR(ocr_service=ocr_service), priority=PRIORITY_OCR_ENHANCED ) markitdown.register_converter( XlsxConverterWithOCR(ocr_service=ocr_service), priority=PRIORITY_OCR_ENHANCED )
--- +++ @@ -1,3 +1,7 @@+""" +Plugin registration for markitdown-ocr. +Registers OCR-enhanced converters with priority-based replacement strategy. +""" from typing import Any from markitdown import MarkItDown @@ -13,6 +17,21 @@ def register_converters(markitdown: MarkItDown, **kwargs: Any) -> None: + """ + Register OCR-enhanced converters with MarkItDown. + + This plugin provides OCR support for PDF, DOCX, PPTX, and XLSX files. + The converters are registered with priority -1.0 to run BEFORE built-in + converters (which have priority 0.0), effectively replacing them when + the plugin is enabled. + + Args: + markitdown: MarkItDown instance to register converters with + **kwargs: Additional keyword arguments that may include: + - llm_client: OpenAI-compatible client for LLM-based OCR (required for OCR to work) + - llm_model: Model name (e.g., 'gpt-4o') + - llm_prompt: Custom prompt for text extraction + """ # Create OCR service — reads the same llm_client/llm_model kwargs # that MarkItDown itself already accepts for image descriptions llm_client = kwargs.get("llm_client") @@ -46,4 +65,4 @@ markitdown.register_converter( XlsxConverterWithOCR(ocr_service=ocr_service), priority=PRIORITY_OCR_ENHANCED - )+ )
https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown-ocr/src/markitdown_ocr/_plugin.py
Generate NumPy-style docstrings
import os import sys from . import logs from .shells import shell from .conf import settings, load_source from .const import DEFAULT_PRIORITY, ALL_ENABLED from .exceptions import EmptyCommand from .utils import get_alias, format_raw_script from .output_readers import get_output class Command(object): def __init__(self, script, output): self.script = script self.output = output @property def stdout(self): logs.warn('`stdout` is deprecated, please use `output` instead') return self.output @property def stderr(self): logs.warn('`stderr` is deprecated, please use `output` instead') return self.output @property def script_parts(self): if not hasattr(self, '_script_parts'): try: self._script_parts = shell.split_command(self.script) except Exception: logs.debug(u"Can't split command script {} because:\n {}".format( self, sys.exc_info())) self._script_parts = [] return self._script_parts def __eq__(self, other): if isinstance(other, Command): return (self.script, self.output) == (other.script, other.output) else: return False def __repr__(self): return u'Command(script={}, output={})'.format( self.script, self.output) def update(self, **kwargs): kwargs.setdefault('script', self.script) kwargs.setdefault('output', self.output) return Command(**kwargs) @classmethod def from_raw_script(cls, raw_script): script = format_raw_script(raw_script) if not script: raise EmptyCommand expanded = shell.from_shell(script) output = get_output(script, expanded) return cls(expanded, output) class Rule(object): def __init__(self, name, match, get_new_command, enabled_by_default, side_effect, priority, requires_output): self.name = name self.match = match self.get_new_command = get_new_command self.enabled_by_default = enabled_by_default self.side_effect = side_effect self.priority = priority self.requires_output = requires_output def __eq__(self, other): if isinstance(other, Rule): return ((self.name, self.match, self.get_new_command, self.enabled_by_default, self.side_effect, self.priority, self.requires_output) == (other.name, other.match, other.get_new_command, other.enabled_by_default, other.side_effect, other.priority, other.requires_output)) else: return False def __repr__(self): return 'Rule(name={}, match={}, get_new_command={}, ' \ 'enabled_by_default={}, side_effect={}, ' \ 'priority={}, requires_output={})'.format( self.name, self.match, self.get_new_command, self.enabled_by_default, self.side_effect, self.priority, self.requires_output) @classmethod def from_path(cls, path): name = path.name[:-3] if name in settings.exclude_rules: logs.debug(u'Ignoring excluded rule: {}'.format(name)) return with logs.debug_time(u'Importing rule: {};'.format(name)): try: rule_module = load_source(name, str(path)) except Exception: logs.exception(u"Rule {} failed to load".format(name), sys.exc_info()) return priority = getattr(rule_module, 'priority', DEFAULT_PRIORITY) return cls(name, rule_module.match, rule_module.get_new_command, getattr(rule_module, 'enabled_by_default', True), getattr(rule_module, 'side_effect', None), settings.priority.get(name, priority), getattr(rule_module, 'requires_output', True)) @property def is_enabled(self): return ( self.name in settings.rules or self.enabled_by_default and ALL_ENABLED in settings.rules ) def is_match(self, command): if command.output is None and self.requires_output: return False try: with logs.debug_time(u'Trying rule: {};'.format(self.name)): if self.match(command): return True except Exception: logs.rule_failed(self, sys.exc_info()) def get_corrected_commands(self, command): new_commands = self.get_new_command(command) if not isinstance(new_commands, list): new_commands = (new_commands,) for n, new_command in enumerate(new_commands): yield CorrectedCommand(script=new_command, side_effect=self.side_effect, priority=(n + 1) * self.priority) class CorrectedCommand(object): def __init__(self, script, side_effect, priority): self.script = script self.side_effect = side_effect self.priority = priority def __eq__(self, other): if isinstance(other, CorrectedCommand): return (other.script, other.side_effect) == \ (self.script, self.side_effect) else: return False def __hash__(self): return (self.script, self.side_effect).__hash__() def __repr__(self): return u'CorrectedCommand(script={}, side_effect={}, priority={})'.format( self.script, self.side_effect, self.priority) def _get_script(self): if settings.repeat: repeat_fuck = '{} --repeat {}--force-command {}'.format( get_alias(), '--debug ' if settings.debug else '', shell.quote(self.script)) return shell.or_(self.script, repeat_fuck) else: return self.script def run(self, old_cmd): if self.side_effect: self.side_effect(old_cmd, self.script) if settings.alter_history: shell.put_to_history(self.script) # This depends on correct setting of PYTHONIOENCODING by the alias: logs.debug(u'PYTHONIOENCODING: {}'.format( os.environ.get('PYTHONIOENCODING', '!!not-set!!'))) sys.stdout.write(self._get_script())
--- +++ @@ -10,8 +10,15 @@ class Command(object): + """Command that should be fixed.""" def __init__(self, script, output): + """Initializes command with given values. + + :type script: basestring + :type output: basestring + + """ self.script = script self.output = output @@ -48,12 +55,24 @@ self.script, self.output) def update(self, **kwargs): + """Returns new command with replaced fields. + + :rtype: Command + + """ kwargs.setdefault('script', self.script) kwargs.setdefault('output', self.output) return Command(**kwargs) @classmethod def from_raw_script(cls, raw_script): + """Creates instance of `Command` from a list of script parts. + + :type raw_script: [basestring] + :rtype: Command + :raises: EmptyCommand + + """ script = format_raw_script(raw_script) if not script: raise EmptyCommand @@ -64,10 +83,22 @@ class Rule(object): + """Rule for fixing commands.""" def __init__(self, name, match, get_new_command, enabled_by_default, side_effect, priority, requires_output): + """Initializes rule with given fields. + + :type name: basestring + :type match: (Command) -> bool + :type get_new_command: (Command) -> (basestring | [basestring]) + :type enabled_by_default: boolean + :type side_effect: (Command, basestring) -> None + :type priority: int + :type requires_output: bool + + """ self.name = name self.match = match self.get_new_command = get_new_command @@ -97,6 +128,12 @@ @classmethod def from_path(cls, path): + """Creates rule instance from path. + + :type path: pathlib.Path + :rtype: Rule + + """ name = path.name[:-3] if name in settings.exclude_rules: logs.debug(u'Ignoring excluded rule: {}'.format(name)) @@ -117,6 +154,11 @@ @property def is_enabled(self): + """Returns `True` when rule enabled. + + :rtype: bool + + """ return ( self.name in settings.rules or self.enabled_by_default @@ -124,6 +166,12 @@ ) def is_match(self, command): + """Returns `True` if rule matches the command. + + :type command: Command + :rtype: bool + + """ if command.output is None and self.requires_output: return False @@ -135,6 +183,12 @@ logs.rule_failed(self, sys.exc_info()) def get_corrected_commands(self, command): + """Returns generator with corrected commands. + + :type command: Command + :rtype: Iterable[CorrectedCommand] + + """ new_commands = self.get_new_command(command) if not isinstance(new_commands, list): new_commands = (new_commands,) @@ -145,13 +199,22 @@ class CorrectedCommand(object): + """Corrected by rule command.""" def __init__(self, script, side_effect, priority): + """Initializes instance with given fields. + + :type script: basestring + :type side_effect: (Command, basestring) -> None + :type priority: int + + """ self.script = script self.side_effect = side_effect self.priority = priority def __eq__(self, other): + """Ignores `priority` field.""" if isinstance(other, CorrectedCommand): return (other.script, other.side_effect) == \ (self.script, self.side_effect) @@ -166,6 +229,12 @@ self.script, self.side_effect, self.priority) def _get_script(self): + """Returns fixed commands script. + + If `settings.repeat` is `True`, appends command with second attempt + of running fuck in case fixed command fails again. + + """ if settings.repeat: repeat_fuck = '{} --repeat {}--force-command {}'.format( get_alias(), @@ -176,6 +245,11 @@ return self.script def run(self, old_cmd): + """Runs command from rule for passed command. + + :type old_cmd: Command + + """ if self.side_effect: self.side_effect(old_cmd, self.script) if settings.alter_history: @@ -184,4 +258,4 @@ logs.debug(u'PYTHONIOENCODING: {}'.format( os.environ.get('PYTHONIOENCODING', '!!not-set!!'))) - sys.stdout.write(self._get_script())+ sys.stdout.write(self._get_script())
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/types.py
Document functions with clear intent
import io import re import sys from typing import Any, BinaryIO, Optional from markitdown.converters import HtmlConverter from markitdown.converter_utils.docx.pre_process import pre_process_docx from markitdown import DocumentConverterResult, StreamInfo from markitdown._exceptions import ( MissingDependencyException, MISSING_DEPENDENCY_MESSAGE, ) from ._ocr_service import LLMVisionOCRService # Try loading dependencies _dependency_exc_info = None try: import mammoth from docx import Document except ImportError: _dependency_exc_info = sys.exc_info() # Placeholder injected into HTML so that mammoth never sees the OCR markers. # Must be a single token with no special markdown characters. _PLACEHOLDER = "MARKITDOWNOCRBLOCK{}" class DocxConverterWithOCR(HtmlConverter): def __init__(self, ocr_service: Optional[LLMVisionOCRService] = None): super().__init__() self._html_converter = HtmlConverter() self.ocr_service = ocr_service def accepts( self, file_stream: BinaryIO, stream_info: StreamInfo, **kwargs: Any, ) -> bool: mimetype = (stream_info.mimetype or "").lower() extension = (stream_info.extension or "").lower() if extension == ".docx": return True if mimetype.startswith( "application/vnd.openxmlformats-officedocument.wordprocessingml" ): return True return False def convert( self, file_stream: BinaryIO, stream_info: StreamInfo, **kwargs: Any, ) -> DocumentConverterResult: if _dependency_exc_info is not None: raise MissingDependencyException( MISSING_DEPENDENCY_MESSAGE.format( converter=type(self).__name__, extension=".docx", feature="docx", ) ) from _dependency_exc_info[1].with_traceback( _dependency_exc_info[2] ) # type: ignore[union-attr] # Get OCR service if available (from kwargs or instance) ocr_service: Optional[LLMVisionOCRService] = ( kwargs.get("ocr_service") or self.ocr_service ) if ocr_service: # 1. Extract and OCR images — returns raw text per image file_stream.seek(0) image_ocr_map = self._extract_and_ocr_images(file_stream, ocr_service) # 2. Convert DOCX → HTML via mammoth file_stream.seek(0) pre_process_stream = pre_process_docx(file_stream) html_result = mammoth.convert_to_html( pre_process_stream, style_map=kwargs.get("style_map") ).value # 3. Replace <img> tags with plain placeholder tokens so that # mammoth's HTML→markdown step never escapes our OCR markers. html_with_placeholders, ocr_texts = self._inject_placeholders( html_result, image_ocr_map ) # 4. Convert HTML → markdown md_result = self._html_converter.convert_string( html_with_placeholders, **kwargs ) md = md_result.markdown # 5. Swap placeholders for the actual OCR blocks (post-conversion # so * and _ are never escaped by the markdown converter). for i, raw_text in enumerate(ocr_texts): placeholder = _PLACEHOLDER.format(i) ocr_block = f"*[Image OCR]\n{raw_text}\n[End OCR]*" md = md.replace(placeholder, ocr_block) return DocumentConverterResult(markdown=md) else: # Standard conversion without OCR style_map = kwargs.get("style_map", None) pre_process_stream = pre_process_docx(file_stream) return self._html_converter.convert_string( mammoth.convert_to_html(pre_process_stream, style_map=style_map).value, **kwargs, ) def _extract_and_ocr_images( self, file_stream: BinaryIO, ocr_service: LLMVisionOCRService ) -> dict[str, str]: ocr_map = {} try: file_stream.seek(0) doc = Document(file_stream) for rel in doc.part.rels.values(): if "image" in rel.target_ref.lower(): try: image_bytes = rel.target_part.blob image_stream = io.BytesIO(image_bytes) ocr_result = ocr_service.extract_text(image_stream) if ocr_result.text.strip(): # Store raw text only — markers added later ocr_map[rel.rId] = ocr_result.text.strip() except Exception: continue except Exception: pass return ocr_map def _inject_placeholders( self, html: str, ocr_map: dict[str, str] ) -> tuple[str, list[str]]: if not ocr_map: return html, [] ocr_texts = list(ocr_map.values()) used: list[int] = [] def replace_img(match: re.Match) -> str: # type: ignore[type-arg] for i in range(len(ocr_texts)): if i not in used: used.append(i) return f"<p>{_PLACEHOLDER.format(i)}</p>" return "" # remove image if all OCR texts already used result = re.sub(r"<img[^>]*>", replace_img, html) # Any OCR texts that had no matching <img> tag go at the end for i in range(len(ocr_texts)): if i not in used: result += f"<p>{_PLACEHOLDER.format(i)}</p>" return result, ocr_texts
--- +++ @@ -1,3 +1,7 @@+""" +Enhanced DOCX Converter with OCR support for embedded images. +Extracts images from Word documents and performs OCR while maintaining context. +""" import io import re @@ -27,6 +31,10 @@ class DocxConverterWithOCR(HtmlConverter): + """ + Enhanced DOCX Converter with OCR support for embedded images. + Maintains document flow while extracting text from images inline. + """ def __init__(self, ocr_service: Optional[LLMVisionOCRService] = None): super().__init__() @@ -118,6 +126,12 @@ def _extract_and_ocr_images( self, file_stream: BinaryIO, ocr_service: LLMVisionOCRService ) -> dict[str, str]: + """ + Extract images from DOCX and OCR them. + + Returns: + Dict mapping image relationship IDs to raw OCR text (no markers). + """ ocr_map = {} try: @@ -146,6 +160,12 @@ def _inject_placeholders( self, html: str, ocr_map: dict[str, str] ) -> tuple[str, list[str]]: + """ + Replace <img> tags with numbered placeholder tokens. + + Returns: + (html_with_placeholders, ordered list of raw OCR texts) + """ if not ocr_map: return html, [] @@ -166,4 +186,4 @@ if i not in used: result += f"<p>{_PLACEHOLDER.format(i)}</p>" - return result, ocr_texts+ return result, ocr_texts
https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown-ocr/src/markitdown_ocr/_docx_converter_with_ocr.py
Add docstrings including usage examples
import atexit import os import pickle import re import shelve import sys import six from decorator import decorator from difflib import get_close_matches as difflib_get_close_matches from functools import wraps from .logs import warn, exception from .conf import settings from .system import Path DEVNULL = open(os.devnull, 'w') if six.PY2: import anydbm shelve_open_error = anydbm.error else: import dbm shelve_open_error = dbm.error def memoize(fn): memo = {} @wraps(fn) def wrapper(*args, **kwargs): if not memoize.disabled: key = pickle.dumps((args, kwargs)) if key not in memo: memo[key] = fn(*args, **kwargs) value = memo[key] else: # Memoize is disabled, call the function value = fn(*args, **kwargs) return value return wrapper memoize.disabled = False @memoize def which(program): try: from shutil import which return which(program) except ImportError: def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None def default_settings(params): def _default_settings(fn, command): for k, w in params.items(): settings.setdefault(k, w) return fn(command) return decorator(_default_settings) def get_closest(word, possibilities, cutoff=0.6, fallback_to_first=True): possibilities = list(possibilities) try: return difflib_get_close_matches(word, possibilities, 1, cutoff)[0] except IndexError: if fallback_to_first: return possibilities[0] def get_close_matches(word, possibilities, n=None, cutoff=0.6): if n is None: n = settings.num_close_matches return difflib_get_close_matches(word, possibilities, n, cutoff) def include_path_in_search(path): return not any(path.startswith(x) for x in settings.excluded_search_path_prefixes) @memoize def get_all_executables(): from thefuck.shells import shell def _safe(fn, fallback): try: return fn() except OSError: return fallback tf_alias = get_alias() tf_entry_points = ['thefuck', 'fuck'] bins = [exe.name.decode('utf8') if six.PY2 else exe.name for path in os.environ.get('PATH', '').split(os.pathsep) if include_path_in_search(path) for exe in _safe(lambda: list(Path(path).iterdir()), []) if not _safe(exe.is_dir, True) and exe.name not in tf_entry_points] aliases = [alias.decode('utf8') if six.PY2 else alias for alias in shell.get_aliases() if alias != tf_alias] return bins + aliases def replace_argument(script, from_, to): replaced_in_the_end = re.sub(u' {}$'.format(re.escape(from_)), u' {}'.format(to), script, count=1) if replaced_in_the_end != script: return replaced_in_the_end else: return script.replace( u' {} '.format(from_), u' {} '.format(to), 1) @decorator def eager(fn, *args, **kwargs): return list(fn(*args, **kwargs)) @eager def get_all_matched_commands(stderr, separator='Did you mean'): if not isinstance(separator, list): separator = [separator] should_yield = False for line in stderr.split('\n'): for sep in separator: if sep in line: should_yield = True break else: if should_yield and line: yield line.strip() def replace_command(command, broken, matched): new_cmds = get_close_matches(broken, matched, cutoff=0.1) return [replace_argument(command.script, broken, new_cmd.strip()) for new_cmd in new_cmds] @memoize def is_app(command, *app_names, **kwargs): at_least = kwargs.pop('at_least', 0) if kwargs: raise TypeError("got an unexpected keyword argument '{}'".format(kwargs.keys())) if len(command.script_parts) > at_least: return os.path.basename(command.script_parts[0]) in app_names return False def for_app(*app_names, **kwargs): def _for_app(fn, command): if is_app(command, *app_names, **kwargs): return fn(command) else: return False return decorator(_for_app) class Cache(object): def __init__(self): self._db = None def _init_db(self): try: self._setup_db() except Exception: exception("Unable to init cache", sys.exc_info()) self._db = {} def _setup_db(self): cache_dir = self._get_cache_dir() cache_path = Path(cache_dir).joinpath('thefuck').as_posix() try: self._db = shelve.open(cache_path) except shelve_open_error + (ImportError,): # Caused when switching between Python versions warn("Removing possibly out-dated cache") os.remove(cache_path) self._db = shelve.open(cache_path) atexit.register(self._db.close) def _get_cache_dir(self): default_xdg_cache_dir = os.path.expanduser("~/.cache") cache_dir = os.getenv("XDG_CACHE_HOME", default_xdg_cache_dir) # Ensure the cache_path exists, Python 2 does not have the exist_ok # parameter try: os.makedirs(cache_dir) except OSError: if not os.path.isdir(cache_dir): raise return cache_dir def _get_mtime(self, path): try: return str(os.path.getmtime(path)) except OSError: return '0' def _get_key(self, fn, depends_on, args, kwargs): parts = (fn.__module__, repr(fn).split('at')[0], depends_on, args, kwargs) return str(pickle.dumps(parts)) def get_value(self, fn, depends_on, args, kwargs): if self._db is None: self._init_db() depends_on = [Path(name).expanduser().absolute().as_posix() for name in depends_on] key = self._get_key(fn, depends_on, args, kwargs) etag = '.'.join(self._get_mtime(path) for path in depends_on) if self._db.get(key, {}).get('etag') == etag: return self._db[key]['value'] else: value = fn(*args, **kwargs) self._db[key] = {'etag': etag, 'value': value} return value _cache = Cache() def cache(*depends_on): def cache_decorator(fn): @memoize @wraps(fn) def wrapper(*args, **kwargs): if cache.disabled: return fn(*args, **kwargs) else: return _cache.get_value(fn, depends_on, args, kwargs) return wrapper return cache_decorator cache.disabled = False def get_installation_version(): try: from importlib.metadata import version return version('thefuck') except ImportError: import pkg_resources return pkg_resources.require('thefuck')[0].version def get_alias(): return os.environ.get('TF_ALIAS', 'fuck') @memoize def get_valid_history_without_current(command): def _not_corrected(history, tf_alias): previous = None for line in history: if previous is not None and line != tf_alias: yield previous previous = line if history: yield history[-1] from thefuck.shells import shell history = shell.get_history() tf_alias = get_alias() executables = set(get_all_executables())\ .union(shell.get_builtin_commands()) return [line for line in _not_corrected(history, tf_alias) if not line.startswith(tf_alias) and not line == command.script and line.split(' ')[0] in executables] def format_raw_script(raw_script): if six.PY2: script = ' '.join(arg.decode('utf-8') for arg in raw_script) else: script = ' '.join(raw_script) return script.lstrip()
--- +++ @@ -23,6 +23,7 @@ def memoize(fn): + """Caches previous calls to the function.""" memo = {} @wraps(fn) @@ -46,6 +47,7 @@ @memoize def which(program): + """Returns `program` path or `None`.""" try: from shutil import which @@ -69,6 +71,15 @@ def default_settings(params): + """Adds default values to settings if it not presented. + + Usage: + + @default_settings({'apt': '/usr/bin/apt'}) + def match(command): + print(settings.apt) + + """ def _default_settings(fn, command): for k, w in params.items(): settings.setdefault(k, w) @@ -77,6 +88,7 @@ def get_closest(word, possibilities, cutoff=0.6, fallback_to_first=True): + """Returns closest match or just first from possibilities.""" possibilities = list(possibilities) try: return difflib_get_close_matches(word, possibilities, 1, cutoff)[0] @@ -86,6 +98,7 @@ def get_close_matches(word, possibilities, n=None, cutoff=0.6): + """Overrides `difflib.get_close_match` to control argument `n`.""" if n is None: n = settings.num_close_matches return difflib_get_close_matches(word, possibilities, n, cutoff) @@ -121,6 +134,7 @@ def replace_argument(script, from_, to): + """Replaces command line argument.""" replaced_in_the_end = re.sub(u' {}$'.format(re.escape(from_)), u' {}'.format(to), script, count=1) if replaced_in_the_end != script: @@ -151,6 +165,7 @@ def replace_command(command, broken, matched): + """Helper for *_no_command rules.""" new_cmds = get_close_matches(broken, matched, cutoff=0.1) return [replace_argument(command.script, broken, new_cmd.strip()) for new_cmd in new_cmds] @@ -158,6 +173,7 @@ @memoize def is_app(command, *app_names, **kwargs): + """Returns `True` if command is call to one of passed app names.""" at_least = kwargs.pop('at_least', 0) if kwargs: @@ -170,6 +186,7 @@ def for_app(*app_names, **kwargs): + """Specifies that matching script is for one of app names.""" def _for_app(fn, command): if is_app(command, *app_names, **kwargs): return fn(command) @@ -180,6 +197,7 @@ class Cache(object): + """Lazy read cache and save changes at exit.""" def __init__(self): self._db = None @@ -251,6 +269,14 @@ def cache(*depends_on): + """Caches function result in temporary file. + + Cache will be expired when modification date of files from `depends_on` + will be changed. + + Only functions should be wrapped in `cache`, not methods. + + """ def cache_decorator(fn): @memoize @wraps(fn) @@ -286,6 +312,7 @@ @memoize def get_valid_history_without_current(command): def _not_corrected(history, tf_alias): + """Returns all lines from history except that comes before `fuck`.""" previous = None for line in history: if previous is not None and line != tf_alias: @@ -306,9 +333,15 @@ def format_raw_script(raw_script): + """Creates single script from a list of script parts. + + :type raw_script: [basestring] + :rtype: basestring + + """ if six.PY2: script = ' '.join(arg.decode('utf-8') for arg in raw_script) else: script = ' '.join(raw_script) - return script.lstrip()+ return script.lstrip()
https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/utils.py
Add structured docstrings to improve clarity
import locale from typing import BinaryIO, Any from striprtf.striprtf import rtf_to_text from markitdown import ( MarkItDown, DocumentConverter, DocumentConverterResult, StreamInfo, ) __plugin_interface_version__ = ( 1 # The version of the plugin interface that this plugin uses ) ACCEPTED_MIME_TYPE_PREFIXES = [ "text/rtf", "application/rtf", ] ACCEPTED_FILE_EXTENSIONS = [".rtf"] def register_converters(markitdown: MarkItDown, **kwargs): # Simply create and attach an RtfConverter instance markitdown.register_converter(RtfConverter()) class RtfConverter(DocumentConverter): def accepts( self, file_stream: BinaryIO, stream_info: StreamInfo, **kwargs: Any, ) -> bool: mimetype = (stream_info.mimetype or "").lower() extension = (stream_info.extension or "").lower() if extension in ACCEPTED_FILE_EXTENSIONS: return True for prefix in ACCEPTED_MIME_TYPE_PREFIXES: if mimetype.startswith(prefix): return True return False def convert( self, file_stream: BinaryIO, stream_info: StreamInfo, **kwargs: Any, ) -> DocumentConverterResult: # Read the file stream into an str using hte provided charset encoding, or using the system default encoding = stream_info.charset or locale.getpreferredencoding() stream_data = file_stream.read().decode(encoding) # Return the result return DocumentConverterResult( title=None, markdown=rtf_to_text(stream_data), )
--- +++ @@ -23,12 +23,18 @@ def register_converters(markitdown: MarkItDown, **kwargs): + """ + Called during construction of MarkItDown instances to register converters provided by plugins. + """ # Simply create and attach an RtfConverter instance markitdown.register_converter(RtfConverter()) class RtfConverter(DocumentConverter): + """ + Converts an RTF file to in the simplest possible way. + """ def accepts( self, @@ -62,4 +68,4 @@ return DocumentConverterResult( title=None, markdown=rtf_to_text(stream_data), - )+ )
https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown-sample-plugin/src/markitdown_sample_plugin/_plugin.py
Write docstrings including parameters and return values
import sys import io import re from typing import BinaryIO, Any from .._base_converter import DocumentConverter, DocumentConverterResult from .._stream_info import StreamInfo from .._exceptions import MissingDependencyException, MISSING_DEPENDENCY_MESSAGE # Pattern for MasterFormat-style partial numbering (e.g., ".1", ".2", ".10") PARTIAL_NUMBERING_PATTERN = re.compile(r"^\.\d+$") def _merge_partial_numbering_lines(text: str) -> str: lines = text.split("\n") result_lines: list[str] = [] i = 0 while i < len(lines): line = lines[i] stripped = line.strip() # Check if this line is ONLY a partial numbering if PARTIAL_NUMBERING_PATTERN.match(stripped): # Look for the next non-empty line to merge with j = i + 1 while j < len(lines) and not lines[j].strip(): j += 1 if j < len(lines): # Merge the partial numbering with the next line next_line = lines[j].strip() result_lines.append(f"{stripped} {next_line}") i = j + 1 # Skip past the merged line else: # No next line to merge with, keep as is result_lines.append(line) i += 1 else: result_lines.append(line) i += 1 return "\n".join(result_lines) # Load dependencies _dependency_exc_info = None try: import pdfminer import pdfminer.high_level import pdfplumber except ImportError: _dependency_exc_info = sys.exc_info() ACCEPTED_MIME_TYPE_PREFIXES = [ "application/pdf", "application/x-pdf", ] ACCEPTED_FILE_EXTENSIONS = [".pdf"] def _to_markdown_table(table: list[list[str]], include_separator: bool = True) -> str: if not table: return "" # Normalize None → "" table = [[cell if cell is not None else "" for cell in row] for row in table] # Filter out empty rows table = [row for row in table if any(cell.strip() for cell in row)] if not table: return "" # Column widths col_widths = [max(len(str(cell)) for cell in col) for col in zip(*table)] def fmt_row(row: list[str]) -> str: return ( "|" + "|".join(str(cell).ljust(width) for cell, width in zip(row, col_widths)) + "|" ) if include_separator: header, *rows = table md = [fmt_row(header)] md.append("|" + "|".join("-" * w for w in col_widths) + "|") for row in rows: md.append(fmt_row(row)) else: md = [fmt_row(row) for row in table] return "\n".join(md) def _extract_form_content_from_words(page: Any) -> str | None: words = page.extract_words(keep_blank_chars=True, x_tolerance=3, y_tolerance=3) if not words: return None # Group words by their Y position (rows) y_tolerance = 5 rows_by_y: dict[float, list[dict]] = {} for word in words: y_key = round(word["top"] / y_tolerance) * y_tolerance if y_key not in rows_by_y: rows_by_y[y_key] = [] rows_by_y[y_key].append(word) # Sort rows by Y position sorted_y_keys = sorted(rows_by_y.keys()) page_width = page.width if hasattr(page, "width") else 612 # First pass: analyze each row row_info: list[dict] = [] for y_key in sorted_y_keys: row_words = sorted(rows_by_y[y_key], key=lambda w: w["x0"]) if not row_words: continue first_x0 = row_words[0]["x0"] last_x1 = row_words[-1]["x1"] line_width = last_x1 - first_x0 combined_text = " ".join(w["text"] for w in row_words) # Count distinct x-position groups (columns) x_positions = [w["x0"] for w in row_words] x_groups: list[float] = [] for x in sorted(x_positions): if not x_groups or x - x_groups[-1] > 50: x_groups.append(x) # Determine row type is_paragraph = line_width > page_width * 0.55 and len(combined_text) > 60 # Check for MasterFormat-style partial numbering (e.g., ".1", ".2") # These should be treated as list items, not table rows has_partial_numbering = False if row_words: first_word = row_words[0]["text"].strip() if PARTIAL_NUMBERING_PATTERN.match(first_word): has_partial_numbering = True row_info.append( { "y_key": y_key, "words": row_words, "text": combined_text, "x_groups": x_groups, "is_paragraph": is_paragraph, "num_columns": len(x_groups), "has_partial_numbering": has_partial_numbering, } ) # Collect ALL x-positions from rows with 3+ columns (table-like rows) # This gives us the global column structure all_table_x_positions: list[float] = [] for info in row_info: if info["num_columns"] >= 3 and not info["is_paragraph"]: all_table_x_positions.extend(info["x_groups"]) if not all_table_x_positions: return None # Compute adaptive column clustering tolerance based on gap analysis all_table_x_positions.sort() # Calculate gaps between consecutive x-positions gaps = [] for i in range(len(all_table_x_positions) - 1): gap = all_table_x_positions[i + 1] - all_table_x_positions[i] if gap > 5: # Only significant gaps gaps.append(gap) # Determine optimal tolerance using statistical analysis if gaps and len(gaps) >= 3: # Use 70th percentile of gaps as threshold (balances precision/recall) sorted_gaps = sorted(gaps) percentile_70_idx = int(len(sorted_gaps) * 0.70) adaptive_tolerance = sorted_gaps[percentile_70_idx] # Clamp tolerance to reasonable range [25, 50] adaptive_tolerance = max(25, min(50, adaptive_tolerance)) else: # Fallback to conservative value adaptive_tolerance = 35 # Compute global column boundaries using adaptive tolerance global_columns: list[float] = [] for x in all_table_x_positions: if not global_columns or x - global_columns[-1] > adaptive_tolerance: global_columns.append(x) # Adaptive max column check based on page characteristics # Calculate average column width if len(global_columns) > 1: content_width = global_columns[-1] - global_columns[0] avg_col_width = content_width / len(global_columns) # Forms with very narrow columns (< 30px) are likely dense text if avg_col_width < 30: return None # Compute adaptive max based on columns per inch # Typical forms have 3-8 columns per inch columns_per_inch = len(global_columns) / (content_width / 72) # If density is too high (> 10 cols/inch), likely not a form if columns_per_inch > 10: return None # Adaptive max: allow more columns for wider pages # Standard letter is 612pt wide, so scale accordingly adaptive_max_columns = int(20 * (page_width / 612)) adaptive_max_columns = max(15, adaptive_max_columns) # At least 15 if len(global_columns) > adaptive_max_columns: return None else: # Single column, not a form return None # Now classify each row as table row or not # A row is a table row if it has words that align with 2+ of the global columns for info in row_info: if info["is_paragraph"]: info["is_table_row"] = False continue # Rows with partial numbering (e.g., ".1", ".2") are list items, not table rows if info["has_partial_numbering"]: info["is_table_row"] = False continue # Count how many global columns this row's words align with aligned_columns: set[int] = set() for word in info["words"]: word_x = word["x0"] for col_idx, col_x in enumerate(global_columns): if abs(word_x - col_x) < 40: aligned_columns.add(col_idx) break # If row uses 2+ of the established columns, it's a table row info["is_table_row"] = len(aligned_columns) >= 2 # Find table regions (consecutive table rows) table_regions: list[tuple[int, int]] = [] # (start_idx, end_idx) i = 0 while i < len(row_info): if row_info[i]["is_table_row"]: start_idx = i while i < len(row_info) and row_info[i]["is_table_row"]: i += 1 end_idx = i table_regions.append((start_idx, end_idx)) else: i += 1 # Check if enough rows are table rows (at least 20%) total_table_rows = sum(end - start for start, end in table_regions) if len(row_info) > 0 and total_table_rows / len(row_info) < 0.2: return None # Build output - collect table data first, then format with proper column widths result_lines: list[str] = [] num_cols = len(global_columns) # Helper function to extract cells from a row def extract_cells(info: dict) -> list[str]: cells: list[str] = ["" for _ in range(num_cols)] for word in info["words"]: word_x = word["x0"] # Find the correct column using boundary ranges assigned_col = num_cols - 1 # Default to last column for col_idx in range(num_cols - 1): col_end = global_columns[col_idx + 1] if word_x < col_end - 20: assigned_col = col_idx break if cells[assigned_col]: cells[assigned_col] += " " + word["text"] else: cells[assigned_col] = word["text"] return cells # Process rows, collecting table data for proper formatting idx = 0 while idx < len(row_info): info = row_info[idx] # Check if this row starts a table region table_region = None for start, end in table_regions: if idx == start: table_region = (start, end) break if table_region: start, end = table_region # Collect all rows in this table table_data: list[list[str]] = [] for table_idx in range(start, end): cells = extract_cells(row_info[table_idx]) table_data.append(cells) # Calculate column widths for this table if table_data: col_widths = [ max(len(row[col]) for row in table_data) for col in range(num_cols) ] # Ensure minimum width of 3 for separator dashes col_widths = [max(w, 3) for w in col_widths] # Format header row header = table_data[0] header_str = ( "| " + " | ".join( cell.ljust(col_widths[i]) for i, cell in enumerate(header) ) + " |" ) result_lines.append(header_str) # Format separator row separator = ( "| " + " | ".join("-" * col_widths[i] for i in range(num_cols)) + " |" ) result_lines.append(separator) # Format data rows for row in table_data[1:]: row_str = ( "| " + " | ".join( cell.ljust(col_widths[i]) for i, cell in enumerate(row) ) + " |" ) result_lines.append(row_str) idx = end # Skip to end of table region else: # Check if we're inside a table region (not at start) in_table = False for start, end in table_regions: if start < idx < end: in_table = True break if not in_table: # Non-table content result_lines.append(info["text"]) idx += 1 return "\n".join(result_lines) def _extract_tables_from_words(page: Any) -> list[list[list[str]]]: words = page.extract_words(keep_blank_chars=True, x_tolerance=3, y_tolerance=3) if not words: return [] # Group words by their Y position (rows) y_tolerance = 5 rows_by_y: dict[float, list[dict]] = {} for word in words: y_key = round(word["top"] / y_tolerance) * y_tolerance if y_key not in rows_by_y: rows_by_y[y_key] = [] rows_by_y[y_key].append(word) # Sort rows by Y position sorted_y_keys = sorted(rows_by_y.keys()) # Find potential column boundaries by analyzing x positions across all rows all_x_positions = [] for words_in_row in rows_by_y.values(): for word in words_in_row: all_x_positions.append(word["x0"]) if not all_x_positions: return [] # Cluster x positions to find column starts all_x_positions.sort() x_tolerance_col = 20 column_starts: list[float] = [] for x in all_x_positions: if not column_starts or x - column_starts[-1] > x_tolerance_col: column_starts.append(x) # Need at least 3 columns but not too many (likely text layout, not table) if len(column_starts) < 3 or len(column_starts) > 10: return [] # Find rows that span multiple columns (potential table rows) table_rows = [] for y_key in sorted_y_keys: words_in_row = sorted(rows_by_y[y_key], key=lambda w: w["x0"]) # Assign words to columns row_data = [""] * len(column_starts) for word in words_in_row: # Find the closest column best_col = 0 min_dist = float("inf") for i, col_x in enumerate(column_starts): dist = abs(word["x0"] - col_x) if dist < min_dist: min_dist = dist best_col = i if row_data[best_col]: row_data[best_col] += " " + word["text"] else: row_data[best_col] = word["text"] # Only include rows that have content in multiple columns non_empty = sum(1 for cell in row_data if cell.strip()) if non_empty >= 2: table_rows.append(row_data) # Validate table quality - tables should have: # 1. Enough rows (at least 3 including header) # 2. Short cell content (tables have concise data, not paragraphs) # 3. Consistent structure across rows if len(table_rows) < 3: return [] # Check if cells contain short, structured data (not long text) long_cell_count = 0 total_cell_count = 0 for row in table_rows: for cell in row: if cell.strip(): total_cell_count += 1 # If cell has more than 30 chars, it's likely prose text if len(cell.strip()) > 30: long_cell_count += 1 # If more than 30% of cells are long, this is probably not a table if total_cell_count > 0 and long_cell_count / total_cell_count > 0.3: return [] return [table_rows] class PdfConverter(DocumentConverter): def accepts( self, file_stream: BinaryIO, stream_info: StreamInfo, **kwargs: Any, ) -> bool: mimetype = (stream_info.mimetype or "").lower() extension = (stream_info.extension or "").lower() if extension in ACCEPTED_FILE_EXTENSIONS: return True for prefix in ACCEPTED_MIME_TYPE_PREFIXES: if mimetype.startswith(prefix): return True return False def convert( self, file_stream: BinaryIO, stream_info: StreamInfo, **kwargs: Any, ) -> DocumentConverterResult: if _dependency_exc_info is not None: raise MissingDependencyException( MISSING_DEPENDENCY_MESSAGE.format( converter=type(self).__name__, extension=".pdf", feature="pdf", ) ) from _dependency_exc_info[1].with_traceback( _dependency_exc_info[2] ) # type: ignore[union-attr] assert isinstance(file_stream, io.IOBase) # Read file stream into BytesIO for compatibility with pdfplumber pdf_bytes = io.BytesIO(file_stream.read()) try: # Single pass: check every page for form-style content. # Pages with tables/forms get rich extraction; plain-text # pages are collected separately. page.close() is called # after each page to free pdfplumber's cached objects and # keep memory usage constant regardless of page count. markdown_chunks: list[str] = [] form_page_count = 0 plain_page_indices: list[int] = [] with pdfplumber.open(pdf_bytes) as pdf: for page_idx, page in enumerate(pdf.pages): page_content = _extract_form_content_from_words(page) if page_content is not None: form_page_count += 1 if page_content.strip(): markdown_chunks.append(page_content) else: plain_page_indices.append(page_idx) text = page.extract_text() if text and text.strip(): markdown_chunks.append(text.strip()) page.close() # Free cached page data immediately # If no pages had form-style content, use pdfminer for # the whole document (better text spacing for prose). if form_page_count == 0: pdf_bytes.seek(0) markdown = pdfminer.high_level.extract_text(pdf_bytes) else: markdown = "\n\n".join(markdown_chunks).strip() except Exception: # Fallback if pdfplumber fails pdf_bytes.seek(0) markdown = pdfminer.high_level.extract_text(pdf_bytes) # Fallback if still empty if not markdown: pdf_bytes.seek(0) markdown = pdfminer.high_level.extract_text(pdf_bytes) # Post-process to merge MasterFormat-style partial numbering with following text markdown = _merge_partial_numbering_lines(markdown) return DocumentConverterResult(markdown=markdown)
--- +++ @@ -12,6 +12,20 @@ def _merge_partial_numbering_lines(text: str) -> str: + """ + Post-process extracted text to merge MasterFormat-style partial numbering + with the following text line. + + MasterFormat documents use partial numbering like: + .1 The intent of this Request for Proposal... + .2 Available information relative to... + + Some PDF extractors split these into separate lines: + .1 + The intent of this Request for Proposal... + + This function merges them back together. + """ lines = text.split("\n") result_lines: list[str] = [] i = 0 @@ -62,6 +76,13 @@ def _to_markdown_table(table: list[list[str]], include_separator: bool = True) -> str: + """Convert a 2D list (rows/columns) into a nicely aligned Markdown table. + + Args: + table: 2D list of cell values + include_separator: If True, include header separator row (standard markdown). + If False, output simple pipe-separated rows. + """ if not table: return "" @@ -97,6 +118,17 @@ def _extract_form_content_from_words(page: Any) -> str | None: + """ + Extract form-style content from a PDF page by analyzing word positions. + This handles borderless forms/tables where words are aligned in columns. + + Returns markdown with proper table formatting: + - Tables have pipe-separated columns with header separator rows + - Non-table content is rendered as plain text + + Returns None if the page doesn't appear to be a form-style document, + indicating that pdfminer should be used instead for better text spacing. + """ words = page.extract_words(keep_blank_chars=True, x_tolerance=3, y_tolerance=3) if not words: return None @@ -364,6 +396,13 @@ def _extract_tables_from_words(page: Any) -> list[list[list[str]]]: + """ + Extract tables from a PDF page by analyzing word positions. + This handles borderless tables where words are aligned in columns. + + This function is designed for structured tabular data (like invoices), + not for multi-column text layouts in scientific documents. + """ words = page.extract_words(keep_blank_chars=True, x_tolerance=3, y_tolerance=3) if not words: return [] @@ -454,6 +493,11 @@ class PdfConverter(DocumentConverter): + """ + Converts PDFs to Markdown. + Supports extracting tables into aligned Markdown format (via pdfplumber). + Falls back to pdfminer if pdfplumber is missing or fails. + """ def accepts( self, @@ -542,4 +586,4 @@ # Post-process to merge MasterFormat-style partial numbering with following text markdown = _merge_partial_numbering_lines(markdown) - return DocumentConverterResult(markdown=markdown)+ return DocumentConverterResult(markdown=markdown)
https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/converters/_pdf_converter.py
Add well-formatted docstrings
import io import sys from typing import Any, BinaryIO, Optional from markitdown import DocumentConverter, DocumentConverterResult, StreamInfo from markitdown._exceptions import ( MissingDependencyException, MISSING_DEPENDENCY_MESSAGE, ) from ._ocr_service import LLMVisionOCRService # Import dependencies _dependency_exc_info = None try: import pdfminer import pdfminer.high_level import pdfplumber from PIL import Image except ImportError: _dependency_exc_info = sys.exc_info() def _extract_images_from_page(page: Any) -> list[dict]: images_info = [] try: # Try multiple methods to detect images images = [] # Method 1: Use page.images (standard approach) if hasattr(page, "images") and page.images: images = page.images # Method 2: If no images found, try underlying PDF objects if not images and hasattr(page, "objects") and "image" in page.objects: images = page.objects.get("image", []) # Method 3: Try filtering all objects for image types if not images and hasattr(page, "objects"): all_objs = page.objects for obj_type in all_objs.keys(): if "image" in obj_type.lower() or "xobject" in obj_type.lower(): potential_imgs = all_objs.get(obj_type, []) if potential_imgs: images = potential_imgs break for i, img_dict in enumerate(images): try: # Try to get the actual image stream from the PDF img_stream = None y_pos = 0 # Method A: If img_dict has 'stream' key, use it directly if "stream" in img_dict and hasattr(img_dict["stream"], "get_data"): try: img_bytes = img_dict["stream"].get_data() # Try to open as PIL Image to validate/decode pil_img = Image.open(io.BytesIO(img_bytes)) # Convert to RGB if needed (handle CMYK, etc.) if pil_img.mode not in ("RGB", "L"): pil_img = pil_img.convert("RGB") # Save to stream as PNG img_stream = io.BytesIO() pil_img.save(img_stream, format="PNG") img_stream.seek(0) y_pos = img_dict.get("top", 0) except Exception: pass # Method B: Fallback to rendering page region if img_stream is None: x0 = img_dict.get("x0", 0) y0 = img_dict.get("top", 0) x1 = img_dict.get("x1", 0) y1 = img_dict.get("bottom", 0) y_pos = y0 # Check if dimensions are valid if x1 <= x0 or y1 <= y0: continue # Use pdfplumber's within_bbox to crop, then render # This preserves coordinate system correctly bbox = (x0, y0, x1, y1) cropped_page = page.within_bbox(bbox) # Render at 150 DPI (balance between quality and size) page_img = cropped_page.to_image(resolution=150) # Save to stream img_stream = io.BytesIO() page_img.original.save(img_stream, format="PNG") img_stream.seek(0) if img_stream: images_info.append( { "stream": img_stream, "name": f"page_{page.page_number}_img_{i}", "y_pos": y_pos, } ) except Exception: continue except Exception: pass return images_info class PdfConverterWithOCR(DocumentConverter): def __init__(self, ocr_service: Optional[LLMVisionOCRService] = None): super().__init__() self.ocr_service = ocr_service def accepts( self, file_stream: BinaryIO, stream_info: StreamInfo, **kwargs: Any, ) -> bool: mimetype = (stream_info.mimetype or "").lower() extension = (stream_info.extension or "").lower() if extension == ".pdf": return True if mimetype.startswith("application/pdf") or mimetype.startswith( "application/x-pdf" ): return True return False def convert( self, file_stream: BinaryIO, stream_info: StreamInfo, **kwargs: Any, ) -> DocumentConverterResult: if _dependency_exc_info is not None: raise MissingDependencyException( MISSING_DEPENDENCY_MESSAGE.format( converter=type(self).__name__, extension=".pdf", feature="pdf", ) ) from _dependency_exc_info[1].with_traceback( _dependency_exc_info[2] ) # type: ignore[union-attr] # Get OCR service if available (from kwargs or instance) ocr_service: LLMVisionOCRService | None = ( kwargs.get("ocr_service") or self.ocr_service ) # Read PDF into BytesIO file_stream.seek(0) pdf_bytes = io.BytesIO(file_stream.read()) markdown_content = [] try: with pdfplumber.open(pdf_bytes) as pdf: for page_num, page in enumerate(pdf.pages, 1): markdown_content.append(f"\n## Page {page_num}\n") # If OCR is enabled, interleave text and images by position if ocr_service: images_on_page = self._extract_page_images(pdf_bytes, page_num) if images_on_page: # Extract text lines with Y positions chars = page.chars if chars: # Group chars into lines based on Y position lines_with_y = [] current_line = [] current_y = None for char in sorted( chars, key=lambda c: (c["top"], c["x0"]) ): y = char["top"] if current_y is None: current_y = y elif abs(y - current_y) > 2: # New line threshold if current_line: text = "".join( [c["text"] for c in current_line] ) lines_with_y.append( {"y": current_y, "text": text.strip()} ) current_line = [] current_y = y current_line.append(char) # Add last line if current_line: text = "".join([c["text"] for c in current_line]) lines_with_y.append( {"y": current_y, "text": text.strip()} ) else: # Fallback: use simple text extraction text_content = page.extract_text() or "" lines_with_y = [ {"y": i * 10, "text": line} for i, line in enumerate(text_content.split("\n")) ] # OCR all images image_data = [] for img_info in images_on_page: ocr_result = ocr_service.extract_text( img_info["stream"] ) if ocr_result.text.strip(): image_data.append( { "y_pos": img_info["y_pos"], "name": img_info["name"], "ocr_text": ocr_result.text, "backend": ocr_result.backend_used, "type": "image", } ) # Add text items content_items = [ { "y_pos": item["y"], "text": item["text"], "type": "text", } for item in lines_with_y if item["text"] ] content_items.extend(image_data) # Sort all items by Y position (top to bottom) content_items.sort(key=lambda x: x["y_pos"]) # Build markdown by interleaving text and images for item in content_items: if item["type"] == "text": markdown_content.append(item["text"]) else: # image ocr_text = item["ocr_text"] img_marker = ( f"\n\n*[Image OCR]\n{ocr_text}\n[End OCR]*\n" ) markdown_content.append(img_marker) else: # No images detected - just extract regular text text_content = page.extract_text() or "" if text_content.strip(): markdown_content.append(text_content.strip()) else: # No OCR, just extract text text_content = page.extract_text() or "" if text_content.strip(): markdown_content.append(text_content.strip()) # Build final markdown markdown = "\n\n".join(markdown_content).strip() # Fallback to pdfminer if empty if not markdown: pdf_bytes.seek(0) markdown = pdfminer.high_level.extract_text(pdf_bytes) except Exception: # Fallback to pdfminer try: pdf_bytes.seek(0) markdown = pdfminer.high_level.extract_text(pdf_bytes) except Exception: markdown = "" # Final fallback: If still empty/whitespace and OCR is available, # treat as scanned PDF and OCR full pages if ocr_service and (not markdown or not markdown.strip()): pdf_bytes.seek(0) markdown = self._ocr_full_pages(pdf_bytes, ocr_service) return DocumentConverterResult(markdown=markdown) def _extract_page_images(self, pdf_bytes: io.BytesIO, page_num: int) -> list[dict]: images = [] try: pdf_bytes.seek(0) with pdfplumber.open(pdf_bytes) as pdf: if page_num <= len(pdf.pages): page = pdf.pages[page_num - 1] # 0-indexed images = _extract_images_from_page(page) except Exception: pass # Sort by vertical position (top to bottom) images.sort(key=lambda x: x["y_pos"]) return images def _ocr_full_pages( self, pdf_bytes: io.BytesIO, ocr_service: LLMVisionOCRService ) -> str: markdown_parts = [] try: pdf_bytes.seek(0) with pdfplumber.open(pdf_bytes) as pdf: for page_num, page in enumerate(pdf.pages, 1): try: markdown_parts.append(f"\n## Page {page_num}\n") # Render page to image page_img = page.to_image(resolution=300) img_stream = io.BytesIO() page_img.original.save(img_stream, format="PNG") img_stream.seek(0) # Run OCR ocr_result = ocr_service.extract_text(img_stream) if ocr_result.text.strip(): text = ocr_result.text.strip() markdown_parts.append(f"*[Image OCR]\n{text}\n[End OCR]*") else: markdown_parts.append( "*[No text could be extracted from this page]*" ) except Exception as e: markdown_parts.append( f"*[Error processing page {page_num}: {str(e)}]*" ) continue except Exception: # pdfplumber failed (e.g. malformed EOF) — try PyMuPDF for rendering markdown_parts = [] try: import fitz # PyMuPDF pdf_bytes.seek(0) doc = fitz.open(stream=pdf_bytes.read(), filetype="pdf") for page_num in range(1, doc.page_count + 1): try: markdown_parts.append(f"\n## Page {page_num}\n") page = doc[page_num - 1] mat = fitz.Matrix(300 / 72, 300 / 72) # 300 DPI pix = page.get_pixmap(matrix=mat) img_stream = io.BytesIO(pix.tobytes("png")) img_stream.seek(0) ocr_result = ocr_service.extract_text(img_stream) if ocr_result.text.strip(): text = ocr_result.text.strip() markdown_parts.append(f"*[Image OCR]\n{text}\n[End OCR]*") else: markdown_parts.append( "*[No text could be extracted from this page]*" ) except Exception as e: markdown_parts.append( f"*[Error processing page {page_num}: {str(e)}]*" ) continue doc.close() except Exception: return "*[Error: Could not process scanned PDF]*" return "\n\n".join(markdown_parts).strip()
--- +++ @@ -1,3 +1,7 @@+""" +Enhanced PDF Converter with OCR support for embedded images. +Extracts images from PDFs and performs OCR while maintaining document context. +""" import io import sys @@ -22,6 +26,12 @@ def _extract_images_from_page(page: Any) -> list[dict]: + """ + Extract images from a PDF page by rendering page regions. + + Returns: + List of dicts with 'stream', 'bbox', 'name', 'y_pos' keys + """ images_info = [] try: @@ -117,6 +127,10 @@ class PdfConverterWithOCR(DocumentConverter): + """ + Enhanced PDF Converter with OCR support for embedded images. + Maintains document structure while extracting text from images inline. + """ def __init__(self, ocr_service: Optional[LLMVisionOCRService] = None): super().__init__() @@ -297,6 +311,16 @@ return DocumentConverterResult(markdown=markdown) def _extract_page_images(self, pdf_bytes: io.BytesIO, page_num: int) -> list[dict]: + """ + Extract images from a PDF page using pdfplumber. + + Args: + pdf_bytes: PDF file as BytesIO + page_num: Page number (1-indexed) + + Returns: + List of image info dicts with 'stream', 'bbox', 'name', 'y_pos' + """ images = [] try: @@ -316,6 +340,17 @@ def _ocr_full_pages( self, pdf_bytes: io.BytesIO, ocr_service: LLMVisionOCRService ) -> str: + """ + Fallback for scanned PDFs: Convert entire pages to images and OCR them. + Used when text extraction returns empty/whitespace results. + + Args: + pdf_bytes: PDF file as BytesIO + ocr_service: OCR service to use + + Returns: + Markdown text extracted from OCR of full pages + """ markdown_parts = [] try: @@ -384,4 +419,4 @@ except Exception: return "*[Error: Could not process scanned PDF]*" - return "\n\n".join(markdown_parts).strip()+ return "\n\n".join(markdown_parts).strip()
https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown-ocr/src/markitdown_ocr/_pdf_converter_with_ocr.py
Add docstrings that explain inputs and outputs
import io import sys from typing import Any, BinaryIO, Optional from typing import BinaryIO, Any, Optional from markitdown.converters import HtmlConverter from markitdown import DocumentConverter, DocumentConverterResult, StreamInfo from markitdown._exceptions import ( MissingDependencyException, MISSING_DEPENDENCY_MESSAGE, ) from ._ocr_service import LLMVisionOCRService _dependency_exc_info = None try: import pptx except ImportError: _dependency_exc_info = sys.exc_info() class PptxConverterWithOCR(DocumentConverter): def __init__(self, ocr_service: Optional[LLMVisionOCRService] = None): super().__init__() self._html_converter = HtmlConverter() self.ocr_service = ocr_service def accepts( self, file_stream: BinaryIO, stream_info: StreamInfo, **kwargs: Any, ) -> bool: mimetype = (stream_info.mimetype or "").lower() extension = (stream_info.extension or "").lower() if extension == ".pptx": return True if mimetype.startswith( "application/vnd.openxmlformats-officedocument.presentationml" ): return True return False def convert( self, file_stream: BinaryIO, stream_info: StreamInfo, **kwargs: Any, ) -> DocumentConverterResult: if _dependency_exc_info is not None: raise MissingDependencyException( MISSING_DEPENDENCY_MESSAGE.format( converter=type(self).__name__, extension=".pptx", feature="pptx", ) ) from _dependency_exc_info[1].with_traceback( _dependency_exc_info[2] ) # type: ignore[union-attr] # Get OCR service (from kwargs or instance) ocr_service: Optional[LLMVisionOCRService] = ( kwargs.get("ocr_service") or self.ocr_service ) llm_client = kwargs.get("llm_client") presentation = pptx.Presentation(file_stream) md_content = "" slide_num = 0 for slide in presentation.slides: slide_num += 1 md_content += f"\\n\\n<!-- Slide number: {slide_num} -->\\n" title = slide.shapes.title def get_shape_content(shape, **kwargs): nonlocal md_content # Pictures if self._is_picture(shape): # Get image data image_stream = io.BytesIO(shape.image.blob) # Try LLM description first if available llm_description = "" if llm_client and kwargs.get("llm_model"): try: from ._llm_caption import llm_caption image_filename = shape.image.filename image_extension = None if image_filename: import os image_extension = os.path.splitext(image_filename)[1] image_stream_info = StreamInfo( mimetype=shape.image.content_type, extension=image_extension, filename=image_filename, ) llm_description = llm_caption( image_stream, image_stream_info, client=llm_client, model=kwargs.get("llm_model"), prompt=kwargs.get("llm_prompt"), ) except Exception: pass # Try OCR if LLM failed or not available ocr_text = "" if not llm_description and ocr_service: try: image_stream.seek(0) ocr_result = ocr_service.extract_text(image_stream) if ocr_result.text.strip(): ocr_text = ocr_result.text.strip() except Exception: pass # Format extracted content using unified OCR block format content = (llm_description or ocr_text or "").strip() if content: md_content += f"\n*[Image OCR]\n{content}\n[End OCR]*\n" # Tables if self._is_table(shape): md_content += self._convert_table_to_markdown(shape.table, **kwargs) # Charts if shape.has_chart: md_content += self._convert_chart_to_markdown(shape.chart) # Text areas elif shape.has_text_frame: if shape == title: md_content += "# " + shape.text.lstrip() + "\\n" else: md_content += shape.text + "\\n" # Group Shapes if shape.shape_type == pptx.enum.shapes.MSO_SHAPE_TYPE.GROUP: sorted_shapes = sorted( shape.shapes, key=lambda x: ( float("-inf") if not x.top else x.top, float("-inf") if not x.left else x.left, ), ) for subshape in sorted_shapes: get_shape_content(subshape, **kwargs) sorted_shapes = sorted( slide.shapes, key=lambda x: ( float("-inf") if not x.top else x.top, float("-inf") if not x.left else x.left, ), ) for shape in sorted_shapes: get_shape_content(shape, **kwargs) md_content = md_content.strip() if slide.has_notes_slide: md_content += "\\n\\n### Notes:\\n" notes_frame = slide.notes_slide.notes_text_frame if notes_frame is not None: md_content += notes_frame.text md_content = md_content.strip() return DocumentConverterResult(markdown=md_content.strip()) def _is_picture(self, shape): if shape.shape_type == pptx.enum.shapes.MSO_SHAPE_TYPE.PICTURE: return True if shape.shape_type == pptx.enum.shapes.MSO_SHAPE_TYPE.PLACEHOLDER: if hasattr(shape, "image"): return True return False def _is_table(self, shape): if shape.shape_type == pptx.enum.shapes.MSO_SHAPE_TYPE.TABLE: return True return False def _convert_table_to_markdown(self, table, **kwargs): import html html_table = "<html><body><table>" first_row = True for row in table.rows: html_table += "<tr>" for cell in row.cells: if first_row: html_table += "<th>" + html.escape(cell.text) + "</th>" else: html_table += "<td>" + html.escape(cell.text) + "</td>" html_table += "</tr>" first_row = False html_table += "</table></body></html>" return ( self._html_converter.convert_string(html_table, **kwargs).markdown.strip() + "\\n" ) def _convert_chart_to_markdown(self, chart): try: md = "\\n\\n### Chart" if chart.has_title: md += f": {chart.chart_title.text_frame.text}" md += "\\n\\n" data = [] category_names = [c.label for c in chart.plots[0].categories] series_names = [s.name for s in chart.series] data.append(["Category"] + series_names) for idx, category in enumerate(category_names): row = [category] for series in chart.series: row.append(series.values[idx]) data.append(row) markdown_table = [] for row in data: markdown_table.append("| " + " | ".join(map(str, row)) + " |") header = markdown_table[0] separator = "|" + "|".join(["---"] * len(data[0])) + "|" return md + "\\n".join([header, separator] + markdown_table[1:]) except ValueError as e: if "unsupported plot type" in str(e): return "\\n\\n[unsupported chart]\\n\\n" except Exception: return "\\n\\n[unsupported chart]\\n\\n"
--- +++ @@ -1,3 +1,7 @@+""" +Enhanced PPTX Converter with improved OCR support. +Already has LLM-based image description, this enhances it with traditional OCR fallback. +""" import io import sys @@ -21,6 +25,7 @@ class PptxConverterWithOCR(DocumentConverter): + """Enhanced PPTX Converter with OCR fallback.""" def __init__(self, ocr_service: Optional[LLMVisionOCRService] = None): super().__init__() @@ -241,4 +246,4 @@ if "unsupported plot type" in str(e): return "\\n\\n[unsupported chart]\\n\\n" except Exception: - return "\\n\\n[unsupported chart]\\n\\n"+ return "\\n\\n[unsupported chart]\\n\\n"
https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown-ocr/src/markitdown_ocr/_pptx_converter_with_ocr.py
Add docstrings that explain inputs and outputs
import contextlib import sys import os from collections.abc import AsyncIterator from mcp.server.fastmcp import FastMCP from starlette.applications import Starlette from mcp.server.sse import SseServerTransport from starlette.requests import Request from starlette.routing import Mount, Route from starlette.types import Receive, Scope, Send from mcp.server import Server from mcp.server.streamable_http_manager import StreamableHTTPSessionManager from markitdown import MarkItDown import uvicorn # Initialize FastMCP server for MarkItDown (SSE) mcp = FastMCP("markitdown") @mcp.tool() async def convert_to_markdown(uri: str) -> str: return MarkItDown(enable_plugins=check_plugins_enabled()).convert_uri(uri).markdown def check_plugins_enabled() -> bool: return os.getenv("MARKITDOWN_ENABLE_PLUGINS", "false").strip().lower() in ( "true", "1", "yes", ) def create_starlette_app(mcp_server: Server, *, debug: bool = False) -> Starlette: sse = SseServerTransport("/messages/") session_manager = StreamableHTTPSessionManager( app=mcp_server, event_store=None, json_response=True, stateless=True, ) async def handle_sse(request: Request) -> None: async with sse.connect_sse( request.scope, request.receive, request._send, ) as (read_stream, write_stream): await mcp_server.run( read_stream, write_stream, mcp_server.create_initialization_options(), ) async def handle_streamable_http( scope: Scope, receive: Receive, send: Send ) -> None: await session_manager.handle_request(scope, receive, send) @contextlib.asynccontextmanager async def lifespan(app: Starlette) -> AsyncIterator[None]: async with session_manager.run(): print("Application started with StreamableHTTP session manager!") try: yield finally: print("Application shutting down...") return Starlette( debug=debug, routes=[ Route("/sse", endpoint=handle_sse), Mount("/mcp", app=handle_streamable_http), Mount("/messages/", app=sse.handle_post_message), ], lifespan=lifespan, ) # Main entry point def main(): import argparse mcp_server = mcp._mcp_server parser = argparse.ArgumentParser(description="Run a MarkItDown MCP server") parser.add_argument( "--http", action="store_true", help="Run the server with Streamable HTTP and SSE transport rather than STDIO (default: False)", ) parser.add_argument( "--sse", action="store_true", help="(Deprecated) An alias for --http (default: False)", ) parser.add_argument( "--host", default=None, help="Host to bind to (default: 127.0.0.1)" ) parser.add_argument( "--port", type=int, default=None, help="Port to listen on (default: 3001)" ) args = parser.parse_args() use_http = args.http or args.sse if not use_http and (args.host or args.port): parser.error( "Host and port arguments are only valid when using streamable HTTP or SSE transport (see: --http)." ) sys.exit(1) if use_http: starlette_app = create_starlette_app(mcp_server, debug=True) uvicorn.run( starlette_app, host=args.host if args.host else "127.0.0.1", port=args.port if args.port else 3001, ) else: mcp.run() if __name__ == "__main__": main()
--- +++ @@ -19,6 +19,7 @@ @mcp.tool() async def convert_to_markdown(uri: str) -> str: + """Convert a resource described by an http:, https:, file: or data: URI to markdown""" return MarkItDown(enable_plugins=check_plugins_enabled()).convert_uri(uri).markdown @@ -58,6 +59,7 @@ @contextlib.asynccontextmanager async def lifespan(app: Starlette) -> AsyncIterator[None]: + """Context manager for session manager.""" async with session_manager.run(): print("Application started with StreamableHTTP session manager!") try: @@ -122,4 +124,4 @@ if __name__ == "__main__": - main()+ main()
https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown-mcp/src/markitdown_mcp/__main__.py