instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Generate documentation strings for clarity |
import argparse
import copy
def generate_neighbours(path):
dict_of_neighbours = {}
with open(path) as f:
for line in f:
if line.split()[0] not in dict_of_neighbours:
_list = []
_list.append([line.split()[1], line.split()[2]])
dict_of_neighbours[line.split()[0]] = _list
else:
dict_of_neighbours[line.split()[0]].append(
[line.split()[1], line.split()[2]]
)
if line.split()[1] not in dict_of_neighbours:
_list = []
_list.append([line.split()[0], line.split()[2]])
dict_of_neighbours[line.split()[1]] = _list
else:
dict_of_neighbours[line.split()[1]].append(
[line.split()[0], line.split()[2]]
)
return dict_of_neighbours
def generate_first_solution(path, dict_of_neighbours):
with open(path) as f:
start_node = f.read(1)
end_node = start_node
first_solution = []
visiting = start_node
distance_of_first_solution = 0
while visiting not in first_solution:
minim = 10000
for k in dict_of_neighbours[visiting]:
if int(k[1]) < int(minim) and k[0] not in first_solution:
minim = k[1]
best_node = k[0]
first_solution.append(visiting)
distance_of_first_solution = distance_of_first_solution + int(minim)
visiting = best_node
first_solution.append(end_node)
position = 0
for k in dict_of_neighbours[first_solution[-2]]:
if k[0] == start_node:
break
position += 1
distance_of_first_solution = (
distance_of_first_solution
+ int(dict_of_neighbours[first_solution[-2]][position][1])
- 10000
)
return first_solution, distance_of_first_solution
def find_neighborhood(solution, dict_of_neighbours):
neighborhood_of_solution = []
for n in solution[1:-1]:
idx1 = solution.index(n)
for kn in solution[1:-1]:
idx2 = solution.index(kn)
if n == kn:
continue
_tmp = copy.deepcopy(solution)
_tmp[idx1] = kn
_tmp[idx2] = n
distance = 0
for k in _tmp[:-1]:
next_node = _tmp[_tmp.index(k) + 1]
for i in dict_of_neighbours[k]:
if i[0] == next_node:
distance = distance + int(i[1])
_tmp.append(distance)
if _tmp not in neighborhood_of_solution:
neighborhood_of_solution.append(_tmp)
index_of_last_item_in_the_list = len(neighborhood_of_solution[0]) - 1
neighborhood_of_solution.sort(key=lambda x: x[index_of_last_item_in_the_list])
return neighborhood_of_solution
def tabu_search(
first_solution, distance_of_first_solution, dict_of_neighbours, iters, size
):
count = 1
solution = first_solution
tabu_list = []
best_cost = distance_of_first_solution
best_solution_ever = solution
while count <= iters:
neighborhood = find_neighborhood(solution, dict_of_neighbours)
index_of_best_solution = 0
best_solution = neighborhood[index_of_best_solution]
best_cost_index = len(best_solution) - 1
found = False
while not found:
i = 0
while i < len(best_solution):
if best_solution[i] != solution[i]:
first_exchange_node = best_solution[i]
second_exchange_node = solution[i]
break
i = i + 1
if [first_exchange_node, second_exchange_node] not in tabu_list and [
second_exchange_node,
first_exchange_node,
] not in tabu_list:
tabu_list.append([first_exchange_node, second_exchange_node])
found = True
solution = best_solution[:-1]
cost = neighborhood[index_of_best_solution][best_cost_index]
if cost < best_cost:
best_cost = cost
best_solution_ever = solution
else:
index_of_best_solution = index_of_best_solution + 1
best_solution = neighborhood[index_of_best_solution]
if len(tabu_list) >= size:
tabu_list.pop(0)
count = count + 1
return best_solution_ever, best_cost
def main(args=None):
dict_of_neighbours = generate_neighbours(args.File)
first_solution, distance_of_first_solution = generate_first_solution(
args.File, dict_of_neighbours
)
best_sol, best_cost = tabu_search(
first_solution,
distance_of_first_solution,
dict_of_neighbours,
args.Iterations,
args.Size,
)
print(f"Best solution: {best_sol}, with total distance: {best_cost}.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Tabu Search")
parser.add_argument(
"-f",
"--File",
type=str,
help="Path to the file containing the data",
required=True,
)
parser.add_argument(
"-i",
"--Iterations",
type=int,
help="How many iterations the algorithm should perform",
required=True,
)
parser.add_argument(
"-s", "--Size", type=int, help="Size of the tabu list", required=True
)
# Pass the arguments to main method
main(parser.parse_args()) | --- +++ @@ -1,9 +1,51 @@+"""
+This is pure Python implementation of Tabu search algorithm for a Travelling Salesman
+Problem, that the distances between the cities are symmetric (the distance between city
+'a' and city 'b' is the same between city 'b' and city 'a').
+The TSP can be represented into a graph. The cities are represented by nodes and the
+distance between them is represented by the weight of the ark between the nodes.
+
+The .txt file with the graph has the form:
+
+node1 node2 distance_between_node1_and_node2
+node1 node3 distance_between_node1_and_node3
+...
+
+Be careful node1, node2 and the distance between them, must exist only once. This means
+in the .txt file should not exist:
+node1 node2 distance_between_node1_and_node2
+node2 node1 distance_between_node2_and_node1
+
+For pytests run following command:
+pytest
+
+For manual testing run:
+python tabu_search.py -f your_file_name.txt -number_of_iterations_of_tabu_search \
+ -s size_of_tabu_search
+e.g. python tabu_search.py -f tabudata2.txt -i 4 -s 3
+"""
import argparse
import copy
def generate_neighbours(path):
+ """
+ Pure implementation of generating a dictionary of neighbors and the cost with each
+ neighbor, given a path file that includes a graph.
+
+ :param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt)
+ :return dict_of_neighbours: Dictionary with key each node and value a list of lists
+ with the neighbors of the node and the cost (distance) for each neighbor.
+
+ Example of dict_of_neighbours:
+ >>) dict_of_neighbours[a]
+ [[b,20],[c,18],[d,22],[e,26]]
+
+ This indicates the neighbors of node (city) 'a', which has neighbor the node 'b'
+ with distance 20, the node 'c' with distance 18, the node 'd' with distance 22 and
+ the node 'e' with distance 26.
+ """
dict_of_neighbours = {}
@@ -30,6 +72,21 @@
def generate_first_solution(path, dict_of_neighbours):
+ """
+ Pure implementation of generating the first solution for the Tabu search to start,
+ with the redundant resolution strategy. That means that we start from the starting
+ node (e.g. node 'a'), then we go to the city nearest (lowest distance) to this node
+ (let's assume is node 'c'), then we go to the nearest city of the node 'c', etc.
+ till we have visited all cities and return to the starting node.
+
+ :param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt)
+ :param dict_of_neighbours: Dictionary with key each node and value a list of lists
+ with the neighbors of the node and the cost (distance) for each neighbor.
+ :return first_solution: The solution for the first iteration of Tabu search using
+ the redundant resolution strategy in a list.
+ :return distance_of_first_solution: The total distance that Travelling Salesman
+ will travel, if he follows the path in first_solution.
+ """
with open(path) as f:
start_node = f.read(1)
@@ -68,6 +125,34 @@
def find_neighborhood(solution, dict_of_neighbours):
+ """
+ Pure implementation of generating the neighborhood (sorted by total distance of
+ each solution from lowest to highest) of a solution with 1-1 exchange method, that
+ means we exchange each node in a solution with each other node and generating a
+ number of solution named neighborhood.
+
+ :param solution: The solution in which we want to find the neighborhood.
+ :param dict_of_neighbours: Dictionary with key each node and value a list of lists
+ with the neighbors of the node and the cost (distance) for each neighbor.
+ :return neighborhood_of_solution: A list that includes the solutions and the total
+ distance of each solution (in form of list) that are produced with 1-1 exchange
+ from the solution that the method took as an input
+
+ Example:
+ >>> find_neighborhood(['a', 'c', 'b', 'd', 'e', 'a'],
+ ... {'a': [['b', '20'], ['c', '18'], ['d', '22'], ['e', '26']],
+ ... 'c': [['a', '18'], ['b', '10'], ['d', '23'], ['e', '24']],
+ ... 'b': [['a', '20'], ['c', '10'], ['d', '11'], ['e', '12']],
+ ... 'e': [['a', '26'], ['b', '12'], ['c', '24'], ['d', '40']],
+ ... 'd': [['a', '22'], ['b', '11'], ['c', '23'], ['e', '40']]}
+ ... ) # doctest: +NORMALIZE_WHITESPACE
+ [['a', 'e', 'b', 'd', 'c', 'a', 90],
+ ['a', 'c', 'd', 'b', 'e', 'a', 90],
+ ['a', 'd', 'b', 'c', 'e', 'a', 93],
+ ['a', 'c', 'b', 'e', 'd', 'a', 102],
+ ['a', 'c', 'e', 'd', 'b', 'a', 113],
+ ['a', 'b', 'c', 'd', 'e', 'a', 119]]
+ """
neighborhood_of_solution = []
@@ -103,6 +188,23 @@ def tabu_search(
first_solution, distance_of_first_solution, dict_of_neighbours, iters, size
):
+ """
+ Pure implementation of Tabu search algorithm for a Travelling Salesman Problem in
+ Python.
+
+ :param first_solution: The solution for the first iteration of Tabu search using
+ the redundant resolution strategy in a list.
+ :param distance_of_first_solution: The total distance that Travelling Salesman will
+ travel, if he follows the path in first_solution.
+ :param dict_of_neighbours: Dictionary with key each node and value a list of lists
+ with the neighbors of the node and the cost (distance) for each neighbor.
+ :param iters: The number of iterations that Tabu search will execute.
+ :param size: The size of Tabu List.
+ :return best_solution_ever: The solution with the lowest distance that occurred
+ during the execution of Tabu search.
+ :return best_cost: The total distance that Travelling Salesman will travel, if he
+ follows the path in best_solution ever.
+ """
count = 1
solution = first_solution
tabu_list = []
@@ -187,4 +289,4 @@ )
# Pass the arguments to main method
- main(parser.parse_args())+ main(parser.parse_args())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/tabu_search.py |
Annotate my code with docstrings |
def bead_sort(sequence: list) -> list:
if any(not isinstance(x, int) or x < 0 for x in sequence):
raise TypeError("Sequence must be list of non-negative integers")
for _ in range(len(sequence)):
for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])): # noqa: RUF007
if rod_upper > rod_lower:
sequence[i] -= rod_upper - rod_lower
sequence[i + 1] += rod_upper - rod_lower
return sequence
if __name__ == "__main__":
assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9] | --- +++ @@ -1,6 +1,33 @@+"""
+Bead sort only works for sequences of non-negative integers.
+https://en.wikipedia.org/wiki/Bead_sort
+"""
def bead_sort(sequence: list) -> list:
+ """
+ >>> bead_sort([6, 11, 12, 4, 1, 5])
+ [1, 4, 5, 6, 11, 12]
+
+ >>> bead_sort([9, 8, 7, 6, 5, 4 ,3, 2, 1])
+ [1, 2, 3, 4, 5, 6, 7, 8, 9]
+
+ >>> bead_sort([5, 0, 4, 3])
+ [0, 3, 4, 5]
+
+ >>> bead_sort([8, 2, 1])
+ [1, 2, 8]
+
+ >>> bead_sort([1, .9, 0.0, 0, -1, -.9])
+ Traceback (most recent call last):
+ ...
+ TypeError: Sequence must be list of non-negative integers
+
+ >>> bead_sort("Hello world")
+ Traceback (most recent call last):
+ ...
+ TypeError: Sequence must be list of non-negative integers
+ """
if any(not isinstance(x, int) or x < 0 for x in sequence):
raise TypeError("Sequence must be list of non-negative integers")
for _ in range(len(sequence)):
@@ -13,4 +40,4 @@
if __name__ == "__main__":
assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
- assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]+ assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/bead_sort.py |
Insert docstrings into my code |
import multiprocessing as mp
# lock used to ensure that two processes do not access a pipe at the same time
# NOTE This breaks testing on build runner. May work better locally
# process_lock = mp.Lock()
"""
The function run by the processes that sorts the list
position = the position in the list the process represents, used to know which
neighbor we pass our value to
value = the initial value at list[position]
LSend, RSend = the pipes we use to send to our left and right neighbors
LRcv, RRcv = the pipes we use to receive from our left and right neighbors
resultPipe = the pipe used to send results back to main
"""
def oe_process(
position,
value,
l_send,
r_send,
lr_cv,
rr_cv,
result_pipe,
multiprocessing_context,
):
process_lock = multiprocessing_context.Lock()
# we perform n swaps since after n swaps we know we are sorted
# we *could* stop early if we are sorted already, but it takes as long to
# find out we are sorted as it does to sort the list with this algorithm
for i in range(10):
if (i + position) % 2 == 0 and r_send is not None:
# send your value to your right neighbor
with process_lock:
r_send[1].send(value)
# receive your right neighbor's value
with process_lock:
temp = rr_cv[0].recv()
# take the lower value since you are on the left
value = min(value, temp)
elif (i + position) % 2 != 0 and l_send is not None:
# send your value to your left neighbor
with process_lock:
l_send[1].send(value)
# receive your left neighbor's value
with process_lock:
temp = lr_cv[0].recv()
# take the higher value since you are on the right
value = max(value, temp)
# after all swaps are performed, send the values back to main
result_pipe[1].send(value)
"""
the function which creates the processes that perform the parallel swaps
arr = the list to be sorted
"""
def odd_even_transposition(arr):
# spawn method is considered safer than fork
multiprocessing_context = mp.get_context("spawn")
process_array_ = []
result_pipe = []
# initialize the list of pipes where the values will be retrieved
for _ in arr:
result_pipe.append(multiprocessing_context.Pipe())
# creates the processes
# the first and last process only have one neighbor so they are made outside
# of the loop
temp_rs = multiprocessing_context.Pipe()
temp_rr = multiprocessing_context.Pipe()
process_array_.append(
multiprocessing_context.Process(
target=oe_process,
args=(
0,
arr[0],
None,
temp_rs,
None,
temp_rr,
result_pipe[0],
multiprocessing_context,
),
)
)
temp_lr = temp_rs
temp_ls = temp_rr
for i in range(1, len(arr) - 1):
temp_rs = multiprocessing_context.Pipe()
temp_rr = multiprocessing_context.Pipe()
process_array_.append(
multiprocessing_context.Process(
target=oe_process,
args=(
i,
arr[i],
temp_ls,
temp_rs,
temp_lr,
temp_rr,
result_pipe[i],
multiprocessing_context,
),
)
)
temp_lr = temp_rs
temp_ls = temp_rr
process_array_.append(
multiprocessing_context.Process(
target=oe_process,
args=(
len(arr) - 1,
arr[len(arr) - 1],
temp_ls,
None,
temp_lr,
None,
result_pipe[len(arr) - 1],
multiprocessing_context,
),
)
)
# start the processes
for p in process_array_:
p.start()
# wait for the processes to end and write their values to the list
for p in range(len(result_pipe)):
arr[p] = result_pipe[p][0].recv()
process_array_[p].join()
return arr
# creates a reverse sorted list and sorts it
def main():
arr = list(range(10, 0, -1))
print("Initial List")
print(*arr)
arr = odd_even_transposition(arr)
print("Sorted List\n")
print(*arr)
if __name__ == "__main__":
main() | --- +++ @@ -1,3 +1,15 @@+"""
+This is an implementation of odd-even transposition sort.
+
+It works by performing a series of parallel swaps between odd and even pairs of
+variables in the list.
+
+This implementation represents each variable in the list with a process and
+each process communicates with its neighboring processes in the list to perform
+comparisons.
+They are synchronized with locks and message passing but other forms of
+synchronization could be used.
+"""
import multiprocessing as mp
@@ -67,6 +79,26 @@
def odd_even_transposition(arr):
+ """
+ >>> odd_even_transposition(list(range(10)[::-1])) == sorted(list(range(10)[::-1]))
+ True
+ >>> odd_even_transposition(["a", "x", "c"]) == sorted(["x", "a", "c"])
+ True
+ >>> odd_even_transposition([1.9, 42.0, 2.8]) == sorted([1.9, 42.0, 2.8])
+ True
+ >>> odd_even_transposition([False, True, False]) == sorted([False, False, True])
+ True
+ >>> odd_even_transposition([1, 32.0, 9]) == sorted([False, False, True])
+ False
+ >>> odd_even_transposition([1, 32.0, 9]) == sorted([1.0, 32, 9.0])
+ True
+ >>> unsorted_list = [-442, -98, -554, 266, -491, 985, -53, -529, 82, -429]
+ >>> odd_even_transposition(unsorted_list) == sorted(unsorted_list)
+ True
+ >>> unsorted_list = [-442, -98, -554, 266, -491, 985, -53, -529, 82, -429]
+ >>> odd_even_transposition(unsorted_list) == sorted(unsorted_list + [1])
+ False
+ """
# spawn method is considered safer than fork
multiprocessing_context = mp.get_context("spawn")
@@ -157,4 +189,4 @@
if __name__ == "__main__":
- main()+ main()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/odd_even_transposition_parallel.py |
Create docstrings for API functions |
import math
from collections.abc import Sequence
from typing import Any, Protocol
class Comparable(Protocol):
def __lt__(self, other: Any, /) -> bool: ...
def jump_search[T: Comparable](arr: Sequence[T], item: T) -> int:
arr_size = len(arr)
block_size = int(math.sqrt(arr_size))
prev = 0
step = block_size
while arr[min(step, arr_size) - 1] < item:
prev = step
step += block_size
if prev >= arr_size:
return -1
while arr[prev] < item:
prev += 1
if prev == min(step, arr_size):
return -1
if arr[prev] == item:
return prev
return -1
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
array = [int(item) for item in user_input.split(",")]
x = int(input("Enter the number to be searched:\n"))
res = jump_search(array, x)
if res == -1:
print("Number not found!")
else:
print(f"Number {x} is at index {res}") | --- +++ @@ -1,3 +1,12 @@+"""
+Pure Python implementation of the jump search algorithm.
+This algorithm iterates through a sorted collection with a step of n^(1/2),
+until the element compared is bigger than the one searched.
+It will then perform a linear search until it matches the wanted number.
+If not found, it returns -1.
+
+https://en.wikipedia.org/wiki/Jump_search
+"""
import math
from collections.abc import Sequence
@@ -9,6 +18,22 @@
def jump_search[T: Comparable](arr: Sequence[T], item: T) -> int:
+ """
+ Python implementation of the jump search algorithm.
+ Return the index if the `item` is found, otherwise return -1.
+
+ Examples:
+ >>> jump_search([0, 1, 2, 3, 4, 5], 3)
+ 3
+ >>> jump_search([-5, -2, -1], -1)
+ 2
+ >>> jump_search([0, 5, 10, 20], 8)
+ -1
+ >>> jump_search([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610], 55)
+ 10
+ >>> jump_search(["aa", "bb", "cc", "dd", "ee", "ff"], "ee")
+ 4
+ """
arr_size = len(arr)
block_size = int(math.sqrt(arr_size))
@@ -39,4 +64,4 @@ if res == -1:
print("Number not found!")
else:
- print(f"Number {x} is at index {res}")+ print(f"Number {x} is at index {res}")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/searches/jump_search.py |
Add structured docstrings to improve clarity |
def pancake_sort(arr):
cur = len(arr)
while cur > 1:
# Find the maximum number in arr
mi = arr.index(max(arr[0:cur]))
# Reverse from 0 to mi
arr = arr[mi::-1] + arr[mi + 1 : len(arr)]
# Reverse whole list
arr = arr[cur - 1 :: -1] + arr[cur : len(arr)]
cur -= 1
return arr
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(pancake_sort(unsorted)) | --- +++ @@ -1,6 +1,26 @@+"""
+This is a pure Python implementation of the pancake sort algorithm
+For doctests run following command:
+python3 -m doctest -v pancake_sort.py
+or
+python -m doctest -v pancake_sort.py
+For manual testing run:
+python pancake_sort.py
+"""
def pancake_sort(arr):
+ """Sort Array with Pancake Sort.
+ :param arr: Collection containing comparable items
+ :return: Collection ordered in ascending order of items
+ Examples:
+ >>> pancake_sort([0, 5, 3, 2, 2])
+ [0, 2, 2, 3, 5]
+ >>> pancake_sort([])
+ []
+ >>> pancake_sort([-2, -5, -45])
+ [-45, -5, -2]
+ """
cur = len(arr)
while cur > 1:
# Find the maximum number in arr
@@ -16,4 +36,4 @@ if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
- print(pancake_sort(unsorted))+ print(pancake_sort(unsorted))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/pancake_sort.py |
Add docstrings for better understanding |
from __future__ import annotations
def pigeon_sort(array: list[int]) -> list[int]:
if len(array) == 0:
return array
_min, _max = min(array), max(array)
# Compute the variables
holes_range = _max - _min + 1
holes, holes_repeat = [0] * holes_range, [0] * holes_range
# Make the sorting.
for i in array:
index = i - _min
holes[index] = i
holes_repeat[index] += 1
# Makes the array back by replacing the numbers.
index = 0
for i in range(holes_range):
while holes_repeat[i] > 0:
array[index] = holes[i]
index += 1
holes_repeat[i] -= 1
# Returns the sorted array.
return array
if __name__ == "__main__":
import doctest
doctest.testmod()
user_input = input("Enter numbers separated by comma:\n")
unsorted = [int(x) for x in user_input.split(",")]
print(pigeon_sort(unsorted)) | --- +++ @@ -1,8 +1,30 @@+"""
+This is an implementation of Pigeon Hole Sort.
+For doctests run following command:
+
+python3 -m doctest -v pigeon_sort.py
+or
+python -m doctest -v pigeon_sort.py
+
+For manual testing run:
+python pigeon_sort.py
+"""
from __future__ import annotations
def pigeon_sort(array: list[int]) -> list[int]:
+ """
+ Implementation of pigeon hole sort algorithm
+ :param array: Collection of comparable items
+ :return: Collection sorted in ascending order
+ >>> pigeon_sort([0, 5, 3, 2, 2])
+ [0, 2, 2, 3, 5]
+ >>> pigeon_sort([])
+ []
+ >>> pigeon_sort([-2, -5, -45])
+ [-45, -5, -2]
+ """
if len(array) == 0:
return array
@@ -36,4 +58,4 @@ doctest.testmod()
user_input = input("Enter numbers separated by comma:\n")
unsorted = [int(x) for x in user_input.split(",")]
- print(pigeon_sort(unsorted))+ print(pigeon_sort(unsorted))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/pigeon_sort.py |
Write docstrings for backend logic |
def odd_even_sort(input_list: list) -> list:
is_sorted = False
while is_sorted is False: # Until all the indices are traversed keep looping
is_sorted = True
for i in range(0, len(input_list) - 1, 2): # iterating over all even indices
if input_list[i] > input_list[i + 1]:
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
# swapping if elements not in order
is_sorted = False
for i in range(1, len(input_list) - 1, 2): # iterating over all odd indices
if input_list[i] > input_list[i + 1]:
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
# swapping if elements not in order
is_sorted = False
return input_list
if __name__ == "__main__":
print("Enter list to be sorted")
input_list = [int(x) for x in input().split()]
# inputing elements of the list in one line
sorted_list = odd_even_sort(input_list)
print("The sorted list is")
print(sorted_list) | --- +++ @@ -1,6 +1,30 @@+"""
+Odd even sort implementation.
+
+https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort
+"""
def odd_even_sort(input_list: list) -> list:
+ """
+ Sort input with odd even sort.
+
+ This algorithm uses the same idea of bubblesort,
+ but by first dividing in two phase (odd and even).
+ Originally developed for use on parallel processors
+ with local interconnections.
+ :param collection: mutable ordered sequence of elements
+ :return: same collection in ascending order
+ Examples:
+ >>> odd_even_sort([5 , 4 ,3 ,2 ,1])
+ [1, 2, 3, 4, 5]
+ >>> odd_even_sort([])
+ []
+ >>> odd_even_sort([-10 ,-1 ,10 ,2])
+ [-10, -1, 2, 10]
+ >>> odd_even_sort([1 ,2 ,3 ,4])
+ [1, 2, 3, 4]
+ """
is_sorted = False
while is_sorted is False: # Until all the indices are traversed keep looping
is_sorted = True
@@ -24,4 +48,4 @@ # inputing elements of the list in one line
sorted_list = odd_even_sort(input_list)
print("The sorted list is")
- print(sorted_list)+ print(sorted_list)
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/odd_even_sort.py |
Write Python docstrings for this snippet |
def odd_even_transposition(arr: list) -> list:
arr_size = len(arr)
for _ in range(arr_size):
for i in range(_ % 2, arr_size - 1, 2):
if arr[i + 1] < arr[i]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
return arr
if __name__ == "__main__":
arr = list(range(10, 0, -1))
print(f"Original: {arr}. Sorted: {odd_even_transposition(arr)}") | --- +++ @@ -1,6 +1,24 @@+"""
+Source: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort
+
+This is a non-parallelized implementation of odd-even transposition sort.
+
+Normally the swaps in each set happen simultaneously, without that the algorithm
+is no better than bubble sort.
+"""
def odd_even_transposition(arr: list) -> list:
+ """
+ >>> odd_even_transposition([5, 4, 3, 2, 1])
+ [1, 2, 3, 4, 5]
+
+ >>> odd_even_transposition([13, 11, 18, 0, -1])
+ [-1, 0, 11, 13, 18]
+
+ >>> odd_even_transposition([-.1, 1.1, .1, -2.9])
+ [-2.9, -0.1, 0.1, 1.1]
+ """
arr_size = len(arr)
for _ in range(arr_size):
for i in range(_ % 2, arr_size - 1, 2):
@@ -12,4 +30,4 @@
if __name__ == "__main__":
arr = list(range(10, 0, -1))
- print(f"Original: {arr}. Sorted: {odd_even_transposition(arr)}")+ print(f"Original: {arr}. Sorted: {odd_even_transposition(arr)}")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/odd_even_transposition_single_threaded.py |
Create docstrings for each class method |
def binary_insertion_sort(collection: list) -> list:
n = len(collection)
for i in range(1, n):
value_to_insert = collection[i]
low = 0
high = i - 1
while low <= high:
mid = (low + high) // 2
if value_to_insert < collection[mid]:
high = mid - 1
else:
low = mid + 1
for j in range(i, low, -1):
collection[j] = collection[j - 1]
collection[low] = value_to_insert
return collection
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
try:
unsorted = [int(item) for item in user_input.split(",")]
except ValueError:
print("Invalid input. Please enter valid integers separated by commas.")
raise
print(f"{binary_insertion_sort(unsorted) = }") | --- +++ @@ -1,6 +1,42 @@+"""
+This is a pure Python implementation of the binary insertion sort algorithm
+
+For doctests run following command:
+python -m doctest -v binary_insertion_sort.py
+or
+python3 -m doctest -v binary_insertion_sort.py
+
+For manual testing run:
+python binary_insertion_sort.py
+"""
def binary_insertion_sort(collection: list) -> list:
+ """
+ Sorts a list using the binary insertion sort algorithm.
+
+ :param collection: A mutable ordered collection with comparable items.
+ :return: The same collection ordered in ascending order.
+
+ Examples:
+ >>> binary_insertion_sort([0, 4, 1234, 4, 1])
+ [0, 1, 4, 4, 1234]
+ >>> binary_insertion_sort([]) == sorted([])
+ True
+ >>> binary_insertion_sort([-1, -2, -3]) == sorted([-1, -2, -3])
+ True
+ >>> lst = ['d', 'a', 'b', 'e', 'c']
+ >>> binary_insertion_sort(lst) == sorted(lst)
+ True
+ >>> import random
+ >>> collection = random.sample(range(-50, 50), 100)
+ >>> binary_insertion_sort(collection) == sorted(collection)
+ True
+ >>> import string
+ >>> collection = random.choices(string.ascii_letters + string.digits, k=100)
+ >>> binary_insertion_sort(collection) == sorted(collection)
+ True
+ """
n = len(collection)
for i in range(1, n):
@@ -27,4 +63,4 @@ except ValueError:
print("Invalid input. Please enter valid integers separated by commas.")
raise
- print(f"{binary_insertion_sort(unsorted) = }")+ print(f"{binary_insertion_sort(unsorted) = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/binary_insertion_sort.py |
Generate helpful docstrings for debugging |
from __future__ import annotations
RADIX = 10
def radix_sort(list_of_ints: list[int]) -> list[int]:
placement = 1
max_digit = max(list_of_ints)
while placement <= max_digit:
# declare and initialize empty buckets
buckets: list[list] = [[] for _ in range(RADIX)]
# split list_of_ints between the buckets
for i in list_of_ints:
tmp = int((i / placement) % RADIX)
buckets[tmp].append(i)
# put each buckets' contents into list_of_ints
a = 0
for b in range(RADIX):
for i in buckets[b]:
list_of_ints[a] = i
a += 1
# move to next
placement *= RADIX
return list_of_ints
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,3 +1,8 @@+"""
+This is a pure Python implementation of the radix sort algorithm
+
+Source: https://en.wikipedia.org/wiki/Radix_sort
+"""
from __future__ import annotations
@@ -5,6 +10,18 @@
def radix_sort(list_of_ints: list[int]) -> list[int]:
+ """
+ Examples:
+ >>> radix_sort([0, 5, 3, 2, 2])
+ [0, 2, 2, 3, 5]
+
+ >>> radix_sort(list(range(15))) == sorted(range(15))
+ True
+ >>> radix_sort(list(range(14,-1,-1))) == sorted(range(15))
+ True
+ >>> radix_sort([1,100,10,1000]) == sorted([1,100,10,1000])
+ True
+ """
placement = 1
max_digit = max(list_of_ints)
while placement <= max_digit:
@@ -28,4 +45,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/radix_sort.py |
Add clean documentation to messy code |
from __future__ import annotations
def slowsort(sequence: list, start: int | None = None, end: int | None = None) -> None:
if start is None:
start = 0
if end is None:
end = len(sequence) - 1
if start >= end:
return
mid = (start + end) // 2
slowsort(sequence, start, mid)
slowsort(sequence, mid + 1, end)
if sequence[end] < sequence[mid]:
sequence[end], sequence[mid] = sequence[mid], sequence[end]
slowsort(sequence, start, end - 1)
if __name__ == "__main__":
from doctest import testmod
testmod() | --- +++ @@ -1,8 +1,40 @@+"""
+Slowsort is a sorting algorithm. It is of humorous nature and not useful.
+It's based on the principle of multiply and surrender,
+a tongue-in-cheek joke of divide and conquer.
+It was published in 1986 by Andrei Broder and Jorge Stolfi
+in their paper Pessimal Algorithms and Simplexity Analysis
+(a parody of optimal algorithms and complexity analysis).
+
+Source: https://en.wikipedia.org/wiki/Slowsort
+"""
from __future__ import annotations
def slowsort(sequence: list, start: int | None = None, end: int | None = None) -> None:
+ """
+ Sorts sequence[start..end] (both inclusive) in-place.
+ start defaults to 0 if not given.
+ end defaults to len(sequence) - 1 if not given.
+ It returns None.
+ >>> seq = [1, 6, 2, 5, 3, 4, 4, 5]; slowsort(seq); seq
+ [1, 2, 3, 4, 4, 5, 5, 6]
+ >>> seq = []; slowsort(seq); seq
+ []
+ >>> seq = [2]; slowsort(seq); seq
+ [2]
+ >>> seq = [1, 2, 3, 4]; slowsort(seq); seq
+ [1, 2, 3, 4]
+ >>> seq = [4, 3, 2, 1]; slowsort(seq); seq
+ [1, 2, 3, 4]
+ >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, 2, 7); seq
+ [9, 8, 2, 3, 4, 5, 6, 7, 1, 0]
+ >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, end = 4); seq
+ [5, 6, 7, 8, 9, 4, 3, 2, 1, 0]
+ >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, start = 5); seq
+ [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]
+ """
if start is None:
start = 0
@@ -26,4 +58,4 @@ if __name__ == "__main__":
from doctest import testmod
- testmod()+ testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/slowsort.py |
Write beginner-friendly docstrings | def quick_sort_3partition(sorting: list, left: int, right: int) -> None:
if right <= left:
return
a = i = left
b = right
pivot = sorting[left]
while i <= b:
if sorting[i] < pivot:
sorting[a], sorting[i] = sorting[i], sorting[a]
a += 1
i += 1
elif sorting[i] > pivot:
sorting[b], sorting[i] = sorting[i], sorting[b]
b -= 1
else:
i += 1
quick_sort_3partition(sorting, left, a - 1)
quick_sort_3partition(sorting, b + 1, right)
def quick_sort_lomuto_partition(sorting: list, left: int, right: int) -> None:
if left < right:
pivot_index = lomuto_partition(sorting, left, right)
quick_sort_lomuto_partition(sorting, left, pivot_index - 1)
quick_sort_lomuto_partition(sorting, pivot_index + 1, right)
def lomuto_partition(sorting: list, left: int, right: int) -> int:
pivot = sorting[right]
store_index = left
for i in range(left, right):
if sorting[i] < pivot:
sorting[store_index], sorting[i] = sorting[i], sorting[store_index]
store_index += 1
sorting[right], sorting[store_index] = sorting[store_index], sorting[right]
return store_index
def three_way_radix_quicksort(sorting: list) -> list:
if len(sorting) <= 1:
return sorting
return (
three_way_radix_quicksort([i for i in sorting if i < sorting[0]])
+ [i for i in sorting if i == sorting[0]]
+ three_way_radix_quicksort([i for i in sorting if i > sorting[0]])
)
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
quick_sort_3partition(unsorted, 0, len(unsorted) - 1)
print(unsorted) | --- +++ @@ -1,4 +1,27 @@ def quick_sort_3partition(sorting: list, left: int, right: int) -> None:
+ """ "
+ Python implementation of quick sort algorithm with 3-way partition.
+ The idea of 3-way quick sort is based on "Dutch National Flag algorithm".
+
+ :param sorting: sort list
+ :param left: left endpoint of sorting
+ :param right: right endpoint of sorting
+ :return: None
+
+ Examples:
+ >>> array1 = [5, -1, -1, 5, 5, 24, 0]
+ >>> quick_sort_3partition(array1, 0, 6)
+ >>> array1
+ [-1, -1, 0, 5, 5, 5, 24]
+ >>> array2 = [9, 0, 2, 6]
+ >>> quick_sort_3partition(array2, 0, 3)
+ >>> array2
+ [0, 2, 6, 9]
+ >>> array3 = []
+ >>> quick_sort_3partition(array3, 0, 0)
+ >>> array3
+ []
+ """
if right <= left:
return
a = i = left
@@ -19,6 +42,30 @@
def quick_sort_lomuto_partition(sorting: list, left: int, right: int) -> None:
+ """
+ A pure Python implementation of quick sort algorithm(in-place)
+ with Lomuto partition scheme:
+ https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme
+
+ :param sorting: sort list
+ :param left: left endpoint of sorting
+ :param right: right endpoint of sorting
+ :return: None
+
+ Examples:
+ >>> nums1 = [0, 5, 3, 1, 2]
+ >>> quick_sort_lomuto_partition(nums1, 0, 4)
+ >>> nums1
+ [0, 1, 2, 3, 5]
+ >>> nums2 = []
+ >>> quick_sort_lomuto_partition(nums2, 0, 0)
+ >>> nums2
+ []
+ >>> nums3 = [-2, 5, 0, -4]
+ >>> quick_sort_lomuto_partition(nums3, 0, 3)
+ >>> nums3
+ [-4, -2, 0, 5]
+ """
if left < right:
pivot_index = lomuto_partition(sorting, left, right)
quick_sort_lomuto_partition(sorting, left, pivot_index - 1)
@@ -26,6 +73,11 @@
def lomuto_partition(sorting: list, left: int, right: int) -> int:
+ """
+ Example:
+ >>> lomuto_partition([1,5,7,6], 0, 3)
+ 2
+ """
pivot = sorting[right]
store_index = left
for i in range(left, right):
@@ -37,6 +89,21 @@
def three_way_radix_quicksort(sorting: list) -> list:
+ """
+ Three-way radix quicksort:
+ https://en.wikipedia.org/wiki/Quicksort#Three-way_radix_quicksort
+ First divide the list into three parts.
+ Then recursively sort the "less than" and "greater than" partitions.
+
+ >>> three_way_radix_quicksort([])
+ []
+ >>> three_way_radix_quicksort([1])
+ [1]
+ >>> three_way_radix_quicksort([-5, -2, 1, -2, 0, 1])
+ [-5, -2, -2, 0, 1, 1]
+ >>> three_way_radix_quicksort([1, 2, 5, 1, 2, 0, 0, 5, 2, -1])
+ [-1, 0, 0, 1, 1, 2, 2, 2, 5, 5]
+ """
if len(sorting) <= 1:
return sorting
return (
@@ -54,4 +121,4 @@ user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
quick_sort_3partition(unsorted, 0, len(unsorted) - 1)
- print(unsorted)+ print(unsorted)
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/quick_sort_3_partition.py |
Provide clean and structured docstrings |
def shell_sort(collection: list) -> list:
# Choose an initial gap value
gap = len(collection)
# Set the gap value to be decreased by a factor of 1.3
# after each iteration
shrink = 1.3
# Continue sorting until the gap is 1
while gap > 1:
# Decrease the gap value
gap = int(gap / shrink)
# Sort the elements using insertion sort
for i in range(gap, len(collection)):
temp = collection[i]
j = i
while j >= gap and collection[j - gap] > temp:
collection[j] = collection[j - gap]
j -= gap
collection[j] = temp
return collection
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,6 +1,39 @@+"""
+This function implements the shell sort algorithm
+which is slightly faster than its pure implementation.
+
+This shell sort is implemented using a gap, which
+shrinks by a certain factor each iteration. In this
+implementation, the gap is initially set to the
+length of the collection. The gap is then reduced by
+a certain factor (1.3) each iteration.
+
+For each iteration, the algorithm compares elements
+that are a certain number of positions apart
+(determined by the gap). If the element at the higher
+position is greater than the element at the lower
+position, the two elements are swapped. The process
+is repeated until the gap is equal to 1.
+
+The reason this is more efficient is that it reduces
+the number of comparisons that need to be made. By
+using a smaller gap, the list is sorted more quickly.
+"""
def shell_sort(collection: list) -> list:
+ """Implementation of shell sort algorithm in Python
+ :param collection: Some mutable ordered collection with heterogeneous
+ comparable items inside
+ :return: the same collection ordered by ascending
+
+ >>> shell_sort([3, 2, 1])
+ [1, 2, 3]
+ >>> shell_sort([])
+ []
+ >>> shell_sort([1])
+ [1]
+ """
# Choose an initial gap value
gap = len(collection)
@@ -29,4 +62,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/shrink_shell_sort.py |
Add docstrings for internal functions |
def shell_sort(collection: list[int]) -> list[int]:
# Marcin Ciura's gap sequence
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
for gap in gaps:
for i in range(gap, len(collection)):
insert_value = collection[i]
j = i
while j >= gap and collection[j - gap] > insert_value:
collection[j] = collection[j - gap]
j -= gap
if j != i:
collection[j] = insert_value
return collection
if __name__ == "__main__":
from doctest import testmod
testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(shell_sort(unsorted)) | --- +++ @@ -1,6 +1,21 @@+"""
+https://en.wikipedia.org/wiki/Shellsort#Pseudocode
+"""
def shell_sort(collection: list[int]) -> list[int]:
+ """Pure implementation of shell sort algorithm in Python
+ :param collection: Some mutable ordered collection with heterogeneous
+ comparable items inside
+ :return: the same collection ordered by ascending
+
+ >>> shell_sort([0, 5, 3, 2, 2])
+ [0, 2, 2, 3, 5]
+ >>> shell_sort([])
+ []
+ >>> shell_sort([-2, -5, -45])
+ [-45, -5, -2]
+ """
# Marcin Ciura's gap sequence
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
@@ -22,4 +37,4 @@ testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
- print(shell_sort(unsorted))+ print(shell_sort(unsorted))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/shell_sort.py |
Help me write clear docstrings |
from __future__ import annotations
def rec_insertion_sort(collection: list, n: int):
# Checks if the entire collection has been sorted
if len(collection) <= 1 or n <= 1:
return
insert_next(collection, n - 1)
rec_insertion_sort(collection, n - 1)
def insert_next(collection: list, index: int):
# Checks order between adjacent elements
if index >= len(collection) or collection[index - 1] <= collection[index]:
return
# Swaps adjacent elements since they are not in ascending order
collection[index - 1], collection[index] = (
collection[index],
collection[index - 1],
)
insert_next(collection, index + 1)
if __name__ == "__main__":
numbers = input("Enter integers separated by spaces: ")
number_list: list[int] = [int(num) for num in numbers.split()]
rec_insertion_sort(number_list, len(number_list))
print(number_list) | --- +++ @@ -1,8 +1,33 @@+"""
+A recursive implementation of the insertion sort algorithm
+"""
from __future__ import annotations
def rec_insertion_sort(collection: list, n: int):
+ """
+ Given a collection of numbers and its length, sorts the collections
+ in ascending order
+
+ :param collection: A mutable collection of comparable elements
+ :param n: The length of collections
+
+ >>> col = [1, 2, 1]
+ >>> rec_insertion_sort(col, len(col))
+ >>> col
+ [1, 1, 2]
+
+ >>> col = [2, 1, 0, -1, -2]
+ >>> rec_insertion_sort(col, len(col))
+ >>> col
+ [-2, -1, 0, 1, 2]
+
+ >>> col = [1]
+ >>> rec_insertion_sort(col, len(col))
+ >>> col
+ [1]
+ """
# Checks if the entire collection has been sorted
if len(collection) <= 1 or n <= 1:
return
@@ -12,6 +37,24 @@
def insert_next(collection: list, index: int):
+ """
+ Inserts the '(index-1)th' element into place
+
+ >>> col = [3, 2, 4, 2]
+ >>> insert_next(col, 1)
+ >>> col
+ [2, 3, 4, 2]
+
+ >>> col = [3, 2, 3]
+ >>> insert_next(col, 2)
+ >>> col
+ [3, 2, 3]
+
+ >>> col = []
+ >>> insert_next(col, 1)
+ >>> col
+ []
+ """
# Checks order between adjacent elements
if index >= len(collection) or collection[index - 1] <= collection[index]:
return
@@ -29,4 +72,4 @@ numbers = input("Enter integers separated by spaces: ")
number_list: list[int] = [int(num) for num in numbers.split()]
rec_insertion_sort(number_list, len(number_list))
- print(number_list)+ print(number_list)
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/recursive_insertion_sort.py |
Add detailed documentation for each class |
def wiggle_sort(nums: list) -> list:
for i, _ in enumerate(nums):
if (i % 2 == 1) == (nums[i - 1] > nums[i]):
nums[i - 1], nums[i] = nums[i], nums[i - 1]
return nums
if __name__ == "__main__":
print("Enter the array elements:")
array = list(map(int, input().split()))
print("The unsorted array is:")
print(array)
print("Array after Wiggle sort:")
print(wiggle_sort(array)) | --- +++ @@ -1,6 +1,27 @@+"""
+Wiggle Sort.
+
+Given an unsorted array nums, reorder it such
+that nums[0] < nums[1] > nums[2] < nums[3]....
+For example:
+if input numbers = [3, 5, 2, 1, 6, 4]
+one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
+"""
def wiggle_sort(nums: list) -> list:
+ """
+ Python implementation of wiggle.
+ Example:
+ >>> wiggle_sort([0, 5, 3, 2, 2])
+ [0, 5, 2, 3, 2]
+ >>> wiggle_sort([])
+ []
+ >>> wiggle_sort([-2, -5, -45])
+ [-45, -2, -5]
+ >>> wiggle_sort([-2.1, -5.68, -45.11])
+ [-45.11, -2.1, -5.68]
+ """
for i, _ in enumerate(nums):
if (i % 2 == 1) == (nums[i - 1] > nums[i]):
nums[i - 1], nums[i] = nums[i], nums[i - 1]
@@ -14,4 +35,4 @@ print("The unsorted array is:")
print(array)
print("Array after Wiggle sort:")
- print(wiggle_sort(array))+ print(wiggle_sort(array))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/wiggle_sort.py |
Add documentation for all methods |
"""https://en.wikipedia.org/wiki/Merge_sort """
def merge(arr: list[int]) -> list[int]:
if len(arr) > 1:
middle_length = len(arr) // 2 # Finds the middle of the array
left_array = arr[
:middle_length
] # Creates an array of the elements in the first half.
right_array = arr[
middle_length:
] # Creates an array of the elements in the second half.
left_size = len(left_array)
right_size = len(right_array)
merge(left_array) # Starts sorting the left.
merge(right_array) # Starts sorting the right
left_index = 0 # Left Counter
right_index = 0 # Right Counter
index = 0 # Position Counter
while (
left_index < left_size and right_index < right_size
): # Runs until the lowers size of the left and right are sorted.
if left_array[left_index] < right_array[right_index]:
arr[index] = left_array[left_index]
left_index += 1
else:
arr[index] = right_array[right_index]
right_index += 1
index += 1
while (
left_index < left_size
): # Adds the left over elements in the left half of the array
arr[index] = left_array[left_index]
left_index += 1
index += 1
while (
right_index < right_size
): # Adds the left over elements in the right half of the array
arr[index] = right_array[right_index]
right_index += 1
index += 1
return arr
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,8 +1,23 @@+"""A merge sort which accepts an array as input and recursively
+splits an array in half and sorts and combines them.
+"""
"""https://en.wikipedia.org/wiki/Merge_sort """
def merge(arr: list[int]) -> list[int]:
+ """Return a sorted array.
+ >>> merge([10,9,8,7,6,5,4,3,2,1])
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+ >>> merge([1,2,3,4,5,6,7,8,9,10])
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+ >>> merge([10,22,1,2,3,9,15,23])
+ [1, 2, 3, 9, 10, 15, 22, 23]
+ >>> merge([100])
+ [100]
+ >>> merge([])
+ []
+ """
if len(arr) > 1:
middle_length = len(arr) // 2 # Finds the middle of the array
left_array = arr[
@@ -46,4 +61,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/recursive_mergesort_array.py |
Document classes and their methods |
def stalin_sort(sequence: list[int]) -> list[int]:
result = [sequence[0]]
for element in sequence[1:]:
if element >= result[-1]:
result.append(element)
return result
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,6 +1,38 @@+"""
+Stalin Sort algorithm: Removes elements that are out of order.
+Elements that are not greater than or equal to the previous element are discarded.
+Reference: https://medium.com/@kaweendra/the-ultimate-sorting-algorithm-6513d6968420
+"""
def stalin_sort(sequence: list[int]) -> list[int]:
+ """
+ Sorts a list using the Stalin sort algorithm.
+
+ >>> stalin_sort([4, 3, 5, 2, 1, 7])
+ [4, 5, 7]
+
+ >>> stalin_sort([1, 2, 3, 4])
+ [1, 2, 3, 4]
+
+ >>> stalin_sort([4, 5, 5, 2, 3])
+ [4, 5, 5]
+
+ >>> stalin_sort([6, 11, 12, 4, 1, 5])
+ [6, 11, 12]
+
+ >>> stalin_sort([5, 0, 4, 3])
+ [5]
+
+ >>> stalin_sort([5, 4, 3, 2, 1])
+ [5]
+
+ >>> stalin_sort([1, 2, 3, 4, 5])
+ [1, 2, 3, 4, 5]
+
+ >>> stalin_sort([1, 2, 8, 7, 6])
+ [1, 2, 8]
+ """
result = [sequence[0]]
for element in sequence[1:]:
if element >= result[-1]:
@@ -12,4 +44,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/stalin_sort.py |
Add docstrings for production code |
def merge_sort(collection):
start, end = [], []
while len(collection) > 1:
min_one, max_one = min(collection), max(collection)
start.append(min_one)
end.append(max_one)
collection.remove(min_one)
collection.remove(max_one)
end.reverse()
return start + collection + end
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(*merge_sort(unsorted), sep=",") | --- +++ @@ -1,6 +1,28 @@+"""
+Python implementation of a sort algorithm.
+Best Case Scenario : O(n)
+Worst Case Scenario : O(n^2) because native Python functions:min, max and remove are
+already O(n)
+"""
def merge_sort(collection):
+ """Pure implementation of the fastest merge sort algorithm in Python
+
+ :param collection: some mutable ordered collection with heterogeneous
+ comparable items inside
+ :return: a collection ordered by ascending
+
+ Examples:
+ >>> merge_sort([0, 5, 3, 2, 2])
+ [0, 2, 2, 3, 5]
+
+ >>> merge_sort([])
+ []
+
+ >>> merge_sort([-2, -5, -45])
+ [-45, -5, -2]
+ """
start, end = [], []
while len(collection) > 1:
min_one, max_one = min(collection), max(collection)
@@ -15,4 +37,4 @@ if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
- print(*merge_sort(unsorted), sep=",")+ print(*merge_sort(unsorted), sep=",")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/unknown_sort.py |
Generate consistent docstrings | from __future__ import annotations
import collections
import pprint
from pathlib import Path
def signature(word: str) -> str:
frequencies = collections.Counter(word)
return "".join(
f"{char}{frequency}" for char, frequency in sorted(frequencies.items())
)
def anagram(my_word: str) -> list[str]:
return word_by_signature[signature(my_word)]
data: str = Path(__file__).parent.joinpath("words.txt").read_text(encoding="utf-8")
word_list = sorted({word.strip().lower() for word in data.splitlines()})
word_by_signature = collections.defaultdict(list)
for word in word_list:
word_by_signature[signature(word)].append(word)
if __name__ == "__main__":
all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1}
with open("anagrams.txt", "w") as file:
file.write("all_anagrams = \n")
file.write(pprint.pformat(all_anagrams)) | --- +++ @@ -6,6 +6,16 @@
def signature(word: str) -> str:
+ """
+ Return a word's frequency-based signature.
+
+ >>> signature("test")
+ 'e1s1t2'
+ >>> signature("this is a test")
+ ' 3a1e1h1i2s3t3'
+ >>> signature("finaltest")
+ 'a1e1f1i1l1n1s1t2'
+ """
frequencies = collections.Counter(word)
return "".join(
f"{char}{frequency}" for char, frequency in sorted(frequencies.items())
@@ -13,6 +23,16 @@
def anagram(my_word: str) -> list[str]:
+ """
+ Return every anagram of the given word from the dictionary.
+
+ >>> anagram('test')
+ ['sett', 'stet', 'test']
+ >>> anagram('this is a test')
+ []
+ >>> anagram('final')
+ ['final']
+ """
return word_by_signature[signature(my_word)]
@@ -28,4 +48,4 @@
with open("anagrams.txt", "w") as file:
file.write("all_anagrams = \n")
- file.write(pprint.pformat(all_anagrams))+ file.write(pprint.pformat(all_anagrams))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/anagrams.py |
Add detailed documentation for each class |
from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def __iter__(self) -> Iterator[int]:
if self.left:
yield from self.left
yield self.val
if self.right:
yield from self.right
def __len__(self) -> int:
return sum(1 for _ in self)
def insert(self, val: int) -> None:
if val < self.val:
if self.left is None:
self.left = Node(val)
else:
self.left.insert(val)
elif val > self.val:
if self.right is None:
self.right = Node(val)
else:
self.right.insert(val)
def tree_sort(arr: list[int]) -> tuple[int, ...]:
if len(arr) == 0:
return tuple(arr)
root = Node(arr[0])
for item in arr[1:]:
root.insert(item)
return tuple(root)
if __name__ == "__main__":
import doctest
doctest.testmod()
print(f"{tree_sort([5, 6, 1, -1, 4, 37, -3, 7]) = }") | --- +++ @@ -1,3 +1,8 @@+"""
+Tree_sort algorithm.
+
+Build a Binary Search Tree and then iterate thru it to get a sorted list.
+"""
from __future__ import annotations
@@ -35,6 +40,23 @@
def tree_sort(arr: list[int]) -> tuple[int, ...]:
+ """
+ >>> tree_sort([])
+ ()
+ >>> tree_sort((1,))
+ (1,)
+ >>> tree_sort((1, 2))
+ (1, 2)
+ >>> tree_sort([5, 2, 7])
+ (2, 5, 7)
+ >>> tree_sort((5, -4, 9, 2, 7))
+ (-4, 2, 5, 7, 9)
+ >>> tree_sort([5, 6, 1, -1, 4, 37, 2, 7])
+ (-1, 1, 2, 4, 5, 6, 7, 37)
+
+ # >>> tree_sort(range(10, -10, -1)) == tuple(sorted(range(10, -10, -1)))
+ # True
+ """
if len(arr) == 0:
return tuple(arr)
root = Node(arr[0])
@@ -47,4 +69,4 @@ import doctest
doctest.testmod()
- print(f"{tree_sort([5, 6, 1, -1, 4, 37, -3, 7]) = }")+ print(f"{tree_sort([5, 6, 1, -1, 4, 37, -3, 7]) = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/tree_sort.py |
Can you add docstrings to this Python file? |
class BoyerMooreSearch:
def __init__(self, text: str, pattern: str):
self.text, self.pattern = text, pattern
self.textLen, self.patLen = len(text), len(pattern)
def match_in_pattern(self, char: str) -> int:
for i in range(self.patLen - 1, -1, -1):
if char == self.pattern[i]:
return i
return -1
def mismatch_in_text(self, current_pos: int) -> int:
for i in range(self.patLen - 1, -1, -1):
if self.pattern[i] != self.text[current_pos + i]:
return current_pos + i
return -1
def bad_character_heuristic(self) -> list[int]:
positions = []
for i in range(self.textLen - self.patLen + 1):
mismatch_index = self.mismatch_in_text(i)
if mismatch_index == -1:
positions.append(i)
else:
match_index = self.match_in_pattern(self.text[mismatch_index])
i = (
mismatch_index - match_index
) # shifting index lgtm [py/multiple-definition]
return positions
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,12 +1,53 @@+"""
+The algorithm finds the pattern in given text using following rule.
+
+The bad-character rule considers the mismatched character in Text.
+The next occurrence of that character to the left in Pattern is found,
+
+If the mismatched character occurs to the left in Pattern,
+a shift is proposed that aligns text block and pattern.
+
+If the mismatched character does not occur to the left in Pattern,
+a shift is proposed that moves the entirety of Pattern past
+the point of mismatch in the text.
+
+If there is no mismatch then the pattern matches with text block.
+
+Time Complexity : O(n/m)
+ n=length of main string
+ m=length of pattern string
+"""
class BoyerMooreSearch:
+ """
+ Example usage:
+
+ bms = BoyerMooreSearch(text="ABAABA", pattern="AB")
+ positions = bms.bad_character_heuristic()
+
+ where 'positions' contain the locations where the pattern was matched.
+ """
def __init__(self, text: str, pattern: str):
self.text, self.pattern = text, pattern
self.textLen, self.patLen = len(text), len(pattern)
def match_in_pattern(self, char: str) -> int:
+ """
+ Finds the index of char in pattern in reverse order.
+
+ Parameters :
+ char (chr): character to be searched
+
+ Returns :
+ i (int): index of char from last in pattern
+ -1 (int): if char is not found in pattern
+
+ >>> bms = BoyerMooreSearch(text="ABAABA", pattern="AB")
+ >>> bms.match_in_pattern("B")
+ 1
+ """
for i in range(self.patLen - 1, -1, -1):
if char == self.pattern[i]:
@@ -14,6 +55,21 @@ return -1
def mismatch_in_text(self, current_pos: int) -> int:
+ """
+ Find the index of mis-matched character in text when compared with pattern
+ from last.
+
+ Parameters :
+ current_pos (int): current index position of text
+
+ Returns :
+ i (int): index of mismatched char from last in text
+ -1 (int): if there is no mismatch between pattern and text block
+
+ >>> bms = BoyerMooreSearch(text="ABAABA", pattern="AB")
+ >>> bms.mismatch_in_text(2)
+ 3
+ """
for i in range(self.patLen - 1, -1, -1):
if self.pattern[i] != self.text[current_pos + i]:
@@ -21,6 +77,13 @@ return -1
def bad_character_heuristic(self) -> list[int]:
+ """
+ Finds the positions of the pattern location.
+
+ >>> bms = BoyerMooreSearch(text="ABAABA", pattern="AB")
+ >>> bms.bad_character_heuristic()
+ [0, 3]
+ """
positions = []
for i in range(self.textLen - self.patLen + 1):
@@ -38,4 +101,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/boyer_moore_search.py |
Add docstrings that explain purpose and usage |
from __future__ import annotations
from random import randrange
def quick_sort(collection: list) -> list:
# Base case: if the collection has 0 or 1 elements, it is already sorted
if len(collection) < 2:
return collection
# Randomly select a pivot index and remove the pivot element from the collection
pivot_index = randrange(len(collection))
pivot = collection.pop(pivot_index)
# Partition the remaining elements into two groups: lesser or equal, and greater
lesser = [item for item in collection if item <= pivot]
greater = [item for item in collection if item > pivot]
# Recursively sort the lesser and greater groups, and combine with the pivot
return [*quick_sort(lesser), pivot, *quick_sort(greater)]
if __name__ == "__main__":
# Get user input and convert it into a list of integers
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
# Print the result of sorting the user-provided list
print(quick_sort(unsorted)) | --- +++ @@ -1,3 +1,12 @@+"""
+A pure Python implementation of the quick sort algorithm
+
+For doctests run following command:
+python3 -m doctest -v quick_sort.py
+
+For manual testing run:
+python3 quick_sort.py
+"""
from __future__ import annotations
@@ -5,6 +14,19 @@
def quick_sort(collection: list) -> list:
+ """A pure Python implementation of quicksort algorithm.
+
+ :param collection: a mutable collection of comparable items
+ :return: the same collection ordered in ascending order
+
+ Examples:
+ >>> quick_sort([0, 5, 3, 2, 2])
+ [0, 2, 2, 3, 5]
+ >>> quick_sort([])
+ []
+ >>> quick_sort([-2, 5, 0, -45])
+ [-45, -2, 0, 5]
+ """
# Base case: if the collection has 0 or 1 elements, it is already sorted
if len(collection) < 2:
return collection
@@ -27,4 +49,4 @@ unsorted = [int(item) for item in user_input.split(",")]
# Print the result of sorting the user-provided list
- print(quick_sort(unsorted))+ print(quick_sort(unsorted))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/quick_sort.py |
Add docstrings to my Python code |
def get_check_digit(barcode: int) -> int:
barcode //= 10 # exclude the last digit
checker = False
s = 0
# extract and check each digit
while barcode != 0:
mult = 1 if checker else 3
s += mult * (barcode % 10)
barcode //= 10
checker = not checker
return (10 - (s % 10)) % 10
def is_valid(barcode: int) -> bool:
return len(str(barcode)) == 13 and get_check_digit(barcode) == barcode % 10
def get_barcode(barcode: str) -> int:
if str(barcode).isalpha():
msg = f"Barcode '{barcode}' has alphabetic characters."
raise ValueError(msg)
elif int(barcode) < 0:
raise ValueError("The entered barcode has a negative value. Try again.")
else:
return int(barcode)
if __name__ == "__main__":
import doctest
doctest.testmod()
"""
Enter a barcode.
"""
barcode = get_barcode(input("Barcode: ").strip())
if is_valid(barcode):
print(f"'{barcode}' is a valid barcode.")
else:
print(f"'{barcode}' is NOT a valid barcode.") | --- +++ @@ -1,6 +1,23 @@+"""
+https://en.wikipedia.org/wiki/Check_digit#Algorithms
+"""
def get_check_digit(barcode: int) -> int:
+ """
+ Returns the last digit of barcode by excluding the last digit first
+ and then computing to reach the actual last digit from the remaining
+ 12 digits.
+
+ >>> get_check_digit(8718452538119)
+ 9
+ >>> get_check_digit(87184523)
+ 5
+ >>> get_check_digit(87193425381086)
+ 9
+ >>> [get_check_digit(x) for x in range(0, 100, 10)]
+ [0, 7, 4, 1, 8, 5, 2, 9, 6, 3]
+ """
barcode //= 10 # exclude the last digit
checker = False
s = 0
@@ -16,10 +33,37 @@
def is_valid(barcode: int) -> bool:
+ """
+ Checks for length of barcode and last-digit
+ Returns boolean value of validity of barcode
+
+ >>> is_valid(8718452538119)
+ True
+ >>> is_valid(87184525)
+ False
+ >>> is_valid(87193425381089)
+ False
+ >>> is_valid(0)
+ False
+ >>> is_valid(dwefgiweuf)
+ Traceback (most recent call last):
+ ...
+ NameError: name 'dwefgiweuf' is not defined
+ """
return len(str(barcode)) == 13 and get_check_digit(barcode) == barcode % 10
def get_barcode(barcode: str) -> int:
+ """
+ Returns the barcode as an integer
+
+ >>> get_barcode("8718452538119")
+ 8718452538119
+ >>> get_barcode("dwefgiweuf")
+ Traceback (most recent call last):
+ ...
+ ValueError: Barcode 'dwefgiweuf' has alphabetic characters.
+ """
if str(barcode).isalpha():
msg = f"Barcode '{barcode}' has alphabetic characters."
raise ValueError(msg)
@@ -42,4 +86,4 @@ if is_valid(barcode):
print(f"'{barcode}' is a valid barcode.")
else:
- print(f"'{barcode}' is NOT a valid barcode.")+ print(f"'{barcode}' is NOT a valid barcode.")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/barcode_validator.py |
Add documentation for all methods |
def damerau_levenshtein_distance(first_string: str, second_string: str) -> int:
# Create a dynamic programming matrix to store the distances
dp_matrix = [[0] * (len(second_string) + 1) for _ in range(len(first_string) + 1)]
# Initialize the matrix
for i in range(len(first_string) + 1):
dp_matrix[i][0] = i
for j in range(len(second_string) + 1):
dp_matrix[0][j] = j
# Fill the matrix
for i, first_char in enumerate(first_string, start=1):
for j, second_char in enumerate(second_string, start=1):
cost = int(first_char != second_char)
dp_matrix[i][j] = min(
dp_matrix[i - 1][j] + 1, # Deletion
dp_matrix[i][j - 1] + 1, # Insertion
dp_matrix[i - 1][j - 1] + cost, # Substitution
)
if (
i > 1
and j > 1
and first_string[i - 1] == second_string[j - 2]
and first_string[i - 2] == second_string[j - 1]
):
# Transposition
dp_matrix[i][j] = min(dp_matrix[i][j], dp_matrix[i - 2][j - 2] + cost)
return dp_matrix[-1][-1]
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,6 +1,38 @@+"""
+This script is a implementation of the Damerau-Levenshtein distance algorithm.
+
+It's an algorithm that measures the edit distance between two string sequences
+
+More information about this algorithm can be found in this wikipedia article:
+https://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance
+"""
def damerau_levenshtein_distance(first_string: str, second_string: str) -> int:
+ """
+ Implements the Damerau-Levenshtein distance algorithm that measures
+ the edit distance between two strings.
+
+ Parameters:
+ first_string: The first string to compare
+ second_string: The second string to compare
+
+ Returns:
+ distance: The edit distance between the first and second strings
+
+ >>> damerau_levenshtein_distance("cat", "cut")
+ 1
+ >>> damerau_levenshtein_distance("kitten", "sitting")
+ 3
+ >>> damerau_levenshtein_distance("hello", "world")
+ 4
+ >>> damerau_levenshtein_distance("book", "back")
+ 2
+ >>> damerau_levenshtein_distance("container", "containment")
+ 3
+ >>> damerau_levenshtein_distance("container", "containment")
+ 3
+ """
# Create a dynamic programming matrix to store the distances
dp_matrix = [[0] * (len(second_string) + 1) for _ in range(len(first_string) + 1)]
@@ -36,4 +68,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/damerau_levenshtein_distance.py |
Provide clean and structured docstrings |
def is_pangram(
input_str: str = "The quick brown fox jumps over the lazy dog",
) -> bool:
# Declare frequency as a set to have unique occurrences of letters
frequency = set()
# Replace all the whitespace in our sentence
input_str = input_str.replace(" ", "")
for alpha in input_str:
if "a" <= alpha.lower() <= "z":
frequency.add(alpha.lower())
return len(frequency) == 26
def is_pangram_faster(
input_str: str = "The quick brown fox jumps over the lazy dog",
) -> bool:
flag = [False] * 26
for char in input_str:
if char.islower():
flag[ord(char) - 97] = True
elif char.isupper():
flag[ord(char) - 65] = True
return all(flag)
def is_pangram_fastest(
input_str: str = "The quick brown fox jumps over the lazy dog",
) -> bool:
return len({char for char in input_str.lower() if char.isalpha()}) == 26
def benchmark() -> None:
from timeit import timeit
setup = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest"
print(timeit("is_pangram()", setup=setup))
print(timeit("is_pangram_faster()", setup=setup))
print(timeit("is_pangram_fastest()", setup=setup))
# 5.348480500048026, 2.6477354579837993, 1.8470395830227062
# 5.036091582966037, 2.644472333951853, 1.8869528750656173
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark() | --- +++ @@ -1,8 +1,26 @@+"""
+wiki: https://en.wikipedia.org/wiki/Pangram
+"""
def is_pangram(
input_str: str = "The quick brown fox jumps over the lazy dog",
) -> bool:
+ """
+ A Pangram String contains all the alphabets at least once.
+ >>> is_pangram("The quick brown fox jumps over the lazy dog")
+ True
+ >>> is_pangram("Waltz, bad nymph, for quick jigs vex.")
+ True
+ >>> is_pangram("Jived fox nymph grabs quick waltz.")
+ True
+ >>> is_pangram("My name is Unknown")
+ False
+ >>> is_pangram("The quick brown fox jumps over the la_y dog")
+ False
+ >>> is_pangram()
+ True
+ """
# Declare frequency as a set to have unique occurrences of letters
frequency = set()
@@ -17,6 +35,18 @@ def is_pangram_faster(
input_str: str = "The quick brown fox jumps over the lazy dog",
) -> bool:
+ """
+ >>> is_pangram_faster("The quick brown fox jumps over the lazy dog")
+ True
+ >>> is_pangram_faster("Waltz, bad nymph, for quick jigs vex.")
+ True
+ >>> is_pangram_faster("Jived fox nymph grabs quick waltz.")
+ True
+ >>> is_pangram_faster("The quick brown fox jumps over the la_y dog")
+ False
+ >>> is_pangram_faster()
+ True
+ """
flag = [False] * 26
for char in input_str:
if char.islower():
@@ -29,10 +59,25 @@ def is_pangram_fastest(
input_str: str = "The quick brown fox jumps over the lazy dog",
) -> bool:
+ """
+ >>> is_pangram_fastest("The quick brown fox jumps over the lazy dog")
+ True
+ >>> is_pangram_fastest("Waltz, bad nymph, for quick jigs vex.")
+ True
+ >>> is_pangram_fastest("Jived fox nymph grabs quick waltz.")
+ True
+ >>> is_pangram_fastest("The quick brown fox jumps over the la_y dog")
+ False
+ >>> is_pangram_fastest()
+ True
+ """
return len({char for char in input_str.lower() if char.isalpha()}) == 26
def benchmark() -> None:
+ """
+ Benchmark code comparing different version.
+ """
from timeit import timeit
setup = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest"
@@ -47,4 +92,4 @@ import doctest
doctest.testmod()
- benchmark()+ benchmark()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/is_pangram.py |
Improve documentation using docstrings |
def validate_initial_digits(credit_card_number: str) -> bool:
return credit_card_number.startswith(("34", "35", "37", "4", "5", "6"))
def luhn_validation(credit_card_number: str) -> bool:
cc_number = credit_card_number
total = 0
half_len = len(cc_number) - 2
for i in range(half_len, -1, -2):
# double the value of every second digit
digit = int(cc_number[i])
digit *= 2
# If doubling of a number results in a two digit number
# i.e greater than 9(e.g., 6 x 2 = 12),
# then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6),
# to get a single digit number.
if digit > 9:
digit %= 10
digit += 1
cc_number = cc_number[:i] + str(digit) + cc_number[i + 1 :]
total += digit
# Sum up the remaining digits
for i in range(len(cc_number) - 1, -1, -2):
total += int(cc_number[i])
return total % 10 == 0
def validate_credit_card_number(credit_card_number: str) -> bool:
error_message = f"{credit_card_number} is an invalid credit card number because"
if not credit_card_number.isdigit():
print(f"{error_message} it has nonnumerical characters.")
return False
if not 13 <= len(credit_card_number) <= 16:
print(f"{error_message} of its length.")
return False
if not validate_initial_digits(credit_card_number):
print(f"{error_message} of its first two digits.")
return False
if not luhn_validation(credit_card_number):
print(f"{error_message} it fails the Luhn check.")
return False
print(f"{credit_card_number} is a valid credit card number.")
return True
if __name__ == "__main__":
import doctest
doctest.testmod()
validate_credit_card_number("4111111111111111")
validate_credit_card_number("32323") | --- +++ @@ -1,10 +1,33 @@+"""
+Functions for testing the validity of credit card numbers.
+
+https://en.wikipedia.org/wiki/Luhn_algorithm
+"""
def validate_initial_digits(credit_card_number: str) -> bool:
+ """
+ Function to validate initial digits of a given credit card number.
+ >>> valid = "4111111111111111 41111111111111 34 35 37 412345 523456 634567"
+ >>> all(validate_initial_digits(cc) for cc in valid.split())
+ True
+ >>> invalid = "14 25 76 32323 36111111111111"
+ >>> all(validate_initial_digits(cc) is False for cc in invalid.split())
+ True
+ """
return credit_card_number.startswith(("34", "35", "37", "4", "5", "6"))
def luhn_validation(credit_card_number: str) -> bool:
+ """
+ Function to luhn algorithm validation for a given credit card number.
+ >>> luhn_validation('4111111111111111')
+ True
+ >>> luhn_validation('36111111111111')
+ True
+ >>> luhn_validation('41111111111111')
+ False
+ """
cc_number = credit_card_number
total = 0
half_len = len(cc_number) - 2
@@ -30,6 +53,27 @@
def validate_credit_card_number(credit_card_number: str) -> bool:
+ """
+ Function to validate the given credit card number.
+ >>> validate_credit_card_number('4111111111111111')
+ 4111111111111111 is a valid credit card number.
+ True
+ >>> validate_credit_card_number('helloworld$')
+ helloworld$ is an invalid credit card number because it has nonnumerical characters.
+ False
+ >>> validate_credit_card_number('32323')
+ 32323 is an invalid credit card number because of its length.
+ False
+ >>> validate_credit_card_number('32323323233232332323')
+ 32323323233232332323 is an invalid credit card number because of its length.
+ False
+ >>> validate_credit_card_number('36111111111111')
+ 36111111111111 is an invalid credit card number because of its first two digits.
+ False
+ >>> validate_credit_card_number('41111111111111')
+ 41111111111111 is an invalid credit card number because it fails the Luhn check.
+ False
+ """
error_message = f"{credit_card_number} is an invalid credit card number because"
if not credit_card_number.isdigit():
print(f"{error_message} it has nonnumerical characters.")
@@ -56,4 +100,4 @@
doctest.testmod()
validate_credit_card_number("4111111111111111")
- validate_credit_card_number("32323")+ validate_credit_card_number("32323")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/credit_card_validator.py |
Add docstrings with type hints explained | # Frequency Finder
import string
# frequency taken from https://en.wikipedia.org/wiki/Letter_frequency
english_letter_freq = {
"E": 12.70,
"T": 9.06,
"A": 8.17,
"O": 7.51,
"I": 6.97,
"N": 6.75,
"S": 6.33,
"H": 6.09,
"R": 5.99,
"D": 4.25,
"L": 4.03,
"C": 2.78,
"U": 2.76,
"M": 2.41,
"W": 2.36,
"F": 2.23,
"G": 2.02,
"Y": 1.97,
"P": 1.93,
"B": 1.29,
"V": 0.98,
"K": 0.77,
"J": 0.15,
"X": 0.15,
"Q": 0.10,
"Z": 0.07,
}
ETAOIN = "ETAOINSHRDLCUMWFGYPBVKJXQZ"
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def get_letter_count(message: str) -> dict[str, int]:
letter_count = dict.fromkeys(string.ascii_uppercase, 0)
for letter in message.upper():
if letter in LETTERS:
letter_count[letter] += 1
return letter_count
def get_item_at_index_zero(x: tuple) -> str:
return x[0]
def get_frequency_order(message: str) -> str:
letter_to_freq = get_letter_count(message)
freq_to_letter: dict[int, list[str]] = {
freq: [] for letter, freq in letter_to_freq.items()
}
for letter in LETTERS:
freq_to_letter[letter_to_freq[letter]].append(letter)
freq_to_letter_str: dict[int, str] = {}
for freq in freq_to_letter: # noqa: PLC0206
freq_to_letter[freq].sort(key=ETAOIN.find, reverse=True)
freq_to_letter_str[freq] = "".join(freq_to_letter[freq])
freq_pairs = list(freq_to_letter_str.items())
freq_pairs.sort(key=get_item_at_index_zero, reverse=True)
freq_order: list[str] = [freq_pair[1] for freq_pair in freq_pairs]
return "".join(freq_order)
def english_freq_match_score(message: str) -> int:
freq_order = get_frequency_order(message)
match_score = 0
for common_letter in ETAOIN[:6]:
if common_letter in freq_order[:6]:
match_score += 1
for uncommon_letter in ETAOIN[-6:]:
if uncommon_letter in freq_order[-6:]:
match_score += 1
return match_score
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -49,6 +49,15 @@
def get_frequency_order(message: str) -> str:
+ """
+ Get the frequency order of the letters in the given string
+ >>> get_frequency_order('Hello World')
+ 'LOWDRHEZQXJKVBPYGFMUCSNIAT'
+ >>> get_frequency_order('Hello@')
+ 'LHOEZQXJKVBPYGFWMUCDRSNIAT'
+ >>> get_frequency_order('h')
+ 'HZQXJKVBPYGFWMUCLDRSNIOATE'
+ """
letter_to_freq = get_letter_count(message)
freq_to_letter: dict[int, list[str]] = {
freq: [] for letter, freq in letter_to_freq.items()
@@ -71,6 +80,10 @@
def english_freq_match_score(message: str) -> int:
+ """
+ >>> english_freq_match_score('Hello World')
+ 1
+ """
freq_order = get_frequency_order(message)
match_score = 0
for common_letter in ETAOIN[:6]:
@@ -87,4 +100,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/frequency_finder.py |
Add docstrings to make code maintainable | # Created by susmith98
from collections import Counter
from timeit import timeit
# Problem Description:
# Check if characters of the given string can be rearranged to form a palindrome.
# Counter is faster for long strings and non-Counter is faster for short strings.
def can_string_be_rearranged_as_palindrome_counter(
input_str: str = "",
) -> bool:
return sum(c % 2 for c in Counter(input_str.replace(" ", "").lower()).values()) < 2
def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool:
if len(input_str) == 0:
return True
lower_case_input_str = input_str.replace(" ", "").lower()
# character_freq_dict: Stores the frequency of every character in the input string
character_freq_dict: dict[str, int] = {}
for character in lower_case_input_str:
character_freq_dict[character] = character_freq_dict.get(character, 0) + 1
"""
Above line of code is equivalent to:
1) Getting the frequency of current character till previous index
>>> character_freq = character_freq_dict.get(character, 0)
2) Incrementing the frequency of current character by 1
>>> character_freq = character_freq + 1
3) Updating the frequency of current character
>>> character_freq_dict[character] = character_freq
"""
"""
OBSERVATIONS:
Even length palindrome
-> Every character appears even no.of times.
Odd length palindrome
-> Every character appears even no.of times except for one character.
LOGIC:
Step 1: We'll count number of characters that appear odd number of times i.e oddChar
Step 2:If we find more than 1 character that appears odd number of times,
It is not possible to rearrange as a palindrome
"""
odd_char = 0
for character_count in character_freq_dict.values():
if character_count % 2:
odd_char += 1
return not odd_char > 1
def benchmark(input_str: str = "") -> None:
print("\nFor string = ", input_str, ":")
print(
"> can_string_be_rearranged_as_palindrome_counter()",
"\tans =",
can_string_be_rearranged_as_palindrome_counter(input_str),
"\ttime =",
timeit(
"z.can_string_be_rearranged_as_palindrome_counter(z.check_str)",
setup="import __main__ as z",
),
"seconds",
)
print(
"> can_string_be_rearranged_as_palindrome()",
"\tans =",
can_string_be_rearranged_as_palindrome(input_str),
"\ttime =",
timeit(
"z.can_string_be_rearranged_as_palindrome(z.check_str)",
setup="import __main__ as z",
),
"seconds",
)
if __name__ == "__main__":
check_str = input(
"Enter string to determine if it can be rearranged as a palindrome or not: "
).strip()
benchmark(check_str)
status = can_string_be_rearranged_as_palindrome_counter(check_str)
print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome") | --- +++ @@ -11,10 +11,34 @@ def can_string_be_rearranged_as_palindrome_counter(
input_str: str = "",
) -> bool:
+ """
+ A Palindrome is a String that reads the same forward as it does backwards.
+ Examples of Palindromes mom, dad, malayalam
+ >>> can_string_be_rearranged_as_palindrome_counter("Momo")
+ True
+ >>> can_string_be_rearranged_as_palindrome_counter("Mother")
+ False
+ >>> can_string_be_rearranged_as_palindrome_counter("Father")
+ False
+ >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama")
+ True
+ """
return sum(c % 2 for c in Counter(input_str.replace(" ", "").lower()).values()) < 2
def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool:
+ """
+ A Palindrome is a String that reads the same forward as it does backwards.
+ Examples of Palindromes mom, dad, malayalam
+ >>> can_string_be_rearranged_as_palindrome("Momo")
+ True
+ >>> can_string_be_rearranged_as_palindrome("Mother")
+ False
+ >>> can_string_be_rearranged_as_palindrome("Father")
+ False
+ >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama")
+ True
+ """
if len(input_str) == 0:
return True
lower_case_input_str = input_str.replace(" ", "").lower()
@@ -52,6 +76,9 @@
def benchmark(input_str: str = "") -> None:
+ """
+ Benchmark code for comparing above 2 functions
+ """
print("\nFor string = ", input_str, ":")
print(
"> can_string_be_rearranged_as_palindrome_counter()",
@@ -83,4 +110,4 @@ ).strip()
benchmark(check_str)
status = can_string_be_rearranged_as_palindrome_counter(check_str)
- print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")+ print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/can_string_be_rearranged_as_palindrome.py |
Add docstrings to improve readability | import os
from string import ascii_letters
LETTERS_AND_SPACE = ascii_letters + " \t\n"
def load_dictionary() -> dict[str, None]:
path = os.path.split(os.path.realpath(__file__))
english_words: dict[str, None] = {}
with open(path[0] + "/dictionary.txt") as dictionary_file:
for word in dictionary_file.read().split("\n"):
english_words[word] = None
return english_words
ENGLISH_WORDS = load_dictionary()
def get_english_count(message: str) -> float:
message = message.upper()
message = remove_non_letters(message)
possible_words = message.split()
matches = len([word for word in possible_words if word in ENGLISH_WORDS])
return float(matches) / len(possible_words)
def remove_non_letters(message: str) -> str:
return "".join(symbol for symbol in message if symbol in LETTERS_AND_SPACE)
def is_english(
message: str, word_percentage: int = 20, letter_percentage: int = 85
) -> bool:
words_match = get_english_count(message) * 100 >= word_percentage
num_letters = len(remove_non_letters(message))
message_letters_percentage = (float(num_letters) / len(message)) * 100
letters_match = message_letters_percentage >= letter_percentage
return words_match and letters_match
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -25,12 +25,30 @@
def remove_non_letters(message: str) -> str:
+ """
+ >>> remove_non_letters("Hi! how are you?")
+ 'Hi how are you'
+ >>> remove_non_letters("P^y%t)h@o*n")
+ 'Python'
+ >>> remove_non_letters("1+1=2")
+ ''
+ >>> remove_non_letters("www.google.com/")
+ 'wwwgooglecom'
+ >>> remove_non_letters("")
+ ''
+ """
return "".join(symbol for symbol in message if symbol in LETTERS_AND_SPACE)
def is_english(
message: str, word_percentage: int = 20, letter_percentage: int = 85
) -> bool:
+ """
+ >>> is_english('Hello World')
+ True
+ >>> is_english('llold HorWd')
+ False
+ """
words_match = get_english_count(message) * 100 >= word_percentage
num_letters = len(remove_non_letters(message))
message_letters_percentage = (float(num_letters) / len(message)) * 100
@@ -41,4 +59,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/detecting_english_programmatically.py |
Add docstrings to incomplete code |
def bitap_string_match(text: str, pattern: str) -> int:
if not pattern:
return 0
m = len(pattern)
if m > len(text):
return -1
# Initial state of bit string 1110
state = ~1
# Bit = 0 if character appears at index, and 1 otherwise
pattern_mask: list[int] = [~0] * 27 # 1111
for i, char in enumerate(pattern):
# For the pattern mask for this character, set the bit to 0 for each i
# the character appears.
pattern_index: int = ord(char) - ord("a")
pattern_mask[pattern_index] &= ~(1 << i)
for i, char in enumerate(text):
text_index = ord(char) - ord("a")
# If this character does not appear in pattern, it's pattern mask is 1111.
# Performing a bitwise OR between state and 1111 will reset the state to 1111
# and start searching the start of pattern again.
state |= pattern_mask[text_index]
state <<= 1
# If the mth bit (counting right to left) of the state is 0, then we have
# found pattern in text
if (state & (1 << m)) == 0:
return i - m + 1
return -1
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,6 +1,45 @@+"""
+Bitap exact string matching
+https://en.wikipedia.org/wiki/Bitap_algorithm
+
+Searches for a pattern inside text, and returns the index of the first occurrence
+of the pattern. Both text and pattern consist of lowercase alphabetical characters only.
+
+Complexity: O(m*n)
+ n = length of text
+ m = length of pattern
+
+Python doctests can be run using this command:
+python3 -m doctest -v bitap_string_match.py
+"""
def bitap_string_match(text: str, pattern: str) -> int:
+ """
+ Retrieves the index of the first occurrence of pattern in text.
+
+ Args:
+ text: A string consisting only of lowercase alphabetical characters.
+ pattern: A string consisting only of lowercase alphabetical characters.
+
+ Returns:
+ int: The index where pattern first occurs. Return -1 if not found.
+
+ >>> bitap_string_match('abdabababc', 'ababc')
+ 5
+ >>> bitap_string_match('aaaaaaaaaaaaaaaaaa', 'a')
+ 0
+ >>> bitap_string_match('zxywsijdfosdfnso', 'zxywsijdfosdfnso')
+ 0
+ >>> bitap_string_match('abdabababc', '')
+ 0
+ >>> bitap_string_match('abdabababc', 'c')
+ 9
+ >>> bitap_string_match('abdabababc', 'fofosdfo')
+ -1
+ >>> bitap_string_match('abdab', 'fofosdfo')
+ -1
+ """
if not pattern:
return 0
m = len(pattern)
@@ -37,4 +76,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/bitap_string_match.py |
Add docstrings to clarify complex logic |
def is_isogram(string: str) -> bool:
if not all(x.isalpha() for x in string):
raise ValueError("String must only contain alphabetic characters.")
letters = sorted(string.lower())
return len(letters) == len(set(letters))
if __name__ == "__main__":
input_str = input("Enter a string ").strip()
isogram = is_isogram(input_str)
print(f"{input_str} is {'an' if isogram else 'not an'} isogram.") | --- +++ @@ -1,6 +1,21 @@+"""
+wiki: https://en.wikipedia.org/wiki/Heterogram_(literature)#Isograms
+"""
def is_isogram(string: str) -> bool:
+ """
+ An isogram is a word in which no letter is repeated.
+ Examples of isograms are uncopyrightable and ambidextrously.
+ >>> is_isogram('Uncopyrightable')
+ True
+ >>> is_isogram('allowance')
+ False
+ >>> is_isogram('copy1')
+ Traceback (most recent call last):
+ ...
+ ValueError: String must only contain alphabetic characters.
+ """
if not all(x.isalpha() for x in string):
raise ValueError("String must only contain alphabetic characters.")
@@ -12,4 +27,4 @@ input_str = input("Enter a string ").strip()
isogram = is_isogram(input_str)
- print(f"{input_str} is {'an' if isogram else 'not an'} isogram.")+ print(f"{input_str} is {'an' if isogram else 'not an'} isogram.")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/is_isogram.py |
Provide docstrings following PEP 257 |
from collections import defaultdict
def check_anagrams(first_str: str, second_str: str) -> bool:
first_str = first_str.lower().strip()
second_str = second_str.lower().strip()
# Remove whitespace
first_str = first_str.replace(" ", "")
second_str = second_str.replace(" ", "")
# Strings of different lengths are not anagrams
if len(first_str) != len(second_str):
return False
# Default values for count should be 0
count: defaultdict[str, int] = defaultdict(int)
# For each character in input strings,
# increment count in the corresponding
for i in range(len(first_str)):
count[first_str[i]] += 1
count[second_str[i]] -= 1
return all(_count == 0 for _count in count.values())
if __name__ == "__main__":
from doctest import testmod
testmod()
input_a = input("Enter the first string ").strip()
input_b = input("Enter the second string ").strip()
status = check_anagrams(input_a, input_b)
print(f"{input_a} and {input_b} are {'' if status else 'not '}anagrams.") | --- +++ @@ -1,37 +1,52 @@-
-from collections import defaultdict
-
-
-def check_anagrams(first_str: str, second_str: str) -> bool:
- first_str = first_str.lower().strip()
- second_str = second_str.lower().strip()
-
- # Remove whitespace
- first_str = first_str.replace(" ", "")
- second_str = second_str.replace(" ", "")
-
- # Strings of different lengths are not anagrams
- if len(first_str) != len(second_str):
- return False
-
- # Default values for count should be 0
- count: defaultdict[str, int] = defaultdict(int)
-
- # For each character in input strings,
- # increment count in the corresponding
- for i in range(len(first_str)):
- count[first_str[i]] += 1
- count[second_str[i]] -= 1
-
- return all(_count == 0 for _count in count.values())
-
-
-if __name__ == "__main__":
- from doctest import testmod
-
- testmod()
- input_a = input("Enter the first string ").strip()
- input_b = input("Enter the second string ").strip()
-
- status = check_anagrams(input_a, input_b)
- print(f"{input_a} and {input_b} are {'' if status else 'not '}anagrams.")+"""
+wiki: https://en.wikipedia.org/wiki/Anagram
+"""
+
+from collections import defaultdict
+
+
+def check_anagrams(first_str: str, second_str: str) -> bool:
+ """
+ Two strings are anagrams if they are made up of the same letters but are
+ arranged differently (ignoring the case).
+ >>> check_anagrams('Silent', 'Listen')
+ True
+ >>> check_anagrams('This is a string', 'Is this a string')
+ True
+ >>> check_anagrams('This is a string', 'Is this a string')
+ True
+ >>> check_anagrams('There', 'Their')
+ False
+ """
+ first_str = first_str.lower().strip()
+ second_str = second_str.lower().strip()
+
+ # Remove whitespace
+ first_str = first_str.replace(" ", "")
+ second_str = second_str.replace(" ", "")
+
+ # Strings of different lengths are not anagrams
+ if len(first_str) != len(second_str):
+ return False
+
+ # Default values for count should be 0
+ count: defaultdict[str, int] = defaultdict(int)
+
+ # For each character in input strings,
+ # increment count in the corresponding
+ for i in range(len(first_str)):
+ count[first_str[i]] += 1
+ count[second_str[i]] -= 1
+
+ return all(_count == 0 for _count in count.values())
+
+
+if __name__ == "__main__":
+ from doctest import testmod
+
+ testmod()
+ input_a = input("Enter the first string ").strip()
+ input_b = input("Enter the second string ").strip()
+
+ status = check_anagrams(input_a, input_b)
+ print(f"{input_a} and {input_b} are {'' if status else 'not '}anagrams.")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/check_anagrams.py |
Generate missing documentation strings |
def jaro_winkler(str1: str, str2: str) -> float:
def get_matched_characters(_str1: str, _str2: str) -> str:
matched = []
limit = min(len(_str1), len(_str2)) // 2
for i, char in enumerate(_str1):
left = int(max(0, i - limit))
right = int(min(i + limit + 1, len(_str2)))
if char in _str2[left:right]:
matched.append(char)
_str2 = (
f"{_str2[0 : _str2.index(char)]} {_str2[_str2.index(char) + 1 :]}"
)
return "".join(matched)
# matching characters
matching_1 = get_matched_characters(str1, str2)
matching_2 = get_matched_characters(str2, str1)
match_count = len(matching_1)
# transposition
transpositions = (
len([(c1, c2) for c1, c2 in zip(matching_1, matching_2) if c1 != c2]) // 2
)
if not match_count:
jaro = 0.0
else:
jaro = (
1
/ 3
* (
match_count / len(str1)
+ match_count / len(str2)
+ (match_count - transpositions) / match_count
)
)
# common prefix up to 4 characters
prefix_len = 0
for c1, c2 in zip(str1[:4], str2[:4]):
if c1 == c2:
prefix_len += 1
else:
break
return jaro + 0.1 * prefix_len * (1 - jaro)
if __name__ == "__main__":
import doctest
doctest.testmod()
print(jaro_winkler("hello", "world")) | --- +++ @@ -1,6 +1,29 @@+"""https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance"""
def jaro_winkler(str1: str, str2: str) -> float:
+ """
+ Jaro-Winkler distance is a string metric measuring an edit distance between two
+ sequences.
+ Output value is between 0.0 and 1.0.
+
+ >>> jaro_winkler("martha", "marhta")
+ 0.9611111111111111
+ >>> jaro_winkler("CRATE", "TRACE")
+ 0.7333333333333334
+ >>> jaro_winkler("test", "dbdbdbdb")
+ 0.0
+ >>> jaro_winkler("test", "test")
+ 1.0
+ >>> jaro_winkler("hello world", "HeLLo W0rlD")
+ 0.6363636363636364
+ >>> jaro_winkler("test", "")
+ 0.0
+ >>> jaro_winkler("hello", "world")
+ 0.4666666666666666
+ >>> jaro_winkler("hell**o", "*world")
+ 0.4365079365079365
+ """
def get_matched_characters(_str1: str, _str2: str) -> str:
matched = []
@@ -54,4 +77,4 @@ import doctest
doctest.testmod()
- print(jaro_winkler("hello", "world"))+ print(jaro_winkler("hello", "world"))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/jaro_winkler.py |
Fully document this Python code with docstrings | from typing import Any
def bubble_sort_iterative(collection: list[Any]) -> list[Any]:
length = len(collection)
for i in reversed(range(length)):
swapped = False
for j in range(i):
if collection[j] > collection[j + 1]:
swapped = True
collection[j], collection[j + 1] = collection[j + 1], collection[j]
if not swapped:
break # Stop iteration if the collection is sorted.
return collection
def bubble_sort_recursive(collection: list[Any]) -> list[Any]:
length = len(collection)
swapped = False
for i in range(length - 1):
if collection[i] > collection[i + 1]:
collection[i], collection[i + 1] = collection[i + 1], collection[i]
swapped = True
return collection if not swapped else bubble_sort_recursive(collection)
if __name__ == "__main__":
import doctest
from random import sample
from timeit import timeit
doctest.testmod()
# Benchmark: Iterative seems slightly faster than recursive.
num_runs = 10_000
unsorted = sample(range(-50, 50), 100)
timer_iterative = timeit(
"bubble_sort_iterative(unsorted[:])", globals=globals(), number=num_runs
)
print("\nIterative bubble sort:")
print(*bubble_sort_iterative(unsorted), sep=",")
print(f"Processing time (iterative): {timer_iterative:.5f}s for {num_runs:,} runs")
unsorted = sample(range(-50, 50), 100)
timer_recursive = timeit(
"bubble_sort_recursive(unsorted[:])", globals=globals(), number=num_runs
)
print("\nRecursive bubble sort:")
print(*bubble_sort_recursive(unsorted), sep=",")
print(f"Processing time (recursive): {timer_recursive:.5f}s for {num_runs:,} runs") | --- +++ @@ -2,6 +2,52 @@
def bubble_sort_iterative(collection: list[Any]) -> list[Any]:
+ """Pure implementation of bubble sort algorithm in Python
+
+ :param collection: some mutable ordered collection with heterogeneous
+ comparable items inside
+ :return: the same collection ordered in ascending order
+
+ Examples:
+ >>> bubble_sort_iterative([0, 5, 2, 3, 2])
+ [0, 2, 2, 3, 5]
+ >>> bubble_sort_iterative([])
+ []
+ >>> bubble_sort_iterative([-2, -45, -5])
+ [-45, -5, -2]
+ >>> bubble_sort_iterative([-23, 0, 6, -4, 34])
+ [-23, -4, 0, 6, 34]
+ >>> bubble_sort_iterative([1, 2, 3, 4])
+ [1, 2, 3, 4]
+ >>> bubble_sort_iterative([3, 3, 3, 3])
+ [3, 3, 3, 3]
+ >>> bubble_sort_iterative([56])
+ [56]
+ >>> bubble_sort_iterative([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2])
+ True
+ >>> bubble_sort_iterative([]) == sorted([])
+ True
+ >>> bubble_sort_iterative([-2, -45, -5]) == sorted([-2, -45, -5])
+ True
+ >>> bubble_sort_iterative([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34])
+ True
+ >>> bubble_sort_iterative(['d', 'a', 'b', 'e']) == sorted(['d', 'a', 'b', 'e'])
+ True
+ >>> bubble_sort_iterative(['z', 'a', 'y', 'b', 'x', 'c'])
+ ['a', 'b', 'c', 'x', 'y', 'z']
+ >>> bubble_sort_iterative([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6])
+ [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7]
+ >>> bubble_sort_iterative([1, 3.3, 5, 7.7, 2, 4.4, 6])
+ [1, 2, 3.3, 4.4, 5, 6, 7.7]
+ >>> import random
+ >>> collection_arg = random.sample(range(-50, 50), 100)
+ >>> bubble_sort_iterative(collection_arg) == sorted(collection_arg)
+ True
+ >>> import string
+ >>> collection_arg = random.choices(string.ascii_letters + string.digits, k=100)
+ >>> bubble_sort_iterative(collection_arg) == sorted(collection_arg)
+ True
+ """
length = len(collection)
for i in reversed(range(length)):
swapped = False
@@ -15,6 +61,47 @@
def bubble_sort_recursive(collection: list[Any]) -> list[Any]:
+ """It is similar iterative bubble sort but recursive.
+
+ :param collection: mutable ordered sequence of elements
+ :return: the same list in ascending order
+
+ Examples:
+ >>> bubble_sort_recursive([0, 5, 2, 3, 2])
+ [0, 2, 2, 3, 5]
+ >>> bubble_sort_recursive([])
+ []
+ >>> bubble_sort_recursive([-2, -45, -5])
+ [-45, -5, -2]
+ >>> bubble_sort_recursive([-23, 0, 6, -4, 34])
+ [-23, -4, 0, 6, 34]
+ >>> bubble_sort_recursive([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2])
+ True
+ >>> bubble_sort_recursive([]) == sorted([])
+ True
+ >>> bubble_sort_recursive([-2, -45, -5]) == sorted([-2, -45, -5])
+ True
+ >>> bubble_sort_recursive([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34])
+ True
+ >>> bubble_sort_recursive(['d', 'a', 'b', 'e']) == sorted(['d', 'a', 'b', 'e'])
+ True
+ >>> bubble_sort_recursive(['z', 'a', 'y', 'b', 'x', 'c'])
+ ['a', 'b', 'c', 'x', 'y', 'z']
+ >>> bubble_sort_recursive([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6])
+ [1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7]
+ >>> bubble_sort_recursive([1, 3.3, 5, 7.7, 2, 4.4, 6])
+ [1, 2, 3.3, 4.4, 5, 6, 7.7]
+ >>> bubble_sort_recursive(['a', 'Z', 'B', 'C', 'A', 'c'])
+ ['A', 'B', 'C', 'Z', 'a', 'c']
+ >>> import random
+ >>> collection_arg = random.sample(range(-50, 50), 100)
+ >>> bubble_sort_recursive(collection_arg) == sorted(collection_arg)
+ True
+ >>> import string
+ >>> collection_arg = random.choices(string.ascii_letters + string.digits, k=100)
+ >>> bubble_sort_recursive(collection_arg) == sorted(collection_arg)
+ True
+ """
length = len(collection)
swapped = False
for i in range(length - 1):
@@ -48,4 +135,4 @@ )
print("\nRecursive bubble sort:")
print(*bubble_sort_recursive(unsorted), sep=",")
- print(f"Processing time (recursive): {timer_recursive:.5f}s for {num_runs:,} runs")+ print(f"Processing time (recursive): {timer_recursive:.5f}s for {num_runs:,} runs")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/bubble_sort.py |
Document this script properly | from __future__ import annotations
def knuth_morris_pratt(text: str, pattern: str) -> int:
# 1) Construct the failure array
failure = get_failure_array(pattern)
# 2) Step through text searching for pattern
i, j = 0, 0 # index into text, pattern
while i < len(text):
if pattern[j] == text[i]:
if j == (len(pattern) - 1):
return i - j
j += 1
# if this is a prefix in our pattern
# just go back far enough to continue
elif j > 0:
j = failure[j - 1]
continue
i += 1
return -1
def get_failure_array(pattern: str) -> list[int]:
failure = [0]
i = 0
j = 1
while j < len(pattern):
if pattern[i] == pattern[j]:
i += 1
elif i > 0:
i = failure[i - 1]
continue
j += 1
failure.append(i)
return failure
if __name__ == "__main__":
import doctest
doctest.testmod()
# Test 1)
pattern = "abc1abc12"
text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc"
text2 = "alskfjaldsk23adsfabcabc"
assert knuth_morris_pratt(text1, pattern)
assert knuth_morris_pratt(text2, pattern)
# Test 2)
pattern = "ABABX"
text = "ABABZABABYABABX"
assert knuth_morris_pratt(text, pattern)
# Test 3)
pattern = "AAAB"
text = "ABAAAAAB"
assert knuth_morris_pratt(text, pattern)
# Test 4)
pattern = "abcdabcy"
text = "abcxabcdabxabcdabcdabcy"
assert knuth_morris_pratt(text, pattern)
# Test 5) -> Doctests
kmp = "knuth_morris_pratt"
assert all(
knuth_morris_pratt(kmp, s) == kmp.find(s)
for s in ("kn", "h_m", "rr", "tt", "not there")
)
# Test 6)
pattern = "aabaabaaa"
assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2] | --- +++ @@ -2,6 +2,25 @@
def knuth_morris_pratt(text: str, pattern: str) -> int:
+ """
+ The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text
+ with complexity O(n + m)
+
+ 1) Preprocess pattern to identify any suffixes that are identical to prefixes
+
+ This tells us where to continue from if we get a mismatch between a character
+ in our pattern and the text.
+
+ 2) Step through the text one character at a time and compare it to a character in
+ the pattern updating our location within the pattern if necessary
+
+ >>> kmp = "knuth_morris_pratt"
+ >>> all(
+ ... knuth_morris_pratt(kmp, s) == kmp.find(s)
+ ... for s in ("kn", "h_m", "rr", "tt", "not there")
+ ... )
+ True
+ """
# 1) Construct the failure array
failure = get_failure_array(pattern)
@@ -24,6 +43,11 @@
def get_failure_array(pattern: str) -> list[int]:
+ """
+ Calculates the new index we should go to if we fail a comparison
+ :param pattern:
+ :return:
+ """
failure = [0]
i = 0
j = 1
@@ -74,4 +98,4 @@
# Test 6)
pattern = "aabaabaaa"
- assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]+ assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/knuth_morris_pratt.py |
Write reusable docstrings | from collections.abc import Callable
def levenshtein_distance(first_word: str, second_word: str) -> int:
# The longer word should come first
if len(first_word) < len(second_word):
return levenshtein_distance(second_word, first_word)
if len(second_word) == 0:
return len(first_word)
previous_row = list(range(len(second_word) + 1))
for i, c1 in enumerate(first_word):
current_row = [i + 1]
for j, c2 in enumerate(second_word):
# Calculate insertions, deletions, and substitutions
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (c1 != c2)
# Get the minimum to append to the current row
current_row.append(min(insertions, deletions, substitutions))
# Store the previous row
previous_row = current_row
# Returns the last element (distance)
return previous_row[-1]
def levenshtein_distance_optimized(first_word: str, second_word: str) -> int:
if len(first_word) < len(second_word):
return levenshtein_distance_optimized(second_word, first_word)
if len(second_word) == 0:
return len(first_word)
previous_row = list(range(len(second_word) + 1))
for i, c1 in enumerate(first_word):
current_row = [i + 1] + [0] * len(second_word)
for j, c2 in enumerate(second_word):
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (c1 != c2)
current_row[j + 1] = min(insertions, deletions, substitutions)
previous_row = current_row
return previous_row[-1]
def benchmark_levenshtein_distance(func: Callable) -> None:
from timeit import timeit
stmt = f"{func.__name__}('sitting', 'kitten')"
setup = f"from __main__ import {func.__name__}"
number = 25_000
result = timeit(stmt=stmt, setup=setup, number=number)
print(f"{func.__name__:<30} finished {number:,} runs in {result:.5f} seconds")
if __name__ == "__main__":
# Get user input for words
first_word = input("Enter the first word for Levenshtein distance:\n").strip()
second_word = input("Enter the second word for Levenshtein distance:\n").strip()
# Calculate and print Levenshtein distances
print(f"{levenshtein_distance(first_word, second_word) = }")
print(f"{levenshtein_distance_optimized(first_word, second_word) = }")
# Benchmark the Levenshtein distance functions
benchmark_levenshtein_distance(levenshtein_distance)
benchmark_levenshtein_distance(levenshtein_distance_optimized) | --- +++ @@ -2,6 +2,27 @@
def levenshtein_distance(first_word: str, second_word: str) -> int:
+ """
+ Implementation of the Levenshtein distance in Python.
+ :param first_word: the first word to measure the difference.
+ :param second_word: the second word to measure the difference.
+ :return: the levenshtein distance between the two words.
+ Examples:
+ >>> levenshtein_distance("planet", "planetary")
+ 3
+ >>> levenshtein_distance("", "test")
+ 4
+ >>> levenshtein_distance("book", "back")
+ 2
+ >>> levenshtein_distance("book", "book")
+ 0
+ >>> levenshtein_distance("test", "")
+ 4
+ >>> levenshtein_distance("", "")
+ 0
+ >>> levenshtein_distance("orchestration", "container")
+ 10
+ """
# The longer word should come first
if len(first_word) < len(second_word):
return levenshtein_distance(second_word, first_word)
@@ -31,6 +52,28 @@
def levenshtein_distance_optimized(first_word: str, second_word: str) -> int:
+ """
+ Compute the Levenshtein distance between two words (strings).
+ The function is optimized for efficiency by modifying rows in place.
+ :param first_word: the first word to measure the difference.
+ :param second_word: the second word to measure the difference.
+ :return: the Levenshtein distance between the two words.
+ Examples:
+ >>> levenshtein_distance_optimized("planet", "planetary")
+ 3
+ >>> levenshtein_distance_optimized("", "test")
+ 4
+ >>> levenshtein_distance_optimized("book", "back")
+ 2
+ >>> levenshtein_distance_optimized("book", "book")
+ 0
+ >>> levenshtein_distance_optimized("test", "")
+ 4
+ >>> levenshtein_distance_optimized("", "")
+ 0
+ >>> levenshtein_distance_optimized("orchestration", "container")
+ 10
+ """
if len(first_word) < len(second_word):
return levenshtein_distance_optimized(second_word, first_word)
@@ -54,6 +97,11 @@
def benchmark_levenshtein_distance(func: Callable) -> None:
+ """
+ Benchmark the Levenshtein distance function.
+ :param str: The name of the function being benchmarked.
+ :param func: The function to be benchmarked.
+ """
from timeit import timeit
stmt = f"{func.__name__}('sitting', 'kitten')"
@@ -74,4 +122,4 @@
# Benchmark the Levenshtein distance functions
benchmark_levenshtein_distance(levenshtein_distance)
- benchmark_levenshtein_distance(levenshtein_distance_optimized)+ benchmark_levenshtein_distance(levenshtein_distance_optimized)
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/levenshtein_distance.py |
Write docstrings describing functionality |
def create_ngram(sentence: str, ngram_size: int) -> list[str]:
return [sentence[i : i + ngram_size] for i in range(len(sentence) - ngram_size + 1)]
if __name__ == "__main__":
from doctest import testmod
testmod() | --- +++ @@ -1,10 +1,23 @@+"""
+https://en.wikipedia.org/wiki/N-gram
+"""
def create_ngram(sentence: str, ngram_size: int) -> list[str]:
+ """
+ Create ngrams from a sentence
+
+ >>> create_ngram("I am a sentence", 2)
+ ['I ', ' a', 'am', 'm ', ' a', 'a ', ' s', 'se', 'en', 'nt', 'te', 'en', 'nc', 'ce']
+ >>> create_ngram("I am an NLPer", 2)
+ ['I ', ' a', 'am', 'm ', ' a', 'an', 'n ', ' N', 'NL', 'LP', 'Pe', 'er']
+ >>> create_ngram("This is short", 50)
+ []
+ """
return [sentence[i : i + ngram_size] for i in range(len(sentence) - ngram_size + 1)]
if __name__ == "__main__":
from doctest import testmod
- testmod()+ testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/ngram.py |
Document all endpoints with docstrings |
def compute_transform_tables(
source_string: str,
destination_string: str,
copy_cost: int,
replace_cost: int,
delete_cost: int,
insert_cost: int,
) -> tuple[list[list[int]], list[list[str]]]:
source_seq = list(source_string)
destination_seq = list(destination_string)
len_source_seq = len(source_seq)
len_destination_seq = len(destination_seq)
costs = [
[0 for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1)
]
ops = [
["0" for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1)
]
for i in range(1, len_source_seq + 1):
costs[i][0] = i * delete_cost
ops[i][0] = f"D{source_seq[i - 1]}"
for i in range(1, len_destination_seq + 1):
costs[0][i] = i * insert_cost
ops[0][i] = f"I{destination_seq[i - 1]}"
for i in range(1, len_source_seq + 1):
for j in range(1, len_destination_seq + 1):
if source_seq[i - 1] == destination_seq[j - 1]:
costs[i][j] = costs[i - 1][j - 1] + copy_cost
ops[i][j] = f"C{source_seq[i - 1]}"
else:
costs[i][j] = costs[i - 1][j - 1] + replace_cost
ops[i][j] = f"R{source_seq[i - 1]}" + str(destination_seq[j - 1])
if costs[i - 1][j] + delete_cost < costs[i][j]:
costs[i][j] = costs[i - 1][j] + delete_cost
ops[i][j] = f"D{source_seq[i - 1]}"
if costs[i][j - 1] + insert_cost < costs[i][j]:
costs[i][j] = costs[i][j - 1] + insert_cost
ops[i][j] = f"I{destination_seq[j - 1]}"
return costs, ops
def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]:
if i == 0 and j == 0:
return []
elif ops[i][j][0] in {"C", "R"}:
seq = assemble_transformation(ops, i - 1, j - 1)
seq.append(ops[i][j])
return seq
elif ops[i][j][0] == "D":
seq = assemble_transformation(ops, i - 1, j)
seq.append(ops[i][j])
return seq
else:
seq = assemble_transformation(ops, i, j - 1)
seq.append(ops[i][j])
return seq
if __name__ == "__main__":
_, operations = compute_transform_tables("Python", "Algorithms", -1, 1, 2, 2)
m = len(operations)
n = len(operations[0])
sequence = assemble_transformation(operations, m - 1, n - 1)
string = list("Python")
i = 0
cost = 0
with open("min_cost.txt", "w") as file:
for op in sequence:
print("".join(string))
if op[0] == "C":
file.write("%-16s" % "Copy %c" % op[1]) # noqa: UP031
file.write("\t\t\t" + "".join(string))
file.write("\r\n")
cost -= 1
elif op[0] == "R":
string[i] = op[2]
file.write("%-16s" % ("Replace %c" % op[1] + " with " + str(op[2]))) # noqa: UP031
file.write("\t\t" + "".join(string))
file.write("\r\n")
cost += 1
elif op[0] == "D":
string.pop(i)
file.write("%-16s" % "Delete %c" % op[1]) # noqa: UP031
file.write("\t\t\t" + "".join(string))
file.write("\r\n")
cost += 2
else:
string.insert(i, op[1])
file.write("%-16s" % "Insert %c" % op[1]) # noqa: UP031
file.write("\t\t\t" + "".join(string))
file.write("\r\n")
cost += 2
i += 1
print("".join(string))
print("Cost: ", cost)
file.write("\r\nMinimum cost: " + str(cost)) | --- +++ @@ -1,3 +1,12 @@+"""
+Algorithm for calculating the most cost-efficient sequence for converting one string
+into another.
+The only allowed operations are
+--- Cost to copy a character is copy_cost
+--- Cost to replace a character is replace_cost
+--- Cost to delete a character is delete_cost
+--- Cost to insert a character is insert_cost
+"""
def compute_transform_tables(
@@ -8,6 +17,23 @@ delete_cost: int,
insert_cost: int,
) -> tuple[list[list[int]], list[list[str]]]:
+ """
+ Finds the most cost efficient sequence
+ for converting one string into another.
+
+ >>> costs, operations = compute_transform_tables("cat", "cut", 1, 2, 3, 3)
+ >>> costs[0][:4]
+ [0, 3, 6, 9]
+ >>> costs[2][:4]
+ [6, 4, 3, 6]
+ >>> operations[0][:4]
+ ['0', 'Ic', 'Iu', 'It']
+ >>> operations[3][:4]
+ ['Dt', 'Dt', 'Rtu', 'Ct']
+
+ >>> compute_transform_tables("", "", 1, 2, 3, 3)
+ ([[0]], [['0']])
+ """
source_seq = list(source_string)
destination_seq = list(destination_string)
len_source_seq = len(source_seq)
@@ -48,6 +74,32 @@
def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]:
+ """
+ Assembles the transformations based on the ops table.
+
+ >>> ops = [['0', 'Ic', 'Iu', 'It'],
+ ... ['Dc', 'Cc', 'Iu', 'It'],
+ ... ['Da', 'Da', 'Rau', 'Rat'],
+ ... ['Dt', 'Dt', 'Rtu', 'Ct']]
+ >>> x = len(ops) - 1
+ >>> y = len(ops[0]) - 1
+ >>> assemble_transformation(ops, x, y)
+ ['Cc', 'Rau', 'Ct']
+
+ >>> ops1 = [['0']]
+ >>> x1 = len(ops1) - 1
+ >>> y1 = len(ops1[0]) - 1
+ >>> assemble_transformation(ops1, x1, y1)
+ []
+
+ >>> ops2 = [['0', 'I1', 'I2', 'I3'],
+ ... ['D1', 'C1', 'I2', 'I3'],
+ ... ['D2', 'D2', 'R23', 'R23']]
+ >>> x2 = len(ops2) - 1
+ >>> y2 = len(ops2[0]) - 1
+ >>> assemble_transformation(ops2, x2, y2)
+ ['C1', 'I2', 'R23']
+ """
if i == 0 and j == 0:
return []
elif ops[i][j][0] in {"C", "R"}:
@@ -115,4 +167,4 @@ print("".join(string))
print("Cost: ", cost)
- file.write("\r\nMinimum cost: " + str(cost))+ file.write("\r\nMinimum cost: " + str(cost))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/min_cost_string_conversion.py |
Write docstrings that follow conventions |
def circle_sort(collection: list) -> list:
if len(collection) < 2:
return collection
def circle_sort_util(collection: list, low: int, high: int) -> bool:
swapped = False
if low == high:
return swapped
left = low
right = high
while left < right:
if collection[left] > collection[right]:
collection[left], collection[right] = (
collection[right],
collection[left],
)
swapped = True
left += 1
right -= 1
if left == right and collection[left] > collection[right + 1]:
collection[left], collection[right + 1] = (
collection[right + 1],
collection[left],
)
swapped = True
mid = low + int((high - low) / 2)
left_swap = circle_sort_util(collection, low, mid)
right_swap = circle_sort_util(collection, mid + 1, high)
return swapped or left_swap or right_swap
is_not_sorted = True
while is_not_sorted is True:
is_not_sorted = circle_sort_util(collection, 0, len(collection) - 1)
return collection
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(circle_sort(unsorted)) | --- +++ @@ -1,11 +1,43 @@+"""
+This is a Python implementation of the circle sort algorithm
+
+For doctests run following command:
+python3 -m doctest -v circle_sort.py
+
+For manual testing run:
+python3 circle_sort.py
+"""
def circle_sort(collection: list) -> list:
+ """A pure Python implementation of circle sort algorithm
+
+ :param collection: a mutable collection of comparable items in any order
+ :return: the same collection in ascending order
+
+ Examples:
+ >>> circle_sort([0, 5, 3, 2, 2])
+ [0, 2, 2, 3, 5]
+ >>> circle_sort([])
+ []
+ >>> circle_sort([-2, 5, 0, -45])
+ [-45, -2, 0, 5]
+ >>> collections = ([], [0, 5, 3, 2, 2], [-2, 5, 0, -45])
+ >>> all(sorted(collection) == circle_sort(collection) for collection in collections)
+ True
+ """
if len(collection) < 2:
return collection
def circle_sort_util(collection: list, low: int, high: int) -> bool:
+ """
+ >>> arr = [5,4,3,2,1]
+ >>> circle_sort_util(lst, 0, 2)
+ True
+ >>> arr
+ [3, 4, 5, 2, 1]
+ """
swapped = False
@@ -51,4 +83,4 @@ if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
- print(circle_sort(unsorted))+ print(circle_sort(unsorted))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/circle_sort.py |
Provide clean and structured docstrings |
def join(separator: str, separated: list[str]) -> str:
# Check that all elements are strings
for word_or_phrase in separated:
# If the element is not a string, raise an exception
if not isinstance(word_or_phrase, str):
raise Exception("join() accepts only strings")
joined: str = ""
"""
The last element of the list is not followed by the separator.
So, we need to iterate through the list and join each element
with the separator except the last element.
"""
last_index: int = len(separated) - 1
"""
Iterate through the list and join each element with the separator.
Except the last element, all other elements are followed by the separator.
"""
for word_or_phrase in separated[:last_index]:
# join the element with the separator.
joined += word_or_phrase + separator
# If the list is not empty, join the last element.
if separated != []:
joined += separated[last_index]
# Return the joined string.
return joined
if __name__ == "__main__":
from doctest import testmod
testmod() | --- +++ @@ -1,6 +1,43 @@+"""
+Program to join a list of strings with a separator
+"""
def join(separator: str, separated: list[str]) -> str:
+ """
+ Joins a list of strings using a separator
+ and returns the result.
+
+ :param separator: Separator to be used
+ for joining the strings.
+ :param separated: List of strings to be joined.
+
+ :return: Joined string with the specified separator.
+
+ Examples:
+
+ >>> join("", ["a", "b", "c", "d"])
+ 'abcd'
+ >>> join("#", ["a", "b", "c", "d"])
+ 'a#b#c#d'
+ >>> join("#", "a")
+ 'a'
+ >>> join(" ", ["You", "are", "amazing!"])
+ 'You are amazing!'
+ >>> join(",", ["", "", ""])
+ ',,'
+
+ This example should raise an
+ exception for non-string elements:
+ >>> join("#", ["a", "b", "c", 1])
+ Traceback (most recent call last):
+ ...
+ Exception: join() accepts only strings
+
+ Additional test case with a different separator:
+ >>> join("-", ["apple", "banana", "cherry"])
+ 'apple-banana-cherry'
+ """
# Check that all elements are strings
for word_or_phrase in separated:
@@ -34,4 +71,4 @@ if __name__ == "__main__":
from doctest import testmod
- testmod()+ testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/join.py |
Document helper functions with docstrings |
from __future__ import annotations
def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) -> None:
if (direction == 1 and array[index1] > array[index2]) or (
direction == 0 and array[index1] < array[index2]
):
array[index1], array[index2] = array[index2], array[index1]
def bitonic_merge(array: list[int], low: int, length: int, direction: int) -> None:
if length > 1:
middle = int(length / 2)
for i in range(low, low + middle):
comp_and_swap(array, i, i + middle, direction)
bitonic_merge(array, low, middle, direction)
bitonic_merge(array, low + middle, middle, direction)
def bitonic_sort(array: list[int], low: int, length: int, direction: int) -> None:
if length > 1:
middle = int(length / 2)
bitonic_sort(array, low, middle, 1)
bitonic_sort(array, low + middle, middle, 0)
bitonic_merge(array, low, length, direction)
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item.strip()) for item in user_input.split(",")]
bitonic_sort(unsorted, 0, len(unsorted), 1)
print("\nSorted array in ascending order is: ", end="")
print(*unsorted, sep=", ")
bitonic_merge(unsorted, 0, len(unsorted), 0)
print("Sorted array in descending order is: ", end="")
print(*unsorted, sep=", ") | --- +++ @@ -1,8 +1,37 @@+"""
+Python program for Bitonic Sort.
+
+Note that this program works only when size of input is a power of 2.
+"""
from __future__ import annotations
def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) -> None:
+ """Compare the value at given index1 and index2 of the array and swap them as per
+ the given direction.
+
+ The parameter direction indicates the sorting direction, ASCENDING(1) or
+ DESCENDING(0); if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are
+ interchanged.
+
+ >>> arr = [12, 42, -21, 1]
+ >>> comp_and_swap(arr, 1, 2, 1)
+ >>> arr
+ [12, -21, 42, 1]
+
+ >>> comp_and_swap(arr, 1, 2, 0)
+ >>> arr
+ [12, 42, -21, 1]
+
+ >>> comp_and_swap(arr, 0, 3, 1)
+ >>> arr
+ [1, 42, -21, 12]
+
+ >>> comp_and_swap(arr, 0, 3, 0)
+ >>> arr
+ [12, 42, -21, 1]
+ """
if (direction == 1 and array[index1] > array[index2]) or (
direction == 0 and array[index1] < array[index2]
):
@@ -10,6 +39,21 @@
def bitonic_merge(array: list[int], low: int, length: int, direction: int) -> None:
+ """
+ It recursively sorts a bitonic sequence in ascending order, if direction = 1, and in
+ descending if direction = 0.
+ The sequence to be sorted starts at index position low, the parameter length is the
+ number of elements to be sorted.
+
+ >>> arr = [12, 42, -21, 1]
+ >>> bitonic_merge(arr, 0, 4, 1)
+ >>> arr
+ [-21, 1, 12, 42]
+
+ >>> bitonic_merge(arr, 0, 4, 0)
+ >>> arr
+ [42, 12, 1, -21]
+ """
if length > 1:
middle = int(length / 2)
for i in range(low, low + middle):
@@ -19,6 +63,20 @@
def bitonic_sort(array: list[int], low: int, length: int, direction: int) -> None:
+ """
+ This function first produces a bitonic sequence by recursively sorting its two
+ halves in opposite sorting orders, and then calls bitonic_merge to make them in the
+ same order.
+
+ >>> arr = [12, 34, 92, -23, 0, -121, -167, 145]
+ >>> bitonic_sort(arr, 0, 8, 1)
+ >>> arr
+ [-167, -121, -23, 0, 12, 34, 92, 145]
+
+ >>> bitonic_sort(arr, 0, 8, 0)
+ >>> arr
+ [145, 92, 34, 12, 0, -23, -121, -167]
+ """
if length > 1:
middle = int(length / 2)
bitonic_sort(array, low, middle, 1)
@@ -36,4 +94,4 @@
bitonic_merge(unsorted, 0, len(unsorted), 0)
print("Sorted array in descending order is: ", end="")
- print(*unsorted, sep=", ")+ print(*unsorted, sep=", ")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/bitonic_sort.py |
Generate docstrings for this script |
def gnome_sort(lst: list) -> list:
if len(lst) <= 1:
return lst
i = 1
while i < len(lst):
if lst[i - 1] <= lst[i]:
i += 1
else:
lst[i - 1], lst[i] = lst[i], lst[i - 1]
i -= 1
if i == 0:
i = 1
return lst
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(gnome_sort(unsorted)) | --- +++ @@ -1,6 +1,38 @@+"""
+Gnome Sort Algorithm (A.K.A. Stupid Sort)
+
+This algorithm iterates over a list comparing an element with the previous one.
+If order is not respected, it swaps element backward until order is respected with
+previous element. It resumes the initial iteration from element new position.
+
+For doctests run following command:
+python3 -m doctest -v gnome_sort.py
+
+For manual testing run:
+python3 gnome_sort.py
+"""
def gnome_sort(lst: list) -> list:
+ """
+ Pure implementation of the gnome sort algorithm in Python
+
+ Take some mutable ordered collection with heterogeneous comparable items inside as
+ arguments, return the same collection ordered by ascending.
+
+ Examples:
+ >>> gnome_sort([0, 5, 3, 2, 2])
+ [0, 2, 2, 3, 5]
+
+ >>> gnome_sort([])
+ []
+
+ >>> gnome_sort([-2, -5, -45])
+ [-45, -5, -2]
+
+ >>> "".join(gnome_sort(list(set("Gnomes are stupid!"))))
+ ' !Gadeimnoprstu'
+ """
if len(lst) <= 1:
return lst
@@ -21,4 +53,4 @@ if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
- print(gnome_sort(unsorted))+ print(gnome_sort(unsorted))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/gnome_sort.py |
Add docstrings for better understanding |
from collections import Counter
from functools import total_ordering
from data_structures.heap.heap import Heap
@total_ordering
class WordCount:
def __init__(self, word: str, count: int) -> None:
self.word = word
self.count = count
def __eq__(self, other: object) -> bool:
if not isinstance(other, WordCount):
return NotImplemented
return self.count == other.count
def __lt__(self, other: object) -> bool:
if not isinstance(other, WordCount):
return NotImplemented
return self.count < other.count
def top_k_frequent_words(words: list[str], k_value: int) -> list[str]:
heap: Heap[WordCount] = Heap()
count_by_word = Counter(words)
heap.build_max_heap(
[WordCount(word, count) for word, count in count_by_word.items()]
)
return [heap.extract_max().word for _ in range(min(k_value, len(count_by_word)))]
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,3 +1,17 @@+"""
+Finds the top K most frequent words from the provided word list.
+
+This implementation aims to show how to solve the problem using the Heap class
+already present in this repository.
+Computing order statistics is, in fact, a typical usage of heaps.
+
+This is mostly shown for educational purposes, since the problem can be solved
+in a few lines using collections.Counter from the Python standard library:
+
+from collections import Counter
+def top_k_frequent_words(words, k_value):
+ return [x[0] for x in Counter(words).most_common(k_value)]
+"""
from collections import Counter
from functools import total_ordering
@@ -12,17 +26,66 @@ self.count = count
def __eq__(self, other: object) -> bool:
+ """
+ >>> WordCount('a', 1).__eq__(WordCount('b', 1))
+ True
+ >>> WordCount('a', 1).__eq__(WordCount('a', 1))
+ True
+ >>> WordCount('a', 1).__eq__(WordCount('a', 2))
+ False
+ >>> WordCount('a', 1).__eq__(WordCount('b', 2))
+ False
+ >>> WordCount('a', 1).__eq__(1)
+ NotImplemented
+ """
if not isinstance(other, WordCount):
return NotImplemented
return self.count == other.count
def __lt__(self, other: object) -> bool:
+ """
+ >>> WordCount('a', 1).__lt__(WordCount('b', 1))
+ False
+ >>> WordCount('a', 1).__lt__(WordCount('a', 1))
+ False
+ >>> WordCount('a', 1).__lt__(WordCount('a', 2))
+ True
+ >>> WordCount('a', 1).__lt__(WordCount('b', 2))
+ True
+ >>> WordCount('a', 2).__lt__(WordCount('a', 1))
+ False
+ >>> WordCount('a', 2).__lt__(WordCount('b', 1))
+ False
+ >>> WordCount('a', 1).__lt__(1)
+ NotImplemented
+ """
if not isinstance(other, WordCount):
return NotImplemented
return self.count < other.count
def top_k_frequent_words(words: list[str], k_value: int) -> list[str]:
+ """
+ Returns the `k_value` most frequently occurring words,
+ in non-increasing order of occurrence.
+ In this context, a word is defined as an element in the provided list.
+
+ In case `k_value` is greater than the number of distinct words, a value of k equal
+ to the number of distinct words will be considered, instead.
+
+ >>> top_k_frequent_words(['a', 'b', 'c', 'a', 'c', 'c'], 3)
+ ['c', 'a', 'b']
+ >>> top_k_frequent_words(['a', 'b', 'c', 'a', 'c', 'c'], 2)
+ ['c', 'a']
+ >>> top_k_frequent_words(['a', 'b', 'c', 'a', 'c', 'c'], 1)
+ ['c']
+ >>> top_k_frequent_words(['a', 'b', 'c', 'a', 'c', 'c'], 0)
+ []
+ >>> top_k_frequent_words([], 1)
+ []
+ >>> top_k_frequent_words(['a', 'a'], 2)
+ ['a']
+ """
heap: Heap[WordCount] = Heap()
count_by_word = Counter(words)
heap.build_max_heap(
@@ -34,4 +97,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/top_k_frequent_words.py |
Create docstrings for all classes and functions |
def cocktail_shaker_sort(arr: list[int]) -> list[int]:
start, end = 0, len(arr) - 1
while start < end:
swapped = False
# Pass from left to right
for i in range(start, end):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
swapped = True
if not swapped:
break
end -= 1 # Decrease the end pointer after each pass
# Pass from right to left
for i in range(end, start, -1):
if arr[i] < arr[i - 1]:
arr[i], arr[i - 1] = arr[i - 1], arr[i]
swapped = True
if not swapped:
break
start += 1 # Increase the start pointer after each pass
return arr
if __name__ == "__main__":
import doctest
doctest.testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(f"{cocktail_shaker_sort(unsorted) = }") | --- +++ @@ -1,6 +1,34 @@+"""
+An implementation of the cocktail shaker sort algorithm in pure Python.
+
+https://en.wikipedia.org/wiki/Cocktail_shaker_sort
+"""
def cocktail_shaker_sort(arr: list[int]) -> list[int]:
+ """
+ Sorts a list using the Cocktail Shaker Sort algorithm.
+
+ :param arr: List of elements to be sorted.
+ :return: Sorted list.
+
+ >>> cocktail_shaker_sort([4, 5, 2, 1, 2])
+ [1, 2, 2, 4, 5]
+ >>> cocktail_shaker_sort([-4, 5, 0, 1, 2, 11])
+ [-4, 0, 1, 2, 5, 11]
+ >>> cocktail_shaker_sort([0.1, -2.4, 4.4, 2.2])
+ [-2.4, 0.1, 2.2, 4.4]
+ >>> cocktail_shaker_sort([1, 2, 3, 4, 5])
+ [1, 2, 3, 4, 5]
+ >>> cocktail_shaker_sort([-4, -5, -24, -7, -11])
+ [-24, -11, -7, -5, -4]
+ >>> cocktail_shaker_sort(["elderberry", "banana", "date", "apple", "cherry"])
+ ['apple', 'banana', 'cherry', 'date', 'elderberry']
+ >>> cocktail_shaker_sort((-4, -5, -24, -7, -11))
+ Traceback (most recent call last):
+ ...
+ TypeError: 'tuple' object does not support item assignment
+ """
start, end = 0, len(arr) - 1
while start < end:
@@ -37,4 +65,4 @@ doctest.testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
- print(f"{cocktail_shaker_sort(unsorted) = }")+ print(f"{cocktail_shaker_sort(unsorted) = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/cocktail_shaker_sort.py |
Generate NumPy-style docstrings |
def comb_sort(data: list) -> list:
shrink_factor = 1.3
gap = len(data)
completed = False
while not completed:
# Update the gap value for a next comb
gap = int(gap / shrink_factor)
if gap <= 1:
completed = True
index = 0
while index + gap < len(data):
if data[index] > data[index + gap]:
# Swap values
data[index], data[index + gap] = data[index + gap], data[index]
completed = False
index += 1
return data
if __name__ == "__main__":
import doctest
doctest.testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(comb_sort(unsorted)) | --- +++ @@ -1,6 +1,36 @@+"""
+This is pure Python implementation of comb sort algorithm.
+Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz
+Dobosiewicz in 1980. It was rediscovered by Stephen Lacey and Richard Box in 1991.
+Comb sort improves on bubble sort algorithm.
+In bubble sort, distance (or gap) between two compared elements is always one.
+Comb sort improvement is that gap can be much more than 1, in order to prevent slowing
+down by small values at the end of a list.
+
+More info on: https://en.wikipedia.org/wiki/Comb_sort
+
+For doctests run following command:
+python -m doctest -v comb_sort.py
+or
+python3 -m doctest -v comb_sort.py
+
+For manual testing run:
+python comb_sort.py
+"""
def comb_sort(data: list) -> list:
+ """Pure implementation of comb sort algorithm in Python
+ :param data: mutable collection with comparable items
+ :return: the same collection in ascending order
+ Examples:
+ >>> comb_sort([0, 5, 3, 2, 2])
+ [0, 2, 2, 3, 5]
+ >>> comb_sort([])
+ []
+ >>> comb_sort([99, 45, -7, 8, 2, 0, -15, 3])
+ [-15, -7, 0, 2, 3, 8, 45, 99]
+ """
shrink_factor = 1.3
gap = len(data)
completed = False
@@ -29,4 +59,4 @@
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
- print(comb_sort(unsorted))+ print(comb_sort(unsorted))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/comb_sort.py |
Add standardized docstrings across the file |
def counting_sort(collection):
# if the collection is empty, returns empty
if collection == []:
return []
# get some information about the collection
coll_len = len(collection)
coll_max = max(collection)
coll_min = min(collection)
# create the counting array
counting_arr_length = coll_max + 1 - coll_min
counting_arr = [0] * counting_arr_length
# count how much a number appears in the collection
for number in collection:
counting_arr[number - coll_min] += 1
# sum each position with it's predecessors. now, counting_arr[i] tells
# us how many elements <= i has in the collection
for i in range(1, counting_arr_length):
counting_arr[i] = counting_arr[i] + counting_arr[i - 1]
# create the output collection
ordered = [0] * coll_len
# place the elements in the output, respecting the original order (stable
# sort) from end to begin, updating counting_arr
for i in reversed(range(coll_len)):
ordered[counting_arr[collection[i] - coll_min] - 1] = collection[i]
counting_arr[collection[i] - coll_min] -= 1
return ordered
def counting_sort_string(string):
return "".join([chr(i) for i in counting_sort([ord(c) for c in string])])
if __name__ == "__main__":
# Test string sort
assert counting_sort_string("thisisthestring") == "eghhiiinrsssttt"
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(counting_sort(unsorted)) | --- +++ @@ -1,6 +1,27 @@+"""
+This is pure Python implementation of counting sort algorithm
+For doctests run following command:
+python -m doctest -v counting_sort.py
+or
+python3 -m doctest -v counting_sort.py
+For manual testing run:
+python counting_sort.py
+"""
def counting_sort(collection):
+ """Pure implementation of counting sort algorithm in Python
+ :param collection: some mutable ordered collection with heterogeneous
+ comparable items inside
+ :return: the same collection ordered by ascending
+ Examples:
+ >>> counting_sort([0, 5, 3, 2, 2])
+ [0, 2, 2, 3, 5]
+ >>> counting_sort([])
+ []
+ >>> counting_sort([-2, -5, -45])
+ [-45, -5, -2]
+ """
# if the collection is empty, returns empty
if collection == []:
return []
@@ -36,6 +57,10 @@
def counting_sort_string(string):
+ """
+ >>> counting_sort_string("thisisthestring")
+ 'eghhiiinrsssttt'
+ """
return "".join([chr(i) for i in counting_sort([ord(c) for c in string])])
@@ -45,4 +70,4 @@
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
- print(counting_sort(unsorted))+ print(counting_sort(unsorted))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/counting_sort.py |
Document all endpoints with docstrings |
import random
def bogo_sort(collection: list) -> list:
def is_sorted(collection: list) -> bool:
for i in range(len(collection) - 1):
if collection[i] > collection[i + 1]:
return False
return True
while not is_sorted(collection):
random.shuffle(collection)
return collection
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(bogo_sort(unsorted)) | --- +++ @@ -1,8 +1,34 @@+"""
+This is a pure Python implementation of the bogosort algorithm,
+also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort.
+Bogosort generates random permutations until it guesses the correct one.
+
+More info on: https://en.wikipedia.org/wiki/Bogosort
+
+For doctests run following command:
+python -m doctest -v bogo_sort.py
+or
+python3 -m doctest -v bogo_sort.py
+For manual testing run:
+python bogo_sort.py
+"""
import random
def bogo_sort(collection: list) -> list:
+ """Pure implementation of the bogosort algorithm in Python
+ :param collection: some mutable ordered collection with heterogeneous
+ comparable items inside
+ :return: the same collection ordered by ascending
+ Examples:
+ >>> bogo_sort([0, 5, 3, 2, 2])
+ [0, 2, 2, 3, 5]
+ >>> bogo_sort([])
+ []
+ >>> bogo_sort([-2, -5, -45])
+ [-45, -5, -2]
+ """
def is_sorted(collection: list) -> bool:
for i in range(len(collection) - 1):
@@ -18,4 +44,4 @@ if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
- print(bogo_sort(unsorted))+ print(bogo_sort(unsorted))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/bogo_sort.py |
Add docstrings to incomplete code |
# Python program to sort a sequence containing only 0, 1 and 2 in a single pass.
red = 0 # The first color of the flag.
white = 1 # The second color of the flag.
blue = 2 # The third color of the flag.
colors = (red, white, blue)
def dutch_national_flag_sort(sequence: list) -> list:
if not sequence:
return []
if len(sequence) == 1:
return list(sequence)
low = 0
high = len(sequence) - 1
mid = 0
while mid <= high:
if sequence[mid] == colors[0]:
sequence[low], sequence[mid] = sequence[mid], sequence[low]
low += 1
mid += 1
elif sequence[mid] == colors[1]:
mid += 1
elif sequence[mid] == colors[2]:
sequence[mid], sequence[high] = sequence[high], sequence[mid]
high -= 1
else:
msg = f"The elements inside the sequence must contains only {colors} values"
raise ValueError(msg)
return sequence
if __name__ == "__main__":
import doctest
doctest.testmod()
user_input = input("Enter numbers separated by commas:\n").strip()
unsorted = [int(item.strip()) for item in user_input.split(",")]
print(f"{dutch_national_flag_sort(unsorted)}") | --- +++ @@ -1,3 +1,27 @@+"""
+A pure implementation of Dutch national flag (DNF) sort algorithm in Python.
+Dutch National Flag algorithm is an algorithm originally designed by Edsger Dijkstra.
+It is the most optimal sort for 3 unique values (eg. 0, 1, 2) in a sequence. DNF can
+sort a sequence of n size with [0 <= a[i] <= 2] at guaranteed O(n) complexity in a
+single pass.
+
+The flag of the Netherlands consists of three colors: white, red, and blue.
+The task is to randomly arrange balls of white, red, and blue in such a way that balls
+of the same color are placed together. DNF sorts a sequence of 0, 1, and 2's in linear
+time that does not consume any extra space. This algorithm can be implemented only on
+a sequence that contains three unique elements.
+
+1) Time complexity is O(n).
+2) Space complexity is O(1).
+
+More info on: https://en.wikipedia.org/wiki/Dutch_national_flag_problem
+
+For doctests run following command:
+python3 -m doctest -v dutch_national_flag_sort.py
+
+For manual testing run:
+python dnf_sort.py
+"""
# Python program to sort a sequence containing only 0, 1 and 2 in a single pass.
red = 0 # The first color of the flag.
@@ -7,6 +31,40 @@
def dutch_national_flag_sort(sequence: list) -> list:
+ """
+ A pure Python implementation of Dutch National Flag sort algorithm.
+ :param data: 3 unique integer values (e.g., 0, 1, 2) in an sequence
+ :return: The same collection in ascending order
+
+ >>> dutch_national_flag_sort([])
+ []
+ >>> dutch_national_flag_sort([0])
+ [0]
+ >>> dutch_national_flag_sort([2, 1, 0, 0, 1, 2])
+ [0, 0, 1, 1, 2, 2]
+ >>> dutch_national_flag_sort([0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1])
+ [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2]
+ >>> dutch_national_flag_sort("abacab")
+ Traceback (most recent call last):
+ ...
+ ValueError: The elements inside the sequence must contains only (0, 1, 2) values
+ >>> dutch_national_flag_sort("Abacab")
+ Traceback (most recent call last):
+ ...
+ ValueError: The elements inside the sequence must contains only (0, 1, 2) values
+ >>> dutch_national_flag_sort([3, 2, 3, 1, 3, 0, 3])
+ Traceback (most recent call last):
+ ...
+ ValueError: The elements inside the sequence must contains only (0, 1, 2) values
+ >>> dutch_national_flag_sort([-1, 2, -1, 1, -1, 0, -1])
+ Traceback (most recent call last):
+ ...
+ ValueError: The elements inside the sequence must contains only (0, 1, 2) values
+ >>> dutch_national_flag_sort([1.1, 2, 1.1, 1, 1.1, 0, 1.1])
+ Traceback (most recent call last):
+ ...
+ ValueError: The elements inside the sequence must contains only (0, 1, 2) values
+ """
if not sequence:
return []
if len(sequence) == 1:
@@ -37,4 +95,4 @@
user_input = input("Enter numbers separated by commas:\n").strip()
unsorted = [int(item.strip()) for item in user_input.split(",")]
- print(f"{dutch_national_flag_sort(unsorted)}")+ print(f"{dutch_national_flag_sort(unsorted)}")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/dutch_national_flag_sort.py |
Add docstrings that explain logic |
def cyclic_sort(nums: list[int]) -> list[int]:
# Perform cyclic sort
index = 0
while index < len(nums):
# Calculate the correct index for the current element
correct_index = nums[index] - 1
# If the current element is not at its correct position,
# swap it with the element at its correct index
if index != correct_index:
nums[index], nums[correct_index] = nums[correct_index], nums[index]
else:
# If the current element is already in its correct position,
# move to the next element
index += 1
return nums
if __name__ == "__main__":
import doctest
doctest.testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(*cyclic_sort(unsorted), sep=",") | --- +++ @@ -1,6 +1,33 @@+"""
+This is a pure Python implementation of the Cyclic Sort algorithm.
+
+For doctests run following command:
+python -m doctest -v cyclic_sort.py
+or
+python3 -m doctest -v cyclic_sort.py
+For manual testing run:
+python cyclic_sort.py
+or
+python3 cyclic_sort.py
+"""
def cyclic_sort(nums: list[int]) -> list[int]:
+ """
+ Sorts the input list of n integers from 1 to n in-place
+ using the Cyclic Sort algorithm.
+
+ :param nums: List of n integers from 1 to n to be sorted.
+ :return: The same list sorted in ascending order.
+
+ Time complexity: O(n), where n is the number of integers in the list.
+
+ Examples:
+ >>> cyclic_sort([])
+ []
+ >>> cyclic_sort([3, 5, 2, 1, 4])
+ [1, 2, 3, 4, 5]
+ """
# Perform cyclic sort
index = 0
@@ -25,4 +52,4 @@ doctest.testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
- print(*cyclic_sort(unsorted), sep=",")+ print(*cyclic_sort(unsorted), sep=",")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/cyclic_sort.py |
Add detailed docstrings explaining each function |
import math
def insertion_sort(array: list, start: int = 0, end: int = 0) -> list:
end = end or len(array)
for i in range(start, end):
temp_index = i
temp_index_value = array[i]
while temp_index != start and temp_index_value < array[temp_index - 1]:
array[temp_index] = array[temp_index - 1]
temp_index -= 1
array[temp_index] = temp_index_value
return array
def heapify(array: list, index: int, heap_size: int) -> None: # Max Heap
largest = index
left_index = 2 * index + 1 # Left Node
right_index = 2 * index + 2 # Right Node
if left_index < heap_size and array[largest] < array[left_index]:
largest = left_index
if right_index < heap_size and array[largest] < array[right_index]:
largest = right_index
if largest != index:
array[index], array[largest] = array[largest], array[index]
heapify(array, largest, heap_size)
def heap_sort(array: list) -> list:
n = len(array)
for i in range(n // 2, -1, -1):
heapify(array, i, n)
for i in range(n - 1, 0, -1):
array[i], array[0] = array[0], array[i]
heapify(array, 0, i)
return array
def median_of_3(
array: list, first_index: int, middle_index: int, last_index: int
) -> int:
if (array[first_index] > array[middle_index]) != (
array[first_index] > array[last_index]
):
return array[first_index]
elif (array[middle_index] > array[first_index]) != (
array[middle_index] > array[last_index]
):
return array[middle_index]
else:
return array[last_index]
def partition(array: list, low: int, high: int, pivot: int) -> int:
i = low
j = high
while True:
while array[i] < pivot:
i += 1
j -= 1
while pivot < array[j]:
j -= 1
if i >= j:
return i
array[i], array[j] = array[j], array[i]
i += 1
def sort(array: list) -> list:
if len(array) == 0:
return array
max_depth = 2 * math.ceil(math.log2(len(array)))
size_threshold = 16
return intro_sort(array, 0, len(array), size_threshold, max_depth)
def intro_sort(
array: list, start: int, end: int, size_threshold: int, max_depth: int
) -> list:
while end - start > size_threshold:
if max_depth == 0:
return heap_sort(array)
max_depth -= 1
pivot = median_of_3(array, start, start + ((end - start) // 2) + 1, end - 1)
p = partition(array, start, end, pivot)
intro_sort(array, p, end, size_threshold, max_depth)
end = p
return insertion_sort(array, start, end)
if __name__ == "__main__":
import doctest
doctest.testmod()
user_input = input("Enter numbers separated by a comma : ").strip()
unsorted = [float(item) for item in user_input.split(",")]
print(f"{sort(unsorted) = }") | --- +++ @@ -1,8 +1,30 @@+"""
+Introspective Sort is a hybrid sort (Quick Sort + Heap Sort + Insertion Sort)
+if the size of the list is under 16, use insertion sort
+https://en.wikipedia.org/wiki/Introsort
+"""
import math
def insertion_sort(array: list, start: int = 0, end: int = 0) -> list:
+ """
+ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]
+ >>> insertion_sort(array, 0, len(array))
+ [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79]
+ >>> array = [21, 15, 11, 45, -2, -11, 46]
+ >>> insertion_sort(array, 0, len(array))
+ [-11, -2, 11, 15, 21, 45, 46]
+ >>> array = [-2, 0, 89, 11, 48, 79, 12]
+ >>> insertion_sort(array, 0, len(array))
+ [-2, 0, 11, 12, 48, 79, 89]
+ >>> array = ['a', 'z', 'd', 'p', 'v', 'l', 'o', 'o']
+ >>> insertion_sort(array, 0, len(array))
+ ['a', 'd', 'l', 'o', 'o', 'p', 'v', 'z']
+ >>> array = [73.568, 73.56, -45.03, 1.7, 0, 89.45]
+ >>> insertion_sort(array, 0, len(array))
+ [-45.03, 0, 1.7, 73.56, 73.568, 89.45]
+ """
end = end or len(array)
for i in range(start, end):
temp_index = i
@@ -15,6 +37,10 @@
def heapify(array: list, index: int, heap_size: int) -> None: # Max Heap
+ """
+ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]
+ >>> heapify(array, len(array) // 2, len(array))
+ """
largest = index
left_index = 2 * index + 1 # Left Node
right_index = 2 * index + 2 # Right Node
@@ -31,6 +57,16 @@
def heap_sort(array: list) -> list:
+ """
+ >>> heap_sort([4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12])
+ [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79]
+ >>> heap_sort([-2, -11, 0, 0, 0, 87, 45, -69, 78, 12, 10, 103, 89, 52])
+ [-69, -11, -2, 0, 0, 0, 10, 12, 45, 52, 78, 87, 89, 103]
+ >>> heap_sort(['b', 'd', 'e', 'f', 'g', 'p', 'x', 'z', 'b', 's', 'e', 'u', 'v'])
+ ['b', 'b', 'd', 'e', 'e', 'f', 'g', 'p', 's', 'u', 'v', 'x', 'z']
+ >>> heap_sort([6.2, -45.54, 8465.20, 758.56, -457.0, 0, 1, 2.879, 1.7, 11.7])
+ [-457.0, -45.54, 0, 1, 1.7, 2.879, 6.2, 11.7, 758.56, 8465.2]
+ """
n = len(array)
for i in range(n // 2, -1, -1):
@@ -46,6 +82,17 @@ def median_of_3(
array: list, first_index: int, middle_index: int, last_index: int
) -> int:
+ """
+ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]
+ >>> median_of_3(array, 0, ((len(array) - 0) // 2) + 1, len(array) - 1)
+ 12
+ >>> array = [13, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]
+ >>> median_of_3(array, 0, ((len(array) - 0) // 2) + 1, len(array) - 1)
+ 13
+ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 15, 14, 27, 79, 23, 45, 14, 16]
+ >>> median_of_3(array, 0, ((len(array) - 0) // 2) + 1, len(array) - 1)
+ 14
+ """
if (array[first_index] > array[middle_index]) != (
array[first_index] > array[last_index]
):
@@ -59,6 +106,20 @@
def partition(array: list, low: int, high: int, pivot: int) -> int:
+ """
+ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]
+ >>> partition(array, 0, len(array), 12)
+ 8
+ >>> array = [21, 15, 11, 45, -2, -11, 46]
+ >>> partition(array, 0, len(array), 15)
+ 3
+ >>> array = ['a', 'z', 'd', 'p', 'v', 'l', 'o', 'o']
+ >>> partition(array, 0, len(array), 'p')
+ 5
+ >>> array = [6.2, -45.54, 8465.20, 758.56, -457.0, 0, 1, 2.879, 1.7, 11.7]
+ >>> partition(array, 0, len(array), 2.879)
+ 6
+ """
i = low
j = high
while True:
@@ -74,6 +135,27 @@
def sort(array: list) -> list:
+ """
+ :param collection: some mutable ordered collection with heterogeneous
+ comparable items inside
+ :return: the same collection ordered by ascending
+
+ Examples:
+ >>> sort([4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12])
+ [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79]
+ >>> sort([-1, -5, -3, -13, -44])
+ [-44, -13, -5, -3, -1]
+ >>> sort([])
+ []
+ >>> sort([5])
+ [5]
+ >>> sort([-3, 0, -7, 6, 23, -34])
+ [-34, -7, -3, 0, 6, 23]
+ >>> sort([1.7, 1.0, 3.3, 2.1, 0.3 ])
+ [0.3, 1.0, 1.7, 2.1, 3.3]
+ >>> sort(['d', 'a', 'b', 'e', 'c'])
+ ['a', 'b', 'c', 'd', 'e']
+ """
if len(array) == 0:
return array
max_depth = 2 * math.ceil(math.log2(len(array)))
@@ -84,6 +166,12 @@ def intro_sort(
array: list, start: int, end: int, size_threshold: int, max_depth: int
) -> list:
+ """
+ >>> array = [4, 2, 6, 8, 1, 7, 8, 22, 14, 56, 27, 79, 23, 45, 14, 12]
+ >>> max_depth = 2 * math.ceil(math.log2(len(array)))
+ >>> intro_sort(array, 0, len(array), 16, max_depth)
+ [1, 2, 4, 6, 7, 8, 8, 12, 14, 14, 22, 23, 27, 45, 56, 79]
+ """
while end - start > size_threshold:
if max_depth == 0:
return heap_sort(array)
@@ -101,4 +189,4 @@ doctest.testmod()
user_input = input("Enter numbers separated by a comma : ").strip()
unsorted = [float(item) for item in user_input.split(",")]
- print(f"{sort(unsorted) = }")+ print(f"{sort(unsorted) = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/intro_sort.py |
Create simple docstrings for beginners |
from __future__ import annotations
def msd_radix_sort(list_of_ints: list[int]) -> list[int]:
if not list_of_ints:
return []
if min(list_of_ints) < 0:
raise ValueError("All numbers must be positive")
most_bits = max(len(bin(x)[2:]) for x in list_of_ints)
return _msd_radix_sort(list_of_ints, most_bits)
def _msd_radix_sort(list_of_ints: list[int], bit_position: int) -> list[int]:
if bit_position == 0 or len(list_of_ints) in [0, 1]:
return list_of_ints
zeros = []
ones = []
# Split numbers based on bit at bit_position from the right
for number in list_of_ints:
if (number >> (bit_position - 1)) & 1:
# number has a one at bit bit_position
ones.append(number)
else:
# number has a zero at bit bit_position
zeros.append(number)
# recursively split both lists further
zeros = _msd_radix_sort(zeros, bit_position - 1)
ones = _msd_radix_sort(ones, bit_position - 1)
# recombine lists
res = zeros
res.extend(ones)
return res
def msd_radix_sort_inplace(list_of_ints: list[int]):
length = len(list_of_ints)
if not list_of_ints or length == 1:
return
if min(list_of_ints) < 0:
raise ValueError("All numbers must be positive")
most_bits = max(len(bin(x)[2:]) for x in list_of_ints)
_msd_radix_sort_inplace(list_of_ints, most_bits, 0, length)
def _msd_radix_sort_inplace(
list_of_ints: list[int], bit_position: int, begin_index: int, end_index: int
):
if bit_position == 0 or end_index - begin_index <= 1:
return
bit_position -= 1
i = begin_index
j = end_index - 1
while i <= j:
changed = False
if not (list_of_ints[i] >> bit_position) & 1:
# found zero at the beginning
i += 1
changed = True
if (list_of_ints[j] >> bit_position) & 1:
# found one at the end
j -= 1
changed = True
if changed:
continue
list_of_ints[i], list_of_ints[j] = list_of_ints[j], list_of_ints[i]
j -= 1
if j != i:
i += 1
_msd_radix_sort_inplace(list_of_ints, bit_position, begin_index, i)
_msd_radix_sort_inplace(list_of_ints, bit_position, i, end_index)
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,8 +1,32 @@+"""
+Python implementation of the MSD radix sort algorithm.
+It used the binary representation of the integers to sort
+them.
+https://en.wikipedia.org/wiki/Radix_sort
+"""
from __future__ import annotations
def msd_radix_sort(list_of_ints: list[int]) -> list[int]:
+ """
+ Implementation of the MSD radix sort algorithm. Only works
+ with positive integers
+ :param list_of_ints: A list of integers
+ :return: Returns the sorted list
+ >>> msd_radix_sort([40, 12, 1, 100, 4])
+ [1, 4, 12, 40, 100]
+ >>> msd_radix_sort([])
+ []
+ >>> msd_radix_sort([123, 345, 123, 80])
+ [80, 123, 123, 345]
+ >>> msd_radix_sort([1209, 834598, 1, 540402, 45])
+ [1, 45, 1209, 540402, 834598]
+ >>> msd_radix_sort([-1, 34, 45])
+ Traceback (most recent call last):
+ ...
+ ValueError: All numbers must be positive
+ """
if not list_of_ints:
return []
@@ -14,6 +38,18 @@
def _msd_radix_sort(list_of_ints: list[int], bit_position: int) -> list[int]:
+ """
+ Sort the given list based on the bit at bit_position. Numbers with a
+ 0 at that position will be at the start of the list, numbers with a
+ 1 at the end.
+ :param list_of_ints: A list of integers
+ :param bit_position: the position of the bit that gets compared
+ :return: Returns a partially sorted list
+ >>> _msd_radix_sort([45, 2, 32], 1)
+ [2, 32, 45]
+ >>> _msd_radix_sort([10, 4, 12], 2)
+ [4, 12, 10]
+ """
if bit_position == 0 or len(list_of_ints) in [0, 1]:
return list_of_ints
@@ -40,6 +76,27 @@
def msd_radix_sort_inplace(list_of_ints: list[int]):
+ """
+ Inplace implementation of the MSD radix sort algorithm.
+ Sorts based on the binary representation of the integers.
+ >>> lst = [1, 345, 23, 89, 0, 3]
+ >>> msd_radix_sort_inplace(lst)
+ >>> lst == sorted(lst)
+ True
+ >>> lst = [1, 43, 0, 0, 0, 24, 3, 3]
+ >>> msd_radix_sort_inplace(lst)
+ >>> lst == sorted(lst)
+ True
+ >>> lst = []
+ >>> msd_radix_sort_inplace(lst)
+ >>> lst == []
+ True
+ >>> lst = [-1, 34, 23, 4, -42]
+ >>> msd_radix_sort_inplace(lst)
+ Traceback (most recent call last):
+ ...
+ ValueError: All numbers must be positive
+ """
length = len(list_of_ints)
if not list_of_ints or length == 1:
@@ -55,6 +112,19 @@ def _msd_radix_sort_inplace(
list_of_ints: list[int], bit_position: int, begin_index: int, end_index: int
):
+ """
+ Sort the given list based on the bit at bit_position. Numbers with a
+ 0 at that position will be at the start of the list, numbers with a
+ 1 at the end.
+ >>> lst = [45, 2, 32, 24, 534, 2932]
+ >>> _msd_radix_sort_inplace(lst, 1, 0, 3)
+ >>> lst == [32, 2, 45, 24, 534, 2932]
+ True
+ >>> lst = [0, 2, 1, 3, 12, 10, 4, 90, 54, 2323, 756]
+ >>> _msd_radix_sort_inplace(lst, 2, 4, 7)
+ >>> lst == [0, 2, 1, 3, 12, 4, 10, 90, 54, 2323, 756]
+ True
+ """
if bit_position == 0 or end_index - begin_index <= 1:
return
@@ -88,4 +158,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/msd_radix_sort.py |
Write Python docstrings for this snippet |
from collections.abc import MutableSequence
from typing import Any, Protocol, TypeVar
class Comparable(Protocol):
def __lt__(self, other: Any, /) -> bool: ...
T = TypeVar("T", bound=Comparable)
def insertion_sort[T: Comparable](collection: MutableSequence[T]) -> MutableSequence[T]:
for insert_index in range(1, len(collection)):
insert_value = collection[insert_index]
while insert_index > 0 and insert_value < collection[insert_index - 1]:
collection[insert_index] = collection[insert_index - 1]
insert_index -= 1
collection[insert_index] = insert_value
return collection
if __name__ == "__main__":
from doctest import testmod
testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(f"{insertion_sort(unsorted) = }") | --- +++ @@ -1,3 +1,17 @@+"""
+A pure Python implementation of the insertion sort algorithm
+
+This algorithm sorts a collection by comparing adjacent elements.
+When it finds that order is not respected, it moves the element compared
+backward until the order is correct. It then goes back directly to the
+element's initial position resuming forward comparison.
+
+For doctests run following command:
+python3 -m doctest -v insertion_sort.py
+
+For manual testing run:
+python3 insertion_sort.py
+"""
from collections.abc import MutableSequence
from typing import Any, Protocol, TypeVar
@@ -11,6 +25,30 @@
def insertion_sort[T: Comparable](collection: MutableSequence[T]) -> MutableSequence[T]:
+ """A pure Python implementation of the insertion sort algorithm
+
+ :param collection: some mutable ordered collection with heterogeneous
+ comparable items inside
+ :return: the same collection ordered by ascending
+
+ Examples:
+ >>> insertion_sort([0, 5, 3, 2, 2])
+ [0, 2, 2, 3, 5]
+ >>> insertion_sort([]) == sorted([])
+ True
+ >>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45])
+ True
+ >>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c'])
+ True
+ >>> import random
+ >>> collection = random.sample(range(-50, 50), 100)
+ >>> insertion_sort(collection) == sorted(collection)
+ True
+ >>> import string
+ >>> collection = random.choices(string.ascii_letters + string.digits, k=100)
+ >>> insertion_sort(collection) == sorted(collection)
+ True
+ """
for insert_index in range(1, len(collection)):
insert_value = collection[insert_index]
@@ -28,4 +66,4 @@
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
- print(f"{insertion_sort(unsorted) = }")+ print(f"{insertion_sort(unsorted) = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/insertion_sort.py |
Add docstrings for utility scripts |
def naive_pattern_search(s: str, pattern: str) -> list:
pat_len = len(pattern)
position = []
for i in range(len(s) - pat_len + 1):
match_found = True
for j in range(pat_len):
if s[i + j] != pattern[j]:
match_found = False
break
if match_found:
position.append(i)
return position
if __name__ == "__main__":
assert naive_pattern_search("ABCDEFG", "DE") == [3]
print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC")) | --- +++ @@ -1,6 +1,27 @@+"""
+https://en.wikipedia.org/wiki/String-searching_algorithm#Na%C3%AFve_string_search
+this algorithm tries to find the pattern from every position of
+the mainString if pattern is found from position i it add it to
+the answer and does the same for position i+1
+Complexity : O(n*m)
+ n=length of main string
+ m=length of pattern string
+"""
def naive_pattern_search(s: str, pattern: str) -> list:
+ """
+ >>> naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC")
+ [4, 10, 18]
+ >>> naive_pattern_search("ABC", "ABAAABCDBBABCDDEBCABC")
+ []
+ >>> naive_pattern_search("", "ABC")
+ []
+ >>> naive_pattern_search("TEST", "TEST")
+ [0]
+ >>> naive_pattern_search("ABCDEGFTEST", "TEST")
+ [7]
+ """
pat_len = len(pattern)
position = []
for i in range(len(s) - pat_len + 1):
@@ -16,4 +37,4 @@
if __name__ == "__main__":
assert naive_pattern_search("ABCDEFG", "DE") == [3]
- print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))+ print(naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC"))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/naive_string_search.py |
Provide clean and structured docstrings |
from __future__ import annotations
def binary_search_insertion(sorted_list, item):
left = 0
right = len(sorted_list) - 1
while left <= right:
middle = (left + right) // 2
if left == right:
if sorted_list[middle] < item:
left = middle + 1
break
elif sorted_list[middle] < item:
left = middle + 1
else:
right = middle - 1
sorted_list.insert(left, item)
return sorted_list
def merge(left, right):
result = []
while left and right:
if left[0][0] < right[0][0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
return result + left + right
def sortlist_2d(list_2d):
length = len(list_2d)
if length <= 1:
return list_2d
middle = length // 2
return merge(sortlist_2d(list_2d[:middle]), sortlist_2d(list_2d[middle:]))
def merge_insertion_sort(collection: list[int]) -> list[int]:
if len(collection) <= 1:
return collection
"""
Group the items into two pairs, and leave one element if there is a last odd item.
Example: [999, 100, 75, 40, 10000]
-> [999, 100], [75, 40]. Leave 10000.
"""
two_paired_list = []
has_last_odd_item = False
for i in range(0, len(collection), 2):
if i == len(collection) - 1:
has_last_odd_item = True
else:
"""
Sort two-pairs in each groups.
Example: [999, 100], [75, 40]
-> [100, 999], [40, 75]
"""
if collection[i] < collection[i + 1]:
two_paired_list.append([collection[i], collection[i + 1]])
else:
two_paired_list.append([collection[i + 1], collection[i]])
"""
Sort two_paired_list.
Example: [100, 999], [40, 75]
-> [40, 75], [100, 999]
"""
sorted_list_2d = sortlist_2d(two_paired_list)
"""
40 < 100 is sure because it has already been sorted.
Generate the sorted_list of them so that you can avoid unnecessary comparison.
Example:
group0 group1
40 100
75 999
->
group0 group1
[40, 100]
75 999
"""
result = [i[0] for i in sorted_list_2d]
"""
100 < 999 is sure because it has already been sorted.
Put 999 in last of the sorted_list so that you can avoid unnecessary comparison.
Example:
group0 group1
[40, 100]
75 999
->
group0 group1
[40, 100, 999]
75
"""
result.append(sorted_list_2d[-1][1])
"""
Insert the last odd item left if there is.
Example:
group0 group1
[40, 100, 999]
75
->
group0 group1
[40, 100, 999, 10000]
75
"""
if has_last_odd_item:
pivot = collection[-1]
result = binary_search_insertion(result, pivot)
"""
Insert the remaining items.
In this case, 40 < 75 is sure because it has already been sorted.
Therefore, you only need to insert 75 into [100, 999, 10000],
so that you can avoid unnecessary comparison.
Example:
group0 group1
[40, 100, 999, 10000]
^ You don't need to compare with this as 40 < 75 is already sure.
75
->
[40, 75, 100, 999, 10000]
"""
is_last_odd_item_inserted_before_this_index = False
for i in range(len(sorted_list_2d) - 1):
if result[i] == collection[-1] and has_last_odd_item:
is_last_odd_item_inserted_before_this_index = True
pivot = sorted_list_2d[i][1]
# If last_odd_item is inserted before the item's index,
# you should forward index one more.
if is_last_odd_item_inserted_before_this_index:
result = result[: i + 2] + binary_search_insertion(result[i + 2 :], pivot)
else:
result = result[: i + 1] + binary_search_insertion(result[i + 1 :], pivot)
return result
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(merge_insertion_sort(unsorted)) | --- +++ @@ -1,8 +1,24 @@+"""
+This is a pure Python implementation of the merge-insertion sort algorithm
+Source: https://en.wikipedia.org/wiki/Merge-insertion_sort
+
+For doctests run following command:
+python3 -m doctest -v merge_insertion_sort.py
+or
+python -m doctest -v merge_insertion_sort.py
+
+For manual testing run:
+python3 merge_insertion_sort.py
+"""
from __future__ import annotations
def binary_search_insertion(sorted_list, item):
+ """
+ >>> binary_search_insertion([1, 2, 7, 9, 10], 4)
+ [1, 2, 4, 7, 9, 10]
+ """
left = 0
right = len(sorted_list) - 1
while left <= right:
@@ -20,6 +36,10 @@
def merge(left, right):
+ """
+ >>> merge([[1, 6], [9, 10]], [[2, 3], [4, 5], [7, 8]])
+ [[1, 6], [2, 3], [4, 5], [7, 8], [9, 10]]
+ """
result = []
while left and right:
if left[0][0] < right[0][0]:
@@ -30,6 +50,10 @@
def sortlist_2d(list_2d):
+ """
+ >>> sortlist_2d([[9, 10], [1, 6], [7, 8], [2, 3], [4, 5]])
+ [[1, 6], [2, 3], [4, 5], [7, 8], [9, 10]]
+ """
length = len(list_2d)
if length <= 1:
return list_2d
@@ -38,6 +62,28 @@
def merge_insertion_sort(collection: list[int]) -> list[int]:
+ """Pure implementation of merge-insertion sort algorithm in Python
+
+ :param collection: some mutable ordered collection with heterogeneous
+ comparable items inside
+ :return: the same collection ordered by ascending
+
+ Examples:
+ >>> merge_insertion_sort([0, 5, 3, 2, 2])
+ [0, 2, 2, 3, 5]
+
+ >>> merge_insertion_sort([99])
+ [99]
+
+ >>> merge_insertion_sort([-2, -5, -45])
+ [-45, -5, -2]
+
+ Testing with all permutations on range(0,5):
+ >>> import itertools
+ >>> permutations = list(itertools.permutations([0, 1, 2, 3, 4]))
+ >>> all(merge_insertion_sort(p) == [0, 1, 2, 3, 4] for p in permutations)
+ True
+ """
if len(collection) <= 1:
return collection
@@ -151,4 +197,4 @@ if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
- print(merge_insertion_sort(unsorted))+ print(merge_insertion_sort(unsorted))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/merge_insertion_sort.py |
Add docstrings for production code |
import string
email_tests: tuple[tuple[str, bool], ...] = (
("simple@example.com", True),
("very.common@example.com", True),
("disposable.style.email.with+symbol@example.com", True),
("other-email-with-hyphen@and.subdomains.example.com", True),
("fully-qualified-domain@example.com", True),
("user.name+tag+sorting@example.com", True),
("x@example.com", True),
("example-indeed@strange-example.com", True),
("test/test@test.com", True),
(
"123456789012345678901234567890123456789012345678901234567890123@example.com",
True,
),
("admin@mailserver1", True),
("example@s.example", True),
("Abc.example.com", False),
("A@b@c@example.com", False),
("abc@example..com", False),
("a(c)d,e:f;g<h>i[j\\k]l@example.com", False),
(
"12345678901234567890123456789012345678901234567890123456789012345@example.com",
False,
),
("i.like.underscores@but_its_not_allowed_in_this_part", False),
("", False),
)
# The maximum octets (one character as a standard unicode character is one byte)
# that the local part and the domain part can have
MAX_LOCAL_PART_OCTETS = 64
MAX_DOMAIN_OCTETS = 255
def is_valid_email_address(email: str) -> bool:
# (1.) Make sure that there is only one @ symbol in the email address
if email.count("@") != 1:
return False
local_part, domain = email.split("@")
# (2.) Check octet length of the local part and domain
if len(local_part) > MAX_LOCAL_PART_OCTETS or len(domain) > MAX_DOMAIN_OCTETS:
return False
# (3.) Validate the characters in the local-part
if any(
char not in string.ascii_letters + string.digits + ".(!#$%&'*+-/=?^_`{|}~)"
for char in local_part
):
return False
# (4.) Validate the placement of "." characters in the local-part
if local_part.startswith(".") or local_part.endswith(".") or ".." in local_part:
return False
# (5.) Validate the characters in the domain
if any(char not in string.ascii_letters + string.digits + ".-" for char in domain):
return False
# (6.) Validate the placement of "-" characters
if domain.startswith("-") or domain.endswith("."):
return False
# (7.) Validate the placement of "." characters
return not (domain.startswith(".") or domain.endswith(".") or ".." in domain)
if __name__ == "__main__":
import doctest
doctest.testmod()
for email, valid in email_tests:
is_valid = is_valid_email_address(email)
assert is_valid == valid, f"{email} is {is_valid}"
print(f"Email address {email} is {'not ' if not is_valid else ''}valid") | --- +++ @@ -1,3 +1,8 @@+"""
+Implements an is valid email address algorithm
+
+@ https://en.wikipedia.org/wiki/Email_address
+"""
import string
@@ -36,6 +41,36 @@
def is_valid_email_address(email: str) -> bool:
+ """
+ Returns True if the passed email address is valid.
+
+ The local part of the email precedes the singular @ symbol and
+ is associated with a display-name. For example, "john.smith"
+ The domain is stricter than the local part and follows the @ symbol.
+
+ Global email checks:
+ 1. There can only be one @ symbol in the email address. Technically if the
+ @ symbol is quoted in the local-part, then it is valid, however this
+ implementation ignores "" for now.
+ (See https://en.wikipedia.org/wiki/Email_address#:~:text=If%20quoted,)
+ 2. The local-part and the domain are limited to a certain number of octets. With
+ unicode storing a single character in one byte, each octet is equivalent to
+ a character. Hence, we can just check the length of the string.
+ Checks for the local-part:
+ 3. The local-part may contain: upper and lowercase latin letters, digits 0 to 9,
+ and printable characters (!#$%&'*+-/=?^_`{|}~)
+ 4. The local-part may also contain a "." in any place that is not the first or
+ last character, and may not have more than one "." consecutively.
+
+ Checks for the domain:
+ 5. The domain may contain: upper and lowercase latin letters and digits 0 to 9
+ 6. Hyphen "-", provided that it is not the first or last character
+ 7. The domain may also contain a "." in any place that is not the first or
+ last character, and may not have more than one "." consecutively.
+
+ >>> for email, valid in email_tests:
+ ... assert is_valid_email_address(email) == valid
+ """
# (1.) Make sure that there is only one @ symbol in the email address
if email.count("@") != 1:
@@ -77,4 +112,4 @@ for email, valid in email_tests:
is_valid = is_valid_email_address(email)
assert is_valid == valid, f"{email} is {is_valid}"
- print(f"Email address {email} is {'not ' if not is_valid else ''}valid")+ print(f"Email address {email} is {'not ' if not is_valid else ''}valid")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/is_valid_email_address.py |
Add detailed documentation for each class | # Algorithms to determine if a string is palindrome
from timeit import timeit
test_data = {
"MALAYALAM": True,
"String": False,
"rotor": True,
"level": True,
"A": True,
"BB": True,
"ABC": False,
"amanaplanacanalpanama": True, # "a man a plan a canal panama"
"abcdba": False,
"AB": False,
}
# Ensure our test data is valid
assert all((key == key[::-1]) == value for key, value in test_data.items())
def is_palindrome(s: str) -> bool:
start_i = 0
end_i = len(s) - 1
while start_i < end_i:
if s[start_i] == s[end_i]:
start_i += 1
end_i -= 1
else:
return False
return True
def is_palindrome_traversal(s: str) -> bool:
end = len(s) // 2
n = len(s)
# We need to traverse till half of the length of string
# as we can get access of the i'th last element from
# i'th index.
# eg: [0,1,2,3,4,5] => 4th index can be accessed
# with the help of 1st index (i==n-i-1)
# where n is length of string
return all(s[i] == s[n - i - 1] for i in range(end))
def is_palindrome_recursive(s: str) -> bool:
if len(s) <= 1:
return True
if s[0] == s[len(s) - 1]:
return is_palindrome_recursive(s[1:-1])
else:
return False
def is_palindrome_slice(s: str) -> bool:
return s == s[::-1]
def benchmark_function(name: str) -> None:
stmt = f"all({name}(key) == value for key, value in test_data.items())"
setup = f"from __main__ import test_data, {name}"
number = 500000
result = timeit(stmt=stmt, setup=setup, number=number)
print(f"{name:<35} finished {number:,} runs in {result:.5f} seconds")
if __name__ == "__main__":
for key, value in test_data.items():
assert is_palindrome(key) == is_palindrome_recursive(key)
assert is_palindrome(key) == is_palindrome_slice(key)
print(f"{key:21} {value}")
print("a man a plan a canal panama")
# finished 500,000 runs in 0.46793 seconds
benchmark_function("is_palindrome_slice")
# finished 500,000 runs in 0.85234 seconds
benchmark_function("is_palindrome")
# finished 500,000 runs in 1.32028 seconds
benchmark_function("is_palindrome_recursive")
# finished 500,000 runs in 2.08679 seconds
benchmark_function("is_palindrome_traversal") | --- +++ @@ -19,6 +19,12 @@
def is_palindrome(s: str) -> bool:
+ """
+ Return True if s is a palindrome otherwise return False.
+
+ >>> all(is_palindrome(key) == value for key, value in test_data.items())
+ True
+ """
start_i = 0
end_i = len(s) - 1
@@ -32,6 +38,12 @@
def is_palindrome_traversal(s: str) -> bool:
+ """
+ Return True if s is a palindrome otherwise return False.
+
+ >>> all(is_palindrome_traversal(key) == value for key, value in test_data.items())
+ True
+ """
end = len(s) // 2
n = len(s)
@@ -45,6 +57,12 @@
def is_palindrome_recursive(s: str) -> bool:
+ """
+ Return True if s is a palindrome otherwise return False.
+
+ >>> all(is_palindrome_recursive(key) == value for key, value in test_data.items())
+ True
+ """
if len(s) <= 1:
return True
if s[0] == s[len(s) - 1]:
@@ -54,6 +72,12 @@
def is_palindrome_slice(s: str) -> bool:
+ """
+ Return True if s is a palindrome otherwise return False.
+
+ >>> all(is_palindrome_slice(key) == value for key, value in test_data.items())
+ True
+ """
return s == s[::-1]
@@ -79,4 +103,4 @@ # finished 500,000 runs in 1.32028 seconds
benchmark_function("is_palindrome_recursive")
# finished 500,000 runs in 2.08679 seconds
- benchmark_function("is_palindrome_traversal")+ benchmark_function("is_palindrome_traversal")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/palindrome.py |
Write reusable docstrings |
def prefix_function(input_string: str) -> list:
# list for the result values
prefix_result = [0] * len(input_string)
for i in range(1, len(input_string)):
# use last results for better performance - dynamic programming
j = prefix_result[i - 1]
while j > 0 and input_string[i] != input_string[j]:
j = prefix_result[j - 1]
if input_string[i] == input_string[j]:
j += 1
prefix_result[i] = j
return prefix_result
def longest_prefix(input_str: str) -> int:
# just returning maximum value of the array gives us answer
return max(prefix_function(input_str))
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,6 +1,29 @@+"""
+https://cp-algorithms.com/string/prefix-function.html
+
+Prefix function Knuth-Morris-Pratt algorithm
+
+Different algorithm than Knuth-Morris-Pratt pattern finding
+
+E.x. Finding longest prefix which is also suffix
+
+Time Complexity: O(n) - where n is the length of the string
+"""
def prefix_function(input_string: str) -> list:
+ """
+ For the given string this function computes value for each index(i),
+ which represents the longest coincidence of prefix and suffix
+ for given substring (input_str[0...i])
+
+ For the value of the first element the algorithm always returns 0
+
+ >>> prefix_function("aabcdaabc")
+ [0, 1, 0, 0, 0, 1, 2, 3, 4]
+ >>> prefix_function("asdasdad")
+ [0, 0, 0, 1, 2, 3, 4, 0]
+ """
# list for the result values
prefix_result = [0] * len(input_string)
@@ -19,6 +42,17 @@
def longest_prefix(input_str: str) -> int:
+ """
+ Prefix-function use case
+ Finding longest prefix which is suffix as well
+
+ >>> longest_prefix("aabcdaabc")
+ 4
+ >>> longest_prefix("asdasdad")
+ 4
+ >>> longest_prefix("abcab")
+ 2
+ """
# just returning maximum value of the array gives us answer
return max(prefix_function(input_str))
@@ -27,4 +61,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/prefix_function.py |
Add docstrings to improve code quality |
def cycle_sort(array: list) -> list:
array_len = len(array)
for cycle_start in range(array_len - 1):
item = array[cycle_start]
pos = cycle_start
for i in range(cycle_start + 1, array_len):
if array[i] < item:
pos += 1
if pos == cycle_start:
continue
while item == array[pos]:
pos += 1
array[pos], item = item, array[pos]
while pos != cycle_start:
pos = cycle_start
for i in range(cycle_start + 1, array_len):
if array[i] < item:
pos += 1
while item == array[pos]:
pos += 1
array[pos], item = item, array[pos]
return array
if __name__ == "__main__":
assert cycle_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5]
assert cycle_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15] | --- +++ @@ -1,6 +1,23 @@+"""
+Code contributed by Honey Sharma
+Source: https://en.wikipedia.org/wiki/Cycle_sort
+"""
def cycle_sort(array: list) -> list:
+ """
+ >>> cycle_sort([4, 3, 2, 1])
+ [1, 2, 3, 4]
+
+ >>> cycle_sort([-4, 20, 0, -50, 100, -1])
+ [-50, -4, -1, 0, 20, 100]
+
+ >>> cycle_sort([-.1, -.2, 1.3, -.8])
+ [-0.8, -0.2, -0.1, 1.3]
+
+ >>> cycle_sort([])
+ []
+ """
array_len = len(array)
for cycle_start in range(array_len - 1):
item = array[cycle_start]
@@ -33,4 +50,4 @@
if __name__ == "__main__":
assert cycle_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5]
- assert cycle_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]+ assert cycle_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/cycle_sort.py |
Help me add docstrings to my project |
def merge_sort(collection: list) -> list:
def merge(left: list, right: list) -> list:
result = []
while left and right:
result.append(left.pop(0) if left[0] <= right[0] else right.pop(0))
result.extend(left)
result.extend(right)
return result
if len(collection) <= 1:
return collection
mid_index = len(collection) // 2
return merge(merge_sort(collection[:mid_index]), merge_sort(collection[mid_index:]))
if __name__ == "__main__":
import doctest
doctest.testmod()
try:
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
sorted_list = merge_sort(unsorted)
print(*sorted_list, sep=",")
except ValueError:
print("Invalid input. Please enter valid integers separated by commas.") | --- +++ @@ -1,8 +1,42 @@+"""
+This is a pure Python implementation of the merge sort algorithm.
+
+For doctests run following command:
+python -m doctest -v merge_sort.py
+or
+python3 -m doctest -v merge_sort.py
+For manual testing run:
+python merge_sort.py
+"""
def merge_sort(collection: list) -> list:
+ """
+ Sorts a list using the merge sort algorithm.
+
+ :param collection: A mutable ordered collection with comparable items.
+ :return: The same collection ordered in ascending order.
+
+ Time Complexity: O(n log n)
+ Space Complexity: O(n)
+
+ Examples:
+ >>> merge_sort([0, 5, 3, 2, 2])
+ [0, 2, 2, 3, 5]
+ >>> merge_sort([])
+ []
+ >>> merge_sort([-2, -5, -45])
+ [-45, -5, -2]
+ """
def merge(left: list, right: list) -> list:
+ """
+ Merge two sorted lists into a single sorted list.
+
+ :param left: Left collection
+ :param right: Right collection
+ :return: Merged result
+ """
result = []
while left and right:
result.append(left.pop(0) if left[0] <= right[0] else right.pop(0))
@@ -27,4 +61,4 @@ sorted_list = merge_sort(unsorted)
print(*sorted_list, sep=",")
except ValueError:
- print("Invalid input. Please enter valid integers separated by commas.")+ print("Invalid input. Please enter valid integers separated by commas.")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/merge_sort.py |
Generate helpful docstrings for debugging |
from __future__ import annotations
def merge(input_list: list, low: int, mid: int, high: int) -> list:
result = []
left, right = input_list[low:mid], input_list[mid : high + 1]
while left and right:
result.append((left if left[0] <= right[0] else right).pop(0))
input_list[low : high + 1] = result + left + right
return input_list
# iteration over the unsorted list
def iter_merge_sort(input_list: list) -> list:
if len(input_list) <= 1:
return input_list
input_list = list(input_list)
# iteration for two-way merging
p = 2
while p <= len(input_list):
# getting low, high and middle value for merge-sort of single list
for i in range(0, len(input_list), p):
low = i
high = i + p - 1
mid = (low + high + 1) // 2
input_list = merge(input_list, low, mid, high)
# final merge of last two parts
if p * 2 >= len(input_list):
mid = i
input_list = merge(input_list, 0, mid, len(input_list) - 1)
break
p *= 2
return input_list
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
if user_input == "":
unsorted = []
else:
unsorted = [int(item.strip()) for item in user_input.split(",")]
print(iter_merge_sort(unsorted)) | --- +++ @@ -1,8 +1,22 @@+"""
+Implementation of iterative merge sort in Python
+Author: Aman Gupta
+
+For doctests run following command:
+python3 -m doctest -v iterative_merge_sort.py
+
+For manual testing run:
+python3 iterative_merge_sort.py
+"""
from __future__ import annotations
def merge(input_list: list, low: int, mid: int, high: int) -> list:
+ """
+ sorting left-half and right-half individually
+ then merging them into result
+ """
result = []
left, right = input_list[low:mid], input_list[mid : high + 1]
while left and right:
@@ -13,6 +27,40 @@
# iteration over the unsorted list
def iter_merge_sort(input_list: list) -> list:
+ """
+ Return a sorted copy of the input list
+
+ >>> iter_merge_sort([5, 9, 8, 7, 1, 2, 7])
+ [1, 2, 5, 7, 7, 8, 9]
+ >>> iter_merge_sort([1])
+ [1]
+ >>> iter_merge_sort([2, 1])
+ [1, 2]
+ >>> iter_merge_sort([2, 1, 3])
+ [1, 2, 3]
+ >>> iter_merge_sort([4, 3, 2, 1])
+ [1, 2, 3, 4]
+ >>> iter_merge_sort([5, 4, 3, 2, 1])
+ [1, 2, 3, 4, 5]
+ >>> iter_merge_sort(['c', 'b', 'a'])
+ ['a', 'b', 'c']
+ >>> iter_merge_sort([0.3, 0.2, 0.1])
+ [0.1, 0.2, 0.3]
+ >>> iter_merge_sort(['dep', 'dang', 'trai'])
+ ['dang', 'dep', 'trai']
+ >>> iter_merge_sort([6])
+ [6]
+ >>> iter_merge_sort([])
+ []
+ >>> iter_merge_sort([-2, -9, -1, -4])
+ [-9, -4, -2, -1]
+ >>> iter_merge_sort([1.1, 1, 0.0, -1, -1.1])
+ [-1.1, -1, 0.0, 1, 1.1]
+ >>> iter_merge_sort(['c', 'b', 'a'])
+ ['a', 'b', 'c']
+ >>> iter_merge_sort('cba')
+ ['a', 'b', 'c']
+ """
if len(input_list) <= 1:
return input_list
input_list = list(input_list)
@@ -42,4 +90,4 @@ unsorted = []
else:
unsorted = [int(item.strip()) for item in user_input.split(",")]
- print(iter_merge_sort(unsorted))+ print(iter_merge_sort(unsorted))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/iterative_merge_sort.py |
Document all public functions with docstrings |
def heapify(unsorted: list[int], index: int, heap_size: int) -> None:
largest = index
left_index = 2 * index + 1
right_index = 2 * index + 2
if left_index < heap_size and unsorted[left_index] > unsorted[largest]:
largest = left_index
if right_index < heap_size and unsorted[right_index] > unsorted[largest]:
largest = right_index
if largest != index:
unsorted[largest], unsorted[index] = (unsorted[index], unsorted[largest])
heapify(unsorted, largest, heap_size)
def heap_sort(unsorted: list[int]) -> list[int]:
n = len(unsorted)
for i in range(n // 2 - 1, -1, -1):
heapify(unsorted, i, n)
for i in range(n - 1, 0, -1):
unsorted[0], unsorted[i] = unsorted[i], unsorted[0]
heapify(unsorted, 0, i)
return unsorted
if __name__ == "__main__":
import doctest
doctest.testmod()
user_input = input("Enter numbers separated by a comma:\n").strip()
if user_input:
unsorted = [int(item) for item in user_input.split(",")]
print(f"{heap_sort(unsorted) = }") | --- +++ @@ -1,6 +1,22 @@+"""
+A pure Python implementation of the heap sort algorithm.
+"""
def heapify(unsorted: list[int], index: int, heap_size: int) -> None:
+ """
+ :param unsorted: unsorted list containing integers numbers
+ :param index: index
+ :param heap_size: size of the heap
+ :return: None
+ >>> unsorted = [1, 4, 3, 5, 2]
+ >>> heapify(unsorted, 0, len(unsorted))
+ >>> unsorted
+ [4, 5, 3, 1, 2]
+ >>> heapify(unsorted, 0, len(unsorted))
+ >>> unsorted
+ [5, 4, 3, 1, 2]
+ """
largest = index
left_index = 2 * index + 1
right_index = 2 * index + 2
@@ -16,6 +32,22 @@
def heap_sort(unsorted: list[int]) -> list[int]:
+ """
+ A pure Python implementation of the heap sort algorithm
+
+ :param collection: a mutable ordered collection of heterogeneous comparable items
+ :return: the same collection ordered by ascending
+
+ Examples:
+ >>> heap_sort([0, 5, 3, 2, 2])
+ [0, 2, 2, 3, 5]
+ >>> heap_sort([])
+ []
+ >>> heap_sort([-2, -5, -45])
+ [-45, -5, -2]
+ >>> heap_sort([3, 7, 9, 28, 123, -5, 8, -30, -200, 0, 4])
+ [-200, -30, -5, 0, 3, 4, 7, 8, 9, 28, 123]
+ """
n = len(unsorted)
for i in range(n // 2 - 1, -1, -1):
heapify(unsorted, i, n)
@@ -32,4 +64,4 @@ user_input = input("Enter numbers separated by a comma:\n").strip()
if user_input:
unsorted = [int(item) for item in user_input.split(",")]
- print(f"{heap_sort(unsorted) = }")+ print(f"{heap_sort(unsorted) = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/sorts/heap_sort.py |
Generate docstrings for each module | import re
"""
general info:
https://en.wikipedia.org/wiki/Naming_convention_(programming)#Python_and_Ruby
pascal case [ an upper Camel Case ]: https://en.wikipedia.org/wiki/Camel_case
camel case: https://en.wikipedia.org/wiki/Camel_case
kebab case [ can be found in general info ]:
https://en.wikipedia.org/wiki/Naming_convention_(programming)#Python_and_Ruby
snake case: https://en.wikipedia.org/wiki/Snake_case
"""
# assistant functions
def split_input(str_: str) -> list:
return [char.split() for char in re.split(r"[^ a-z A-Z 0-9 \s]", str_)]
def to_simple_case(str_: str) -> str:
string_split = split_input(str_)
return "".join(
["".join([char.capitalize() for char in sub_str]) for sub_str in string_split]
)
def to_complex_case(text: str, upper: bool, separator: str) -> str:
try:
string_split = split_input(text)
if upper:
res_str = "".join(
[
separator.join([char.upper() for char in sub_str])
for sub_str in string_split
]
)
else:
res_str = "".join(
[
separator.join([char.lower() for char in sub_str])
for sub_str in string_split
]
)
return res_str
except IndexError:
return "not valid string"
# main content
def to_pascal_case(text: str) -> str:
return to_simple_case(text)
def to_camel_case(text: str) -> str:
try:
res_str = to_simple_case(text)
return res_str[0].lower() + res_str[1:]
except IndexError:
return "not valid string"
def to_snake_case(text: str, upper: bool) -> str:
return to_complex_case(text, upper, "_")
def to_kebab_case(text: str, upper: bool) -> str:
return to_complex_case(text, upper, "-")
if __name__ == "__main__":
__import__("doctest").testmod() | --- +++ @@ -17,10 +17,24 @@
# assistant functions
def split_input(str_: str) -> list:
+ """
+ >>> split_input("one two 31235three4four")
+ [['one', 'two', '31235three4four']]
+ """
return [char.split() for char in re.split(r"[^ a-z A-Z 0-9 \s]", str_)]
def to_simple_case(str_: str) -> str:
+ """
+ >>> to_simple_case("one two 31235three4four")
+ 'OneTwo31235three4four'
+ >>> to_simple_case("This should be combined")
+ 'ThisShouldBeCombined'
+ >>> to_simple_case("The first letters are capitalized, then string is merged")
+ 'TheFirstLettersAreCapitalizedThenStringIsMerged'
+ >>> to_simple_case("special characters :, ', %, ^, $, are ignored")
+ 'SpecialCharactersAreIgnored'
+ """
string_split = split_input(str_)
return "".join(
["".join([char.capitalize() for char in sub_str]) for sub_str in string_split]
@@ -28,6 +42,20 @@
def to_complex_case(text: str, upper: bool, separator: str) -> str:
+ """
+ Returns the string concatenated with the delimiter we provide.
+
+ Parameters:
+ @text: The string on which we want to perform operation
+ @upper: Boolean value to determine whether we want capitalized result or not
+ @separator: The delimiter with which we want to concatenate words
+
+ Examples:
+ >>> to_complex_case("one two 31235three4four", True, "_")
+ 'ONE_TWO_31235THREE4FOUR'
+ >>> to_complex_case("one two 31235three4four", False, "-")
+ 'one-two-31235three4four'
+ """
try:
string_split = split_input(text)
if upper:
@@ -51,10 +79,18 @@
# main content
def to_pascal_case(text: str) -> str:
+ """
+ >>> to_pascal_case("one two 31235three4four")
+ 'OneTwo31235three4four'
+ """
return to_simple_case(text)
def to_camel_case(text: str) -> str:
+ """
+ >>> to_camel_case("one two 31235three4four")
+ 'oneTwo31235three4four'
+ """
try:
res_str = to_simple_case(text)
return res_str[0].lower() + res_str[1:]
@@ -63,12 +99,24 @@
def to_snake_case(text: str, upper: bool) -> str:
+ """
+ >>> to_snake_case("one two 31235three4four", True)
+ 'ONE_TWO_31235THREE4FOUR'
+ >>> to_snake_case("one two 31235three4four", False)
+ 'one_two_31235three4four'
+ """
return to_complex_case(text, upper, "_")
def to_kebab_case(text: str, upper: bool) -> str:
+ """
+ >>> to_kebab_case("one two 31235three4four", True)
+ 'ONE-TWO-31235THREE4FOUR'
+ >>> to_kebab_case("one two 31235three4four", False)
+ 'one-two-31235three4four'
+ """
return to_complex_case(text, upper, "-")
if __name__ == "__main__":
- __import__("doctest").testmod()+ __import__("doctest").testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/string_switch_case.py |
Add docstrings including usage examples | def to_title_case(word: str) -> str:
"""
Convert the first character to uppercase if it's lowercase
"""
if "a" <= word[0] <= "z":
word = chr(ord(word[0]) - 32) + word[1:]
"""
Convert the remaining characters to lowercase if they are uppercase
"""
for i in range(1, len(word)):
if "A" <= word[i] <= "Z":
word = word[:i] + chr(ord(word[i]) + 32) + word[i + 1 :]
return word
def sentence_to_title_case(input_str: str) -> str:
return " ".join(to_title_case(word) for word in input_str.split())
if __name__ == "__main__":
from doctest import testmod
testmod() | --- +++ @@ -1,27 +1,57 @@-def to_title_case(word: str) -> str:
-
- """
- Convert the first character to uppercase if it's lowercase
- """
- if "a" <= word[0] <= "z":
- word = chr(ord(word[0]) - 32) + word[1:]
-
- """
- Convert the remaining characters to lowercase if they are uppercase
- """
- for i in range(1, len(word)):
- if "A" <= word[i] <= "Z":
- word = word[:i] + chr(ord(word[i]) + 32) + word[i + 1 :]
-
- return word
-
-
-def sentence_to_title_case(input_str: str) -> str:
-
- return " ".join(to_title_case(word) for word in input_str.split())
-
-
-if __name__ == "__main__":
- from doctest import testmod
-
- testmod()+def to_title_case(word: str) -> str:
+ """
+ Converts a string to capitalized case, preserving the input as is
+
+ >>> to_title_case("Aakash")
+ 'Aakash'
+
+ >>> to_title_case("aakash")
+ 'Aakash'
+
+ >>> to_title_case("AAKASH")
+ 'Aakash'
+
+ >>> to_title_case("aAkAsH")
+ 'Aakash'
+ """
+
+ """
+ Convert the first character to uppercase if it's lowercase
+ """
+ if "a" <= word[0] <= "z":
+ word = chr(ord(word[0]) - 32) + word[1:]
+
+ """
+ Convert the remaining characters to lowercase if they are uppercase
+ """
+ for i in range(1, len(word)):
+ if "A" <= word[i] <= "Z":
+ word = word[:i] + chr(ord(word[i]) + 32) + word[i + 1 :]
+
+ return word
+
+
+def sentence_to_title_case(input_str: str) -> str:
+ """
+ Converts a string to title case, preserving the input as is
+
+ >>> sentence_to_title_case("Aakash Giri")
+ 'Aakash Giri'
+
+ >>> sentence_to_title_case("aakash giri")
+ 'Aakash Giri'
+
+ >>> sentence_to_title_case("AAKASH GIRI")
+ 'Aakash Giri'
+
+ >>> sentence_to_title_case("aAkAsH gIrI")
+ 'Aakash Giri'
+ """
+
+ return " ".join(to_title_case(word) for word in input_str.split())
+
+
+if __name__ == "__main__":
+ from doctest import testmod
+
+ testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/title.py |
Can you add docstrings to this Python file? |
def match_pattern(input_string: str, pattern: str) -> bool:
len_string = len(input_string) + 1
len_pattern = len(pattern) + 1
# dp is a 2d matrix where dp[i][j] denotes whether prefix string of
# length i of input_string matches with prefix string of length j of
# given pattern.
# "dp" stands for dynamic programming.
dp = [[0 for i in range(len_pattern)] for j in range(len_string)]
# since string of zero length match pattern of zero length
dp[0][0] = 1
# since pattern of zero length will never match with string of non-zero length
for i in range(1, len_string):
dp[i][0] = 0
# since string of zero length will match with pattern where there
# is at least one * alternatively
for j in range(1, len_pattern):
dp[0][j] = dp[0][j - 2] if pattern[j - 1] == "*" else 0
# now using bottom-up approach to find for all remaining lengths
for i in range(1, len_string):
for j in range(1, len_pattern):
if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".":
dp[i][j] = dp[i - 1][j - 1]
elif pattern[j - 1] == "*":
if dp[i][j - 2] == 1:
dp[i][j] = 1
elif pattern[j - 2] in (input_string[i - 1], "."):
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = 0
else:
dp[i][j] = 0
return bool(dp[-1][-1])
if __name__ == "__main__":
import doctest
doctest.testmod()
# inputing the strings
# input_string = input("input a string :")
# pattern = input("input a pattern :")
input_string = "aab"
pattern = "c*a*b"
# using function to check whether given string matches the given pattern
if match_pattern(input_string, pattern):
print(f"{input_string} matches the given pattern {pattern}")
else:
print(f"{input_string} does not match with the given pattern {pattern}") | --- +++ @@ -1,6 +1,58 @@+"""
+Implementation of regular expression matching with support for '.' and '*'.
+'.' Matches any single character.
+'*' Matches zero or more of the preceding element.
+The matching should cover the entire input string (not partial).
+
+"""
def match_pattern(input_string: str, pattern: str) -> bool:
+ """
+ uses bottom-up dynamic programming solution for matching the input
+ string with a given pattern.
+
+ Runtime: O(len(input_string)*len(pattern))
+
+ Arguments
+ --------
+ input_string: str, any string which should be compared with the pattern
+ pattern: str, the string that represents a pattern and may contain
+ '.' for single character matches and '*' for zero or more of preceding character
+ matches
+
+ Note
+ ----
+ the pattern cannot start with a '*',
+ because there should be at least one character before *
+
+ Returns
+ -------
+ A Boolean denoting whether the given string follows the pattern
+
+ Examples
+ -------
+ >>> match_pattern("aab", "c*a*b")
+ True
+ >>> match_pattern("dabc", "*abc")
+ False
+ >>> match_pattern("aaa", "aa")
+ False
+ >>> match_pattern("aaa", "a.a")
+ True
+ >>> match_pattern("aaab", "aa*")
+ False
+ >>> match_pattern("aaab", ".*")
+ True
+ >>> match_pattern("a", "bbbb")
+ False
+ >>> match_pattern("", "bbbb")
+ False
+ >>> match_pattern("a", "")
+ False
+ >>> match_pattern("", "")
+ True
+ """
len_string = len(input_string) + 1
len_pattern = len(pattern) + 1
@@ -57,4 +109,4 @@ if match_pattern(input_string, pattern):
print(f"{input_string} matches the given pattern {pattern}")
else:
- print(f"{input_string} does not match with the given pattern {pattern}")+ print(f"{input_string} does not match with the given pattern {pattern}")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/wildcard_pattern_matching.py |
Write clean docstrings for readability |
def z_function(input_str: str) -> list[int]:
z_result = [0 for i in range(len(input_str))]
# initialize interval's left pointer and right pointer
left_pointer, right_pointer = 0, 0
for i in range(1, len(input_str)):
# case when current index is inside the interval
if i <= right_pointer:
min_edge = min(right_pointer - i + 1, z_result[i - left_pointer])
z_result[i] = min_edge
while go_next(i, z_result, input_str):
z_result[i] += 1
# if new index's result gives us more right interval,
# we've to update left_pointer and right_pointer
if i + z_result[i] - 1 > right_pointer:
left_pointer, right_pointer = i, i + z_result[i] - 1
return z_result
def go_next(i: int, z_result: list[int], s: str) -> bool:
return i + z_result[i] < len(s) and s[z_result[i]] == s[i + z_result[i]]
def find_pattern(pattern: str, input_str: str) -> int:
answer = 0
# concatenate 'pattern' and 'input_str' and call z_function
# with concatenated string
z_result = z_function(pattern + input_str)
for val in z_result:
# if value is greater then length of the pattern string
# that means this index is starting position of substring
# which is equal to pattern string
if val >= len(pattern):
answer += 1
return answer
if __name__ == "__main__":
import doctest
doctest.testmod() | --- +++ @@ -1,6 +1,32 @@+"""
+https://cp-algorithms.com/string/z-function.html
+
+Z-function or Z algorithm
+
+Efficient algorithm for pattern occurrence in a string
+
+Time Complexity: O(n) - where n is the length of the string
+
+"""
def z_function(input_str: str) -> list[int]:
+ """
+ For the given string this function computes value for each index,
+ which represents the maximal length substring starting from the index
+ and is the same as the prefix of the same size
+
+ e.x. for string 'abab' for second index value would be 2
+
+ For the value of the first element the algorithm always returns 0
+
+ >>> z_function("abracadabra")
+ [0, 0, 0, 1, 0, 1, 0, 4, 0, 0, 1]
+ >>> z_function("aaaa")
+ [0, 3, 2, 1]
+ >>> z_function("zxxzxxz")
+ [0, 0, 0, 4, 0, 0, 1]
+ """
z_result = [0 for i in range(len(input_str))]
# initialize interval's left pointer and right pointer
@@ -24,10 +50,25 @@
def go_next(i: int, z_result: list[int], s: str) -> bool:
+ """
+ Check if we have to move forward to the next characters or not
+ """
return i + z_result[i] < len(s) and s[z_result[i]] == s[i + z_result[i]]
def find_pattern(pattern: str, input_str: str) -> int:
+ """
+ Example of using z-function for pattern occurrence
+ Given function returns the number of times 'pattern'
+ appears in 'input_str' as a substring
+
+ >>> find_pattern("abr", "abracadabra")
+ 2
+ >>> find_pattern("a", "aaaa")
+ 4
+ >>> find_pattern("xz", "zxxzxxz")
+ 2
+ """
answer = 0
# concatenate 'pattern' and 'input_str' and call z_function
# with concatenated string
@@ -46,4 +87,4 @@ if __name__ == "__main__":
import doctest
- doctest.testmod()+ doctest.testmod()
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/strings/z_function.py |
Create simple docstrings for beginners |
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
import os
import httpx
URL_BASE = "https://www.amdoren.com/api/currency.php"
# Currency and their description
list_of_currencies = """
AED United Arab Emirates Dirham
AFN Afghan Afghani
ALL Albanian Lek
AMD Armenian Dram
ANG Netherlands Antillean Guilder
AOA Angolan Kwanza
ARS Argentine Peso
AUD Australian Dollar
AWG Aruban Florin
AZN Azerbaijani Manat
BAM Bosnia & Herzegovina Convertible Mark
BBD Barbadian Dollar
BDT Bangladeshi Taka
BGN Bulgarian Lev
BHD Bahraini Dinar
BIF Burundian Franc
BMD Bermudian Dollar
BND Brunei Dollar
BOB Bolivian Boliviano
BRL Brazilian Real
BSD Bahamian Dollar
BTN Bhutanese Ngultrum
BWP Botswana Pula
BYN Belarus Ruble
BZD Belize Dollar
CAD Canadian Dollar
CDF Congolese Franc
CHF Swiss Franc
CLP Chilean Peso
CNY Chinese Yuan
COP Colombian Peso
CRC Costa Rican Colon
CUC Cuban Convertible Peso
CVE Cape Verdean Escudo
CZK Czech Republic Koruna
DJF Djiboutian Franc
DKK Danish Krone
DOP Dominican Peso
DZD Algerian Dinar
EGP Egyptian Pound
ERN Eritrean Nakfa
ETB Ethiopian Birr
EUR Euro
FJD Fiji Dollar
GBP British Pound Sterling
GEL Georgian Lari
GHS Ghanaian Cedi
GIP Gibraltar Pound
GMD Gambian Dalasi
GNF Guinea Franc
GTQ Guatemalan Quetzal
GYD Guyanaese Dollar
HKD Hong Kong Dollar
HNL Honduran Lempira
HRK Croatian Kuna
HTG Haiti Gourde
HUF Hungarian Forint
IDR Indonesian Rupiah
ILS Israeli Shekel
INR Indian Rupee
IQD Iraqi Dinar
IRR Iranian Rial
ISK Icelandic Krona
JMD Jamaican Dollar
JOD Jordanian Dinar
JPY Japanese Yen
KES Kenyan Shilling
KGS Kyrgystani Som
KHR Cambodian Riel
KMF Comorian Franc
KPW North Korean Won
KRW South Korean Won
KWD Kuwaiti Dinar
KYD Cayman Islands Dollar
KZT Kazakhstan Tenge
LAK Laotian Kip
LBP Lebanese Pound
LKR Sri Lankan Rupee
LRD Liberian Dollar
LSL Lesotho Loti
LYD Libyan Dinar
MAD Moroccan Dirham
MDL Moldovan Leu
MGA Malagasy Ariary
MKD Macedonian Denar
MMK Myanma Kyat
MNT Mongolian Tugrik
MOP Macau Pataca
MRO Mauritanian Ouguiya
MUR Mauritian Rupee
MVR Maldivian Rufiyaa
MWK Malawi Kwacha
MXN Mexican Peso
MYR Malaysian Ringgit
MZN Mozambican Metical
NAD Namibian Dollar
NGN Nigerian Naira
NIO Nicaragua Cordoba
NOK Norwegian Krone
NPR Nepalese Rupee
NZD New Zealand Dollar
OMR Omani Rial
PAB Panamanian Balboa
PEN Peruvian Nuevo Sol
PGK Papua New Guinean Kina
PHP Philippine Peso
PKR Pakistani Rupee
PLN Polish Zloty
PYG Paraguayan Guarani
QAR Qatari Riyal
RON Romanian Leu
RSD Serbian Dinar
RUB Russian Ruble
RWF Rwanda Franc
SAR Saudi Riyal
SBD Solomon Islands Dollar
SCR Seychellois Rupee
SDG Sudanese Pound
SEK Swedish Krona
SGD Singapore Dollar
SHP Saint Helena Pound
SLL Sierra Leonean Leone
SOS Somali Shilling
SRD Surinamese Dollar
SSP South Sudanese Pound
STD Sao Tome and Principe Dobra
SYP Syrian Pound
SZL Swazi Lilangeni
THB Thai Baht
TJS Tajikistan Somoni
TMT Turkmenistani Manat
TND Tunisian Dinar
TOP Tonga Paanga
TRY Turkish Lira
TTD Trinidad and Tobago Dollar
TWD New Taiwan Dollar
TZS Tanzanian Shilling
UAH Ukrainian Hryvnia
UGX Ugandan Shilling
USD United States Dollar
UYU Uruguayan Peso
UZS Uzbekistan Som
VEF Venezuelan Bolivar
VND Vietnamese Dong
VUV Vanuatu Vatu
WST Samoan Tala
XAF Central African CFA franc
XCD East Caribbean Dollar
XOF West African CFA franc
XPF CFP Franc
YER Yemeni Rial
ZAR South African Rand
ZMW Zambian Kwacha
"""
def convert_currency(
from_: str = "USD", to: str = "INR", amount: float = 1.0, api_key: str = ""
) -> str:
# Instead of manually generating parameters
params = locals()
# from is a reserved keyword
params["from"] = params.pop("from_")
res = httpx.get(URL_BASE, params=params, timeout=10).json()
return str(res["amount"]) if res["error"] == 0 else res["error_message"]
if __name__ == "__main__":
TESTING = os.getenv("CI", "")
API_KEY = os.getenv("AMDOREN_API_KEY", "")
if not API_KEY and not TESTING:
raise KeyError(
"API key must be provided in the 'AMDOREN_API_KEY' environment variable."
)
print(
convert_currency(
input("Enter from currency: ").strip(),
input("Enter to currency: ").strip(),
float(input("Enter the amount: ").strip()),
API_KEY,
)
) | --- +++ @@ -1,3 +1,7 @@+"""
+This is used to convert the currency using the Amdoren Currency API
+https://www.amdoren.com
+"""
# /// script
# requires-python = ">=3.13"
@@ -174,6 +178,7 @@ def convert_currency(
from_: str = "USD", to: str = "INR", amount: float = 1.0, api_key: str = ""
) -> str:
+ """https://www.amdoren.com/currency-api/"""
# Instead of manually generating parameters
params = locals()
# from is a reserved keyword
@@ -198,4 +203,4 @@ float(input("Enter the amount: ").strip()),
API_KEY,
)
- )+ )
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/currency_converter.py |
Can you add docstrings to this Python file? |
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
from __future__ import annotations
__author__ = "Muhammad Umer Farooq"
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "Muhammad Umer Farooq"
__email__ = "contact@muhammadumerfarooq.me"
__status__ = "Alpha"
import re
from html.parser import HTMLParser
from urllib import parse
import httpx
class Parser(HTMLParser):
def __init__(self, domain: str) -> None:
super().__init__()
self.urls: list[str] = []
self.domain = domain
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
# Only parse the 'anchor' tag.
if tag == "a":
# Check the list of defined attributes.
for name, value in attrs:
# If href is defined, not empty nor # print it and not already in urls.
if name == "href" and value not in (*self.urls, "", "#"):
url = parse.urljoin(self.domain, value)
self.urls.append(url)
# Get main domain name (example.com)
def get_domain_name(url: str) -> str:
return ".".join(get_sub_domain_name(url).split(".")[-2:])
# Get sub domain name (sub.example.com)
def get_sub_domain_name(url: str) -> str:
return parse.urlparse(url).netloc
def emails_from_url(url: str = "https://github.com") -> list[str]:
# Get the base domain from the url
domain = get_domain_name(url)
# Initialize the parser
parser = Parser(domain)
try:
# Open URL
r = httpx.get(url, timeout=10, follow_redirects=True)
# pass the raw HTML to the parser to get links
parser.feed(r.text)
# Get links and loop through
valid_emails = set()
for link in parser.urls:
# open URL.
# Check if the link is already absolute
if not link.startswith("http://") and not link.startswith("https://"):
# Prepend protocol only if link starts with domain, normalize otherwise
if link.startswith(domain):
link = f"https://{link}"
else:
link = parse.urljoin(f"https://{domain}", link)
try:
read = httpx.get(link, timeout=10, follow_redirects=True)
# Get the valid email.
emails = re.findall("[a-zA-Z0-9]+@" + domain, read.text)
# If not in list then append it.
for email in emails:
valid_emails.add(email)
except ValueError:
pass
except ValueError:
raise SystemExit(1)
# Finally return a sorted list of email addresses with no duplicates.
return sorted(valid_emails)
if __name__ == "__main__":
emails = emails_from_url("https://github.com")
print(f"{len(emails)} emails found:")
print("\n".join(sorted(emails))) | --- +++ @@ -1,3 +1,4 @@+"""Get the site emails from URL."""
# /// script
# requires-python = ">=3.13"
@@ -29,6 +30,9 @@ self.domain = domain
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ """
+ This function parse html to take takes url from tags
+ """
# Only parse the 'anchor' tag.
if tag == "a":
# Check the list of defined attributes.
@@ -41,15 +45,32 @@
# Get main domain name (example.com)
def get_domain_name(url: str) -> str:
+ """
+ This function get the main domain name
+
+ >>> get_domain_name("https://a.b.c.d/e/f?g=h,i=j#k")
+ 'c.d'
+ >>> get_domain_name("Not a URL!")
+ ''
+ """
return ".".join(get_sub_domain_name(url).split(".")[-2:])
# Get sub domain name (sub.example.com)
def get_sub_domain_name(url: str) -> str:
+ """
+ >>> get_sub_domain_name("https://a.b.c.d/e/f?g=h,i=j#k")
+ 'a.b.c.d'
+ >>> get_sub_domain_name("Not a URL!")
+ ''
+ """
return parse.urlparse(url).netloc
def emails_from_url(url: str = "https://github.com") -> list[str]:
+ """
+ This function takes url and return all valid urls
+ """
# Get the base domain from the url
domain = get_domain_name(url)
@@ -93,4 +114,4 @@ if __name__ == "__main__":
emails = emails_from_url("https://github.com")
print(f"{len(emails)} emails found:")
- print("\n".join(sorted(emails)))+ print("\n".join(sorted(emails)))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/emails_from_url.py |
Document functions with detailed explanations | #!/usr/bin/env python3
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
from __future__ import annotations
import os
from typing import Any
import httpx
BASE_URL = "https://api.github.com"
# https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user
AUTHENTICATED_USER_ENDPOINT = BASE_URL + "/user"
# https://github.com/settings/tokens
USER_TOKEN = os.environ.get("USER_TOKEN", "")
def fetch_github_info(auth_token: str) -> dict[Any, Any]:
headers = {
"Authorization": f"token {auth_token}",
"Accept": "application/vnd.github.v3+json",
}
return httpx.get(AUTHENTICATED_USER_ENDPOINT, headers=headers, timeout=10).json()
if __name__ == "__main__": # pragma: no cover
if USER_TOKEN:
for key, value in fetch_github_info(USER_TOKEN).items():
print(f"{key}: {value}")
else:
raise ValueError("'USER_TOKEN' field cannot be empty.") | --- +++ @@ -1,4 +1,22 @@ #!/usr/bin/env python3
+"""
+Created by sarathkaul on 14/11/19
+Updated by lawric1 on 24/11/20
+
+Authentication will be made via access token.
+To generate your personal access token visit https://github.com/settings/tokens.
+
+NOTE:
+Never hardcode any credential information in the code. Always use an environment
+file to store the private information and use the `os` module to get the information
+during runtime.
+
+Create a ".env" file in the root directory and write these two lines in that file
+with your token::
+
+#!/usr/bin/env bash
+export USER_TOKEN=""
+"""
# /// script
# requires-python = ">=3.13"
@@ -24,6 +42,9 @@
def fetch_github_info(auth_token: str) -> dict[Any, Any]:
+ """
+ Fetch GitHub info of a user using the httpx module
+ """
headers = {
"Authorization": f"token {auth_token}",
"Accept": "application/vnd.github.v3+json",
@@ -36,4 +57,4 @@ for key, value in fetch_github_info(USER_TOKEN).items():
print(f"{key}: {value}")
else:
- raise ValueError("'USER_TOKEN' field cannot be empty.")+ raise ValueError("'USER_TOKEN' field cannot be empty.")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/fetch_github_info.py |
Add docstrings to make code maintainable |
import httpx
from bs4 import BeautifulSoup
BASE_URL = "https://www.wellrx.com/prescriptions/{}/{}/?freshSearch=true"
def fetch_pharmacy_and_price_list(drug_name: str, zip_code: str) -> list | None:
try:
# Has user provided both inputs?
if not drug_name or not zip_code:
return None
request_url = BASE_URL.format(drug_name, zip_code)
response = httpx.get(request_url, timeout=10).raise_for_status()
# Scrape the data using bs4
soup = BeautifulSoup(response.text, "html.parser")
# This list will store the name and price.
pharmacy_price_list = []
# Fetch all the grids that contain the items.
grid_list = soup.find_all("div", {"class": "grid-x pharmCard"})
if grid_list and len(grid_list) > 0:
for grid in grid_list:
# Get the pharmacy price.
pharmacy_name = grid.find("p", {"class": "list-title"}).text
# Get the price of the drug.
price = grid.find("span", {"p", "price price-large"}).text
pharmacy_price_list.append(
{
"pharmacy_name": pharmacy_name,
"price": price,
}
)
return pharmacy_price_list
except (httpx.HTTPError, ValueError):
return None
if __name__ == "__main__":
# Enter a drug name and a zip code
drug_name = input("Enter drug name: ").strip()
zip_code = input("Enter zip code: ").strip()
pharmacy_price_list: list | None = fetch_pharmacy_and_price_list(
drug_name, zip_code
)
if pharmacy_price_list:
print(f"\nSearch results for {drug_name} at location {zip_code}:")
for pharmacy_price in pharmacy_price_list:
name = pharmacy_price["pharmacy_name"]
price = pharmacy_price["price"]
print(f"Pharmacy: {name} Price: {price}")
else:
print(f"No results found for {drug_name}") | --- +++ @@ -1,3 +1,9 @@+"""
+
+Scrape the price and pharmacy name for a prescription drug from rx site
+after providing the drug name and zipcode.
+
+"""
import httpx
from bs4 import BeautifulSoup
@@ -6,6 +12,27 @@
def fetch_pharmacy_and_price_list(drug_name: str, zip_code: str) -> list | None:
+ """[summary]
+
+ This function will take input of drug name and zipcode,
+ then request to the BASE_URL site.
+ Get the page data and scrape it to generate the
+ list of the lowest prices for the prescription drug.
+
+ Args:
+ drug_name (str): [Drug name]
+ zip_code(str): [Zip code]
+
+ Returns:
+ list: [List of pharmacy name and price]
+
+ >>> print(fetch_pharmacy_and_price_list(None, None))
+ None
+ >>> print(fetch_pharmacy_and_price_list(None, 30303))
+ None
+ >>> print(fetch_pharmacy_and_price_list("eliquis", None))
+ None
+ """
try:
# Has user provided both inputs?
@@ -61,4 +88,4 @@
print(f"Pharmacy: {name} Price: {price}")
else:
- print(f"No results found for {drug_name}")+ print(f"No results found for {drug_name}")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/fetch_well_rx_price.py |
Add docstrings following best practices |
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# "rich",
# ]
# ///
from datetime import UTC, date, datetime
import httpx
from rich import box
from rich import console as rich_console
from rich import table as rich_table
LIMIT = 10
TODAY = datetime.now(tz=UTC)
API_URL = (
"https://www.forbes.com/forbesapi/person/rtb/0/position/true.json"
"?fields=personName,gender,source,countryOfCitizenship,birthDate,finalWorth"
f"&limit={LIMIT}"
)
def years_old(birth_timestamp: int, today: date | None = None) -> int:
today = today or TODAY.date()
birth_date = datetime.fromtimestamp(birth_timestamp, tz=UTC).date()
return (today.year - birth_date.year) - (
(today.month, today.day) < (birth_date.month, birth_date.day)
)
def get_forbes_real_time_billionaires() -> list[dict[str, int | str]]:
response_json = httpx.get(API_URL, timeout=10).json()
return [
{
"Name": person["personName"],
"Source": person["source"],
"Country": person["countryOfCitizenship"],
"Gender": person["gender"],
"Worth ($)": f"{person['finalWorth'] / 1000:.1f} Billion",
"Age": str(years_old(person["birthDate"] / 1000)),
}
for person in response_json["personList"]["personsLists"]
]
def display_billionaires(forbes_billionaires: list[dict[str, int | str]]) -> None:
table = rich_table.Table(
title=f"Forbes Top {LIMIT} Real-Time Billionaires at {TODAY:%Y-%m-%d %H:%M}",
style="green",
highlight=True,
box=box.SQUARE,
)
for key in forbes_billionaires[0]:
table.add_column(key)
for billionaire in forbes_billionaires:
table.add_row(*billionaire.values())
rich_console.Console().print(table)
if __name__ == "__main__":
from doctest import testmod
testmod()
display_billionaires(get_forbes_real_time_billionaires()) | --- +++ @@ -1,3 +1,7 @@+"""
+CAUTION: You may get a json.decoding error.
+This works for some of us but fails for others.
+"""
# /// script
# requires-python = ">=3.13"
@@ -24,6 +28,29 @@
def years_old(birth_timestamp: int, today: date | None = None) -> int:
+ """
+ Calculate the age in years based on the given birth date. Only the year, month,
+ and day are used in the calculation. The time of day is ignored.
+
+ Args:
+ birth_timestamp: The date of birth.
+ today: (useful for writing tests) or if None then datetime.date.today().
+
+ Returns:
+ int: The age in years.
+
+ Examples:
+ >>> today = date(2024, 1, 12)
+ >>> years_old(birth_timestamp=datetime(1959, 11, 20).timestamp(), today=today)
+ 64
+ >>> years_old(birth_timestamp=datetime(1970, 2, 13).timestamp(), today=today)
+ 53
+ >>> all(
+ ... years_old(datetime(today.year - i, 1, 12).timestamp(), today=today) == i
+ ... for i in range(1, 111)
+ ... )
+ True
+ """
today = today or TODAY.date()
birth_date = datetime.fromtimestamp(birth_timestamp, tz=UTC).date()
return (today.year - birth_date.year) - (
@@ -32,6 +59,12 @@
def get_forbes_real_time_billionaires() -> list[dict[str, int | str]]:
+ """
+ Get the top 10 real-time billionaires using Forbes API.
+
+ Returns:
+ List of top 10 realtime billionaires data.
+ """
response_json = httpx.get(API_URL, timeout=10).json()
return [
{
@@ -47,6 +80,12 @@
def display_billionaires(forbes_billionaires: list[dict[str, int | str]]) -> None:
+ """
+ Display Forbes real-time billionaires in a rich table.
+
+ Args:
+ forbes_billionaires (list): Forbes top 10 real-time billionaires
+ """
table = rich_table.Table(
title=f"Forbes Top {LIMIT} Real-Time Billionaires at {TODAY:%Y-%m-%d %H:%M}",
@@ -67,4 +106,4 @@ from doctest import testmod
testmod()
- display_billionaires(get_forbes_real_time_billionaires())+ display_billionaires(get_forbes_real_time_billionaires())
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/get_top_billionaires.py |
Generate docstrings for each module | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "fake-useragent",
# "httpx",
# ]
# ///
import os
import httpx
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
headers = {"UserAgent": UserAgent().random}
URL = "https://www.mywaifulist.moe/random"
def save_image(image_url: str, image_title: str) -> None:
image = httpx.get(image_url, headers=headers, timeout=10)
with open(image_title, "wb") as file:
file.write(image.content)
def random_anime_character() -> tuple[str, str, str]:
soup = BeautifulSoup(
httpx.get(URL, headers=headers, timeout=10).text, "html.parser"
)
title = soup.find("meta", attrs={"property": "og:title"}).attrs["content"]
image_url = soup.find("meta", attrs={"property": "og:image"}).attrs["content"]
description = soup.find("p", id="description").get_text()
_, image_extension = os.path.splitext(os.path.basename(image_url))
image_title = title.strip().replace(" ", "_")
image_title = f"{image_title}{image_extension}"
save_image(image_url, image_title)
return (title, description, image_title)
if __name__ == "__main__":
title, desc, image_title = random_anime_character()
print(f"{title}\n\n{desc}\n\nImage saved : {image_title}") | --- +++ @@ -18,12 +18,18 @@
def save_image(image_url: str, image_title: str) -> None:
+ """
+ Saves the image of anime character
+ """
image = httpx.get(image_url, headers=headers, timeout=10)
with open(image_title, "wb") as file:
file.write(image.content)
def random_anime_character() -> tuple[str, str, str]:
+ """
+ Returns the Title, Description, and Image Title of a random anime character .
+ """
soup = BeautifulSoup(
httpx.get(URL, headers=headers, timeout=10).text, "html.parser"
)
@@ -39,4 +45,4 @@
if __name__ == "__main__":
title, desc, image_title = random_anime_character()
- print(f"{title}\n\n{desc}\n\nImage saved : {image_title}")+ print(f"{title}\n\n{desc}\n\nImage saved : {image_title}")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/random_anime_character.py |
Add docstrings to improve collaboration | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "fake-useragent",
# "httpx",
# ]
# ///
import httpx
from bs4 import BeautifulSoup, NavigableString, Tag
from fake_useragent import UserAgent
BASE_URL = "https://ww7.gogoanime2.org"
def search_scraper(anime_name: str) -> list:
# concat the name to form the search url.
search_url = f"{BASE_URL}/search?keyword={anime_name}"
response = httpx.get(
search_url, headers={"UserAgent": UserAgent().chrome}, timeout=10
) # request the url.
# Is the response ok?
response.raise_for_status()
# parse with soup.
soup = BeautifulSoup(response.text, "html.parser")
# get list of anime
anime_ul = soup.find("ul", {"class": "items"})
if anime_ul is None or isinstance(anime_ul, NavigableString):
msg = f"Could not find and anime with name {anime_name}"
raise ValueError(msg)
anime_li = anime_ul.children
# for each anime, insert to list. the name and url.
anime_list = []
for anime in anime_li:
if isinstance(anime, Tag):
anime_url = anime.find("a")
if anime_url is None or isinstance(anime_url, NavigableString):
continue
anime_title = anime.find("a")
if anime_title is None or isinstance(anime_title, NavigableString):
continue
anime_list.append({"title": anime_title["title"], "url": anime_url["href"]})
return anime_list
def search_anime_episode_list(episode_endpoint: str) -> list:
request_url = f"{BASE_URL}{episode_endpoint}"
response = httpx.get(
url=request_url, headers={"UserAgent": UserAgent().chrome}, timeout=10
)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
# With this id. get the episode list.
episode_page_ul = soup.find("ul", {"id": "episode_related"})
if episode_page_ul is None or isinstance(episode_page_ul, NavigableString):
msg = f"Could not find any anime eposiodes with name {anime_name}"
raise ValueError(msg)
episode_page_li = episode_page_ul.children
episode_list = []
for episode in episode_page_li:
if isinstance(episode, Tag):
url = episode.find("a")
if url is None or isinstance(url, NavigableString):
continue
title = episode.find("div", {"class": "name"})
if title is None or isinstance(title, NavigableString):
continue
episode_list.append(
{"title": title.text.replace(" ", ""), "url": url["href"]}
)
return episode_list
def get_anime_episode(episode_endpoint: str) -> list:
episode_page_url = f"{BASE_URL}{episode_endpoint}"
response = httpx.get(
url=episode_page_url, headers={"User-Agent": UserAgent().chrome}, timeout=10
)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
url = soup.find("iframe", {"id": "playerframe"})
if url is None or isinstance(url, NavigableString):
msg = f"Could not find url and download url from {episode_endpoint}"
raise RuntimeError(msg)
episode_url = url["src"]
if not isinstance(episode_url, str):
msg = f"Could not find url and download url from {episode_endpoint}"
raise RuntimeError(msg)
download_url = episode_url.replace("/embed/", "/playlist/") + ".m3u8"
return [f"{BASE_URL}{episode_url}", f"{BASE_URL}{download_url}"]
if __name__ == "__main__":
anime_name = input("Enter anime name: ").strip()
anime_list = search_scraper(anime_name)
print("\n")
if len(anime_list) == 0:
print("No anime found with this name")
else:
print(f"Found {len(anime_list)} results: ")
for i, anime in enumerate(anime_list):
anime_title = anime["title"]
print(f"{i + 1}. {anime_title}")
anime_choice = int(input("\nPlease choose from the following list: ").strip())
chosen_anime = anime_list[anime_choice - 1]
print(f"You chose {chosen_anime['title']}. Searching for episodes...")
episode_list = search_anime_episode_list(chosen_anime["url"])
if len(episode_list) == 0:
print("No episode found for this anime")
else:
print(f"Found {len(episode_list)} results: ")
for i, episode in enumerate(episode_list):
print(f"{i + 1}. {episode['title']}")
episode_choice = int(input("\nChoose an episode by serial no: ").strip())
chosen_episode = episode_list[episode_choice - 1]
print(f"You chose {chosen_episode['title']}. Searching...")
episode_url, download_url = get_anime_episode(chosen_episode["url"])
print(f"\nTo watch, ctrl+click on {episode_url}.")
print(f"To download, ctrl+click on {download_url}.") | --- +++ @@ -15,6 +15,23 @@
def search_scraper(anime_name: str) -> list:
+ """[summary]
+
+ Take an url and
+ return list of anime after scraping the site.
+
+ >>> type(search_scraper("demon_slayer"))
+ <class 'list'>
+
+ Args:
+ anime_name (str): [Name of anime]
+
+ Raises:
+ e: [Raises exception on failure]
+
+ Returns:
+ [list]: [List of animes]
+ """
# concat the name to form the search url.
search_url = f"{BASE_URL}/search?keyword={anime_name}"
@@ -53,6 +70,24 @@
def search_anime_episode_list(episode_endpoint: str) -> list:
+ """[summary]
+
+ Take an url and
+ return list of episodes after scraping the site
+ for an url.
+
+ >>> type(search_anime_episode_list("/anime/kimetsu-no-yaiba"))
+ <class 'list'>
+
+ Args:
+ episode_endpoint (str): [Endpoint of episode]
+
+ Raises:
+ e: [description]
+
+ Returns:
+ [list]: [List of episodes]
+ """
request_url = f"{BASE_URL}{episode_endpoint}"
@@ -88,6 +123,22 @@
def get_anime_episode(episode_endpoint: str) -> list:
+ """[summary]
+
+ Get click url and download url from episode url
+
+ >>> type(get_anime_episode("/watch/kimetsu-no-yaiba/1"))
+ <class 'list'>
+
+ Args:
+ episode_endpoint (str): [Endpoint of episode]
+
+ Raises:
+ e: [description]
+
+ Returns:
+ [list]: [List of download and watch url]
+ """
episode_page_url = f"{BASE_URL}{episode_endpoint}"
@@ -143,4 +194,4 @@
episode_url, download_url = get_anime_episode(chosen_episode["url"])
print(f"\nTo watch, ctrl+click on {episode_url}.")
- print(f"To download, ctrl+click on {download_url}.")+ print(f"To download, ctrl+click on {download_url}.")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/fetch_anime_and_play.py |
Expand my code with proper documentation strings |
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "httpx",
# "pandas",
# ]
# ///
from itertools import zip_longest
import httpx
from bs4 import BeautifulSoup
from pandas import DataFrame
def get_amazon_product_data(product: str = "laptop") -> DataFrame:
url = f"https://www.amazon.in/laptop/s?k={product}"
header = {
"User-Agent": (
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"
"(KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36"
),
"Accept-Language": "en-US, en;q=0.5",
}
soup = BeautifulSoup(
httpx.get(url, headers=header, timeout=10).text, features="lxml"
)
# Initialize a Pandas dataframe with the column titles
data_frame = DataFrame(
columns=[
"Product Title",
"Product Link",
"Current Price of the product",
"Product Rating",
"MRP of the product",
"Discount",
]
)
# Loop through each entry and store them in the dataframe
for item, _ in zip_longest(
soup.find_all(
"div",
attrs={"class": "s-result-item", "data-component-type": "s-search-result"},
),
soup.find_all("div", attrs={"class": "a-row a-size-base a-color-base"}),
):
try:
product_title = item.h2.text
product_link = "https://www.amazon.in/" + item.h2.a["href"]
product_price = item.find("span", attrs={"class": "a-offscreen"}).text
try:
product_rating = item.find("span", attrs={"class": "a-icon-alt"}).text
except AttributeError:
product_rating = "Not available"
try:
product_mrp = (
"₹"
+ item.find(
"span", attrs={"class": "a-price a-text-price"}
).text.split("₹")[1]
)
except AttributeError:
product_mrp = ""
try:
discount = float(
(
(
float(product_mrp.strip("₹").replace(",", ""))
- float(product_price.strip("₹").replace(",", ""))
)
/ float(product_mrp.strip("₹").replace(",", ""))
)
* 100
)
except ValueError:
discount = float("nan")
except AttributeError:
continue
data_frame.loc[str(len(data_frame.index))] = [
product_title,
product_link,
product_price,
product_rating,
product_mrp,
discount,
]
data_frame.loc[
data_frame["Current Price of the product"] > data_frame["MRP of the product"],
"MRP of the product",
] = " "
data_frame.loc[
data_frame["Current Price of the product"] > data_frame["MRP of the product"],
"Discount",
] = " "
data_frame.index += 1
return data_frame
if __name__ == "__main__":
product = "headphones"
get_amazon_product_data(product).to_csv(f"Amazon Product Data for {product}.csv") | --- +++ @@ -1,3 +1,8 @@+"""
+This file provides a function which will take a product name as input from the user,
+and fetch from Amazon information about products of this name or category. The product
+information will include title, URL, price, ratings, and the discount available.
+"""
# /// script
# requires-python = ">=3.13"
@@ -16,6 +21,10 @@
def get_amazon_product_data(product: str = "laptop") -> DataFrame:
+ """
+ Take a product name or category as input and return product information from Amazon
+ including title, URL, price, ratings, and the discount available.
+ """
url = f"https://www.amazon.in/laptop/s?k={product}"
header = {
"User-Agent": (
@@ -100,4 +109,4 @@
if __name__ == "__main__":
product = "headphones"
- get_amazon_product_data(product).to_csv(f"Amazon Product Data for {product}.csv")+ get_amazon_product_data(product).to_csv(f"Amazon Product Data for {product}.csv")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/get_amazon_product_data.py |
Write docstrings for this repository |
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
from json import JSONDecodeError
import httpx
def get_openlibrary_data(olid: str = "isbn/0140328726") -> dict:
new_olid = olid.strip().strip("/") # Remove leading/trailing whitespace & slashes
if new_olid.count("/") != 1:
msg = f"{olid} is not a valid Open Library olid"
raise ValueError(msg)
return httpx.get(
f"https://openlibrary.org/{new_olid}.json", timeout=10, follow_redirects=True
).json()
def summarize_book(ol_book_data: dict) -> dict:
desired_keys = {
"title": "Title",
"publish_date": "Publish date",
"authors": "Authors",
"number_of_pages": "Number of pages",
"isbn_10": "ISBN (10)",
"isbn_13": "ISBN (13)",
}
data = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()}
data["Authors"] = [
get_openlibrary_data(author["key"])["name"] for author in data["Authors"]
]
for key, value in data.items():
if isinstance(value, list):
data[key] = ", ".join(value)
return data
if __name__ == "__main__":
import doctest
doctest.testmod()
while True:
isbn = input("\nEnter the ISBN code to search (or 'quit' to stop): ").strip()
if isbn.lower() in ("", "q", "quit", "exit", "stop"):
break
if len(isbn) not in (10, 13) or not isbn.isdigit():
print(f"Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.")
continue
print(f"\nSearching Open Library for ISBN: {isbn}...\n")
try:
book_summary = summarize_book(get_openlibrary_data(f"isbn/{isbn}"))
print("\n".join(f"{key}: {value}" for key, value in book_summary.items()))
except JSONDecodeError:
print(f"Sorry, there are no results for ISBN: {isbn}.") | --- +++ @@ -1,3 +1,8 @@+"""
+Get book and author data from https://openlibrary.org
+
+ISBN: https://en.wikipedia.org/wiki/International_Standard_Book_Number
+"""
# /// script
# requires-python = ">=3.13"
@@ -12,6 +17,17 @@
def get_openlibrary_data(olid: str = "isbn/0140328726") -> dict:
+ """
+ Given an 'isbn/0140328726', return book data from Open Library as a Python dict.
+ Given an '/authors/OL34184A', return authors data as a Python dict.
+ This code must work for olids with or without a leading slash ('/').
+
+ # Comment out doctests if they take too long or have results that may change
+ # >>> get_openlibrary_data(olid='isbn/0140328726') # doctest: +ELLIPSIS
+ {'publishers': ['Puffin'], 'number_of_pages': 96, 'isbn_10': ['0140328726'], ...
+ # >>> get_openlibrary_data(olid='/authors/OL7353617A') # doctest: +ELLIPSIS
+ {'name': 'Adrian Brisku', 'created': {'type': '/type/datetime', ...
+ """
new_olid = olid.strip().strip("/") # Remove leading/trailing whitespace & slashes
if new_olid.count("/") != 1:
msg = f"{olid} is not a valid Open Library olid"
@@ -22,6 +38,9 @@
def summarize_book(ol_book_data: dict) -> dict:
+ """
+ Given Open Library book data, return a summary as a Python dict.
+ """
desired_keys = {
"title": "Title",
"publish_date": "Publish date",
@@ -60,4 +79,4 @@ book_summary = summarize_book(get_openlibrary_data(f"isbn/{isbn}"))
print("\n".join(f"{key}: {value}" for key, value in book_summary.items()))
except JSONDecodeError:
- print(f"Sorry, there are no results for ISBN: {isbn}.")+ print(f"Sorry, there are no results for ISBN: {isbn}.")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/search_books_by_isbn.py |
Write proper docstrings for these functions | # This script is copied from the compvis/stable-diffusion repo (aka the SD V1 repo)
# Original filename: ldm/models/diffusion/ddpm.py
# The purpose to reinstate the old DDPM logic which works with VQ, whereas the V2 one doesn't
# Some models such as LDSR require VQ to work correctly
# The classes are suffixed with "V1" and added back to the "ldm.models.diffusion.ddpm" module
import torch
import torch.nn as nn
import numpy as np
import pytorch_lightning as pl
from torch.optim.lr_scheduler import LambdaLR
from einops import rearrange, repeat
from contextlib import contextmanager
from functools import partial
from tqdm import tqdm
from torchvision.utils import make_grid
from pytorch_lightning.utilities.distributed import rank_zero_only
from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config
from ldm.modules.ema import LitEma
from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution
from ldm.models.autoencoder import VQModelInterface, IdentityFirstStage, AutoencoderKL
from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like
from ldm.models.diffusion.ddim import DDIMSampler
import ldm.models.diffusion.ddpm
__conditioning_keys__ = {'concat': 'c_concat',
'crossattn': 'c_crossattn',
'adm': 'y'}
def disabled_train(self, mode=True):
return self
def uniform_on_device(r1, r2, shape, device):
return (r1 - r2) * torch.rand(*shape, device=device) + r2
class DDPMV1(pl.LightningModule):
# classic DDPM with Gaussian diffusion, in image space
def __init__(self,
unet_config,
timesteps=1000,
beta_schedule="linear",
loss_type="l2",
ckpt_path=None,
ignore_keys=None,
load_only_unet=False,
monitor="val/loss",
use_ema=True,
first_stage_key="image",
image_size=256,
channels=3,
log_every_t=100,
clip_denoised=True,
linear_start=1e-4,
linear_end=2e-2,
cosine_s=8e-3,
given_betas=None,
original_elbo_weight=0.,
v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
l_simple_weight=1.,
conditioning_key=None,
parameterization="eps", # all assuming fixed variance schedules
scheduler_config=None,
use_positional_encodings=False,
learn_logvar=False,
logvar_init=0.,
):
super().__init__()
assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"'
self.parameterization = parameterization
print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
self.cond_stage_model = None
self.clip_denoised = clip_denoised
self.log_every_t = log_every_t
self.first_stage_key = first_stage_key
self.image_size = image_size # try conv?
self.channels = channels
self.use_positional_encodings = use_positional_encodings
self.model = DiffusionWrapperV1(unet_config, conditioning_key)
count_params(self.model, verbose=True)
self.use_ema = use_ema
if self.use_ema:
self.model_ema = LitEma(self.model)
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
self.use_scheduler = scheduler_config is not None
if self.use_scheduler:
self.scheduler_config = scheduler_config
self.v_posterior = v_posterior
self.original_elbo_weight = original_elbo_weight
self.l_simple_weight = l_simple_weight
if monitor is not None:
self.monitor = monitor
if ckpt_path is not None:
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys or [], only_model=load_only_unet)
self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
self.loss_type = loss_type
self.learn_logvar = learn_logvar
self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
if self.learn_logvar:
self.logvar = nn.Parameter(self.logvar, requires_grad=True)
def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
if exists(given_betas):
betas = given_betas
else:
betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
cosine_s=cosine_s)
alphas = 1. - betas
alphas_cumprod = np.cumprod(alphas, axis=0)
alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
timesteps, = betas.shape
self.num_timesteps = int(timesteps)
self.linear_start = linear_start
self.linear_end = linear_end
assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
to_torch = partial(torch.tensor, dtype=torch.float32)
self.register_buffer('betas', to_torch(betas))
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
# calculations for diffusion q(x_t | x_{t-1}) and others
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
# calculations for posterior q(x_{t-1} | x_t, x_0)
posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
1. - alphas_cumprod) + self.v_posterior * betas
# above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
self.register_buffer('posterior_variance', to_torch(posterior_variance))
# below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
self.register_buffer('posterior_mean_coef1', to_torch(
betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
self.register_buffer('posterior_mean_coef2', to_torch(
(1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
if self.parameterization == "eps":
lvlb_weights = self.betas ** 2 / (
2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
elif self.parameterization == "x0":
lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
else:
raise NotImplementedError("mu not supported")
# TODO how to choose this term
lvlb_weights[0] = lvlb_weights[1]
self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
assert not torch.isnan(self.lvlb_weights).all()
@contextmanager
def ema_scope(self, context=None):
if self.use_ema:
self.model_ema.store(self.model.parameters())
self.model_ema.copy_to(self.model)
if context is not None:
print(f"{context}: Switched to EMA weights")
try:
yield None
finally:
if self.use_ema:
self.model_ema.restore(self.model.parameters())
if context is not None:
print(f"{context}: Restored training weights")
def init_from_ckpt(self, path, ignore_keys=None, only_model=False):
sd = torch.load(path, map_location="cpu")
if "state_dict" in list(sd.keys()):
sd = sd["state_dict"]
keys = list(sd.keys())
for k in keys:
for ik in ignore_keys or []:
if k.startswith(ik):
print("Deleting key {} from state_dict.".format(k))
del sd[k]
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
sd, strict=False)
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
if missing:
print(f"Missing Keys: {missing}")
if unexpected:
print(f"Unexpected Keys: {unexpected}")
def q_mean_variance(self, x_start, t):
mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
return mean, variance, log_variance
def predict_start_from_noise(self, x_t, t, noise):
return (
extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
)
def q_posterior(self, x_start, x_t, t):
posterior_mean = (
extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
)
posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
return posterior_mean, posterior_variance, posterior_log_variance_clipped
def p_mean_variance(self, x, t, clip_denoised: bool):
model_out = self.model(x, t)
if self.parameterization == "eps":
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
elif self.parameterization == "x0":
x_recon = model_out
if clip_denoised:
x_recon.clamp_(-1., 1.)
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
return model_mean, posterior_variance, posterior_log_variance
@torch.no_grad()
def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
b, *_, device = *x.shape, x.device
model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
noise = noise_like(x.shape, device, repeat_noise)
# no noise when t == 0
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
@torch.no_grad()
def p_sample_loop(self, shape, return_intermediates=False):
device = self.betas.device
b = shape[0]
img = torch.randn(shape, device=device)
intermediates = [img]
for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
clip_denoised=self.clip_denoised)
if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
intermediates.append(img)
if return_intermediates:
return img, intermediates
return img
@torch.no_grad()
def sample(self, batch_size=16, return_intermediates=False):
image_size = self.image_size
channels = self.channels
return self.p_sample_loop((batch_size, channels, image_size, image_size),
return_intermediates=return_intermediates)
def q_sample(self, x_start, t, noise=None):
noise = default(noise, lambda: torch.randn_like(x_start))
return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
def get_loss(self, pred, target, mean=True):
if self.loss_type == 'l1':
loss = (target - pred).abs()
if mean:
loss = loss.mean()
elif self.loss_type == 'l2':
if mean:
loss = torch.nn.functional.mse_loss(target, pred)
else:
loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
else:
raise NotImplementedError("unknown loss type '{loss_type}'")
return loss
def p_losses(self, x_start, t, noise=None):
noise = default(noise, lambda: torch.randn_like(x_start))
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
model_out = self.model(x_noisy, t)
loss_dict = {}
if self.parameterization == "eps":
target = noise
elif self.parameterization == "x0":
target = x_start
else:
raise NotImplementedError(f"Parameterization {self.parameterization} not yet supported")
loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
log_prefix = 'train' if self.training else 'val'
loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
loss_simple = loss.mean() * self.l_simple_weight
loss_vlb = (self.lvlb_weights[t] * loss).mean()
loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
loss = loss_simple + self.original_elbo_weight * loss_vlb
loss_dict.update({f'{log_prefix}/loss': loss})
return loss, loss_dict
def forward(self, x, *args, **kwargs):
# b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
# assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
return self.p_losses(x, t, *args, **kwargs)
def get_input(self, batch, k):
x = batch[k]
if len(x.shape) == 3:
x = x[..., None]
x = rearrange(x, 'b h w c -> b c h w')
x = x.to(memory_format=torch.contiguous_format).float()
return x
def shared_step(self, batch):
x = self.get_input(batch, self.first_stage_key)
loss, loss_dict = self(x)
return loss, loss_dict
def training_step(self, batch, batch_idx):
loss, loss_dict = self.shared_step(batch)
self.log_dict(loss_dict, prog_bar=True,
logger=True, on_step=True, on_epoch=True)
self.log("global_step", self.global_step,
prog_bar=True, logger=True, on_step=True, on_epoch=False)
if self.use_scheduler:
lr = self.optimizers().param_groups[0]['lr']
self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
return loss
@torch.no_grad()
def validation_step(self, batch, batch_idx):
_, loss_dict_no_ema = self.shared_step(batch)
with self.ema_scope():
_, loss_dict_ema = self.shared_step(batch)
loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
def on_train_batch_end(self, *args, **kwargs):
if self.use_ema:
self.model_ema(self.model)
def _get_rows_from_list(self, samples):
n_imgs_per_row = len(samples)
denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
return denoise_grid
@torch.no_grad()
def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
log = {}
x = self.get_input(batch, self.first_stage_key)
N = min(x.shape[0], N)
n_row = min(x.shape[0], n_row)
x = x.to(self.device)[:N]
log["inputs"] = x
# get diffusion row
diffusion_row = []
x_start = x[:n_row]
for t in range(self.num_timesteps):
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
t = t.to(self.device).long()
noise = torch.randn_like(x_start)
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
diffusion_row.append(x_noisy)
log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
if sample:
# get denoise row
with self.ema_scope("Plotting"):
samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
log["samples"] = samples
log["denoise_row"] = self._get_rows_from_list(denoise_row)
if return_keys:
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
return log
else:
return {key: log[key] for key in return_keys}
return log
def configure_optimizers(self):
lr = self.learning_rate
params = list(self.model.parameters())
if self.learn_logvar:
params = params + [self.logvar]
opt = torch.optim.AdamW(params, lr=lr)
return opt
class LatentDiffusionV1(DDPMV1):
def __init__(self,
first_stage_config,
cond_stage_config,
num_timesteps_cond=None,
cond_stage_key="image",
cond_stage_trainable=False,
concat_mode=True,
cond_stage_forward=None,
conditioning_key=None,
scale_factor=1.0,
scale_by_std=False,
*args, **kwargs):
self.num_timesteps_cond = default(num_timesteps_cond, 1)
self.scale_by_std = scale_by_std
assert self.num_timesteps_cond <= kwargs['timesteps']
# for backwards compatibility after implementation of DiffusionWrapper
if conditioning_key is None:
conditioning_key = 'concat' if concat_mode else 'crossattn'
if cond_stage_config == '__is_unconditional__':
conditioning_key = None
ckpt_path = kwargs.pop("ckpt_path", None)
ignore_keys = kwargs.pop("ignore_keys", [])
super().__init__(*args, conditioning_key=conditioning_key, **kwargs)
self.concat_mode = concat_mode
self.cond_stage_trainable = cond_stage_trainable
self.cond_stage_key = cond_stage_key
try:
self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
except Exception:
self.num_downs = 0
if not scale_by_std:
self.scale_factor = scale_factor
else:
self.register_buffer('scale_factor', torch.tensor(scale_factor))
self.instantiate_first_stage(first_stage_config)
self.instantiate_cond_stage(cond_stage_config)
self.cond_stage_forward = cond_stage_forward
self.clip_denoised = False
self.bbox_tokenizer = None
self.restarted_from_ckpt = False
if ckpt_path is not None:
self.init_from_ckpt(ckpt_path, ignore_keys)
self.restarted_from_ckpt = True
def make_cond_schedule(self, ):
self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
self.cond_ids[:self.num_timesteps_cond] = ids
@rank_zero_only
@torch.no_grad()
def on_train_batch_start(self, batch, batch_idx, dataloader_idx):
# only for very first batch
if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt:
assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
# set rescale weight to 1./std of encodings
print("### USING STD-RESCALING ###")
x = super().get_input(batch, self.first_stage_key)
x = x.to(self.device)
encoder_posterior = self.encode_first_stage(x)
z = self.get_first_stage_encoding(encoder_posterior).detach()
del self.scale_factor
self.register_buffer('scale_factor', 1. / z.flatten().std())
print(f"setting self.scale_factor to {self.scale_factor}")
print("### USING STD-RESCALING ###")
def register_schedule(self,
given_betas=None, beta_schedule="linear", timesteps=1000,
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
self.shorten_cond_schedule = self.num_timesteps_cond > 1
if self.shorten_cond_schedule:
self.make_cond_schedule()
def instantiate_first_stage(self, config):
model = instantiate_from_config(config)
self.first_stage_model = model.eval()
self.first_stage_model.train = disabled_train
for param in self.first_stage_model.parameters():
param.requires_grad = False
def instantiate_cond_stage(self, config):
if not self.cond_stage_trainable:
if config == "__is_first_stage__":
print("Using first stage also as cond stage.")
self.cond_stage_model = self.first_stage_model
elif config == "__is_unconditional__":
print(f"Training {self.__class__.__name__} as an unconditional model.")
self.cond_stage_model = None
# self.be_unconditional = True
else:
model = instantiate_from_config(config)
self.cond_stage_model = model.eval()
self.cond_stage_model.train = disabled_train
for param in self.cond_stage_model.parameters():
param.requires_grad = False
else:
assert config != '__is_first_stage__'
assert config != '__is_unconditional__'
model = instantiate_from_config(config)
self.cond_stage_model = model
def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):
denoise_row = []
for zd in tqdm(samples, desc=desc):
denoise_row.append(self.decode_first_stage(zd.to(self.device),
force_not_quantize=force_no_decoder_quantization))
n_imgs_per_row = len(denoise_row)
denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W
denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
return denoise_grid
def get_first_stage_encoding(self, encoder_posterior):
if isinstance(encoder_posterior, DiagonalGaussianDistribution):
z = encoder_posterior.sample()
elif isinstance(encoder_posterior, torch.Tensor):
z = encoder_posterior
else:
raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
return self.scale_factor * z
def get_learned_conditioning(self, c):
if self.cond_stage_forward is None:
if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
c = self.cond_stage_model.encode(c)
if isinstance(c, DiagonalGaussianDistribution):
c = c.mode()
else:
c = self.cond_stage_model(c)
else:
assert hasattr(self.cond_stage_model, self.cond_stage_forward)
c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
return c
def meshgrid(self, h, w):
y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
arr = torch.cat([y, x], dim=-1)
return arr
def delta_border(self, h, w):
lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
arr = self.meshgrid(h, w) / lower_right_corner
dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
return edge_dist
def get_weighting(self, h, w, Ly, Lx, device):
weighting = self.delta_border(h, w)
weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"],
self.split_input_params["clip_max_weight"], )
weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
if self.split_input_params["tie_braker"]:
L_weighting = self.delta_border(Ly, Lx)
L_weighting = torch.clip(L_weighting,
self.split_input_params["clip_min_tie_weight"],
self.split_input_params["clip_max_tie_weight"])
L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
weighting = weighting * L_weighting
return weighting
def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
bs, nc, h, w = x.shape
# number of crops in image
Ly = (h - kernel_size[0]) // stride[0] + 1
Lx = (w - kernel_size[1]) // stride[1] + 1
if uf == 1 and df == 1:
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
unfold = torch.nn.Unfold(**fold_params)
fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)
normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
elif uf > 1 and df == 1:
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
unfold = torch.nn.Unfold(**fold_params)
fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
dilation=1, padding=0,
stride=(stride[0] * uf, stride[1] * uf))
fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)
normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
elif df > 1 and uf == 1:
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
unfold = torch.nn.Unfold(**fold_params)
fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
dilation=1, padding=0,
stride=(stride[0] // df, stride[1] // df))
fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)
normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
else:
raise NotImplementedError
return fold, unfold, normalization, weighting
@torch.no_grad()
def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
cond_key=None, return_original_cond=False, bs=None):
x = super().get_input(batch, k)
if bs is not None:
x = x[:bs]
x = x.to(self.device)
encoder_posterior = self.encode_first_stage(x)
z = self.get_first_stage_encoding(encoder_posterior).detach()
if self.model.conditioning_key is not None:
if cond_key is None:
cond_key = self.cond_stage_key
if cond_key != self.first_stage_key:
if cond_key in ['caption', 'coordinates_bbox']:
xc = batch[cond_key]
elif cond_key == 'class_label':
xc = batch
else:
xc = super().get_input(batch, cond_key).to(self.device)
else:
xc = x
if not self.cond_stage_trainable or force_c_encode:
if isinstance(xc, dict) or isinstance(xc, list):
# import pudb; pudb.set_trace()
c = self.get_learned_conditioning(xc)
else:
c = self.get_learned_conditioning(xc.to(self.device))
else:
c = xc
if bs is not None:
c = c[:bs]
if self.use_positional_encodings:
pos_x, pos_y = self.compute_latent_shifts(batch)
ckey = __conditioning_keys__[self.model.conditioning_key]
c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y}
else:
c = None
xc = None
if self.use_positional_encodings:
pos_x, pos_y = self.compute_latent_shifts(batch)
c = {'pos_x': pos_x, 'pos_y': pos_y}
out = [z, c]
if return_first_stage_outputs:
xrec = self.decode_first_stage(z)
out.extend([x, xrec])
if return_original_cond:
out.append(xc)
return out
@torch.no_grad()
def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
if predict_cids:
if z.dim() == 4:
z = torch.argmax(z.exp(), dim=1).long()
z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
z = rearrange(z, 'b h w c -> b c h w').contiguous()
z = 1. / self.scale_factor * z
if hasattr(self, "split_input_params"):
if self.split_input_params["patch_distributed_vq"]:
ks = self.split_input_params["ks"] # eg. (128, 128)
stride = self.split_input_params["stride"] # eg. (64, 64)
uf = self.split_input_params["vqf"]
bs, nc, h, w = z.shape
if ks[0] > h or ks[1] > w:
ks = (min(ks[0], h), min(ks[1], w))
print("reducing Kernel")
if stride[0] > h or stride[1] > w:
stride = (min(stride[0], h), min(stride[1], w))
print("reducing stride")
fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
z = unfold(z) # (bn, nc * prod(**ks), L)
# 1. Reshape to img shape
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
# 2. apply model loop over last dim
if isinstance(self.first_stage_model, VQModelInterface):
output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
force_not_quantize=predict_cids or force_not_quantize)
for i in range(z.shape[-1])]
else:
output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
for i in range(z.shape[-1])]
o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
o = o * weighting
# Reverse 1. reshape to img shape
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
# stitch crops together
decoded = fold(o)
decoded = decoded / normalization # norm is shape (1, 1, h, w)
return decoded
else:
if isinstance(self.first_stage_model, VQModelInterface):
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
else:
return self.first_stage_model.decode(z)
else:
if isinstance(self.first_stage_model, VQModelInterface):
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
else:
return self.first_stage_model.decode(z)
# same as above but without decorator
def differentiable_decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
if predict_cids:
if z.dim() == 4:
z = torch.argmax(z.exp(), dim=1).long()
z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
z = rearrange(z, 'b h w c -> b c h w').contiguous()
z = 1. / self.scale_factor * z
if hasattr(self, "split_input_params"):
if self.split_input_params["patch_distributed_vq"]:
ks = self.split_input_params["ks"] # eg. (128, 128)
stride = self.split_input_params["stride"] # eg. (64, 64)
uf = self.split_input_params["vqf"]
bs, nc, h, w = z.shape
if ks[0] > h or ks[1] > w:
ks = (min(ks[0], h), min(ks[1], w))
print("reducing Kernel")
if stride[0] > h or stride[1] > w:
stride = (min(stride[0], h), min(stride[1], w))
print("reducing stride")
fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
z = unfold(z) # (bn, nc * prod(**ks), L)
# 1. Reshape to img shape
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
# 2. apply model loop over last dim
if isinstance(self.first_stage_model, VQModelInterface):
output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
force_not_quantize=predict_cids or force_not_quantize)
for i in range(z.shape[-1])]
else:
output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
for i in range(z.shape[-1])]
o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
o = o * weighting
# Reverse 1. reshape to img shape
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
# stitch crops together
decoded = fold(o)
decoded = decoded / normalization # norm is shape (1, 1, h, w)
return decoded
else:
if isinstance(self.first_stage_model, VQModelInterface):
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
else:
return self.first_stage_model.decode(z)
else:
if isinstance(self.first_stage_model, VQModelInterface):
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
else:
return self.first_stage_model.decode(z)
@torch.no_grad()
def encode_first_stage(self, x):
if hasattr(self, "split_input_params"):
if self.split_input_params["patch_distributed_vq"]:
ks = self.split_input_params["ks"] # eg. (128, 128)
stride = self.split_input_params["stride"] # eg. (64, 64)
df = self.split_input_params["vqf"]
self.split_input_params['original_image_size'] = x.shape[-2:]
bs, nc, h, w = x.shape
if ks[0] > h or ks[1] > w:
ks = (min(ks[0], h), min(ks[1], w))
print("reducing Kernel")
if stride[0] > h or stride[1] > w:
stride = (min(stride[0], h), min(stride[1], w))
print("reducing stride")
fold, unfold, normalization, weighting = self.get_fold_unfold(x, ks, stride, df=df)
z = unfold(x) # (bn, nc * prod(**ks), L)
# Reshape to img shape
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
output_list = [self.first_stage_model.encode(z[:, :, :, :, i])
for i in range(z.shape[-1])]
o = torch.stack(output_list, axis=-1)
o = o * weighting
# Reverse reshape to img shape
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
# stitch crops together
decoded = fold(o)
decoded = decoded / normalization
return decoded
else:
return self.first_stage_model.encode(x)
else:
return self.first_stage_model.encode(x)
def shared_step(self, batch, **kwargs):
x, c = self.get_input(batch, self.first_stage_key)
loss = self(x, c)
return loss
def forward(self, x, c, *args, **kwargs):
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
if self.model.conditioning_key is not None:
assert c is not None
if self.cond_stage_trainable:
c = self.get_learned_conditioning(c)
if self.shorten_cond_schedule: # TODO: drop this option
tc = self.cond_ids[t].to(self.device)
c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
return self.p_losses(x, c, t, *args, **kwargs)
def apply_model(self, x_noisy, t, cond, return_ids=False):
if isinstance(cond, dict):
# hybrid case, cond is expected to be a dict
pass
else:
if not isinstance(cond, list):
cond = [cond]
key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
cond = {key: cond}
if hasattr(self, "split_input_params"):
assert len(cond) == 1 # todo can only deal with one conditioning atm
assert not return_ids
ks = self.split_input_params["ks"] # eg. (128, 128)
stride = self.split_input_params["stride"] # eg. (64, 64)
h, w = x_noisy.shape[-2:]
fold, unfold, normalization, weighting = self.get_fold_unfold(x_noisy, ks, stride)
z = unfold(x_noisy) # (bn, nc * prod(**ks), L)
# Reshape to img shape
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
z_list = [z[:, :, :, :, i] for i in range(z.shape[-1])]
if self.cond_stage_key in ["image", "LR_image", "segmentation",
'bbox_img'] and self.model.conditioning_key: # todo check for completeness
c_key = next(iter(cond.keys())) # get key
c = next(iter(cond.values())) # get value
assert (len(c) == 1) # todo extend to list with more than one elem
c = c[0] # get element
c = unfold(c)
c = c.view((c.shape[0], -1, ks[0], ks[1], c.shape[-1])) # (bn, nc, ks[0], ks[1], L )
cond_list = [{c_key: [c[:, :, :, :, i]]} for i in range(c.shape[-1])]
elif self.cond_stage_key == 'coordinates_bbox':
assert 'original_image_size' in self.split_input_params, 'BoundingBoxRescaling is missing original_image_size'
# assuming padding of unfold is always 0 and its dilation is always 1
n_patches_per_row = int((w - ks[0]) / stride[0] + 1)
full_img_h, full_img_w = self.split_input_params['original_image_size']
# as we are operating on latents, we need the factor from the original image size to the
# spatial latent size to properly rescale the crops for regenerating the bbox annotations
num_downs = self.first_stage_model.encoder.num_resolutions - 1
rescale_latent = 2 ** (num_downs)
# get top left positions of patches as conforming for the bbbox tokenizer, therefore we
# need to rescale the tl patch coordinates to be in between (0,1)
tl_patch_coordinates = [(rescale_latent * stride[0] * (patch_nr % n_patches_per_row) / full_img_w,
rescale_latent * stride[1] * (patch_nr // n_patches_per_row) / full_img_h)
for patch_nr in range(z.shape[-1])]
# patch_limits are tl_coord, width and height coordinates as (x_tl, y_tl, h, w)
patch_limits = [(x_tl, y_tl,
rescale_latent * ks[0] / full_img_w,
rescale_latent * ks[1] / full_img_h) for x_tl, y_tl in tl_patch_coordinates]
# patch_values = [(np.arange(x_tl,min(x_tl+ks, 1.)),np.arange(y_tl,min(y_tl+ks, 1.))) for x_tl, y_tl in tl_patch_coordinates]
# tokenize crop coordinates for the bounding boxes of the respective patches
patch_limits_tknzd = [torch.LongTensor(self.bbox_tokenizer._crop_encoder(bbox))[None].to(self.device)
for bbox in patch_limits] # list of length l with tensors of shape (1, 2)
print(patch_limits_tknzd[0].shape)
# cut tknzd crop position from conditioning
assert isinstance(cond, dict), 'cond must be dict to be fed into model'
cut_cond = cond['c_crossattn'][0][..., :-2].to(self.device)
print(cut_cond.shape)
adapted_cond = torch.stack([torch.cat([cut_cond, p], dim=1) for p in patch_limits_tknzd])
adapted_cond = rearrange(adapted_cond, 'l b n -> (l b) n')
print(adapted_cond.shape)
adapted_cond = self.get_learned_conditioning(adapted_cond)
print(adapted_cond.shape)
adapted_cond = rearrange(adapted_cond, '(l b) n d -> l b n d', l=z.shape[-1])
print(adapted_cond.shape)
cond_list = [{'c_crossattn': [e]} for e in adapted_cond]
else:
cond_list = [cond for i in range(z.shape[-1])] # Todo make this more efficient
# apply model by loop over crops
output_list = [self.model(z_list[i], t, **cond_list[i]) for i in range(z.shape[-1])]
assert not isinstance(output_list[0],
tuple) # todo cant deal with multiple model outputs check this never happens
o = torch.stack(output_list, axis=-1)
o = o * weighting
# Reverse reshape to img shape
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
# stitch crops together
x_recon = fold(o) / normalization
else:
x_recon = self.model(x_noisy, t, **cond)
if isinstance(x_recon, tuple) and not return_ids:
return x_recon[0]
else:
return x_recon
def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
def _prior_bpd(self, x_start):
batch_size = x_start.shape[0]
t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
return mean_flat(kl_prior) / np.log(2.0)
def p_losses(self, x_start, cond, t, noise=None):
noise = default(noise, lambda: torch.randn_like(x_start))
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
model_output = self.apply_model(x_noisy, t, cond)
loss_dict = {}
prefix = 'train' if self.training else 'val'
if self.parameterization == "x0":
target = x_start
elif self.parameterization == "eps":
target = noise
else:
raise NotImplementedError()
loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])
loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
logvar_t = self.logvar[t].to(self.device)
loss = loss_simple / torch.exp(logvar_t) + logvar_t
# loss = loss_simple / torch.exp(self.logvar) + self.logvar
if self.learn_logvar:
loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
loss_dict.update({'logvar': self.logvar.data.mean()})
loss = self.l_simple_weight * loss.mean()
loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))
loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
loss += (self.original_elbo_weight * loss_vlb)
loss_dict.update({f'{prefix}/loss': loss})
return loss, loss_dict
def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
return_x0=False, score_corrector=None, corrector_kwargs=None):
t_in = t
model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
if score_corrector is not None:
assert self.parameterization == "eps"
model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
if return_codebook_ids:
model_out, logits = model_out
if self.parameterization == "eps":
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
elif self.parameterization == "x0":
x_recon = model_out
else:
raise NotImplementedError()
if clip_denoised:
x_recon.clamp_(-1., 1.)
if quantize_denoised:
x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
if return_codebook_ids:
return model_mean, posterior_variance, posterior_log_variance, logits
elif return_x0:
return model_mean, posterior_variance, posterior_log_variance, x_recon
else:
return model_mean, posterior_variance, posterior_log_variance
@torch.no_grad()
def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
return_codebook_ids=False, quantize_denoised=False, return_x0=False,
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
b, *_, device = *x.shape, x.device
outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
return_codebook_ids=return_codebook_ids,
quantize_denoised=quantize_denoised,
return_x0=return_x0,
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
if return_codebook_ids:
raise DeprecationWarning("Support dropped.")
model_mean, _, model_log_variance, logits = outputs
elif return_x0:
model_mean, _, model_log_variance, x0 = outputs
else:
model_mean, _, model_log_variance = outputs
noise = noise_like(x.shape, device, repeat_noise) * temperature
if noise_dropout > 0.:
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
# no noise when t == 0
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
if return_codebook_ids:
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
if return_x0:
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
else:
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
@torch.no_grad()
def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
log_every_t=None):
if not log_every_t:
log_every_t = self.log_every_t
timesteps = self.num_timesteps
if batch_size is not None:
b = batch_size if batch_size is not None else shape[0]
shape = [batch_size] + list(shape)
else:
b = batch_size = shape[0]
if x_T is None:
img = torch.randn(shape, device=self.device)
else:
img = x_T
intermediates = []
if cond is not None:
if isinstance(cond, dict):
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
[x[:batch_size] for x in cond[key]] for key in cond}
else:
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
if start_T is not None:
timesteps = min(timesteps, start_T)
iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
total=timesteps) if verbose else reversed(
range(0, timesteps))
if type(temperature) == float:
temperature = [temperature] * timesteps
for i in iterator:
ts = torch.full((b,), i, device=self.device, dtype=torch.long)
if self.shorten_cond_schedule:
assert self.model.conditioning_key != 'hybrid'
tc = self.cond_ids[ts].to(cond.device)
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
img, x0_partial = self.p_sample(img, cond, ts,
clip_denoised=self.clip_denoised,
quantize_denoised=quantize_denoised, return_x0=True,
temperature=temperature[i], noise_dropout=noise_dropout,
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
if mask is not None:
assert x0 is not None
img_orig = self.q_sample(x0, ts)
img = img_orig * mask + (1. - mask) * img
if i % log_every_t == 0 or i == timesteps - 1:
intermediates.append(x0_partial)
if callback:
callback(i)
if img_callback:
img_callback(img, i)
return img, intermediates
@torch.no_grad()
def p_sample_loop(self, cond, shape, return_intermediates=False,
x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
mask=None, x0=None, img_callback=None, start_T=None,
log_every_t=None):
if not log_every_t:
log_every_t = self.log_every_t
device = self.betas.device
b = shape[0]
if x_T is None:
img = torch.randn(shape, device=device)
else:
img = x_T
intermediates = [img]
if timesteps is None:
timesteps = self.num_timesteps
if start_T is not None:
timesteps = min(timesteps, start_T)
iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
range(0, timesteps))
if mask is not None:
assert x0 is not None
assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
for i in iterator:
ts = torch.full((b,), i, device=device, dtype=torch.long)
if self.shorten_cond_schedule:
assert self.model.conditioning_key != 'hybrid'
tc = self.cond_ids[ts].to(cond.device)
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
img = self.p_sample(img, cond, ts,
clip_denoised=self.clip_denoised,
quantize_denoised=quantize_denoised)
if mask is not None:
img_orig = self.q_sample(x0, ts)
img = img_orig * mask + (1. - mask) * img
if i % log_every_t == 0 or i == timesteps - 1:
intermediates.append(img)
if callback:
callback(i)
if img_callback:
img_callback(img, i)
if return_intermediates:
return img, intermediates
return img
@torch.no_grad()
def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
verbose=True, timesteps=None, quantize_denoised=False,
mask=None, x0=None, shape=None,**kwargs):
if shape is None:
shape = (batch_size, self.channels, self.image_size, self.image_size)
if cond is not None:
if isinstance(cond, dict):
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
[x[:batch_size] for x in cond[key]] for key in cond}
else:
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
return self.p_sample_loop(cond,
shape,
return_intermediates=return_intermediates, x_T=x_T,
verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
mask=mask, x0=x0)
@torch.no_grad()
def sample_log(self,cond,batch_size,ddim, ddim_steps,**kwargs):
if ddim:
ddim_sampler = DDIMSampler(self)
shape = (self.channels, self.image_size, self.image_size)
samples, intermediates =ddim_sampler.sample(ddim_steps,batch_size,
shape,cond,verbose=False,**kwargs)
else:
samples, intermediates = self.sample(cond=cond, batch_size=batch_size,
return_intermediates=True,**kwargs)
return samples, intermediates
@torch.no_grad()
def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
plot_diffusion_rows=True, **kwargs):
use_ddim = ddim_steps is not None
log = {}
z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
return_first_stage_outputs=True,
force_c_encode=True,
return_original_cond=True,
bs=N)
N = min(x.shape[0], N)
n_row = min(x.shape[0], n_row)
log["inputs"] = x
log["reconstruction"] = xrec
if self.model.conditioning_key is not None:
if hasattr(self.cond_stage_model, "decode"):
xc = self.cond_stage_model.decode(c)
log["conditioning"] = xc
elif self.cond_stage_key in ["caption"]:
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["caption"])
log["conditioning"] = xc
elif self.cond_stage_key == 'class_label':
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"])
log['conditioning'] = xc
elif isimage(xc):
log["conditioning"] = xc
if ismap(xc):
log["original_conditioning"] = self.to_rgb(xc)
if plot_diffusion_rows:
# get diffusion row
diffusion_row = []
z_start = z[:n_row]
for t in range(self.num_timesteps):
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
t = t.to(self.device).long()
noise = torch.randn_like(z_start)
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
diffusion_row.append(self.decode_first_stage(z_noisy))
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
log["diffusion_row"] = diffusion_grid
if sample:
# get denoise row
with self.ema_scope("Plotting"):
samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
ddim_steps=ddim_steps,eta=ddim_eta)
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
x_samples = self.decode_first_stage(samples)
log["samples"] = x_samples
if plot_denoise_rows:
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
log["denoise_row"] = denoise_grid
if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
self.first_stage_model, IdentityFirstStage):
# also display when quantizing x0 while sampling
with self.ema_scope("Plotting Quantized Denoised"):
samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
ddim_steps=ddim_steps,eta=ddim_eta,
quantize_denoised=True)
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
# quantize_denoised=True)
x_samples = self.decode_first_stage(samples.to(self.device))
log["samples_x0_quantized"] = x_samples
if inpaint:
# make a simple center square
h, w = z.shape[2], z.shape[3]
mask = torch.ones(N, h, w).to(self.device)
# zeros will be filled in
mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
mask = mask[:, None, ...]
with self.ema_scope("Plotting Inpaint"):
samples, _ = self.sample_log(cond=c,batch_size=N,ddim=use_ddim, eta=ddim_eta,
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
x_samples = self.decode_first_stage(samples.to(self.device))
log["samples_inpainting"] = x_samples
log["mask"] = mask
# outpaint
with self.ema_scope("Plotting Outpaint"):
samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,eta=ddim_eta,
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
x_samples = self.decode_first_stage(samples.to(self.device))
log["samples_outpainting"] = x_samples
if plot_progressive_rows:
with self.ema_scope("Plotting Progressives"):
img, progressives = self.progressive_denoising(c,
shape=(self.channels, self.image_size, self.image_size),
batch_size=N)
prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
log["progressive_row"] = prog_row
if return_keys:
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
return log
else:
return {key: log[key] for key in return_keys}
return log
def configure_optimizers(self):
lr = self.learning_rate
params = list(self.model.parameters())
if self.cond_stage_trainable:
print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
params = params + list(self.cond_stage_model.parameters())
if self.learn_logvar:
print('Diffusion model optimizing logvar')
params.append(self.logvar)
opt = torch.optim.AdamW(params, lr=lr)
if self.use_scheduler:
assert 'target' in self.scheduler_config
scheduler = instantiate_from_config(self.scheduler_config)
print("Setting up LambdaLR scheduler...")
scheduler = [
{
'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
'interval': 'step',
'frequency': 1
}]
return [opt], scheduler
return opt
@torch.no_grad()
def to_rgb(self, x):
x = x.float()
if not hasattr(self, "colorize"):
self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
x = nn.functional.conv2d(x, weight=self.colorize)
x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
return x
class DiffusionWrapperV1(pl.LightningModule):
def __init__(self, diff_model_config, conditioning_key):
super().__init__()
self.diffusion_model = instantiate_from_config(diff_model_config)
self.conditioning_key = conditioning_key
assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm']
def forward(self, x, t, c_concat: list = None, c_crossattn: list = None):
if self.conditioning_key is None:
out = self.diffusion_model(x, t)
elif self.conditioning_key == 'concat':
xc = torch.cat([x] + c_concat, dim=1)
out = self.diffusion_model(xc, t)
elif self.conditioning_key == 'crossattn':
cc = torch.cat(c_crossattn, 1)
out = self.diffusion_model(x, t, context=cc)
elif self.conditioning_key == 'hybrid':
xc = torch.cat([x] + c_concat, dim=1)
cc = torch.cat(c_crossattn, 1)
out = self.diffusion_model(xc, t, context=cc)
elif self.conditioning_key == 'adm':
cc = c_crossattn[0]
out = self.diffusion_model(x, t, y=cc)
else:
raise NotImplementedError()
return out
class Layout2ImgDiffusionV1(LatentDiffusionV1):
# TODO: move all layout-specific hacks to this class
def __init__(self, cond_stage_key, *args, **kwargs):
assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
super().__init__(*args, cond_stage_key=cond_stage_key, **kwargs)
def log_images(self, batch, N=8, *args, **kwargs):
logs = super().log_images(*args, batch=batch, N=N, **kwargs)
key = 'train' if self.training else 'validation'
dset = self.trainer.datamodule.datasets[key]
mapper = dset.conditional_builders[self.cond_stage_key]
bbox_imgs = []
map_fn = lambda catno: dset.get_textual_label(dset.get_category_id(catno))
for tknzd_bbox in batch[self.cond_stage_key][:N]:
bboximg = mapper.plot(tknzd_bbox.detach().cpu(), map_fn, (256, 256))
bbox_imgs.append(bboximg)
cond_img = torch.stack(bbox_imgs, dim=0)
logs['bbox_image'] = cond_img
return logs
ldm.models.diffusion.ddpm.DDPMV1 = DDPMV1
ldm.models.diffusion.ddpm.LatentDiffusionV1 = LatentDiffusionV1
ldm.models.diffusion.ddpm.DiffusionWrapperV1 = DiffusionWrapperV1
ldm.models.diffusion.ddpm.Layout2ImgDiffusionV1 = Layout2ImgDiffusionV1 | --- +++ @@ -31,6 +31,8 @@
def disabled_train(self, mode=True):
+ """Overwrite model.train with this function to make sure train/eval mode
+ does not change anymore."""
return self
@@ -199,6 +201,12 @@ print(f"Unexpected Keys: {unexpected}")
def q_mean_variance(self, x_start, t):
+ """
+ Get the distribution q(x_t | x_0).
+ :param x_start: the [N x C x ...] tensor of noiseless inputs.
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
+ :return: A tuple (mean, variance, log_variance), all of x_start's shape.
+ """
mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
@@ -413,6 +421,7 @@
class LatentDiffusionV1(DDPMV1):
+ """main class"""
def __init__(self,
first_stage_config,
cond_stage_config,
@@ -559,6 +568,12 @@ return arr
def delta_border(self, h, w):
+ """
+ :param h: height
+ :param w: width
+ :return: normalized distance to image border,
+ with min distance = 0 at border and max dist = 0.5 at image center
+ """
lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
arr = self.meshgrid(h, w) / lower_right_corner
dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
@@ -583,6 +598,10 @@ return weighting
def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
+ """
+ :param x: img of size (bs, c, h, w)
+ :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
+ """
bs, nc, h, w = x.shape
# number of crops in image
@@ -966,6 +985,13 @@ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
def _prior_bpd(self, x_start):
+ """
+ Get the prior KL term for the variational lower-bound, measured in
+ bits-per-dim.
+ This term can't be optimized, as it only depends on the encoder.
+ :param x_start: the [N x C x ...] tensor of inputs.
+ :return: a batch of [N] KL values (in bits), one per batch element.
+ """
batch_size = x_start.shape[0]
t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
@@ -1414,4 +1440,4 @@ ldm.models.diffusion.ddpm.DDPMV1 = DDPMV1
ldm.models.diffusion.ddpm.LatentDiffusionV1 = LatentDiffusionV1
ldm.models.diffusion.ddpm.DiffusionWrapperV1 = DiffusionWrapperV1
-ldm.models.diffusion.ddpm.Layout2ImgDiffusionV1 = Layout2ImgDiffusionV1+ldm.models.diffusion.ddpm.Layout2ImgDiffusionV1 = Layout2ImgDiffusionV1
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/extensions-builtin/LDSR/sd_hijack_ddpm_v1.py |
Add docstrings for internal functions | #!/usr/bin/env python3
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "fake-useragent",
# "httpx",
# ]
# ///
from __future__ import annotations
import json
import httpx
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
headers = {"UserAgent": UserAgent().random}
def extract_user_profile(script) -> dict:
data = script.contents[0]
info = json.loads(data[data.find('{"config"') : -1])
return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]
class InstagramUser:
def __init__(self, username):
self.url = f"https://www.instagram.com/{username}/"
self.user_data = self.get_json()
def get_json(self) -> dict:
html = httpx.get(self.url, headers=headers, timeout=10).text
scripts = BeautifulSoup(html, "html.parser").find_all("script")
try:
return extract_user_profile(scripts[4])
except (json.decoder.JSONDecodeError, KeyError):
return extract_user_profile(scripts[3])
def __repr__(self) -> str:
return f"{self.__class__.__name__}('{self.username}')"
def __str__(self) -> str:
return f"{self.fullname} ({self.username}) is {self.biography}"
@property
def username(self) -> str:
return self.user_data["username"]
@property
def fullname(self) -> str:
return self.user_data["full_name"]
@property
def biography(self) -> str:
return self.user_data["biography"]
@property
def email(self) -> str:
return self.user_data["business_email"]
@property
def website(self) -> str:
return self.user_data["external_url"]
@property
def number_of_followers(self) -> int:
return self.user_data["edge_followed_by"]["count"]
@property
def number_of_followings(self) -> int:
return self.user_data["edge_follow"]["count"]
@property
def number_of_posts(self) -> int:
return self.user_data["edge_owner_to_timeline_media"]["count"]
@property
def profile_picture_url(self) -> str:
return self.user_data["profile_pic_url_hd"]
@property
def is_verified(self) -> bool:
return self.user_data["is_verified"]
@property
def is_private(self) -> bool:
return self.user_data["is_private"]
def test_instagram_user(username: str = "github") -> None:
import os
if os.environ.get("CI"):
return # test failing on GitHub Actions
instagram_user = InstagramUser(username)
assert instagram_user.user_data
assert isinstance(instagram_user.user_data, dict)
assert instagram_user.username == username
if username != "github":
return
assert instagram_user.fullname == "GitHub"
assert instagram_user.biography == "Built for developers."
assert instagram_user.number_of_posts > 150
assert instagram_user.number_of_followers > 120000
assert instagram_user.number_of_followings > 15
assert instagram_user.email == "support@github.com"
assert instagram_user.website == "https://github.com/readme"
assert instagram_user.profile_picture_url.startswith("https://instagram.")
assert instagram_user.is_verified is True
assert instagram_user.is_private is False
if __name__ == "__main__":
import doctest
doctest.testmod()
instagram_user = InstagramUser("github")
print(instagram_user)
print(f"{instagram_user.number_of_posts = }")
print(f"{instagram_user.number_of_followers = }")
print(f"{instagram_user.number_of_followings = }")
print(f"{instagram_user.email = }")
print(f"{instagram_user.website = }")
print(f"{instagram_user.profile_picture_url = }")
print(f"{instagram_user.is_verified = }")
print(f"{instagram_user.is_private = }") | --- +++ @@ -21,18 +21,34 @@
def extract_user_profile(script) -> dict:
+ """
+ May raise json.decoder.JSONDecodeError
+ """
data = script.contents[0]
info = json.loads(data[data.find('{"config"') : -1])
return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]
class InstagramUser:
+ """
+ Class Instagram crawl instagram user information
+
+ Usage: (doctest failing on GitHub Actions)
+ # >>> instagram_user = InstagramUser("github")
+ # >>> instagram_user.is_verified
+ True
+ # >>> instagram_user.biography
+ 'Built for developers.'
+ """
def __init__(self, username):
self.url = f"https://www.instagram.com/{username}/"
self.user_data = self.get_json()
def get_json(self) -> dict:
+ """
+ Return a dict of user information
+ """
html = httpx.get(self.url, headers=headers, timeout=10).text
scripts = BeautifulSoup(html, "html.parser").find_all("script")
try:
@@ -92,6 +108,10 @@
def test_instagram_user(username: str = "github") -> None:
+ """
+ A self running doctest
+ >>> test_instagram_user()
+ """
import os
if os.environ.get("CI"):
@@ -127,4 +147,4 @@ print(f"{instagram_user.website = }")
print(f"{instagram_user.profile_picture_url = }")
print(f"{instagram_user.is_verified = }")
- print(f"{instagram_user.is_private = }")+ print(f"{instagram_user.is_private = }")
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/instagram_crawler.py |
Generate docstrings with parameter types | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "httpx",
# ]
# ///
import httpx
def get_apod_data(api_key: str) -> dict:
url = "https://api.nasa.gov/planetary/apod"
return httpx.get(url, params={"api_key": api_key}, timeout=10).json()
def save_apod(api_key: str, path: str = ".") -> dict:
apod_data = get_apod_data(api_key)
img_url = apod_data["url"]
img_name = img_url.split("/")[-1]
response = httpx.get(img_url, timeout=10)
with open(f"{path}/{img_name}", "wb+") as img_file:
img_file.write(response.content)
del response
return apod_data
def get_archive_data(query: str) -> dict:
url = "https://images-api.nasa.gov/search"
return httpx.get(url, params={"q": query}, timeout=10).json()
if __name__ == "__main__":
print(save_apod("YOUR API KEY"))
apollo_2011_items = get_archive_data("apollo 2011")["collection"]["items"]
print(apollo_2011_items[0]["data"][0]["description"]) | --- +++ @@ -9,6 +9,10 @@
def get_apod_data(api_key: str) -> dict:
+ """
+ Get the APOD(Astronomical Picture of the day) data
+ Get your API Key from: https://api.nasa.gov/
+ """
url = "https://api.nasa.gov/planetary/apod"
return httpx.get(url, params={"api_key": api_key}, timeout=10).json()
@@ -26,6 +30,9 @@
def get_archive_data(query: str) -> dict:
+ """
+ Get the data of a particular query from NASA archives
+ """
url = "https://images-api.nasa.gov/search"
return httpx.get(url, params={"q": query}, timeout=10).json()
@@ -33,4 +40,4 @@ if __name__ == "__main__":
print(save_apod("YOUR API KEY"))
apollo_2011_items = get_archive_data("apollo 2011")["collection"]["items"]
- print(apollo_2011_items[0]["data"][0]["description"])+ print(apollo_2011_items[0]["data"][0]["description"])
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/nasa_data.py |
Create Google-style docstrings for my code | #!/usr/bin/env python3
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "beautifulsoup4",
# "httpx",
# ]
# ///
import httpx
from bs4 import BeautifulSoup
def world_covid19_stats(
url: str = "https://www.worldometers.info/coronavirus/",
) -> dict:
soup = BeautifulSoup(
httpx.get(url, timeout=10, follow_redirects=True).text, "html.parser"
)
keys = soup.find_all("h1")
values = soup.find_all("div", {"class": "maincounter-number"})
keys += soup.find_all("span", {"class": "panel-title"})
values += soup.find_all("div", {"class": "number-table-main"})
return {key.text.strip(): value.text.strip() for key, value in zip(keys, values)}
if __name__ == "__main__":
print("\033[1m COVID-19 Status of the World \033[0m\n")
print("\n".join(f"{key}\n{value}" for key, value in world_covid19_stats().items())) | --- +++ @@ -1,5 +1,9 @@ #!/usr/bin/env python3
+"""
+Provide the current worldwide COVID-19 statistics.
+This data is being scrapped from 'https://www.worldometers.info/coronavirus/'.
+"""
# /// script
# requires-python = ">=3.13"
@@ -16,6 +20,9 @@ def world_covid19_stats(
url: str = "https://www.worldometers.info/coronavirus/",
) -> dict:
+ """
+ Return a dict of current worldwide COVID-19 statistics
+ """
soup = BeautifulSoup(
httpx.get(url, timeout=10, follow_redirects=True).text, "html.parser"
)
@@ -28,4 +35,4 @@
if __name__ == "__main__":
print("\033[1m COVID-19 Status of the World \033[0m\n")
- print("\n".join(f"{key}\n{value}" for key, value in world_covid19_stats().items()))+ print("\n".join(f"{key}\n{value}" for key, value in world_covid19_stats().items()))
| https://raw.githubusercontent.com/TheAlgorithms/Python/HEAD/web_programming/world_covid19_stats.py |
Document helper functions with docstrings | from __future__ import annotations
import gradio as gr
import logging
import os
import re
import lora_patches
import network
import network_lora
import network_glora
import network_hada
import network_ia3
import network_lokr
import network_full
import network_norm
import network_oft
import torch
from typing import Union
from modules import shared, devices, sd_models, errors, scripts, sd_hijack
import modules.textual_inversion.textual_inversion as textual_inversion
import modules.models.sd3.mmdit
from lora_logger import logger
module_types = [
network_lora.ModuleTypeLora(),
network_hada.ModuleTypeHada(),
network_ia3.ModuleTypeIa3(),
network_lokr.ModuleTypeLokr(),
network_full.ModuleTypeFull(),
network_norm.ModuleTypeNorm(),
network_glora.ModuleTypeGLora(),
network_oft.ModuleTypeOFT(),
]
re_digits = re.compile(r"\d+")
re_x_proj = re.compile(r"(.*)_([qkv]_proj)$")
re_compiled = {}
suffix_conversion = {
"attentions": {},
"resnets": {
"conv1": "in_layers_2",
"conv2": "out_layers_3",
"norm1": "in_layers_0",
"norm2": "out_layers_0",
"time_emb_proj": "emb_layers_1",
"conv_shortcut": "skip_connection",
}
}
def convert_diffusers_name_to_compvis(key, is_sd2):
def match(match_list, regex_text):
regex = re_compiled.get(regex_text)
if regex is None:
regex = re.compile(regex_text)
re_compiled[regex_text] = regex
r = re.match(regex, key)
if not r:
return False
match_list.clear()
match_list.extend([int(x) if re.match(re_digits, x) else x for x in r.groups()])
return True
m = []
if match(m, r"lora_unet_conv_in(.*)"):
return f'diffusion_model_input_blocks_0_0{m[0]}'
if match(m, r"lora_unet_conv_out(.*)"):
return f'diffusion_model_out_2{m[0]}'
if match(m, r"lora_unet_time_embedding_linear_(\d+)(.*)"):
return f"diffusion_model_time_embed_{m[0] * 2 - 2}{m[1]}"
if match(m, r"lora_unet_down_blocks_(\d+)_(attentions|resnets)_(\d+)_(.+)"):
suffix = suffix_conversion.get(m[1], {}).get(m[3], m[3])
return f"diffusion_model_input_blocks_{1 + m[0] * 3 + m[2]}_{1 if m[1] == 'attentions' else 0}_{suffix}"
if match(m, r"lora_unet_mid_block_(attentions|resnets)_(\d+)_(.+)"):
suffix = suffix_conversion.get(m[0], {}).get(m[2], m[2])
return f"diffusion_model_middle_block_{1 if m[0] == 'attentions' else m[1] * 2}_{suffix}"
if match(m, r"lora_unet_up_blocks_(\d+)_(attentions|resnets)_(\d+)_(.+)"):
suffix = suffix_conversion.get(m[1], {}).get(m[3], m[3])
return f"diffusion_model_output_blocks_{m[0] * 3 + m[2]}_{1 if m[1] == 'attentions' else 0}_{suffix}"
if match(m, r"lora_unet_down_blocks_(\d+)_downsamplers_0_conv"):
return f"diffusion_model_input_blocks_{3 + m[0] * 3}_0_op"
if match(m, r"lora_unet_up_blocks_(\d+)_upsamplers_0_conv"):
return f"diffusion_model_output_blocks_{2 + m[0] * 3}_{2 if m[0]>0 else 1}_conv"
if match(m, r"lora_te_text_model_encoder_layers_(\d+)_(.+)"):
if is_sd2:
if 'mlp_fc1' in m[1]:
return f"model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc1', 'mlp_c_fc')}"
elif 'mlp_fc2' in m[1]:
return f"model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc2', 'mlp_c_proj')}"
else:
return f"model_transformer_resblocks_{m[0]}_{m[1].replace('self_attn', 'attn')}"
return f"transformer_text_model_encoder_layers_{m[0]}_{m[1]}"
if match(m, r"lora_te2_text_model_encoder_layers_(\d+)_(.+)"):
if 'mlp_fc1' in m[1]:
return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc1', 'mlp_c_fc')}"
elif 'mlp_fc2' in m[1]:
return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc2', 'mlp_c_proj')}"
else:
return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('self_attn', 'attn')}"
return key
def assign_network_names_to_compvis_modules(sd_model):
network_layer_mapping = {}
if shared.sd_model.is_sdxl:
for i, embedder in enumerate(shared.sd_model.conditioner.embedders):
if not hasattr(embedder, 'wrapped'):
continue
for name, module in embedder.wrapped.named_modules():
network_name = f'{i}_{name.replace(".", "_")}'
network_layer_mapping[network_name] = module
module.network_layer_name = network_name
else:
cond_stage_model = getattr(shared.sd_model.cond_stage_model, 'wrapped', shared.sd_model.cond_stage_model)
for name, module in cond_stage_model.named_modules():
network_name = name.replace(".", "_")
network_layer_mapping[network_name] = module
module.network_layer_name = network_name
for name, module in shared.sd_model.model.named_modules():
network_name = name.replace(".", "_")
network_layer_mapping[network_name] = module
module.network_layer_name = network_name
sd_model.network_layer_mapping = network_layer_mapping
class BundledTIHash(str):
def __init__(self, hash_str):
self.hash = hash_str
def __str__(self):
return self.hash if shared.opts.lora_bundled_ti_to_infotext else ''
def load_network(name, network_on_disk):
net = network.Network(name, network_on_disk)
net.mtime = os.path.getmtime(network_on_disk.filename)
sd = sd_models.read_state_dict(network_on_disk.filename)
# this should not be needed but is here as an emergency fix for an unknown error people are experiencing in 1.2.0
if not hasattr(shared.sd_model, 'network_layer_mapping'):
assign_network_names_to_compvis_modules(shared.sd_model)
keys_failed_to_match = {}
is_sd2 = 'model_transformer_resblocks' in shared.sd_model.network_layer_mapping
if hasattr(shared.sd_model, 'diffusers_weight_map'):
diffusers_weight_map = shared.sd_model.diffusers_weight_map
elif hasattr(shared.sd_model, 'diffusers_weight_mapping'):
diffusers_weight_map = {}
for k, v in shared.sd_model.diffusers_weight_mapping():
diffusers_weight_map[k] = v
shared.sd_model.diffusers_weight_map = diffusers_weight_map
else:
diffusers_weight_map = None
matched_networks = {}
bundle_embeddings = {}
for key_network, weight in sd.items():
if diffusers_weight_map:
key_network_without_network_parts, network_name, network_weight = key_network.rsplit(".", 2)
network_part = network_name + '.' + network_weight
else:
key_network_without_network_parts, _, network_part = key_network.partition(".")
if key_network_without_network_parts == "bundle_emb":
emb_name, vec_name = network_part.split(".", 1)
emb_dict = bundle_embeddings.get(emb_name, {})
if vec_name.split('.')[0] == 'string_to_param':
_, k2 = vec_name.split('.', 1)
emb_dict['string_to_param'] = {k2: weight}
else:
emb_dict[vec_name] = weight
bundle_embeddings[emb_name] = emb_dict
if diffusers_weight_map:
key = diffusers_weight_map.get(key_network_without_network_parts, key_network_without_network_parts)
else:
key = convert_diffusers_name_to_compvis(key_network_without_network_parts, is_sd2)
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
if sd_module is None:
m = re_x_proj.match(key)
if m:
sd_module = shared.sd_model.network_layer_mapping.get(m.group(1), None)
# SDXL loras seem to already have correct compvis keys, so only need to replace "lora_unet" with "diffusion_model"
if sd_module is None and "lora_unet" in key_network_without_network_parts:
key = key_network_without_network_parts.replace("lora_unet", "diffusion_model")
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
elif sd_module is None and "lora_te1_text_model" in key_network_without_network_parts:
key = key_network_without_network_parts.replace("lora_te1_text_model", "0_transformer_text_model")
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
# some SD1 Loras also have correct compvis keys
if sd_module is None:
key = key_network_without_network_parts.replace("lora_te1_text_model", "transformer_text_model")
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
# kohya_ss OFT module
elif sd_module is None and "oft_unet" in key_network_without_network_parts:
key = key_network_without_network_parts.replace("oft_unet", "diffusion_model")
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
# KohakuBlueLeaf OFT module
if sd_module is None and "oft_diag" in key:
key = key_network_without_network_parts.replace("lora_unet", "diffusion_model")
key = key_network_without_network_parts.replace("lora_te1_text_model", "0_transformer_text_model")
sd_module = shared.sd_model.network_layer_mapping.get(key, None)
if sd_module is None:
keys_failed_to_match[key_network] = key
continue
if key not in matched_networks:
matched_networks[key] = network.NetworkWeights(network_key=key_network, sd_key=key, w={}, sd_module=sd_module)
matched_networks[key].w[network_part] = weight
for key, weights in matched_networks.items():
net_module = None
for nettype in module_types:
net_module = nettype.create_module(net, weights)
if net_module is not None:
break
if net_module is None:
raise AssertionError(f"Could not find a module type (out of {', '.join([x.__class__.__name__ for x in module_types])}) that would accept those keys: {', '.join(weights.w)}")
net.modules[key] = net_module
embeddings = {}
for emb_name, data in bundle_embeddings.items():
embedding = textual_inversion.create_embedding_from_data(data, emb_name, filename=network_on_disk.filename + "/" + emb_name)
embedding.loaded = None
embedding.shorthash = BundledTIHash(name)
embeddings[emb_name] = embedding
net.bundle_embeddings = embeddings
if keys_failed_to_match:
logging.debug(f"Network {network_on_disk.filename} didn't match keys: {keys_failed_to_match}")
return net
def purge_networks_from_memory():
while len(networks_in_memory) > shared.opts.lora_in_memory_limit and len(networks_in_memory) > 0:
name = next(iter(networks_in_memory))
networks_in_memory.pop(name, None)
devices.torch_gc()
def load_networks(names, te_multipliers=None, unet_multipliers=None, dyn_dims=None):
emb_db = sd_hijack.model_hijack.embedding_db
already_loaded = {}
for net in loaded_networks:
if net.name in names:
already_loaded[net.name] = net
for emb_name, embedding in net.bundle_embeddings.items():
if embedding.loaded:
emb_db.register_embedding_by_name(None, shared.sd_model, emb_name)
loaded_networks.clear()
unavailable_networks = []
for name in names:
if name.lower() in forbidden_network_aliases and available_networks.get(name) is None:
unavailable_networks.append(name)
elif available_network_aliases.get(name) is None:
unavailable_networks.append(name)
if unavailable_networks:
update_available_networks_by_names(unavailable_networks)
networks_on_disk = [available_networks.get(name, None) if name.lower() in forbidden_network_aliases else available_network_aliases.get(name, None) for name in names]
if any(x is None for x in networks_on_disk):
list_available_networks()
networks_on_disk = [available_networks.get(name, None) if name.lower() in forbidden_network_aliases else available_network_aliases.get(name, None) for name in names]
failed_to_load_networks = []
for i, (network_on_disk, name) in enumerate(zip(networks_on_disk, names)):
net = already_loaded.get(name, None)
if network_on_disk is not None:
if net is None:
net = networks_in_memory.get(name)
if net is None or os.path.getmtime(network_on_disk.filename) > net.mtime:
try:
net = load_network(name, network_on_disk)
networks_in_memory.pop(name, None)
networks_in_memory[name] = net
except Exception as e:
errors.display(e, f"loading network {network_on_disk.filename}")
continue
net.mentioned_name = name
network_on_disk.read_hash()
if net is None:
failed_to_load_networks.append(name)
logging.info(f"Couldn't find network with name {name}")
continue
net.te_multiplier = te_multipliers[i] if te_multipliers else 1.0
net.unet_multiplier = unet_multipliers[i] if unet_multipliers else 1.0
net.dyn_dim = dyn_dims[i] if dyn_dims else 1.0
loaded_networks.append(net)
for emb_name, embedding in net.bundle_embeddings.items():
if embedding.loaded is None and emb_name in emb_db.word_embeddings:
logger.warning(
f'Skip bundle embedding: "{emb_name}"'
' as it was already loaded from embeddings folder'
)
continue
embedding.loaded = False
if emb_db.expected_shape == -1 or emb_db.expected_shape == embedding.shape:
embedding.loaded = True
emb_db.register_embedding(embedding, shared.sd_model)
else:
emb_db.skipped_embeddings[name] = embedding
if failed_to_load_networks:
lora_not_found_message = f'Lora not found: {", ".join(failed_to_load_networks)}'
sd_hijack.model_hijack.comments.append(lora_not_found_message)
if shared.opts.lora_not_found_warning_console:
print(f'\n{lora_not_found_message}\n')
if shared.opts.lora_not_found_gradio_warning:
gr.Warning(lora_not_found_message)
purge_networks_from_memory()
def allowed_layer_without_weight(layer):
if isinstance(layer, torch.nn.LayerNorm) and not layer.elementwise_affine:
return True
return False
def store_weights_backup(weight):
if weight is None:
return None
return weight.to(devices.cpu, copy=True)
def restore_weights_backup(obj, field, weight):
if weight is None:
setattr(obj, field, None)
return
getattr(obj, field).copy_(weight)
def network_restore_weights_from_backup(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.GroupNorm, torch.nn.LayerNorm, torch.nn.MultiheadAttention]):
weights_backup = getattr(self, "network_weights_backup", None)
bias_backup = getattr(self, "network_bias_backup", None)
if weights_backup is None and bias_backup is None:
return
if weights_backup is not None:
if isinstance(self, torch.nn.MultiheadAttention):
restore_weights_backup(self, 'in_proj_weight', weights_backup[0])
restore_weights_backup(self.out_proj, 'weight', weights_backup[1])
else:
restore_weights_backup(self, 'weight', weights_backup)
if isinstance(self, torch.nn.MultiheadAttention):
restore_weights_backup(self.out_proj, 'bias', bias_backup)
else:
restore_weights_backup(self, 'bias', bias_backup)
def network_apply_weights(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.GroupNorm, torch.nn.LayerNorm, torch.nn.MultiheadAttention]):
network_layer_name = getattr(self, 'network_layer_name', None)
if network_layer_name is None:
return
current_names = getattr(self, "network_current_names", ())
wanted_names = tuple((x.name, x.te_multiplier, x.unet_multiplier, x.dyn_dim) for x in loaded_networks)
weights_backup = getattr(self, "network_weights_backup", None)
if weights_backup is None and wanted_names != ():
if current_names != () and not allowed_layer_without_weight(self):
raise RuntimeError(f"{network_layer_name} - no backup weights found and current weights are not unchanged")
if isinstance(self, torch.nn.MultiheadAttention):
weights_backup = (store_weights_backup(self.in_proj_weight), store_weights_backup(self.out_proj.weight))
else:
weights_backup = store_weights_backup(self.weight)
self.network_weights_backup = weights_backup
bias_backup = getattr(self, "network_bias_backup", None)
if bias_backup is None and wanted_names != ():
if isinstance(self, torch.nn.MultiheadAttention) and self.out_proj.bias is not None:
bias_backup = store_weights_backup(self.out_proj.bias)
elif getattr(self, 'bias', None) is not None:
bias_backup = store_weights_backup(self.bias)
else:
bias_backup = None
# Unlike weight which always has value, some modules don't have bias.
# Only report if bias is not None and current bias are not unchanged.
if bias_backup is not None and current_names != ():
raise RuntimeError("no backup bias found and current bias are not unchanged")
self.network_bias_backup = bias_backup
if current_names != wanted_names:
network_restore_weights_from_backup(self)
for net in loaded_networks:
module = net.modules.get(network_layer_name, None)
if module is not None and hasattr(self, 'weight') and not isinstance(module, modules.models.sd3.mmdit.QkvLinear):
try:
with torch.no_grad():
if getattr(self, 'fp16_weight', None) is None:
weight = self.weight
bias = self.bias
else:
weight = self.fp16_weight.clone().to(self.weight.device)
bias = getattr(self, 'fp16_bias', None)
if bias is not None:
bias = bias.clone().to(self.bias.device)
updown, ex_bias = module.calc_updown(weight)
if len(weight.shape) == 4 and weight.shape[1] == 9:
# inpainting model. zero pad updown to make channel[1] 4 to 9
updown = torch.nn.functional.pad(updown, (0, 0, 0, 0, 0, 5))
self.weight.copy_((weight.to(dtype=updown.dtype) + updown).to(dtype=self.weight.dtype))
if ex_bias is not None and hasattr(self, 'bias'):
if self.bias is None:
self.bias = torch.nn.Parameter(ex_bias).to(self.weight.dtype)
else:
self.bias.copy_((bias + ex_bias).to(dtype=self.bias.dtype))
except RuntimeError as e:
logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
continue
module_q = net.modules.get(network_layer_name + "_q_proj", None)
module_k = net.modules.get(network_layer_name + "_k_proj", None)
module_v = net.modules.get(network_layer_name + "_v_proj", None)
module_out = net.modules.get(network_layer_name + "_out_proj", None)
if isinstance(self, torch.nn.MultiheadAttention) and module_q and module_k and module_v and module_out:
try:
with torch.no_grad():
# Send "real" orig_weight into MHA's lora module
qw, kw, vw = self.in_proj_weight.chunk(3, 0)
updown_q, _ = module_q.calc_updown(qw)
updown_k, _ = module_k.calc_updown(kw)
updown_v, _ = module_v.calc_updown(vw)
del qw, kw, vw
updown_qkv = torch.vstack([updown_q, updown_k, updown_v])
updown_out, ex_bias = module_out.calc_updown(self.out_proj.weight)
self.in_proj_weight += updown_qkv
self.out_proj.weight += updown_out
if ex_bias is not None:
if self.out_proj.bias is None:
self.out_proj.bias = torch.nn.Parameter(ex_bias)
else:
self.out_proj.bias += ex_bias
except RuntimeError as e:
logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
continue
if isinstance(self, modules.models.sd3.mmdit.QkvLinear) and module_q and module_k and module_v:
try:
with torch.no_grad():
# Send "real" orig_weight into MHA's lora module
qw, kw, vw = self.weight.chunk(3, 0)
updown_q, _ = module_q.calc_updown(qw)
updown_k, _ = module_k.calc_updown(kw)
updown_v, _ = module_v.calc_updown(vw)
del qw, kw, vw
updown_qkv = torch.vstack([updown_q, updown_k, updown_v])
self.weight += updown_qkv
except RuntimeError as e:
logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
continue
if module is None:
continue
logging.debug(f"Network {net.name} layer {network_layer_name}: couldn't find supported operation")
extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
self.network_current_names = wanted_names
def network_forward(org_module, input, original_forward):
if len(loaded_networks) == 0:
return original_forward(org_module, input)
input = devices.cond_cast_unet(input)
network_restore_weights_from_backup(org_module)
network_reset_cached_weight(org_module)
y = original_forward(org_module, input)
network_layer_name = getattr(org_module, 'network_layer_name', None)
for lora in loaded_networks:
module = lora.modules.get(network_layer_name, None)
if module is None:
continue
y = module.forward(input, y)
return y
def network_reset_cached_weight(self: Union[torch.nn.Conv2d, torch.nn.Linear]):
self.network_current_names = ()
self.network_weights_backup = None
self.network_bias_backup = None
def network_Linear_forward(self, input):
if shared.opts.lora_functional:
return network_forward(self, input, originals.Linear_forward)
network_apply_weights(self)
return originals.Linear_forward(self, input)
def network_Linear_load_state_dict(self, *args, **kwargs):
network_reset_cached_weight(self)
return originals.Linear_load_state_dict(self, *args, **kwargs)
def network_Conv2d_forward(self, input):
if shared.opts.lora_functional:
return network_forward(self, input, originals.Conv2d_forward)
network_apply_weights(self)
return originals.Conv2d_forward(self, input)
def network_Conv2d_load_state_dict(self, *args, **kwargs):
network_reset_cached_weight(self)
return originals.Conv2d_load_state_dict(self, *args, **kwargs)
def network_GroupNorm_forward(self, input):
if shared.opts.lora_functional:
return network_forward(self, input, originals.GroupNorm_forward)
network_apply_weights(self)
return originals.GroupNorm_forward(self, input)
def network_GroupNorm_load_state_dict(self, *args, **kwargs):
network_reset_cached_weight(self)
return originals.GroupNorm_load_state_dict(self, *args, **kwargs)
def network_LayerNorm_forward(self, input):
if shared.opts.lora_functional:
return network_forward(self, input, originals.LayerNorm_forward)
network_apply_weights(self)
return originals.LayerNorm_forward(self, input)
def network_LayerNorm_load_state_dict(self, *args, **kwargs):
network_reset_cached_weight(self)
return originals.LayerNorm_load_state_dict(self, *args, **kwargs)
def network_MultiheadAttention_forward(self, *args, **kwargs):
network_apply_weights(self)
return originals.MultiheadAttention_forward(self, *args, **kwargs)
def network_MultiheadAttention_load_state_dict(self, *args, **kwargs):
network_reset_cached_weight(self)
return originals.MultiheadAttention_load_state_dict(self, *args, **kwargs)
def process_network_files(names: list[str] | None = None):
candidates = list(shared.walk_files(shared.cmd_opts.lora_dir, allowed_extensions=[".pt", ".ckpt", ".safetensors"]))
candidates += list(shared.walk_files(shared.cmd_opts.lyco_dir_backcompat, allowed_extensions=[".pt", ".ckpt", ".safetensors"]))
for filename in candidates:
if os.path.isdir(filename):
continue
name = os.path.splitext(os.path.basename(filename))[0]
# if names is provided, only load networks with names in the list
if names and name not in names:
continue
try:
entry = network.NetworkOnDisk(name, filename)
except OSError: # should catch FileNotFoundError and PermissionError etc.
errors.report(f"Failed to load network {name} from {filename}", exc_info=True)
continue
available_networks[name] = entry
if entry.alias in available_network_aliases:
forbidden_network_aliases[entry.alias.lower()] = 1
available_network_aliases[name] = entry
available_network_aliases[entry.alias] = entry
def update_available_networks_by_names(names: list[str]):
process_network_files(names)
def list_available_networks():
available_networks.clear()
available_network_aliases.clear()
forbidden_network_aliases.clear()
available_network_hash_lookup.clear()
forbidden_network_aliases.update({"none": 1, "Addams": 1})
os.makedirs(shared.cmd_opts.lora_dir, exist_ok=True)
process_network_files()
re_network_name = re.compile(r"(.*)\s*\([0-9a-fA-F]+\)")
def infotext_pasted(infotext, params):
if "AddNet Module 1" in [x[1] for x in scripts.scripts_txt2img.infotext_fields]:
return # if the other extension is active, it will handle those fields, no need to do anything
added = []
for k in params:
if not k.startswith("AddNet Model "):
continue
num = k[13:]
if params.get("AddNet Module " + num) != "LoRA":
continue
name = params.get("AddNet Model " + num)
if name is None:
continue
m = re_network_name.match(name)
if m:
name = m.group(1)
multiplier = params.get("AddNet Weight A " + num, "1.0")
added.append(f"<lora:{name}:{multiplier}>")
if added:
params["Prompt"] += "\n" + "".join(added)
originals: lora_patches.LoraPatches = None
extra_network_lora = None
available_networks = {}
available_network_aliases = {}
loaded_networks = []
loaded_bundle_embeddings = {}
networks_in_memory = {}
available_network_hash_lookup = {}
forbidden_network_aliases = {}
list_available_networks() | --- +++ @@ -1,728 +1,737 @@-from __future__ import annotations
-import gradio as gr
-import logging
-import os
-import re
-
-import lora_patches
-import network
-import network_lora
-import network_glora
-import network_hada
-import network_ia3
-import network_lokr
-import network_full
-import network_norm
-import network_oft
-
-import torch
-from typing import Union
-
-from modules import shared, devices, sd_models, errors, scripts, sd_hijack
-import modules.textual_inversion.textual_inversion as textual_inversion
-import modules.models.sd3.mmdit
-
-from lora_logger import logger
-
-module_types = [
- network_lora.ModuleTypeLora(),
- network_hada.ModuleTypeHada(),
- network_ia3.ModuleTypeIa3(),
- network_lokr.ModuleTypeLokr(),
- network_full.ModuleTypeFull(),
- network_norm.ModuleTypeNorm(),
- network_glora.ModuleTypeGLora(),
- network_oft.ModuleTypeOFT(),
-]
-
-
-re_digits = re.compile(r"\d+")
-re_x_proj = re.compile(r"(.*)_([qkv]_proj)$")
-re_compiled = {}
-
-suffix_conversion = {
- "attentions": {},
- "resnets": {
- "conv1": "in_layers_2",
- "conv2": "out_layers_3",
- "norm1": "in_layers_0",
- "norm2": "out_layers_0",
- "time_emb_proj": "emb_layers_1",
- "conv_shortcut": "skip_connection",
- }
-}
-
-
-def convert_diffusers_name_to_compvis(key, is_sd2):
- def match(match_list, regex_text):
- regex = re_compiled.get(regex_text)
- if regex is None:
- regex = re.compile(regex_text)
- re_compiled[regex_text] = regex
-
- r = re.match(regex, key)
- if not r:
- return False
-
- match_list.clear()
- match_list.extend([int(x) if re.match(re_digits, x) else x for x in r.groups()])
- return True
-
- m = []
-
- if match(m, r"lora_unet_conv_in(.*)"):
- return f'diffusion_model_input_blocks_0_0{m[0]}'
-
- if match(m, r"lora_unet_conv_out(.*)"):
- return f'diffusion_model_out_2{m[0]}'
-
- if match(m, r"lora_unet_time_embedding_linear_(\d+)(.*)"):
- return f"diffusion_model_time_embed_{m[0] * 2 - 2}{m[1]}"
-
- if match(m, r"lora_unet_down_blocks_(\d+)_(attentions|resnets)_(\d+)_(.+)"):
- suffix = suffix_conversion.get(m[1], {}).get(m[3], m[3])
- return f"diffusion_model_input_blocks_{1 + m[0] * 3 + m[2]}_{1 if m[1] == 'attentions' else 0}_{suffix}"
-
- if match(m, r"lora_unet_mid_block_(attentions|resnets)_(\d+)_(.+)"):
- suffix = suffix_conversion.get(m[0], {}).get(m[2], m[2])
- return f"diffusion_model_middle_block_{1 if m[0] == 'attentions' else m[1] * 2}_{suffix}"
-
- if match(m, r"lora_unet_up_blocks_(\d+)_(attentions|resnets)_(\d+)_(.+)"):
- suffix = suffix_conversion.get(m[1], {}).get(m[3], m[3])
- return f"diffusion_model_output_blocks_{m[0] * 3 + m[2]}_{1 if m[1] == 'attentions' else 0}_{suffix}"
-
- if match(m, r"lora_unet_down_blocks_(\d+)_downsamplers_0_conv"):
- return f"diffusion_model_input_blocks_{3 + m[0] * 3}_0_op"
-
- if match(m, r"lora_unet_up_blocks_(\d+)_upsamplers_0_conv"):
- return f"diffusion_model_output_blocks_{2 + m[0] * 3}_{2 if m[0]>0 else 1}_conv"
-
- if match(m, r"lora_te_text_model_encoder_layers_(\d+)_(.+)"):
- if is_sd2:
- if 'mlp_fc1' in m[1]:
- return f"model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc1', 'mlp_c_fc')}"
- elif 'mlp_fc2' in m[1]:
- return f"model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc2', 'mlp_c_proj')}"
- else:
- return f"model_transformer_resblocks_{m[0]}_{m[1].replace('self_attn', 'attn')}"
-
- return f"transformer_text_model_encoder_layers_{m[0]}_{m[1]}"
-
- if match(m, r"lora_te2_text_model_encoder_layers_(\d+)_(.+)"):
- if 'mlp_fc1' in m[1]:
- return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc1', 'mlp_c_fc')}"
- elif 'mlp_fc2' in m[1]:
- return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc2', 'mlp_c_proj')}"
- else:
- return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('self_attn', 'attn')}"
-
- return key
-
-
-def assign_network_names_to_compvis_modules(sd_model):
- network_layer_mapping = {}
-
- if shared.sd_model.is_sdxl:
- for i, embedder in enumerate(shared.sd_model.conditioner.embedders):
- if not hasattr(embedder, 'wrapped'):
- continue
-
- for name, module in embedder.wrapped.named_modules():
- network_name = f'{i}_{name.replace(".", "_")}'
- network_layer_mapping[network_name] = module
- module.network_layer_name = network_name
- else:
- cond_stage_model = getattr(shared.sd_model.cond_stage_model, 'wrapped', shared.sd_model.cond_stage_model)
-
- for name, module in cond_stage_model.named_modules():
- network_name = name.replace(".", "_")
- network_layer_mapping[network_name] = module
- module.network_layer_name = network_name
-
- for name, module in shared.sd_model.model.named_modules():
- network_name = name.replace(".", "_")
- network_layer_mapping[network_name] = module
- module.network_layer_name = network_name
-
- sd_model.network_layer_mapping = network_layer_mapping
-
-
-class BundledTIHash(str):
- def __init__(self, hash_str):
- self.hash = hash_str
-
- def __str__(self):
- return self.hash if shared.opts.lora_bundled_ti_to_infotext else ''
-
-
-def load_network(name, network_on_disk):
- net = network.Network(name, network_on_disk)
- net.mtime = os.path.getmtime(network_on_disk.filename)
-
- sd = sd_models.read_state_dict(network_on_disk.filename)
-
- # this should not be needed but is here as an emergency fix for an unknown error people are experiencing in 1.2.0
- if not hasattr(shared.sd_model, 'network_layer_mapping'):
- assign_network_names_to_compvis_modules(shared.sd_model)
-
- keys_failed_to_match = {}
- is_sd2 = 'model_transformer_resblocks' in shared.sd_model.network_layer_mapping
- if hasattr(shared.sd_model, 'diffusers_weight_map'):
- diffusers_weight_map = shared.sd_model.diffusers_weight_map
- elif hasattr(shared.sd_model, 'diffusers_weight_mapping'):
- diffusers_weight_map = {}
- for k, v in shared.sd_model.diffusers_weight_mapping():
- diffusers_weight_map[k] = v
- shared.sd_model.diffusers_weight_map = diffusers_weight_map
- else:
- diffusers_weight_map = None
-
- matched_networks = {}
- bundle_embeddings = {}
-
- for key_network, weight in sd.items():
-
- if diffusers_weight_map:
- key_network_without_network_parts, network_name, network_weight = key_network.rsplit(".", 2)
- network_part = network_name + '.' + network_weight
- else:
- key_network_without_network_parts, _, network_part = key_network.partition(".")
-
- if key_network_without_network_parts == "bundle_emb":
- emb_name, vec_name = network_part.split(".", 1)
- emb_dict = bundle_embeddings.get(emb_name, {})
- if vec_name.split('.')[0] == 'string_to_param':
- _, k2 = vec_name.split('.', 1)
- emb_dict['string_to_param'] = {k2: weight}
- else:
- emb_dict[vec_name] = weight
- bundle_embeddings[emb_name] = emb_dict
-
- if diffusers_weight_map:
- key = diffusers_weight_map.get(key_network_without_network_parts, key_network_without_network_parts)
- else:
- key = convert_diffusers_name_to_compvis(key_network_without_network_parts, is_sd2)
-
- sd_module = shared.sd_model.network_layer_mapping.get(key, None)
-
- if sd_module is None:
- m = re_x_proj.match(key)
- if m:
- sd_module = shared.sd_model.network_layer_mapping.get(m.group(1), None)
-
- # SDXL loras seem to already have correct compvis keys, so only need to replace "lora_unet" with "diffusion_model"
- if sd_module is None and "lora_unet" in key_network_without_network_parts:
- key = key_network_without_network_parts.replace("lora_unet", "diffusion_model")
- sd_module = shared.sd_model.network_layer_mapping.get(key, None)
- elif sd_module is None and "lora_te1_text_model" in key_network_without_network_parts:
- key = key_network_without_network_parts.replace("lora_te1_text_model", "0_transformer_text_model")
- sd_module = shared.sd_model.network_layer_mapping.get(key, None)
-
- # some SD1 Loras also have correct compvis keys
- if sd_module is None:
- key = key_network_without_network_parts.replace("lora_te1_text_model", "transformer_text_model")
- sd_module = shared.sd_model.network_layer_mapping.get(key, None)
-
- # kohya_ss OFT module
- elif sd_module is None and "oft_unet" in key_network_without_network_parts:
- key = key_network_without_network_parts.replace("oft_unet", "diffusion_model")
- sd_module = shared.sd_model.network_layer_mapping.get(key, None)
-
- # KohakuBlueLeaf OFT module
- if sd_module is None and "oft_diag" in key:
- key = key_network_without_network_parts.replace("lora_unet", "diffusion_model")
- key = key_network_without_network_parts.replace("lora_te1_text_model", "0_transformer_text_model")
- sd_module = shared.sd_model.network_layer_mapping.get(key, None)
-
- if sd_module is None:
- keys_failed_to_match[key_network] = key
- continue
-
- if key not in matched_networks:
- matched_networks[key] = network.NetworkWeights(network_key=key_network, sd_key=key, w={}, sd_module=sd_module)
-
- matched_networks[key].w[network_part] = weight
-
- for key, weights in matched_networks.items():
- net_module = None
- for nettype in module_types:
- net_module = nettype.create_module(net, weights)
- if net_module is not None:
- break
-
- if net_module is None:
- raise AssertionError(f"Could not find a module type (out of {', '.join([x.__class__.__name__ for x in module_types])}) that would accept those keys: {', '.join(weights.w)}")
-
- net.modules[key] = net_module
-
- embeddings = {}
- for emb_name, data in bundle_embeddings.items():
- embedding = textual_inversion.create_embedding_from_data(data, emb_name, filename=network_on_disk.filename + "/" + emb_name)
- embedding.loaded = None
- embedding.shorthash = BundledTIHash(name)
- embeddings[emb_name] = embedding
-
- net.bundle_embeddings = embeddings
-
- if keys_failed_to_match:
- logging.debug(f"Network {network_on_disk.filename} didn't match keys: {keys_failed_to_match}")
-
- return net
-
-
-def purge_networks_from_memory():
- while len(networks_in_memory) > shared.opts.lora_in_memory_limit and len(networks_in_memory) > 0:
- name = next(iter(networks_in_memory))
- networks_in_memory.pop(name, None)
-
- devices.torch_gc()
-
-
-def load_networks(names, te_multipliers=None, unet_multipliers=None, dyn_dims=None):
- emb_db = sd_hijack.model_hijack.embedding_db
- already_loaded = {}
-
- for net in loaded_networks:
- if net.name in names:
- already_loaded[net.name] = net
- for emb_name, embedding in net.bundle_embeddings.items():
- if embedding.loaded:
- emb_db.register_embedding_by_name(None, shared.sd_model, emb_name)
-
- loaded_networks.clear()
-
- unavailable_networks = []
- for name in names:
- if name.lower() in forbidden_network_aliases and available_networks.get(name) is None:
- unavailable_networks.append(name)
- elif available_network_aliases.get(name) is None:
- unavailable_networks.append(name)
-
- if unavailable_networks:
- update_available_networks_by_names(unavailable_networks)
-
- networks_on_disk = [available_networks.get(name, None) if name.lower() in forbidden_network_aliases else available_network_aliases.get(name, None) for name in names]
- if any(x is None for x in networks_on_disk):
- list_available_networks()
-
- networks_on_disk = [available_networks.get(name, None) if name.lower() in forbidden_network_aliases else available_network_aliases.get(name, None) for name in names]
-
- failed_to_load_networks = []
-
- for i, (network_on_disk, name) in enumerate(zip(networks_on_disk, names)):
- net = already_loaded.get(name, None)
-
- if network_on_disk is not None:
- if net is None:
- net = networks_in_memory.get(name)
-
- if net is None or os.path.getmtime(network_on_disk.filename) > net.mtime:
- try:
- net = load_network(name, network_on_disk)
-
- networks_in_memory.pop(name, None)
- networks_in_memory[name] = net
- except Exception as e:
- errors.display(e, f"loading network {network_on_disk.filename}")
- continue
-
- net.mentioned_name = name
-
- network_on_disk.read_hash()
-
- if net is None:
- failed_to_load_networks.append(name)
- logging.info(f"Couldn't find network with name {name}")
- continue
-
- net.te_multiplier = te_multipliers[i] if te_multipliers else 1.0
- net.unet_multiplier = unet_multipliers[i] if unet_multipliers else 1.0
- net.dyn_dim = dyn_dims[i] if dyn_dims else 1.0
- loaded_networks.append(net)
-
- for emb_name, embedding in net.bundle_embeddings.items():
- if embedding.loaded is None and emb_name in emb_db.word_embeddings:
- logger.warning(
- f'Skip bundle embedding: "{emb_name}"'
- ' as it was already loaded from embeddings folder'
- )
- continue
-
- embedding.loaded = False
- if emb_db.expected_shape == -1 or emb_db.expected_shape == embedding.shape:
- embedding.loaded = True
- emb_db.register_embedding(embedding, shared.sd_model)
- else:
- emb_db.skipped_embeddings[name] = embedding
-
- if failed_to_load_networks:
- lora_not_found_message = f'Lora not found: {", ".join(failed_to_load_networks)}'
- sd_hijack.model_hijack.comments.append(lora_not_found_message)
- if shared.opts.lora_not_found_warning_console:
- print(f'\n{lora_not_found_message}\n')
- if shared.opts.lora_not_found_gradio_warning:
- gr.Warning(lora_not_found_message)
-
- purge_networks_from_memory()
-
-
-def allowed_layer_without_weight(layer):
- if isinstance(layer, torch.nn.LayerNorm) and not layer.elementwise_affine:
- return True
-
- return False
-
-
-def store_weights_backup(weight):
- if weight is None:
- return None
-
- return weight.to(devices.cpu, copy=True)
-
-
-def restore_weights_backup(obj, field, weight):
- if weight is None:
- setattr(obj, field, None)
- return
-
- getattr(obj, field).copy_(weight)
-
-
-def network_restore_weights_from_backup(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.GroupNorm, torch.nn.LayerNorm, torch.nn.MultiheadAttention]):
- weights_backup = getattr(self, "network_weights_backup", None)
- bias_backup = getattr(self, "network_bias_backup", None)
-
- if weights_backup is None and bias_backup is None:
- return
-
- if weights_backup is not None:
- if isinstance(self, torch.nn.MultiheadAttention):
- restore_weights_backup(self, 'in_proj_weight', weights_backup[0])
- restore_weights_backup(self.out_proj, 'weight', weights_backup[1])
- else:
- restore_weights_backup(self, 'weight', weights_backup)
-
- if isinstance(self, torch.nn.MultiheadAttention):
- restore_weights_backup(self.out_proj, 'bias', bias_backup)
- else:
- restore_weights_backup(self, 'bias', bias_backup)
-
-
-def network_apply_weights(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.GroupNorm, torch.nn.LayerNorm, torch.nn.MultiheadAttention]):
-
- network_layer_name = getattr(self, 'network_layer_name', None)
- if network_layer_name is None:
- return
-
- current_names = getattr(self, "network_current_names", ())
- wanted_names = tuple((x.name, x.te_multiplier, x.unet_multiplier, x.dyn_dim) for x in loaded_networks)
-
- weights_backup = getattr(self, "network_weights_backup", None)
- if weights_backup is None and wanted_names != ():
- if current_names != () and not allowed_layer_without_weight(self):
- raise RuntimeError(f"{network_layer_name} - no backup weights found and current weights are not unchanged")
-
- if isinstance(self, torch.nn.MultiheadAttention):
- weights_backup = (store_weights_backup(self.in_proj_weight), store_weights_backup(self.out_proj.weight))
- else:
- weights_backup = store_weights_backup(self.weight)
-
- self.network_weights_backup = weights_backup
-
- bias_backup = getattr(self, "network_bias_backup", None)
- if bias_backup is None and wanted_names != ():
- if isinstance(self, torch.nn.MultiheadAttention) and self.out_proj.bias is not None:
- bias_backup = store_weights_backup(self.out_proj.bias)
- elif getattr(self, 'bias', None) is not None:
- bias_backup = store_weights_backup(self.bias)
- else:
- bias_backup = None
-
- # Unlike weight which always has value, some modules don't have bias.
- # Only report if bias is not None and current bias are not unchanged.
- if bias_backup is not None and current_names != ():
- raise RuntimeError("no backup bias found and current bias are not unchanged")
-
- self.network_bias_backup = bias_backup
-
- if current_names != wanted_names:
- network_restore_weights_from_backup(self)
-
- for net in loaded_networks:
- module = net.modules.get(network_layer_name, None)
- if module is not None and hasattr(self, 'weight') and not isinstance(module, modules.models.sd3.mmdit.QkvLinear):
- try:
- with torch.no_grad():
- if getattr(self, 'fp16_weight', None) is None:
- weight = self.weight
- bias = self.bias
- else:
- weight = self.fp16_weight.clone().to(self.weight.device)
- bias = getattr(self, 'fp16_bias', None)
- if bias is not None:
- bias = bias.clone().to(self.bias.device)
- updown, ex_bias = module.calc_updown(weight)
-
- if len(weight.shape) == 4 and weight.shape[1] == 9:
- # inpainting model. zero pad updown to make channel[1] 4 to 9
- updown = torch.nn.functional.pad(updown, (0, 0, 0, 0, 0, 5))
-
- self.weight.copy_((weight.to(dtype=updown.dtype) + updown).to(dtype=self.weight.dtype))
- if ex_bias is not None and hasattr(self, 'bias'):
- if self.bias is None:
- self.bias = torch.nn.Parameter(ex_bias).to(self.weight.dtype)
- else:
- self.bias.copy_((bias + ex_bias).to(dtype=self.bias.dtype))
- except RuntimeError as e:
- logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
- extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
-
- continue
-
- module_q = net.modules.get(network_layer_name + "_q_proj", None)
- module_k = net.modules.get(network_layer_name + "_k_proj", None)
- module_v = net.modules.get(network_layer_name + "_v_proj", None)
- module_out = net.modules.get(network_layer_name + "_out_proj", None)
-
- if isinstance(self, torch.nn.MultiheadAttention) and module_q and module_k and module_v and module_out:
- try:
- with torch.no_grad():
- # Send "real" orig_weight into MHA's lora module
- qw, kw, vw = self.in_proj_weight.chunk(3, 0)
- updown_q, _ = module_q.calc_updown(qw)
- updown_k, _ = module_k.calc_updown(kw)
- updown_v, _ = module_v.calc_updown(vw)
- del qw, kw, vw
- updown_qkv = torch.vstack([updown_q, updown_k, updown_v])
- updown_out, ex_bias = module_out.calc_updown(self.out_proj.weight)
-
- self.in_proj_weight += updown_qkv
- self.out_proj.weight += updown_out
- if ex_bias is not None:
- if self.out_proj.bias is None:
- self.out_proj.bias = torch.nn.Parameter(ex_bias)
- else:
- self.out_proj.bias += ex_bias
-
- except RuntimeError as e:
- logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
- extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
-
- continue
-
- if isinstance(self, modules.models.sd3.mmdit.QkvLinear) and module_q and module_k and module_v:
- try:
- with torch.no_grad():
- # Send "real" orig_weight into MHA's lora module
- qw, kw, vw = self.weight.chunk(3, 0)
- updown_q, _ = module_q.calc_updown(qw)
- updown_k, _ = module_k.calc_updown(kw)
- updown_v, _ = module_v.calc_updown(vw)
- del qw, kw, vw
- updown_qkv = torch.vstack([updown_q, updown_k, updown_v])
- self.weight += updown_qkv
-
- except RuntimeError as e:
- logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
- extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
-
- continue
-
- if module is None:
- continue
-
- logging.debug(f"Network {net.name} layer {network_layer_name}: couldn't find supported operation")
- extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
-
- self.network_current_names = wanted_names
-
-
-def network_forward(org_module, input, original_forward):
-
- if len(loaded_networks) == 0:
- return original_forward(org_module, input)
-
- input = devices.cond_cast_unet(input)
-
- network_restore_weights_from_backup(org_module)
- network_reset_cached_weight(org_module)
-
- y = original_forward(org_module, input)
-
- network_layer_name = getattr(org_module, 'network_layer_name', None)
- for lora in loaded_networks:
- module = lora.modules.get(network_layer_name, None)
- if module is None:
- continue
-
- y = module.forward(input, y)
-
- return y
-
-
-def network_reset_cached_weight(self: Union[torch.nn.Conv2d, torch.nn.Linear]):
- self.network_current_names = ()
- self.network_weights_backup = None
- self.network_bias_backup = None
-
-
-def network_Linear_forward(self, input):
- if shared.opts.lora_functional:
- return network_forward(self, input, originals.Linear_forward)
-
- network_apply_weights(self)
-
- return originals.Linear_forward(self, input)
-
-
-def network_Linear_load_state_dict(self, *args, **kwargs):
- network_reset_cached_weight(self)
-
- return originals.Linear_load_state_dict(self, *args, **kwargs)
-
-
-def network_Conv2d_forward(self, input):
- if shared.opts.lora_functional:
- return network_forward(self, input, originals.Conv2d_forward)
-
- network_apply_weights(self)
-
- return originals.Conv2d_forward(self, input)
-
-
-def network_Conv2d_load_state_dict(self, *args, **kwargs):
- network_reset_cached_weight(self)
-
- return originals.Conv2d_load_state_dict(self, *args, **kwargs)
-
-
-def network_GroupNorm_forward(self, input):
- if shared.opts.lora_functional:
- return network_forward(self, input, originals.GroupNorm_forward)
-
- network_apply_weights(self)
-
- return originals.GroupNorm_forward(self, input)
-
-
-def network_GroupNorm_load_state_dict(self, *args, **kwargs):
- network_reset_cached_weight(self)
-
- return originals.GroupNorm_load_state_dict(self, *args, **kwargs)
-
-
-def network_LayerNorm_forward(self, input):
- if shared.opts.lora_functional:
- return network_forward(self, input, originals.LayerNorm_forward)
-
- network_apply_weights(self)
-
- return originals.LayerNorm_forward(self, input)
-
-
-def network_LayerNorm_load_state_dict(self, *args, **kwargs):
- network_reset_cached_weight(self)
-
- return originals.LayerNorm_load_state_dict(self, *args, **kwargs)
-
-
-def network_MultiheadAttention_forward(self, *args, **kwargs):
- network_apply_weights(self)
-
- return originals.MultiheadAttention_forward(self, *args, **kwargs)
-
-
-def network_MultiheadAttention_load_state_dict(self, *args, **kwargs):
- network_reset_cached_weight(self)
-
- return originals.MultiheadAttention_load_state_dict(self, *args, **kwargs)
-
-
-def process_network_files(names: list[str] | None = None):
- candidates = list(shared.walk_files(shared.cmd_opts.lora_dir, allowed_extensions=[".pt", ".ckpt", ".safetensors"]))
- candidates += list(shared.walk_files(shared.cmd_opts.lyco_dir_backcompat, allowed_extensions=[".pt", ".ckpt", ".safetensors"]))
- for filename in candidates:
- if os.path.isdir(filename):
- continue
- name = os.path.splitext(os.path.basename(filename))[0]
- # if names is provided, only load networks with names in the list
- if names and name not in names:
- continue
- try:
- entry = network.NetworkOnDisk(name, filename)
- except OSError: # should catch FileNotFoundError and PermissionError etc.
- errors.report(f"Failed to load network {name} from {filename}", exc_info=True)
- continue
-
- available_networks[name] = entry
-
- if entry.alias in available_network_aliases:
- forbidden_network_aliases[entry.alias.lower()] = 1
-
- available_network_aliases[name] = entry
- available_network_aliases[entry.alias] = entry
-
-
-def update_available_networks_by_names(names: list[str]):
- process_network_files(names)
-
-
-def list_available_networks():
- available_networks.clear()
- available_network_aliases.clear()
- forbidden_network_aliases.clear()
- available_network_hash_lookup.clear()
- forbidden_network_aliases.update({"none": 1, "Addams": 1})
-
- os.makedirs(shared.cmd_opts.lora_dir, exist_ok=True)
-
- process_network_files()
-
-
-re_network_name = re.compile(r"(.*)\s*\([0-9a-fA-F]+\)")
-
-
-def infotext_pasted(infotext, params):
- if "AddNet Module 1" in [x[1] for x in scripts.scripts_txt2img.infotext_fields]:
- return # if the other extension is active, it will handle those fields, no need to do anything
-
- added = []
-
- for k in params:
- if not k.startswith("AddNet Model "):
- continue
-
- num = k[13:]
-
- if params.get("AddNet Module " + num) != "LoRA":
- continue
-
- name = params.get("AddNet Model " + num)
- if name is None:
- continue
-
- m = re_network_name.match(name)
- if m:
- name = m.group(1)
-
- multiplier = params.get("AddNet Weight A " + num, "1.0")
-
- added.append(f"<lora:{name}:{multiplier}>")
-
- if added:
- params["Prompt"] += "\n" + "".join(added)
-
-
-originals: lora_patches.LoraPatches = None
-
-extra_network_lora = None
-
-available_networks = {}
-available_network_aliases = {}
-loaded_networks = []
-loaded_bundle_embeddings = {}
-networks_in_memory = {}
-available_network_hash_lookup = {}
-forbidden_network_aliases = {}
-
-list_available_networks()+from __future__ import annotations
+import gradio as gr
+import logging
+import os
+import re
+
+import lora_patches
+import network
+import network_lora
+import network_glora
+import network_hada
+import network_ia3
+import network_lokr
+import network_full
+import network_norm
+import network_oft
+
+import torch
+from typing import Union
+
+from modules import shared, devices, sd_models, errors, scripts, sd_hijack
+import modules.textual_inversion.textual_inversion as textual_inversion
+import modules.models.sd3.mmdit
+
+from lora_logger import logger
+
+module_types = [
+ network_lora.ModuleTypeLora(),
+ network_hada.ModuleTypeHada(),
+ network_ia3.ModuleTypeIa3(),
+ network_lokr.ModuleTypeLokr(),
+ network_full.ModuleTypeFull(),
+ network_norm.ModuleTypeNorm(),
+ network_glora.ModuleTypeGLora(),
+ network_oft.ModuleTypeOFT(),
+]
+
+
+re_digits = re.compile(r"\d+")
+re_x_proj = re.compile(r"(.*)_([qkv]_proj)$")
+re_compiled = {}
+
+suffix_conversion = {
+ "attentions": {},
+ "resnets": {
+ "conv1": "in_layers_2",
+ "conv2": "out_layers_3",
+ "norm1": "in_layers_0",
+ "norm2": "out_layers_0",
+ "time_emb_proj": "emb_layers_1",
+ "conv_shortcut": "skip_connection",
+ }
+}
+
+
+def convert_diffusers_name_to_compvis(key, is_sd2):
+ def match(match_list, regex_text):
+ regex = re_compiled.get(regex_text)
+ if regex is None:
+ regex = re.compile(regex_text)
+ re_compiled[regex_text] = regex
+
+ r = re.match(regex, key)
+ if not r:
+ return False
+
+ match_list.clear()
+ match_list.extend([int(x) if re.match(re_digits, x) else x for x in r.groups()])
+ return True
+
+ m = []
+
+ if match(m, r"lora_unet_conv_in(.*)"):
+ return f'diffusion_model_input_blocks_0_0{m[0]}'
+
+ if match(m, r"lora_unet_conv_out(.*)"):
+ return f'diffusion_model_out_2{m[0]}'
+
+ if match(m, r"lora_unet_time_embedding_linear_(\d+)(.*)"):
+ return f"diffusion_model_time_embed_{m[0] * 2 - 2}{m[1]}"
+
+ if match(m, r"lora_unet_down_blocks_(\d+)_(attentions|resnets)_(\d+)_(.+)"):
+ suffix = suffix_conversion.get(m[1], {}).get(m[3], m[3])
+ return f"diffusion_model_input_blocks_{1 + m[0] * 3 + m[2]}_{1 if m[1] == 'attentions' else 0}_{suffix}"
+
+ if match(m, r"lora_unet_mid_block_(attentions|resnets)_(\d+)_(.+)"):
+ suffix = suffix_conversion.get(m[0], {}).get(m[2], m[2])
+ return f"diffusion_model_middle_block_{1 if m[0] == 'attentions' else m[1] * 2}_{suffix}"
+
+ if match(m, r"lora_unet_up_blocks_(\d+)_(attentions|resnets)_(\d+)_(.+)"):
+ suffix = suffix_conversion.get(m[1], {}).get(m[3], m[3])
+ return f"diffusion_model_output_blocks_{m[0] * 3 + m[2]}_{1 if m[1] == 'attentions' else 0}_{suffix}"
+
+ if match(m, r"lora_unet_down_blocks_(\d+)_downsamplers_0_conv"):
+ return f"diffusion_model_input_blocks_{3 + m[0] * 3}_0_op"
+
+ if match(m, r"lora_unet_up_blocks_(\d+)_upsamplers_0_conv"):
+ return f"diffusion_model_output_blocks_{2 + m[0] * 3}_{2 if m[0]>0 else 1}_conv"
+
+ if match(m, r"lora_te_text_model_encoder_layers_(\d+)_(.+)"):
+ if is_sd2:
+ if 'mlp_fc1' in m[1]:
+ return f"model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc1', 'mlp_c_fc')}"
+ elif 'mlp_fc2' in m[1]:
+ return f"model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc2', 'mlp_c_proj')}"
+ else:
+ return f"model_transformer_resblocks_{m[0]}_{m[1].replace('self_attn', 'attn')}"
+
+ return f"transformer_text_model_encoder_layers_{m[0]}_{m[1]}"
+
+ if match(m, r"lora_te2_text_model_encoder_layers_(\d+)_(.+)"):
+ if 'mlp_fc1' in m[1]:
+ return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc1', 'mlp_c_fc')}"
+ elif 'mlp_fc2' in m[1]:
+ return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('mlp_fc2', 'mlp_c_proj')}"
+ else:
+ return f"1_model_transformer_resblocks_{m[0]}_{m[1].replace('self_attn', 'attn')}"
+
+ return key
+
+
+def assign_network_names_to_compvis_modules(sd_model):
+ network_layer_mapping = {}
+
+ if shared.sd_model.is_sdxl:
+ for i, embedder in enumerate(shared.sd_model.conditioner.embedders):
+ if not hasattr(embedder, 'wrapped'):
+ continue
+
+ for name, module in embedder.wrapped.named_modules():
+ network_name = f'{i}_{name.replace(".", "_")}'
+ network_layer_mapping[network_name] = module
+ module.network_layer_name = network_name
+ else:
+ cond_stage_model = getattr(shared.sd_model.cond_stage_model, 'wrapped', shared.sd_model.cond_stage_model)
+
+ for name, module in cond_stage_model.named_modules():
+ network_name = name.replace(".", "_")
+ network_layer_mapping[network_name] = module
+ module.network_layer_name = network_name
+
+ for name, module in shared.sd_model.model.named_modules():
+ network_name = name.replace(".", "_")
+ network_layer_mapping[network_name] = module
+ module.network_layer_name = network_name
+
+ sd_model.network_layer_mapping = network_layer_mapping
+
+
+class BundledTIHash(str):
+ def __init__(self, hash_str):
+ self.hash = hash_str
+
+ def __str__(self):
+ return self.hash if shared.opts.lora_bundled_ti_to_infotext else ''
+
+
+def load_network(name, network_on_disk):
+ net = network.Network(name, network_on_disk)
+ net.mtime = os.path.getmtime(network_on_disk.filename)
+
+ sd = sd_models.read_state_dict(network_on_disk.filename)
+
+ # this should not be needed but is here as an emergency fix for an unknown error people are experiencing in 1.2.0
+ if not hasattr(shared.sd_model, 'network_layer_mapping'):
+ assign_network_names_to_compvis_modules(shared.sd_model)
+
+ keys_failed_to_match = {}
+ is_sd2 = 'model_transformer_resblocks' in shared.sd_model.network_layer_mapping
+ if hasattr(shared.sd_model, 'diffusers_weight_map'):
+ diffusers_weight_map = shared.sd_model.diffusers_weight_map
+ elif hasattr(shared.sd_model, 'diffusers_weight_mapping'):
+ diffusers_weight_map = {}
+ for k, v in shared.sd_model.diffusers_weight_mapping():
+ diffusers_weight_map[k] = v
+ shared.sd_model.diffusers_weight_map = diffusers_weight_map
+ else:
+ diffusers_weight_map = None
+
+ matched_networks = {}
+ bundle_embeddings = {}
+
+ for key_network, weight in sd.items():
+
+ if diffusers_weight_map:
+ key_network_without_network_parts, network_name, network_weight = key_network.rsplit(".", 2)
+ network_part = network_name + '.' + network_weight
+ else:
+ key_network_without_network_parts, _, network_part = key_network.partition(".")
+
+ if key_network_without_network_parts == "bundle_emb":
+ emb_name, vec_name = network_part.split(".", 1)
+ emb_dict = bundle_embeddings.get(emb_name, {})
+ if vec_name.split('.')[0] == 'string_to_param':
+ _, k2 = vec_name.split('.', 1)
+ emb_dict['string_to_param'] = {k2: weight}
+ else:
+ emb_dict[vec_name] = weight
+ bundle_embeddings[emb_name] = emb_dict
+
+ if diffusers_weight_map:
+ key = diffusers_weight_map.get(key_network_without_network_parts, key_network_without_network_parts)
+ else:
+ key = convert_diffusers_name_to_compvis(key_network_without_network_parts, is_sd2)
+
+ sd_module = shared.sd_model.network_layer_mapping.get(key, None)
+
+ if sd_module is None:
+ m = re_x_proj.match(key)
+ if m:
+ sd_module = shared.sd_model.network_layer_mapping.get(m.group(1), None)
+
+ # SDXL loras seem to already have correct compvis keys, so only need to replace "lora_unet" with "diffusion_model"
+ if sd_module is None and "lora_unet" in key_network_without_network_parts:
+ key = key_network_without_network_parts.replace("lora_unet", "diffusion_model")
+ sd_module = shared.sd_model.network_layer_mapping.get(key, None)
+ elif sd_module is None and "lora_te1_text_model" in key_network_without_network_parts:
+ key = key_network_without_network_parts.replace("lora_te1_text_model", "0_transformer_text_model")
+ sd_module = shared.sd_model.network_layer_mapping.get(key, None)
+
+ # some SD1 Loras also have correct compvis keys
+ if sd_module is None:
+ key = key_network_without_network_parts.replace("lora_te1_text_model", "transformer_text_model")
+ sd_module = shared.sd_model.network_layer_mapping.get(key, None)
+
+ # kohya_ss OFT module
+ elif sd_module is None and "oft_unet" in key_network_without_network_parts:
+ key = key_network_without_network_parts.replace("oft_unet", "diffusion_model")
+ sd_module = shared.sd_model.network_layer_mapping.get(key, None)
+
+ # KohakuBlueLeaf OFT module
+ if sd_module is None and "oft_diag" in key:
+ key = key_network_without_network_parts.replace("lora_unet", "diffusion_model")
+ key = key_network_without_network_parts.replace("lora_te1_text_model", "0_transformer_text_model")
+ sd_module = shared.sd_model.network_layer_mapping.get(key, None)
+
+ if sd_module is None:
+ keys_failed_to_match[key_network] = key
+ continue
+
+ if key not in matched_networks:
+ matched_networks[key] = network.NetworkWeights(network_key=key_network, sd_key=key, w={}, sd_module=sd_module)
+
+ matched_networks[key].w[network_part] = weight
+
+ for key, weights in matched_networks.items():
+ net_module = None
+ for nettype in module_types:
+ net_module = nettype.create_module(net, weights)
+ if net_module is not None:
+ break
+
+ if net_module is None:
+ raise AssertionError(f"Could not find a module type (out of {', '.join([x.__class__.__name__ for x in module_types])}) that would accept those keys: {', '.join(weights.w)}")
+
+ net.modules[key] = net_module
+
+ embeddings = {}
+ for emb_name, data in bundle_embeddings.items():
+ embedding = textual_inversion.create_embedding_from_data(data, emb_name, filename=network_on_disk.filename + "/" + emb_name)
+ embedding.loaded = None
+ embedding.shorthash = BundledTIHash(name)
+ embeddings[emb_name] = embedding
+
+ net.bundle_embeddings = embeddings
+
+ if keys_failed_to_match:
+ logging.debug(f"Network {network_on_disk.filename} didn't match keys: {keys_failed_to_match}")
+
+ return net
+
+
+def purge_networks_from_memory():
+ while len(networks_in_memory) > shared.opts.lora_in_memory_limit and len(networks_in_memory) > 0:
+ name = next(iter(networks_in_memory))
+ networks_in_memory.pop(name, None)
+
+ devices.torch_gc()
+
+
+def load_networks(names, te_multipliers=None, unet_multipliers=None, dyn_dims=None):
+ emb_db = sd_hijack.model_hijack.embedding_db
+ already_loaded = {}
+
+ for net in loaded_networks:
+ if net.name in names:
+ already_loaded[net.name] = net
+ for emb_name, embedding in net.bundle_embeddings.items():
+ if embedding.loaded:
+ emb_db.register_embedding_by_name(None, shared.sd_model, emb_name)
+
+ loaded_networks.clear()
+
+ unavailable_networks = []
+ for name in names:
+ if name.lower() in forbidden_network_aliases and available_networks.get(name) is None:
+ unavailable_networks.append(name)
+ elif available_network_aliases.get(name) is None:
+ unavailable_networks.append(name)
+
+ if unavailable_networks:
+ update_available_networks_by_names(unavailable_networks)
+
+ networks_on_disk = [available_networks.get(name, None) if name.lower() in forbidden_network_aliases else available_network_aliases.get(name, None) for name in names]
+ if any(x is None for x in networks_on_disk):
+ list_available_networks()
+
+ networks_on_disk = [available_networks.get(name, None) if name.lower() in forbidden_network_aliases else available_network_aliases.get(name, None) for name in names]
+
+ failed_to_load_networks = []
+
+ for i, (network_on_disk, name) in enumerate(zip(networks_on_disk, names)):
+ net = already_loaded.get(name, None)
+
+ if network_on_disk is not None:
+ if net is None:
+ net = networks_in_memory.get(name)
+
+ if net is None or os.path.getmtime(network_on_disk.filename) > net.mtime:
+ try:
+ net = load_network(name, network_on_disk)
+
+ networks_in_memory.pop(name, None)
+ networks_in_memory[name] = net
+ except Exception as e:
+ errors.display(e, f"loading network {network_on_disk.filename}")
+ continue
+
+ net.mentioned_name = name
+
+ network_on_disk.read_hash()
+
+ if net is None:
+ failed_to_load_networks.append(name)
+ logging.info(f"Couldn't find network with name {name}")
+ continue
+
+ net.te_multiplier = te_multipliers[i] if te_multipliers else 1.0
+ net.unet_multiplier = unet_multipliers[i] if unet_multipliers else 1.0
+ net.dyn_dim = dyn_dims[i] if dyn_dims else 1.0
+ loaded_networks.append(net)
+
+ for emb_name, embedding in net.bundle_embeddings.items():
+ if embedding.loaded is None and emb_name in emb_db.word_embeddings:
+ logger.warning(
+ f'Skip bundle embedding: "{emb_name}"'
+ ' as it was already loaded from embeddings folder'
+ )
+ continue
+
+ embedding.loaded = False
+ if emb_db.expected_shape == -1 or emb_db.expected_shape == embedding.shape:
+ embedding.loaded = True
+ emb_db.register_embedding(embedding, shared.sd_model)
+ else:
+ emb_db.skipped_embeddings[name] = embedding
+
+ if failed_to_load_networks:
+ lora_not_found_message = f'Lora not found: {", ".join(failed_to_load_networks)}'
+ sd_hijack.model_hijack.comments.append(lora_not_found_message)
+ if shared.opts.lora_not_found_warning_console:
+ print(f'\n{lora_not_found_message}\n')
+ if shared.opts.lora_not_found_gradio_warning:
+ gr.Warning(lora_not_found_message)
+
+ purge_networks_from_memory()
+
+
+def allowed_layer_without_weight(layer):
+ if isinstance(layer, torch.nn.LayerNorm) and not layer.elementwise_affine:
+ return True
+
+ return False
+
+
+def store_weights_backup(weight):
+ if weight is None:
+ return None
+
+ return weight.to(devices.cpu, copy=True)
+
+
+def restore_weights_backup(obj, field, weight):
+ if weight is None:
+ setattr(obj, field, None)
+ return
+
+ getattr(obj, field).copy_(weight)
+
+
+def network_restore_weights_from_backup(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.GroupNorm, torch.nn.LayerNorm, torch.nn.MultiheadAttention]):
+ weights_backup = getattr(self, "network_weights_backup", None)
+ bias_backup = getattr(self, "network_bias_backup", None)
+
+ if weights_backup is None and bias_backup is None:
+ return
+
+ if weights_backup is not None:
+ if isinstance(self, torch.nn.MultiheadAttention):
+ restore_weights_backup(self, 'in_proj_weight', weights_backup[0])
+ restore_weights_backup(self.out_proj, 'weight', weights_backup[1])
+ else:
+ restore_weights_backup(self, 'weight', weights_backup)
+
+ if isinstance(self, torch.nn.MultiheadAttention):
+ restore_weights_backup(self.out_proj, 'bias', bias_backup)
+ else:
+ restore_weights_backup(self, 'bias', bias_backup)
+
+
+def network_apply_weights(self: Union[torch.nn.Conv2d, torch.nn.Linear, torch.nn.GroupNorm, torch.nn.LayerNorm, torch.nn.MultiheadAttention]):
+ """
+ Applies the currently selected set of networks to the weights of torch layer self.
+ If weights already have this particular set of networks applied, does nothing.
+ If not, restores original weights from backup and alters weights according to networks.
+ """
+
+ network_layer_name = getattr(self, 'network_layer_name', None)
+ if network_layer_name is None:
+ return
+
+ current_names = getattr(self, "network_current_names", ())
+ wanted_names = tuple((x.name, x.te_multiplier, x.unet_multiplier, x.dyn_dim) for x in loaded_networks)
+
+ weights_backup = getattr(self, "network_weights_backup", None)
+ if weights_backup is None and wanted_names != ():
+ if current_names != () and not allowed_layer_without_weight(self):
+ raise RuntimeError(f"{network_layer_name} - no backup weights found and current weights are not unchanged")
+
+ if isinstance(self, torch.nn.MultiheadAttention):
+ weights_backup = (store_weights_backup(self.in_proj_weight), store_weights_backup(self.out_proj.weight))
+ else:
+ weights_backup = store_weights_backup(self.weight)
+
+ self.network_weights_backup = weights_backup
+
+ bias_backup = getattr(self, "network_bias_backup", None)
+ if bias_backup is None and wanted_names != ():
+ if isinstance(self, torch.nn.MultiheadAttention) and self.out_proj.bias is not None:
+ bias_backup = store_weights_backup(self.out_proj.bias)
+ elif getattr(self, 'bias', None) is not None:
+ bias_backup = store_weights_backup(self.bias)
+ else:
+ bias_backup = None
+
+ # Unlike weight which always has value, some modules don't have bias.
+ # Only report if bias is not None and current bias are not unchanged.
+ if bias_backup is not None and current_names != ():
+ raise RuntimeError("no backup bias found and current bias are not unchanged")
+
+ self.network_bias_backup = bias_backup
+
+ if current_names != wanted_names:
+ network_restore_weights_from_backup(self)
+
+ for net in loaded_networks:
+ module = net.modules.get(network_layer_name, None)
+ if module is not None and hasattr(self, 'weight') and not isinstance(module, modules.models.sd3.mmdit.QkvLinear):
+ try:
+ with torch.no_grad():
+ if getattr(self, 'fp16_weight', None) is None:
+ weight = self.weight
+ bias = self.bias
+ else:
+ weight = self.fp16_weight.clone().to(self.weight.device)
+ bias = getattr(self, 'fp16_bias', None)
+ if bias is not None:
+ bias = bias.clone().to(self.bias.device)
+ updown, ex_bias = module.calc_updown(weight)
+
+ if len(weight.shape) == 4 and weight.shape[1] == 9:
+ # inpainting model. zero pad updown to make channel[1] 4 to 9
+ updown = torch.nn.functional.pad(updown, (0, 0, 0, 0, 0, 5))
+
+ self.weight.copy_((weight.to(dtype=updown.dtype) + updown).to(dtype=self.weight.dtype))
+ if ex_bias is not None and hasattr(self, 'bias'):
+ if self.bias is None:
+ self.bias = torch.nn.Parameter(ex_bias).to(self.weight.dtype)
+ else:
+ self.bias.copy_((bias + ex_bias).to(dtype=self.bias.dtype))
+ except RuntimeError as e:
+ logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
+ extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
+
+ continue
+
+ module_q = net.modules.get(network_layer_name + "_q_proj", None)
+ module_k = net.modules.get(network_layer_name + "_k_proj", None)
+ module_v = net.modules.get(network_layer_name + "_v_proj", None)
+ module_out = net.modules.get(network_layer_name + "_out_proj", None)
+
+ if isinstance(self, torch.nn.MultiheadAttention) and module_q and module_k and module_v and module_out:
+ try:
+ with torch.no_grad():
+ # Send "real" orig_weight into MHA's lora module
+ qw, kw, vw = self.in_proj_weight.chunk(3, 0)
+ updown_q, _ = module_q.calc_updown(qw)
+ updown_k, _ = module_k.calc_updown(kw)
+ updown_v, _ = module_v.calc_updown(vw)
+ del qw, kw, vw
+ updown_qkv = torch.vstack([updown_q, updown_k, updown_v])
+ updown_out, ex_bias = module_out.calc_updown(self.out_proj.weight)
+
+ self.in_proj_weight += updown_qkv
+ self.out_proj.weight += updown_out
+ if ex_bias is not None:
+ if self.out_proj.bias is None:
+ self.out_proj.bias = torch.nn.Parameter(ex_bias)
+ else:
+ self.out_proj.bias += ex_bias
+
+ except RuntimeError as e:
+ logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
+ extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
+
+ continue
+
+ if isinstance(self, modules.models.sd3.mmdit.QkvLinear) and module_q and module_k and module_v:
+ try:
+ with torch.no_grad():
+ # Send "real" orig_weight into MHA's lora module
+ qw, kw, vw = self.weight.chunk(3, 0)
+ updown_q, _ = module_q.calc_updown(qw)
+ updown_k, _ = module_k.calc_updown(kw)
+ updown_v, _ = module_v.calc_updown(vw)
+ del qw, kw, vw
+ updown_qkv = torch.vstack([updown_q, updown_k, updown_v])
+ self.weight += updown_qkv
+
+ except RuntimeError as e:
+ logging.debug(f"Network {net.name} layer {network_layer_name}: {e}")
+ extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
+
+ continue
+
+ if module is None:
+ continue
+
+ logging.debug(f"Network {net.name} layer {network_layer_name}: couldn't find supported operation")
+ extra_network_lora.errors[net.name] = extra_network_lora.errors.get(net.name, 0) + 1
+
+ self.network_current_names = wanted_names
+
+
+def network_forward(org_module, input, original_forward):
+ """
+ Old way of applying Lora by executing operations during layer's forward.
+ Stacking many loras this way results in big performance degradation.
+ """
+
+ if len(loaded_networks) == 0:
+ return original_forward(org_module, input)
+
+ input = devices.cond_cast_unet(input)
+
+ network_restore_weights_from_backup(org_module)
+ network_reset_cached_weight(org_module)
+
+ y = original_forward(org_module, input)
+
+ network_layer_name = getattr(org_module, 'network_layer_name', None)
+ for lora in loaded_networks:
+ module = lora.modules.get(network_layer_name, None)
+ if module is None:
+ continue
+
+ y = module.forward(input, y)
+
+ return y
+
+
+def network_reset_cached_weight(self: Union[torch.nn.Conv2d, torch.nn.Linear]):
+ self.network_current_names = ()
+ self.network_weights_backup = None
+ self.network_bias_backup = None
+
+
+def network_Linear_forward(self, input):
+ if shared.opts.lora_functional:
+ return network_forward(self, input, originals.Linear_forward)
+
+ network_apply_weights(self)
+
+ return originals.Linear_forward(self, input)
+
+
+def network_Linear_load_state_dict(self, *args, **kwargs):
+ network_reset_cached_weight(self)
+
+ return originals.Linear_load_state_dict(self, *args, **kwargs)
+
+
+def network_Conv2d_forward(self, input):
+ if shared.opts.lora_functional:
+ return network_forward(self, input, originals.Conv2d_forward)
+
+ network_apply_weights(self)
+
+ return originals.Conv2d_forward(self, input)
+
+
+def network_Conv2d_load_state_dict(self, *args, **kwargs):
+ network_reset_cached_weight(self)
+
+ return originals.Conv2d_load_state_dict(self, *args, **kwargs)
+
+
+def network_GroupNorm_forward(self, input):
+ if shared.opts.lora_functional:
+ return network_forward(self, input, originals.GroupNorm_forward)
+
+ network_apply_weights(self)
+
+ return originals.GroupNorm_forward(self, input)
+
+
+def network_GroupNorm_load_state_dict(self, *args, **kwargs):
+ network_reset_cached_weight(self)
+
+ return originals.GroupNorm_load_state_dict(self, *args, **kwargs)
+
+
+def network_LayerNorm_forward(self, input):
+ if shared.opts.lora_functional:
+ return network_forward(self, input, originals.LayerNorm_forward)
+
+ network_apply_weights(self)
+
+ return originals.LayerNorm_forward(self, input)
+
+
+def network_LayerNorm_load_state_dict(self, *args, **kwargs):
+ network_reset_cached_weight(self)
+
+ return originals.LayerNorm_load_state_dict(self, *args, **kwargs)
+
+
+def network_MultiheadAttention_forward(self, *args, **kwargs):
+ network_apply_weights(self)
+
+ return originals.MultiheadAttention_forward(self, *args, **kwargs)
+
+
+def network_MultiheadAttention_load_state_dict(self, *args, **kwargs):
+ network_reset_cached_weight(self)
+
+ return originals.MultiheadAttention_load_state_dict(self, *args, **kwargs)
+
+
+def process_network_files(names: list[str] | None = None):
+ candidates = list(shared.walk_files(shared.cmd_opts.lora_dir, allowed_extensions=[".pt", ".ckpt", ".safetensors"]))
+ candidates += list(shared.walk_files(shared.cmd_opts.lyco_dir_backcompat, allowed_extensions=[".pt", ".ckpt", ".safetensors"]))
+ for filename in candidates:
+ if os.path.isdir(filename):
+ continue
+ name = os.path.splitext(os.path.basename(filename))[0]
+ # if names is provided, only load networks with names in the list
+ if names and name not in names:
+ continue
+ try:
+ entry = network.NetworkOnDisk(name, filename)
+ except OSError: # should catch FileNotFoundError and PermissionError etc.
+ errors.report(f"Failed to load network {name} from {filename}", exc_info=True)
+ continue
+
+ available_networks[name] = entry
+
+ if entry.alias in available_network_aliases:
+ forbidden_network_aliases[entry.alias.lower()] = 1
+
+ available_network_aliases[name] = entry
+ available_network_aliases[entry.alias] = entry
+
+
+def update_available_networks_by_names(names: list[str]):
+ process_network_files(names)
+
+
+def list_available_networks():
+ available_networks.clear()
+ available_network_aliases.clear()
+ forbidden_network_aliases.clear()
+ available_network_hash_lookup.clear()
+ forbidden_network_aliases.update({"none": 1, "Addams": 1})
+
+ os.makedirs(shared.cmd_opts.lora_dir, exist_ok=True)
+
+ process_network_files()
+
+
+re_network_name = re.compile(r"(.*)\s*\([0-9a-fA-F]+\)")
+
+
+def infotext_pasted(infotext, params):
+ if "AddNet Module 1" in [x[1] for x in scripts.scripts_txt2img.infotext_fields]:
+ return # if the other extension is active, it will handle those fields, no need to do anything
+
+ added = []
+
+ for k in params:
+ if not k.startswith("AddNet Model "):
+ continue
+
+ num = k[13:]
+
+ if params.get("AddNet Module " + num) != "LoRA":
+ continue
+
+ name = params.get("AddNet Model " + num)
+ if name is None:
+ continue
+
+ m = re_network_name.match(name)
+ if m:
+ name = m.group(1)
+
+ multiplier = params.get("AddNet Weight A " + num, "1.0")
+
+ added.append(f"<lora:{name}:{multiplier}>")
+
+ if added:
+ params["Prompt"] += "\n" + "".join(added)
+
+
+originals: lora_patches.LoraPatches = None
+
+extra_network_lora = None
+
+available_networks = {}
+available_network_aliases = {}
+loaded_networks = []
+loaded_bundle_embeddings = {}
+networks_in_memory = {}
+available_network_hash_lookup = {}
+forbidden_network_aliases = {}
+
+list_available_networks()
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/extensions-builtin/Lora/networks.py |
Add docstrings to existing functions | import json
import os
import os.path
import threading
import diskcache
import tqdm
from modules.paths import data_path, script_path
cache_filename = os.environ.get('SD_WEBUI_CACHE_FILE', os.path.join(data_path, "cache.json"))
cache_dir = os.environ.get('SD_WEBUI_CACHE_DIR', os.path.join(data_path, "cache"))
caches = {}
cache_lock = threading.Lock()
def dump_cache():
pass
def make_cache(subsection: str) -> diskcache.Cache:
return diskcache.Cache(
os.path.join(cache_dir, subsection),
size_limit=2**32, # 4 GB, culling oldest first
disk_min_file_size=2**18, # keep up to 256KB in Sqlite
)
def convert_old_cached_data():
try:
with open(cache_filename, "r", encoding="utf8") as file:
data = json.load(file)
except FileNotFoundError:
return
except Exception:
os.replace(cache_filename, os.path.join(script_path, "tmp", "cache.json"))
print('[ERROR] issue occurred while trying to read cache.json; old cache has been moved to tmp/cache.json')
return
total_count = sum(len(keyvalues) for keyvalues in data.values())
with tqdm.tqdm(total=total_count, desc="converting cache") as progress:
for subsection, keyvalues in data.items():
cache_obj = caches.get(subsection)
if cache_obj is None:
cache_obj = make_cache(subsection)
caches[subsection] = cache_obj
for key, value in keyvalues.items():
cache_obj[key] = value
progress.update(1)
def cache(subsection):
cache_obj = caches.get(subsection)
if not cache_obj:
with cache_lock:
if not os.path.exists(cache_dir) and os.path.isfile(cache_filename):
convert_old_cached_data()
cache_obj = caches.get(subsection)
if not cache_obj:
cache_obj = make_cache(subsection)
caches[subsection] = cache_obj
return cache_obj
def cached_data_for_file(subsection, title, filename, func):
existing_cache = cache(subsection)
ondisk_mtime = os.path.getmtime(filename)
entry = existing_cache.get(title)
if entry:
cached_mtime = entry.get("mtime", 0)
if ondisk_mtime > cached_mtime:
entry = None
if not entry or 'value' not in entry:
value = func()
if value is None:
return None
entry = {'mtime': ondisk_mtime, 'value': value}
existing_cache[title] = entry
dump_cache()
return entry['value'] | --- +++ @@ -1,92 +1,123 @@-import json
-import os
-import os.path
-import threading
-
-import diskcache
-import tqdm
-
-from modules.paths import data_path, script_path
-
-cache_filename = os.environ.get('SD_WEBUI_CACHE_FILE', os.path.join(data_path, "cache.json"))
-cache_dir = os.environ.get('SD_WEBUI_CACHE_DIR', os.path.join(data_path, "cache"))
-caches = {}
-cache_lock = threading.Lock()
-
-
-def dump_cache():
-
- pass
-
-
-def make_cache(subsection: str) -> diskcache.Cache:
- return diskcache.Cache(
- os.path.join(cache_dir, subsection),
- size_limit=2**32, # 4 GB, culling oldest first
- disk_min_file_size=2**18, # keep up to 256KB in Sqlite
- )
-
-
-def convert_old_cached_data():
- try:
- with open(cache_filename, "r", encoding="utf8") as file:
- data = json.load(file)
- except FileNotFoundError:
- return
- except Exception:
- os.replace(cache_filename, os.path.join(script_path, "tmp", "cache.json"))
- print('[ERROR] issue occurred while trying to read cache.json; old cache has been moved to tmp/cache.json')
- return
-
- total_count = sum(len(keyvalues) for keyvalues in data.values())
-
- with tqdm.tqdm(total=total_count, desc="converting cache") as progress:
- for subsection, keyvalues in data.items():
- cache_obj = caches.get(subsection)
- if cache_obj is None:
- cache_obj = make_cache(subsection)
- caches[subsection] = cache_obj
-
- for key, value in keyvalues.items():
- cache_obj[key] = value
- progress.update(1)
-
-
-def cache(subsection):
-
- cache_obj = caches.get(subsection)
- if not cache_obj:
- with cache_lock:
- if not os.path.exists(cache_dir) and os.path.isfile(cache_filename):
- convert_old_cached_data()
-
- cache_obj = caches.get(subsection)
- if not cache_obj:
- cache_obj = make_cache(subsection)
- caches[subsection] = cache_obj
-
- return cache_obj
-
-
-def cached_data_for_file(subsection, title, filename, func):
-
- existing_cache = cache(subsection)
- ondisk_mtime = os.path.getmtime(filename)
-
- entry = existing_cache.get(title)
- if entry:
- cached_mtime = entry.get("mtime", 0)
- if ondisk_mtime > cached_mtime:
- entry = None
-
- if not entry or 'value' not in entry:
- value = func()
- if value is None:
- return None
-
- entry = {'mtime': ondisk_mtime, 'value': value}
- existing_cache[title] = entry
-
- dump_cache()
-
- return entry['value']+import json
+import os
+import os.path
+import threading
+
+import diskcache
+import tqdm
+
+from modules.paths import data_path, script_path
+
+cache_filename = os.environ.get('SD_WEBUI_CACHE_FILE', os.path.join(data_path, "cache.json"))
+cache_dir = os.environ.get('SD_WEBUI_CACHE_DIR', os.path.join(data_path, "cache"))
+caches = {}
+cache_lock = threading.Lock()
+
+
+def dump_cache():
+ """old function for dumping cache to disk; does nothing since diskcache."""
+
+ pass
+
+
+def make_cache(subsection: str) -> diskcache.Cache:
+ return diskcache.Cache(
+ os.path.join(cache_dir, subsection),
+ size_limit=2**32, # 4 GB, culling oldest first
+ disk_min_file_size=2**18, # keep up to 256KB in Sqlite
+ )
+
+
+def convert_old_cached_data():
+ try:
+ with open(cache_filename, "r", encoding="utf8") as file:
+ data = json.load(file)
+ except FileNotFoundError:
+ return
+ except Exception:
+ os.replace(cache_filename, os.path.join(script_path, "tmp", "cache.json"))
+ print('[ERROR] issue occurred while trying to read cache.json; old cache has been moved to tmp/cache.json')
+ return
+
+ total_count = sum(len(keyvalues) for keyvalues in data.values())
+
+ with tqdm.tqdm(total=total_count, desc="converting cache") as progress:
+ for subsection, keyvalues in data.items():
+ cache_obj = caches.get(subsection)
+ if cache_obj is None:
+ cache_obj = make_cache(subsection)
+ caches[subsection] = cache_obj
+
+ for key, value in keyvalues.items():
+ cache_obj[key] = value
+ progress.update(1)
+
+
+def cache(subsection):
+ """
+ Retrieves or initializes a cache for a specific subsection.
+
+ Parameters:
+ subsection (str): The subsection identifier for the cache.
+
+ Returns:
+ diskcache.Cache: The cache data for the specified subsection.
+ """
+
+ cache_obj = caches.get(subsection)
+ if not cache_obj:
+ with cache_lock:
+ if not os.path.exists(cache_dir) and os.path.isfile(cache_filename):
+ convert_old_cached_data()
+
+ cache_obj = caches.get(subsection)
+ if not cache_obj:
+ cache_obj = make_cache(subsection)
+ caches[subsection] = cache_obj
+
+ return cache_obj
+
+
+def cached_data_for_file(subsection, title, filename, func):
+ """
+ Retrieves or generates data for a specific file, using a caching mechanism.
+
+ Parameters:
+ subsection (str): The subsection of the cache to use.
+ title (str): The title of the data entry in the subsection of the cache.
+ filename (str): The path to the file to be checked for modifications.
+ func (callable): A function that generates the data if it is not available in the cache.
+
+ Returns:
+ dict or None: The cached or generated data, or None if data generation fails.
+
+ The `cached_data_for_file` function implements a caching mechanism for data stored in files.
+ It checks if the data associated with the given `title` is present in the cache and compares the
+ modification time of the file with the cached modification time. If the file has been modified,
+ the cache is considered invalid and the data is regenerated using the provided `func`.
+ Otherwise, the cached data is returned.
+
+ If the data generation fails, None is returned to indicate the failure. Otherwise, the generated
+ or cached data is returned as a dictionary.
+ """
+
+ existing_cache = cache(subsection)
+ ondisk_mtime = os.path.getmtime(filename)
+
+ entry = existing_cache.get(title)
+ if entry:
+ cached_mtime = entry.get("mtime", 0)
+ if ondisk_mtime > cached_mtime:
+ entry = None
+
+ if not entry or 'value' not in entry:
+ value = func()
+ if value is None:
+ return None
+
+ entry = {'mtime': ondisk_mtime, 'value': value}
+ existing_cache[title] = entry
+
+ dump_cache()
+
+ return entry['value']
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/cache.py |
Create structured documentation for my script | import sys
import contextlib
from functools import lru_cache
import torch
from modules import errors, shared, npu_specific
if sys.platform == "darwin":
from modules import mac_specific
if shared.cmd_opts.use_ipex:
from modules import xpu_specific
def has_xpu() -> bool:
return shared.cmd_opts.use_ipex and xpu_specific.has_xpu
def has_mps() -> bool:
if sys.platform != "darwin":
return False
else:
return mac_specific.has_mps
def cuda_no_autocast(device_id=None) -> bool:
if device_id is None:
device_id = get_cuda_device_id()
return (
torch.cuda.get_device_capability(device_id) == (7, 5)
and torch.cuda.get_device_name(device_id).startswith("NVIDIA GeForce GTX 16")
)
def get_cuda_device_id():
return (
int(shared.cmd_opts.device_id)
if shared.cmd_opts.device_id is not None and shared.cmd_opts.device_id.isdigit()
else 0
) or torch.cuda.current_device()
def get_cuda_device_string():
if shared.cmd_opts.device_id is not None:
return f"cuda:{shared.cmd_opts.device_id}"
return "cuda"
def get_optimal_device_name():
if torch.cuda.is_available():
return get_cuda_device_string()
if has_mps():
return "mps"
if has_xpu():
return xpu_specific.get_xpu_device_string()
if npu_specific.has_npu:
return npu_specific.get_npu_device_string()
return "cpu"
def get_optimal_device():
return torch.device(get_optimal_device_name())
def get_device_for(task):
if task in shared.cmd_opts.use_cpu or "all" in shared.cmd_opts.use_cpu:
return cpu
return get_optimal_device()
def torch_gc():
if torch.cuda.is_available():
with torch.cuda.device(get_cuda_device_string()):
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
if has_mps():
mac_specific.torch_mps_gc()
if has_xpu():
xpu_specific.torch_xpu_gc()
if npu_specific.has_npu:
torch_npu_set_device()
npu_specific.torch_npu_gc()
def torch_npu_set_device():
# Work around due to bug in torch_npu, revert me after fixed, @see https://gitee.com/ascend/pytorch/issues/I8KECW?from=project-issue
if npu_specific.has_npu:
torch.npu.set_device(0)
def enable_tf32():
if torch.cuda.is_available():
# enabling benchmark option seems to enable a range of cards to do fp16 when they otherwise can't
# see https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/4407
if cuda_no_autocast():
torch.backends.cudnn.benchmark = True
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
errors.run(enable_tf32, "Enabling TF32")
cpu: torch.device = torch.device("cpu")
fp8: bool = False
# Force fp16 for all models in inference. No casting during inference.
# This flag is controlled by "--precision half" command line arg.
force_fp16: bool = False
device: torch.device = None
device_interrogate: torch.device = None
device_gfpgan: torch.device = None
device_esrgan: torch.device = None
device_codeformer: torch.device = None
dtype: torch.dtype = torch.float16
dtype_vae: torch.dtype = torch.float16
dtype_unet: torch.dtype = torch.float16
dtype_inference: torch.dtype = torch.float16
unet_needs_upcast = False
def cond_cast_unet(input):
if force_fp16:
return input.to(torch.float16)
return input.to(dtype_unet) if unet_needs_upcast else input
def cond_cast_float(input):
return input.float() if unet_needs_upcast else input
nv_rng = None
patch_module_list = [
torch.nn.Linear,
torch.nn.Conv2d,
torch.nn.MultiheadAttention,
torch.nn.GroupNorm,
torch.nn.LayerNorm,
]
def manual_cast_forward(target_dtype):
def forward_wrapper(self, *args, **kwargs):
if any(
isinstance(arg, torch.Tensor) and arg.dtype != target_dtype
for arg in args
):
args = [arg.to(target_dtype) if isinstance(arg, torch.Tensor) else arg for arg in args]
kwargs = {k: v.to(target_dtype) if isinstance(v, torch.Tensor) else v for k, v in kwargs.items()}
org_dtype = target_dtype
for param in self.parameters():
if param.dtype != target_dtype:
org_dtype = param.dtype
break
if org_dtype != target_dtype:
self.to(target_dtype)
result = self.org_forward(*args, **kwargs)
if org_dtype != target_dtype:
self.to(org_dtype)
if target_dtype != dtype_inference:
if isinstance(result, tuple):
result = tuple(
i.to(dtype_inference)
if isinstance(i, torch.Tensor)
else i
for i in result
)
elif isinstance(result, torch.Tensor):
result = result.to(dtype_inference)
return result
return forward_wrapper
@contextlib.contextmanager
def manual_cast(target_dtype):
applied = False
for module_type in patch_module_list:
if hasattr(module_type, "org_forward"):
continue
applied = True
org_forward = module_type.forward
if module_type == torch.nn.MultiheadAttention:
module_type.forward = manual_cast_forward(torch.float32)
else:
module_type.forward = manual_cast_forward(target_dtype)
module_type.org_forward = org_forward
try:
yield None
finally:
if applied:
for module_type in patch_module_list:
if hasattr(module_type, "org_forward"):
module_type.forward = module_type.org_forward
delattr(module_type, "org_forward")
def autocast(disable=False):
if disable:
return contextlib.nullcontext()
if force_fp16:
# No casting during inference if force_fp16 is enabled.
# All tensor dtype conversion happens before inference.
return contextlib.nullcontext()
if fp8 and device==cpu:
return torch.autocast("cpu", dtype=torch.bfloat16, enabled=True)
if fp8 and dtype_inference == torch.float32:
return manual_cast(dtype)
if dtype == torch.float32 or dtype_inference == torch.float32:
return contextlib.nullcontext()
if has_xpu() or has_mps() or cuda_no_autocast():
return manual_cast(dtype)
return torch.autocast("cuda")
def without_autocast(disable=False):
return torch.autocast("cuda", enabled=False) if torch.is_autocast_enabled() and not disable else contextlib.nullcontext()
class NansException(Exception):
pass
def test_for_nans(x, where):
if shared.cmd_opts.disable_nan_check:
return
if not torch.isnan(x[(0, ) * len(x.shape)]):
return
if where == "unet":
message = "A tensor with NaNs was produced in Unet."
if not shared.cmd_opts.no_half:
message += " This could be either because there's not enough precision to represent the picture, or because your video card does not support half type. Try setting the \"Upcast cross attention layer to float32\" option in Settings > Stable Diffusion or using the --no-half commandline argument to fix this."
elif where == "vae":
message = "A tensor with NaNs was produced in VAE."
if not shared.cmd_opts.no_half and not shared.cmd_opts.no_half_vae:
message += " This could be because there's not enough precision to represent the picture. Try adding --no-half-vae commandline argument to fix this."
else:
message = "A tensor with NaNs was produced."
message += " Use --disable-nan-check commandline argument to disable this check."
raise NansException(message)
@lru_cache
def first_time_calculation():
x = torch.zeros((1, 1)).to(device, dtype)
linear = torch.nn.Linear(1, 1).to(device, dtype)
linear(x)
x = torch.zeros((1, 1, 3, 3)).to(device, dtype)
conv2d = torch.nn.Conv2d(1, 1, (3, 3)).to(device, dtype)
conv2d(x)
def force_model_fp16():
assert force_fp16
import sgm.modules.diffusionmodules.util as sgm_util
import ldm.modules.diffusionmodules.util as ldm_util
sgm_util.GroupNorm32 = torch.nn.GroupNorm
ldm_util.GroupNorm32 = torch.nn.GroupNorm
print("ldm/sgm GroupNorm32 replaced with normal torch.nn.GroupNorm due to `--precision half`.") | --- +++ @@ -267,6 +267,10 @@
@lru_cache
def first_time_calculation():
+ """
+ just do any calculation with pytorch layers - the first time this is done it allocates about 700MB of memory and
+ spends about 2.7 seconds doing that, at least with NVidia.
+ """
x = torch.zeros((1, 1)).to(device, dtype)
linear = torch.nn.Linear(1, 1).to(device, dtype)
@@ -278,9 +282,14 @@
def force_model_fp16():
+ """
+ ldm and sgm has modules.diffusionmodules.util.GroupNorm32.forward, which
+ force conversion of input to float32. If force_fp16 is enabled, we need to
+ prevent this casting.
+ """
assert force_fp16
import sgm.modules.diffusionmodules.util as sgm_util
import ldm.modules.diffusionmodules.util as ldm_util
sgm_util.GroupNorm32 = torch.nn.GroupNorm
ldm_util.GroupNorm32 = torch.nn.GroupNorm
- print("ldm/sgm GroupNorm32 replaced with normal torch.nn.GroupNorm due to `--precision half`.")+ print("ldm/sgm GroupNorm32 replaced with normal torch.nn.GroupNorm due to `--precision half`.")
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/devices.py |
Write docstrings that follow conventions |
from __future__ import annotations
from dataclasses import dataclass
from typing import Callable
from functools import wraps, cache
import math
import torch.nn as nn
import random
from einops import rearrange
@dataclass
class HypertileParams:
depth = 0
layer_name = ""
tile_size: int = 0
swap_size: int = 0
aspect_ratio: float = 1.0
forward = None
enabled = False
# TODO add SD-XL layers
DEPTH_LAYERS = {
0: [
# SD 1.5 U-Net (diffusers)
"down_blocks.0.attentions.0.transformer_blocks.0.attn1",
"down_blocks.0.attentions.1.transformer_blocks.0.attn1",
"up_blocks.3.attentions.0.transformer_blocks.0.attn1",
"up_blocks.3.attentions.1.transformer_blocks.0.attn1",
"up_blocks.3.attentions.2.transformer_blocks.0.attn1",
# SD 1.5 U-Net (ldm)
"input_blocks.1.1.transformer_blocks.0.attn1",
"input_blocks.2.1.transformer_blocks.0.attn1",
"output_blocks.9.1.transformer_blocks.0.attn1",
"output_blocks.10.1.transformer_blocks.0.attn1",
"output_blocks.11.1.transformer_blocks.0.attn1",
# SD 1.5 VAE
"decoder.mid_block.attentions.0",
"decoder.mid.attn_1",
],
1: [
# SD 1.5 U-Net (diffusers)
"down_blocks.1.attentions.0.transformer_blocks.0.attn1",
"down_blocks.1.attentions.1.transformer_blocks.0.attn1",
"up_blocks.2.attentions.0.transformer_blocks.0.attn1",
"up_blocks.2.attentions.1.transformer_blocks.0.attn1",
"up_blocks.2.attentions.2.transformer_blocks.0.attn1",
# SD 1.5 U-Net (ldm)
"input_blocks.4.1.transformer_blocks.0.attn1",
"input_blocks.5.1.transformer_blocks.0.attn1",
"output_blocks.6.1.transformer_blocks.0.attn1",
"output_blocks.7.1.transformer_blocks.0.attn1",
"output_blocks.8.1.transformer_blocks.0.attn1",
],
2: [
# SD 1.5 U-Net (diffusers)
"down_blocks.2.attentions.0.transformer_blocks.0.attn1",
"down_blocks.2.attentions.1.transformer_blocks.0.attn1",
"up_blocks.1.attentions.0.transformer_blocks.0.attn1",
"up_blocks.1.attentions.1.transformer_blocks.0.attn1",
"up_blocks.1.attentions.2.transformer_blocks.0.attn1",
# SD 1.5 U-Net (ldm)
"input_blocks.7.1.transformer_blocks.0.attn1",
"input_blocks.8.1.transformer_blocks.0.attn1",
"output_blocks.3.1.transformer_blocks.0.attn1",
"output_blocks.4.1.transformer_blocks.0.attn1",
"output_blocks.5.1.transformer_blocks.0.attn1",
],
3: [
# SD 1.5 U-Net (diffusers)
"mid_block.attentions.0.transformer_blocks.0.attn1",
# SD 1.5 U-Net (ldm)
"middle_block.1.transformer_blocks.0.attn1",
],
}
# XL layers, thanks for GitHub@gel-crabs for the help
DEPTH_LAYERS_XL = {
0: [
# SD 1.5 U-Net (diffusers)
"down_blocks.0.attentions.0.transformer_blocks.0.attn1",
"down_blocks.0.attentions.1.transformer_blocks.0.attn1",
"up_blocks.3.attentions.0.transformer_blocks.0.attn1",
"up_blocks.3.attentions.1.transformer_blocks.0.attn1",
"up_blocks.3.attentions.2.transformer_blocks.0.attn1",
# SD 1.5 U-Net (ldm)
"input_blocks.4.1.transformer_blocks.0.attn1",
"input_blocks.5.1.transformer_blocks.0.attn1",
"output_blocks.3.1.transformer_blocks.0.attn1",
"output_blocks.4.1.transformer_blocks.0.attn1",
"output_blocks.5.1.transformer_blocks.0.attn1",
# SD 1.5 VAE
"decoder.mid_block.attentions.0",
"decoder.mid.attn_1",
],
1: [
# SD 1.5 U-Net (diffusers)
#"down_blocks.1.attentions.0.transformer_blocks.0.attn1",
#"down_blocks.1.attentions.1.transformer_blocks.0.attn1",
#"up_blocks.2.attentions.0.transformer_blocks.0.attn1",
#"up_blocks.2.attentions.1.transformer_blocks.0.attn1",
#"up_blocks.2.attentions.2.transformer_blocks.0.attn1",
# SD 1.5 U-Net (ldm)
"input_blocks.4.1.transformer_blocks.1.attn1",
"input_blocks.5.1.transformer_blocks.1.attn1",
"output_blocks.3.1.transformer_blocks.1.attn1",
"output_blocks.4.1.transformer_blocks.1.attn1",
"output_blocks.5.1.transformer_blocks.1.attn1",
"input_blocks.7.1.transformer_blocks.0.attn1",
"input_blocks.8.1.transformer_blocks.0.attn1",
"output_blocks.0.1.transformer_blocks.0.attn1",
"output_blocks.1.1.transformer_blocks.0.attn1",
"output_blocks.2.1.transformer_blocks.0.attn1",
"input_blocks.7.1.transformer_blocks.1.attn1",
"input_blocks.8.1.transformer_blocks.1.attn1",
"output_blocks.0.1.transformer_blocks.1.attn1",
"output_blocks.1.1.transformer_blocks.1.attn1",
"output_blocks.2.1.transformer_blocks.1.attn1",
"input_blocks.7.1.transformer_blocks.2.attn1",
"input_blocks.8.1.transformer_blocks.2.attn1",
"output_blocks.0.1.transformer_blocks.2.attn1",
"output_blocks.1.1.transformer_blocks.2.attn1",
"output_blocks.2.1.transformer_blocks.2.attn1",
"input_blocks.7.1.transformer_blocks.3.attn1",
"input_blocks.8.1.transformer_blocks.3.attn1",
"output_blocks.0.1.transformer_blocks.3.attn1",
"output_blocks.1.1.transformer_blocks.3.attn1",
"output_blocks.2.1.transformer_blocks.3.attn1",
"input_blocks.7.1.transformer_blocks.4.attn1",
"input_blocks.8.1.transformer_blocks.4.attn1",
"output_blocks.0.1.transformer_blocks.4.attn1",
"output_blocks.1.1.transformer_blocks.4.attn1",
"output_blocks.2.1.transformer_blocks.4.attn1",
"input_blocks.7.1.transformer_blocks.5.attn1",
"input_blocks.8.1.transformer_blocks.5.attn1",
"output_blocks.0.1.transformer_blocks.5.attn1",
"output_blocks.1.1.transformer_blocks.5.attn1",
"output_blocks.2.1.transformer_blocks.5.attn1",
"input_blocks.7.1.transformer_blocks.6.attn1",
"input_blocks.8.1.transformer_blocks.6.attn1",
"output_blocks.0.1.transformer_blocks.6.attn1",
"output_blocks.1.1.transformer_blocks.6.attn1",
"output_blocks.2.1.transformer_blocks.6.attn1",
"input_blocks.7.1.transformer_blocks.7.attn1",
"input_blocks.8.1.transformer_blocks.7.attn1",
"output_blocks.0.1.transformer_blocks.7.attn1",
"output_blocks.1.1.transformer_blocks.7.attn1",
"output_blocks.2.1.transformer_blocks.7.attn1",
"input_blocks.7.1.transformer_blocks.8.attn1",
"input_blocks.8.1.transformer_blocks.8.attn1",
"output_blocks.0.1.transformer_blocks.8.attn1",
"output_blocks.1.1.transformer_blocks.8.attn1",
"output_blocks.2.1.transformer_blocks.8.attn1",
"input_blocks.7.1.transformer_blocks.9.attn1",
"input_blocks.8.1.transformer_blocks.9.attn1",
"output_blocks.0.1.transformer_blocks.9.attn1",
"output_blocks.1.1.transformer_blocks.9.attn1",
"output_blocks.2.1.transformer_blocks.9.attn1",
],
2: [
# SD 1.5 U-Net (diffusers)
"mid_block.attentions.0.transformer_blocks.0.attn1",
# SD 1.5 U-Net (ldm)
"middle_block.1.transformer_blocks.0.attn1",
"middle_block.1.transformer_blocks.1.attn1",
"middle_block.1.transformer_blocks.2.attn1",
"middle_block.1.transformer_blocks.3.attn1",
"middle_block.1.transformer_blocks.4.attn1",
"middle_block.1.transformer_blocks.5.attn1",
"middle_block.1.transformer_blocks.6.attn1",
"middle_block.1.transformer_blocks.7.attn1",
"middle_block.1.transformer_blocks.8.attn1",
"middle_block.1.transformer_blocks.9.attn1",
],
3 : [] # TODO - separate layers for SD-XL
}
RNG_INSTANCE = random.Random()
@cache
def get_divisors(value: int, min_value: int, /, max_options: int = 1) -> list[int]:
max_options = max(1, max_options) # at least 1 option should be returned
min_value = min(min_value, value)
divisors = [i for i in range(min_value, value + 1) if value % i == 0] # divisors in small -> big order
ns = [value // i for i in divisors[:max_options]] # has at least 1 element # big -> small order
return ns
def random_divisor(value: int, min_value: int, /, max_options: int = 1) -> int:
ns = get_divisors(value, min_value, max_options=max_options) # get cached divisors
idx = RNG_INSTANCE.randint(0, len(ns) - 1)
return ns[idx]
def set_hypertile_seed(seed: int) -> None:
RNG_INSTANCE.seed(seed)
@cache
def largest_tile_size_available(width: int, height: int) -> int:
gcd = math.gcd(width, height)
largest_tile_size_available = 1
while gcd % (largest_tile_size_available * 2) == 0:
largest_tile_size_available *= 2
return largest_tile_size_available
def iterative_closest_divisors(hw:int, aspect_ratio:float) -> tuple[int, int]:
divisors = [i for i in range(2, hw + 1) if hw % i == 0] # all divisors of hw
pairs = [(i, hw // i) for i in divisors] # all pairs of divisors of hw
ratios = [w/h for h, w in pairs] # all ratios of pairs of divisors of hw
closest_ratio = min(ratios, key=lambda x: abs(x - aspect_ratio)) # closest ratio to aspect_ratio
closest_pair = pairs[ratios.index(closest_ratio)] # closest pair of divisors to aspect_ratio
return closest_pair
@cache
def find_hw_candidates(hw:int, aspect_ratio:float) -> tuple[int, int]:
h, w = round(math.sqrt(hw * aspect_ratio)), round(math.sqrt(hw / aspect_ratio))
# find h and w such that h*w = hw and h/w = aspect_ratio
if h * w != hw:
w_candidate = hw / h
# check if w is an integer
if not w_candidate.is_integer():
h_candidate = hw / w
# check if h is an integer
if not h_candidate.is_integer():
return iterative_closest_divisors(hw, aspect_ratio)
else:
h = int(h_candidate)
else:
w = int(w_candidate)
return h, w
def self_attn_forward(params: HypertileParams, scale_depth=True) -> Callable:
@wraps(params.forward)
def wrapper(*args, **kwargs):
if not params.enabled:
return params.forward(*args, **kwargs)
latent_tile_size = max(128, params.tile_size) // 8
x = args[0]
# VAE
if x.ndim == 4:
b, c, h, w = x.shape
nh = random_divisor(h, latent_tile_size, params.swap_size)
nw = random_divisor(w, latent_tile_size, params.swap_size)
if nh * nw > 1:
x = rearrange(x, "b c (nh h) (nw w) -> (b nh nw) c h w", nh=nh, nw=nw) # split into nh * nw tiles
out = params.forward(x, *args[1:], **kwargs)
if nh * nw > 1:
out = rearrange(out, "(b nh nw) c h w -> b c (nh h) (nw w)", nh=nh, nw=nw)
# U-Net
else:
hw: int = x.size(1)
h, w = find_hw_candidates(hw, params.aspect_ratio)
assert h * w == hw, f"Invalid aspect ratio {params.aspect_ratio} for input of shape {x.shape}, hw={hw}, h={h}, w={w}"
factor = 2 ** params.depth if scale_depth else 1
nh = random_divisor(h, latent_tile_size * factor, params.swap_size)
nw = random_divisor(w, latent_tile_size * factor, params.swap_size)
if nh * nw > 1:
x = rearrange(x, "b (nh h nw w) c -> (b nh nw) (h w) c", h=h // nh, w=w // nw, nh=nh, nw=nw)
out = params.forward(x, *args[1:], **kwargs)
if nh * nw > 1:
out = rearrange(out, "(b nh nw) hw c -> b nh nw hw c", nh=nh, nw=nw)
out = rearrange(out, "b nh nw (h w) c -> b (nh h nw w) c", h=h // nh, w=w // nw)
return out
return wrapper
def hypertile_hook_model(model: nn.Module, width, height, *, enable=False, tile_size_max=128, swap_size=1, max_depth=3, is_sdxl=False):
hypertile_layers = getattr(model, "__webui_hypertile_layers", None)
if hypertile_layers is None:
if not enable:
return
hypertile_layers = {}
layers = DEPTH_LAYERS_XL if is_sdxl else DEPTH_LAYERS
for depth in range(4):
for layer_name, module in model.named_modules():
if any(layer_name.endswith(try_name) for try_name in layers[depth]):
params = HypertileParams()
module.__webui_hypertile_params = params
params.forward = module.forward
params.depth = depth
params.layer_name = layer_name
module.forward = self_attn_forward(params)
hypertile_layers[layer_name] = 1
model.__webui_hypertile_layers = hypertile_layers
aspect_ratio = width / height
tile_size = min(largest_tile_size_available(width, height), tile_size_max)
for layer_name, module in model.named_modules():
if layer_name in hypertile_layers:
params = module.__webui_hypertile_params
params.tile_size = tile_size
params.swap_size = swap_size
params.aspect_ratio = aspect_ratio
params.enabled = enable and params.depth <= max_depth | --- +++ @@ -1,3 +1,8 @@+"""
+Hypertile module for splitting attention layers in SD-1.5 U-Net and SD-1.5 VAE
+Warn: The patch works well only if the input image has a width and height that are multiples of 128
+Original author: @tfernd Github: https://github.com/tfernd/HyperTile
+"""
from __future__ import annotations
@@ -185,6 +190,11 @@
@cache
def get_divisors(value: int, min_value: int, /, max_options: int = 1) -> list[int]:
+ """
+ Returns divisors of value that
+ x * min_value <= value
+ in big -> small order, amount of divisors is limited by max_options
+ """
max_options = max(1, max_options) # at least 1 option should be returned
min_value = min(min_value, value)
divisors = [i for i in range(min_value, value + 1) if value % i == 0] # divisors in small -> big order
@@ -193,6 +203,11 @@
def random_divisor(value: int, min_value: int, /, max_options: int = 1) -> int:
+ """
+ Returns a random divisor of value that
+ x * min_value <= value
+ if max_options is 1, the behavior is deterministic
+ """
ns = get_divisors(value, min_value, max_options=max_options) # get cached divisors
idx = RNG_INSTANCE.randint(0, len(ns) - 1)
@@ -205,6 +220,10 @@
@cache
def largest_tile_size_available(width: int, height: int) -> int:
+ """
+ Calculates the largest tile size available for a given width and height
+ Tile size is always a power of 2
+ """
gcd = math.gcd(width, height)
largest_tile_size_available = 1
while gcd % (largest_tile_size_available * 2) == 0:
@@ -213,6 +232,10 @@
def iterative_closest_divisors(hw:int, aspect_ratio:float) -> tuple[int, int]:
+ """
+ Finds h and w such that h*w = hw and h/w = aspect_ratio
+ We check all possible divisors of hw and return the closest to the aspect ratio
+ """
divisors = [i for i in range(2, hw + 1) if hw % i == 0] # all divisors of hw
pairs = [(i, hw // i) for i in divisors] # all pairs of divisors of hw
ratios = [w/h for h, w in pairs] # all ratios of pairs of divisors of hw
@@ -223,6 +246,9 @@
@cache
def find_hw_candidates(hw:int, aspect_ratio:float) -> tuple[int, int]:
+ """
+ Finds h and w such that h*w = hw and h/w = aspect_ratio
+ """
h, w = round(math.sqrt(hw * aspect_ratio)), round(math.sqrt(hw / aspect_ratio))
# find h and w such that h*w = hw and h/w = aspect_ratio
if h * w != hw:
@@ -322,4 +348,4 @@ params.tile_size = tile_size
params.swap_size = swap_size
params.aspect_ratio = aspect_ratio
- params.enabled = enable and params.depth <= max_depth+ params.enabled = enable and params.depth <= max_depth
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/extensions-builtin/hypertile/hypertile.py |
Include argument descriptions in docstrings | import json
import os
import re
import logging
from collections import defaultdict
from modules import errors
extra_network_registry = {}
extra_network_aliases = {}
def initialize():
extra_network_registry.clear()
extra_network_aliases.clear()
def register_extra_network(extra_network):
extra_network_registry[extra_network.name] = extra_network
def register_extra_network_alias(extra_network, alias):
extra_network_aliases[alias] = extra_network
def register_default_extra_networks():
from modules.extra_networks_hypernet import ExtraNetworkHypernet
register_extra_network(ExtraNetworkHypernet())
class ExtraNetworkParams:
def __init__(self, items=None):
self.items = items or []
self.positional = []
self.named = {}
for item in self.items:
parts = item.split('=', 2) if isinstance(item, str) else [item]
if len(parts) == 2:
self.named[parts[0]] = parts[1]
else:
self.positional.append(item)
def __eq__(self, other):
return self.items == other.items
class ExtraNetwork:
def __init__(self, name):
self.name = name
def activate(self, p, params_list):
raise NotImplementedError
def deactivate(self, p):
raise NotImplementedError
def lookup_extra_networks(extra_network_data):
res = {}
for extra_network_name, extra_network_args in list(extra_network_data.items()):
extra_network = extra_network_registry.get(extra_network_name, None)
alias = extra_network_aliases.get(extra_network_name, None)
if alias is not None and extra_network is None:
extra_network = alias
if extra_network is None:
logging.info(f"Skipping unknown extra network: {extra_network_name}")
continue
res.setdefault(extra_network, []).extend(extra_network_args)
return res
def activate(p, extra_network_data):
activated = []
for extra_network, extra_network_args in lookup_extra_networks(extra_network_data).items():
try:
extra_network.activate(p, extra_network_args)
activated.append(extra_network)
except Exception as e:
errors.display(e, f"activating extra network {extra_network.name} with arguments {extra_network_args}")
for extra_network_name, extra_network in extra_network_registry.items():
if extra_network in activated:
continue
try:
extra_network.activate(p, [])
except Exception as e:
errors.display(e, f"activating extra network {extra_network_name}")
if p.scripts is not None:
p.scripts.after_extra_networks_activate(p, batch_number=p.iteration, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds, extra_network_data=extra_network_data)
def deactivate(p, extra_network_data):
data = lookup_extra_networks(extra_network_data)
for extra_network in data:
try:
extra_network.deactivate(p)
except Exception as e:
errors.display(e, f"deactivating extra network {extra_network.name}")
for extra_network_name, extra_network in extra_network_registry.items():
if extra_network in data:
continue
try:
extra_network.deactivate(p)
except Exception as e:
errors.display(e, f"deactivating unmentioned extra network {extra_network_name}")
re_extra_net = re.compile(r"<(\w+):([^>]+)>")
def parse_prompt(prompt):
res = defaultdict(list)
def found(m):
name = m.group(1)
args = m.group(2)
res[name].append(ExtraNetworkParams(items=args.split(":")))
return ""
prompt = re.sub(re_extra_net, found, prompt)
return prompt, res
def parse_prompts(prompts):
res = []
extra_data = None
for prompt in prompts:
updated_prompt, parsed_extra_data = parse_prompt(prompt)
if extra_data is None:
extra_data = parsed_extra_data
res.append(updated_prompt)
return res, extra_data
def get_user_metadata(filename, lister=None):
if filename is None:
return {}
basename, ext = os.path.splitext(filename)
metadata_filename = basename + '.json'
metadata = {}
try:
exists = lister.exists(metadata_filename) if lister else os.path.exists(metadata_filename)
if exists:
with open(metadata_filename, "r", encoding="utf8") as file:
metadata = json.load(file)
except Exception as e:
errors.display(e, f"reading extra network user metadata from {metadata_filename}")
return metadata | --- +++ @@ -1,175 +1,225 @@-import json
-import os
-import re
-import logging
-from collections import defaultdict
-
-from modules import errors
-
-extra_network_registry = {}
-extra_network_aliases = {}
-
-
-def initialize():
- extra_network_registry.clear()
- extra_network_aliases.clear()
-
-
-def register_extra_network(extra_network):
- extra_network_registry[extra_network.name] = extra_network
-
-
-def register_extra_network_alias(extra_network, alias):
- extra_network_aliases[alias] = extra_network
-
-
-def register_default_extra_networks():
- from modules.extra_networks_hypernet import ExtraNetworkHypernet
- register_extra_network(ExtraNetworkHypernet())
-
-
-class ExtraNetworkParams:
- def __init__(self, items=None):
- self.items = items or []
- self.positional = []
- self.named = {}
-
- for item in self.items:
- parts = item.split('=', 2) if isinstance(item, str) else [item]
- if len(parts) == 2:
- self.named[parts[0]] = parts[1]
- else:
- self.positional.append(item)
-
- def __eq__(self, other):
- return self.items == other.items
-
-
-class ExtraNetwork:
- def __init__(self, name):
- self.name = name
-
- def activate(self, p, params_list):
- raise NotImplementedError
-
- def deactivate(self, p):
-
- raise NotImplementedError
-
-
-def lookup_extra_networks(extra_network_data):
-
- res = {}
-
- for extra_network_name, extra_network_args in list(extra_network_data.items()):
- extra_network = extra_network_registry.get(extra_network_name, None)
- alias = extra_network_aliases.get(extra_network_name, None)
-
- if alias is not None and extra_network is None:
- extra_network = alias
-
- if extra_network is None:
- logging.info(f"Skipping unknown extra network: {extra_network_name}")
- continue
-
- res.setdefault(extra_network, []).extend(extra_network_args)
-
- return res
-
-
-def activate(p, extra_network_data):
-
- activated = []
-
- for extra_network, extra_network_args in lookup_extra_networks(extra_network_data).items():
-
- try:
- extra_network.activate(p, extra_network_args)
- activated.append(extra_network)
- except Exception as e:
- errors.display(e, f"activating extra network {extra_network.name} with arguments {extra_network_args}")
-
- for extra_network_name, extra_network in extra_network_registry.items():
- if extra_network in activated:
- continue
-
- try:
- extra_network.activate(p, [])
- except Exception as e:
- errors.display(e, f"activating extra network {extra_network_name}")
-
- if p.scripts is not None:
- p.scripts.after_extra_networks_activate(p, batch_number=p.iteration, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds, extra_network_data=extra_network_data)
-
-
-def deactivate(p, extra_network_data):
-
- data = lookup_extra_networks(extra_network_data)
-
- for extra_network in data:
- try:
- extra_network.deactivate(p)
- except Exception as e:
- errors.display(e, f"deactivating extra network {extra_network.name}")
-
- for extra_network_name, extra_network in extra_network_registry.items():
- if extra_network in data:
- continue
-
- try:
- extra_network.deactivate(p)
- except Exception as e:
- errors.display(e, f"deactivating unmentioned extra network {extra_network_name}")
-
-
-re_extra_net = re.compile(r"<(\w+):([^>]+)>")
-
-
-def parse_prompt(prompt):
- res = defaultdict(list)
-
- def found(m):
- name = m.group(1)
- args = m.group(2)
-
- res[name].append(ExtraNetworkParams(items=args.split(":")))
-
- return ""
-
- prompt = re.sub(re_extra_net, found, prompt)
-
- return prompt, res
-
-
-def parse_prompts(prompts):
- res = []
- extra_data = None
-
- for prompt in prompts:
- updated_prompt, parsed_extra_data = parse_prompt(prompt)
-
- if extra_data is None:
- extra_data = parsed_extra_data
-
- res.append(updated_prompt)
-
- return res, extra_data
-
-
-def get_user_metadata(filename, lister=None):
- if filename is None:
- return {}
-
- basename, ext = os.path.splitext(filename)
- metadata_filename = basename + '.json'
-
- metadata = {}
- try:
- exists = lister.exists(metadata_filename) if lister else os.path.exists(metadata_filename)
- if exists:
- with open(metadata_filename, "r", encoding="utf8") as file:
- metadata = json.load(file)
- except Exception as e:
- errors.display(e, f"reading extra network user metadata from {metadata_filename}")
-
- return metadata+import json
+import os
+import re
+import logging
+from collections import defaultdict
+
+from modules import errors
+
+extra_network_registry = {}
+extra_network_aliases = {}
+
+
+def initialize():
+ extra_network_registry.clear()
+ extra_network_aliases.clear()
+
+
+def register_extra_network(extra_network):
+ extra_network_registry[extra_network.name] = extra_network
+
+
+def register_extra_network_alias(extra_network, alias):
+ extra_network_aliases[alias] = extra_network
+
+
+def register_default_extra_networks():
+ from modules.extra_networks_hypernet import ExtraNetworkHypernet
+ register_extra_network(ExtraNetworkHypernet())
+
+
+class ExtraNetworkParams:
+ def __init__(self, items=None):
+ self.items = items or []
+ self.positional = []
+ self.named = {}
+
+ for item in self.items:
+ parts = item.split('=', 2) if isinstance(item, str) else [item]
+ if len(parts) == 2:
+ self.named[parts[0]] = parts[1]
+ else:
+ self.positional.append(item)
+
+ def __eq__(self, other):
+ return self.items == other.items
+
+
+class ExtraNetwork:
+ def __init__(self, name):
+ self.name = name
+
+ def activate(self, p, params_list):
+ """
+ Called by processing on every run. Whatever the extra network is meant to do should be activated here.
+ Passes arguments related to this extra network in params_list.
+ User passes arguments by specifying this in his prompt:
+
+ <name:arg1:arg2:arg3>
+
+ Where name matches the name of this ExtraNetwork object, and arg1:arg2:arg3 are any natural number of text arguments
+ separated by colon.
+
+ Even if the user does not mention this ExtraNetwork in his prompt, the call will still be made, with empty params_list -
+ in this case, all effects of this extra networks should be disabled.
+
+ Can be called multiple times before deactivate() - each new call should override the previous call completely.
+
+ For example, if this ExtraNetwork's name is 'hypernet' and user's prompt is:
+
+ > "1girl, <hypernet:agm:1.1> <extrasupernet:master:12:13:14> <hypernet:ray>"
+
+ params_list will be:
+
+ [
+ ExtraNetworkParams(items=["agm", "1.1"]),
+ ExtraNetworkParams(items=["ray"])
+ ]
+
+ """
+ raise NotImplementedError
+
+ def deactivate(self, p):
+ """
+ Called at the end of processing for housekeeping. No need to do anything here.
+ """
+
+ raise NotImplementedError
+
+
+def lookup_extra_networks(extra_network_data):
+ """returns a dict mapping ExtraNetwork objects to lists of arguments for those extra networks.
+
+ Example input:
+ {
+ 'lora': [<modules.extra_networks.ExtraNetworkParams object at 0x0000020690D58310>],
+ 'lyco': [<modules.extra_networks.ExtraNetworkParams object at 0x0000020690D58F70>],
+ 'hypernet': [<modules.extra_networks.ExtraNetworkParams object at 0x0000020690D5A800>]
+ }
+
+ Example output:
+
+ {
+ <extra_networks_lora.ExtraNetworkLora object at 0x0000020581BEECE0>: [<modules.extra_networks.ExtraNetworkParams object at 0x0000020690D58310>, <modules.extra_networks.ExtraNetworkParams object at 0x0000020690D58F70>],
+ <modules.extra_networks_hypernet.ExtraNetworkHypernet object at 0x0000020581BEEE60>: [<modules.extra_networks.ExtraNetworkParams object at 0x0000020690D5A800>]
+ }
+ """
+
+ res = {}
+
+ for extra_network_name, extra_network_args in list(extra_network_data.items()):
+ extra_network = extra_network_registry.get(extra_network_name, None)
+ alias = extra_network_aliases.get(extra_network_name, None)
+
+ if alias is not None and extra_network is None:
+ extra_network = alias
+
+ if extra_network is None:
+ logging.info(f"Skipping unknown extra network: {extra_network_name}")
+ continue
+
+ res.setdefault(extra_network, []).extend(extra_network_args)
+
+ return res
+
+
+def activate(p, extra_network_data):
+ """call activate for extra networks in extra_network_data in specified order, then call
+ activate for all remaining registered networks with an empty argument list"""
+
+ activated = []
+
+ for extra_network, extra_network_args in lookup_extra_networks(extra_network_data).items():
+
+ try:
+ extra_network.activate(p, extra_network_args)
+ activated.append(extra_network)
+ except Exception as e:
+ errors.display(e, f"activating extra network {extra_network.name} with arguments {extra_network_args}")
+
+ for extra_network_name, extra_network in extra_network_registry.items():
+ if extra_network in activated:
+ continue
+
+ try:
+ extra_network.activate(p, [])
+ except Exception as e:
+ errors.display(e, f"activating extra network {extra_network_name}")
+
+ if p.scripts is not None:
+ p.scripts.after_extra_networks_activate(p, batch_number=p.iteration, prompts=p.prompts, seeds=p.seeds, subseeds=p.subseeds, extra_network_data=extra_network_data)
+
+
+def deactivate(p, extra_network_data):
+ """call deactivate for extra networks in extra_network_data in specified order, then call
+ deactivate for all remaining registered networks"""
+
+ data = lookup_extra_networks(extra_network_data)
+
+ for extra_network in data:
+ try:
+ extra_network.deactivate(p)
+ except Exception as e:
+ errors.display(e, f"deactivating extra network {extra_network.name}")
+
+ for extra_network_name, extra_network in extra_network_registry.items():
+ if extra_network in data:
+ continue
+
+ try:
+ extra_network.deactivate(p)
+ except Exception as e:
+ errors.display(e, f"deactivating unmentioned extra network {extra_network_name}")
+
+
+re_extra_net = re.compile(r"<(\w+):([^>]+)>")
+
+
+def parse_prompt(prompt):
+ res = defaultdict(list)
+
+ def found(m):
+ name = m.group(1)
+ args = m.group(2)
+
+ res[name].append(ExtraNetworkParams(items=args.split(":")))
+
+ return ""
+
+ prompt = re.sub(re_extra_net, found, prompt)
+
+ return prompt, res
+
+
+def parse_prompts(prompts):
+ res = []
+ extra_data = None
+
+ for prompt in prompts:
+ updated_prompt, parsed_extra_data = parse_prompt(prompt)
+
+ if extra_data is None:
+ extra_data = parsed_extra_data
+
+ res.append(updated_prompt)
+
+ return res, extra_data
+
+
+def get_user_metadata(filename, lister=None):
+ if filename is None:
+ return {}
+
+ basename, ext = os.path.splitext(filename)
+ metadata_filename = basename + '.json'
+
+ metadata = {}
+ try:
+ exists = lister.exists(metadata_filename) if lister else os.path.exists(metadata_filename)
+ if exists:
+ with open(metadata_filename, "r", encoding="utf8") as file:
+ metadata = json.load(file)
+ except Exception as e:
+ errors.display(e, f"reading extra network user metadata from {metadata_filename}")
+
+ return metadata
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/extra_networks.py |
Generate docstrings with examples | import base64
import io
import os
import time
import datetime
import uvicorn
import ipaddress
import requests
import gradio as gr
from threading import Lock
from io import BytesIO
from fastapi import APIRouter, Depends, FastAPI, Request, Response
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.exceptions import HTTPException
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
from secrets import compare_digest
import modules.shared as shared
from modules import sd_samplers, deepbooru, sd_hijack, images, scripts, ui, postprocessing, errors, restart, shared_items, script_callbacks, infotext_utils, sd_models, sd_schedulers
from modules.api import models
from modules.shared import opts
from modules.processing import StableDiffusionProcessingTxt2Img, StableDiffusionProcessingImg2Img, process_images
from modules.textual_inversion.textual_inversion import create_embedding, train_embedding
from modules.hypernetworks.hypernetwork import create_hypernetwork, train_hypernetwork
from PIL import PngImagePlugin
from modules.sd_models_config import find_checkpoint_config_near_filename
from modules.realesrgan_model import get_realesrgan_models
from modules import devices
from typing import Any
import piexif
import piexif.helper
from contextlib import closing
from modules.progress import create_task_id, add_task_to_queue, start_task, finish_task, current_task
def script_name_to_index(name, scripts):
try:
return [script.title().lower() for script in scripts].index(name.lower())
except Exception as e:
raise HTTPException(status_code=422, detail=f"Script '{name}' not found") from e
def validate_sampler_name(name):
config = sd_samplers.all_samplers_map.get(name, None)
if config is None:
raise HTTPException(status_code=400, detail="Sampler not found")
return name
def setUpscalers(req: dict):
reqDict = vars(req)
reqDict['extras_upscaler_1'] = reqDict.pop('upscaler_1', None)
reqDict['extras_upscaler_2'] = reqDict.pop('upscaler_2', None)
return reqDict
def verify_url(url):
import socket
from urllib.parse import urlparse
try:
parsed_url = urlparse(url)
domain_name = parsed_url.netloc
host = socket.gethostbyname_ex(domain_name)
for ip in host[2]:
ip_addr = ipaddress.ip_address(ip)
if not ip_addr.is_global:
return False
except Exception:
return False
return True
def decode_base64_to_image(encoding):
if encoding.startswith("http://") or encoding.startswith("https://"):
if not opts.api_enable_requests:
raise HTTPException(status_code=500, detail="Requests not allowed")
if opts.api_forbid_local_requests and not verify_url(encoding):
raise HTTPException(status_code=500, detail="Request to local resource not allowed")
headers = {'user-agent': opts.api_useragent} if opts.api_useragent else {}
response = requests.get(encoding, timeout=30, headers=headers)
try:
image = images.read(BytesIO(response.content))
return image
except Exception as e:
raise HTTPException(status_code=500, detail="Invalid image url") from e
if encoding.startswith("data:image/"):
encoding = encoding.split(";")[1].split(",")[1]
try:
image = images.read(BytesIO(base64.b64decode(encoding)))
return image
except Exception as e:
raise HTTPException(status_code=500, detail="Invalid encoded image") from e
def encode_pil_to_base64(image):
with io.BytesIO() as output_bytes:
if isinstance(image, str):
return image
if opts.samples_format.lower() == 'png':
use_metadata = False
metadata = PngImagePlugin.PngInfo()
for key, value in image.info.items():
if isinstance(key, str) and isinstance(value, str):
metadata.add_text(key, value)
use_metadata = True
image.save(output_bytes, format="PNG", pnginfo=(metadata if use_metadata else None), quality=opts.jpeg_quality)
elif opts.samples_format.lower() in ("jpg", "jpeg", "webp"):
if image.mode in ("RGBA", "P"):
image = image.convert("RGB")
parameters = image.info.get('parameters', None)
exif_bytes = piexif.dump({
"Exif": { piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(parameters or "", encoding="unicode") }
})
if opts.samples_format.lower() in ("jpg", "jpeg"):
image.save(output_bytes, format="JPEG", exif = exif_bytes, quality=opts.jpeg_quality)
else:
image.save(output_bytes, format="WEBP", exif = exif_bytes, quality=opts.jpeg_quality)
else:
raise HTTPException(status_code=500, detail="Invalid image format")
bytes_data = output_bytes.getvalue()
return base64.b64encode(bytes_data)
def api_middleware(app: FastAPI):
rich_available = False
try:
if os.environ.get('WEBUI_RICH_EXCEPTIONS', None) is not None:
import anyio # importing just so it can be placed on silent list
import starlette # importing just so it can be placed on silent list
from rich.console import Console
console = Console()
rich_available = True
except Exception:
pass
@app.middleware("http")
async def log_and_time(req: Request, call_next):
ts = time.time()
res: Response = await call_next(req)
duration = str(round(time.time() - ts, 4))
res.headers["X-Process-Time"] = duration
endpoint = req.scope.get('path', 'err')
if shared.cmd_opts.api_log and endpoint.startswith('/sdapi'):
print('API {t} {code} {prot}/{ver} {method} {endpoint} {cli} {duration}'.format(
t=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
code=res.status_code,
ver=req.scope.get('http_version', '0.0'),
cli=req.scope.get('client', ('0:0.0.0', 0))[0],
prot=req.scope.get('scheme', 'err'),
method=req.scope.get('method', 'err'),
endpoint=endpoint,
duration=duration,
))
return res
def handle_exception(request: Request, e: Exception):
err = {
"error": type(e).__name__,
"detail": vars(e).get('detail', ''),
"body": vars(e).get('body', ''),
"errors": str(e),
}
if not isinstance(e, HTTPException): # do not print backtrace on known httpexceptions
message = f"API error: {request.method}: {request.url} {err}"
if rich_available:
print(message)
console.print_exception(show_locals=True, max_frames=2, extra_lines=1, suppress=[anyio, starlette], word_wrap=False, width=min([console.width, 200]))
else:
errors.report(message, exc_info=True)
return JSONResponse(status_code=vars(e).get('status_code', 500), content=jsonable_encoder(err))
@app.middleware("http")
async def exception_handling(request: Request, call_next):
try:
return await call_next(request)
except Exception as e:
return handle_exception(request, e)
@app.exception_handler(Exception)
async def fastapi_exception_handler(request: Request, e: Exception):
return handle_exception(request, e)
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, e: HTTPException):
return handle_exception(request, e)
class Api:
def __init__(self, app: FastAPI, queue_lock: Lock):
if shared.cmd_opts.api_auth:
self.credentials = {}
for auth in shared.cmd_opts.api_auth.split(","):
user, password = auth.split(":")
self.credentials[user] = password
self.router = APIRouter()
self.app = app
self.queue_lock = queue_lock
api_middleware(self.app)
self.add_api_route("/sdapi/v1/txt2img", self.text2imgapi, methods=["POST"], response_model=models.TextToImageResponse)
self.add_api_route("/sdapi/v1/img2img", self.img2imgapi, methods=["POST"], response_model=models.ImageToImageResponse)
self.add_api_route("/sdapi/v1/extra-single-image", self.extras_single_image_api, methods=["POST"], response_model=models.ExtrasSingleImageResponse)
self.add_api_route("/sdapi/v1/extra-batch-images", self.extras_batch_images_api, methods=["POST"], response_model=models.ExtrasBatchImagesResponse)
self.add_api_route("/sdapi/v1/png-info", self.pnginfoapi, methods=["POST"], response_model=models.PNGInfoResponse)
self.add_api_route("/sdapi/v1/progress", self.progressapi, methods=["GET"], response_model=models.ProgressResponse)
self.add_api_route("/sdapi/v1/interrogate", self.interrogateapi, methods=["POST"])
self.add_api_route("/sdapi/v1/interrupt", self.interruptapi, methods=["POST"])
self.add_api_route("/sdapi/v1/skip", self.skip, methods=["POST"])
self.add_api_route("/sdapi/v1/options", self.get_config, methods=["GET"], response_model=models.OptionsModel)
self.add_api_route("/sdapi/v1/options", self.set_config, methods=["POST"])
self.add_api_route("/sdapi/v1/cmd-flags", self.get_cmd_flags, methods=["GET"], response_model=models.FlagsModel)
self.add_api_route("/sdapi/v1/samplers", self.get_samplers, methods=["GET"], response_model=list[models.SamplerItem])
self.add_api_route("/sdapi/v1/schedulers", self.get_schedulers, methods=["GET"], response_model=list[models.SchedulerItem])
self.add_api_route("/sdapi/v1/upscalers", self.get_upscalers, methods=["GET"], response_model=list[models.UpscalerItem])
self.add_api_route("/sdapi/v1/latent-upscale-modes", self.get_latent_upscale_modes, methods=["GET"], response_model=list[models.LatentUpscalerModeItem])
self.add_api_route("/sdapi/v1/sd-models", self.get_sd_models, methods=["GET"], response_model=list[models.SDModelItem])
self.add_api_route("/sdapi/v1/sd-vae", self.get_sd_vaes, methods=["GET"], response_model=list[models.SDVaeItem])
self.add_api_route("/sdapi/v1/hypernetworks", self.get_hypernetworks, methods=["GET"], response_model=list[models.HypernetworkItem])
self.add_api_route("/sdapi/v1/face-restorers", self.get_face_restorers, methods=["GET"], response_model=list[models.FaceRestorerItem])
self.add_api_route("/sdapi/v1/realesrgan-models", self.get_realesrgan_models, methods=["GET"], response_model=list[models.RealesrganItem])
self.add_api_route("/sdapi/v1/prompt-styles", self.get_prompt_styles, methods=["GET"], response_model=list[models.PromptStyleItem])
self.add_api_route("/sdapi/v1/embeddings", self.get_embeddings, methods=["GET"], response_model=models.EmbeddingsResponse)
self.add_api_route("/sdapi/v1/refresh-embeddings", self.refresh_embeddings, methods=["POST"])
self.add_api_route("/sdapi/v1/refresh-checkpoints", self.refresh_checkpoints, methods=["POST"])
self.add_api_route("/sdapi/v1/refresh-vae", self.refresh_vae, methods=["POST"])
self.add_api_route("/sdapi/v1/create/embedding", self.create_embedding, methods=["POST"], response_model=models.CreateResponse)
self.add_api_route("/sdapi/v1/create/hypernetwork", self.create_hypernetwork, methods=["POST"], response_model=models.CreateResponse)
self.add_api_route("/sdapi/v1/train/embedding", self.train_embedding, methods=["POST"], response_model=models.TrainResponse)
self.add_api_route("/sdapi/v1/train/hypernetwork", self.train_hypernetwork, methods=["POST"], response_model=models.TrainResponse)
self.add_api_route("/sdapi/v1/memory", self.get_memory, methods=["GET"], response_model=models.MemoryResponse)
self.add_api_route("/sdapi/v1/unload-checkpoint", self.unloadapi, methods=["POST"])
self.add_api_route("/sdapi/v1/reload-checkpoint", self.reloadapi, methods=["POST"])
self.add_api_route("/sdapi/v1/scripts", self.get_scripts_list, methods=["GET"], response_model=models.ScriptsList)
self.add_api_route("/sdapi/v1/script-info", self.get_script_info, methods=["GET"], response_model=list[models.ScriptInfo])
self.add_api_route("/sdapi/v1/extensions", self.get_extensions_list, methods=["GET"], response_model=list[models.ExtensionItem])
if shared.cmd_opts.api_server_stop:
self.add_api_route("/sdapi/v1/server-kill", self.kill_webui, methods=["POST"])
self.add_api_route("/sdapi/v1/server-restart", self.restart_webui, methods=["POST"])
self.add_api_route("/sdapi/v1/server-stop", self.stop_webui, methods=["POST"])
self.default_script_arg_txt2img = []
self.default_script_arg_img2img = []
txt2img_script_runner = scripts.scripts_txt2img
img2img_script_runner = scripts.scripts_img2img
if not txt2img_script_runner.scripts or not img2img_script_runner.scripts:
ui.create_ui()
if not txt2img_script_runner.scripts:
txt2img_script_runner.initialize_scripts(False)
if not self.default_script_arg_txt2img:
self.default_script_arg_txt2img = self.init_default_script_args(txt2img_script_runner)
if not img2img_script_runner.scripts:
img2img_script_runner.initialize_scripts(True)
if not self.default_script_arg_img2img:
self.default_script_arg_img2img = self.init_default_script_args(img2img_script_runner)
def add_api_route(self, path: str, endpoint, **kwargs):
if shared.cmd_opts.api_auth:
return self.app.add_api_route(path, endpoint, dependencies=[Depends(self.auth)], **kwargs)
return self.app.add_api_route(path, endpoint, **kwargs)
def auth(self, credentials: HTTPBasicCredentials = Depends(HTTPBasic())):
if credentials.username in self.credentials:
if compare_digest(credentials.password, self.credentials[credentials.username]):
return True
raise HTTPException(status_code=401, detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"})
def get_selectable_script(self, script_name, script_runner):
if script_name is None or script_name == "":
return None, None
script_idx = script_name_to_index(script_name, script_runner.selectable_scripts)
script = script_runner.selectable_scripts[script_idx]
return script, script_idx
def get_scripts_list(self):
t2ilist = [script.name for script in scripts.scripts_txt2img.scripts if script.name is not None]
i2ilist = [script.name for script in scripts.scripts_img2img.scripts if script.name is not None]
return models.ScriptsList(txt2img=t2ilist, img2img=i2ilist)
def get_script_info(self):
res = []
for script_list in [scripts.scripts_txt2img.scripts, scripts.scripts_img2img.scripts]:
res += [script.api_info for script in script_list if script.api_info is not None]
return res
def get_script(self, script_name, script_runner):
if script_name is None or script_name == "":
return None, None
script_idx = script_name_to_index(script_name, script_runner.scripts)
return script_runner.scripts[script_idx]
def init_default_script_args(self, script_runner):
#find max idx from the scripts in runner and generate a none array to init script_args
last_arg_index = 1
for script in script_runner.scripts:
if last_arg_index < script.args_to:
last_arg_index = script.args_to
# None everywhere except position 0 to initialize script args
script_args = [None]*last_arg_index
script_args[0] = 0
# get default values
with gr.Blocks(): # will throw errors calling ui function without this
for script in script_runner.scripts:
if script.ui(script.is_img2img):
ui_default_values = []
for elem in script.ui(script.is_img2img):
ui_default_values.append(elem.value)
script_args[script.args_from:script.args_to] = ui_default_values
return script_args
def init_script_args(self, request, default_script_args, selectable_scripts, selectable_idx, script_runner, *, input_script_args=None):
script_args = default_script_args.copy()
if input_script_args is not None:
for index, value in input_script_args.items():
script_args[index] = value
# position 0 in script_arg is the idx+1 of the selectable script that is going to be run when using scripts.scripts_*2img.run()
if selectable_scripts:
script_args[selectable_scripts.args_from:selectable_scripts.args_to] = request.script_args
script_args[0] = selectable_idx + 1
# Now check for always on scripts
if request.alwayson_scripts:
for alwayson_script_name in request.alwayson_scripts.keys():
alwayson_script = self.get_script(alwayson_script_name, script_runner)
if alwayson_script is None:
raise HTTPException(status_code=422, detail=f"always on script {alwayson_script_name} not found")
# Selectable script in always on script param check
if alwayson_script.alwayson is False:
raise HTTPException(status_code=422, detail="Cannot have a selectable script in the always on scripts params")
# always on script with no arg should always run so you don't really need to add them to the requests
if "args" in request.alwayson_scripts[alwayson_script_name]:
# min between arg length in scriptrunner and arg length in the request
for idx in range(0, min((alwayson_script.args_to - alwayson_script.args_from), len(request.alwayson_scripts[alwayson_script_name]["args"]))):
script_args[alwayson_script.args_from + idx] = request.alwayson_scripts[alwayson_script_name]["args"][idx]
return script_args
def apply_infotext(self, request, tabname, *, script_runner=None, mentioned_script_args=None):
if not request.infotext:
return {}
possible_fields = infotext_utils.paste_fields[tabname]["fields"]
set_fields = request.model_dump(exclude_unset=True) if hasattr(request, "request") else request.dict(exclude_unset=True) # pydantic v1/v2 have different names for this
params = infotext_utils.parse_generation_parameters(request.infotext)
def get_field_value(field, params):
value = field.function(params) if field.function else params.get(field.label)
if value is None:
return None
if field.api in request.__fields__:
target_type = request.__fields__[field.api].type_
else:
target_type = type(field.component.value)
if target_type == type(None):
return None
if isinstance(value, dict) and value.get('__type__') == 'generic_update': # this is a gradio.update rather than a value
value = value.get('value')
if value is not None and not isinstance(value, target_type):
value = target_type(value)
return value
for field in possible_fields:
if not field.api:
continue
if field.api in set_fields:
continue
value = get_field_value(field, params)
if value is not None:
setattr(request, field.api, value)
if request.override_settings is None:
request.override_settings = {}
overridden_settings = infotext_utils.get_override_settings(params)
for _, setting_name, value in overridden_settings:
if setting_name not in request.override_settings:
request.override_settings[setting_name] = value
if script_runner is not None and mentioned_script_args is not None:
indexes = {v: i for i, v in enumerate(script_runner.inputs)}
script_fields = ((field, indexes[field.component]) for field in possible_fields if field.component in indexes)
for field, index in script_fields:
value = get_field_value(field, params)
if value is None:
continue
mentioned_script_args[index] = value
return params
def text2imgapi(self, txt2imgreq: models.StableDiffusionTxt2ImgProcessingAPI):
task_id = txt2imgreq.force_task_id or create_task_id("txt2img")
script_runner = scripts.scripts_txt2img
infotext_script_args = {}
self.apply_infotext(txt2imgreq, "txt2img", script_runner=script_runner, mentioned_script_args=infotext_script_args)
selectable_scripts, selectable_script_idx = self.get_selectable_script(txt2imgreq.script_name, script_runner)
sampler, scheduler = sd_samplers.get_sampler_and_scheduler(txt2imgreq.sampler_name or txt2imgreq.sampler_index, txt2imgreq.scheduler)
populate = txt2imgreq.copy(update={ # Override __init__ params
"sampler_name": validate_sampler_name(sampler),
"do_not_save_samples": not txt2imgreq.save_images,
"do_not_save_grid": not txt2imgreq.save_images,
})
if populate.sampler_name:
populate.sampler_index = None # prevent a warning later on
if not populate.scheduler and scheduler != "Automatic":
populate.scheduler = scheduler
args = vars(populate)
args.pop('script_name', None)
args.pop('script_args', None) # will refeed them to the pipeline directly after initializing them
args.pop('alwayson_scripts', None)
args.pop('infotext', None)
script_args = self.init_script_args(txt2imgreq, self.default_script_arg_txt2img, selectable_scripts, selectable_script_idx, script_runner, input_script_args=infotext_script_args)
send_images = args.pop('send_images', True)
args.pop('save_images', None)
add_task_to_queue(task_id)
with self.queue_lock:
with closing(StableDiffusionProcessingTxt2Img(sd_model=shared.sd_model, **args)) as p:
p.is_api = True
p.scripts = script_runner
p.outpath_grids = opts.outdir_txt2img_grids
p.outpath_samples = opts.outdir_txt2img_samples
try:
shared.state.begin(job="scripts_txt2img")
start_task(task_id)
if selectable_scripts is not None:
p.script_args = script_args
processed = scripts.scripts_txt2img.run(p, *p.script_args) # Need to pass args as list here
else:
p.script_args = tuple(script_args) # Need to pass args as tuple here
processed = process_images(p)
finish_task(task_id)
finally:
shared.state.end()
shared.total_tqdm.clear()
b64images = list(map(encode_pil_to_base64, processed.images)) if send_images else []
return models.TextToImageResponse(images=b64images, parameters=vars(txt2imgreq), info=processed.js())
def img2imgapi(self, img2imgreq: models.StableDiffusionImg2ImgProcessingAPI):
task_id = img2imgreq.force_task_id or create_task_id("img2img")
init_images = img2imgreq.init_images
if init_images is None:
raise HTTPException(status_code=404, detail="Init image not found")
mask = img2imgreq.mask
if mask:
mask = decode_base64_to_image(mask)
script_runner = scripts.scripts_img2img
infotext_script_args = {}
self.apply_infotext(img2imgreq, "img2img", script_runner=script_runner, mentioned_script_args=infotext_script_args)
selectable_scripts, selectable_script_idx = self.get_selectable_script(img2imgreq.script_name, script_runner)
sampler, scheduler = sd_samplers.get_sampler_and_scheduler(img2imgreq.sampler_name or img2imgreq.sampler_index, img2imgreq.scheduler)
populate = img2imgreq.copy(update={ # Override __init__ params
"sampler_name": validate_sampler_name(sampler),
"do_not_save_samples": not img2imgreq.save_images,
"do_not_save_grid": not img2imgreq.save_images,
"mask": mask,
})
if populate.sampler_name:
populate.sampler_index = None # prevent a warning later on
if not populate.scheduler and scheduler != "Automatic":
populate.scheduler = scheduler
args = vars(populate)
args.pop('include_init_images', None) # this is meant to be done by "exclude": True in model, but it's for a reason that I cannot determine.
args.pop('script_name', None)
args.pop('script_args', None) # will refeed them to the pipeline directly after initializing them
args.pop('alwayson_scripts', None)
args.pop('infotext', None)
script_args = self.init_script_args(img2imgreq, self.default_script_arg_img2img, selectable_scripts, selectable_script_idx, script_runner, input_script_args=infotext_script_args)
send_images = args.pop('send_images', True)
args.pop('save_images', None)
add_task_to_queue(task_id)
with self.queue_lock:
with closing(StableDiffusionProcessingImg2Img(sd_model=shared.sd_model, **args)) as p:
p.init_images = [decode_base64_to_image(x) for x in init_images]
p.is_api = True
p.scripts = script_runner
p.outpath_grids = opts.outdir_img2img_grids
p.outpath_samples = opts.outdir_img2img_samples
try:
shared.state.begin(job="scripts_img2img")
start_task(task_id)
if selectable_scripts is not None:
p.script_args = script_args
processed = scripts.scripts_img2img.run(p, *p.script_args) # Need to pass args as list here
else:
p.script_args = tuple(script_args) # Need to pass args as tuple here
processed = process_images(p)
finish_task(task_id)
finally:
shared.state.end()
shared.total_tqdm.clear()
b64images = list(map(encode_pil_to_base64, processed.images)) if send_images else []
if not img2imgreq.include_init_images:
img2imgreq.init_images = None
img2imgreq.mask = None
return models.ImageToImageResponse(images=b64images, parameters=vars(img2imgreq), info=processed.js())
def extras_single_image_api(self, req: models.ExtrasSingleImageRequest):
reqDict = setUpscalers(req)
reqDict['image'] = decode_base64_to_image(reqDict['image'])
with self.queue_lock:
result = postprocessing.run_extras(extras_mode=0, image_folder="", input_dir="", output_dir="", save_output=False, **reqDict)
return models.ExtrasSingleImageResponse(image=encode_pil_to_base64(result[0][0]), html_info=result[1])
def extras_batch_images_api(self, req: models.ExtrasBatchImagesRequest):
reqDict = setUpscalers(req)
image_list = reqDict.pop('imageList', [])
image_folder = [decode_base64_to_image(x.data) for x in image_list]
with self.queue_lock:
result = postprocessing.run_extras(extras_mode=1, image_folder=image_folder, image="", input_dir="", output_dir="", save_output=False, **reqDict)
return models.ExtrasBatchImagesResponse(images=list(map(encode_pil_to_base64, result[0])), html_info=result[1])
def pnginfoapi(self, req: models.PNGInfoRequest):
image = decode_base64_to_image(req.image.strip())
if image is None:
return models.PNGInfoResponse(info="")
geninfo, items = images.read_info_from_image(image)
if geninfo is None:
geninfo = ""
params = infotext_utils.parse_generation_parameters(geninfo)
script_callbacks.infotext_pasted_callback(geninfo, params)
return models.PNGInfoResponse(info=geninfo, items=items, parameters=params)
def progressapi(self, req: models.ProgressRequest = Depends()):
# copy from check_progress_call of ui.py
if shared.state.job_count == 0:
return models.ProgressResponse(progress=0, eta_relative=0, state=shared.state.dict(), textinfo=shared.state.textinfo)
# avoid dividing zero
progress = 0.01
if shared.state.job_count > 0:
progress += shared.state.job_no / shared.state.job_count
if shared.state.sampling_steps > 0:
progress += 1 / shared.state.job_count * shared.state.sampling_step / shared.state.sampling_steps
time_since_start = time.time() - shared.state.time_start
eta = (time_since_start/progress)
eta_relative = eta-time_since_start
progress = min(progress, 1)
shared.state.set_current_image()
current_image = None
if shared.state.current_image and not req.skip_current_image:
current_image = encode_pil_to_base64(shared.state.current_image)
return models.ProgressResponse(progress=progress, eta_relative=eta_relative, state=shared.state.dict(), current_image=current_image, textinfo=shared.state.textinfo, current_task=current_task)
def interrogateapi(self, interrogatereq: models.InterrogateRequest):
image_b64 = interrogatereq.image
if image_b64 is None:
raise HTTPException(status_code=404, detail="Image not found")
img = decode_base64_to_image(image_b64)
img = img.convert('RGB')
# Override object param
with self.queue_lock:
if interrogatereq.model == "clip":
processed = shared.interrogator.interrogate(img)
elif interrogatereq.model == "deepdanbooru":
processed = deepbooru.model.tag(img)
else:
raise HTTPException(status_code=404, detail="Model not found")
return models.InterrogateResponse(caption=processed)
def interruptapi(self):
shared.state.interrupt()
return {}
def unloadapi(self):
sd_models.unload_model_weights()
return {}
def reloadapi(self):
sd_models.send_model_to_device(shared.sd_model)
return {}
def skip(self):
shared.state.skip()
def get_config(self):
options = {}
for key in shared.opts.data.keys():
metadata = shared.opts.data_labels.get(key)
if(metadata is not None):
options.update({key: shared.opts.data.get(key, shared.opts.data_labels.get(key).default)})
else:
options.update({key: shared.opts.data.get(key, None)})
return options
def set_config(self, req: dict[str, Any]):
checkpoint_name = req.get("sd_model_checkpoint", None)
if checkpoint_name is not None and checkpoint_name not in sd_models.checkpoint_aliases:
raise RuntimeError(f"model {checkpoint_name!r} not found")
for k, v in req.items():
shared.opts.set(k, v, is_api=True)
shared.opts.save(shared.config_filename)
return
def get_cmd_flags(self):
return vars(shared.cmd_opts)
def get_samplers(self):
return [{"name": sampler[0], "aliases":sampler[2], "options":sampler[3]} for sampler in sd_samplers.all_samplers]
def get_schedulers(self):
return [
{
"name": scheduler.name,
"label": scheduler.label,
"aliases": scheduler.aliases,
"default_rho": scheduler.default_rho,
"need_inner_model": scheduler.need_inner_model,
}
for scheduler in sd_schedulers.schedulers]
def get_upscalers(self):
return [
{
"name": upscaler.name,
"model_name": upscaler.scaler.model_name,
"model_path": upscaler.data_path,
"model_url": None,
"scale": upscaler.scale,
}
for upscaler in shared.sd_upscalers
]
def get_latent_upscale_modes(self):
return [
{
"name": upscale_mode,
}
for upscale_mode in [*(shared.latent_upscale_modes or {})]
]
def get_sd_models(self):
import modules.sd_models as sd_models
return [{"title": x.title, "model_name": x.model_name, "hash": x.shorthash, "sha256": x.sha256, "filename": x.filename, "config": find_checkpoint_config_near_filename(x)} for x in sd_models.checkpoints_list.values()]
def get_sd_vaes(self):
import modules.sd_vae as sd_vae
return [{"model_name": x, "filename": sd_vae.vae_dict[x]} for x in sd_vae.vae_dict.keys()]
def get_hypernetworks(self):
return [{"name": name, "path": shared.hypernetworks[name]} for name in shared.hypernetworks]
def get_face_restorers(self):
return [{"name":x.name(), "cmd_dir": getattr(x, "cmd_dir", None)} for x in shared.face_restorers]
def get_realesrgan_models(self):
return [{"name":x.name,"path":x.data_path, "scale":x.scale} for x in get_realesrgan_models(None)]
def get_prompt_styles(self):
styleList = []
for k in shared.prompt_styles.styles:
style = shared.prompt_styles.styles[k]
styleList.append({"name":style[0], "prompt": style[1], "negative_prompt": style[2]})
return styleList
def get_embeddings(self):
db = sd_hijack.model_hijack.embedding_db
def convert_embedding(embedding):
return {
"step": embedding.step,
"sd_checkpoint": embedding.sd_checkpoint,
"sd_checkpoint_name": embedding.sd_checkpoint_name,
"shape": embedding.shape,
"vectors": embedding.vectors,
}
def convert_embeddings(embeddings):
return {embedding.name: convert_embedding(embedding) for embedding in embeddings.values()}
return {
"loaded": convert_embeddings(db.word_embeddings),
"skipped": convert_embeddings(db.skipped_embeddings),
}
def refresh_embeddings(self):
with self.queue_lock:
sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings(force_reload=True)
def refresh_checkpoints(self):
with self.queue_lock:
shared.refresh_checkpoints()
def refresh_vae(self):
with self.queue_lock:
shared_items.refresh_vae_list()
def create_embedding(self, args: dict):
try:
shared.state.begin(job="create_embedding")
filename = create_embedding(**args) # create empty embedding
sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings() # reload embeddings so new one can be immediately used
return models.CreateResponse(info=f"create embedding filename: {filename}")
except AssertionError as e:
return models.TrainResponse(info=f"create embedding error: {e}")
finally:
shared.state.end()
def create_hypernetwork(self, args: dict):
try:
shared.state.begin(job="create_hypernetwork")
filename = create_hypernetwork(**args) # create empty embedding
return models.CreateResponse(info=f"create hypernetwork filename: {filename}")
except AssertionError as e:
return models.TrainResponse(info=f"create hypernetwork error: {e}")
finally:
shared.state.end()
def train_embedding(self, args: dict):
try:
shared.state.begin(job="train_embedding")
apply_optimizations = shared.opts.training_xattention_optimizations
error = None
filename = ''
if not apply_optimizations:
sd_hijack.undo_optimizations()
try:
embedding, filename = train_embedding(**args) # can take a long time to complete
except Exception as e:
error = e
finally:
if not apply_optimizations:
sd_hijack.apply_optimizations()
return models.TrainResponse(info=f"train embedding complete: filename: {filename} error: {error}")
except Exception as msg:
return models.TrainResponse(info=f"train embedding error: {msg}")
finally:
shared.state.end()
def train_hypernetwork(self, args: dict):
try:
shared.state.begin(job="train_hypernetwork")
shared.loaded_hypernetworks = []
apply_optimizations = shared.opts.training_xattention_optimizations
error = None
filename = ''
if not apply_optimizations:
sd_hijack.undo_optimizations()
try:
hypernetwork, filename = train_hypernetwork(**args)
except Exception as e:
error = e
finally:
shared.sd_model.cond_stage_model.to(devices.device)
shared.sd_model.first_stage_model.to(devices.device)
if not apply_optimizations:
sd_hijack.apply_optimizations()
shared.state.end()
return models.TrainResponse(info=f"train embedding complete: filename: {filename} error: {error}")
except Exception as exc:
return models.TrainResponse(info=f"train embedding error: {exc}")
finally:
shared.state.end()
def get_memory(self):
try:
import os
import psutil
process = psutil.Process(os.getpid())
res = process.memory_info() # only rss is cross-platform guaranteed so we dont rely on other values
ram_total = 100 * res.rss / process.memory_percent() # and total memory is calculated as actual value is not cross-platform safe
ram = { 'free': ram_total - res.rss, 'used': res.rss, 'total': ram_total }
except Exception as err:
ram = { 'error': f'{err}' }
try:
import torch
if torch.cuda.is_available():
s = torch.cuda.mem_get_info()
system = { 'free': s[0], 'used': s[1] - s[0], 'total': s[1] }
s = dict(torch.cuda.memory_stats(shared.device))
allocated = { 'current': s['allocated_bytes.all.current'], 'peak': s['allocated_bytes.all.peak'] }
reserved = { 'current': s['reserved_bytes.all.current'], 'peak': s['reserved_bytes.all.peak'] }
active = { 'current': s['active_bytes.all.current'], 'peak': s['active_bytes.all.peak'] }
inactive = { 'current': s['inactive_split_bytes.all.current'], 'peak': s['inactive_split_bytes.all.peak'] }
warnings = { 'retries': s['num_alloc_retries'], 'oom': s['num_ooms'] }
cuda = {
'system': system,
'active': active,
'allocated': allocated,
'reserved': reserved,
'inactive': inactive,
'events': warnings,
}
else:
cuda = {'error': 'unavailable'}
except Exception as err:
cuda = {'error': f'{err}'}
return models.MemoryResponse(ram=ram, cuda=cuda)
def get_extensions_list(self):
from modules import extensions
extensions.list_extensions()
ext_list = []
for ext in extensions.extensions:
ext: extensions.Extension
ext.read_info_from_repo()
if ext.remote is not None:
ext_list.append({
"name": ext.name,
"remote": ext.remote,
"branch": ext.branch,
"commit_hash":ext.commit_hash,
"commit_date":ext.commit_date,
"version":ext.version,
"enabled":ext.enabled
})
return ext_list
def launch(self, server_name, port, root_path):
self.app.include_router(self.router)
uvicorn.run(
self.app,
host=server_name,
port=port,
timeout_keep_alive=shared.cmd_opts.timeout_keep_alive,
root_path=root_path,
ssl_keyfile=shared.cmd_opts.tls_keyfile,
ssl_certfile=shared.cmd_opts.tls_certfile
)
def kill_webui(self):
restart.stop_program()
def restart_webui(self):
if restart.is_restartable():
restart.restart_program()
return Response(status_code=501)
def stop_webui(request):
shared.state.server_command = "stop"
return Response("Stopping.")
| --- +++ @@ -56,6 +56,7 @@
def verify_url(url):
+ """Returns True if the url refers to a global resource."""
import socket
from urllib.parse import urlparse
@@ -360,6 +361,12 @@ return script_args
def apply_infotext(self, request, tabname, *, script_runner=None, mentioned_script_args=None):
+ """Processes `infotext` field from the `request`, and sets other fields of the `request` according to what's in infotext.
+
+ If request already has a field set, and that field is encountered in infotext too, the value from infotext is ignored.
+
+ Additionally, fills `mentioned_script_args` dict with index: value pairs for script arguments read from infotext.
+ """
if not request.infotext:
return {}
@@ -918,3 +925,4 @@ def stop_webui(request):
shared.state.server_command = "stop"
return Response("Stopping.")
+
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/api/api.py |
Generate docstrings for each module | from __future__ import annotations
import logging
import os
from functools import cached_property
from typing import TYPE_CHECKING, Callable
import cv2
import numpy as np
import torch
from modules import devices, errors, face_restoration, shared
if TYPE_CHECKING:
from facexlib.utils.face_restoration_helper import FaceRestoreHelper
logger = logging.getLogger(__name__)
def bgr_image_to_rgb_tensor(img: np.ndarray) -> torch.Tensor:
assert img.shape[2] == 3, "image must be RGB"
if img.dtype == "float64":
img = img.astype("float32")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return torch.from_numpy(img.transpose(2, 0, 1)).float()
def rgb_tensor_to_bgr_image(tensor: torch.Tensor, *, min_max=(0.0, 1.0)) -> np.ndarray:
tensor = tensor.squeeze(0).float().detach().cpu().clamp_(*min_max)
tensor = (tensor - min_max[0]) / (min_max[1] - min_max[0])
assert tensor.dim() == 3, "tensor must be RGB"
img_np = tensor.numpy().transpose(1, 2, 0)
if img_np.shape[2] == 1: # gray image, no RGB/BGR required
return np.squeeze(img_np, axis=2)
return cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB)
def create_face_helper(device) -> FaceRestoreHelper:
from facexlib.detection import retinaface
from facexlib.utils.face_restoration_helper import FaceRestoreHelper
if hasattr(retinaface, 'device'):
retinaface.device = device
return FaceRestoreHelper(
upscale_factor=1,
face_size=512,
crop_ratio=(1, 1),
det_model='retinaface_resnet50',
save_ext='png',
use_parse=True,
device=device,
)
def restore_with_face_helper(
np_image: np.ndarray,
face_helper: FaceRestoreHelper,
restore_face: Callable[[torch.Tensor], torch.Tensor],
) -> np.ndarray:
from torchvision.transforms.functional import normalize
np_image = np_image[:, :, ::-1]
original_resolution = np_image.shape[0:2]
try:
logger.debug("Detecting faces...")
face_helper.clean_all()
face_helper.read_image(np_image)
face_helper.get_face_landmarks_5(only_center_face=False, resize=640, eye_dist_threshold=5)
face_helper.align_warp_face()
logger.debug("Found %d faces, restoring", len(face_helper.cropped_faces))
for cropped_face in face_helper.cropped_faces:
cropped_face_t = bgr_image_to_rgb_tensor(cropped_face / 255.0)
normalize(cropped_face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
cropped_face_t = cropped_face_t.unsqueeze(0).to(devices.device_codeformer)
try:
with torch.no_grad():
cropped_face_t = restore_face(cropped_face_t)
devices.torch_gc()
except Exception:
errors.report('Failed face-restoration inference', exc_info=True)
restored_face = rgb_tensor_to_bgr_image(cropped_face_t, min_max=(-1, 1))
restored_face = (restored_face * 255.0).astype('uint8')
face_helper.add_restored_face(restored_face)
logger.debug("Merging restored faces into image")
face_helper.get_inverse_affine(None)
img = face_helper.paste_faces_to_input_image()
img = img[:, :, ::-1]
if original_resolution != img.shape[0:2]:
img = cv2.resize(
img,
(0, 0),
fx=original_resolution[1] / img.shape[1],
fy=original_resolution[0] / img.shape[0],
interpolation=cv2.INTER_LINEAR,
)
logger.debug("Face restoration complete")
finally:
face_helper.clean_all()
return img
class CommonFaceRestoration(face_restoration.FaceRestoration):
net: torch.Module | None
model_url: str
model_download_name: str
def __init__(self, model_path: str):
super().__init__()
self.net = None
self.model_path = model_path
os.makedirs(model_path, exist_ok=True)
@cached_property
def face_helper(self) -> FaceRestoreHelper:
return create_face_helper(self.get_device())
def send_model_to(self, device):
if self.net:
logger.debug("Sending %s to %s", self.net, device)
self.net.to(device)
if self.face_helper:
logger.debug("Sending face helper to %s", device)
self.face_helper.face_det.to(device)
self.face_helper.face_parse.to(device)
def get_device(self):
raise NotImplementedError("get_device must be implemented by subclasses")
def load_net(self) -> torch.Module:
raise NotImplementedError("load_net must be implemented by subclasses")
def restore_with_helper(
self,
np_image: np.ndarray,
restore_face: Callable[[torch.Tensor], torch.Tensor],
) -> np.ndarray:
try:
if self.net is None:
self.net = self.load_net()
except Exception:
logger.warning("Unable to load face-restoration model", exc_info=True)
return np_image
try:
self.send_model_to(self.get_device())
return restore_with_face_helper(np_image, self.face_helper, restore_face)
finally:
if shared.opts.face_restoration_unload:
self.send_model_to(devices.cpu)
def patch_facexlib(dirname: str) -> None:
import facexlib.detection
import facexlib.parsing
det_facex_load_file_from_url = facexlib.detection.load_file_from_url
par_facex_load_file_from_url = facexlib.parsing.load_file_from_url
def update_kwargs(kwargs):
return dict(kwargs, save_dir=dirname, model_dir=None)
def facex_load_file_from_url(**kwargs):
return det_facex_load_file_from_url(**update_kwargs(kwargs))
def facex_load_file_from_url2(**kwargs):
return par_facex_load_file_from_url(**update_kwargs(kwargs))
facexlib.detection.load_file_from_url = facex_load_file_from_url
facexlib.parsing.load_file_from_url = facex_load_file_from_url2 | --- +++ @@ -18,6 +18,7 @@
def bgr_image_to_rgb_tensor(img: np.ndarray) -> torch.Tensor:
+ """Convert a BGR NumPy image in [0..1] range to a PyTorch RGB float32 tensor."""
assert img.shape[2] == 3, "image must be RGB"
if img.dtype == "float64":
img = img.astype("float32")
@@ -26,6 +27,9 @@
def rgb_tensor_to_bgr_image(tensor: torch.Tensor, *, min_max=(0.0, 1.0)) -> np.ndarray:
+ """
+ Convert a PyTorch RGB tensor in range `min_max` to a BGR NumPy image in [0..1] range.
+ """
tensor = tensor.squeeze(0).float().detach().cpu().clamp_(*min_max)
tensor = (tensor - min_max[0]) / (min_max[1] - min_max[0])
assert tensor.dim() == 3, "tensor must be RGB"
@@ -56,6 +60,11 @@ face_helper: FaceRestoreHelper,
restore_face: Callable[[torch.Tensor], torch.Tensor],
) -> np.ndarray:
+ """
+ Find faces in the image using face_helper, restore them using restore_face, and paste them back into the image.
+
+ `restore_face` should take a cropped face image and return a restored face image.
+ """
from torchvision.transforms.functional import normalize
np_image = np_image[:, :, ::-1]
original_resolution = np_image.shape[0:2]
@@ -168,4 +177,4 @@ return par_facex_load_file_from_url(**update_kwargs(kwargs))
facexlib.detection.load_file_from_url = facex_load_file_from_url
- facexlib.parsing.load_file_from_url = facex_load_file_from_url2+ facexlib.parsing.load_file_from_url = facex_load_file_from_url2
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/face_restoration_utils.py |
Add return value explanations in docstrings | import numpy as np
import gradio as gr
import math
from modules.ui_components import InputAccordion
import modules.scripts as scripts
from modules.torch_utils import float64
class SoftInpaintingSettings:
def __init__(self,
mask_blend_power,
mask_blend_scale,
inpaint_detail_preservation,
composite_mask_influence,
composite_difference_threshold,
composite_difference_contrast):
self.mask_blend_power = mask_blend_power
self.mask_blend_scale = mask_blend_scale
self.inpaint_detail_preservation = inpaint_detail_preservation
self.composite_mask_influence = composite_mask_influence
self.composite_difference_threshold = composite_difference_threshold
self.composite_difference_contrast = composite_difference_contrast
def add_generation_params(self, dest):
dest[enabled_gen_param_label] = True
dest[gen_param_labels.mask_blend_power] = self.mask_blend_power
dest[gen_param_labels.mask_blend_scale] = self.mask_blend_scale
dest[gen_param_labels.inpaint_detail_preservation] = self.inpaint_detail_preservation
dest[gen_param_labels.composite_mask_influence] = self.composite_mask_influence
dest[gen_param_labels.composite_difference_threshold] = self.composite_difference_threshold
dest[gen_param_labels.composite_difference_contrast] = self.composite_difference_contrast
# ------------------- Methods -------------------
def processing_uses_inpainting(p):
# TODO: Figure out a better way to determine if inpainting is being used by p
if getattr(p, "image_mask", None) is not None:
return True
if getattr(p, "mask", None) is not None:
return True
if getattr(p, "nmask", None) is not None:
return True
return False
def latent_blend(settings, a, b, t):
import torch
# NOTE: We use inplace operations wherever possible.
if len(t.shape) == 3:
# [4][w][h] to [1][4][w][h]
t2 = t.unsqueeze(0)
# [4][w][h] to [1][1][w][h] - the [4] seem redundant.
t3 = t[0].unsqueeze(0).unsqueeze(0)
else:
t2 = t
t3 = t[:, 0][:, None]
one_minus_t2 = 1 - t2
one_minus_t3 = 1 - t3
# Linearly interpolate the image vectors.
a_scaled = a * one_minus_t2
b_scaled = b * t2
image_interp = a_scaled
image_interp.add_(b_scaled)
result_type = image_interp.dtype
del a_scaled, b_scaled, t2, one_minus_t2
# Calculate the magnitude of the interpolated vectors. (We will remove this magnitude.)
# 64-bit operations are used here to allow large exponents.
current_magnitude = torch.norm(image_interp, p=2, dim=1, keepdim=True).to(float64(image_interp)).add_(0.00001)
# Interpolate the powered magnitudes, then un-power them (bring them back to a power of 1).
a_magnitude = torch.norm(a, p=2, dim=1, keepdim=True).to(float64(a)).pow_(settings.inpaint_detail_preservation) * one_minus_t3
b_magnitude = torch.norm(b, p=2, dim=1, keepdim=True).to(float64(b)).pow_(settings.inpaint_detail_preservation) * t3
desired_magnitude = a_magnitude
desired_magnitude.add_(b_magnitude).pow_(1 / settings.inpaint_detail_preservation)
del a_magnitude, b_magnitude, t3, one_minus_t3
# Change the linearly interpolated image vectors' magnitudes to the value we want.
# This is the last 64-bit operation.
image_interp_scaling_factor = desired_magnitude
image_interp_scaling_factor.div_(current_magnitude)
image_interp_scaling_factor = image_interp_scaling_factor.to(result_type)
image_interp_scaled = image_interp
image_interp_scaled.mul_(image_interp_scaling_factor)
del current_magnitude
del desired_magnitude
del image_interp
del image_interp_scaling_factor
del result_type
return image_interp_scaled
def get_modified_nmask(settings, nmask, sigma):
import torch
return torch.pow(nmask, (sigma ** settings.mask_blend_power) * settings.mask_blend_scale)
def apply_adaptive_masks(
settings: SoftInpaintingSettings,
nmask,
latent_orig,
latent_processed,
overlay_images,
width, height,
paste_to):
import torch
import modules.processing as proc
import modules.images as images
from PIL import Image, ImageOps, ImageFilter
# TODO: Bias the blending according to the latent mask, add adjustable parameter for bias control.
if len(nmask.shape) == 3:
latent_mask = nmask[0].float()
else:
latent_mask = nmask[:, 0].float()
# convert the original mask into a form we use to scale distances for thresholding
mask_scalar = 1 - (torch.clamp(latent_mask, min=0, max=1) ** (settings.mask_blend_scale / 2))
mask_scalar = (0.5 * (1 - settings.composite_mask_influence)
+ mask_scalar * settings.composite_mask_influence)
mask_scalar = mask_scalar / (1.00001 - mask_scalar)
mask_scalar = mask_scalar.cpu().numpy()
latent_distance = torch.norm(latent_processed - latent_orig, p=2, dim=1)
kernel, kernel_center = get_gaussian_kernel(stddev_radius=1.5, max_radius=2)
masks_for_overlay = []
for i, (distance_map, overlay_image) in enumerate(zip(latent_distance, overlay_images)):
converted_mask = distance_map.float().cpu().numpy()
converted_mask = weighted_histogram_filter(converted_mask, kernel, kernel_center,
percentile_min=0.9, percentile_max=1, min_width=1)
converted_mask = weighted_histogram_filter(converted_mask, kernel, kernel_center,
percentile_min=0.25, percentile_max=0.75, min_width=1)
# The distance at which opacity of original decreases to 50%
if len(mask_scalar.shape) == 3:
if mask_scalar.shape[0] > i:
half_weighted_distance = settings.composite_difference_threshold * mask_scalar[i]
else:
half_weighted_distance = settings.composite_difference_threshold * mask_scalar[0]
else:
half_weighted_distance = settings.composite_difference_threshold * mask_scalar
converted_mask = converted_mask / half_weighted_distance
converted_mask = 1 / (1 + converted_mask ** settings.composite_difference_contrast)
converted_mask = smootherstep(converted_mask)
converted_mask = 1 - converted_mask
converted_mask = 255. * converted_mask
converted_mask = converted_mask.astype(np.uint8)
converted_mask = Image.fromarray(converted_mask)
converted_mask = images.resize_image(2, converted_mask, width, height)
converted_mask = proc.create_binary_mask(converted_mask, round=False)
# Remove aliasing artifacts using a gaussian blur.
converted_mask = converted_mask.filter(ImageFilter.GaussianBlur(radius=4))
# Expand the mask to fit the whole image if needed.
if paste_to is not None:
converted_mask = proc.uncrop(converted_mask,
(overlay_image.width, overlay_image.height),
paste_to)
masks_for_overlay.append(converted_mask)
image_masked = Image.new('RGBa', (overlay_image.width, overlay_image.height))
image_masked.paste(overlay_image.convert("RGBA").convert("RGBa"),
mask=ImageOps.invert(converted_mask.convert('L')))
overlay_images[i] = image_masked.convert('RGBA')
return masks_for_overlay
def apply_masks(
settings,
nmask,
overlay_images,
width, height,
paste_to):
import torch
import modules.processing as proc
import modules.images as images
from PIL import Image, ImageOps, ImageFilter
converted_mask = nmask[0].float()
converted_mask = torch.clamp(converted_mask, min=0, max=1).pow_(settings.mask_blend_scale / 2)
converted_mask = 255. * converted_mask
converted_mask = converted_mask.cpu().numpy().astype(np.uint8)
converted_mask = Image.fromarray(converted_mask)
converted_mask = images.resize_image(2, converted_mask, width, height)
converted_mask = proc.create_binary_mask(converted_mask, round=False)
# Remove aliasing artifacts using a gaussian blur.
converted_mask = converted_mask.filter(ImageFilter.GaussianBlur(radius=4))
# Expand the mask to fit the whole image if needed.
if paste_to is not None:
converted_mask = proc.uncrop(converted_mask,
(width, height),
paste_to)
masks_for_overlay = []
for i, overlay_image in enumerate(overlay_images):
masks_for_overlay[i] = converted_mask
image_masked = Image.new('RGBa', (overlay_image.width, overlay_image.height))
image_masked.paste(overlay_image.convert("RGBA").convert("RGBa"),
mask=ImageOps.invert(converted_mask.convert('L')))
overlay_images[i] = image_masked.convert('RGBA')
return masks_for_overlay
def weighted_histogram_filter(img, kernel, kernel_center, percentile_min=0.0, percentile_max=1.0, min_width=1.0):
# Converts an index tuple into a vector.
def vec(x):
return np.array(x)
kernel_min = -kernel_center
kernel_max = vec(kernel.shape) - kernel_center
def weighted_histogram_filter_single(idx):
idx = vec(idx)
min_index = np.maximum(0, idx + kernel_min)
max_index = np.minimum(vec(img.shape), idx + kernel_max)
window_shape = max_index - min_index
class WeightedElement:
def __init__(self, value, weight):
self.value: float = value
self.weight: float = weight
self.window_min: float = 0.0
self.window_max: float = 1.0
# Collect the values in the image as WeightedElements,
# weighted by their corresponding kernel values.
values = []
for window_tup in np.ndindex(tuple(window_shape)):
window_index = vec(window_tup)
image_index = window_index + min_index
centered_kernel_index = image_index - idx
kernel_index = centered_kernel_index + kernel_center
element = WeightedElement(img[tuple(image_index)], kernel[tuple(kernel_index)])
values.append(element)
def sort_key(x: WeightedElement):
return x.value
values.sort(key=sort_key)
# Calculate the height of the stack (sum)
# and each sample's range they occupy in the stack
sum = 0
for i in range(len(values)):
values[i].window_min = sum
sum += values[i].weight
values[i].window_max = sum
# Calculate what range of this stack ("window")
# we want to get the weighted average across.
window_min = sum * percentile_min
window_max = sum * percentile_max
window_width = window_max - window_min
# Ensure the window is within the stack and at least a certain size.
if window_width < min_width:
window_center = (window_min + window_max) / 2
window_min = window_center - min_width / 2
window_max = window_center + min_width / 2
if window_max > sum:
window_max = sum
window_min = sum - min_width
if window_min < 0:
window_min = 0
window_max = min_width
value = 0
value_weight = 0
# Get the weighted average of all the samples
# that overlap with the window, weighted
# by the size of their overlap.
for i in range(len(values)):
if window_min >= values[i].window_max:
continue
if window_max <= values[i].window_min:
break
s = max(window_min, values[i].window_min)
e = min(window_max, values[i].window_max)
w = e - s
value += values[i].value * w
value_weight += w
return value / value_weight if value_weight != 0 else 0
img_out = img.copy()
# Apply the kernel operation over each pixel.
for index in np.ndindex(img.shape):
img_out[index] = weighted_histogram_filter_single(index)
return img_out
def smoothstep(x):
return x * x * (3 - 2 * x)
def smootherstep(x):
return x * x * x * (x * (6 * x - 15) + 10)
def get_gaussian_kernel(stddev_radius=1.0, max_radius=2):
# Evaluates a 0-1 normalized gaussian function for a given square distance from the mean.
def gaussian(sqr_mag):
return math.exp(-sqr_mag / (stddev_radius * stddev_radius))
# Helper function for converting a tuple to an array.
def vec(x):
return np.array(x)
"""
Since a gaussian is unbounded, we need to limit ourselves
to a finite range.
We taper the ends off at the end of that range so they equal zero
while preserving the maximum value of 1 at the mean.
"""
zero_radius = max_radius + 1.0
gauss_zero = gaussian(zero_radius * zero_radius)
gauss_kernel_scale = 1 / (1 - gauss_zero)
def gaussian_kernel_func(coordinate):
x = coordinate[0] ** 2.0 + coordinate[1] ** 2.0
x = gaussian(x)
x -= gauss_zero
x *= gauss_kernel_scale
x = max(0.0, x)
return x
size = max_radius * 2 + 1
kernel_center = max_radius
kernel = np.zeros((size, size))
for index in np.ndindex(kernel.shape):
kernel[index] = gaussian_kernel_func(vec(index) - kernel_center)
return kernel, kernel_center
# ------------------- Constants -------------------
default = SoftInpaintingSettings(1, 0.5, 4, 0, 0.5, 2)
enabled_ui_label = "Soft inpainting"
enabled_gen_param_label = "Soft inpainting enabled"
enabled_el_id = "soft_inpainting_enabled"
ui_labels = SoftInpaintingSettings(
"Schedule bias",
"Preservation strength",
"Transition contrast boost",
"Mask influence",
"Difference threshold",
"Difference contrast")
ui_info = SoftInpaintingSettings(
"Shifts when preservation of original content occurs during denoising.",
"How strongly partially masked content should be preserved.",
"Amplifies the contrast that may be lost in partially masked regions.",
"How strongly the original mask should bias the difference threshold.",
"How much an image region can change before the original pixels are not blended in anymore.",
"How sharp the transition should be between blended and not blended.")
gen_param_labels = SoftInpaintingSettings(
"Soft inpainting schedule bias",
"Soft inpainting preservation strength",
"Soft inpainting transition contrast boost",
"Soft inpainting mask influence",
"Soft inpainting difference threshold",
"Soft inpainting difference contrast")
el_ids = SoftInpaintingSettings(
"mask_blend_power",
"mask_blend_scale",
"inpaint_detail_preservation",
"composite_mask_influence",
"composite_difference_threshold",
"composite_difference_contrast")
# ------------------- Script -------------------
class Script(scripts.Script):
def __init__(self):
self.section = "inpaint"
self.masks_for_overlay = None
self.overlay_images = None
def title(self):
return "Soft Inpainting"
def show(self, is_img2img):
return scripts.AlwaysVisible if is_img2img else False
def ui(self, is_img2img):
if not is_img2img:
return
with InputAccordion(False, label=enabled_ui_label, elem_id=enabled_el_id) as soft_inpainting_enabled:
with gr.Group():
gr.Markdown(
"""
Soft inpainting allows you to **seamlessly blend original content with inpainted content** according to the mask opacity.
**High _Mask blur_** values are recommended!
""")
power = \
gr.Slider(label=ui_labels.mask_blend_power,
info=ui_info.mask_blend_power,
minimum=0,
maximum=8,
step=0.1,
value=default.mask_blend_power,
elem_id=el_ids.mask_blend_power)
scale = \
gr.Slider(label=ui_labels.mask_blend_scale,
info=ui_info.mask_blend_scale,
minimum=0,
maximum=8,
step=0.05,
value=default.mask_blend_scale,
elem_id=el_ids.mask_blend_scale)
detail = \
gr.Slider(label=ui_labels.inpaint_detail_preservation,
info=ui_info.inpaint_detail_preservation,
minimum=1,
maximum=32,
step=0.5,
value=default.inpaint_detail_preservation,
elem_id=el_ids.inpaint_detail_preservation)
gr.Markdown(
"""
### Pixel Composite Settings
""")
mask_inf = \
gr.Slider(label=ui_labels.composite_mask_influence,
info=ui_info.composite_mask_influence,
minimum=0,
maximum=1,
step=0.05,
value=default.composite_mask_influence,
elem_id=el_ids.composite_mask_influence)
dif_thresh = \
gr.Slider(label=ui_labels.composite_difference_threshold,
info=ui_info.composite_difference_threshold,
minimum=0,
maximum=8,
step=0.25,
value=default.composite_difference_threshold,
elem_id=el_ids.composite_difference_threshold)
dif_contr = \
gr.Slider(label=ui_labels.composite_difference_contrast,
info=ui_info.composite_difference_contrast,
minimum=0,
maximum=8,
step=0.25,
value=default.composite_difference_contrast,
elem_id=el_ids.composite_difference_contrast)
with gr.Accordion("Help", open=False):
gr.Markdown(
f"""
### {ui_labels.mask_blend_power}
The blending strength of original content is scaled proportionally with the decreasing noise level values at each step (sigmas).
This ensures that the influence of the denoiser and original content preservation is roughly balanced at each step.
This balance can be shifted using this parameter, controlling whether earlier or later steps have stronger preservation.
- **Below 1**: Stronger preservation near the end (with low sigma)
- **1**: Balanced (proportional to sigma)
- **Above 1**: Stronger preservation in the beginning (with high sigma)
""")
gr.Markdown(
f"""
### {ui_labels.mask_blend_scale}
Skews whether partially masked image regions should be more likely to preserve the original content or favor inpainted content.
This may need to be adjusted depending on the {ui_labels.mask_blend_power}, CFG Scale, prompt and Denoising strength.
- **Low values**: Favors generated content.
- **High values**: Favors original content.
""")
gr.Markdown(
f"""
### {ui_labels.inpaint_detail_preservation}
This parameter controls how the original latent vectors and denoised latent vectors are interpolated.
With higher values, the magnitude of the resulting blended vector will be closer to the maximum of the two interpolated vectors.
This can prevent the loss of contrast that occurs with linear interpolation.
- **Low values**: Softer blending, details may fade.
- **High values**: Stronger contrast, may over-saturate colors.
""")
gr.Markdown(
"""
## Pixel Composite Settings
Masks are generated based on how much a part of the image changed after denoising.
These masks are used to blend the original and final images together.
If the difference is low, the original pixels are used instead of the pixels returned by the inpainting process.
""")
gr.Markdown(
f"""
### {ui_labels.composite_mask_influence}
This parameter controls how much the mask should bias this sensitivity to difference.
- **0**: Ignore the mask, only consider differences in image content.
- **1**: Follow the mask closely despite image content changes.
""")
gr.Markdown(
f"""
### {ui_labels.composite_difference_threshold}
This value represents the difference at which the original pixels will have less than 50% opacity.
- **Low values**: Two images patches must be almost the same in order to retain original pixels.
- **High values**: Two images patches can be very different and still retain original pixels.
""")
gr.Markdown(
f"""
### {ui_labels.composite_difference_contrast}
This value represents the contrast between the opacity of the original and inpainted content.
- **Low values**: The blend will be more gradual and have longer transitions, but may cause ghosting.
- **High values**: Ghosting will be less common, but transitions may be very sudden.
""")
self.infotext_fields = [(soft_inpainting_enabled, enabled_gen_param_label),
(power, gen_param_labels.mask_blend_power),
(scale, gen_param_labels.mask_blend_scale),
(detail, gen_param_labels.inpaint_detail_preservation),
(mask_inf, gen_param_labels.composite_mask_influence),
(dif_thresh, gen_param_labels.composite_difference_threshold),
(dif_contr, gen_param_labels.composite_difference_contrast)]
self.paste_field_names = []
for _, field_name in self.infotext_fields:
self.paste_field_names.append(field_name)
return [soft_inpainting_enabled,
power,
scale,
detail,
mask_inf,
dif_thresh,
dif_contr]
def process(self, p, enabled, power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr):
if not enabled:
return
if not processing_uses_inpainting(p):
return
# Shut off the rounding it normally does.
p.mask_round = False
settings = SoftInpaintingSettings(power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr)
# p.extra_generation_params["Mask rounding"] = False
settings.add_generation_params(p.extra_generation_params)
def on_mask_blend(self, p, mba: scripts.MaskBlendArgs, enabled, power, scale, detail_preservation, mask_inf,
dif_thresh, dif_contr):
if not enabled:
return
if not processing_uses_inpainting(p):
return
if mba.is_final_blend:
mba.blended_latent = mba.current_latent
return
settings = SoftInpaintingSettings(power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr)
# todo: Why is sigma 2D? Both values are the same.
mba.blended_latent = latent_blend(settings,
mba.init_latent,
mba.current_latent,
get_modified_nmask(settings, mba.nmask, mba.sigma[0]))
def post_sample(self, p, ps: scripts.PostSampleArgs, enabled, power, scale, detail_preservation, mask_inf,
dif_thresh, dif_contr):
if not enabled:
return
if not processing_uses_inpainting(p):
return
nmask = getattr(p, "nmask", None)
if nmask is None:
return
from modules import images
from modules.shared import opts
settings = SoftInpaintingSettings(power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr)
# since the original code puts holes in the existing overlay images,
# we have to rebuild them.
self.overlay_images = []
for img in p.init_images:
image = images.flatten(img, opts.img2img_background_color)
if p.paste_to is None and p.resize_mode != 3:
image = images.resize_image(p.resize_mode, image, p.width, p.height)
self.overlay_images.append(image.convert('RGBA'))
if len(p.init_images) == 1:
self.overlay_images = self.overlay_images * p.batch_size
if getattr(ps.samples, 'already_decoded', False):
self.masks_for_overlay = apply_masks(settings=settings,
nmask=nmask,
overlay_images=self.overlay_images,
width=p.width,
height=p.height,
paste_to=p.paste_to)
else:
self.masks_for_overlay = apply_adaptive_masks(settings=settings,
nmask=nmask,
latent_orig=p.init_latent,
latent_processed=ps.samples,
overlay_images=self.overlay_images,
width=p.width,
height=p.height,
paste_to=p.paste_to)
def postprocess_maskoverlay(self, p, ppmo: scripts.PostProcessMaskOverlayArgs, enabled, power, scale,
detail_preservation, mask_inf, dif_thresh, dif_contr):
if not enabled:
return
if not processing_uses_inpainting(p):
return
if self.masks_for_overlay is None:
return
if self.overlay_images is None:
return
ppmo.mask_for_overlay = self.masks_for_overlay[ppmo.index]
ppmo.overlay_image = self.overlay_images[ppmo.index] | --- +++ @@ -48,6 +48,12 @@
def latent_blend(settings, a, b, t):
+ """
+ Interpolates two latent image representations according to the parameter t,
+ where the interpolated vectors' magnitudes are also interpolated separately.
+ The "detail_preservation" factor biases the magnitude interpolation towards
+ the larger of the two magnitudes.
+ """
import torch
# NOTE: We use inplace operations wherever possible.
@@ -100,6 +106,20 @@
def get_modified_nmask(settings, nmask, sigma):
+ """
+ Converts a negative mask representing the transparency of the original latent vectors being overlaid
+ to a mask that is scaled according to the denoising strength for this step.
+
+ Where:
+ 0 = fully opaque, infinite density, fully masked
+ 1 = fully transparent, zero density, fully unmasked
+
+ We bring this transparency to a power, as this allows one to simulate N number of blending operations
+ where N can be any positive real value. Using this one can control the balance of influence between
+ the denoiser and the original latents according to the sigma value.
+
+ NOTE: "mask" is not used
+ """
import torch
return torch.pow(nmask, (sigma ** settings.mask_blend_power) * settings.mask_blend_scale)
@@ -225,6 +245,31 @@
def weighted_histogram_filter(img, kernel, kernel_center, percentile_min=0.0, percentile_max=1.0, min_width=1.0):
+ """
+ Generalization convolution filter capable of applying
+ weighted mean, median, maximum, and minimum filters
+ parametrically using an arbitrary kernel.
+
+ Args:
+ img (nparray):
+ The image, a 2-D array of floats, to which the filter is being applied.
+ kernel (nparray):
+ The kernel, a 2-D array of floats.
+ kernel_center (nparray):
+ The kernel center coordinate, a 1-D array with two elements.
+ percentile_min (float):
+ The lower bound of the histogram window used by the filter,
+ from 0 to 1.
+ percentile_max (float):
+ The upper bound of the histogram window used by the filter,
+ from 0 to 1.
+ min_width (float):
+ The minimum size of the histogram window bounds, in weight units.
+ Must be greater than 0.
+
+ Returns:
+ (nparray): A filtered copy of the input image "img", a 2-D array of floats.
+ """
# Converts an index tuple into a vector.
def vec(x):
@@ -240,6 +285,10 @@ window_shape = max_index - min_index
class WeightedElement:
+ """
+ An element of the histogram, its weight
+ and bounds.
+ """
def __init__(self, value, weight):
self.value: float = value
@@ -322,14 +371,36 @@
def smoothstep(x):
+ """
+ The smoothstep function, input should be clamped to 0-1 range.
+ Turns a diagonal line (f(x) = x) into a sigmoid-like curve.
+ """
return x * x * (3 - 2 * x)
def smootherstep(x):
+ """
+ The smootherstep function, input should be clamped to 0-1 range.
+ Turns a diagonal line (f(x) = x) into a sigmoid-like curve.
+ """
return x * x * x * (x * (6 * x - 15) + 10)
def get_gaussian_kernel(stddev_radius=1.0, max_radius=2):
+ """
+ Creates a Gaussian kernel with thresholded edges.
+
+ Args:
+ stddev_radius (float):
+ Standard deviation of the gaussian kernel, in pixels.
+ max_radius (int):
+ The size of the filter kernel. The number of pixels is (max_radius*2+1) ** 2.
+ The kernel is thresholded so that any values one pixel beyond this radius
+ is weighted at 0.
+
+ Returns:
+ (nparray, nparray): A kernel array (shape: (N, N)), its center coordinate (shape: (2))
+ """
# Evaluates a 0-1 normalized gaussian function for a given square distance from the mean.
def gaussian(sqr_mag):
@@ -686,4 +757,4 @@ return
ppmo.mask_for_overlay = self.masks_for_overlay[ppmo.index]
- ppmo.overlay_image = self.overlay_images[ppmo.index]+ ppmo.overlay_image = self.overlay_images[ppmo.index]
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/extensions-builtin/soft-inpainting/scripts/soft_inpainting.py |
Add docstrings explaining edge cases | import inspect
from pydantic import BaseModel, Field, create_model
from typing import Any, Optional, Literal
from inflection import underscore
from modules.processing import StableDiffusionProcessingTxt2Img, StableDiffusionProcessingImg2Img
from modules.shared import sd_upscalers, opts, parser
API_NOT_ALLOWED = [
"self",
"kwargs",
"sd_model",
"outpath_samples",
"outpath_grids",
"sampler_index",
# "do_not_save_samples",
# "do_not_save_grid",
"extra_generation_params",
"overlay_images",
"do_not_reload_embeddings",
"seed_enable_extras",
"prompt_for_display",
"sampler_noise_scheduler_override",
"ddim_discretize"
]
class ModelDef(BaseModel):
field: str
field_alias: str
field_type: Any
field_value: Any
field_exclude: bool = False
class PydanticModelGenerator:
def __init__(
self,
model_name: str = None,
class_instance = None,
additional_fields = None,
):
def field_type_generator(k, v):
field_type = v.annotation
if field_type == 'Image':
# images are sent as base64 strings via API
field_type = 'str'
return Optional[field_type]
def merge_class_params(class_):
all_classes = list(filter(lambda x: x is not object, inspect.getmro(class_)))
parameters = {}
for classes in all_classes:
parameters = {**parameters, **inspect.signature(classes.__init__).parameters}
return parameters
self._model_name = model_name
self._class_data = merge_class_params(class_instance)
self._model_def = [
ModelDef(
field=underscore(k),
field_alias=k,
field_type=field_type_generator(k, v),
field_value=None if isinstance(v.default, property) else v.default
)
for (k,v) in self._class_data.items() if k not in API_NOT_ALLOWED
]
for fields in additional_fields:
self._model_def.append(ModelDef(
field=underscore(fields["key"]),
field_alias=fields["key"],
field_type=fields["type"],
field_value=fields["default"],
field_exclude=fields["exclude"] if "exclude" in fields else False))
def generate_model(self):
fields = {
d.field: (d.field_type, Field(default=d.field_value, alias=d.field_alias, exclude=d.field_exclude)) for d in self._model_def
}
DynamicModel = create_model(self._model_name, **fields)
DynamicModel.__config__.allow_population_by_field_name = True
DynamicModel.__config__.allow_mutation = True
return DynamicModel
StableDiffusionTxt2ImgProcessingAPI = PydanticModelGenerator(
"StableDiffusionProcessingTxt2Img",
StableDiffusionProcessingTxt2Img,
[
{"key": "sampler_index", "type": str, "default": "Euler"},
{"key": "script_name", "type": str, "default": None},
{"key": "script_args", "type": list, "default": []},
{"key": "send_images", "type": bool, "default": True},
{"key": "save_images", "type": bool, "default": False},
{"key": "alwayson_scripts", "type": dict, "default": {}},
{"key": "force_task_id", "type": str, "default": None},
{"key": "infotext", "type": str, "default": None},
]
).generate_model()
StableDiffusionImg2ImgProcessingAPI = PydanticModelGenerator(
"StableDiffusionProcessingImg2Img",
StableDiffusionProcessingImg2Img,
[
{"key": "sampler_index", "type": str, "default": "Euler"},
{"key": "init_images", "type": list, "default": None},
{"key": "denoising_strength", "type": float, "default": 0.75},
{"key": "mask", "type": str, "default": None},
{"key": "include_init_images", "type": bool, "default": False, "exclude" : True},
{"key": "script_name", "type": str, "default": None},
{"key": "script_args", "type": list, "default": []},
{"key": "send_images", "type": bool, "default": True},
{"key": "save_images", "type": bool, "default": False},
{"key": "alwayson_scripts", "type": dict, "default": {}},
{"key": "force_task_id", "type": str, "default": None},
{"key": "infotext", "type": str, "default": None},
]
).generate_model()
class TextToImageResponse(BaseModel):
images: list[str] = Field(default=None, title="Image", description="The generated image in base64 format.")
parameters: dict
info: str
class ImageToImageResponse(BaseModel):
images: list[str] = Field(default=None, title="Image", description="The generated image in base64 format.")
parameters: dict
info: str
class ExtrasBaseRequest(BaseModel):
resize_mode: Literal[0, 1] = Field(default=0, title="Resize Mode", description="Sets the resize mode: 0 to upscale by upscaling_resize amount, 1 to upscale up to upscaling_resize_h x upscaling_resize_w.")
show_extras_results: bool = Field(default=True, title="Show results", description="Should the backend return the generated image?")
gfpgan_visibility: float = Field(default=0, title="GFPGAN Visibility", ge=0, le=1, allow_inf_nan=False, description="Sets the visibility of GFPGAN, values should be between 0 and 1.")
codeformer_visibility: float = Field(default=0, title="CodeFormer Visibility", ge=0, le=1, allow_inf_nan=False, description="Sets the visibility of CodeFormer, values should be between 0 and 1.")
codeformer_weight: float = Field(default=0, title="CodeFormer Weight", ge=0, le=1, allow_inf_nan=False, description="Sets the weight of CodeFormer, values should be between 0 and 1.")
upscaling_resize: float = Field(default=2, title="Upscaling Factor", gt=0, description="By how much to upscale the image, only used when resize_mode=0.")
upscaling_resize_w: int = Field(default=512, title="Target Width", ge=1, description="Target width for the upscaler to hit. Only used when resize_mode=1.")
upscaling_resize_h: int = Field(default=512, title="Target Height", ge=1, description="Target height for the upscaler to hit. Only used when resize_mode=1.")
upscaling_crop: bool = Field(default=True, title="Crop to fit", description="Should the upscaler crop the image to fit in the chosen size?")
upscaler_1: str = Field(default="None", title="Main upscaler", description=f"The name of the main upscaler to use, it has to be one of this list: {' , '.join([x.name for x in sd_upscalers])}")
upscaler_2: str = Field(default="None", title="Secondary upscaler", description=f"The name of the secondary upscaler to use, it has to be one of this list: {' , '.join([x.name for x in sd_upscalers])}")
extras_upscaler_2_visibility: float = Field(default=0, title="Secondary upscaler visibility", ge=0, le=1, allow_inf_nan=False, description="Sets the visibility of secondary upscaler, values should be between 0 and 1.")
upscale_first: bool = Field(default=False, title="Upscale first", description="Should the upscaler run before restoring faces?")
class ExtraBaseResponse(BaseModel):
html_info: str = Field(title="HTML info", description="A series of HTML tags containing the process info.")
class ExtrasSingleImageRequest(ExtrasBaseRequest):
image: str = Field(default="", title="Image", description="Image to work on, must be a Base64 string containing the image's data.")
class ExtrasSingleImageResponse(ExtraBaseResponse):
image: str = Field(default=None, title="Image", description="The generated image in base64 format.")
class FileData(BaseModel):
data: str = Field(title="File data", description="Base64 representation of the file")
name: str = Field(title="File name")
class ExtrasBatchImagesRequest(ExtrasBaseRequest):
imageList: list[FileData] = Field(title="Images", description="List of images to work on. Must be Base64 strings")
class ExtrasBatchImagesResponse(ExtraBaseResponse):
images: list[str] = Field(title="Images", description="The generated images in base64 format.")
class PNGInfoRequest(BaseModel):
image: str = Field(title="Image", description="The base64 encoded PNG image")
class PNGInfoResponse(BaseModel):
info: str = Field(title="Image info", description="A string with the parameters used to generate the image")
items: dict = Field(title="Items", description="A dictionary containing all the other fields the image had")
parameters: dict = Field(title="Parameters", description="A dictionary with parsed generation info fields")
class ProgressRequest(BaseModel):
skip_current_image: bool = Field(default=False, title="Skip current image", description="Skip current image serialization")
class ProgressResponse(BaseModel):
progress: float = Field(title="Progress", description="The progress with a range of 0 to 1")
eta_relative: float = Field(title="ETA in secs")
state: dict = Field(title="State", description="The current state snapshot")
current_image: str = Field(default=None, title="Current image", description="The current image in base64 format. opts.show_progress_every_n_steps is required for this to work.")
textinfo: str = Field(default=None, title="Info text", description="Info text used by WebUI.")
class InterrogateRequest(BaseModel):
image: str = Field(default="", title="Image", description="Image to work on, must be a Base64 string containing the image's data.")
model: str = Field(default="clip", title="Model", description="The interrogate model used.")
class InterrogateResponse(BaseModel):
caption: str = Field(default=None, title="Caption", description="The generated caption for the image.")
class TrainResponse(BaseModel):
info: str = Field(title="Train info", description="Response string from train embedding or hypernetwork task.")
class CreateResponse(BaseModel):
info: str = Field(title="Create info", description="Response string from create embedding or hypernetwork task.")
fields = {}
for key, metadata in opts.data_labels.items():
value = opts.data.get(key)
optType = opts.typemap.get(type(metadata.default), type(metadata.default)) if metadata.default else Any
if metadata is not None:
fields.update({key: (Optional[optType], Field(default=metadata.default, description=metadata.label))})
else:
fields.update({key: (Optional[optType], Field())})
OptionsModel = create_model("Options", **fields)
flags = {}
_options = vars(parser)['_option_string_actions']
for key in _options:
if(_options[key].dest != 'help'):
flag = _options[key]
_type = str
if _options[key].default is not None:
_type = type(_options[key].default)
flags.update({flag.dest: (_type, Field(default=flag.default, description=flag.help))})
FlagsModel = create_model("Flags", **flags)
class SamplerItem(BaseModel):
name: str = Field(title="Name")
aliases: list[str] = Field(title="Aliases")
options: dict[str, str] = Field(title="Options")
class SchedulerItem(BaseModel):
name: str = Field(title="Name")
label: str = Field(title="Label")
aliases: Optional[list[str]] = Field(title="Aliases")
default_rho: Optional[float] = Field(title="Default Rho")
need_inner_model: Optional[bool] = Field(title="Needs Inner Model")
class UpscalerItem(BaseModel):
name: str = Field(title="Name")
model_name: Optional[str] = Field(title="Model Name")
model_path: Optional[str] = Field(title="Path")
model_url: Optional[str] = Field(title="URL")
scale: Optional[float] = Field(title="Scale")
class LatentUpscalerModeItem(BaseModel):
name: str = Field(title="Name")
class SDModelItem(BaseModel):
title: str = Field(title="Title")
model_name: str = Field(title="Model Name")
hash: Optional[str] = Field(title="Short hash")
sha256: Optional[str] = Field(title="sha256 hash")
filename: str = Field(title="Filename")
config: Optional[str] = Field(title="Config file")
class SDVaeItem(BaseModel):
model_name: str = Field(title="Model Name")
filename: str = Field(title="Filename")
class HypernetworkItem(BaseModel):
name: str = Field(title="Name")
path: Optional[str] = Field(title="Path")
class FaceRestorerItem(BaseModel):
name: str = Field(title="Name")
cmd_dir: Optional[str] = Field(title="Path")
class RealesrganItem(BaseModel):
name: str = Field(title="Name")
path: Optional[str] = Field(title="Path")
scale: Optional[int] = Field(title="Scale")
class PromptStyleItem(BaseModel):
name: str = Field(title="Name")
prompt: Optional[str] = Field(title="Prompt")
negative_prompt: Optional[str] = Field(title="Negative Prompt")
class EmbeddingItem(BaseModel):
step: Optional[int] = Field(title="Step", description="The number of steps that were used to train this embedding, if available")
sd_checkpoint: Optional[str] = Field(title="SD Checkpoint", description="The hash of the checkpoint this embedding was trained on, if available")
sd_checkpoint_name: Optional[str] = Field(title="SD Checkpoint Name", description="The name of the checkpoint this embedding was trained on, if available. Note that this is the name that was used by the trainer; for a stable identifier, use `sd_checkpoint` instead")
shape: int = Field(title="Shape", description="The length of each individual vector in the embedding")
vectors: int = Field(title="Vectors", description="The number of vectors in the embedding")
class EmbeddingsResponse(BaseModel):
loaded: dict[str, EmbeddingItem] = Field(title="Loaded", description="Embeddings loaded for the current model")
skipped: dict[str, EmbeddingItem] = Field(title="Skipped", description="Embeddings skipped for the current model (likely due to architecture incompatibility)")
class MemoryResponse(BaseModel):
ram: dict = Field(title="RAM", description="System memory stats")
cuda: dict = Field(title="CUDA", description="nVidia CUDA memory stats")
class ScriptsList(BaseModel):
txt2img: list = Field(default=None, title="Txt2img", description="Titles of scripts (txt2img)")
img2img: list = Field(default=None, title="Img2img", description="Titles of scripts (img2img)")
class ScriptArg(BaseModel):
label: str = Field(default=None, title="Label", description="Name of the argument in UI")
value: Optional[Any] = Field(default=None, title="Value", description="Default value of the argument")
minimum: Optional[Any] = Field(default=None, title="Minimum", description="Minimum allowed value for the argumentin UI")
maximum: Optional[Any] = Field(default=None, title="Minimum", description="Maximum allowed value for the argumentin UI")
step: Optional[Any] = Field(default=None, title="Minimum", description="Step for changing value of the argumentin UI")
choices: Optional[list[str]] = Field(default=None, title="Choices", description="Possible values for the argument")
class ScriptInfo(BaseModel):
name: str = Field(default=None, title="Name", description="Script name")
is_alwayson: bool = Field(default=None, title="IsAlwayson", description="Flag specifying whether this script is an alwayson script")
is_img2img: bool = Field(default=None, title="IsImg2img", description="Flag specifying whether this script is an img2img script")
args: list[ScriptArg] = Field(title="Arguments", description="List of script's arguments")
class ExtensionItem(BaseModel):
name: str = Field(title="Name", description="Extension name")
remote: str = Field(title="Remote", description="Extension Repository URL")
branch: str = Field(title="Branch", description="Extension Repository Branch")
commit_hash: str = Field(title="Commit Hash", description="Extension Repository Commit Hash")
version: str = Field(title="Version", description="Extension Version")
commit_date: str = Field(title="Commit Date", description="Extension Repository Commit Date")
enabled: bool = Field(title="Enabled", description="Flag specifying whether this extension is enabled") | --- +++ @@ -25,6 +25,7 @@ ]
class ModelDef(BaseModel):
+ """Assistance Class for Pydantic Dynamic Model Generation"""
field: str
field_alias: str
@@ -34,6 +35,11 @@
class PydanticModelGenerator:
+ """
+ Takes in created classes and stubs them out in a way FastAPI/Pydantic is happy about:
+ source_data is a snapshot of the default values produced by the class
+ params are the names of the actual keys required by __init__
+ """
def __init__(
self,
@@ -79,6 +85,10 @@ field_exclude=fields["exclude"] if "exclude" in fields else False))
def generate_model(self):
+ """
+ Creates a pydantic BaseModel
+ from the json and overrides provided at initialization
+ """
fields = {
d.field: (d.field_type, Field(default=d.field_value, alias=d.field_alias, exclude=d.field_exclude)) for d in self._model_def
}
@@ -316,4 +326,4 @@ commit_hash: str = Field(title="Commit Hash", description="Extension Repository Commit Hash")
version: str = Field(title="Version", description="Extension Version")
commit_date: str = Field(title="Commit Date", description="Extension Repository Commit Date")
- enabled: bool = Field(title="Enabled", description="Flag specifying whether this extension is enabled")+ enabled: bool = Field(title="Enabled", description="Flag specifying whether this extension is enabled")
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/api/models.py |
Include argument descriptions in docstrings | from __future__ import annotations
import configparser
import dataclasses
import os
import threading
import re
from modules import shared, errors, cache, scripts
from modules.gitpython_hack import Repo
from modules.paths_internal import extensions_dir, extensions_builtin_dir, script_path # noqa: F401
extensions: list[Extension] = []
extension_paths: dict[str, Extension] = {}
loaded_extensions: dict[str, Exception] = {}
os.makedirs(extensions_dir, exist_ok=True)
def active():
if shared.cmd_opts.disable_all_extensions or shared.opts.disable_all_extensions == "all":
return []
elif shared.cmd_opts.disable_extra_extensions or shared.opts.disable_all_extensions == "extra":
return [x for x in extensions if x.enabled and x.is_builtin]
else:
return [x for x in extensions if x.enabled]
@dataclasses.dataclass
class CallbackOrderInfo:
name: str
before: list
after: list
class ExtensionMetadata:
filename = "metadata.ini"
config: configparser.ConfigParser
canonical_name: str
requires: list
def __init__(self, path, canonical_name):
self.config = configparser.ConfigParser()
filepath = os.path.join(path, self.filename)
# `self.config.read()` will quietly swallow OSErrors (which FileNotFoundError is),
# so no need to check whether the file exists beforehand.
try:
self.config.read(filepath)
except Exception:
errors.report(f"Error reading {self.filename} for extension {canonical_name}.", exc_info=True)
self.canonical_name = self.config.get("Extension", "Name", fallback=canonical_name)
self.canonical_name = canonical_name.lower().strip()
self.requires = None
def get_script_requirements(self, field, section, extra_section=None):
x = self.config.get(section, field, fallback='')
if extra_section:
x = x + ', ' + self.config.get(extra_section, field, fallback='')
listed_requirements = self.parse_list(x.lower())
res = []
for requirement in listed_requirements:
loaded_requirements = (x for x in requirement.split("|") if x in loaded_extensions)
relevant_requirement = next(loaded_requirements, requirement)
res.append(relevant_requirement)
return res
def parse_list(self, text):
if not text:
return []
# both "," and " " are accepted as separator
return [x for x in re.split(r"[,\s]+", text.strip()) if x]
def list_callback_order_instructions(self):
for section in self.config.sections():
if not section.startswith("callbacks/"):
continue
callback_name = section[10:]
if not callback_name.startswith(self.canonical_name):
errors.report(f"Callback order section for extension {self.canonical_name} is referencing the wrong extension: {section}")
continue
before = self.parse_list(self.config.get(section, 'Before', fallback=''))
after = self.parse_list(self.config.get(section, 'After', fallback=''))
yield CallbackOrderInfo(callback_name, before, after)
class Extension:
lock = threading.Lock()
cached_fields = ['remote', 'commit_date', 'branch', 'commit_hash', 'version']
metadata: ExtensionMetadata
def __init__(self, name, path, enabled=True, is_builtin=False, metadata=None):
self.name = name
self.path = path
self.enabled = enabled
self.status = ''
self.can_update = False
self.is_builtin = is_builtin
self.commit_hash = ''
self.commit_date = None
self.version = ''
self.branch = None
self.remote = None
self.have_info_from_repo = False
self.metadata = metadata if metadata else ExtensionMetadata(self.path, name.lower())
self.canonical_name = metadata.canonical_name
def to_dict(self):
return {x: getattr(self, x) for x in self.cached_fields}
def from_dict(self, d):
for field in self.cached_fields:
setattr(self, field, d[field])
def read_info_from_repo(self):
if self.is_builtin or self.have_info_from_repo:
return
def read_from_repo():
with self.lock:
if self.have_info_from_repo:
return
self.do_read_info_from_repo()
return self.to_dict()
try:
d = cache.cached_data_for_file('extensions-git', self.name, os.path.join(self.path, ".git"), read_from_repo)
self.from_dict(d)
except FileNotFoundError:
pass
self.status = 'unknown' if self.status == '' else self.status
def do_read_info_from_repo(self):
repo = None
try:
if os.path.exists(os.path.join(self.path, ".git")):
repo = Repo(self.path)
except Exception:
errors.report(f"Error reading github repository info from {self.path}", exc_info=True)
if repo is None or repo.bare:
self.remote = None
else:
try:
self.remote = next(repo.remote().urls, None)
commit = repo.head.commit
self.commit_date = commit.committed_date
if repo.active_branch:
self.branch = repo.active_branch.name
self.commit_hash = commit.hexsha
self.version = self.commit_hash[:8]
except Exception:
errors.report(f"Failed reading extension data from Git repository ({self.name})", exc_info=True)
self.remote = None
self.have_info_from_repo = True
def list_files(self, subdir, extension):
dirpath = os.path.join(self.path, subdir)
if not os.path.isdir(dirpath):
return []
res = []
for filename in sorted(os.listdir(dirpath)):
res.append(scripts.ScriptFile(self.path, filename, os.path.join(dirpath, filename)))
res = [x for x in res if os.path.splitext(x.path)[1].lower() == extension and os.path.isfile(x.path)]
return res
def check_updates(self):
repo = Repo(self.path)
branch_name = f'{repo.remote().name}/{self.branch}'
for fetch in repo.remote().fetch(dry_run=True):
if self.branch and fetch.name != branch_name:
continue
if fetch.flags != fetch.HEAD_UPTODATE:
self.can_update = True
self.status = "new commits"
return
try:
origin = repo.rev_parse(branch_name)
if repo.head.commit != origin:
self.can_update = True
self.status = "behind HEAD"
return
except Exception:
self.can_update = False
self.status = "unknown (remote error)"
return
self.can_update = False
self.status = "latest"
def fetch_and_reset_hard(self, commit=None):
repo = Repo(self.path)
if commit is None:
commit = f'{repo.remote().name}/{self.branch}'
# Fix: `error: Your local changes to the following files would be overwritten by merge`,
# because WSL2 Docker set 755 file permissions instead of 644, this results to the error.
repo.git.fetch(all=True)
repo.git.reset(commit, hard=True)
self.have_info_from_repo = False
def list_extensions():
extensions.clear()
extension_paths.clear()
loaded_extensions.clear()
if shared.cmd_opts.disable_all_extensions:
print("*** \"--disable-all-extensions\" arg was used, will not load any extensions ***")
elif shared.opts.disable_all_extensions == "all":
print("*** \"Disable all extensions\" option was set, will not load any extensions ***")
elif shared.cmd_opts.disable_extra_extensions:
print("*** \"--disable-extra-extensions\" arg was used, will only load built-in extensions ***")
elif shared.opts.disable_all_extensions == "extra":
print("*** \"Disable all extensions\" option was set, will only load built-in extensions ***")
# scan through extensions directory and load metadata
for dirname in [extensions_builtin_dir, extensions_dir]:
if not os.path.isdir(dirname):
continue
for extension_dirname in sorted(os.listdir(dirname)):
path = os.path.join(dirname, extension_dirname)
if not os.path.isdir(path):
continue
canonical_name = extension_dirname
metadata = ExtensionMetadata(path, canonical_name)
# check for duplicated canonical names
already_loaded_extension = loaded_extensions.get(metadata.canonical_name)
if already_loaded_extension is not None:
errors.report(f'Duplicate canonical name "{canonical_name}" found in extensions "{extension_dirname}" and "{already_loaded_extension.name}". Former will be discarded.', exc_info=False)
continue
is_builtin = dirname == extensions_builtin_dir
extension = Extension(name=extension_dirname, path=path, enabled=extension_dirname not in shared.opts.disabled_extensions, is_builtin=is_builtin, metadata=metadata)
extensions.append(extension)
extension_paths[extension.path] = extension
loaded_extensions[canonical_name] = extension
for extension in extensions:
extension.metadata.requires = extension.metadata.get_script_requirements("Requires", "Extension")
# check for requirements
for extension in extensions:
if not extension.enabled:
continue
for req in extension.metadata.requires:
required_extension = loaded_extensions.get(req)
if required_extension is None:
errors.report(f'Extension "{extension.name}" requires "{req}" which is not installed.', exc_info=False)
continue
if not required_extension.enabled:
errors.report(f'Extension "{extension.name}" requires "{required_extension.name}" which is disabled.', exc_info=False)
continue
def find_extension(filename):
parentdir = os.path.dirname(os.path.realpath(filename))
while parentdir != filename:
extension = extension_paths.get(parentdir)
if extension is not None:
return extension
filename = parentdir
parentdir = os.path.dirname(filename)
return None
| --- +++ @@ -1,294 +1,299 @@-from __future__ import annotations
-
-import configparser
-import dataclasses
-import os
-import threading
-import re
-
-from modules import shared, errors, cache, scripts
-from modules.gitpython_hack import Repo
-from modules.paths_internal import extensions_dir, extensions_builtin_dir, script_path # noqa: F401
-
-extensions: list[Extension] = []
-extension_paths: dict[str, Extension] = {}
-loaded_extensions: dict[str, Exception] = {}
-
-
-os.makedirs(extensions_dir, exist_ok=True)
-
-
-def active():
- if shared.cmd_opts.disable_all_extensions or shared.opts.disable_all_extensions == "all":
- return []
- elif shared.cmd_opts.disable_extra_extensions or shared.opts.disable_all_extensions == "extra":
- return [x for x in extensions if x.enabled and x.is_builtin]
- else:
- return [x for x in extensions if x.enabled]
-
-
-@dataclasses.dataclass
-class CallbackOrderInfo:
- name: str
- before: list
- after: list
-
-
-class ExtensionMetadata:
- filename = "metadata.ini"
- config: configparser.ConfigParser
- canonical_name: str
- requires: list
-
- def __init__(self, path, canonical_name):
- self.config = configparser.ConfigParser()
-
- filepath = os.path.join(path, self.filename)
- # `self.config.read()` will quietly swallow OSErrors (which FileNotFoundError is),
- # so no need to check whether the file exists beforehand.
- try:
- self.config.read(filepath)
- except Exception:
- errors.report(f"Error reading {self.filename} for extension {canonical_name}.", exc_info=True)
-
- self.canonical_name = self.config.get("Extension", "Name", fallback=canonical_name)
- self.canonical_name = canonical_name.lower().strip()
-
- self.requires = None
-
- def get_script_requirements(self, field, section, extra_section=None):
-
- x = self.config.get(section, field, fallback='')
-
- if extra_section:
- x = x + ', ' + self.config.get(extra_section, field, fallback='')
-
- listed_requirements = self.parse_list(x.lower())
- res = []
-
- for requirement in listed_requirements:
- loaded_requirements = (x for x in requirement.split("|") if x in loaded_extensions)
- relevant_requirement = next(loaded_requirements, requirement)
- res.append(relevant_requirement)
-
- return res
-
- def parse_list(self, text):
-
- if not text:
- return []
-
- # both "," and " " are accepted as separator
- return [x for x in re.split(r"[,\s]+", text.strip()) if x]
-
- def list_callback_order_instructions(self):
- for section in self.config.sections():
- if not section.startswith("callbacks/"):
- continue
-
- callback_name = section[10:]
-
- if not callback_name.startswith(self.canonical_name):
- errors.report(f"Callback order section for extension {self.canonical_name} is referencing the wrong extension: {section}")
- continue
-
- before = self.parse_list(self.config.get(section, 'Before', fallback=''))
- after = self.parse_list(self.config.get(section, 'After', fallback=''))
-
- yield CallbackOrderInfo(callback_name, before, after)
-
-
-class Extension:
- lock = threading.Lock()
- cached_fields = ['remote', 'commit_date', 'branch', 'commit_hash', 'version']
- metadata: ExtensionMetadata
-
- def __init__(self, name, path, enabled=True, is_builtin=False, metadata=None):
- self.name = name
- self.path = path
- self.enabled = enabled
- self.status = ''
- self.can_update = False
- self.is_builtin = is_builtin
- self.commit_hash = ''
- self.commit_date = None
- self.version = ''
- self.branch = None
- self.remote = None
- self.have_info_from_repo = False
- self.metadata = metadata if metadata else ExtensionMetadata(self.path, name.lower())
- self.canonical_name = metadata.canonical_name
-
- def to_dict(self):
- return {x: getattr(self, x) for x in self.cached_fields}
-
- def from_dict(self, d):
- for field in self.cached_fields:
- setattr(self, field, d[field])
-
- def read_info_from_repo(self):
- if self.is_builtin or self.have_info_from_repo:
- return
-
- def read_from_repo():
- with self.lock:
- if self.have_info_from_repo:
- return
-
- self.do_read_info_from_repo()
-
- return self.to_dict()
-
- try:
- d = cache.cached_data_for_file('extensions-git', self.name, os.path.join(self.path, ".git"), read_from_repo)
- self.from_dict(d)
- except FileNotFoundError:
- pass
- self.status = 'unknown' if self.status == '' else self.status
-
- def do_read_info_from_repo(self):
- repo = None
- try:
- if os.path.exists(os.path.join(self.path, ".git")):
- repo = Repo(self.path)
- except Exception:
- errors.report(f"Error reading github repository info from {self.path}", exc_info=True)
-
- if repo is None or repo.bare:
- self.remote = None
- else:
- try:
- self.remote = next(repo.remote().urls, None)
- commit = repo.head.commit
- self.commit_date = commit.committed_date
- if repo.active_branch:
- self.branch = repo.active_branch.name
- self.commit_hash = commit.hexsha
- self.version = self.commit_hash[:8]
-
- except Exception:
- errors.report(f"Failed reading extension data from Git repository ({self.name})", exc_info=True)
- self.remote = None
-
- self.have_info_from_repo = True
-
- def list_files(self, subdir, extension):
- dirpath = os.path.join(self.path, subdir)
- if not os.path.isdir(dirpath):
- return []
-
- res = []
- for filename in sorted(os.listdir(dirpath)):
- res.append(scripts.ScriptFile(self.path, filename, os.path.join(dirpath, filename)))
-
- res = [x for x in res if os.path.splitext(x.path)[1].lower() == extension and os.path.isfile(x.path)]
-
- return res
-
- def check_updates(self):
- repo = Repo(self.path)
- branch_name = f'{repo.remote().name}/{self.branch}'
- for fetch in repo.remote().fetch(dry_run=True):
- if self.branch and fetch.name != branch_name:
- continue
- if fetch.flags != fetch.HEAD_UPTODATE:
- self.can_update = True
- self.status = "new commits"
- return
-
- try:
- origin = repo.rev_parse(branch_name)
- if repo.head.commit != origin:
- self.can_update = True
- self.status = "behind HEAD"
- return
- except Exception:
- self.can_update = False
- self.status = "unknown (remote error)"
- return
-
- self.can_update = False
- self.status = "latest"
-
- def fetch_and_reset_hard(self, commit=None):
- repo = Repo(self.path)
- if commit is None:
- commit = f'{repo.remote().name}/{self.branch}'
- # Fix: `error: Your local changes to the following files would be overwritten by merge`,
- # because WSL2 Docker set 755 file permissions instead of 644, this results to the error.
- repo.git.fetch(all=True)
- repo.git.reset(commit, hard=True)
- self.have_info_from_repo = False
-
-
-def list_extensions():
- extensions.clear()
- extension_paths.clear()
- loaded_extensions.clear()
-
- if shared.cmd_opts.disable_all_extensions:
- print("*** \"--disable-all-extensions\" arg was used, will not load any extensions ***")
- elif shared.opts.disable_all_extensions == "all":
- print("*** \"Disable all extensions\" option was set, will not load any extensions ***")
- elif shared.cmd_opts.disable_extra_extensions:
- print("*** \"--disable-extra-extensions\" arg was used, will only load built-in extensions ***")
- elif shared.opts.disable_all_extensions == "extra":
- print("*** \"Disable all extensions\" option was set, will only load built-in extensions ***")
-
-
- # scan through extensions directory and load metadata
- for dirname in [extensions_builtin_dir, extensions_dir]:
- if not os.path.isdir(dirname):
- continue
-
- for extension_dirname in sorted(os.listdir(dirname)):
- path = os.path.join(dirname, extension_dirname)
- if not os.path.isdir(path):
- continue
-
- canonical_name = extension_dirname
- metadata = ExtensionMetadata(path, canonical_name)
-
- # check for duplicated canonical names
- already_loaded_extension = loaded_extensions.get(metadata.canonical_name)
- if already_loaded_extension is not None:
- errors.report(f'Duplicate canonical name "{canonical_name}" found in extensions "{extension_dirname}" and "{already_loaded_extension.name}". Former will be discarded.', exc_info=False)
- continue
-
- is_builtin = dirname == extensions_builtin_dir
- extension = Extension(name=extension_dirname, path=path, enabled=extension_dirname not in shared.opts.disabled_extensions, is_builtin=is_builtin, metadata=metadata)
- extensions.append(extension)
- extension_paths[extension.path] = extension
- loaded_extensions[canonical_name] = extension
-
- for extension in extensions:
- extension.metadata.requires = extension.metadata.get_script_requirements("Requires", "Extension")
-
- # check for requirements
- for extension in extensions:
- if not extension.enabled:
- continue
-
- for req in extension.metadata.requires:
- required_extension = loaded_extensions.get(req)
- if required_extension is None:
- errors.report(f'Extension "{extension.name}" requires "{req}" which is not installed.', exc_info=False)
- continue
-
- if not required_extension.enabled:
- errors.report(f'Extension "{extension.name}" requires "{required_extension.name}" which is disabled.', exc_info=False)
- continue
-
-
-def find_extension(filename):
- parentdir = os.path.dirname(os.path.realpath(filename))
-
- while parentdir != filename:
- extension = extension_paths.get(parentdir)
- if extension is not None:
- return extension
-
- filename = parentdir
- parentdir = os.path.dirname(filename)
-
- return None
+from __future__ import annotations
+
+import configparser
+import dataclasses
+import os
+import threading
+import re
+
+from modules import shared, errors, cache, scripts
+from modules.gitpython_hack import Repo
+from modules.paths_internal import extensions_dir, extensions_builtin_dir, script_path # noqa: F401
+
+extensions: list[Extension] = []
+extension_paths: dict[str, Extension] = {}
+loaded_extensions: dict[str, Exception] = {}
+
+
+os.makedirs(extensions_dir, exist_ok=True)
+
+
+def active():
+ if shared.cmd_opts.disable_all_extensions or shared.opts.disable_all_extensions == "all":
+ return []
+ elif shared.cmd_opts.disable_extra_extensions or shared.opts.disable_all_extensions == "extra":
+ return [x for x in extensions if x.enabled and x.is_builtin]
+ else:
+ return [x for x in extensions if x.enabled]
+
+
+@dataclasses.dataclass
+class CallbackOrderInfo:
+ name: str
+ before: list
+ after: list
+
+
+class ExtensionMetadata:
+ filename = "metadata.ini"
+ config: configparser.ConfigParser
+ canonical_name: str
+ requires: list
+
+ def __init__(self, path, canonical_name):
+ self.config = configparser.ConfigParser()
+
+ filepath = os.path.join(path, self.filename)
+ # `self.config.read()` will quietly swallow OSErrors (which FileNotFoundError is),
+ # so no need to check whether the file exists beforehand.
+ try:
+ self.config.read(filepath)
+ except Exception:
+ errors.report(f"Error reading {self.filename} for extension {canonical_name}.", exc_info=True)
+
+ self.canonical_name = self.config.get("Extension", "Name", fallback=canonical_name)
+ self.canonical_name = canonical_name.lower().strip()
+
+ self.requires = None
+
+ def get_script_requirements(self, field, section, extra_section=None):
+ """reads a list of requirements from the config; field is the name of the field in the ini file,
+ like Requires or Before, and section is the name of the [section] in the ini file; additionally,
+ reads more requirements from [extra_section] if specified."""
+
+ x = self.config.get(section, field, fallback='')
+
+ if extra_section:
+ x = x + ', ' + self.config.get(extra_section, field, fallback='')
+
+ listed_requirements = self.parse_list(x.lower())
+ res = []
+
+ for requirement in listed_requirements:
+ loaded_requirements = (x for x in requirement.split("|") if x in loaded_extensions)
+ relevant_requirement = next(loaded_requirements, requirement)
+ res.append(relevant_requirement)
+
+ return res
+
+ def parse_list(self, text):
+ """converts a line from config ("ext1 ext2, ext3 ") into a python list (["ext1", "ext2", "ext3"])"""
+
+ if not text:
+ return []
+
+ # both "," and " " are accepted as separator
+ return [x for x in re.split(r"[,\s]+", text.strip()) if x]
+
+ def list_callback_order_instructions(self):
+ for section in self.config.sections():
+ if not section.startswith("callbacks/"):
+ continue
+
+ callback_name = section[10:]
+
+ if not callback_name.startswith(self.canonical_name):
+ errors.report(f"Callback order section for extension {self.canonical_name} is referencing the wrong extension: {section}")
+ continue
+
+ before = self.parse_list(self.config.get(section, 'Before', fallback=''))
+ after = self.parse_list(self.config.get(section, 'After', fallback=''))
+
+ yield CallbackOrderInfo(callback_name, before, after)
+
+
+class Extension:
+ lock = threading.Lock()
+ cached_fields = ['remote', 'commit_date', 'branch', 'commit_hash', 'version']
+ metadata: ExtensionMetadata
+
+ def __init__(self, name, path, enabled=True, is_builtin=False, metadata=None):
+ self.name = name
+ self.path = path
+ self.enabled = enabled
+ self.status = ''
+ self.can_update = False
+ self.is_builtin = is_builtin
+ self.commit_hash = ''
+ self.commit_date = None
+ self.version = ''
+ self.branch = None
+ self.remote = None
+ self.have_info_from_repo = False
+ self.metadata = metadata if metadata else ExtensionMetadata(self.path, name.lower())
+ self.canonical_name = metadata.canonical_name
+
+ def to_dict(self):
+ return {x: getattr(self, x) for x in self.cached_fields}
+
+ def from_dict(self, d):
+ for field in self.cached_fields:
+ setattr(self, field, d[field])
+
+ def read_info_from_repo(self):
+ if self.is_builtin or self.have_info_from_repo:
+ return
+
+ def read_from_repo():
+ with self.lock:
+ if self.have_info_from_repo:
+ return
+
+ self.do_read_info_from_repo()
+
+ return self.to_dict()
+
+ try:
+ d = cache.cached_data_for_file('extensions-git', self.name, os.path.join(self.path, ".git"), read_from_repo)
+ self.from_dict(d)
+ except FileNotFoundError:
+ pass
+ self.status = 'unknown' if self.status == '' else self.status
+
+ def do_read_info_from_repo(self):
+ repo = None
+ try:
+ if os.path.exists(os.path.join(self.path, ".git")):
+ repo = Repo(self.path)
+ except Exception:
+ errors.report(f"Error reading github repository info from {self.path}", exc_info=True)
+
+ if repo is None or repo.bare:
+ self.remote = None
+ else:
+ try:
+ self.remote = next(repo.remote().urls, None)
+ commit = repo.head.commit
+ self.commit_date = commit.committed_date
+ if repo.active_branch:
+ self.branch = repo.active_branch.name
+ self.commit_hash = commit.hexsha
+ self.version = self.commit_hash[:8]
+
+ except Exception:
+ errors.report(f"Failed reading extension data from Git repository ({self.name})", exc_info=True)
+ self.remote = None
+
+ self.have_info_from_repo = True
+
+ def list_files(self, subdir, extension):
+ dirpath = os.path.join(self.path, subdir)
+ if not os.path.isdir(dirpath):
+ return []
+
+ res = []
+ for filename in sorted(os.listdir(dirpath)):
+ res.append(scripts.ScriptFile(self.path, filename, os.path.join(dirpath, filename)))
+
+ res = [x for x in res if os.path.splitext(x.path)[1].lower() == extension and os.path.isfile(x.path)]
+
+ return res
+
+ def check_updates(self):
+ repo = Repo(self.path)
+ branch_name = f'{repo.remote().name}/{self.branch}'
+ for fetch in repo.remote().fetch(dry_run=True):
+ if self.branch and fetch.name != branch_name:
+ continue
+ if fetch.flags != fetch.HEAD_UPTODATE:
+ self.can_update = True
+ self.status = "new commits"
+ return
+
+ try:
+ origin = repo.rev_parse(branch_name)
+ if repo.head.commit != origin:
+ self.can_update = True
+ self.status = "behind HEAD"
+ return
+ except Exception:
+ self.can_update = False
+ self.status = "unknown (remote error)"
+ return
+
+ self.can_update = False
+ self.status = "latest"
+
+ def fetch_and_reset_hard(self, commit=None):
+ repo = Repo(self.path)
+ if commit is None:
+ commit = f'{repo.remote().name}/{self.branch}'
+ # Fix: `error: Your local changes to the following files would be overwritten by merge`,
+ # because WSL2 Docker set 755 file permissions instead of 644, this results to the error.
+ repo.git.fetch(all=True)
+ repo.git.reset(commit, hard=True)
+ self.have_info_from_repo = False
+
+
+def list_extensions():
+ extensions.clear()
+ extension_paths.clear()
+ loaded_extensions.clear()
+
+ if shared.cmd_opts.disable_all_extensions:
+ print("*** \"--disable-all-extensions\" arg was used, will not load any extensions ***")
+ elif shared.opts.disable_all_extensions == "all":
+ print("*** \"Disable all extensions\" option was set, will not load any extensions ***")
+ elif shared.cmd_opts.disable_extra_extensions:
+ print("*** \"--disable-extra-extensions\" arg was used, will only load built-in extensions ***")
+ elif shared.opts.disable_all_extensions == "extra":
+ print("*** \"Disable all extensions\" option was set, will only load built-in extensions ***")
+
+
+ # scan through extensions directory and load metadata
+ for dirname in [extensions_builtin_dir, extensions_dir]:
+ if not os.path.isdir(dirname):
+ continue
+
+ for extension_dirname in sorted(os.listdir(dirname)):
+ path = os.path.join(dirname, extension_dirname)
+ if not os.path.isdir(path):
+ continue
+
+ canonical_name = extension_dirname
+ metadata = ExtensionMetadata(path, canonical_name)
+
+ # check for duplicated canonical names
+ already_loaded_extension = loaded_extensions.get(metadata.canonical_name)
+ if already_loaded_extension is not None:
+ errors.report(f'Duplicate canonical name "{canonical_name}" found in extensions "{extension_dirname}" and "{already_loaded_extension.name}". Former will be discarded.', exc_info=False)
+ continue
+
+ is_builtin = dirname == extensions_builtin_dir
+ extension = Extension(name=extension_dirname, path=path, enabled=extension_dirname not in shared.opts.disabled_extensions, is_builtin=is_builtin, metadata=metadata)
+ extensions.append(extension)
+ extension_paths[extension.path] = extension
+ loaded_extensions[canonical_name] = extension
+
+ for extension in extensions:
+ extension.metadata.requires = extension.metadata.get_script_requirements("Requires", "Extension")
+
+ # check for requirements
+ for extension in extensions:
+ if not extension.enabled:
+ continue
+
+ for req in extension.metadata.requires:
+ required_extension = loaded_extensions.get(req)
+ if required_extension is None:
+ errors.report(f'Extension "{extension.name}" requires "{req}" which is not installed.', exc_info=False)
+ continue
+
+ if not required_extension.enabled:
+ errors.report(f'Extension "{extension.name}" requires "{required_extension.name}" which is disabled.', exc_info=False)
+ continue
+
+
+def find_extension(filename):
+ parentdir = os.path.dirname(os.path.realpath(filename))
+
+ while parentdir != filename:
+ extension = extension_paths.get(parentdir)
+ if extension is not None:
+ return extension
+
+ filename = parentdir
+ parentdir = os.path.dirname(filename)
+
+ return None
+
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/extensions.py |
Create docstrings for each class method | from __future__ import annotations
import datetime
import functools
import pytz
import io
import math
import os
from collections import namedtuple
import re
import numpy as np
import piexif
import piexif.helper
from PIL import Image, ImageFont, ImageDraw, ImageColor, PngImagePlugin, ImageOps
# pillow_avif needs to be imported somewhere in code for it to work
import pillow_avif # noqa: F401
import string
import json
import hashlib
from modules import sd_samplers, shared, script_callbacks, errors
from modules.paths_internal import roboto_ttf_file
from modules.shared import opts
LANCZOS = (Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS)
def get_font(fontsize: int):
try:
return ImageFont.truetype(opts.font or roboto_ttf_file, fontsize)
except Exception:
return ImageFont.truetype(roboto_ttf_file, fontsize)
def image_grid(imgs, batch_size=1, rows=None):
if rows is None:
if opts.n_rows > 0:
rows = opts.n_rows
elif opts.n_rows == 0:
rows = batch_size
elif opts.grid_prevent_empty_spots:
rows = math.floor(math.sqrt(len(imgs)))
while len(imgs) % rows != 0:
rows -= 1
else:
rows = math.sqrt(len(imgs))
rows = round(rows)
if rows > len(imgs):
rows = len(imgs)
cols = math.ceil(len(imgs) / rows)
params = script_callbacks.ImageGridLoopParams(imgs, cols, rows)
script_callbacks.image_grid_callback(params)
w, h = map(max, zip(*(img.size for img in imgs)))
grid_background_color = ImageColor.getcolor(opts.grid_background_color, 'RGB')
grid = Image.new('RGB', size=(params.cols * w, params.rows * h), color=grid_background_color)
for i, img in enumerate(params.imgs):
img_w, img_h = img.size
w_offset, h_offset = 0 if img_w == w else (w - img_w) // 2, 0 if img_h == h else (h - img_h) // 2
grid.paste(img, box=(i % params.cols * w + w_offset, i // params.cols * h + h_offset))
return grid
class Grid(namedtuple("_Grid", ["tiles", "tile_w", "tile_h", "image_w", "image_h", "overlap"])):
@property
def tile_count(self) -> int:
return sum(len(row[2]) for row in self.tiles)
def split_grid(image: Image.Image, tile_w: int = 512, tile_h: int = 512, overlap: int = 64) -> Grid:
w, h = image.size
non_overlap_width = tile_w - overlap
non_overlap_height = tile_h - overlap
cols = math.ceil((w - overlap) / non_overlap_width)
rows = math.ceil((h - overlap) / non_overlap_height)
dx = (w - tile_w) / (cols - 1) if cols > 1 else 0
dy = (h - tile_h) / (rows - 1) if rows > 1 else 0
grid = Grid([], tile_w, tile_h, w, h, overlap)
for row in range(rows):
row_images = []
y = int(row * dy)
if y + tile_h >= h:
y = h - tile_h
for col in range(cols):
x = int(col * dx)
if x + tile_w >= w:
x = w - tile_w
tile = image.crop((x, y, x + tile_w, y + tile_h))
row_images.append([x, tile_w, tile])
grid.tiles.append([y, tile_h, row_images])
return grid
def combine_grid(grid):
def make_mask_image(r):
r = r * 255 / grid.overlap
r = r.astype(np.uint8)
return Image.fromarray(r, 'L')
mask_w = make_mask_image(np.arange(grid.overlap, dtype=np.float32).reshape((1, grid.overlap)).repeat(grid.tile_h, axis=0))
mask_h = make_mask_image(np.arange(grid.overlap, dtype=np.float32).reshape((grid.overlap, 1)).repeat(grid.image_w, axis=1))
combined_image = Image.new("RGB", (grid.image_w, grid.image_h))
for y, h, row in grid.tiles:
combined_row = Image.new("RGB", (grid.image_w, h))
for x, w, tile in row:
if x == 0:
combined_row.paste(tile, (0, 0))
continue
combined_row.paste(tile.crop((0, 0, grid.overlap, h)), (x, 0), mask=mask_w)
combined_row.paste(tile.crop((grid.overlap, 0, w, h)), (x + grid.overlap, 0))
if y == 0:
combined_image.paste(combined_row, (0, 0))
continue
combined_image.paste(combined_row.crop((0, 0, combined_row.width, grid.overlap)), (0, y), mask=mask_h)
combined_image.paste(combined_row.crop((0, grid.overlap, combined_row.width, h)), (0, y + grid.overlap))
return combined_image
class GridAnnotation:
def __init__(self, text='', is_active=True):
self.text = text
self.is_active = is_active
self.size = None
def draw_grid_annotations(im, width, height, hor_texts, ver_texts, margin=0):
color_active = ImageColor.getcolor(opts.grid_text_active_color, 'RGB')
color_inactive = ImageColor.getcolor(opts.grid_text_inactive_color, 'RGB')
color_background = ImageColor.getcolor(opts.grid_background_color, 'RGB')
def wrap(drawing, text, font, line_length):
lines = ['']
for word in text.split():
line = f'{lines[-1]} {word}'.strip()
if drawing.textlength(line, font=font) <= line_length:
lines[-1] = line
else:
lines.append(word)
return lines
def draw_texts(drawing, draw_x, draw_y, lines, initial_fnt, initial_fontsize):
for line in lines:
fnt = initial_fnt
fontsize = initial_fontsize
while drawing.multiline_textsize(line.text, font=fnt)[0] > line.allowed_width and fontsize > 0:
fontsize -= 1
fnt = get_font(fontsize)
drawing.multiline_text((draw_x, draw_y + line.size[1] / 2), line.text, font=fnt, fill=color_active if line.is_active else color_inactive, anchor="mm", align="center")
if not line.is_active:
drawing.line((draw_x - line.size[0] // 2, draw_y + line.size[1] // 2, draw_x + line.size[0] // 2, draw_y + line.size[1] // 2), fill=color_inactive, width=4)
draw_y += line.size[1] + line_spacing
fontsize = (width + height) // 25
line_spacing = fontsize // 2
fnt = get_font(fontsize)
pad_left = 0 if sum([sum([len(line.text) for line in lines]) for lines in ver_texts]) == 0 else width * 3 // 4
cols = im.width // width
rows = im.height // height
assert cols == len(hor_texts), f'bad number of horizontal texts: {len(hor_texts)}; must be {cols}'
assert rows == len(ver_texts), f'bad number of vertical texts: {len(ver_texts)}; must be {rows}'
calc_img = Image.new("RGB", (1, 1), color_background)
calc_d = ImageDraw.Draw(calc_img)
for texts, allowed_width in zip(hor_texts + ver_texts, [width] * len(hor_texts) + [pad_left] * len(ver_texts)):
items = [] + texts
texts.clear()
for line in items:
wrapped = wrap(calc_d, line.text, fnt, allowed_width)
texts += [GridAnnotation(x, line.is_active) for x in wrapped]
for line in texts:
bbox = calc_d.multiline_textbbox((0, 0), line.text, font=fnt)
line.size = (bbox[2] - bbox[0], bbox[3] - bbox[1])
line.allowed_width = allowed_width
hor_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing for lines in hor_texts]
ver_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing * len(lines) for lines in ver_texts]
pad_top = 0 if sum(hor_text_heights) == 0 else max(hor_text_heights) + line_spacing * 2
result = Image.new("RGB", (im.width + pad_left + margin * (cols-1), im.height + pad_top + margin * (rows-1)), color_background)
for row in range(rows):
for col in range(cols):
cell = im.crop((width * col, height * row, width * (col+1), height * (row+1)))
result.paste(cell, (pad_left + (width + margin) * col, pad_top + (height + margin) * row))
d = ImageDraw.Draw(result)
for col in range(cols):
x = pad_left + (width + margin) * col + width / 2
y = pad_top / 2 - hor_text_heights[col] / 2
draw_texts(d, x, y, hor_texts[col], fnt, fontsize)
for row in range(rows):
x = pad_left / 2
y = pad_top + (height + margin) * row + height / 2 - ver_text_heights[row] / 2
draw_texts(d, x, y, ver_texts[row], fnt, fontsize)
return result
def draw_prompt_matrix(im, width, height, all_prompts, margin=0):
prompts = all_prompts[1:]
boundary = math.ceil(len(prompts) / 2)
prompts_horiz = prompts[:boundary]
prompts_vert = prompts[boundary:]
hor_texts = [[GridAnnotation(x, is_active=pos & (1 << i) != 0) for i, x in enumerate(prompts_horiz)] for pos in range(1 << len(prompts_horiz))]
ver_texts = [[GridAnnotation(x, is_active=pos & (1 << i) != 0) for i, x in enumerate(prompts_vert)] for pos in range(1 << len(prompts_vert))]
return draw_grid_annotations(im, width, height, hor_texts, ver_texts, margin)
def resize_image(resize_mode, im, width, height, upscaler_name=None):
upscaler_name = upscaler_name or opts.upscaler_for_img2img
def resize(im, w, h):
if upscaler_name is None or upscaler_name == "None" or im.mode == 'L':
return im.resize((w, h), resample=LANCZOS)
scale = max(w / im.width, h / im.height)
if scale > 1.0:
upscalers = [x for x in shared.sd_upscalers if x.name == upscaler_name]
if len(upscalers) == 0:
upscaler = shared.sd_upscalers[0]
print(f"could not find upscaler named {upscaler_name or '<empty string>'}, using {upscaler.name} as a fallback")
else:
upscaler = upscalers[0]
im = upscaler.scaler.upscale(im, scale, upscaler.data_path)
if im.width != w or im.height != h:
im = im.resize((w, h), resample=LANCZOS)
return im
if resize_mode == 0:
res = resize(im, width, height)
elif resize_mode == 1:
ratio = width / height
src_ratio = im.width / im.height
src_w = width if ratio > src_ratio else im.width * height // im.height
src_h = height if ratio <= src_ratio else im.height * width // im.width
resized = resize(im, src_w, src_h)
res = Image.new("RGB", (width, height))
res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
else:
ratio = width / height
src_ratio = im.width / im.height
src_w = width if ratio < src_ratio else im.width * height // im.height
src_h = height if ratio >= src_ratio else im.height * width // im.width
resized = resize(im, src_w, src_h)
res = Image.new("RGB", (width, height))
res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
if ratio < src_ratio:
fill_height = height // 2 - src_h // 2
if fill_height > 0:
res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
res.paste(resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)), box=(0, fill_height + src_h))
elif ratio > src_ratio:
fill_width = width // 2 - src_w // 2
if fill_width > 0:
res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0))
res.paste(resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)), box=(fill_width + src_w, 0))
return res
if not shared.cmd_opts.unix_filenames_sanitization:
invalid_filename_chars = '#<>:"/\\|?*\n\r\t'
else:
invalid_filename_chars = '/'
invalid_filename_prefix = ' '
invalid_filename_postfix = ' .'
re_nonletters = re.compile(r'[\s' + string.punctuation + ']+')
re_pattern = re.compile(r"(.*?)(?:\[([^\[\]]+)\]|$)")
re_pattern_arg = re.compile(r"(.*)<([^>]*)>$")
max_filename_part_length = shared.cmd_opts.filenames_max_length
NOTHING_AND_SKIP_PREVIOUS_TEXT = object()
def sanitize_filename_part(text, replace_spaces=True):
if text is None:
return None
if replace_spaces:
text = text.replace(' ', '_')
text = text.translate({ord(x): '_' for x in invalid_filename_chars})
text = text.lstrip(invalid_filename_prefix)[:max_filename_part_length]
text = text.rstrip(invalid_filename_postfix)
return text
@functools.cache
def get_scheduler_str(sampler_name, scheduler_name):
if scheduler_name == 'Automatic':
config = sd_samplers.find_sampler_config(sampler_name)
scheduler_name = config.options.get('scheduler', 'Automatic')
return scheduler_name.capitalize()
@functools.cache
def get_sampler_scheduler_str(sampler_name, scheduler_name):
return f'{sampler_name} {get_scheduler_str(sampler_name, scheduler_name)}'
def get_sampler_scheduler(p, sampler):
if hasattr(p, 'scheduler') and hasattr(p, 'sampler_name'):
if sampler:
sampler_scheduler = get_sampler_scheduler_str(p.sampler_name, p.scheduler)
else:
sampler_scheduler = get_scheduler_str(p.sampler_name, p.scheduler)
return sanitize_filename_part(sampler_scheduler, replace_spaces=False)
return NOTHING_AND_SKIP_PREVIOUS_TEXT
class FilenameGenerator:
replacements = {
'basename': lambda self: self.basename or 'img',
'seed': lambda self: self.seed if self.seed is not None else '',
'seed_first': lambda self: self.seed if self.p.batch_size == 1 else self.p.all_seeds[0],
'seed_last': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if self.p.batch_size == 1 else self.p.all_seeds[-1],
'steps': lambda self: self.p and self.p.steps,
'cfg': lambda self: self.p and self.p.cfg_scale,
'width': lambda self: self.image.width,
'height': lambda self: self.image.height,
'styles': lambda self: self.p and sanitize_filename_part(", ".join([style for style in self.p.styles if not style == "None"]) or "None", replace_spaces=False),
'sampler': lambda self: self.p and sanitize_filename_part(self.p.sampler_name, replace_spaces=False),
'sampler_scheduler': lambda self: self.p and get_sampler_scheduler(self.p, True),
'scheduler': lambda self: self.p and get_sampler_scheduler(self.p, False),
'model_hash': lambda self: getattr(self.p, "sd_model_hash", shared.sd_model.sd_model_hash),
'model_name': lambda self: sanitize_filename_part(shared.sd_model.sd_checkpoint_info.name_for_extra, replace_spaces=False),
'date': lambda self: datetime.datetime.now().strftime('%Y-%m-%d'),
'datetime': lambda self, *args: self.datetime(*args), # accepts formats: [datetime], [datetime<Format>], [datetime<Format><Time Zone>]
'job_timestamp': lambda self: getattr(self.p, "job_timestamp", shared.state.job_timestamp),
'prompt_hash': lambda self, *args: self.string_hash(self.prompt, *args),
'negative_prompt_hash': lambda self, *args: self.string_hash(self.p.negative_prompt, *args),
'full_prompt_hash': lambda self, *args: self.string_hash(f"{self.p.prompt} {self.p.negative_prompt}", *args), # a space in between to create a unique string
'prompt': lambda self: sanitize_filename_part(self.prompt),
'prompt_no_styles': lambda self: self.prompt_no_style(),
'prompt_spaces': lambda self: sanitize_filename_part(self.prompt, replace_spaces=False),
'prompt_words': lambda self: self.prompt_words(),
'batch_number': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if self.p.batch_size == 1 or self.zip else self.p.batch_index + 1,
'batch_size': lambda self: self.p.batch_size,
'generation_number': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if (self.p.n_iter == 1 and self.p.batch_size == 1) or self.zip else self.p.iteration * self.p.batch_size + self.p.batch_index + 1,
'hasprompt': lambda self, *args: self.hasprompt(*args), # accepts formats:[hasprompt<prompt1|default><prompt2>..]
'clip_skip': lambda self: opts.data["CLIP_stop_at_last_layers"],
'denoising': lambda self: self.p.denoising_strength if self.p and self.p.denoising_strength else NOTHING_AND_SKIP_PREVIOUS_TEXT,
'user': lambda self: self.p.user,
'vae_filename': lambda self: self.get_vae_filename(),
'none': lambda self: '', # Overrides the default, so you can get just the sequence number
'image_hash': lambda self, *args: self.image_hash(*args) # accepts formats: [image_hash<length>] default full hash
}
default_time_format = '%Y%m%d%H%M%S'
def __init__(self, p, seed, prompt, image, zip=False, basename=""):
self.p = p
self.seed = seed
self.prompt = prompt
self.image = image
self.zip = zip
self.basename = basename
def get_vae_filename(self):
import modules.sd_vae as sd_vae
if sd_vae.loaded_vae_file is None:
return "NoneType"
file_name = os.path.basename(sd_vae.loaded_vae_file)
split_file_name = file_name.split('.')
if len(split_file_name) > 1 and split_file_name[0] == '':
return split_file_name[1] # if the first character of the filename is "." then [1] is obtained.
else:
return split_file_name[0]
def hasprompt(self, *args):
lower = self.prompt.lower()
if self.p is None or self.prompt is None:
return None
outres = ""
for arg in args:
if arg != "":
division = arg.split("|")
expected = division[0].lower()
default = division[1] if len(division) > 1 else ""
if lower.find(expected) >= 0:
outres = f'{outres}{expected}'
else:
outres = outres if default == "" else f'{outres}{default}'
return sanitize_filename_part(outres)
def prompt_no_style(self):
if self.p is None or self.prompt is None:
return None
prompt_no_style = self.prompt
for style in shared.prompt_styles.get_style_prompts(self.p.styles):
if style:
for part in style.split("{prompt}"):
prompt_no_style = prompt_no_style.replace(part, "").replace(", ,", ",").strip().strip(',')
prompt_no_style = prompt_no_style.replace(style, "").strip().strip(',').strip()
return sanitize_filename_part(prompt_no_style, replace_spaces=False)
def prompt_words(self):
words = [x for x in re_nonletters.split(self.prompt or "") if x]
if len(words) == 0:
words = ["empty"]
return sanitize_filename_part(" ".join(words[0:opts.directories_max_prompt_words]), replace_spaces=False)
def datetime(self, *args):
time_datetime = datetime.datetime.now()
time_format = args[0] if (args and args[0] != "") else self.default_time_format
try:
time_zone = pytz.timezone(args[1]) if len(args) > 1 else None
except pytz.exceptions.UnknownTimeZoneError:
time_zone = None
time_zone_time = time_datetime.astimezone(time_zone)
try:
formatted_time = time_zone_time.strftime(time_format)
except (ValueError, TypeError):
formatted_time = time_zone_time.strftime(self.default_time_format)
return sanitize_filename_part(formatted_time, replace_spaces=False)
def image_hash(self, *args):
length = int(args[0]) if (args and args[0] != "") else None
return hashlib.sha256(self.image.tobytes()).hexdigest()[0:length]
def string_hash(self, text, *args):
length = int(args[0]) if (args and args[0] != "") else 8
return hashlib.sha256(text.encode()).hexdigest()[0:length]
def apply(self, x):
res = ''
for m in re_pattern.finditer(x):
text, pattern = m.groups()
if pattern is None:
res += text
continue
pattern_args = []
while True:
m = re_pattern_arg.match(pattern)
if m is None:
break
pattern, arg = m.groups()
pattern_args.insert(0, arg)
fun = self.replacements.get(pattern.lower())
if fun is not None:
try:
replacement = fun(self, *pattern_args)
except Exception:
replacement = None
errors.report(f"Error adding [{pattern}] to filename", exc_info=True)
if replacement == NOTHING_AND_SKIP_PREVIOUS_TEXT:
continue
elif replacement is not None:
res += text + str(replacement)
continue
res += f'{text}[{pattern}]'
return res
def get_next_sequence_number(path, basename):
result = -1
if basename != '':
basename = f"{basename}-"
prefix_length = len(basename)
for p in os.listdir(path):
if p.startswith(basename):
parts = os.path.splitext(p[prefix_length:])[0].split('-') # splits the filename (removing the basename first if one is defined, so the sequence number is always the first element)
try:
result = max(int(parts[0]), result)
except ValueError:
pass
return result + 1
def save_image_with_geninfo(image, geninfo, filename, extension=None, existing_pnginfo=None, pnginfo_section_name='parameters'):
if extension is None:
extension = os.path.splitext(filename)[1]
image_format = Image.registered_extensions()[extension]
if extension.lower() == '.png':
existing_pnginfo = existing_pnginfo or {}
if opts.enable_pnginfo:
existing_pnginfo[pnginfo_section_name] = geninfo
if opts.enable_pnginfo:
pnginfo_data = PngImagePlugin.PngInfo()
for k, v in (existing_pnginfo or {}).items():
pnginfo_data.add_text(k, str(v))
else:
pnginfo_data = None
image.save(filename, format=image_format, quality=opts.jpeg_quality, pnginfo=pnginfo_data)
elif extension.lower() in (".jpg", ".jpeg", ".webp"):
if image.mode == 'RGBA':
image = image.convert("RGB")
elif image.mode == 'I;16':
image = image.point(lambda p: p * 0.0038910505836576).convert("RGB" if extension.lower() == ".webp" else "L")
image.save(filename, format=image_format, quality=opts.jpeg_quality, lossless=opts.webp_lossless)
if opts.enable_pnginfo and geninfo is not None:
exif_bytes = piexif.dump({
"Exif": {
piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(geninfo or "", encoding="unicode")
},
})
piexif.insert(exif_bytes, filename)
elif extension.lower() == '.avif':
if opts.enable_pnginfo and geninfo is not None:
exif_bytes = piexif.dump({
"Exif": {
piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(geninfo or "", encoding="unicode")
},
})
else:
exif_bytes = None
image.save(filename,format=image_format, quality=opts.jpeg_quality, exif=exif_bytes)
elif extension.lower() == ".gif":
image.save(filename, format=image_format, comment=geninfo)
else:
image.save(filename, format=image_format, quality=opts.jpeg_quality)
def save_image(image, path, basename, seed=None, prompt=None, extension='png', info=None, short_filename=False, no_prompt=False, grid=False, pnginfo_section_name='parameters', p=None, existing_info=None, forced_filename=None, suffix="", save_to_dirs=None):
namegen = FilenameGenerator(p, seed, prompt, image, basename=basename)
# WebP and JPG formats have maximum dimension limits of 16383 and 65535 respectively. switch to PNG which has a much higher limit
if (image.height > 65535 or image.width > 65535) and extension.lower() in ("jpg", "jpeg") or (image.height > 16383 or image.width > 16383) and extension.lower() == "webp":
print('Image dimensions too large; saving as PNG')
extension = "png"
if save_to_dirs is None:
save_to_dirs = (grid and opts.grid_save_to_dirs) or (not grid and opts.save_to_dirs and not no_prompt)
if save_to_dirs:
dirname = namegen.apply(opts.directories_filename_pattern or "[prompt_words]").lstrip(' ').rstrip('\\ /')
path = os.path.join(path, dirname)
os.makedirs(path, exist_ok=True)
if forced_filename is None:
if short_filename or seed is None:
file_decoration = ""
elif opts.save_to_dirs:
file_decoration = opts.samples_filename_pattern or "[seed]"
else:
file_decoration = opts.samples_filename_pattern or "[seed]-[prompt_spaces]"
file_decoration = namegen.apply(file_decoration) + suffix
add_number = opts.save_images_add_number or file_decoration == ''
if file_decoration != "" and add_number:
file_decoration = f"-{file_decoration}"
if add_number:
basecount = get_next_sequence_number(path, basename)
fullfn = None
for i in range(500):
fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}"
fullfn = os.path.join(path, f"{fn}{file_decoration}.{extension}")
if not os.path.exists(fullfn):
break
else:
fullfn = os.path.join(path, f"{file_decoration}.{extension}")
else:
fullfn = os.path.join(path, f"{forced_filename}.{extension}")
pnginfo = existing_info or {}
if info is not None:
pnginfo[pnginfo_section_name] = info
params = script_callbacks.ImageSaveParams(image, p, fullfn, pnginfo)
script_callbacks.before_image_saved_callback(params)
image = params.image
fullfn = params.filename
info = params.pnginfo.get(pnginfo_section_name, None)
def _atomically_save_image(image_to_save, filename_without_extension, extension):
temp_file_path = f"{filename_without_extension}.tmp"
save_image_with_geninfo(image_to_save, info, temp_file_path, extension, existing_pnginfo=params.pnginfo, pnginfo_section_name=pnginfo_section_name)
filename = filename_without_extension + extension
if shared.opts.save_images_replace_action != "Replace":
n = 0
while os.path.exists(filename):
n += 1
filename = f"{filename_without_extension}-{n}{extension}"
os.replace(temp_file_path, filename)
fullfn_without_extension, extension = os.path.splitext(params.filename)
if hasattr(os, 'statvfs'):
max_name_len = os.statvfs(path).f_namemax
fullfn_without_extension = fullfn_without_extension[:max_name_len - max(4, len(extension))]
params.filename = fullfn_without_extension + extension
fullfn = params.filename
_atomically_save_image(image, fullfn_without_extension, extension)
image.already_saved_as = fullfn
oversize = image.width > opts.target_side_length or image.height > opts.target_side_length
if opts.export_for_4chan and (oversize or os.stat(fullfn).st_size > opts.img_downscale_threshold * 1024 * 1024):
ratio = image.width / image.height
resize_to = None
if oversize and ratio > 1:
resize_to = round(opts.target_side_length), round(image.height * opts.target_side_length / image.width)
elif oversize:
resize_to = round(image.width * opts.target_side_length / image.height), round(opts.target_side_length)
if resize_to is not None:
try:
# Resizing image with LANCZOS could throw an exception if e.g. image mode is I;16
image = image.resize(resize_to, LANCZOS)
except Exception:
image = image.resize(resize_to)
try:
_atomically_save_image(image, fullfn_without_extension, ".jpg")
except Exception as e:
errors.display(e, "saving image as downscaled JPG")
if opts.save_txt and info is not None:
txt_fullfn = f"{fullfn_without_extension}.txt"
with open(txt_fullfn, "w", encoding="utf8") as file:
file.write(f"{info}\n")
else:
txt_fullfn = None
script_callbacks.image_saved_callback(params)
return fullfn, txt_fullfn
IGNORED_INFO_KEYS = {
'jfif', 'jfif_version', 'jfif_unit', 'jfif_density', 'dpi', 'exif',
'loop', 'background', 'timestamp', 'duration', 'progressive', 'progression',
'icc_profile', 'chromaticity', 'photoshop',
}
def read_info_from_image(image: Image.Image) -> tuple[str | None, dict]:
items = (image.info or {}).copy()
geninfo = items.pop('parameters', None)
if "exif" in items:
exif_data = items["exif"]
try:
exif = piexif.load(exif_data)
except OSError:
# memory / exif was not valid so piexif tried to read from a file
exif = None
exif_comment = (exif or {}).get("Exif", {}).get(piexif.ExifIFD.UserComment, b'')
try:
exif_comment = piexif.helper.UserComment.load(exif_comment)
except ValueError:
exif_comment = exif_comment.decode('utf8', errors="ignore")
if exif_comment:
geninfo = exif_comment
elif "comment" in items: # for gif
if isinstance(items["comment"], bytes):
geninfo = items["comment"].decode('utf8', errors="ignore")
else:
geninfo = items["comment"]
for field in IGNORED_INFO_KEYS:
items.pop(field, None)
if items.get("Software", None) == "NovelAI":
try:
json_info = json.loads(items["Comment"])
sampler = sd_samplers.samplers_map.get(json_info["sampler"], "Euler a")
geninfo = f"""{items["Description"]}
Negative prompt: {json_info["uc"]}
Steps: {json_info["steps"]}, Sampler: {sampler}, CFG scale: {json_info["scale"]}, Seed: {json_info["seed"]}, Size: {image.width}x{image.height}, Clip skip: 2, ENSD: 31337"""
except Exception:
errors.report("Error parsing NovelAI image generation parameters", exc_info=True)
return geninfo, items
def image_data(data):
import gradio as gr
try:
image = read(io.BytesIO(data))
textinfo, _ = read_info_from_image(image)
return textinfo, None
except Exception:
pass
try:
text = data.decode('utf8')
assert len(text) < 10000
return text, None
except Exception:
pass
return gr.update(), None
def flatten(img, bgcolor):
if img.mode == "RGBA":
background = Image.new('RGBA', img.size, bgcolor)
background.paste(img, mask=img)
img = background
return img.convert('RGB')
def read(fp, **kwargs):
image = Image.open(fp, **kwargs)
image = fix_image(image)
return image
def fix_image(image: Image.Image):
if image is None:
return None
try:
image = ImageOps.exif_transpose(image)
image = fix_png_transparency(image)
except Exception:
pass
return image
def fix_png_transparency(image: Image.Image):
if image.mode not in ("RGB", "P") or not isinstance(image.info.get("transparency"), bytes):
return image
image = image.convert("RGBA")
return image | --- +++ @@ -1,811 +1,877 @@-from __future__ import annotations
-
-import datetime
-import functools
-import pytz
-import io
-import math
-import os
-from collections import namedtuple
-import re
-
-import numpy as np
-import piexif
-import piexif.helper
-from PIL import Image, ImageFont, ImageDraw, ImageColor, PngImagePlugin, ImageOps
-# pillow_avif needs to be imported somewhere in code for it to work
-import pillow_avif # noqa: F401
-import string
-import json
-import hashlib
-
-from modules import sd_samplers, shared, script_callbacks, errors
-from modules.paths_internal import roboto_ttf_file
-from modules.shared import opts
-
-LANCZOS = (Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS)
-
-
-def get_font(fontsize: int):
- try:
- return ImageFont.truetype(opts.font or roboto_ttf_file, fontsize)
- except Exception:
- return ImageFont.truetype(roboto_ttf_file, fontsize)
-
-
-def image_grid(imgs, batch_size=1, rows=None):
- if rows is None:
- if opts.n_rows > 0:
- rows = opts.n_rows
- elif opts.n_rows == 0:
- rows = batch_size
- elif opts.grid_prevent_empty_spots:
- rows = math.floor(math.sqrt(len(imgs)))
- while len(imgs) % rows != 0:
- rows -= 1
- else:
- rows = math.sqrt(len(imgs))
- rows = round(rows)
- if rows > len(imgs):
- rows = len(imgs)
-
- cols = math.ceil(len(imgs) / rows)
-
- params = script_callbacks.ImageGridLoopParams(imgs, cols, rows)
- script_callbacks.image_grid_callback(params)
-
- w, h = map(max, zip(*(img.size for img in imgs)))
- grid_background_color = ImageColor.getcolor(opts.grid_background_color, 'RGB')
- grid = Image.new('RGB', size=(params.cols * w, params.rows * h), color=grid_background_color)
-
- for i, img in enumerate(params.imgs):
- img_w, img_h = img.size
- w_offset, h_offset = 0 if img_w == w else (w - img_w) // 2, 0 if img_h == h else (h - img_h) // 2
- grid.paste(img, box=(i % params.cols * w + w_offset, i // params.cols * h + h_offset))
-
- return grid
-
-
-class Grid(namedtuple("_Grid", ["tiles", "tile_w", "tile_h", "image_w", "image_h", "overlap"])):
- @property
- def tile_count(self) -> int:
- return sum(len(row[2]) for row in self.tiles)
-
-
-def split_grid(image: Image.Image, tile_w: int = 512, tile_h: int = 512, overlap: int = 64) -> Grid:
- w, h = image.size
-
- non_overlap_width = tile_w - overlap
- non_overlap_height = tile_h - overlap
-
- cols = math.ceil((w - overlap) / non_overlap_width)
- rows = math.ceil((h - overlap) / non_overlap_height)
-
- dx = (w - tile_w) / (cols - 1) if cols > 1 else 0
- dy = (h - tile_h) / (rows - 1) if rows > 1 else 0
-
- grid = Grid([], tile_w, tile_h, w, h, overlap)
- for row in range(rows):
- row_images = []
-
- y = int(row * dy)
-
- if y + tile_h >= h:
- y = h - tile_h
-
- for col in range(cols):
- x = int(col * dx)
-
- if x + tile_w >= w:
- x = w - tile_w
-
- tile = image.crop((x, y, x + tile_w, y + tile_h))
-
- row_images.append([x, tile_w, tile])
-
- grid.tiles.append([y, tile_h, row_images])
-
- return grid
-
-
-def combine_grid(grid):
- def make_mask_image(r):
- r = r * 255 / grid.overlap
- r = r.astype(np.uint8)
- return Image.fromarray(r, 'L')
-
- mask_w = make_mask_image(np.arange(grid.overlap, dtype=np.float32).reshape((1, grid.overlap)).repeat(grid.tile_h, axis=0))
- mask_h = make_mask_image(np.arange(grid.overlap, dtype=np.float32).reshape((grid.overlap, 1)).repeat(grid.image_w, axis=1))
-
- combined_image = Image.new("RGB", (grid.image_w, grid.image_h))
- for y, h, row in grid.tiles:
- combined_row = Image.new("RGB", (grid.image_w, h))
- for x, w, tile in row:
- if x == 0:
- combined_row.paste(tile, (0, 0))
- continue
-
- combined_row.paste(tile.crop((0, 0, grid.overlap, h)), (x, 0), mask=mask_w)
- combined_row.paste(tile.crop((grid.overlap, 0, w, h)), (x + grid.overlap, 0))
-
- if y == 0:
- combined_image.paste(combined_row, (0, 0))
- continue
-
- combined_image.paste(combined_row.crop((0, 0, combined_row.width, grid.overlap)), (0, y), mask=mask_h)
- combined_image.paste(combined_row.crop((0, grid.overlap, combined_row.width, h)), (0, y + grid.overlap))
-
- return combined_image
-
-
-class GridAnnotation:
- def __init__(self, text='', is_active=True):
- self.text = text
- self.is_active = is_active
- self.size = None
-
-
-def draw_grid_annotations(im, width, height, hor_texts, ver_texts, margin=0):
-
- color_active = ImageColor.getcolor(opts.grid_text_active_color, 'RGB')
- color_inactive = ImageColor.getcolor(opts.grid_text_inactive_color, 'RGB')
- color_background = ImageColor.getcolor(opts.grid_background_color, 'RGB')
-
- def wrap(drawing, text, font, line_length):
- lines = ['']
- for word in text.split():
- line = f'{lines[-1]} {word}'.strip()
- if drawing.textlength(line, font=font) <= line_length:
- lines[-1] = line
- else:
- lines.append(word)
- return lines
-
- def draw_texts(drawing, draw_x, draw_y, lines, initial_fnt, initial_fontsize):
- for line in lines:
- fnt = initial_fnt
- fontsize = initial_fontsize
- while drawing.multiline_textsize(line.text, font=fnt)[0] > line.allowed_width and fontsize > 0:
- fontsize -= 1
- fnt = get_font(fontsize)
- drawing.multiline_text((draw_x, draw_y + line.size[1] / 2), line.text, font=fnt, fill=color_active if line.is_active else color_inactive, anchor="mm", align="center")
-
- if not line.is_active:
- drawing.line((draw_x - line.size[0] // 2, draw_y + line.size[1] // 2, draw_x + line.size[0] // 2, draw_y + line.size[1] // 2), fill=color_inactive, width=4)
-
- draw_y += line.size[1] + line_spacing
-
- fontsize = (width + height) // 25
- line_spacing = fontsize // 2
-
- fnt = get_font(fontsize)
-
- pad_left = 0 if sum([sum([len(line.text) for line in lines]) for lines in ver_texts]) == 0 else width * 3 // 4
-
- cols = im.width // width
- rows = im.height // height
-
- assert cols == len(hor_texts), f'bad number of horizontal texts: {len(hor_texts)}; must be {cols}'
- assert rows == len(ver_texts), f'bad number of vertical texts: {len(ver_texts)}; must be {rows}'
-
- calc_img = Image.new("RGB", (1, 1), color_background)
- calc_d = ImageDraw.Draw(calc_img)
-
- for texts, allowed_width in zip(hor_texts + ver_texts, [width] * len(hor_texts) + [pad_left] * len(ver_texts)):
- items = [] + texts
- texts.clear()
-
- for line in items:
- wrapped = wrap(calc_d, line.text, fnt, allowed_width)
- texts += [GridAnnotation(x, line.is_active) for x in wrapped]
-
- for line in texts:
- bbox = calc_d.multiline_textbbox((0, 0), line.text, font=fnt)
- line.size = (bbox[2] - bbox[0], bbox[3] - bbox[1])
- line.allowed_width = allowed_width
-
- hor_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing for lines in hor_texts]
- ver_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing * len(lines) for lines in ver_texts]
-
- pad_top = 0 if sum(hor_text_heights) == 0 else max(hor_text_heights) + line_spacing * 2
-
- result = Image.new("RGB", (im.width + pad_left + margin * (cols-1), im.height + pad_top + margin * (rows-1)), color_background)
-
- for row in range(rows):
- for col in range(cols):
- cell = im.crop((width * col, height * row, width * (col+1), height * (row+1)))
- result.paste(cell, (pad_left + (width + margin) * col, pad_top + (height + margin) * row))
-
- d = ImageDraw.Draw(result)
-
- for col in range(cols):
- x = pad_left + (width + margin) * col + width / 2
- y = pad_top / 2 - hor_text_heights[col] / 2
-
- draw_texts(d, x, y, hor_texts[col], fnt, fontsize)
-
- for row in range(rows):
- x = pad_left / 2
- y = pad_top + (height + margin) * row + height / 2 - ver_text_heights[row] / 2
-
- draw_texts(d, x, y, ver_texts[row], fnt, fontsize)
-
- return result
-
-
-def draw_prompt_matrix(im, width, height, all_prompts, margin=0):
- prompts = all_prompts[1:]
- boundary = math.ceil(len(prompts) / 2)
-
- prompts_horiz = prompts[:boundary]
- prompts_vert = prompts[boundary:]
-
- hor_texts = [[GridAnnotation(x, is_active=pos & (1 << i) != 0) for i, x in enumerate(prompts_horiz)] for pos in range(1 << len(prompts_horiz))]
- ver_texts = [[GridAnnotation(x, is_active=pos & (1 << i) != 0) for i, x in enumerate(prompts_vert)] for pos in range(1 << len(prompts_vert))]
-
- return draw_grid_annotations(im, width, height, hor_texts, ver_texts, margin)
-
-
-def resize_image(resize_mode, im, width, height, upscaler_name=None):
-
- upscaler_name = upscaler_name or opts.upscaler_for_img2img
-
- def resize(im, w, h):
- if upscaler_name is None or upscaler_name == "None" or im.mode == 'L':
- return im.resize((w, h), resample=LANCZOS)
-
- scale = max(w / im.width, h / im.height)
-
- if scale > 1.0:
- upscalers = [x for x in shared.sd_upscalers if x.name == upscaler_name]
- if len(upscalers) == 0:
- upscaler = shared.sd_upscalers[0]
- print(f"could not find upscaler named {upscaler_name or '<empty string>'}, using {upscaler.name} as a fallback")
- else:
- upscaler = upscalers[0]
-
- im = upscaler.scaler.upscale(im, scale, upscaler.data_path)
-
- if im.width != w or im.height != h:
- im = im.resize((w, h), resample=LANCZOS)
-
- return im
-
- if resize_mode == 0:
- res = resize(im, width, height)
-
- elif resize_mode == 1:
- ratio = width / height
- src_ratio = im.width / im.height
-
- src_w = width if ratio > src_ratio else im.width * height // im.height
- src_h = height if ratio <= src_ratio else im.height * width // im.width
-
- resized = resize(im, src_w, src_h)
- res = Image.new("RGB", (width, height))
- res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
-
- else:
- ratio = width / height
- src_ratio = im.width / im.height
-
- src_w = width if ratio < src_ratio else im.width * height // im.height
- src_h = height if ratio >= src_ratio else im.height * width // im.width
-
- resized = resize(im, src_w, src_h)
- res = Image.new("RGB", (width, height))
- res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
-
- if ratio < src_ratio:
- fill_height = height // 2 - src_h // 2
- if fill_height > 0:
- res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
- res.paste(resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)), box=(0, fill_height + src_h))
- elif ratio > src_ratio:
- fill_width = width // 2 - src_w // 2
- if fill_width > 0:
- res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0))
- res.paste(resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)), box=(fill_width + src_w, 0))
-
- return res
-
-
-if not shared.cmd_opts.unix_filenames_sanitization:
- invalid_filename_chars = '#<>:"/\\|?*\n\r\t'
-else:
- invalid_filename_chars = '/'
-invalid_filename_prefix = ' '
-invalid_filename_postfix = ' .'
-re_nonletters = re.compile(r'[\s' + string.punctuation + ']+')
-re_pattern = re.compile(r"(.*?)(?:\[([^\[\]]+)\]|$)")
-re_pattern_arg = re.compile(r"(.*)<([^>]*)>$")
-max_filename_part_length = shared.cmd_opts.filenames_max_length
-NOTHING_AND_SKIP_PREVIOUS_TEXT = object()
-
-
-def sanitize_filename_part(text, replace_spaces=True):
- if text is None:
- return None
-
- if replace_spaces:
- text = text.replace(' ', '_')
-
- text = text.translate({ord(x): '_' for x in invalid_filename_chars})
- text = text.lstrip(invalid_filename_prefix)[:max_filename_part_length]
- text = text.rstrip(invalid_filename_postfix)
- return text
-
-
-@functools.cache
-def get_scheduler_str(sampler_name, scheduler_name):
- if scheduler_name == 'Automatic':
- config = sd_samplers.find_sampler_config(sampler_name)
- scheduler_name = config.options.get('scheduler', 'Automatic')
- return scheduler_name.capitalize()
-
-
-@functools.cache
-def get_sampler_scheduler_str(sampler_name, scheduler_name):
- return f'{sampler_name} {get_scheduler_str(sampler_name, scheduler_name)}'
-
-
-def get_sampler_scheduler(p, sampler):
- if hasattr(p, 'scheduler') and hasattr(p, 'sampler_name'):
- if sampler:
- sampler_scheduler = get_sampler_scheduler_str(p.sampler_name, p.scheduler)
- else:
- sampler_scheduler = get_scheduler_str(p.sampler_name, p.scheduler)
- return sanitize_filename_part(sampler_scheduler, replace_spaces=False)
- return NOTHING_AND_SKIP_PREVIOUS_TEXT
-
-
-class FilenameGenerator:
- replacements = {
- 'basename': lambda self: self.basename or 'img',
- 'seed': lambda self: self.seed if self.seed is not None else '',
- 'seed_first': lambda self: self.seed if self.p.batch_size == 1 else self.p.all_seeds[0],
- 'seed_last': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if self.p.batch_size == 1 else self.p.all_seeds[-1],
- 'steps': lambda self: self.p and self.p.steps,
- 'cfg': lambda self: self.p and self.p.cfg_scale,
- 'width': lambda self: self.image.width,
- 'height': lambda self: self.image.height,
- 'styles': lambda self: self.p and sanitize_filename_part(", ".join([style for style in self.p.styles if not style == "None"]) or "None", replace_spaces=False),
- 'sampler': lambda self: self.p and sanitize_filename_part(self.p.sampler_name, replace_spaces=False),
- 'sampler_scheduler': lambda self: self.p and get_sampler_scheduler(self.p, True),
- 'scheduler': lambda self: self.p and get_sampler_scheduler(self.p, False),
- 'model_hash': lambda self: getattr(self.p, "sd_model_hash", shared.sd_model.sd_model_hash),
- 'model_name': lambda self: sanitize_filename_part(shared.sd_model.sd_checkpoint_info.name_for_extra, replace_spaces=False),
- 'date': lambda self: datetime.datetime.now().strftime('%Y-%m-%d'),
- 'datetime': lambda self, *args: self.datetime(*args), # accepts formats: [datetime], [datetime<Format>], [datetime<Format><Time Zone>]
- 'job_timestamp': lambda self: getattr(self.p, "job_timestamp", shared.state.job_timestamp),
- 'prompt_hash': lambda self, *args: self.string_hash(self.prompt, *args),
- 'negative_prompt_hash': lambda self, *args: self.string_hash(self.p.negative_prompt, *args),
- 'full_prompt_hash': lambda self, *args: self.string_hash(f"{self.p.prompt} {self.p.negative_prompt}", *args), # a space in between to create a unique string
- 'prompt': lambda self: sanitize_filename_part(self.prompt),
- 'prompt_no_styles': lambda self: self.prompt_no_style(),
- 'prompt_spaces': lambda self: sanitize_filename_part(self.prompt, replace_spaces=False),
- 'prompt_words': lambda self: self.prompt_words(),
- 'batch_number': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if self.p.batch_size == 1 or self.zip else self.p.batch_index + 1,
- 'batch_size': lambda self: self.p.batch_size,
- 'generation_number': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if (self.p.n_iter == 1 and self.p.batch_size == 1) or self.zip else self.p.iteration * self.p.batch_size + self.p.batch_index + 1,
- 'hasprompt': lambda self, *args: self.hasprompt(*args), # accepts formats:[hasprompt<prompt1|default><prompt2>..]
- 'clip_skip': lambda self: opts.data["CLIP_stop_at_last_layers"],
- 'denoising': lambda self: self.p.denoising_strength if self.p and self.p.denoising_strength else NOTHING_AND_SKIP_PREVIOUS_TEXT,
- 'user': lambda self: self.p.user,
- 'vae_filename': lambda self: self.get_vae_filename(),
- 'none': lambda self: '', # Overrides the default, so you can get just the sequence number
- 'image_hash': lambda self, *args: self.image_hash(*args) # accepts formats: [image_hash<length>] default full hash
- }
- default_time_format = '%Y%m%d%H%M%S'
-
- def __init__(self, p, seed, prompt, image, zip=False, basename=""):
- self.p = p
- self.seed = seed
- self.prompt = prompt
- self.image = image
- self.zip = zip
- self.basename = basename
-
- def get_vae_filename(self):
-
- import modules.sd_vae as sd_vae
-
- if sd_vae.loaded_vae_file is None:
- return "NoneType"
-
- file_name = os.path.basename(sd_vae.loaded_vae_file)
- split_file_name = file_name.split('.')
- if len(split_file_name) > 1 and split_file_name[0] == '':
- return split_file_name[1] # if the first character of the filename is "." then [1] is obtained.
- else:
- return split_file_name[0]
-
-
- def hasprompt(self, *args):
- lower = self.prompt.lower()
- if self.p is None or self.prompt is None:
- return None
- outres = ""
- for arg in args:
- if arg != "":
- division = arg.split("|")
- expected = division[0].lower()
- default = division[1] if len(division) > 1 else ""
- if lower.find(expected) >= 0:
- outres = f'{outres}{expected}'
- else:
- outres = outres if default == "" else f'{outres}{default}'
- return sanitize_filename_part(outres)
-
- def prompt_no_style(self):
- if self.p is None or self.prompt is None:
- return None
-
- prompt_no_style = self.prompt
- for style in shared.prompt_styles.get_style_prompts(self.p.styles):
- if style:
- for part in style.split("{prompt}"):
- prompt_no_style = prompt_no_style.replace(part, "").replace(", ,", ",").strip().strip(',')
-
- prompt_no_style = prompt_no_style.replace(style, "").strip().strip(',').strip()
-
- return sanitize_filename_part(prompt_no_style, replace_spaces=False)
-
- def prompt_words(self):
- words = [x for x in re_nonletters.split(self.prompt or "") if x]
- if len(words) == 0:
- words = ["empty"]
- return sanitize_filename_part(" ".join(words[0:opts.directories_max_prompt_words]), replace_spaces=False)
-
- def datetime(self, *args):
- time_datetime = datetime.datetime.now()
-
- time_format = args[0] if (args and args[0] != "") else self.default_time_format
- try:
- time_zone = pytz.timezone(args[1]) if len(args) > 1 else None
- except pytz.exceptions.UnknownTimeZoneError:
- time_zone = None
-
- time_zone_time = time_datetime.astimezone(time_zone)
- try:
- formatted_time = time_zone_time.strftime(time_format)
- except (ValueError, TypeError):
- formatted_time = time_zone_time.strftime(self.default_time_format)
-
- return sanitize_filename_part(formatted_time, replace_spaces=False)
-
- def image_hash(self, *args):
- length = int(args[0]) if (args and args[0] != "") else None
- return hashlib.sha256(self.image.tobytes()).hexdigest()[0:length]
-
- def string_hash(self, text, *args):
- length = int(args[0]) if (args and args[0] != "") else 8
- return hashlib.sha256(text.encode()).hexdigest()[0:length]
-
- def apply(self, x):
- res = ''
-
- for m in re_pattern.finditer(x):
- text, pattern = m.groups()
-
- if pattern is None:
- res += text
- continue
-
- pattern_args = []
- while True:
- m = re_pattern_arg.match(pattern)
- if m is None:
- break
-
- pattern, arg = m.groups()
- pattern_args.insert(0, arg)
-
- fun = self.replacements.get(pattern.lower())
- if fun is not None:
- try:
- replacement = fun(self, *pattern_args)
- except Exception:
- replacement = None
- errors.report(f"Error adding [{pattern}] to filename", exc_info=True)
-
- if replacement == NOTHING_AND_SKIP_PREVIOUS_TEXT:
- continue
- elif replacement is not None:
- res += text + str(replacement)
- continue
-
- res += f'{text}[{pattern}]'
-
- return res
-
-
-def get_next_sequence_number(path, basename):
- result = -1
- if basename != '':
- basename = f"{basename}-"
-
- prefix_length = len(basename)
- for p in os.listdir(path):
- if p.startswith(basename):
- parts = os.path.splitext(p[prefix_length:])[0].split('-') # splits the filename (removing the basename first if one is defined, so the sequence number is always the first element)
- try:
- result = max(int(parts[0]), result)
- except ValueError:
- pass
-
- return result + 1
-
-
-def save_image_with_geninfo(image, geninfo, filename, extension=None, existing_pnginfo=None, pnginfo_section_name='parameters'):
-
- if extension is None:
- extension = os.path.splitext(filename)[1]
-
- image_format = Image.registered_extensions()[extension]
-
- if extension.lower() == '.png':
- existing_pnginfo = existing_pnginfo or {}
- if opts.enable_pnginfo:
- existing_pnginfo[pnginfo_section_name] = geninfo
-
- if opts.enable_pnginfo:
- pnginfo_data = PngImagePlugin.PngInfo()
- for k, v in (existing_pnginfo or {}).items():
- pnginfo_data.add_text(k, str(v))
- else:
- pnginfo_data = None
-
- image.save(filename, format=image_format, quality=opts.jpeg_quality, pnginfo=pnginfo_data)
-
- elif extension.lower() in (".jpg", ".jpeg", ".webp"):
- if image.mode == 'RGBA':
- image = image.convert("RGB")
- elif image.mode == 'I;16':
- image = image.point(lambda p: p * 0.0038910505836576).convert("RGB" if extension.lower() == ".webp" else "L")
-
- image.save(filename, format=image_format, quality=opts.jpeg_quality, lossless=opts.webp_lossless)
-
- if opts.enable_pnginfo and geninfo is not None:
- exif_bytes = piexif.dump({
- "Exif": {
- piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(geninfo or "", encoding="unicode")
- },
- })
-
- piexif.insert(exif_bytes, filename)
- elif extension.lower() == '.avif':
- if opts.enable_pnginfo and geninfo is not None:
- exif_bytes = piexif.dump({
- "Exif": {
- piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(geninfo or "", encoding="unicode")
- },
- })
- else:
- exif_bytes = None
-
- image.save(filename,format=image_format, quality=opts.jpeg_quality, exif=exif_bytes)
- elif extension.lower() == ".gif":
- image.save(filename, format=image_format, comment=geninfo)
- else:
- image.save(filename, format=image_format, quality=opts.jpeg_quality)
-
-
-def save_image(image, path, basename, seed=None, prompt=None, extension='png', info=None, short_filename=False, no_prompt=False, grid=False, pnginfo_section_name='parameters', p=None, existing_info=None, forced_filename=None, suffix="", save_to_dirs=None):
- namegen = FilenameGenerator(p, seed, prompt, image, basename=basename)
-
- # WebP and JPG formats have maximum dimension limits of 16383 and 65535 respectively. switch to PNG which has a much higher limit
- if (image.height > 65535 or image.width > 65535) and extension.lower() in ("jpg", "jpeg") or (image.height > 16383 or image.width > 16383) and extension.lower() == "webp":
- print('Image dimensions too large; saving as PNG')
- extension = "png"
-
- if save_to_dirs is None:
- save_to_dirs = (grid and opts.grid_save_to_dirs) or (not grid and opts.save_to_dirs and not no_prompt)
-
- if save_to_dirs:
- dirname = namegen.apply(opts.directories_filename_pattern or "[prompt_words]").lstrip(' ').rstrip('\\ /')
- path = os.path.join(path, dirname)
-
- os.makedirs(path, exist_ok=True)
-
- if forced_filename is None:
- if short_filename or seed is None:
- file_decoration = ""
- elif opts.save_to_dirs:
- file_decoration = opts.samples_filename_pattern or "[seed]"
- else:
- file_decoration = opts.samples_filename_pattern or "[seed]-[prompt_spaces]"
-
- file_decoration = namegen.apply(file_decoration) + suffix
-
- add_number = opts.save_images_add_number or file_decoration == ''
-
- if file_decoration != "" and add_number:
- file_decoration = f"-{file_decoration}"
-
- if add_number:
- basecount = get_next_sequence_number(path, basename)
- fullfn = None
- for i in range(500):
- fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}"
- fullfn = os.path.join(path, f"{fn}{file_decoration}.{extension}")
- if not os.path.exists(fullfn):
- break
- else:
- fullfn = os.path.join(path, f"{file_decoration}.{extension}")
- else:
- fullfn = os.path.join(path, f"{forced_filename}.{extension}")
-
- pnginfo = existing_info or {}
- if info is not None:
- pnginfo[pnginfo_section_name] = info
-
- params = script_callbacks.ImageSaveParams(image, p, fullfn, pnginfo)
- script_callbacks.before_image_saved_callback(params)
-
- image = params.image
- fullfn = params.filename
- info = params.pnginfo.get(pnginfo_section_name, None)
-
- def _atomically_save_image(image_to_save, filename_without_extension, extension):
- temp_file_path = f"{filename_without_extension}.tmp"
-
- save_image_with_geninfo(image_to_save, info, temp_file_path, extension, existing_pnginfo=params.pnginfo, pnginfo_section_name=pnginfo_section_name)
-
- filename = filename_without_extension + extension
- if shared.opts.save_images_replace_action != "Replace":
- n = 0
- while os.path.exists(filename):
- n += 1
- filename = f"{filename_without_extension}-{n}{extension}"
- os.replace(temp_file_path, filename)
-
- fullfn_without_extension, extension = os.path.splitext(params.filename)
- if hasattr(os, 'statvfs'):
- max_name_len = os.statvfs(path).f_namemax
- fullfn_without_extension = fullfn_without_extension[:max_name_len - max(4, len(extension))]
- params.filename = fullfn_without_extension + extension
- fullfn = params.filename
- _atomically_save_image(image, fullfn_without_extension, extension)
-
- image.already_saved_as = fullfn
-
- oversize = image.width > opts.target_side_length or image.height > opts.target_side_length
- if opts.export_for_4chan and (oversize or os.stat(fullfn).st_size > opts.img_downscale_threshold * 1024 * 1024):
- ratio = image.width / image.height
- resize_to = None
- if oversize and ratio > 1:
- resize_to = round(opts.target_side_length), round(image.height * opts.target_side_length / image.width)
- elif oversize:
- resize_to = round(image.width * opts.target_side_length / image.height), round(opts.target_side_length)
-
- if resize_to is not None:
- try:
- # Resizing image with LANCZOS could throw an exception if e.g. image mode is I;16
- image = image.resize(resize_to, LANCZOS)
- except Exception:
- image = image.resize(resize_to)
- try:
- _atomically_save_image(image, fullfn_without_extension, ".jpg")
- except Exception as e:
- errors.display(e, "saving image as downscaled JPG")
-
- if opts.save_txt and info is not None:
- txt_fullfn = f"{fullfn_without_extension}.txt"
- with open(txt_fullfn, "w", encoding="utf8") as file:
- file.write(f"{info}\n")
- else:
- txt_fullfn = None
-
- script_callbacks.image_saved_callback(params)
-
- return fullfn, txt_fullfn
-
-
-IGNORED_INFO_KEYS = {
- 'jfif', 'jfif_version', 'jfif_unit', 'jfif_density', 'dpi', 'exif',
- 'loop', 'background', 'timestamp', 'duration', 'progressive', 'progression',
- 'icc_profile', 'chromaticity', 'photoshop',
-}
-
-
-def read_info_from_image(image: Image.Image) -> tuple[str | None, dict]:
- items = (image.info or {}).copy()
-
- geninfo = items.pop('parameters', None)
-
- if "exif" in items:
- exif_data = items["exif"]
- try:
- exif = piexif.load(exif_data)
- except OSError:
- # memory / exif was not valid so piexif tried to read from a file
- exif = None
- exif_comment = (exif or {}).get("Exif", {}).get(piexif.ExifIFD.UserComment, b'')
- try:
- exif_comment = piexif.helper.UserComment.load(exif_comment)
- except ValueError:
- exif_comment = exif_comment.decode('utf8', errors="ignore")
-
- if exif_comment:
- geninfo = exif_comment
- elif "comment" in items: # for gif
- if isinstance(items["comment"], bytes):
- geninfo = items["comment"].decode('utf8', errors="ignore")
- else:
- geninfo = items["comment"]
-
- for field in IGNORED_INFO_KEYS:
- items.pop(field, None)
-
- if items.get("Software", None) == "NovelAI":
- try:
- json_info = json.loads(items["Comment"])
- sampler = sd_samplers.samplers_map.get(json_info["sampler"], "Euler a")
-
- geninfo = f"""{items["Description"]}
-Negative prompt: {json_info["uc"]}
-Steps: {json_info["steps"]}, Sampler: {sampler}, CFG scale: {json_info["scale"]}, Seed: {json_info["seed"]}, Size: {image.width}x{image.height}, Clip skip: 2, ENSD: 31337"""
- except Exception:
- errors.report("Error parsing NovelAI image generation parameters", exc_info=True)
-
- return geninfo, items
-
-
-def image_data(data):
- import gradio as gr
-
- try:
- image = read(io.BytesIO(data))
- textinfo, _ = read_info_from_image(image)
- return textinfo, None
- except Exception:
- pass
-
- try:
- text = data.decode('utf8')
- assert len(text) < 10000
- return text, None
-
- except Exception:
- pass
-
- return gr.update(), None
-
-
-def flatten(img, bgcolor):
-
- if img.mode == "RGBA":
- background = Image.new('RGBA', img.size, bgcolor)
- background.paste(img, mask=img)
- img = background
-
- return img.convert('RGB')
-
-
-def read(fp, **kwargs):
- image = Image.open(fp, **kwargs)
- image = fix_image(image)
-
- return image
-
-
-def fix_image(image: Image.Image):
- if image is None:
- return None
-
- try:
- image = ImageOps.exif_transpose(image)
- image = fix_png_transparency(image)
- except Exception:
- pass
-
- return image
-
-
-def fix_png_transparency(image: Image.Image):
- if image.mode not in ("RGB", "P") or not isinstance(image.info.get("transparency"), bytes):
- return image
-
- image = image.convert("RGBA")
- return image+from __future__ import annotations
+
+import datetime
+import functools
+import pytz
+import io
+import math
+import os
+from collections import namedtuple
+import re
+
+import numpy as np
+import piexif
+import piexif.helper
+from PIL import Image, ImageFont, ImageDraw, ImageColor, PngImagePlugin, ImageOps
+# pillow_avif needs to be imported somewhere in code for it to work
+import pillow_avif # noqa: F401
+import string
+import json
+import hashlib
+
+from modules import sd_samplers, shared, script_callbacks, errors
+from modules.paths_internal import roboto_ttf_file
+from modules.shared import opts
+
+LANCZOS = (Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS)
+
+
+def get_font(fontsize: int):
+ try:
+ return ImageFont.truetype(opts.font or roboto_ttf_file, fontsize)
+ except Exception:
+ return ImageFont.truetype(roboto_ttf_file, fontsize)
+
+
+def image_grid(imgs, batch_size=1, rows=None):
+ if rows is None:
+ if opts.n_rows > 0:
+ rows = opts.n_rows
+ elif opts.n_rows == 0:
+ rows = batch_size
+ elif opts.grid_prevent_empty_spots:
+ rows = math.floor(math.sqrt(len(imgs)))
+ while len(imgs) % rows != 0:
+ rows -= 1
+ else:
+ rows = math.sqrt(len(imgs))
+ rows = round(rows)
+ if rows > len(imgs):
+ rows = len(imgs)
+
+ cols = math.ceil(len(imgs) / rows)
+
+ params = script_callbacks.ImageGridLoopParams(imgs, cols, rows)
+ script_callbacks.image_grid_callback(params)
+
+ w, h = map(max, zip(*(img.size for img in imgs)))
+ grid_background_color = ImageColor.getcolor(opts.grid_background_color, 'RGB')
+ grid = Image.new('RGB', size=(params.cols * w, params.rows * h), color=grid_background_color)
+
+ for i, img in enumerate(params.imgs):
+ img_w, img_h = img.size
+ w_offset, h_offset = 0 if img_w == w else (w - img_w) // 2, 0 if img_h == h else (h - img_h) // 2
+ grid.paste(img, box=(i % params.cols * w + w_offset, i // params.cols * h + h_offset))
+
+ return grid
+
+
+class Grid(namedtuple("_Grid", ["tiles", "tile_w", "tile_h", "image_w", "image_h", "overlap"])):
+ @property
+ def tile_count(self) -> int:
+ """
+ The total number of tiles in the grid.
+ """
+ return sum(len(row[2]) for row in self.tiles)
+
+
+def split_grid(image: Image.Image, tile_w: int = 512, tile_h: int = 512, overlap: int = 64) -> Grid:
+ w, h = image.size
+
+ non_overlap_width = tile_w - overlap
+ non_overlap_height = tile_h - overlap
+
+ cols = math.ceil((w - overlap) / non_overlap_width)
+ rows = math.ceil((h - overlap) / non_overlap_height)
+
+ dx = (w - tile_w) / (cols - 1) if cols > 1 else 0
+ dy = (h - tile_h) / (rows - 1) if rows > 1 else 0
+
+ grid = Grid([], tile_w, tile_h, w, h, overlap)
+ for row in range(rows):
+ row_images = []
+
+ y = int(row * dy)
+
+ if y + tile_h >= h:
+ y = h - tile_h
+
+ for col in range(cols):
+ x = int(col * dx)
+
+ if x + tile_w >= w:
+ x = w - tile_w
+
+ tile = image.crop((x, y, x + tile_w, y + tile_h))
+
+ row_images.append([x, tile_w, tile])
+
+ grid.tiles.append([y, tile_h, row_images])
+
+ return grid
+
+
+def combine_grid(grid):
+ def make_mask_image(r):
+ r = r * 255 / grid.overlap
+ r = r.astype(np.uint8)
+ return Image.fromarray(r, 'L')
+
+ mask_w = make_mask_image(np.arange(grid.overlap, dtype=np.float32).reshape((1, grid.overlap)).repeat(grid.tile_h, axis=0))
+ mask_h = make_mask_image(np.arange(grid.overlap, dtype=np.float32).reshape((grid.overlap, 1)).repeat(grid.image_w, axis=1))
+
+ combined_image = Image.new("RGB", (grid.image_w, grid.image_h))
+ for y, h, row in grid.tiles:
+ combined_row = Image.new("RGB", (grid.image_w, h))
+ for x, w, tile in row:
+ if x == 0:
+ combined_row.paste(tile, (0, 0))
+ continue
+
+ combined_row.paste(tile.crop((0, 0, grid.overlap, h)), (x, 0), mask=mask_w)
+ combined_row.paste(tile.crop((grid.overlap, 0, w, h)), (x + grid.overlap, 0))
+
+ if y == 0:
+ combined_image.paste(combined_row, (0, 0))
+ continue
+
+ combined_image.paste(combined_row.crop((0, 0, combined_row.width, grid.overlap)), (0, y), mask=mask_h)
+ combined_image.paste(combined_row.crop((0, grid.overlap, combined_row.width, h)), (0, y + grid.overlap))
+
+ return combined_image
+
+
+class GridAnnotation:
+ def __init__(self, text='', is_active=True):
+ self.text = text
+ self.is_active = is_active
+ self.size = None
+
+
+def draw_grid_annotations(im, width, height, hor_texts, ver_texts, margin=0):
+
+ color_active = ImageColor.getcolor(opts.grid_text_active_color, 'RGB')
+ color_inactive = ImageColor.getcolor(opts.grid_text_inactive_color, 'RGB')
+ color_background = ImageColor.getcolor(opts.grid_background_color, 'RGB')
+
+ def wrap(drawing, text, font, line_length):
+ lines = ['']
+ for word in text.split():
+ line = f'{lines[-1]} {word}'.strip()
+ if drawing.textlength(line, font=font) <= line_length:
+ lines[-1] = line
+ else:
+ lines.append(word)
+ return lines
+
+ def draw_texts(drawing, draw_x, draw_y, lines, initial_fnt, initial_fontsize):
+ for line in lines:
+ fnt = initial_fnt
+ fontsize = initial_fontsize
+ while drawing.multiline_textsize(line.text, font=fnt)[0] > line.allowed_width and fontsize > 0:
+ fontsize -= 1
+ fnt = get_font(fontsize)
+ drawing.multiline_text((draw_x, draw_y + line.size[1] / 2), line.text, font=fnt, fill=color_active if line.is_active else color_inactive, anchor="mm", align="center")
+
+ if not line.is_active:
+ drawing.line((draw_x - line.size[0] // 2, draw_y + line.size[1] // 2, draw_x + line.size[0] // 2, draw_y + line.size[1] // 2), fill=color_inactive, width=4)
+
+ draw_y += line.size[1] + line_spacing
+
+ fontsize = (width + height) // 25
+ line_spacing = fontsize // 2
+
+ fnt = get_font(fontsize)
+
+ pad_left = 0 if sum([sum([len(line.text) for line in lines]) for lines in ver_texts]) == 0 else width * 3 // 4
+
+ cols = im.width // width
+ rows = im.height // height
+
+ assert cols == len(hor_texts), f'bad number of horizontal texts: {len(hor_texts)}; must be {cols}'
+ assert rows == len(ver_texts), f'bad number of vertical texts: {len(ver_texts)}; must be {rows}'
+
+ calc_img = Image.new("RGB", (1, 1), color_background)
+ calc_d = ImageDraw.Draw(calc_img)
+
+ for texts, allowed_width in zip(hor_texts + ver_texts, [width] * len(hor_texts) + [pad_left] * len(ver_texts)):
+ items = [] + texts
+ texts.clear()
+
+ for line in items:
+ wrapped = wrap(calc_d, line.text, fnt, allowed_width)
+ texts += [GridAnnotation(x, line.is_active) for x in wrapped]
+
+ for line in texts:
+ bbox = calc_d.multiline_textbbox((0, 0), line.text, font=fnt)
+ line.size = (bbox[2] - bbox[0], bbox[3] - bbox[1])
+ line.allowed_width = allowed_width
+
+ hor_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing for lines in hor_texts]
+ ver_text_heights = [sum([line.size[1] + line_spacing for line in lines]) - line_spacing * len(lines) for lines in ver_texts]
+
+ pad_top = 0 if sum(hor_text_heights) == 0 else max(hor_text_heights) + line_spacing * 2
+
+ result = Image.new("RGB", (im.width + pad_left + margin * (cols-1), im.height + pad_top + margin * (rows-1)), color_background)
+
+ for row in range(rows):
+ for col in range(cols):
+ cell = im.crop((width * col, height * row, width * (col+1), height * (row+1)))
+ result.paste(cell, (pad_left + (width + margin) * col, pad_top + (height + margin) * row))
+
+ d = ImageDraw.Draw(result)
+
+ for col in range(cols):
+ x = pad_left + (width + margin) * col + width / 2
+ y = pad_top / 2 - hor_text_heights[col] / 2
+
+ draw_texts(d, x, y, hor_texts[col], fnt, fontsize)
+
+ for row in range(rows):
+ x = pad_left / 2
+ y = pad_top + (height + margin) * row + height / 2 - ver_text_heights[row] / 2
+
+ draw_texts(d, x, y, ver_texts[row], fnt, fontsize)
+
+ return result
+
+
+def draw_prompt_matrix(im, width, height, all_prompts, margin=0):
+ prompts = all_prompts[1:]
+ boundary = math.ceil(len(prompts) / 2)
+
+ prompts_horiz = prompts[:boundary]
+ prompts_vert = prompts[boundary:]
+
+ hor_texts = [[GridAnnotation(x, is_active=pos & (1 << i) != 0) for i, x in enumerate(prompts_horiz)] for pos in range(1 << len(prompts_horiz))]
+ ver_texts = [[GridAnnotation(x, is_active=pos & (1 << i) != 0) for i, x in enumerate(prompts_vert)] for pos in range(1 << len(prompts_vert))]
+
+ return draw_grid_annotations(im, width, height, hor_texts, ver_texts, margin)
+
+
+def resize_image(resize_mode, im, width, height, upscaler_name=None):
+ """
+ Resizes an image with the specified resize_mode, width, and height.
+
+ Args:
+ resize_mode: The mode to use when resizing the image.
+ 0: Resize the image to the specified width and height.
+ 1: Resize the image to fill the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, cropping the excess.
+ 2: Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center the image within the dimensions, filling empty with data from image.
+ im: The image to resize.
+ width: The width to resize the image to.
+ height: The height to resize the image to.
+ upscaler_name: The name of the upscaler to use. If not provided, defaults to opts.upscaler_for_img2img.
+ """
+
+ upscaler_name = upscaler_name or opts.upscaler_for_img2img
+
+ def resize(im, w, h):
+ if upscaler_name is None or upscaler_name == "None" or im.mode == 'L':
+ return im.resize((w, h), resample=LANCZOS)
+
+ scale = max(w / im.width, h / im.height)
+
+ if scale > 1.0:
+ upscalers = [x for x in shared.sd_upscalers if x.name == upscaler_name]
+ if len(upscalers) == 0:
+ upscaler = shared.sd_upscalers[0]
+ print(f"could not find upscaler named {upscaler_name or '<empty string>'}, using {upscaler.name} as a fallback")
+ else:
+ upscaler = upscalers[0]
+
+ im = upscaler.scaler.upscale(im, scale, upscaler.data_path)
+
+ if im.width != w or im.height != h:
+ im = im.resize((w, h), resample=LANCZOS)
+
+ return im
+
+ if resize_mode == 0:
+ res = resize(im, width, height)
+
+ elif resize_mode == 1:
+ ratio = width / height
+ src_ratio = im.width / im.height
+
+ src_w = width if ratio > src_ratio else im.width * height // im.height
+ src_h = height if ratio <= src_ratio else im.height * width // im.width
+
+ resized = resize(im, src_w, src_h)
+ res = Image.new("RGB", (width, height))
+ res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
+
+ else:
+ ratio = width / height
+ src_ratio = im.width / im.height
+
+ src_w = width if ratio < src_ratio else im.width * height // im.height
+ src_h = height if ratio >= src_ratio else im.height * width // im.width
+
+ resized = resize(im, src_w, src_h)
+ res = Image.new("RGB", (width, height))
+ res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
+
+ if ratio < src_ratio:
+ fill_height = height // 2 - src_h // 2
+ if fill_height > 0:
+ res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
+ res.paste(resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)), box=(0, fill_height + src_h))
+ elif ratio > src_ratio:
+ fill_width = width // 2 - src_w // 2
+ if fill_width > 0:
+ res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0))
+ res.paste(resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)), box=(fill_width + src_w, 0))
+
+ return res
+
+
+if not shared.cmd_opts.unix_filenames_sanitization:
+ invalid_filename_chars = '#<>:"/\\|?*\n\r\t'
+else:
+ invalid_filename_chars = '/'
+invalid_filename_prefix = ' '
+invalid_filename_postfix = ' .'
+re_nonletters = re.compile(r'[\s' + string.punctuation + ']+')
+re_pattern = re.compile(r"(.*?)(?:\[([^\[\]]+)\]|$)")
+re_pattern_arg = re.compile(r"(.*)<([^>]*)>$")
+max_filename_part_length = shared.cmd_opts.filenames_max_length
+NOTHING_AND_SKIP_PREVIOUS_TEXT = object()
+
+
+def sanitize_filename_part(text, replace_spaces=True):
+ if text is None:
+ return None
+
+ if replace_spaces:
+ text = text.replace(' ', '_')
+
+ text = text.translate({ord(x): '_' for x in invalid_filename_chars})
+ text = text.lstrip(invalid_filename_prefix)[:max_filename_part_length]
+ text = text.rstrip(invalid_filename_postfix)
+ return text
+
+
+@functools.cache
+def get_scheduler_str(sampler_name, scheduler_name):
+ """Returns {Scheduler} if the scheduler is applicable to the sampler"""
+ if scheduler_name == 'Automatic':
+ config = sd_samplers.find_sampler_config(sampler_name)
+ scheduler_name = config.options.get('scheduler', 'Automatic')
+ return scheduler_name.capitalize()
+
+
+@functools.cache
+def get_sampler_scheduler_str(sampler_name, scheduler_name):
+ """Returns the '{Sampler} {Scheduler}' if the scheduler is applicable to the sampler"""
+ return f'{sampler_name} {get_scheduler_str(sampler_name, scheduler_name)}'
+
+
+def get_sampler_scheduler(p, sampler):
+ """Returns '{Sampler} {Scheduler}' / '{Scheduler}' / 'NOTHING_AND_SKIP_PREVIOUS_TEXT'"""
+ if hasattr(p, 'scheduler') and hasattr(p, 'sampler_name'):
+ if sampler:
+ sampler_scheduler = get_sampler_scheduler_str(p.sampler_name, p.scheduler)
+ else:
+ sampler_scheduler = get_scheduler_str(p.sampler_name, p.scheduler)
+ return sanitize_filename_part(sampler_scheduler, replace_spaces=False)
+ return NOTHING_AND_SKIP_PREVIOUS_TEXT
+
+
+class FilenameGenerator:
+ replacements = {
+ 'basename': lambda self: self.basename or 'img',
+ 'seed': lambda self: self.seed if self.seed is not None else '',
+ 'seed_first': lambda self: self.seed if self.p.batch_size == 1 else self.p.all_seeds[0],
+ 'seed_last': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if self.p.batch_size == 1 else self.p.all_seeds[-1],
+ 'steps': lambda self: self.p and self.p.steps,
+ 'cfg': lambda self: self.p and self.p.cfg_scale,
+ 'width': lambda self: self.image.width,
+ 'height': lambda self: self.image.height,
+ 'styles': lambda self: self.p and sanitize_filename_part(", ".join([style for style in self.p.styles if not style == "None"]) or "None", replace_spaces=False),
+ 'sampler': lambda self: self.p and sanitize_filename_part(self.p.sampler_name, replace_spaces=False),
+ 'sampler_scheduler': lambda self: self.p and get_sampler_scheduler(self.p, True),
+ 'scheduler': lambda self: self.p and get_sampler_scheduler(self.p, False),
+ 'model_hash': lambda self: getattr(self.p, "sd_model_hash", shared.sd_model.sd_model_hash),
+ 'model_name': lambda self: sanitize_filename_part(shared.sd_model.sd_checkpoint_info.name_for_extra, replace_spaces=False),
+ 'date': lambda self: datetime.datetime.now().strftime('%Y-%m-%d'),
+ 'datetime': lambda self, *args: self.datetime(*args), # accepts formats: [datetime], [datetime<Format>], [datetime<Format><Time Zone>]
+ 'job_timestamp': lambda self: getattr(self.p, "job_timestamp", shared.state.job_timestamp),
+ 'prompt_hash': lambda self, *args: self.string_hash(self.prompt, *args),
+ 'negative_prompt_hash': lambda self, *args: self.string_hash(self.p.negative_prompt, *args),
+ 'full_prompt_hash': lambda self, *args: self.string_hash(f"{self.p.prompt} {self.p.negative_prompt}", *args), # a space in between to create a unique string
+ 'prompt': lambda self: sanitize_filename_part(self.prompt),
+ 'prompt_no_styles': lambda self: self.prompt_no_style(),
+ 'prompt_spaces': lambda self: sanitize_filename_part(self.prompt, replace_spaces=False),
+ 'prompt_words': lambda self: self.prompt_words(),
+ 'batch_number': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if self.p.batch_size == 1 or self.zip else self.p.batch_index + 1,
+ 'batch_size': lambda self: self.p.batch_size,
+ 'generation_number': lambda self: NOTHING_AND_SKIP_PREVIOUS_TEXT if (self.p.n_iter == 1 and self.p.batch_size == 1) or self.zip else self.p.iteration * self.p.batch_size + self.p.batch_index + 1,
+ 'hasprompt': lambda self, *args: self.hasprompt(*args), # accepts formats:[hasprompt<prompt1|default><prompt2>..]
+ 'clip_skip': lambda self: opts.data["CLIP_stop_at_last_layers"],
+ 'denoising': lambda self: self.p.denoising_strength if self.p and self.p.denoising_strength else NOTHING_AND_SKIP_PREVIOUS_TEXT,
+ 'user': lambda self: self.p.user,
+ 'vae_filename': lambda self: self.get_vae_filename(),
+ 'none': lambda self: '', # Overrides the default, so you can get just the sequence number
+ 'image_hash': lambda self, *args: self.image_hash(*args) # accepts formats: [image_hash<length>] default full hash
+ }
+ default_time_format = '%Y%m%d%H%M%S'
+
+ def __init__(self, p, seed, prompt, image, zip=False, basename=""):
+ self.p = p
+ self.seed = seed
+ self.prompt = prompt
+ self.image = image
+ self.zip = zip
+ self.basename = basename
+
+ def get_vae_filename(self):
+ """Get the name of the VAE file."""
+
+ import modules.sd_vae as sd_vae
+
+ if sd_vae.loaded_vae_file is None:
+ return "NoneType"
+
+ file_name = os.path.basename(sd_vae.loaded_vae_file)
+ split_file_name = file_name.split('.')
+ if len(split_file_name) > 1 and split_file_name[0] == '':
+ return split_file_name[1] # if the first character of the filename is "." then [1] is obtained.
+ else:
+ return split_file_name[0]
+
+
+ def hasprompt(self, *args):
+ lower = self.prompt.lower()
+ if self.p is None or self.prompt is None:
+ return None
+ outres = ""
+ for arg in args:
+ if arg != "":
+ division = arg.split("|")
+ expected = division[0].lower()
+ default = division[1] if len(division) > 1 else ""
+ if lower.find(expected) >= 0:
+ outres = f'{outres}{expected}'
+ else:
+ outres = outres if default == "" else f'{outres}{default}'
+ return sanitize_filename_part(outres)
+
+ def prompt_no_style(self):
+ if self.p is None or self.prompt is None:
+ return None
+
+ prompt_no_style = self.prompt
+ for style in shared.prompt_styles.get_style_prompts(self.p.styles):
+ if style:
+ for part in style.split("{prompt}"):
+ prompt_no_style = prompt_no_style.replace(part, "").replace(", ,", ",").strip().strip(',')
+
+ prompt_no_style = prompt_no_style.replace(style, "").strip().strip(',').strip()
+
+ return sanitize_filename_part(prompt_no_style, replace_spaces=False)
+
+ def prompt_words(self):
+ words = [x for x in re_nonletters.split(self.prompt or "") if x]
+ if len(words) == 0:
+ words = ["empty"]
+ return sanitize_filename_part(" ".join(words[0:opts.directories_max_prompt_words]), replace_spaces=False)
+
+ def datetime(self, *args):
+ time_datetime = datetime.datetime.now()
+
+ time_format = args[0] if (args and args[0] != "") else self.default_time_format
+ try:
+ time_zone = pytz.timezone(args[1]) if len(args) > 1 else None
+ except pytz.exceptions.UnknownTimeZoneError:
+ time_zone = None
+
+ time_zone_time = time_datetime.astimezone(time_zone)
+ try:
+ formatted_time = time_zone_time.strftime(time_format)
+ except (ValueError, TypeError):
+ formatted_time = time_zone_time.strftime(self.default_time_format)
+
+ return sanitize_filename_part(formatted_time, replace_spaces=False)
+
+ def image_hash(self, *args):
+ length = int(args[0]) if (args and args[0] != "") else None
+ return hashlib.sha256(self.image.tobytes()).hexdigest()[0:length]
+
+ def string_hash(self, text, *args):
+ length = int(args[0]) if (args and args[0] != "") else 8
+ return hashlib.sha256(text.encode()).hexdigest()[0:length]
+
+ def apply(self, x):
+ res = ''
+
+ for m in re_pattern.finditer(x):
+ text, pattern = m.groups()
+
+ if pattern is None:
+ res += text
+ continue
+
+ pattern_args = []
+ while True:
+ m = re_pattern_arg.match(pattern)
+ if m is None:
+ break
+
+ pattern, arg = m.groups()
+ pattern_args.insert(0, arg)
+
+ fun = self.replacements.get(pattern.lower())
+ if fun is not None:
+ try:
+ replacement = fun(self, *pattern_args)
+ except Exception:
+ replacement = None
+ errors.report(f"Error adding [{pattern}] to filename", exc_info=True)
+
+ if replacement == NOTHING_AND_SKIP_PREVIOUS_TEXT:
+ continue
+ elif replacement is not None:
+ res += text + str(replacement)
+ continue
+
+ res += f'{text}[{pattern}]'
+
+ return res
+
+
+def get_next_sequence_number(path, basename):
+ """
+ Determines and returns the next sequence number to use when saving an image in the specified directory.
+
+ The sequence starts at 0.
+ """
+ result = -1
+ if basename != '':
+ basename = f"{basename}-"
+
+ prefix_length = len(basename)
+ for p in os.listdir(path):
+ if p.startswith(basename):
+ parts = os.path.splitext(p[prefix_length:])[0].split('-') # splits the filename (removing the basename first if one is defined, so the sequence number is always the first element)
+ try:
+ result = max(int(parts[0]), result)
+ except ValueError:
+ pass
+
+ return result + 1
+
+
+def save_image_with_geninfo(image, geninfo, filename, extension=None, existing_pnginfo=None, pnginfo_section_name='parameters'):
+ """
+ Saves image to filename, including geninfo as text information for generation info.
+ For PNG images, geninfo is added to existing pnginfo dictionary using the pnginfo_section_name argument as key.
+ For JPG images, there's no dictionary and geninfo just replaces the EXIF description.
+ """
+
+ if extension is None:
+ extension = os.path.splitext(filename)[1]
+
+ image_format = Image.registered_extensions()[extension]
+
+ if extension.lower() == '.png':
+ existing_pnginfo = existing_pnginfo or {}
+ if opts.enable_pnginfo:
+ existing_pnginfo[pnginfo_section_name] = geninfo
+
+ if opts.enable_pnginfo:
+ pnginfo_data = PngImagePlugin.PngInfo()
+ for k, v in (existing_pnginfo or {}).items():
+ pnginfo_data.add_text(k, str(v))
+ else:
+ pnginfo_data = None
+
+ image.save(filename, format=image_format, quality=opts.jpeg_quality, pnginfo=pnginfo_data)
+
+ elif extension.lower() in (".jpg", ".jpeg", ".webp"):
+ if image.mode == 'RGBA':
+ image = image.convert("RGB")
+ elif image.mode == 'I;16':
+ image = image.point(lambda p: p * 0.0038910505836576).convert("RGB" if extension.lower() == ".webp" else "L")
+
+ image.save(filename, format=image_format, quality=opts.jpeg_quality, lossless=opts.webp_lossless)
+
+ if opts.enable_pnginfo and geninfo is not None:
+ exif_bytes = piexif.dump({
+ "Exif": {
+ piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(geninfo or "", encoding="unicode")
+ },
+ })
+
+ piexif.insert(exif_bytes, filename)
+ elif extension.lower() == '.avif':
+ if opts.enable_pnginfo and geninfo is not None:
+ exif_bytes = piexif.dump({
+ "Exif": {
+ piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(geninfo or "", encoding="unicode")
+ },
+ })
+ else:
+ exif_bytes = None
+
+ image.save(filename,format=image_format, quality=opts.jpeg_quality, exif=exif_bytes)
+ elif extension.lower() == ".gif":
+ image.save(filename, format=image_format, comment=geninfo)
+ else:
+ image.save(filename, format=image_format, quality=opts.jpeg_quality)
+
+
+def save_image(image, path, basename, seed=None, prompt=None, extension='png', info=None, short_filename=False, no_prompt=False, grid=False, pnginfo_section_name='parameters', p=None, existing_info=None, forced_filename=None, suffix="", save_to_dirs=None):
+ """Save an image.
+
+ Args:
+ image (`PIL.Image`):
+ The image to be saved.
+ path (`str`):
+ The directory to save the image. Note, the option `save_to_dirs` will make the image to be saved into a sub directory.
+ basename (`str`):
+ The base filename which will be applied to `filename pattern`.
+ seed, prompt, short_filename,
+ extension (`str`):
+ Image file extension, default is `png`.
+ pngsectionname (`str`):
+ Specify the name of the section which `info` will be saved in.
+ info (`str` or `PngImagePlugin.iTXt`):
+ PNG info chunks.
+ existing_info (`dict`):
+ Additional PNG info. `existing_info == {pngsectionname: info, ...}`
+ no_prompt:
+ TODO I don't know its meaning.
+ p (`StableDiffusionProcessing`)
+ forced_filename (`str`):
+ If specified, `basename` and filename pattern will be ignored.
+ save_to_dirs (bool):
+ If true, the image will be saved into a subdirectory of `path`.
+
+ Returns: (fullfn, txt_fullfn)
+ fullfn (`str`):
+ The full path of the saved imaged.
+ txt_fullfn (`str` or None):
+ If a text file is saved for this image, this will be its full path. Otherwise None.
+ """
+ namegen = FilenameGenerator(p, seed, prompt, image, basename=basename)
+
+ # WebP and JPG formats have maximum dimension limits of 16383 and 65535 respectively. switch to PNG which has a much higher limit
+ if (image.height > 65535 or image.width > 65535) and extension.lower() in ("jpg", "jpeg") or (image.height > 16383 or image.width > 16383) and extension.lower() == "webp":
+ print('Image dimensions too large; saving as PNG')
+ extension = "png"
+
+ if save_to_dirs is None:
+ save_to_dirs = (grid and opts.grid_save_to_dirs) or (not grid and opts.save_to_dirs and not no_prompt)
+
+ if save_to_dirs:
+ dirname = namegen.apply(opts.directories_filename_pattern or "[prompt_words]").lstrip(' ').rstrip('\\ /')
+ path = os.path.join(path, dirname)
+
+ os.makedirs(path, exist_ok=True)
+
+ if forced_filename is None:
+ if short_filename or seed is None:
+ file_decoration = ""
+ elif opts.save_to_dirs:
+ file_decoration = opts.samples_filename_pattern or "[seed]"
+ else:
+ file_decoration = opts.samples_filename_pattern or "[seed]-[prompt_spaces]"
+
+ file_decoration = namegen.apply(file_decoration) + suffix
+
+ add_number = opts.save_images_add_number or file_decoration == ''
+
+ if file_decoration != "" and add_number:
+ file_decoration = f"-{file_decoration}"
+
+ if add_number:
+ basecount = get_next_sequence_number(path, basename)
+ fullfn = None
+ for i in range(500):
+ fn = f"{basecount + i:05}" if basename == '' else f"{basename}-{basecount + i:04}"
+ fullfn = os.path.join(path, f"{fn}{file_decoration}.{extension}")
+ if not os.path.exists(fullfn):
+ break
+ else:
+ fullfn = os.path.join(path, f"{file_decoration}.{extension}")
+ else:
+ fullfn = os.path.join(path, f"{forced_filename}.{extension}")
+
+ pnginfo = existing_info or {}
+ if info is not None:
+ pnginfo[pnginfo_section_name] = info
+
+ params = script_callbacks.ImageSaveParams(image, p, fullfn, pnginfo)
+ script_callbacks.before_image_saved_callback(params)
+
+ image = params.image
+ fullfn = params.filename
+ info = params.pnginfo.get(pnginfo_section_name, None)
+
+ def _atomically_save_image(image_to_save, filename_without_extension, extension):
+ """
+ save image with .tmp extension to avoid race condition when another process detects new image in the directory
+ """
+ temp_file_path = f"{filename_without_extension}.tmp"
+
+ save_image_with_geninfo(image_to_save, info, temp_file_path, extension, existing_pnginfo=params.pnginfo, pnginfo_section_name=pnginfo_section_name)
+
+ filename = filename_without_extension + extension
+ if shared.opts.save_images_replace_action != "Replace":
+ n = 0
+ while os.path.exists(filename):
+ n += 1
+ filename = f"{filename_without_extension}-{n}{extension}"
+ os.replace(temp_file_path, filename)
+
+ fullfn_without_extension, extension = os.path.splitext(params.filename)
+ if hasattr(os, 'statvfs'):
+ max_name_len = os.statvfs(path).f_namemax
+ fullfn_without_extension = fullfn_without_extension[:max_name_len - max(4, len(extension))]
+ params.filename = fullfn_without_extension + extension
+ fullfn = params.filename
+ _atomically_save_image(image, fullfn_without_extension, extension)
+
+ image.already_saved_as = fullfn
+
+ oversize = image.width > opts.target_side_length or image.height > opts.target_side_length
+ if opts.export_for_4chan and (oversize or os.stat(fullfn).st_size > opts.img_downscale_threshold * 1024 * 1024):
+ ratio = image.width / image.height
+ resize_to = None
+ if oversize and ratio > 1:
+ resize_to = round(opts.target_side_length), round(image.height * opts.target_side_length / image.width)
+ elif oversize:
+ resize_to = round(image.width * opts.target_side_length / image.height), round(opts.target_side_length)
+
+ if resize_to is not None:
+ try:
+ # Resizing image with LANCZOS could throw an exception if e.g. image mode is I;16
+ image = image.resize(resize_to, LANCZOS)
+ except Exception:
+ image = image.resize(resize_to)
+ try:
+ _atomically_save_image(image, fullfn_without_extension, ".jpg")
+ except Exception as e:
+ errors.display(e, "saving image as downscaled JPG")
+
+ if opts.save_txt and info is not None:
+ txt_fullfn = f"{fullfn_without_extension}.txt"
+ with open(txt_fullfn, "w", encoding="utf8") as file:
+ file.write(f"{info}\n")
+ else:
+ txt_fullfn = None
+
+ script_callbacks.image_saved_callback(params)
+
+ return fullfn, txt_fullfn
+
+
+IGNORED_INFO_KEYS = {
+ 'jfif', 'jfif_version', 'jfif_unit', 'jfif_density', 'dpi', 'exif',
+ 'loop', 'background', 'timestamp', 'duration', 'progressive', 'progression',
+ 'icc_profile', 'chromaticity', 'photoshop',
+}
+
+
+def read_info_from_image(image: Image.Image) -> tuple[str | None, dict]:
+ items = (image.info or {}).copy()
+
+ geninfo = items.pop('parameters', None)
+
+ if "exif" in items:
+ exif_data = items["exif"]
+ try:
+ exif = piexif.load(exif_data)
+ except OSError:
+ # memory / exif was not valid so piexif tried to read from a file
+ exif = None
+ exif_comment = (exif or {}).get("Exif", {}).get(piexif.ExifIFD.UserComment, b'')
+ try:
+ exif_comment = piexif.helper.UserComment.load(exif_comment)
+ except ValueError:
+ exif_comment = exif_comment.decode('utf8', errors="ignore")
+
+ if exif_comment:
+ geninfo = exif_comment
+ elif "comment" in items: # for gif
+ if isinstance(items["comment"], bytes):
+ geninfo = items["comment"].decode('utf8', errors="ignore")
+ else:
+ geninfo = items["comment"]
+
+ for field in IGNORED_INFO_KEYS:
+ items.pop(field, None)
+
+ if items.get("Software", None) == "NovelAI":
+ try:
+ json_info = json.loads(items["Comment"])
+ sampler = sd_samplers.samplers_map.get(json_info["sampler"], "Euler a")
+
+ geninfo = f"""{items["Description"]}
+Negative prompt: {json_info["uc"]}
+Steps: {json_info["steps"]}, Sampler: {sampler}, CFG scale: {json_info["scale"]}, Seed: {json_info["seed"]}, Size: {image.width}x{image.height}, Clip skip: 2, ENSD: 31337"""
+ except Exception:
+ errors.report("Error parsing NovelAI image generation parameters", exc_info=True)
+
+ return geninfo, items
+
+
+def image_data(data):
+ import gradio as gr
+
+ try:
+ image = read(io.BytesIO(data))
+ textinfo, _ = read_info_from_image(image)
+ return textinfo, None
+ except Exception:
+ pass
+
+ try:
+ text = data.decode('utf8')
+ assert len(text) < 10000
+ return text, None
+
+ except Exception:
+ pass
+
+ return gr.update(), None
+
+
+def flatten(img, bgcolor):
+ """replaces transparency with bgcolor (example: "#ffffff"), returning an RGB mode image with no transparency"""
+
+ if img.mode == "RGBA":
+ background = Image.new('RGBA', img.size, bgcolor)
+ background.paste(img, mask=img)
+ img = background
+
+ return img.convert('RGB')
+
+
+def read(fp, **kwargs):
+ image = Image.open(fp, **kwargs)
+ image = fix_image(image)
+
+ return image
+
+
+def fix_image(image: Image.Image):
+ if image is None:
+ return None
+
+ try:
+ image = ImageOps.exif_transpose(image)
+ image = fix_png_transparency(image)
+ except Exception:
+ pass
+
+ return image
+
+
+def fix_png_transparency(image: Image.Image):
+ if image.mode not in ("RGB", "P") or not isinstance(image.info.get("transparency"), bytes):
+ return image
+
+ image = image.convert("RGBA")
+ return image
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/images.py |
Add standardized docstrings across the file | ### This file contains impls for underlying related models (CLIP, T5, etc)
import torch
import math
from torch import nn
from transformers import CLIPTokenizer, T5TokenizerFast
from modules import sd_hijack
#################################################################################################
### Core/Utility
#################################################################################################
class AutocastLinear(nn.Linear):
def forward(self, x):
return torch.nn.functional.linear(x, self.weight.to(x.dtype), self.bias.to(x.dtype) if self.bias is not None else None)
def attention(q, k, v, heads, mask=None):
b, _, dim_head = q.shape
dim_head //= heads
q, k, v = [t.view(b, -1, heads, dim_head).transpose(1, 2) for t in (q, k, v)]
out = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False)
return out.transpose(1, 2).reshape(b, -1, heads * dim_head)
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, bias=True, dtype=None, device=None):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features, bias=bias, dtype=dtype, device=device)
self.act = act_layer
self.fc2 = nn.Linear(hidden_features, out_features, bias=bias, dtype=dtype, device=device)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.fc2(x)
return x
#################################################################################################
### CLIP
#################################################################################################
class CLIPAttention(torch.nn.Module):
def __init__(self, embed_dim, heads, dtype, device):
super().__init__()
self.heads = heads
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=True, dtype=dtype, device=device)
def forward(self, x, mask=None):
q = self.q_proj(x)
k = self.k_proj(x)
v = self.v_proj(x)
out = attention(q, k, v, self.heads, mask)
return self.out_proj(out)
ACTIVATIONS = {
"quick_gelu": lambda a: a * torch.sigmoid(1.702 * a),
"gelu": torch.nn.functional.gelu,
}
class CLIPLayer(torch.nn.Module):
def __init__(self, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device):
super().__init__()
self.layer_norm1 = nn.LayerNorm(embed_dim, dtype=dtype, device=device)
self.self_attn = CLIPAttention(embed_dim, heads, dtype, device)
self.layer_norm2 = nn.LayerNorm(embed_dim, dtype=dtype, device=device)
#self.mlp = CLIPMLP(embed_dim, intermediate_size, intermediate_activation, dtype, device)
self.mlp = Mlp(embed_dim, intermediate_size, embed_dim, act_layer=ACTIVATIONS[intermediate_activation], dtype=dtype, device=device)
def forward(self, x, mask=None):
x += self.self_attn(self.layer_norm1(x), mask)
x += self.mlp(self.layer_norm2(x))
return x
class CLIPEncoder(torch.nn.Module):
def __init__(self, num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device):
super().__init__()
self.layers = torch.nn.ModuleList([CLIPLayer(embed_dim, heads, intermediate_size, intermediate_activation, dtype, device) for i in range(num_layers)])
def forward(self, x, mask=None, intermediate_output=None):
if intermediate_output is not None:
if intermediate_output < 0:
intermediate_output = len(self.layers) + intermediate_output
intermediate = None
for i, layer in enumerate(self.layers):
x = layer(x, mask)
if i == intermediate_output:
intermediate = x.clone()
return x, intermediate
class CLIPEmbeddings(torch.nn.Module):
def __init__(self, embed_dim, vocab_size=49408, num_positions=77, dtype=None, device=None, textual_inversion_key="clip_l"):
super().__init__()
self.token_embedding = sd_hijack.TextualInversionEmbeddings(vocab_size, embed_dim, dtype=dtype, device=device, textual_inversion_key=textual_inversion_key)
self.position_embedding = torch.nn.Embedding(num_positions, embed_dim, dtype=dtype, device=device)
def forward(self, input_tokens):
return self.token_embedding(input_tokens) + self.position_embedding.weight
class CLIPTextModel_(torch.nn.Module):
def __init__(self, config_dict, dtype, device):
num_layers = config_dict["num_hidden_layers"]
embed_dim = config_dict["hidden_size"]
heads = config_dict["num_attention_heads"]
intermediate_size = config_dict["intermediate_size"]
intermediate_activation = config_dict["hidden_act"]
super().__init__()
self.embeddings = CLIPEmbeddings(embed_dim, dtype=torch.float32, device=device, textual_inversion_key=config_dict.get('textual_inversion_key', 'clip_l'))
self.encoder = CLIPEncoder(num_layers, embed_dim, heads, intermediate_size, intermediate_activation, dtype, device)
self.final_layer_norm = nn.LayerNorm(embed_dim, dtype=dtype, device=device)
def forward(self, input_tokens, intermediate_output=None, final_layer_norm_intermediate=True):
x = self.embeddings(input_tokens)
causal_mask = torch.empty(x.shape[1], x.shape[1], dtype=x.dtype, device=x.device).fill_(float("-inf")).triu_(1)
x, i = self.encoder(x, mask=causal_mask, intermediate_output=intermediate_output)
x = self.final_layer_norm(x)
if i is not None and final_layer_norm_intermediate:
i = self.final_layer_norm(i)
pooled_output = x[torch.arange(x.shape[0], device=x.device), input_tokens.to(dtype=torch.int, device=x.device).argmax(dim=-1),]
return x, i, pooled_output
class CLIPTextModel(torch.nn.Module):
def __init__(self, config_dict, dtype, device):
super().__init__()
self.num_layers = config_dict["num_hidden_layers"]
self.text_model = CLIPTextModel_(config_dict, dtype, device)
embed_dim = config_dict["hidden_size"]
self.text_projection = nn.Linear(embed_dim, embed_dim, bias=False, dtype=dtype, device=device)
self.text_projection.weight.copy_(torch.eye(embed_dim))
self.dtype = dtype
def get_input_embeddings(self):
return self.text_model.embeddings.token_embedding
def set_input_embeddings(self, embeddings):
self.text_model.embeddings.token_embedding = embeddings
def forward(self, *args, **kwargs):
x = self.text_model(*args, **kwargs)
out = self.text_projection(x[2])
return (x[0], x[1], out, x[2])
class SDTokenizer:
def __init__(self, max_length=77, pad_with_end=True, tokenizer=None, has_start_token=True, pad_to_max_length=True, min_length=None):
self.tokenizer = tokenizer
self.max_length = max_length
self.min_length = min_length
empty = self.tokenizer('')["input_ids"]
if has_start_token:
self.tokens_start = 1
self.start_token = empty[0]
self.end_token = empty[1]
else:
self.tokens_start = 0
self.start_token = None
self.end_token = empty[0]
self.pad_with_end = pad_with_end
self.pad_to_max_length = pad_to_max_length
vocab = self.tokenizer.get_vocab()
self.inv_vocab = {v: k for k, v in vocab.items()}
self.max_word_length = 8
def tokenize_with_weights(self, text:str):
if self.pad_with_end:
pad_token = self.end_token
else:
pad_token = 0
batch = []
if self.start_token is not None:
batch.append((self.start_token, 1.0))
to_tokenize = text.replace("\n", " ").split(' ')
to_tokenize = [x for x in to_tokenize if x != ""]
for word in to_tokenize:
batch.extend([(t, 1) for t in self.tokenizer(word)["input_ids"][self.tokens_start:-1]])
batch.append((self.end_token, 1.0))
if self.pad_to_max_length:
batch.extend([(pad_token, 1.0)] * (self.max_length - len(batch)))
if self.min_length is not None and len(batch) < self.min_length:
batch.extend([(pad_token, 1.0)] * (self.min_length - len(batch)))
return [batch]
class SDXLClipGTokenizer(SDTokenizer):
def __init__(self, tokenizer):
super().__init__(pad_with_end=False, tokenizer=tokenizer)
class SD3Tokenizer:
def __init__(self):
clip_tokenizer = CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
self.clip_l = SDTokenizer(tokenizer=clip_tokenizer)
self.clip_g = SDXLClipGTokenizer(clip_tokenizer)
self.t5xxl = T5XXLTokenizer()
def tokenize_with_weights(self, text:str):
out = {}
out["g"] = self.clip_g.tokenize_with_weights(text)
out["l"] = self.clip_l.tokenize_with_weights(text)
out["t5xxl"] = self.t5xxl.tokenize_with_weights(text)
return out
class ClipTokenWeightEncoder:
def encode_token_weights(self, token_weight_pairs):
tokens = [a[0] for a in token_weight_pairs[0]]
out, pooled = self([tokens])
if pooled is not None:
first_pooled = pooled[0:1].cpu()
else:
first_pooled = pooled
output = [out[0:1]]
return torch.cat(output, dim=-2).cpu(), first_pooled
class SDClipModel(torch.nn.Module, ClipTokenWeightEncoder):
LAYERS = ["last", "pooled", "hidden"]
def __init__(self, device="cpu", max_length=77, layer="last", layer_idx=None, textmodel_json_config=None, dtype=None, model_class=CLIPTextModel,
special_tokens=None, layer_norm_hidden_state=True, return_projected_pooled=True):
super().__init__()
assert layer in self.LAYERS
self.transformer = model_class(textmodel_json_config, dtype, device)
self.num_layers = self.transformer.num_layers
self.max_length = max_length
self.transformer = self.transformer.eval()
for param in self.parameters():
param.requires_grad = False
self.layer = layer
self.layer_idx = None
self.special_tokens = special_tokens if special_tokens is not None else {"start": 49406, "end": 49407, "pad": 49407}
self.logit_scale = torch.nn.Parameter(torch.tensor(4.6055))
self.layer_norm_hidden_state = layer_norm_hidden_state
self.return_projected_pooled = return_projected_pooled
if layer == "hidden":
assert layer_idx is not None
assert abs(layer_idx) < self.num_layers
self.set_clip_options({"layer": layer_idx})
self.options_default = (self.layer, self.layer_idx, self.return_projected_pooled)
def set_clip_options(self, options):
layer_idx = options.get("layer", self.layer_idx)
self.return_projected_pooled = options.get("projected_pooled", self.return_projected_pooled)
if layer_idx is None or abs(layer_idx) > self.num_layers:
self.layer = "last"
else:
self.layer = "hidden"
self.layer_idx = layer_idx
def forward(self, tokens):
backup_embeds = self.transformer.get_input_embeddings()
tokens = torch.asarray(tokens, dtype=torch.int64, device=backup_embeds.weight.device)
outputs = self.transformer(tokens, intermediate_output=self.layer_idx, final_layer_norm_intermediate=self.layer_norm_hidden_state)
self.transformer.set_input_embeddings(backup_embeds)
if self.layer == "last":
z = outputs[0]
else:
z = outputs[1]
pooled_output = None
if len(outputs) >= 3:
if not self.return_projected_pooled and len(outputs) >= 4 and outputs[3] is not None:
pooled_output = outputs[3].float()
elif outputs[2] is not None:
pooled_output = outputs[2].float()
return z.float(), pooled_output
class SDXLClipG(SDClipModel):
def __init__(self, config, device="cpu", layer="penultimate", layer_idx=None, dtype=None):
if layer == "penultimate":
layer="hidden"
layer_idx=-2
super().__init__(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config=config, dtype=dtype, special_tokens={"start": 49406, "end": 49407, "pad": 0}, layer_norm_hidden_state=False)
class T5XXLModel(SDClipModel):
def __init__(self, config, device="cpu", layer="last", layer_idx=None, dtype=None):
super().__init__(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config=config, dtype=dtype, special_tokens={"end": 1, "pad": 0}, model_class=T5)
#################################################################################################
### T5 implementation, for the T5-XXL text encoder portion, largely pulled from upstream impl
#################################################################################################
class T5XXLTokenizer(SDTokenizer):
def __init__(self):
super().__init__(pad_with_end=False, tokenizer=T5TokenizerFast.from_pretrained("google/t5-v1_1-xxl"), has_start_token=False, pad_to_max_length=False, max_length=99999999, min_length=77)
class T5LayerNorm(torch.nn.Module):
def __init__(self, hidden_size, eps=1e-6, dtype=None, device=None):
super().__init__()
self.weight = torch.nn.Parameter(torch.ones(hidden_size, dtype=dtype, device=device))
self.variance_epsilon = eps
def forward(self, x):
variance = x.pow(2).mean(-1, keepdim=True)
x = x * torch.rsqrt(variance + self.variance_epsilon)
return self.weight.to(device=x.device, dtype=x.dtype) * x
class T5DenseGatedActDense(torch.nn.Module):
def __init__(self, model_dim, ff_dim, dtype, device):
super().__init__()
self.wi_0 = AutocastLinear(model_dim, ff_dim, bias=False, dtype=dtype, device=device)
self.wi_1 = AutocastLinear(model_dim, ff_dim, bias=False, dtype=dtype, device=device)
self.wo = AutocastLinear(ff_dim, model_dim, bias=False, dtype=dtype, device=device)
def forward(self, x):
hidden_gelu = torch.nn.functional.gelu(self.wi_0(x), approximate="tanh")
hidden_linear = self.wi_1(x)
x = hidden_gelu * hidden_linear
x = self.wo(x)
return x
class T5LayerFF(torch.nn.Module):
def __init__(self, model_dim, ff_dim, dtype, device):
super().__init__()
self.DenseReluDense = T5DenseGatedActDense(model_dim, ff_dim, dtype, device)
self.layer_norm = T5LayerNorm(model_dim, dtype=dtype, device=device)
def forward(self, x):
forwarded_states = self.layer_norm(x)
forwarded_states = self.DenseReluDense(forwarded_states)
x += forwarded_states
return x
class T5Attention(torch.nn.Module):
def __init__(self, model_dim, inner_dim, num_heads, relative_attention_bias, dtype, device):
super().__init__()
# Mesh TensorFlow initialization to avoid scaling before softmax
self.q = AutocastLinear(model_dim, inner_dim, bias=False, dtype=dtype, device=device)
self.k = AutocastLinear(model_dim, inner_dim, bias=False, dtype=dtype, device=device)
self.v = AutocastLinear(model_dim, inner_dim, bias=False, dtype=dtype, device=device)
self.o = AutocastLinear(inner_dim, model_dim, bias=False, dtype=dtype, device=device)
self.num_heads = num_heads
self.relative_attention_bias = None
if relative_attention_bias:
self.relative_attention_num_buckets = 32
self.relative_attention_max_distance = 128
self.relative_attention_bias = torch.nn.Embedding(self.relative_attention_num_buckets, self.num_heads, device=device)
@staticmethod
def _relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128):
relative_buckets = 0
if bidirectional:
num_buckets //= 2
relative_buckets += (relative_position > 0).to(torch.long) * num_buckets
relative_position = torch.abs(relative_position)
else:
relative_position = -torch.min(relative_position, torch.zeros_like(relative_position))
# now relative_position is in the range [0, inf)
# half of the buckets are for exact increments in positions
max_exact = num_buckets // 2
is_small = relative_position < max_exact
# The other half of the buckets are for logarithmically bigger bins in positions up to max_distance
relative_position_if_large = max_exact + (
torch.log(relative_position.float() / max_exact)
/ math.log(max_distance / max_exact)
* (num_buckets - max_exact)
).to(torch.long)
relative_position_if_large = torch.min(relative_position_if_large, torch.full_like(relative_position_if_large, num_buckets - 1))
relative_buckets += torch.where(is_small, relative_position, relative_position_if_large)
return relative_buckets
def compute_bias(self, query_length, key_length, device):
context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
relative_position = memory_position - context_position # shape (query_length, key_length)
relative_position_bucket = self._relative_position_bucket(
relative_position, # shape (query_length, key_length)
bidirectional=True,
num_buckets=self.relative_attention_num_buckets,
max_distance=self.relative_attention_max_distance,
)
values = self.relative_attention_bias(relative_position_bucket) # shape (query_length, key_length, num_heads)
values = values.permute([2, 0, 1]).unsqueeze(0) # shape (1, num_heads, query_length, key_length)
return values
def forward(self, x, past_bias=None):
q = self.q(x)
k = self.k(x)
v = self.v(x)
if self.relative_attention_bias is not None:
past_bias = self.compute_bias(x.shape[1], x.shape[1], x.device)
if past_bias is not None:
mask = past_bias
else:
mask = None
out = attention(q, k * ((k.shape[-1] / self.num_heads) ** 0.5), v, self.num_heads, mask.to(x.dtype) if mask is not None else None)
return self.o(out), past_bias
class T5LayerSelfAttention(torch.nn.Module):
def __init__(self, model_dim, inner_dim, ff_dim, num_heads, relative_attention_bias, dtype, device):
super().__init__()
self.SelfAttention = T5Attention(model_dim, inner_dim, num_heads, relative_attention_bias, dtype, device)
self.layer_norm = T5LayerNorm(model_dim, dtype=dtype, device=device)
def forward(self, x, past_bias=None):
output, past_bias = self.SelfAttention(self.layer_norm(x), past_bias=past_bias)
x += output
return x, past_bias
class T5Block(torch.nn.Module):
def __init__(self, model_dim, inner_dim, ff_dim, num_heads, relative_attention_bias, dtype, device):
super().__init__()
self.layer = torch.nn.ModuleList()
self.layer.append(T5LayerSelfAttention(model_dim, inner_dim, ff_dim, num_heads, relative_attention_bias, dtype, device))
self.layer.append(T5LayerFF(model_dim, ff_dim, dtype, device))
def forward(self, x, past_bias=None):
x, past_bias = self.layer[0](x, past_bias)
x = self.layer[-1](x)
return x, past_bias
class T5Stack(torch.nn.Module):
def __init__(self, num_layers, model_dim, inner_dim, ff_dim, num_heads, vocab_size, dtype, device):
super().__init__()
self.embed_tokens = torch.nn.Embedding(vocab_size, model_dim, device=device)
self.block = torch.nn.ModuleList([T5Block(model_dim, inner_dim, ff_dim, num_heads, relative_attention_bias=(i == 0), dtype=dtype, device=device) for i in range(num_layers)])
self.final_layer_norm = T5LayerNorm(model_dim, dtype=dtype, device=device)
def forward(self, input_ids, intermediate_output=None, final_layer_norm_intermediate=True):
intermediate = None
x = self.embed_tokens(input_ids).to(torch.float32) # needs float32 or else T5 returns all zeroes
past_bias = None
for i, layer in enumerate(self.block):
x, past_bias = layer(x, past_bias)
if i == intermediate_output:
intermediate = x.clone()
x = self.final_layer_norm(x)
if intermediate is not None and final_layer_norm_intermediate:
intermediate = self.final_layer_norm(intermediate)
return x, intermediate
class T5(torch.nn.Module):
def __init__(self, config_dict, dtype, device):
super().__init__()
self.num_layers = config_dict["num_layers"]
self.encoder = T5Stack(self.num_layers, config_dict["d_model"], config_dict["d_model"], config_dict["d_ff"], config_dict["num_heads"], config_dict["vocab_size"], dtype, device)
self.dtype = dtype
def get_input_embeddings(self):
return self.encoder.embed_tokens
def set_input_embeddings(self, embeddings):
self.encoder.embed_tokens = embeddings
def forward(self, *args, **kwargs):
return self.encoder(*args, **kwargs) | --- +++ @@ -14,12 +14,19 @@
class AutocastLinear(nn.Linear):
+ """Same as usual linear layer, but casts its weights to whatever the parameter type is.
+
+ This is different from torch.autocast in a way that float16 layer processing float32 input
+ will return float16 with autocast on, and float32 with this. T5 seems to be fucked
+ if you do it in full float16 (returning almost all zeros in the final output).
+ """
def forward(self, x):
return torch.nn.functional.linear(x, self.weight.to(x.dtype), self.bias.to(x.dtype) if self.bias is not None else None)
def attention(q, k, v, heads, mask=None):
+ """Convenience wrapper around a basic attention operation"""
b, _, dim_head = q.shape
dim_head //= heads
q, k, v = [t.view(b, -1, heads, dim_head).transpose(1, 2) for t in (q, k, v)]
@@ -28,6 +35,7 @@
class Mlp(nn.Module):
+ """ MLP as used in Vision Transformer, MLP-Mixer and related networks"""
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, bias=True, dtype=None, device=None):
super().__init__()
out_features = out_features or in_features
@@ -180,6 +188,7 @@
def tokenize_with_weights(self, text:str):
+ """Tokenize the text, with weight values - presume 1.0 for all and ignore other features here. The details aren't relevant for a reference impl, and weights themselves has weak effect on SD3."""
if self.pad_with_end:
pad_token = self.end_token
else:
@@ -232,6 +241,7 @@
class SDClipModel(torch.nn.Module, ClipTokenWeightEncoder):
+ """Uses the CLIP transformer encoder for text (from huggingface)"""
LAYERS = ["last", "pooled", "hidden"]
def __init__(self, device="cpu", max_length=77, layer="last", layer_idx=None, textmodel_json_config=None, dtype=None, model_class=CLIPTextModel,
special_tokens=None, layer_norm_hidden_state=True, return_projected_pooled=True):
@@ -283,6 +293,7 @@
class SDXLClipG(SDClipModel):
+ """Wraps the CLIP-G model into the SD-CLIP-Model interface"""
def __init__(self, config, device="cpu", layer="penultimate", layer_idx=None, dtype=None):
if layer == "penultimate":
layer="hidden"
@@ -291,6 +302,7 @@
class T5XXLModel(SDClipModel):
+ """Wraps the T5-XXL model into the SD-CLIP-Model interface for convenience"""
def __init__(self, config, device="cpu", layer="last", layer_idx=None, dtype=None):
super().__init__(device=device, layer=layer, layer_idx=layer_idx, textmodel_json_config=config, dtype=dtype, special_tokens={"end": 1, "pad": 0}, model_class=T5)
@@ -300,6 +312,7 @@ #################################################################################################
class T5XXLTokenizer(SDTokenizer):
+ """Wraps the T5 Tokenizer from HF into the SDTokenizer interface"""
def __init__(self):
super().__init__(pad_with_end=False, tokenizer=T5TokenizerFast.from_pretrained("google/t5-v1_1-xxl"), has_start_token=False, pad_to_max_length=False, max_length=99999999, min_length=77)
@@ -361,6 +374,26 @@
@staticmethod
def _relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128):
+ """
+ Adapted from Mesh Tensorflow:
+ https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
+
+ Translate relative position to a bucket number for relative attention. The relative position is defined as
+ memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
+ position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for
+ small absolute relative_position and larger buckets for larger absolute relative_positions. All relative
+ positions >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket.
+ This should allow for more graceful generalization to longer sequences than the model has been trained on
+
+ Args:
+ relative_position: an int32 Tensor
+ bidirectional: a boolean - whether the attention is bidirectional
+ num_buckets: an integer
+ max_distance: an integer
+
+ Returns:
+ a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
+ """
relative_buckets = 0
if bidirectional:
num_buckets //= 2
@@ -383,6 +416,7 @@ return relative_buckets
def compute_bias(self, query_length, key_length, device):
+ """Compute binned relative position bias"""
context_position = torch.arange(query_length, dtype=torch.long, device=device)[:, None]
memory_position = torch.arange(key_length, dtype=torch.long, device=device)[None, :]
relative_position = memory_position - context_position # shape (query_length, key_length)
@@ -473,4 +507,4 @@ self.encoder.embed_tokens = embeddings
def forward(self, *args, **kwargs):
- return self.encoder(*args, **kwargs)+ return self.encoder(*args, **kwargs)
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/models/sd3/other_impls.py |
Improve my code by adding docstrings | import json
import os
import signal
import sys
import re
from modules.timer import startup_timer
def gradio_server_name():
from modules.shared_cmd_options import cmd_opts
if cmd_opts.server_name:
return cmd_opts.server_name
else:
return "0.0.0.0" if cmd_opts.listen else None
def fix_torch_version():
import torch
# Truncate version number of nightly/local build of PyTorch to not cause exceptions with CodeFormer or Safetensors
if ".dev" in torch.__version__ or "+git" in torch.__version__:
torch.__long_version__ = torch.__version__
torch.__version__ = re.search(r'[\d.]+[\d]', torch.__version__).group(0)
def fix_pytorch_lightning():
# Checks if pytorch_lightning.utilities.distributed already exists in the sys.modules cache
if 'pytorch_lightning.utilities.distributed' not in sys.modules:
import pytorch_lightning
# Lets the user know that the library was not found and then will set it to pytorch_lightning.utilities.rank_zero
print("Pytorch_lightning.distributed not found, attempting pytorch_lightning.rank_zero")
sys.modules["pytorch_lightning.utilities.distributed"] = pytorch_lightning.utilities.rank_zero
def fix_asyncio_event_loop_policy():
import asyncio
if sys.platform == "win32" and hasattr(asyncio, "WindowsSelectorEventLoopPolicy"):
# "Any thread" and "selector" should be orthogonal, but there's not a clean
# interface for composing policies so pick the right base.
_BasePolicy = asyncio.WindowsSelectorEventLoopPolicy # type: ignore
else:
_BasePolicy = asyncio.DefaultEventLoopPolicy
class AnyThreadEventLoopPolicy(_BasePolicy): # type: ignore
def get_event_loop(self) -> asyncio.AbstractEventLoop:
try:
return super().get_event_loop()
except (RuntimeError, AssertionError):
# This was an AssertionError in python 3.4.2 (which ships with debian jessie)
# and changed to a RuntimeError in 3.4.3.
# "There is no current event loop in thread %r"
loop = self.new_event_loop()
self.set_event_loop(loop)
return loop
asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())
def restore_config_state_file():
from modules import shared, config_states
config_state_file = shared.opts.restore_config_state_file
if config_state_file == "":
return
shared.opts.restore_config_state_file = ""
shared.opts.save(shared.config_filename)
if os.path.isfile(config_state_file):
print(f"*** About to restore extension state from file: {config_state_file}")
with open(config_state_file, "r", encoding="utf-8") as f:
config_state = json.load(f)
config_states.restore_extension_config(config_state)
startup_timer.record("restore extension config")
elif config_state_file:
print(f"!!! Config state backup not found: {config_state_file}")
def validate_tls_options():
from modules.shared_cmd_options import cmd_opts
if not (cmd_opts.tls_keyfile and cmd_opts.tls_certfile):
return
try:
if not os.path.exists(cmd_opts.tls_keyfile):
print("Invalid path to TLS keyfile given")
if not os.path.exists(cmd_opts.tls_certfile):
print(f"Invalid path to TLS certfile: '{cmd_opts.tls_certfile}'")
except TypeError:
cmd_opts.tls_keyfile = cmd_opts.tls_certfile = None
print("TLS setup invalid, running webui without TLS")
else:
print("Running with TLS")
startup_timer.record("TLS")
def get_gradio_auth_creds():
from modules.shared_cmd_options import cmd_opts
def process_credential_line(s):
s = s.strip()
if not s:
return None
return tuple(s.split(':', 1))
if cmd_opts.gradio_auth:
for cred in cmd_opts.gradio_auth.split(','):
cred = process_credential_line(cred)
if cred:
yield cred
if cmd_opts.gradio_auth_path:
with open(cmd_opts.gradio_auth_path, 'r', encoding="utf8") as file:
for line in file.readlines():
for cred in line.strip().split(','):
cred = process_credential_line(cred)
if cred:
yield cred
def dumpstacks():
import threading
import traceback
id2name = {th.ident: th.name for th in threading.enumerate()}
code = []
for threadId, stack in sys._current_frames().items():
code.append(f"\n# Thread: {id2name.get(threadId, '')}({threadId})")
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append(f"""File: "{filename}", line {lineno}, in {name}""")
if line:
code.append(" " + line.strip())
print("\n".join(code))
def configure_sigint_handler():
# make the program just exit at ctrl+c without waiting for anything
from modules import shared
def sigint_handler(sig, frame):
print(f'Interrupted with signal {sig} in {frame}')
if shared.opts.dump_stacks_on_signal:
dumpstacks()
os._exit(0)
if not os.environ.get("COVERAGE_RUN"):
# Don't install the immediate-quit handler when running under coverage,
# as then the coverage report won't be generated.
signal.signal(signal.SIGINT, sigint_handler)
def configure_opts_onchange():
from modules import shared, sd_models, sd_vae, ui_tempdir, sd_hijack
from modules.call_queue import wrap_queued_call
shared.opts.onchange("sd_model_checkpoint", wrap_queued_call(lambda: sd_models.reload_model_weights()), call=False)
shared.opts.onchange("sd_vae", wrap_queued_call(lambda: sd_vae.reload_vae_weights()), call=False)
shared.opts.onchange("sd_vae_overrides_per_model_preferences", wrap_queued_call(lambda: sd_vae.reload_vae_weights()), call=False)
shared.opts.onchange("temp_dir", ui_tempdir.on_tmpdir_changed)
shared.opts.onchange("gradio_theme", shared.reload_gradio_theme)
shared.opts.onchange("cross_attention_optimization", wrap_queued_call(lambda: sd_hijack.model_hijack.redo_hijack(shared.sd_model)), call=False)
shared.opts.onchange("fp8_storage", wrap_queued_call(lambda: sd_models.reload_model_weights()), call=False)
shared.opts.onchange("cache_fp16_weight", wrap_queued_call(lambda: sd_models.reload_model_weights(forced_reload=True)), call=False)
startup_timer.record("opts onchange")
def setup_middleware(app):
from starlette.middleware.gzip import GZipMiddleware
app.middleware_stack = None # reset current middleware to allow modifying user provided list
app.add_middleware(GZipMiddleware, minimum_size=1000)
configure_cors_middleware(app)
app.build_middleware_stack() # rebuild middleware stack on-the-fly
def configure_cors_middleware(app):
from starlette.middleware.cors import CORSMiddleware
from modules.shared_cmd_options import cmd_opts
cors_options = {
"allow_methods": ["*"],
"allow_headers": ["*"],
"allow_credentials": True,
}
if cmd_opts.cors_allow_origins:
cors_options["allow_origins"] = cmd_opts.cors_allow_origins.split(',')
if cmd_opts.cors_allow_origins_regex:
cors_options["allow_origin_regex"] = cmd_opts.cors_allow_origins_regex
app.add_middleware(CORSMiddleware, **cors_options)
| --- +++ @@ -1,197 +1,215 @@-import json
-import os
-import signal
-import sys
-import re
-
-from modules.timer import startup_timer
-
-
-def gradio_server_name():
- from modules.shared_cmd_options import cmd_opts
-
- if cmd_opts.server_name:
- return cmd_opts.server_name
- else:
- return "0.0.0.0" if cmd_opts.listen else None
-
-
-def fix_torch_version():
- import torch
-
- # Truncate version number of nightly/local build of PyTorch to not cause exceptions with CodeFormer or Safetensors
- if ".dev" in torch.__version__ or "+git" in torch.__version__:
- torch.__long_version__ = torch.__version__
- torch.__version__ = re.search(r'[\d.]+[\d]', torch.__version__).group(0)
-
-def fix_pytorch_lightning():
- # Checks if pytorch_lightning.utilities.distributed already exists in the sys.modules cache
- if 'pytorch_lightning.utilities.distributed' not in sys.modules:
- import pytorch_lightning
- # Lets the user know that the library was not found and then will set it to pytorch_lightning.utilities.rank_zero
- print("Pytorch_lightning.distributed not found, attempting pytorch_lightning.rank_zero")
- sys.modules["pytorch_lightning.utilities.distributed"] = pytorch_lightning.utilities.rank_zero
-
-def fix_asyncio_event_loop_policy():
-
- import asyncio
-
- if sys.platform == "win32" and hasattr(asyncio, "WindowsSelectorEventLoopPolicy"):
- # "Any thread" and "selector" should be orthogonal, but there's not a clean
- # interface for composing policies so pick the right base.
- _BasePolicy = asyncio.WindowsSelectorEventLoopPolicy # type: ignore
- else:
- _BasePolicy = asyncio.DefaultEventLoopPolicy
-
- class AnyThreadEventLoopPolicy(_BasePolicy): # type: ignore
-
- def get_event_loop(self) -> asyncio.AbstractEventLoop:
- try:
- return super().get_event_loop()
- except (RuntimeError, AssertionError):
- # This was an AssertionError in python 3.4.2 (which ships with debian jessie)
- # and changed to a RuntimeError in 3.4.3.
- # "There is no current event loop in thread %r"
- loop = self.new_event_loop()
- self.set_event_loop(loop)
- return loop
-
- asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())
-
-
-def restore_config_state_file():
- from modules import shared, config_states
-
- config_state_file = shared.opts.restore_config_state_file
- if config_state_file == "":
- return
-
- shared.opts.restore_config_state_file = ""
- shared.opts.save(shared.config_filename)
-
- if os.path.isfile(config_state_file):
- print(f"*** About to restore extension state from file: {config_state_file}")
- with open(config_state_file, "r", encoding="utf-8") as f:
- config_state = json.load(f)
- config_states.restore_extension_config(config_state)
- startup_timer.record("restore extension config")
- elif config_state_file:
- print(f"!!! Config state backup not found: {config_state_file}")
-
-
-def validate_tls_options():
- from modules.shared_cmd_options import cmd_opts
-
- if not (cmd_opts.tls_keyfile and cmd_opts.tls_certfile):
- return
-
- try:
- if not os.path.exists(cmd_opts.tls_keyfile):
- print("Invalid path to TLS keyfile given")
- if not os.path.exists(cmd_opts.tls_certfile):
- print(f"Invalid path to TLS certfile: '{cmd_opts.tls_certfile}'")
- except TypeError:
- cmd_opts.tls_keyfile = cmd_opts.tls_certfile = None
- print("TLS setup invalid, running webui without TLS")
- else:
- print("Running with TLS")
- startup_timer.record("TLS")
-
-
-def get_gradio_auth_creds():
- from modules.shared_cmd_options import cmd_opts
-
- def process_credential_line(s):
- s = s.strip()
- if not s:
- return None
- return tuple(s.split(':', 1))
-
- if cmd_opts.gradio_auth:
- for cred in cmd_opts.gradio_auth.split(','):
- cred = process_credential_line(cred)
- if cred:
- yield cred
-
- if cmd_opts.gradio_auth_path:
- with open(cmd_opts.gradio_auth_path, 'r', encoding="utf8") as file:
- for line in file.readlines():
- for cred in line.strip().split(','):
- cred = process_credential_line(cred)
- if cred:
- yield cred
-
-
-def dumpstacks():
- import threading
- import traceback
-
- id2name = {th.ident: th.name for th in threading.enumerate()}
- code = []
- for threadId, stack in sys._current_frames().items():
- code.append(f"\n# Thread: {id2name.get(threadId, '')}({threadId})")
- for filename, lineno, name, line in traceback.extract_stack(stack):
- code.append(f"""File: "{filename}", line {lineno}, in {name}""")
- if line:
- code.append(" " + line.strip())
-
- print("\n".join(code))
-
-
-def configure_sigint_handler():
- # make the program just exit at ctrl+c without waiting for anything
-
- from modules import shared
-
- def sigint_handler(sig, frame):
- print(f'Interrupted with signal {sig} in {frame}')
-
- if shared.opts.dump_stacks_on_signal:
- dumpstacks()
-
- os._exit(0)
-
- if not os.environ.get("COVERAGE_RUN"):
- # Don't install the immediate-quit handler when running under coverage,
- # as then the coverage report won't be generated.
- signal.signal(signal.SIGINT, sigint_handler)
-
-
-def configure_opts_onchange():
- from modules import shared, sd_models, sd_vae, ui_tempdir, sd_hijack
- from modules.call_queue import wrap_queued_call
-
- shared.opts.onchange("sd_model_checkpoint", wrap_queued_call(lambda: sd_models.reload_model_weights()), call=False)
- shared.opts.onchange("sd_vae", wrap_queued_call(lambda: sd_vae.reload_vae_weights()), call=False)
- shared.opts.onchange("sd_vae_overrides_per_model_preferences", wrap_queued_call(lambda: sd_vae.reload_vae_weights()), call=False)
- shared.opts.onchange("temp_dir", ui_tempdir.on_tmpdir_changed)
- shared.opts.onchange("gradio_theme", shared.reload_gradio_theme)
- shared.opts.onchange("cross_attention_optimization", wrap_queued_call(lambda: sd_hijack.model_hijack.redo_hijack(shared.sd_model)), call=False)
- shared.opts.onchange("fp8_storage", wrap_queued_call(lambda: sd_models.reload_model_weights()), call=False)
- shared.opts.onchange("cache_fp16_weight", wrap_queued_call(lambda: sd_models.reload_model_weights(forced_reload=True)), call=False)
- startup_timer.record("opts onchange")
-
-
-def setup_middleware(app):
- from starlette.middleware.gzip import GZipMiddleware
-
- app.middleware_stack = None # reset current middleware to allow modifying user provided list
- app.add_middleware(GZipMiddleware, minimum_size=1000)
- configure_cors_middleware(app)
- app.build_middleware_stack() # rebuild middleware stack on-the-fly
-
-
-def configure_cors_middleware(app):
- from starlette.middleware.cors import CORSMiddleware
- from modules.shared_cmd_options import cmd_opts
-
- cors_options = {
- "allow_methods": ["*"],
- "allow_headers": ["*"],
- "allow_credentials": True,
- }
- if cmd_opts.cors_allow_origins:
- cors_options["allow_origins"] = cmd_opts.cors_allow_origins.split(',')
- if cmd_opts.cors_allow_origins_regex:
- cors_options["allow_origin_regex"] = cmd_opts.cors_allow_origins_regex
- app.add_middleware(CORSMiddleware, **cors_options)
+import json
+import os
+import signal
+import sys
+import re
+
+from modules.timer import startup_timer
+
+
+def gradio_server_name():
+ from modules.shared_cmd_options import cmd_opts
+
+ if cmd_opts.server_name:
+ return cmd_opts.server_name
+ else:
+ return "0.0.0.0" if cmd_opts.listen else None
+
+
+def fix_torch_version():
+ import torch
+
+ # Truncate version number of nightly/local build of PyTorch to not cause exceptions with CodeFormer or Safetensors
+ if ".dev" in torch.__version__ or "+git" in torch.__version__:
+ torch.__long_version__ = torch.__version__
+ torch.__version__ = re.search(r'[\d.]+[\d]', torch.__version__).group(0)
+
+def fix_pytorch_lightning():
+ # Checks if pytorch_lightning.utilities.distributed already exists in the sys.modules cache
+ if 'pytorch_lightning.utilities.distributed' not in sys.modules:
+ import pytorch_lightning
+ # Lets the user know that the library was not found and then will set it to pytorch_lightning.utilities.rank_zero
+ print("Pytorch_lightning.distributed not found, attempting pytorch_lightning.rank_zero")
+ sys.modules["pytorch_lightning.utilities.distributed"] = pytorch_lightning.utilities.rank_zero
+
+def fix_asyncio_event_loop_policy():
+ """
+ The default `asyncio` event loop policy only automatically creates
+ event loops in the main threads. Other threads must create event
+ loops explicitly or `asyncio.get_event_loop` (and therefore
+ `.IOLoop.current`) will fail. Installing this policy allows event
+ loops to be created automatically on any thread, matching the
+ behavior of Tornado versions prior to 5.0 (or 5.0 on Python 2).
+ """
+
+ import asyncio
+
+ if sys.platform == "win32" and hasattr(asyncio, "WindowsSelectorEventLoopPolicy"):
+ # "Any thread" and "selector" should be orthogonal, but there's not a clean
+ # interface for composing policies so pick the right base.
+ _BasePolicy = asyncio.WindowsSelectorEventLoopPolicy # type: ignore
+ else:
+ _BasePolicy = asyncio.DefaultEventLoopPolicy
+
+ class AnyThreadEventLoopPolicy(_BasePolicy): # type: ignore
+ """Event loop policy that allows loop creation on any thread.
+ Usage::
+
+ asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())
+ """
+
+ def get_event_loop(self) -> asyncio.AbstractEventLoop:
+ try:
+ return super().get_event_loop()
+ except (RuntimeError, AssertionError):
+ # This was an AssertionError in python 3.4.2 (which ships with debian jessie)
+ # and changed to a RuntimeError in 3.4.3.
+ # "There is no current event loop in thread %r"
+ loop = self.new_event_loop()
+ self.set_event_loop(loop)
+ return loop
+
+ asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())
+
+
+def restore_config_state_file():
+ from modules import shared, config_states
+
+ config_state_file = shared.opts.restore_config_state_file
+ if config_state_file == "":
+ return
+
+ shared.opts.restore_config_state_file = ""
+ shared.opts.save(shared.config_filename)
+
+ if os.path.isfile(config_state_file):
+ print(f"*** About to restore extension state from file: {config_state_file}")
+ with open(config_state_file, "r", encoding="utf-8") as f:
+ config_state = json.load(f)
+ config_states.restore_extension_config(config_state)
+ startup_timer.record("restore extension config")
+ elif config_state_file:
+ print(f"!!! Config state backup not found: {config_state_file}")
+
+
+def validate_tls_options():
+ from modules.shared_cmd_options import cmd_opts
+
+ if not (cmd_opts.tls_keyfile and cmd_opts.tls_certfile):
+ return
+
+ try:
+ if not os.path.exists(cmd_opts.tls_keyfile):
+ print("Invalid path to TLS keyfile given")
+ if not os.path.exists(cmd_opts.tls_certfile):
+ print(f"Invalid path to TLS certfile: '{cmd_opts.tls_certfile}'")
+ except TypeError:
+ cmd_opts.tls_keyfile = cmd_opts.tls_certfile = None
+ print("TLS setup invalid, running webui without TLS")
+ else:
+ print("Running with TLS")
+ startup_timer.record("TLS")
+
+
+def get_gradio_auth_creds():
+ """
+ Convert the gradio_auth and gradio_auth_path commandline arguments into
+ an iterable of (username, password) tuples.
+ """
+ from modules.shared_cmd_options import cmd_opts
+
+ def process_credential_line(s):
+ s = s.strip()
+ if not s:
+ return None
+ return tuple(s.split(':', 1))
+
+ if cmd_opts.gradio_auth:
+ for cred in cmd_opts.gradio_auth.split(','):
+ cred = process_credential_line(cred)
+ if cred:
+ yield cred
+
+ if cmd_opts.gradio_auth_path:
+ with open(cmd_opts.gradio_auth_path, 'r', encoding="utf8") as file:
+ for line in file.readlines():
+ for cred in line.strip().split(','):
+ cred = process_credential_line(cred)
+ if cred:
+ yield cred
+
+
+def dumpstacks():
+ import threading
+ import traceback
+
+ id2name = {th.ident: th.name for th in threading.enumerate()}
+ code = []
+ for threadId, stack in sys._current_frames().items():
+ code.append(f"\n# Thread: {id2name.get(threadId, '')}({threadId})")
+ for filename, lineno, name, line in traceback.extract_stack(stack):
+ code.append(f"""File: "{filename}", line {lineno}, in {name}""")
+ if line:
+ code.append(" " + line.strip())
+
+ print("\n".join(code))
+
+
+def configure_sigint_handler():
+ # make the program just exit at ctrl+c without waiting for anything
+
+ from modules import shared
+
+ def sigint_handler(sig, frame):
+ print(f'Interrupted with signal {sig} in {frame}')
+
+ if shared.opts.dump_stacks_on_signal:
+ dumpstacks()
+
+ os._exit(0)
+
+ if not os.environ.get("COVERAGE_RUN"):
+ # Don't install the immediate-quit handler when running under coverage,
+ # as then the coverage report won't be generated.
+ signal.signal(signal.SIGINT, sigint_handler)
+
+
+def configure_opts_onchange():
+ from modules import shared, sd_models, sd_vae, ui_tempdir, sd_hijack
+ from modules.call_queue import wrap_queued_call
+
+ shared.opts.onchange("sd_model_checkpoint", wrap_queued_call(lambda: sd_models.reload_model_weights()), call=False)
+ shared.opts.onchange("sd_vae", wrap_queued_call(lambda: sd_vae.reload_vae_weights()), call=False)
+ shared.opts.onchange("sd_vae_overrides_per_model_preferences", wrap_queued_call(lambda: sd_vae.reload_vae_weights()), call=False)
+ shared.opts.onchange("temp_dir", ui_tempdir.on_tmpdir_changed)
+ shared.opts.onchange("gradio_theme", shared.reload_gradio_theme)
+ shared.opts.onchange("cross_attention_optimization", wrap_queued_call(lambda: sd_hijack.model_hijack.redo_hijack(shared.sd_model)), call=False)
+ shared.opts.onchange("fp8_storage", wrap_queued_call(lambda: sd_models.reload_model_weights()), call=False)
+ shared.opts.onchange("cache_fp16_weight", wrap_queued_call(lambda: sd_models.reload_model_weights(forced_reload=True)), call=False)
+ startup_timer.record("opts onchange")
+
+
+def setup_middleware(app):
+ from starlette.middleware.gzip import GZipMiddleware
+
+ app.middleware_stack = None # reset current middleware to allow modifying user provided list
+ app.add_middleware(GZipMiddleware, minimum_size=1000)
+ configure_cors_middleware(app)
+ app.build_middleware_stack() # rebuild middleware stack on-the-fly
+
+
+def configure_cors_middleware(app):
+ from starlette.middleware.cors import CORSMiddleware
+ from modules.shared_cmd_options import cmd_opts
+
+ cors_options = {
+ "allow_methods": ["*"],
+ "allow_headers": ["*"],
+ "allow_credentials": True,
+ }
+ if cmd_opts.cors_allow_origins:
+ cors_options["allow_origins"] = cmd_opts.cors_allow_origins.split(',')
+ if cmd_opts.cors_allow_origins_regex:
+ cors_options["allow_origin_regex"] = cmd_opts.cors_allow_origins_regex
+ app.add_middleware(CORSMiddleware, **cors_options)
+
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/initialize_util.py |
Generate descriptive docstrings automatically | import importlib
import logging
import os
import sys
import warnings
from threading import Thread
from modules.timer import startup_timer
def imports():
logging.getLogger("torch.distributed.nn").setLevel(logging.ERROR) # sshh...
logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
import torch # noqa: F401
startup_timer.record("import torch")
import pytorch_lightning # noqa: F401
startup_timer.record("import torch")
warnings.filterwarnings(action="ignore", category=DeprecationWarning, module="pytorch_lightning")
warnings.filterwarnings(action="ignore", category=UserWarning, module="torchvision")
os.environ.setdefault('GRADIO_ANALYTICS_ENABLED', 'False')
import gradio # noqa: F401
startup_timer.record("import gradio")
from modules import paths, timer, import_hook, errors # noqa: F401
startup_timer.record("setup paths")
import ldm.modules.encoders.modules # noqa: F401
startup_timer.record("import ldm")
import sgm.modules.encoders.modules # noqa: F401
startup_timer.record("import sgm")
from modules import shared_init
shared_init.initialize()
startup_timer.record("initialize shared")
from modules import processing, gradio_extensons, ui # noqa: F401
startup_timer.record("other imports")
def check_versions():
from modules.shared_cmd_options import cmd_opts
if not cmd_opts.skip_version_check:
from modules import errors
errors.check_versions()
def initialize():
from modules import initialize_util
initialize_util.fix_torch_version()
initialize_util.fix_pytorch_lightning()
initialize_util.fix_asyncio_event_loop_policy()
initialize_util.validate_tls_options()
initialize_util.configure_sigint_handler()
initialize_util.configure_opts_onchange()
from modules import sd_models
sd_models.setup_model()
startup_timer.record("setup SD model")
from modules.shared_cmd_options import cmd_opts
from modules import codeformer_model
warnings.filterwarnings(action="ignore", category=UserWarning, module="torchvision.transforms.functional_tensor")
codeformer_model.setup_model(cmd_opts.codeformer_models_path)
startup_timer.record("setup codeformer")
from modules import gfpgan_model
gfpgan_model.setup_model(cmd_opts.gfpgan_models_path)
startup_timer.record("setup gfpgan")
initialize_rest(reload_script_modules=False)
def initialize_rest(*, reload_script_modules=False):
from modules.shared_cmd_options import cmd_opts
from modules import sd_samplers
sd_samplers.set_samplers()
startup_timer.record("set samplers")
from modules import extensions
extensions.list_extensions()
startup_timer.record("list extensions")
from modules import initialize_util
initialize_util.restore_config_state_file()
startup_timer.record("restore config state file")
from modules import shared, upscaler, scripts
if cmd_opts.ui_debug_mode:
shared.sd_upscalers = upscaler.UpscalerLanczos().scalers
scripts.load_scripts()
return
from modules import sd_models
sd_models.list_models()
startup_timer.record("list SD models")
from modules import localization
localization.list_localizations(cmd_opts.localizations_dir)
startup_timer.record("list localizations")
with startup_timer.subcategory("load scripts"):
scripts.load_scripts()
if reload_script_modules and shared.opts.enable_reloading_ui_scripts:
for module in [module for name, module in sys.modules.items() if name.startswith("modules.ui")]:
importlib.reload(module)
startup_timer.record("reload script modules")
from modules import modelloader
modelloader.load_upscalers()
startup_timer.record("load upscalers")
from modules import sd_vae
sd_vae.refresh_vae_list()
startup_timer.record("refresh VAE")
from modules import textual_inversion
textual_inversion.textual_inversion.list_textual_inversion_templates()
startup_timer.record("refresh textual inversion templates")
from modules import script_callbacks, sd_hijack_optimizations, sd_hijack
script_callbacks.on_list_optimizers(sd_hijack_optimizations.list_optimizers)
sd_hijack.list_optimizers()
startup_timer.record("scripts list_optimizers")
from modules import sd_unet
sd_unet.list_unets()
startup_timer.record("scripts list_unets")
def load_model():
from modules import devices
devices.torch_npu_set_device()
shared.sd_model # noqa: B018
if sd_hijack.current_optimizer is None:
sd_hijack.apply_optimizations()
devices.first_time_calculation()
if not shared.cmd_opts.skip_load_model_at_start:
Thread(target=load_model).start()
from modules import shared_items
shared_items.reload_hypernetworks()
startup_timer.record("reload hypernetworks")
from modules import ui_extra_networks
ui_extra_networks.initialize()
ui_extra_networks.register_default_pages()
from modules import extra_networks
extra_networks.initialize()
extra_networks.register_default_extra_networks()
startup_timer.record("initialize extra networks") | --- +++ @@ -1,160 +1,169 @@-import importlib
-import logging
-import os
-import sys
-import warnings
-from threading import Thread
-
-from modules.timer import startup_timer
-
-
-def imports():
- logging.getLogger("torch.distributed.nn").setLevel(logging.ERROR) # sshh...
- logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
-
- import torch # noqa: F401
- startup_timer.record("import torch")
- import pytorch_lightning # noqa: F401
- startup_timer.record("import torch")
- warnings.filterwarnings(action="ignore", category=DeprecationWarning, module="pytorch_lightning")
- warnings.filterwarnings(action="ignore", category=UserWarning, module="torchvision")
-
- os.environ.setdefault('GRADIO_ANALYTICS_ENABLED', 'False')
- import gradio # noqa: F401
- startup_timer.record("import gradio")
-
- from modules import paths, timer, import_hook, errors # noqa: F401
- startup_timer.record("setup paths")
-
- import ldm.modules.encoders.modules # noqa: F401
- startup_timer.record("import ldm")
-
- import sgm.modules.encoders.modules # noqa: F401
- startup_timer.record("import sgm")
-
- from modules import shared_init
- shared_init.initialize()
- startup_timer.record("initialize shared")
-
- from modules import processing, gradio_extensons, ui # noqa: F401
- startup_timer.record("other imports")
-
-
-def check_versions():
- from modules.shared_cmd_options import cmd_opts
-
- if not cmd_opts.skip_version_check:
- from modules import errors
- errors.check_versions()
-
-
-def initialize():
- from modules import initialize_util
- initialize_util.fix_torch_version()
- initialize_util.fix_pytorch_lightning()
- initialize_util.fix_asyncio_event_loop_policy()
- initialize_util.validate_tls_options()
- initialize_util.configure_sigint_handler()
- initialize_util.configure_opts_onchange()
-
- from modules import sd_models
- sd_models.setup_model()
- startup_timer.record("setup SD model")
-
- from modules.shared_cmd_options import cmd_opts
-
- from modules import codeformer_model
- warnings.filterwarnings(action="ignore", category=UserWarning, module="torchvision.transforms.functional_tensor")
- codeformer_model.setup_model(cmd_opts.codeformer_models_path)
- startup_timer.record("setup codeformer")
-
- from modules import gfpgan_model
- gfpgan_model.setup_model(cmd_opts.gfpgan_models_path)
- startup_timer.record("setup gfpgan")
-
- initialize_rest(reload_script_modules=False)
-
-
-def initialize_rest(*, reload_script_modules=False):
- from modules.shared_cmd_options import cmd_opts
-
- from modules import sd_samplers
- sd_samplers.set_samplers()
- startup_timer.record("set samplers")
-
- from modules import extensions
- extensions.list_extensions()
- startup_timer.record("list extensions")
-
- from modules import initialize_util
- initialize_util.restore_config_state_file()
- startup_timer.record("restore config state file")
-
- from modules import shared, upscaler, scripts
- if cmd_opts.ui_debug_mode:
- shared.sd_upscalers = upscaler.UpscalerLanczos().scalers
- scripts.load_scripts()
- return
-
- from modules import sd_models
- sd_models.list_models()
- startup_timer.record("list SD models")
-
- from modules import localization
- localization.list_localizations(cmd_opts.localizations_dir)
- startup_timer.record("list localizations")
-
- with startup_timer.subcategory("load scripts"):
- scripts.load_scripts()
-
- if reload_script_modules and shared.opts.enable_reloading_ui_scripts:
- for module in [module for name, module in sys.modules.items() if name.startswith("modules.ui")]:
- importlib.reload(module)
- startup_timer.record("reload script modules")
-
- from modules import modelloader
- modelloader.load_upscalers()
- startup_timer.record("load upscalers")
-
- from modules import sd_vae
- sd_vae.refresh_vae_list()
- startup_timer.record("refresh VAE")
-
- from modules import textual_inversion
- textual_inversion.textual_inversion.list_textual_inversion_templates()
- startup_timer.record("refresh textual inversion templates")
-
- from modules import script_callbacks, sd_hijack_optimizations, sd_hijack
- script_callbacks.on_list_optimizers(sd_hijack_optimizations.list_optimizers)
- sd_hijack.list_optimizers()
- startup_timer.record("scripts list_optimizers")
-
- from modules import sd_unet
- sd_unet.list_unets()
- startup_timer.record("scripts list_unets")
-
- def load_model():
- from modules import devices
- devices.torch_npu_set_device()
-
- shared.sd_model # noqa: B018
-
- if sd_hijack.current_optimizer is None:
- sd_hijack.apply_optimizations()
-
- devices.first_time_calculation()
- if not shared.cmd_opts.skip_load_model_at_start:
- Thread(target=load_model).start()
-
- from modules import shared_items
- shared_items.reload_hypernetworks()
- startup_timer.record("reload hypernetworks")
-
- from modules import ui_extra_networks
- ui_extra_networks.initialize()
- ui_extra_networks.register_default_pages()
-
- from modules import extra_networks
- extra_networks.initialize()
- extra_networks.register_default_extra_networks()
- startup_timer.record("initialize extra networks")+import importlib
+import logging
+import os
+import sys
+import warnings
+from threading import Thread
+
+from modules.timer import startup_timer
+
+
+def imports():
+ logging.getLogger("torch.distributed.nn").setLevel(logging.ERROR) # sshh...
+ logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
+
+ import torch # noqa: F401
+ startup_timer.record("import torch")
+ import pytorch_lightning # noqa: F401
+ startup_timer.record("import torch")
+ warnings.filterwarnings(action="ignore", category=DeprecationWarning, module="pytorch_lightning")
+ warnings.filterwarnings(action="ignore", category=UserWarning, module="torchvision")
+
+ os.environ.setdefault('GRADIO_ANALYTICS_ENABLED', 'False')
+ import gradio # noqa: F401
+ startup_timer.record("import gradio")
+
+ from modules import paths, timer, import_hook, errors # noqa: F401
+ startup_timer.record("setup paths")
+
+ import ldm.modules.encoders.modules # noqa: F401
+ startup_timer.record("import ldm")
+
+ import sgm.modules.encoders.modules # noqa: F401
+ startup_timer.record("import sgm")
+
+ from modules import shared_init
+ shared_init.initialize()
+ startup_timer.record("initialize shared")
+
+ from modules import processing, gradio_extensons, ui # noqa: F401
+ startup_timer.record("other imports")
+
+
+def check_versions():
+ from modules.shared_cmd_options import cmd_opts
+
+ if not cmd_opts.skip_version_check:
+ from modules import errors
+ errors.check_versions()
+
+
+def initialize():
+ from modules import initialize_util
+ initialize_util.fix_torch_version()
+ initialize_util.fix_pytorch_lightning()
+ initialize_util.fix_asyncio_event_loop_policy()
+ initialize_util.validate_tls_options()
+ initialize_util.configure_sigint_handler()
+ initialize_util.configure_opts_onchange()
+
+ from modules import sd_models
+ sd_models.setup_model()
+ startup_timer.record("setup SD model")
+
+ from modules.shared_cmd_options import cmd_opts
+
+ from modules import codeformer_model
+ warnings.filterwarnings(action="ignore", category=UserWarning, module="torchvision.transforms.functional_tensor")
+ codeformer_model.setup_model(cmd_opts.codeformer_models_path)
+ startup_timer.record("setup codeformer")
+
+ from modules import gfpgan_model
+ gfpgan_model.setup_model(cmd_opts.gfpgan_models_path)
+ startup_timer.record("setup gfpgan")
+
+ initialize_rest(reload_script_modules=False)
+
+
+def initialize_rest(*, reload_script_modules=False):
+ """
+ Called both from initialize() and when reloading the webui.
+ """
+ from modules.shared_cmd_options import cmd_opts
+
+ from modules import sd_samplers
+ sd_samplers.set_samplers()
+ startup_timer.record("set samplers")
+
+ from modules import extensions
+ extensions.list_extensions()
+ startup_timer.record("list extensions")
+
+ from modules import initialize_util
+ initialize_util.restore_config_state_file()
+ startup_timer.record("restore config state file")
+
+ from modules import shared, upscaler, scripts
+ if cmd_opts.ui_debug_mode:
+ shared.sd_upscalers = upscaler.UpscalerLanczos().scalers
+ scripts.load_scripts()
+ return
+
+ from modules import sd_models
+ sd_models.list_models()
+ startup_timer.record("list SD models")
+
+ from modules import localization
+ localization.list_localizations(cmd_opts.localizations_dir)
+ startup_timer.record("list localizations")
+
+ with startup_timer.subcategory("load scripts"):
+ scripts.load_scripts()
+
+ if reload_script_modules and shared.opts.enable_reloading_ui_scripts:
+ for module in [module for name, module in sys.modules.items() if name.startswith("modules.ui")]:
+ importlib.reload(module)
+ startup_timer.record("reload script modules")
+
+ from modules import modelloader
+ modelloader.load_upscalers()
+ startup_timer.record("load upscalers")
+
+ from modules import sd_vae
+ sd_vae.refresh_vae_list()
+ startup_timer.record("refresh VAE")
+
+ from modules import textual_inversion
+ textual_inversion.textual_inversion.list_textual_inversion_templates()
+ startup_timer.record("refresh textual inversion templates")
+
+ from modules import script_callbacks, sd_hijack_optimizations, sd_hijack
+ script_callbacks.on_list_optimizers(sd_hijack_optimizations.list_optimizers)
+ sd_hijack.list_optimizers()
+ startup_timer.record("scripts list_optimizers")
+
+ from modules import sd_unet
+ sd_unet.list_unets()
+ startup_timer.record("scripts list_unets")
+
+ def load_model():
+ """
+ Accesses shared.sd_model property to load model.
+ After it's available, if it has been loaded before this access by some extension,
+ its optimization may be None because the list of optimizers has not been filled
+ by that time, so we apply optimization again.
+ """
+ from modules import devices
+ devices.torch_npu_set_device()
+
+ shared.sd_model # noqa: B018
+
+ if sd_hijack.current_optimizer is None:
+ sd_hijack.apply_optimizations()
+
+ devices.first_time_calculation()
+ if not shared.cmd_opts.skip_load_model_at_start:
+ Thread(target=load_model).start()
+
+ from modules import shared_items
+ shared_items.reload_hypernetworks()
+ startup_timer.record("reload hypernetworks")
+
+ from modules import ui_extra_networks
+ ui_extra_networks.initialize()
+ ui_extra_networks.register_default_pages()
+
+ from modules import extra_networks
+ extra_networks.initialize()
+ extra_networks.register_default_extra_networks()
+ startup_timer.record("initialize extra networks")
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/initialize.py |
Auto-generate documentation strings for this file | from __future__ import annotations
import base64
import io
import json
import os
import re
import sys
import gradio as gr
from modules.paths import data_path
from modules import shared, ui_tempdir, script_callbacks, processing, infotext_versions, images, prompt_parser, errors
from PIL import Image
sys.modules['modules.generation_parameters_copypaste'] = sys.modules[__name__] # alias for old name
re_param_code = r'\s*(\w[\w \-/]+):\s*("(?:\\.|[^\\"])+"|[^,]*)(?:,|$)'
re_param = re.compile(re_param_code)
re_imagesize = re.compile(r"^(\d+)x(\d+)$")
re_hypernet_hash = re.compile("\(([0-9a-f]+)\)$")
type_of_gr_update = type(gr.update())
class ParamBinding:
def __init__(self, paste_button, tabname, source_text_component=None, source_image_component=None, source_tabname=None, override_settings_component=None, paste_field_names=None):
self.paste_button = paste_button
self.tabname = tabname
self.source_text_component = source_text_component
self.source_image_component = source_image_component
self.source_tabname = source_tabname
self.override_settings_component = override_settings_component
self.paste_field_names = paste_field_names or []
class PasteField(tuple):
def __new__(cls, component, target, *, api=None):
return super().__new__(cls, (component, target))
def __init__(self, component, target, *, api=None):
super().__init__()
self.api = api
self.component = component
self.label = target if isinstance(target, str) else None
self.function = target if callable(target) else None
paste_fields: dict[str, dict] = {}
registered_param_bindings: list[ParamBinding] = []
def reset():
paste_fields.clear()
registered_param_bindings.clear()
def quote(text):
if ',' not in str(text) and '\n' not in str(text) and ':' not in str(text):
return text
return json.dumps(text, ensure_ascii=False)
def unquote(text):
if len(text) == 0 or text[0] != '"' or text[-1] != '"':
return text
try:
return json.loads(text)
except Exception:
return text
def image_from_url_text(filedata):
if filedata is None:
return None
if type(filedata) == list and filedata and type(filedata[0]) == dict and filedata[0].get("is_file", False):
filedata = filedata[0]
if type(filedata) == dict and filedata.get("is_file", False):
filename = filedata["name"]
is_in_right_dir = ui_tempdir.check_tmp_file(shared.demo, filename)
assert is_in_right_dir, 'trying to open image file outside of allowed directories'
filename = filename.rsplit('?', 1)[0]
return images.read(filename)
if type(filedata) == list:
if len(filedata) == 0:
return None
filedata = filedata[0]
if filedata.startswith("data:image/png;base64,"):
filedata = filedata[len("data:image/png;base64,"):]
filedata = base64.decodebytes(filedata.encode('utf-8'))
image = images.read(io.BytesIO(filedata))
return image
def add_paste_fields(tabname, init_img, fields, override_settings_component=None):
if fields:
for i in range(len(fields)):
if not isinstance(fields[i], PasteField):
fields[i] = PasteField(*fields[i])
paste_fields[tabname] = {"init_img": init_img, "fields": fields, "override_settings_component": override_settings_component}
# backwards compatibility for existing extensions
import modules.ui
if tabname == 'txt2img':
modules.ui.txt2img_paste_fields = fields
elif tabname == 'img2img':
modules.ui.img2img_paste_fields = fields
def create_buttons(tabs_list):
buttons = {}
for tab in tabs_list:
buttons[tab] = gr.Button(f"Send to {tab}", elem_id=f"{tab}_tab")
return buttons
def bind_buttons(buttons, send_image, send_generate_info):
for tabname, button in buttons.items():
source_text_component = send_generate_info if isinstance(send_generate_info, gr.components.Component) else None
source_tabname = send_generate_info if isinstance(send_generate_info, str) else None
register_paste_params_button(ParamBinding(paste_button=button, tabname=tabname, source_text_component=source_text_component, source_image_component=send_image, source_tabname=source_tabname))
def register_paste_params_button(binding: ParamBinding):
registered_param_bindings.append(binding)
def connect_paste_params_buttons():
for binding in registered_param_bindings:
destination_image_component = paste_fields[binding.tabname]["init_img"]
fields = paste_fields[binding.tabname]["fields"]
override_settings_component = binding.override_settings_component or paste_fields[binding.tabname]["override_settings_component"]
destination_width_component = next(iter([field for field, name in fields if name == "Size-1"] if fields else []), None)
destination_height_component = next(iter([field for field, name in fields if name == "Size-2"] if fields else []), None)
if binding.source_image_component and destination_image_component:
need_send_dementions = destination_width_component and binding.tabname != 'inpaint'
if isinstance(binding.source_image_component, gr.Gallery):
func = send_image_and_dimensions if need_send_dementions else image_from_url_text
jsfunc = "extract_image_from_gallery"
else:
func = send_image_and_dimensions if need_send_dementions else lambda x: x
jsfunc = None
binding.paste_button.click(
fn=func,
_js=jsfunc,
inputs=[binding.source_image_component],
outputs=[destination_image_component, destination_width_component, destination_height_component] if need_send_dementions else [destination_image_component],
show_progress=False,
)
if binding.source_text_component is not None and fields is not None:
connect_paste(binding.paste_button, fields, binding.source_text_component, override_settings_component, binding.tabname)
if binding.source_tabname is not None and fields is not None:
paste_field_names = ['Prompt', 'Negative prompt', 'Steps', 'Face restoration'] + (["Seed"] if shared.opts.send_seed else []) + binding.paste_field_names
binding.paste_button.click(
fn=lambda *x: x,
inputs=[field for field, name in paste_fields[binding.source_tabname]["fields"] if name in paste_field_names],
outputs=[field for field, name in fields if name in paste_field_names],
show_progress=False,
)
binding.paste_button.click(
fn=None,
_js=f"switch_to_{binding.tabname}",
inputs=None,
outputs=None,
show_progress=False,
)
def send_image_and_dimensions(x):
if isinstance(x, Image.Image):
img = x
else:
img = image_from_url_text(x)
if shared.opts.send_size and isinstance(img, Image.Image):
w = img.width
h = img.height
else:
w = gr.update()
h = gr.update()
return img, w, h
def restore_old_hires_fix_params(res):
firstpass_width = res.get('First pass size-1', None)
firstpass_height = res.get('First pass size-2', None)
if shared.opts.use_old_hires_fix_width_height:
hires_width = int(res.get("Hires resize-1", 0))
hires_height = int(res.get("Hires resize-2", 0))
if hires_width and hires_height:
res['Size-1'] = hires_width
res['Size-2'] = hires_height
return
if firstpass_width is None or firstpass_height is None:
return
firstpass_width, firstpass_height = int(firstpass_width), int(firstpass_height)
width = int(res.get("Size-1", 512))
height = int(res.get("Size-2", 512))
if firstpass_width == 0 or firstpass_height == 0:
firstpass_width, firstpass_height = processing.old_hires_fix_first_pass_dimensions(width, height)
res['Size-1'] = firstpass_width
res['Size-2'] = firstpass_height
res['Hires resize-1'] = width
res['Hires resize-2'] = height
def parse_generation_parameters(x: str, skip_fields: list[str] | None = None):
if skip_fields is None:
skip_fields = shared.opts.infotext_skip_pasting
res = {}
prompt = ""
negative_prompt = ""
done_with_prompt = False
*lines, lastline = x.strip().split("\n")
if len(re_param.findall(lastline)) < 3:
lines.append(lastline)
lastline = ''
for line in lines:
line = line.strip()
if line.startswith("Negative prompt:"):
done_with_prompt = True
line = line[16:].strip()
if done_with_prompt:
negative_prompt += ("" if negative_prompt == "" else "\n") + line
else:
prompt += ("" if prompt == "" else "\n") + line
for k, v in re_param.findall(lastline):
try:
if v[0] == '"' and v[-1] == '"':
v = unquote(v)
m = re_imagesize.match(v)
if m is not None:
res[f"{k}-1"] = m.group(1)
res[f"{k}-2"] = m.group(2)
else:
res[k] = v
except Exception:
print(f"Error parsing \"{k}: {v}\"")
# Extract styles from prompt
if shared.opts.infotext_styles != "Ignore":
found_styles, prompt_no_styles, negative_prompt_no_styles = shared.prompt_styles.extract_styles_from_prompt(prompt, negative_prompt)
same_hr_styles = True
if ("Hires prompt" in res or "Hires negative prompt" in res) and (infotext_ver > infotext_versions.v180_hr_styles if (infotext_ver := infotext_versions.parse_version(res.get("Version"))) else True):
hr_prompt, hr_negative_prompt = res.get("Hires prompt", prompt), res.get("Hires negative prompt", negative_prompt)
hr_found_styles, hr_prompt_no_styles, hr_negative_prompt_no_styles = shared.prompt_styles.extract_styles_from_prompt(hr_prompt, hr_negative_prompt)
if same_hr_styles := found_styles == hr_found_styles:
res["Hires prompt"] = '' if hr_prompt_no_styles == prompt_no_styles else hr_prompt_no_styles
res['Hires negative prompt'] = '' if hr_negative_prompt_no_styles == negative_prompt_no_styles else hr_negative_prompt_no_styles
if same_hr_styles:
prompt, negative_prompt = prompt_no_styles, negative_prompt_no_styles
if (shared.opts.infotext_styles == "Apply if any" and found_styles) or shared.opts.infotext_styles == "Apply":
res['Styles array'] = found_styles
res["Prompt"] = prompt
res["Negative prompt"] = negative_prompt
# Missing CLIP skip means it was set to 1 (the default)
if "Clip skip" not in res:
res["Clip skip"] = "1"
hypernet = res.get("Hypernet", None)
if hypernet is not None:
res["Prompt"] += f"""<hypernet:{hypernet}:{res.get("Hypernet strength", "1.0")}>"""
if "Hires resize-1" not in res:
res["Hires resize-1"] = 0
res["Hires resize-2"] = 0
if "Hires sampler" not in res:
res["Hires sampler"] = "Use same sampler"
if "Hires schedule type" not in res:
res["Hires schedule type"] = "Use same scheduler"
if "Hires checkpoint" not in res:
res["Hires checkpoint"] = "Use same checkpoint"
if "Hires prompt" not in res:
res["Hires prompt"] = ""
if "Hires negative prompt" not in res:
res["Hires negative prompt"] = ""
if "Mask mode" not in res:
res["Mask mode"] = "Inpaint masked"
if "Masked content" not in res:
res["Masked content"] = 'original'
if "Inpaint area" not in res:
res["Inpaint area"] = "Whole picture"
if "Masked area padding" not in res:
res["Masked area padding"] = 32
restore_old_hires_fix_params(res)
# Missing RNG means the default was set, which is GPU RNG
if "RNG" not in res:
res["RNG"] = "GPU"
if "Schedule type" not in res:
res["Schedule type"] = "Automatic"
if "Schedule max sigma" not in res:
res["Schedule max sigma"] = 0
if "Schedule min sigma" not in res:
res["Schedule min sigma"] = 0
if "Schedule rho" not in res:
res["Schedule rho"] = 0
if "VAE Encoder" not in res:
res["VAE Encoder"] = "Full"
if "VAE Decoder" not in res:
res["VAE Decoder"] = "Full"
if "FP8 weight" not in res:
res["FP8 weight"] = "Disable"
if "Cache FP16 weight for LoRA" not in res and res["FP8 weight"] != "Disable":
res["Cache FP16 weight for LoRA"] = False
prompt_attention = prompt_parser.parse_prompt_attention(prompt)
prompt_attention += prompt_parser.parse_prompt_attention(negative_prompt)
prompt_uses_emphasis = len(prompt_attention) != len([p for p in prompt_attention if p[1] == 1.0 or p[0] == 'BREAK'])
if "Emphasis" not in res and prompt_uses_emphasis:
res["Emphasis"] = "Original"
if "Refiner switch by sampling steps" not in res:
res["Refiner switch by sampling steps"] = False
infotext_versions.backcompat(res)
for key in skip_fields:
res.pop(key, None)
return res
infotext_to_setting_name_mapping = [
]
"""Mapping of infotext labels to setting names. Only left for backwards compatibility - use OptionInfo(..., infotext='...') instead.
Example content:
infotext_to_setting_name_mapping = [
('Conditional mask weight', 'inpainting_mask_weight'),
('Model hash', 'sd_model_checkpoint'),
('ENSD', 'eta_noise_seed_delta'),
('Schedule type', 'k_sched_type'),
]
"""
def create_override_settings_dict(text_pairs):
res = {}
params = {}
for pair in text_pairs:
k, v = pair.split(":", maxsplit=1)
params[k] = v.strip()
mapping = [(info.infotext, k) for k, info in shared.opts.data_labels.items() if info.infotext]
for param_name, setting_name in mapping + infotext_to_setting_name_mapping:
value = params.get(param_name, None)
if value is None:
continue
res[setting_name] = shared.opts.cast_value(setting_name, value)
return res
def get_override_settings(params, *, skip_fields=None):
res = []
mapping = [(info.infotext, k) for k, info in shared.opts.data_labels.items() if info.infotext]
for param_name, setting_name in mapping + infotext_to_setting_name_mapping:
if param_name in (skip_fields or {}):
continue
v = params.get(param_name, None)
if v is None:
continue
if setting_name == "sd_model_checkpoint" and shared.opts.disable_weights_auto_swap:
continue
v = shared.opts.cast_value(setting_name, v)
current_value = getattr(shared.opts, setting_name, None)
if v == current_value:
continue
res.append((param_name, setting_name, v))
return res
def connect_paste(button, paste_fields, input_comp, override_settings_component, tabname):
def paste_func(prompt):
if not prompt and not shared.cmd_opts.hide_ui_dir_config and not shared.cmd_opts.no_prompt_history:
filename = os.path.join(data_path, "params.txt")
try:
with open(filename, "r", encoding="utf8") as file:
prompt = file.read()
except OSError:
pass
params = parse_generation_parameters(prompt)
script_callbacks.infotext_pasted_callback(prompt, params)
res = []
for output, key in paste_fields:
if callable(key):
try:
v = key(params)
except Exception:
errors.report(f"Error executing {key}", exc_info=True)
v = None
else:
v = params.get(key, None)
if v is None:
res.append(gr.update())
elif isinstance(v, type_of_gr_update):
res.append(v)
else:
try:
valtype = type(output.value)
if valtype == bool and v == "False":
val = False
elif valtype == int:
val = float(v)
else:
val = valtype(v)
res.append(gr.update(value=val))
except Exception:
res.append(gr.update())
return res
if override_settings_component is not None:
already_handled_fields = {key: 1 for _, key in paste_fields}
def paste_settings(params):
vals = get_override_settings(params, skip_fields=already_handled_fields)
vals_pairs = [f"{infotext_text}: {value}" for infotext_text, setting_name, value in vals]
return gr.Dropdown.update(value=vals_pairs, choices=vals_pairs, visible=bool(vals_pairs))
paste_fields = paste_fields + [(override_settings_component, paste_settings)]
button.click(
fn=paste_func,
inputs=[input_comp],
outputs=[x[0] for x in paste_fields],
show_progress=False,
)
button.click(
fn=None,
_js=f"recalculate_prompts_{tabname}",
inputs=[],
outputs=[],
show_progress=False,
)
| --- +++ @@ -1,510 +1,546 @@-from __future__ import annotations
-import base64
-import io
-import json
-import os
-import re
-import sys
-
-import gradio as gr
-from modules.paths import data_path
-from modules import shared, ui_tempdir, script_callbacks, processing, infotext_versions, images, prompt_parser, errors
-from PIL import Image
-
-sys.modules['modules.generation_parameters_copypaste'] = sys.modules[__name__] # alias for old name
-
-re_param_code = r'\s*(\w[\w \-/]+):\s*("(?:\\.|[^\\"])+"|[^,]*)(?:,|$)'
-re_param = re.compile(re_param_code)
-re_imagesize = re.compile(r"^(\d+)x(\d+)$")
-re_hypernet_hash = re.compile("\(([0-9a-f]+)\)$")
-type_of_gr_update = type(gr.update())
-
-
-class ParamBinding:
- def __init__(self, paste_button, tabname, source_text_component=None, source_image_component=None, source_tabname=None, override_settings_component=None, paste_field_names=None):
- self.paste_button = paste_button
- self.tabname = tabname
- self.source_text_component = source_text_component
- self.source_image_component = source_image_component
- self.source_tabname = source_tabname
- self.override_settings_component = override_settings_component
- self.paste_field_names = paste_field_names or []
-
-
-class PasteField(tuple):
- def __new__(cls, component, target, *, api=None):
- return super().__new__(cls, (component, target))
-
- def __init__(self, component, target, *, api=None):
- super().__init__()
-
- self.api = api
- self.component = component
- self.label = target if isinstance(target, str) else None
- self.function = target if callable(target) else None
-
-
-paste_fields: dict[str, dict] = {}
-registered_param_bindings: list[ParamBinding] = []
-
-
-def reset():
- paste_fields.clear()
- registered_param_bindings.clear()
-
-
-def quote(text):
- if ',' not in str(text) and '\n' not in str(text) and ':' not in str(text):
- return text
-
- return json.dumps(text, ensure_ascii=False)
-
-
-def unquote(text):
- if len(text) == 0 or text[0] != '"' or text[-1] != '"':
- return text
-
- try:
- return json.loads(text)
- except Exception:
- return text
-
-
-def image_from_url_text(filedata):
- if filedata is None:
- return None
-
- if type(filedata) == list and filedata and type(filedata[0]) == dict and filedata[0].get("is_file", False):
- filedata = filedata[0]
-
- if type(filedata) == dict and filedata.get("is_file", False):
- filename = filedata["name"]
- is_in_right_dir = ui_tempdir.check_tmp_file(shared.demo, filename)
- assert is_in_right_dir, 'trying to open image file outside of allowed directories'
-
- filename = filename.rsplit('?', 1)[0]
- return images.read(filename)
-
- if type(filedata) == list:
- if len(filedata) == 0:
- return None
-
- filedata = filedata[0]
-
- if filedata.startswith("data:image/png;base64,"):
- filedata = filedata[len("data:image/png;base64,"):]
-
- filedata = base64.decodebytes(filedata.encode('utf-8'))
- image = images.read(io.BytesIO(filedata))
- return image
-
-
-def add_paste_fields(tabname, init_img, fields, override_settings_component=None):
-
- if fields:
- for i in range(len(fields)):
- if not isinstance(fields[i], PasteField):
- fields[i] = PasteField(*fields[i])
-
- paste_fields[tabname] = {"init_img": init_img, "fields": fields, "override_settings_component": override_settings_component}
-
- # backwards compatibility for existing extensions
- import modules.ui
- if tabname == 'txt2img':
- modules.ui.txt2img_paste_fields = fields
- elif tabname == 'img2img':
- modules.ui.img2img_paste_fields = fields
-
-
-def create_buttons(tabs_list):
- buttons = {}
- for tab in tabs_list:
- buttons[tab] = gr.Button(f"Send to {tab}", elem_id=f"{tab}_tab")
- return buttons
-
-
-def bind_buttons(buttons, send_image, send_generate_info):
- for tabname, button in buttons.items():
- source_text_component = send_generate_info if isinstance(send_generate_info, gr.components.Component) else None
- source_tabname = send_generate_info if isinstance(send_generate_info, str) else None
-
- register_paste_params_button(ParamBinding(paste_button=button, tabname=tabname, source_text_component=source_text_component, source_image_component=send_image, source_tabname=source_tabname))
-
-
-def register_paste_params_button(binding: ParamBinding):
- registered_param_bindings.append(binding)
-
-
-def connect_paste_params_buttons():
- for binding in registered_param_bindings:
- destination_image_component = paste_fields[binding.tabname]["init_img"]
- fields = paste_fields[binding.tabname]["fields"]
- override_settings_component = binding.override_settings_component or paste_fields[binding.tabname]["override_settings_component"]
-
- destination_width_component = next(iter([field for field, name in fields if name == "Size-1"] if fields else []), None)
- destination_height_component = next(iter([field for field, name in fields if name == "Size-2"] if fields else []), None)
-
- if binding.source_image_component and destination_image_component:
- need_send_dementions = destination_width_component and binding.tabname != 'inpaint'
- if isinstance(binding.source_image_component, gr.Gallery):
- func = send_image_and_dimensions if need_send_dementions else image_from_url_text
- jsfunc = "extract_image_from_gallery"
- else:
- func = send_image_and_dimensions if need_send_dementions else lambda x: x
- jsfunc = None
-
- binding.paste_button.click(
- fn=func,
- _js=jsfunc,
- inputs=[binding.source_image_component],
- outputs=[destination_image_component, destination_width_component, destination_height_component] if need_send_dementions else [destination_image_component],
- show_progress=False,
- )
-
- if binding.source_text_component is not None and fields is not None:
- connect_paste(binding.paste_button, fields, binding.source_text_component, override_settings_component, binding.tabname)
-
- if binding.source_tabname is not None and fields is not None:
- paste_field_names = ['Prompt', 'Negative prompt', 'Steps', 'Face restoration'] + (["Seed"] if shared.opts.send_seed else []) + binding.paste_field_names
- binding.paste_button.click(
- fn=lambda *x: x,
- inputs=[field for field, name in paste_fields[binding.source_tabname]["fields"] if name in paste_field_names],
- outputs=[field for field, name in fields if name in paste_field_names],
- show_progress=False,
- )
-
- binding.paste_button.click(
- fn=None,
- _js=f"switch_to_{binding.tabname}",
- inputs=None,
- outputs=None,
- show_progress=False,
- )
-
-
-def send_image_and_dimensions(x):
- if isinstance(x, Image.Image):
- img = x
- else:
- img = image_from_url_text(x)
-
- if shared.opts.send_size and isinstance(img, Image.Image):
- w = img.width
- h = img.height
- else:
- w = gr.update()
- h = gr.update()
-
- return img, w, h
-
-
-def restore_old_hires_fix_params(res):
-
- firstpass_width = res.get('First pass size-1', None)
- firstpass_height = res.get('First pass size-2', None)
-
- if shared.opts.use_old_hires_fix_width_height:
- hires_width = int(res.get("Hires resize-1", 0))
- hires_height = int(res.get("Hires resize-2", 0))
-
- if hires_width and hires_height:
- res['Size-1'] = hires_width
- res['Size-2'] = hires_height
- return
-
- if firstpass_width is None or firstpass_height is None:
- return
-
- firstpass_width, firstpass_height = int(firstpass_width), int(firstpass_height)
- width = int(res.get("Size-1", 512))
- height = int(res.get("Size-2", 512))
-
- if firstpass_width == 0 or firstpass_height == 0:
- firstpass_width, firstpass_height = processing.old_hires_fix_first_pass_dimensions(width, height)
-
- res['Size-1'] = firstpass_width
- res['Size-2'] = firstpass_height
- res['Hires resize-1'] = width
- res['Hires resize-2'] = height
-
-
-def parse_generation_parameters(x: str, skip_fields: list[str] | None = None):
- if skip_fields is None:
- skip_fields = shared.opts.infotext_skip_pasting
-
- res = {}
-
- prompt = ""
- negative_prompt = ""
-
- done_with_prompt = False
-
- *lines, lastline = x.strip().split("\n")
- if len(re_param.findall(lastline)) < 3:
- lines.append(lastline)
- lastline = ''
-
- for line in lines:
- line = line.strip()
- if line.startswith("Negative prompt:"):
- done_with_prompt = True
- line = line[16:].strip()
- if done_with_prompt:
- negative_prompt += ("" if negative_prompt == "" else "\n") + line
- else:
- prompt += ("" if prompt == "" else "\n") + line
-
- for k, v in re_param.findall(lastline):
- try:
- if v[0] == '"' and v[-1] == '"':
- v = unquote(v)
-
- m = re_imagesize.match(v)
- if m is not None:
- res[f"{k}-1"] = m.group(1)
- res[f"{k}-2"] = m.group(2)
- else:
- res[k] = v
- except Exception:
- print(f"Error parsing \"{k}: {v}\"")
-
- # Extract styles from prompt
- if shared.opts.infotext_styles != "Ignore":
- found_styles, prompt_no_styles, negative_prompt_no_styles = shared.prompt_styles.extract_styles_from_prompt(prompt, negative_prompt)
-
- same_hr_styles = True
- if ("Hires prompt" in res or "Hires negative prompt" in res) and (infotext_ver > infotext_versions.v180_hr_styles if (infotext_ver := infotext_versions.parse_version(res.get("Version"))) else True):
- hr_prompt, hr_negative_prompt = res.get("Hires prompt", prompt), res.get("Hires negative prompt", negative_prompt)
- hr_found_styles, hr_prompt_no_styles, hr_negative_prompt_no_styles = shared.prompt_styles.extract_styles_from_prompt(hr_prompt, hr_negative_prompt)
- if same_hr_styles := found_styles == hr_found_styles:
- res["Hires prompt"] = '' if hr_prompt_no_styles == prompt_no_styles else hr_prompt_no_styles
- res['Hires negative prompt'] = '' if hr_negative_prompt_no_styles == negative_prompt_no_styles else hr_negative_prompt_no_styles
-
- if same_hr_styles:
- prompt, negative_prompt = prompt_no_styles, negative_prompt_no_styles
- if (shared.opts.infotext_styles == "Apply if any" and found_styles) or shared.opts.infotext_styles == "Apply":
- res['Styles array'] = found_styles
-
- res["Prompt"] = prompt
- res["Negative prompt"] = negative_prompt
-
- # Missing CLIP skip means it was set to 1 (the default)
- if "Clip skip" not in res:
- res["Clip skip"] = "1"
-
- hypernet = res.get("Hypernet", None)
- if hypernet is not None:
- res["Prompt"] += f"""<hypernet:{hypernet}:{res.get("Hypernet strength", "1.0")}>"""
-
- if "Hires resize-1" not in res:
- res["Hires resize-1"] = 0
- res["Hires resize-2"] = 0
-
- if "Hires sampler" not in res:
- res["Hires sampler"] = "Use same sampler"
-
- if "Hires schedule type" not in res:
- res["Hires schedule type"] = "Use same scheduler"
-
- if "Hires checkpoint" not in res:
- res["Hires checkpoint"] = "Use same checkpoint"
-
- if "Hires prompt" not in res:
- res["Hires prompt"] = ""
-
- if "Hires negative prompt" not in res:
- res["Hires negative prompt"] = ""
-
- if "Mask mode" not in res:
- res["Mask mode"] = "Inpaint masked"
-
- if "Masked content" not in res:
- res["Masked content"] = 'original'
-
- if "Inpaint area" not in res:
- res["Inpaint area"] = "Whole picture"
-
- if "Masked area padding" not in res:
- res["Masked area padding"] = 32
-
- restore_old_hires_fix_params(res)
-
- # Missing RNG means the default was set, which is GPU RNG
- if "RNG" not in res:
- res["RNG"] = "GPU"
-
- if "Schedule type" not in res:
- res["Schedule type"] = "Automatic"
-
- if "Schedule max sigma" not in res:
- res["Schedule max sigma"] = 0
-
- if "Schedule min sigma" not in res:
- res["Schedule min sigma"] = 0
-
- if "Schedule rho" not in res:
- res["Schedule rho"] = 0
-
- if "VAE Encoder" not in res:
- res["VAE Encoder"] = "Full"
-
- if "VAE Decoder" not in res:
- res["VAE Decoder"] = "Full"
-
- if "FP8 weight" not in res:
- res["FP8 weight"] = "Disable"
-
- if "Cache FP16 weight for LoRA" not in res and res["FP8 weight"] != "Disable":
- res["Cache FP16 weight for LoRA"] = False
-
- prompt_attention = prompt_parser.parse_prompt_attention(prompt)
- prompt_attention += prompt_parser.parse_prompt_attention(negative_prompt)
- prompt_uses_emphasis = len(prompt_attention) != len([p for p in prompt_attention if p[1] == 1.0 or p[0] == 'BREAK'])
- if "Emphasis" not in res and prompt_uses_emphasis:
- res["Emphasis"] = "Original"
-
- if "Refiner switch by sampling steps" not in res:
- res["Refiner switch by sampling steps"] = False
-
- infotext_versions.backcompat(res)
-
- for key in skip_fields:
- res.pop(key, None)
-
- return res
-
-
-infotext_to_setting_name_mapping = [
-
-]
-"""Mapping of infotext labels to setting names. Only left for backwards compatibility - use OptionInfo(..., infotext='...') instead.
-Example content:
-
-infotext_to_setting_name_mapping = [
- ('Conditional mask weight', 'inpainting_mask_weight'),
- ('Model hash', 'sd_model_checkpoint'),
- ('ENSD', 'eta_noise_seed_delta'),
- ('Schedule type', 'k_sched_type'),
-]
-"""
-
-
-def create_override_settings_dict(text_pairs):
-
- res = {}
-
- params = {}
- for pair in text_pairs:
- k, v = pair.split(":", maxsplit=1)
-
- params[k] = v.strip()
-
- mapping = [(info.infotext, k) for k, info in shared.opts.data_labels.items() if info.infotext]
- for param_name, setting_name in mapping + infotext_to_setting_name_mapping:
- value = params.get(param_name, None)
-
- if value is None:
- continue
-
- res[setting_name] = shared.opts.cast_value(setting_name, value)
-
- return res
-
-
-def get_override_settings(params, *, skip_fields=None):
-
- res = []
-
- mapping = [(info.infotext, k) for k, info in shared.opts.data_labels.items() if info.infotext]
- for param_name, setting_name in mapping + infotext_to_setting_name_mapping:
- if param_name in (skip_fields or {}):
- continue
-
- v = params.get(param_name, None)
- if v is None:
- continue
-
- if setting_name == "sd_model_checkpoint" and shared.opts.disable_weights_auto_swap:
- continue
-
- v = shared.opts.cast_value(setting_name, v)
- current_value = getattr(shared.opts, setting_name, None)
-
- if v == current_value:
- continue
-
- res.append((param_name, setting_name, v))
-
- return res
-
-
-def connect_paste(button, paste_fields, input_comp, override_settings_component, tabname):
- def paste_func(prompt):
- if not prompt and not shared.cmd_opts.hide_ui_dir_config and not shared.cmd_opts.no_prompt_history:
- filename = os.path.join(data_path, "params.txt")
- try:
- with open(filename, "r", encoding="utf8") as file:
- prompt = file.read()
- except OSError:
- pass
-
- params = parse_generation_parameters(prompt)
- script_callbacks.infotext_pasted_callback(prompt, params)
- res = []
-
- for output, key in paste_fields:
- if callable(key):
- try:
- v = key(params)
- except Exception:
- errors.report(f"Error executing {key}", exc_info=True)
- v = None
- else:
- v = params.get(key, None)
-
- if v is None:
- res.append(gr.update())
- elif isinstance(v, type_of_gr_update):
- res.append(v)
- else:
- try:
- valtype = type(output.value)
-
- if valtype == bool and v == "False":
- val = False
- elif valtype == int:
- val = float(v)
- else:
- val = valtype(v)
-
- res.append(gr.update(value=val))
- except Exception:
- res.append(gr.update())
-
- return res
-
- if override_settings_component is not None:
- already_handled_fields = {key: 1 for _, key in paste_fields}
-
- def paste_settings(params):
- vals = get_override_settings(params, skip_fields=already_handled_fields)
-
- vals_pairs = [f"{infotext_text}: {value}" for infotext_text, setting_name, value in vals]
-
- return gr.Dropdown.update(value=vals_pairs, choices=vals_pairs, visible=bool(vals_pairs))
-
- paste_fields = paste_fields + [(override_settings_component, paste_settings)]
-
- button.click(
- fn=paste_func,
- inputs=[input_comp],
- outputs=[x[0] for x in paste_fields],
- show_progress=False,
- )
- button.click(
- fn=None,
- _js=f"recalculate_prompts_{tabname}",
- inputs=[],
- outputs=[],
- show_progress=False,
- )
+from __future__ import annotations
+import base64
+import io
+import json
+import os
+import re
+import sys
+
+import gradio as gr
+from modules.paths import data_path
+from modules import shared, ui_tempdir, script_callbacks, processing, infotext_versions, images, prompt_parser, errors
+from PIL import Image
+
+sys.modules['modules.generation_parameters_copypaste'] = sys.modules[__name__] # alias for old name
+
+re_param_code = r'\s*(\w[\w \-/]+):\s*("(?:\\.|[^\\"])+"|[^,]*)(?:,|$)'
+re_param = re.compile(re_param_code)
+re_imagesize = re.compile(r"^(\d+)x(\d+)$")
+re_hypernet_hash = re.compile("\(([0-9a-f]+)\)$")
+type_of_gr_update = type(gr.update())
+
+
+class ParamBinding:
+ def __init__(self, paste_button, tabname, source_text_component=None, source_image_component=None, source_tabname=None, override_settings_component=None, paste_field_names=None):
+ self.paste_button = paste_button
+ self.tabname = tabname
+ self.source_text_component = source_text_component
+ self.source_image_component = source_image_component
+ self.source_tabname = source_tabname
+ self.override_settings_component = override_settings_component
+ self.paste_field_names = paste_field_names or []
+
+
+class PasteField(tuple):
+ def __new__(cls, component, target, *, api=None):
+ return super().__new__(cls, (component, target))
+
+ def __init__(self, component, target, *, api=None):
+ super().__init__()
+
+ self.api = api
+ self.component = component
+ self.label = target if isinstance(target, str) else None
+ self.function = target if callable(target) else None
+
+
+paste_fields: dict[str, dict] = {}
+registered_param_bindings: list[ParamBinding] = []
+
+
+def reset():
+ paste_fields.clear()
+ registered_param_bindings.clear()
+
+
+def quote(text):
+ if ',' not in str(text) and '\n' not in str(text) and ':' not in str(text):
+ return text
+
+ return json.dumps(text, ensure_ascii=False)
+
+
+def unquote(text):
+ if len(text) == 0 or text[0] != '"' or text[-1] != '"':
+ return text
+
+ try:
+ return json.loads(text)
+ except Exception:
+ return text
+
+
+def image_from_url_text(filedata):
+ if filedata is None:
+ return None
+
+ if type(filedata) == list and filedata and type(filedata[0]) == dict and filedata[0].get("is_file", False):
+ filedata = filedata[0]
+
+ if type(filedata) == dict and filedata.get("is_file", False):
+ filename = filedata["name"]
+ is_in_right_dir = ui_tempdir.check_tmp_file(shared.demo, filename)
+ assert is_in_right_dir, 'trying to open image file outside of allowed directories'
+
+ filename = filename.rsplit('?', 1)[0]
+ return images.read(filename)
+
+ if type(filedata) == list:
+ if len(filedata) == 0:
+ return None
+
+ filedata = filedata[0]
+
+ if filedata.startswith("data:image/png;base64,"):
+ filedata = filedata[len("data:image/png;base64,"):]
+
+ filedata = base64.decodebytes(filedata.encode('utf-8'))
+ image = images.read(io.BytesIO(filedata))
+ return image
+
+
+def add_paste_fields(tabname, init_img, fields, override_settings_component=None):
+
+ if fields:
+ for i in range(len(fields)):
+ if not isinstance(fields[i], PasteField):
+ fields[i] = PasteField(*fields[i])
+
+ paste_fields[tabname] = {"init_img": init_img, "fields": fields, "override_settings_component": override_settings_component}
+
+ # backwards compatibility for existing extensions
+ import modules.ui
+ if tabname == 'txt2img':
+ modules.ui.txt2img_paste_fields = fields
+ elif tabname == 'img2img':
+ modules.ui.img2img_paste_fields = fields
+
+
+def create_buttons(tabs_list):
+ buttons = {}
+ for tab in tabs_list:
+ buttons[tab] = gr.Button(f"Send to {tab}", elem_id=f"{tab}_tab")
+ return buttons
+
+
+def bind_buttons(buttons, send_image, send_generate_info):
+ """old function for backwards compatibility; do not use this, use register_paste_params_button"""
+ for tabname, button in buttons.items():
+ source_text_component = send_generate_info if isinstance(send_generate_info, gr.components.Component) else None
+ source_tabname = send_generate_info if isinstance(send_generate_info, str) else None
+
+ register_paste_params_button(ParamBinding(paste_button=button, tabname=tabname, source_text_component=source_text_component, source_image_component=send_image, source_tabname=source_tabname))
+
+
+def register_paste_params_button(binding: ParamBinding):
+ registered_param_bindings.append(binding)
+
+
+def connect_paste_params_buttons():
+ for binding in registered_param_bindings:
+ destination_image_component = paste_fields[binding.tabname]["init_img"]
+ fields = paste_fields[binding.tabname]["fields"]
+ override_settings_component = binding.override_settings_component or paste_fields[binding.tabname]["override_settings_component"]
+
+ destination_width_component = next(iter([field for field, name in fields if name == "Size-1"] if fields else []), None)
+ destination_height_component = next(iter([field for field, name in fields if name == "Size-2"] if fields else []), None)
+
+ if binding.source_image_component and destination_image_component:
+ need_send_dementions = destination_width_component and binding.tabname != 'inpaint'
+ if isinstance(binding.source_image_component, gr.Gallery):
+ func = send_image_and_dimensions if need_send_dementions else image_from_url_text
+ jsfunc = "extract_image_from_gallery"
+ else:
+ func = send_image_and_dimensions if need_send_dementions else lambda x: x
+ jsfunc = None
+
+ binding.paste_button.click(
+ fn=func,
+ _js=jsfunc,
+ inputs=[binding.source_image_component],
+ outputs=[destination_image_component, destination_width_component, destination_height_component] if need_send_dementions else [destination_image_component],
+ show_progress=False,
+ )
+
+ if binding.source_text_component is not None and fields is not None:
+ connect_paste(binding.paste_button, fields, binding.source_text_component, override_settings_component, binding.tabname)
+
+ if binding.source_tabname is not None and fields is not None:
+ paste_field_names = ['Prompt', 'Negative prompt', 'Steps', 'Face restoration'] + (["Seed"] if shared.opts.send_seed else []) + binding.paste_field_names
+ binding.paste_button.click(
+ fn=lambda *x: x,
+ inputs=[field for field, name in paste_fields[binding.source_tabname]["fields"] if name in paste_field_names],
+ outputs=[field for field, name in fields if name in paste_field_names],
+ show_progress=False,
+ )
+
+ binding.paste_button.click(
+ fn=None,
+ _js=f"switch_to_{binding.tabname}",
+ inputs=None,
+ outputs=None,
+ show_progress=False,
+ )
+
+
+def send_image_and_dimensions(x):
+ if isinstance(x, Image.Image):
+ img = x
+ else:
+ img = image_from_url_text(x)
+
+ if shared.opts.send_size and isinstance(img, Image.Image):
+ w = img.width
+ h = img.height
+ else:
+ w = gr.update()
+ h = gr.update()
+
+ return img, w, h
+
+
+def restore_old_hires_fix_params(res):
+ """for infotexts that specify old First pass size parameter, convert it into
+ width, height, and hr scale"""
+
+ firstpass_width = res.get('First pass size-1', None)
+ firstpass_height = res.get('First pass size-2', None)
+
+ if shared.opts.use_old_hires_fix_width_height:
+ hires_width = int(res.get("Hires resize-1", 0))
+ hires_height = int(res.get("Hires resize-2", 0))
+
+ if hires_width and hires_height:
+ res['Size-1'] = hires_width
+ res['Size-2'] = hires_height
+ return
+
+ if firstpass_width is None or firstpass_height is None:
+ return
+
+ firstpass_width, firstpass_height = int(firstpass_width), int(firstpass_height)
+ width = int(res.get("Size-1", 512))
+ height = int(res.get("Size-2", 512))
+
+ if firstpass_width == 0 or firstpass_height == 0:
+ firstpass_width, firstpass_height = processing.old_hires_fix_first_pass_dimensions(width, height)
+
+ res['Size-1'] = firstpass_width
+ res['Size-2'] = firstpass_height
+ res['Hires resize-1'] = width
+ res['Hires resize-2'] = height
+
+
+def parse_generation_parameters(x: str, skip_fields: list[str] | None = None):
+ """parses generation parameters string, the one you see in text field under the picture in UI:
+```
+girl with an artist's beret, determined, blue eyes, desert scene, computer monitors, heavy makeup, by Alphonse Mucha and Charlie Bowater, ((eyeshadow)), (coquettish), detailed, intricate
+Negative prompt: ugly, fat, obese, chubby, (((deformed))), [blurry], bad anatomy, disfigured, poorly drawn face, mutation, mutated, (extra_limb), (ugly), (poorly drawn hands), messy drawing
+Steps: 20, Sampler: Euler a, CFG scale: 7, Seed: 965400086, Size: 512x512, Model hash: 45dee52b
+```
+
+ returns a dict with field values
+ """
+ if skip_fields is None:
+ skip_fields = shared.opts.infotext_skip_pasting
+
+ res = {}
+
+ prompt = ""
+ negative_prompt = ""
+
+ done_with_prompt = False
+
+ *lines, lastline = x.strip().split("\n")
+ if len(re_param.findall(lastline)) < 3:
+ lines.append(lastline)
+ lastline = ''
+
+ for line in lines:
+ line = line.strip()
+ if line.startswith("Negative prompt:"):
+ done_with_prompt = True
+ line = line[16:].strip()
+ if done_with_prompt:
+ negative_prompt += ("" if negative_prompt == "" else "\n") + line
+ else:
+ prompt += ("" if prompt == "" else "\n") + line
+
+ for k, v in re_param.findall(lastline):
+ try:
+ if v[0] == '"' and v[-1] == '"':
+ v = unquote(v)
+
+ m = re_imagesize.match(v)
+ if m is not None:
+ res[f"{k}-1"] = m.group(1)
+ res[f"{k}-2"] = m.group(2)
+ else:
+ res[k] = v
+ except Exception:
+ print(f"Error parsing \"{k}: {v}\"")
+
+ # Extract styles from prompt
+ if shared.opts.infotext_styles != "Ignore":
+ found_styles, prompt_no_styles, negative_prompt_no_styles = shared.prompt_styles.extract_styles_from_prompt(prompt, negative_prompt)
+
+ same_hr_styles = True
+ if ("Hires prompt" in res or "Hires negative prompt" in res) and (infotext_ver > infotext_versions.v180_hr_styles if (infotext_ver := infotext_versions.parse_version(res.get("Version"))) else True):
+ hr_prompt, hr_negative_prompt = res.get("Hires prompt", prompt), res.get("Hires negative prompt", negative_prompt)
+ hr_found_styles, hr_prompt_no_styles, hr_negative_prompt_no_styles = shared.prompt_styles.extract_styles_from_prompt(hr_prompt, hr_negative_prompt)
+ if same_hr_styles := found_styles == hr_found_styles:
+ res["Hires prompt"] = '' if hr_prompt_no_styles == prompt_no_styles else hr_prompt_no_styles
+ res['Hires negative prompt'] = '' if hr_negative_prompt_no_styles == negative_prompt_no_styles else hr_negative_prompt_no_styles
+
+ if same_hr_styles:
+ prompt, negative_prompt = prompt_no_styles, negative_prompt_no_styles
+ if (shared.opts.infotext_styles == "Apply if any" and found_styles) or shared.opts.infotext_styles == "Apply":
+ res['Styles array'] = found_styles
+
+ res["Prompt"] = prompt
+ res["Negative prompt"] = negative_prompt
+
+ # Missing CLIP skip means it was set to 1 (the default)
+ if "Clip skip" not in res:
+ res["Clip skip"] = "1"
+
+ hypernet = res.get("Hypernet", None)
+ if hypernet is not None:
+ res["Prompt"] += f"""<hypernet:{hypernet}:{res.get("Hypernet strength", "1.0")}>"""
+
+ if "Hires resize-1" not in res:
+ res["Hires resize-1"] = 0
+ res["Hires resize-2"] = 0
+
+ if "Hires sampler" not in res:
+ res["Hires sampler"] = "Use same sampler"
+
+ if "Hires schedule type" not in res:
+ res["Hires schedule type"] = "Use same scheduler"
+
+ if "Hires checkpoint" not in res:
+ res["Hires checkpoint"] = "Use same checkpoint"
+
+ if "Hires prompt" not in res:
+ res["Hires prompt"] = ""
+
+ if "Hires negative prompt" not in res:
+ res["Hires negative prompt"] = ""
+
+ if "Mask mode" not in res:
+ res["Mask mode"] = "Inpaint masked"
+
+ if "Masked content" not in res:
+ res["Masked content"] = 'original'
+
+ if "Inpaint area" not in res:
+ res["Inpaint area"] = "Whole picture"
+
+ if "Masked area padding" not in res:
+ res["Masked area padding"] = 32
+
+ restore_old_hires_fix_params(res)
+
+ # Missing RNG means the default was set, which is GPU RNG
+ if "RNG" not in res:
+ res["RNG"] = "GPU"
+
+ if "Schedule type" not in res:
+ res["Schedule type"] = "Automatic"
+
+ if "Schedule max sigma" not in res:
+ res["Schedule max sigma"] = 0
+
+ if "Schedule min sigma" not in res:
+ res["Schedule min sigma"] = 0
+
+ if "Schedule rho" not in res:
+ res["Schedule rho"] = 0
+
+ if "VAE Encoder" not in res:
+ res["VAE Encoder"] = "Full"
+
+ if "VAE Decoder" not in res:
+ res["VAE Decoder"] = "Full"
+
+ if "FP8 weight" not in res:
+ res["FP8 weight"] = "Disable"
+
+ if "Cache FP16 weight for LoRA" not in res and res["FP8 weight"] != "Disable":
+ res["Cache FP16 weight for LoRA"] = False
+
+ prompt_attention = prompt_parser.parse_prompt_attention(prompt)
+ prompt_attention += prompt_parser.parse_prompt_attention(negative_prompt)
+ prompt_uses_emphasis = len(prompt_attention) != len([p for p in prompt_attention if p[1] == 1.0 or p[0] == 'BREAK'])
+ if "Emphasis" not in res and prompt_uses_emphasis:
+ res["Emphasis"] = "Original"
+
+ if "Refiner switch by sampling steps" not in res:
+ res["Refiner switch by sampling steps"] = False
+
+ infotext_versions.backcompat(res)
+
+ for key in skip_fields:
+ res.pop(key, None)
+
+ return res
+
+
+infotext_to_setting_name_mapping = [
+
+]
+"""Mapping of infotext labels to setting names. Only left for backwards compatibility - use OptionInfo(..., infotext='...') instead.
+Example content:
+
+infotext_to_setting_name_mapping = [
+ ('Conditional mask weight', 'inpainting_mask_weight'),
+ ('Model hash', 'sd_model_checkpoint'),
+ ('ENSD', 'eta_noise_seed_delta'),
+ ('Schedule type', 'k_sched_type'),
+]
+"""
+
+
+def create_override_settings_dict(text_pairs):
+ """creates processing's override_settings parameters from gradio's multiselect
+
+ Example input:
+ ['Clip skip: 2', 'Model hash: e6e99610c4', 'ENSD: 31337']
+
+ Example output:
+ {'CLIP_stop_at_last_layers': 2, 'sd_model_checkpoint': 'e6e99610c4', 'eta_noise_seed_delta': 31337}
+ """
+
+ res = {}
+
+ params = {}
+ for pair in text_pairs:
+ k, v = pair.split(":", maxsplit=1)
+
+ params[k] = v.strip()
+
+ mapping = [(info.infotext, k) for k, info in shared.opts.data_labels.items() if info.infotext]
+ for param_name, setting_name in mapping + infotext_to_setting_name_mapping:
+ value = params.get(param_name, None)
+
+ if value is None:
+ continue
+
+ res[setting_name] = shared.opts.cast_value(setting_name, value)
+
+ return res
+
+
+def get_override_settings(params, *, skip_fields=None):
+ """Returns a list of settings overrides from the infotext parameters dictionary.
+
+ This function checks the `params` dictionary for any keys that correspond to settings in `shared.opts` and returns
+ a list of tuples containing the parameter name, setting name, and new value cast to correct type.
+
+ It checks for conditions before adding an override:
+ - ignores settings that match the current value
+ - ignores parameter keys present in skip_fields argument.
+
+ Example input:
+ {"Clip skip": "2"}
+
+ Example output:
+ [("Clip skip", "CLIP_stop_at_last_layers", 2)]
+ """
+
+ res = []
+
+ mapping = [(info.infotext, k) for k, info in shared.opts.data_labels.items() if info.infotext]
+ for param_name, setting_name in mapping + infotext_to_setting_name_mapping:
+ if param_name in (skip_fields or {}):
+ continue
+
+ v = params.get(param_name, None)
+ if v is None:
+ continue
+
+ if setting_name == "sd_model_checkpoint" and shared.opts.disable_weights_auto_swap:
+ continue
+
+ v = shared.opts.cast_value(setting_name, v)
+ current_value = getattr(shared.opts, setting_name, None)
+
+ if v == current_value:
+ continue
+
+ res.append((param_name, setting_name, v))
+
+ return res
+
+
+def connect_paste(button, paste_fields, input_comp, override_settings_component, tabname):
+ def paste_func(prompt):
+ if not prompt and not shared.cmd_opts.hide_ui_dir_config and not shared.cmd_opts.no_prompt_history:
+ filename = os.path.join(data_path, "params.txt")
+ try:
+ with open(filename, "r", encoding="utf8") as file:
+ prompt = file.read()
+ except OSError:
+ pass
+
+ params = parse_generation_parameters(prompt)
+ script_callbacks.infotext_pasted_callback(prompt, params)
+ res = []
+
+ for output, key in paste_fields:
+ if callable(key):
+ try:
+ v = key(params)
+ except Exception:
+ errors.report(f"Error executing {key}", exc_info=True)
+ v = None
+ else:
+ v = params.get(key, None)
+
+ if v is None:
+ res.append(gr.update())
+ elif isinstance(v, type_of_gr_update):
+ res.append(v)
+ else:
+ try:
+ valtype = type(output.value)
+
+ if valtype == bool and v == "False":
+ val = False
+ elif valtype == int:
+ val = float(v)
+ else:
+ val = valtype(v)
+
+ res.append(gr.update(value=val))
+ except Exception:
+ res.append(gr.update())
+
+ return res
+
+ if override_settings_component is not None:
+ already_handled_fields = {key: 1 for _, key in paste_fields}
+
+ def paste_settings(params):
+ vals = get_override_settings(params, skip_fields=already_handled_fields)
+
+ vals_pairs = [f"{infotext_text}: {value}" for infotext_text, setting_name, value in vals]
+
+ return gr.Dropdown.update(value=vals_pairs, choices=vals_pairs, visible=bool(vals_pairs))
+
+ paste_fields = paste_fields + [(override_settings_component, paste_settings)]
+
+ button.click(
+ fn=paste_func,
+ inputs=[input_comp],
+ outputs=[x[0] for x in paste_fields],
+ show_progress=False,
+ )
+ button.click(
+ fn=None,
+ _js=f"recalculate_prompts_{tabname}",
+ inputs=[],
+ outputs=[],
+ show_progress=False,
+ )
+
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/infotext_utils.py |
Improve my code by adding docstrings | from PIL import Image, ImageFilter, ImageOps
def get_crop_region_v2(mask, pad=0):
mask = mask if isinstance(mask, Image.Image) else Image.fromarray(mask)
if box := mask.getbbox():
x1, y1, x2, y2 = box
return (max(x1 - pad, 0), max(y1 - pad, 0), min(x2 + pad, mask.size[0]), min(y2 + pad, mask.size[1])) if pad else box
def get_crop_region(mask, pad=0):
mask = mask if isinstance(mask, Image.Image) else Image.fromarray(mask)
if box := get_crop_region_v2(mask, pad):
return box
x1, y1 = mask.size
x2 = y2 = 0
return max(x1 - pad, 0), max(y1 - pad, 0), min(x2 + pad, mask.size[0]), min(y2 + pad, mask.size[1])
def expand_crop_region(crop_region, processing_width, processing_height, image_width, image_height):
x1, y1, x2, y2 = crop_region
ratio_crop_region = (x2 - x1) / (y2 - y1)
ratio_processing = processing_width / processing_height
if ratio_crop_region > ratio_processing:
desired_height = (x2 - x1) / ratio_processing
desired_height_diff = int(desired_height - (y2-y1))
y1 -= desired_height_diff//2
y2 += desired_height_diff - desired_height_diff//2
if y2 >= image_height:
diff = y2 - image_height
y2 -= diff
y1 -= diff
if y1 < 0:
y2 -= y1
y1 -= y1
if y2 >= image_height:
y2 = image_height
else:
desired_width = (y2 - y1) * ratio_processing
desired_width_diff = int(desired_width - (x2-x1))
x1 -= desired_width_diff//2
x2 += desired_width_diff - desired_width_diff//2
if x2 >= image_width:
diff = x2 - image_width
x2 -= diff
x1 -= diff
if x1 < 0:
x2 -= x1
x1 -= x1
if x2 >= image_width:
x2 = image_width
return x1, y1, x2, y2
def fill(image, mask):
image_mod = Image.new('RGBA', (image.width, image.height))
image_masked = Image.new('RGBa', (image.width, image.height))
image_masked.paste(image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(mask.convert('L')))
image_masked = image_masked.convert('RGBa')
for radius, repeats in [(256, 1), (64, 1), (16, 2), (4, 4), (2, 2), (0, 1)]:
blurred = image_masked.filter(ImageFilter.GaussianBlur(radius)).convert('RGBA')
for _ in range(repeats):
image_mod.alpha_composite(blurred)
return image_mod.convert("RGB")
| --- +++ @@ -1,73 +1,96 @@-from PIL import Image, ImageFilter, ImageOps
-
-
-def get_crop_region_v2(mask, pad=0):
- mask = mask if isinstance(mask, Image.Image) else Image.fromarray(mask)
- if box := mask.getbbox():
- x1, y1, x2, y2 = box
- return (max(x1 - pad, 0), max(y1 - pad, 0), min(x2 + pad, mask.size[0]), min(y2 + pad, mask.size[1])) if pad else box
-
-
-def get_crop_region(mask, pad=0):
- mask = mask if isinstance(mask, Image.Image) else Image.fromarray(mask)
- if box := get_crop_region_v2(mask, pad):
- return box
- x1, y1 = mask.size
- x2 = y2 = 0
- return max(x1 - pad, 0), max(y1 - pad, 0), min(x2 + pad, mask.size[0]), min(y2 + pad, mask.size[1])
-
-
-def expand_crop_region(crop_region, processing_width, processing_height, image_width, image_height):
-
- x1, y1, x2, y2 = crop_region
-
- ratio_crop_region = (x2 - x1) / (y2 - y1)
- ratio_processing = processing_width / processing_height
-
- if ratio_crop_region > ratio_processing:
- desired_height = (x2 - x1) / ratio_processing
- desired_height_diff = int(desired_height - (y2-y1))
- y1 -= desired_height_diff//2
- y2 += desired_height_diff - desired_height_diff//2
- if y2 >= image_height:
- diff = y2 - image_height
- y2 -= diff
- y1 -= diff
- if y1 < 0:
- y2 -= y1
- y1 -= y1
- if y2 >= image_height:
- y2 = image_height
- else:
- desired_width = (y2 - y1) * ratio_processing
- desired_width_diff = int(desired_width - (x2-x1))
- x1 -= desired_width_diff//2
- x2 += desired_width_diff - desired_width_diff//2
- if x2 >= image_width:
- diff = x2 - image_width
- x2 -= diff
- x1 -= diff
- if x1 < 0:
- x2 -= x1
- x1 -= x1
- if x2 >= image_width:
- x2 = image_width
-
- return x1, y1, x2, y2
-
-
-def fill(image, mask):
-
- image_mod = Image.new('RGBA', (image.width, image.height))
-
- image_masked = Image.new('RGBa', (image.width, image.height))
- image_masked.paste(image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(mask.convert('L')))
-
- image_masked = image_masked.convert('RGBa')
-
- for radius, repeats in [(256, 1), (64, 1), (16, 2), (4, 4), (2, 2), (0, 1)]:
- blurred = image_masked.filter(ImageFilter.GaussianBlur(radius)).convert('RGBA')
- for _ in range(repeats):
- image_mod.alpha_composite(blurred)
-
- return image_mod.convert("RGB")
+from PIL import Image, ImageFilter, ImageOps
+
+
+def get_crop_region_v2(mask, pad=0):
+ """
+ Finds a rectangular region that contains all masked ares in a mask.
+ Returns None if mask is completely black mask (all 0)
+
+ Parameters:
+ mask: PIL.Image.Image L mode or numpy 1d array
+ pad: int number of pixels that the region will be extended on all sides
+ Returns: (x1, y1, x2, y2) | None
+
+ Introduced post 1.9.0
+ """
+ mask = mask if isinstance(mask, Image.Image) else Image.fromarray(mask)
+ if box := mask.getbbox():
+ x1, y1, x2, y2 = box
+ return (max(x1 - pad, 0), max(y1 - pad, 0), min(x2 + pad, mask.size[0]), min(y2 + pad, mask.size[1])) if pad else box
+
+
+def get_crop_region(mask, pad=0):
+ """
+ Same function as get_crop_region_v2 but handles completely black mask (all 0) differently
+ when mask all black still return coordinates but the coordinates may be invalid ie x2>x1 or y2>y1
+ Notes: it is possible for the coordinates to be "valid" again if pad size is sufficiently large
+ (mask_size.x-pad, mask_size.y-pad, pad, pad)
+
+ Extension developer should use get_crop_region_v2 instead unless for compatibility considerations.
+ """
+ mask = mask if isinstance(mask, Image.Image) else Image.fromarray(mask)
+ if box := get_crop_region_v2(mask, pad):
+ return box
+ x1, y1 = mask.size
+ x2 = y2 = 0
+ return max(x1 - pad, 0), max(y1 - pad, 0), min(x2 + pad, mask.size[0]), min(y2 + pad, mask.size[1])
+
+
+def expand_crop_region(crop_region, processing_width, processing_height, image_width, image_height):
+ """expands crop region get_crop_region() to match the ratio of the image the region will processed in; returns expanded region
+ for example, if user drew mask in a 128x32 region, and the dimensions for processing are 512x512, the region will be expanded to 128x128."""
+
+ x1, y1, x2, y2 = crop_region
+
+ ratio_crop_region = (x2 - x1) / (y2 - y1)
+ ratio_processing = processing_width / processing_height
+
+ if ratio_crop_region > ratio_processing:
+ desired_height = (x2 - x1) / ratio_processing
+ desired_height_diff = int(desired_height - (y2-y1))
+ y1 -= desired_height_diff//2
+ y2 += desired_height_diff - desired_height_diff//2
+ if y2 >= image_height:
+ diff = y2 - image_height
+ y2 -= diff
+ y1 -= diff
+ if y1 < 0:
+ y2 -= y1
+ y1 -= y1
+ if y2 >= image_height:
+ y2 = image_height
+ else:
+ desired_width = (y2 - y1) * ratio_processing
+ desired_width_diff = int(desired_width - (x2-x1))
+ x1 -= desired_width_diff//2
+ x2 += desired_width_diff - desired_width_diff//2
+ if x2 >= image_width:
+ diff = x2 - image_width
+ x2 -= diff
+ x1 -= diff
+ if x1 < 0:
+ x2 -= x1
+ x1 -= x1
+ if x2 >= image_width:
+ x2 = image_width
+
+ return x1, y1, x2, y2
+
+
+def fill(image, mask):
+ """fills masked regions with colors from image using blur. Not extremely effective."""
+
+ image_mod = Image.new('RGBA', (image.width, image.height))
+
+ image_masked = Image.new('RGBa', (image.width, image.height))
+ image_masked.paste(image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(mask.convert('L')))
+
+ image_masked = image_masked.convert('RGBa')
+
+ for radius, repeats in [(256, 1), (64, 1), (16, 2), (4, 4), (2, 2), (0, 1)]:
+ blurred = image_masked.filter(ImageFilter.GaussianBlur(radius)).convert('RGBA')
+ for _ in range(repeats):
+ image_mod.alpha_composite(blurred)
+
+ return image_mod.convert("RGB")
+
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/masking.py |
Document helper functions with docstrings | from __future__ import annotations
import importlib
import logging
import os
from typing import TYPE_CHECKING
from urllib.parse import urlparse
import torch
from modules import shared
from modules.upscaler import Upscaler, UpscalerLanczos, UpscalerNearest, UpscalerNone
if TYPE_CHECKING:
import spandrel
logger = logging.getLogger(__name__)
def load_file_from_url(
url: str,
*,
model_dir: str,
progress: bool = True,
file_name: str | None = None,
hash_prefix: str | None = None,
) -> str:
os.makedirs(model_dir, exist_ok=True)
if not file_name:
parts = urlparse(url)
file_name = os.path.basename(parts.path)
cached_file = os.path.abspath(os.path.join(model_dir, file_name))
if not os.path.exists(cached_file):
print(f'Downloading: "{url}" to {cached_file}\n')
from torch.hub import download_url_to_file
download_url_to_file(url, cached_file, progress=progress, hash_prefix=hash_prefix)
return cached_file
def load_models(model_path: str, model_url: str = None, command_path: str = None, ext_filter=None, download_name=None, ext_blacklist=None, hash_prefix=None) -> list:
output = []
try:
places = []
if command_path is not None and command_path != model_path:
pretrained_path = os.path.join(command_path, 'experiments/pretrained_models')
if os.path.exists(pretrained_path):
print(f"Appending path: {pretrained_path}")
places.append(pretrained_path)
elif os.path.exists(command_path):
places.append(command_path)
places.append(model_path)
for place in places:
for full_path in shared.walk_files(place, allowed_extensions=ext_filter):
if os.path.islink(full_path) and not os.path.exists(full_path):
print(f"Skipping broken symlink: {full_path}")
continue
if ext_blacklist is not None and any(full_path.endswith(x) for x in ext_blacklist):
continue
if full_path not in output:
output.append(full_path)
if model_url is not None and len(output) == 0:
if download_name is not None:
output.append(load_file_from_url(model_url, model_dir=places[0], file_name=download_name, hash_prefix=hash_prefix))
else:
output.append(model_url)
except Exception:
pass
return output
def friendly_name(file: str):
if file.startswith("http"):
file = urlparse(file).path
file = os.path.basename(file)
model_name, extension = os.path.splitext(file)
return model_name
def load_upscalers():
# We can only do this 'magic' method to dynamically load upscalers if they are referenced,
# so we'll try to import any _model.py files before looking in __subclasses__
modules_dir = os.path.join(shared.script_path, "modules")
for file in os.listdir(modules_dir):
if "_model.py" in file:
model_name = file.replace("_model.py", "")
full_model = f"modules.{model_name}_model"
try:
importlib.import_module(full_model)
except Exception:
pass
data = []
commandline_options = vars(shared.cmd_opts)
# some of upscaler classes will not go away after reloading their modules, and we'll end
# up with two copies of those classes. The newest copy will always be the last in the list,
# so we go from end to beginning and ignore duplicates
used_classes = {}
for cls in reversed(Upscaler.__subclasses__()):
classname = str(cls)
if classname not in used_classes:
used_classes[classname] = cls
for cls in reversed(used_classes.values()):
name = cls.__name__
cmd_name = f"{name.lower().replace('upscaler', '')}_models_path"
commandline_model_path = commandline_options.get(cmd_name, None)
scaler = cls(commandline_model_path)
scaler.user_path = commandline_model_path
scaler.model_download_path = commandline_model_path or scaler.model_path
data += scaler.scalers
shared.sd_upscalers = sorted(
data,
# Special case for UpscalerNone keeps it at the beginning of the list.
key=lambda x: x.name.lower() if not isinstance(x.scaler, (UpscalerNone, UpscalerLanczos, UpscalerNearest)) else ""
)
# None: not loaded, False: failed to load, True: loaded
_spandrel_extra_init_state = None
def _init_spandrel_extra_archs() -> None:
global _spandrel_extra_init_state
if _spandrel_extra_init_state is not None:
return
try:
import spandrel
import spandrel_extra_arches
spandrel.MAIN_REGISTRY.add(*spandrel_extra_arches.EXTRA_REGISTRY)
_spandrel_extra_init_state = True
except Exception:
logger.warning("Failed to load spandrel_extra_arches", exc_info=True)
_spandrel_extra_init_state = False
def load_spandrel_model(
path: str | os.PathLike,
*,
device: str | torch.device | None,
prefer_half: bool = False,
dtype: str | torch.dtype | None = None,
expected_architecture: str | None = None,
) -> spandrel.ModelDescriptor:
global _spandrel_extra_init_state
import spandrel
_init_spandrel_extra_archs()
model_descriptor = spandrel.ModelLoader(device=device).load_from_file(str(path))
arch = model_descriptor.architecture
if expected_architecture and arch.name != expected_architecture:
logger.warning(
f"Model {path!r} is not a {expected_architecture!r} model (got {arch.name!r})",
)
half = False
if prefer_half:
if model_descriptor.supports_half:
model_descriptor.model.half()
half = True
else:
logger.info("Model %s does not support half precision, ignoring --half", path)
if dtype:
model_descriptor.model.to(dtype=dtype)
model_descriptor.model.eval()
logger.debug(
"Loaded %s from %s (device=%s, half=%s, dtype=%s)",
arch, path, device, half, dtype,
)
return model_descriptor | --- +++ @@ -25,6 +25,10 @@ file_name: str | None = None,
hash_prefix: str | None = None,
) -> str:
+ """Download a file from `url` into `model_dir`, using the file present if possible.
+
+ Returns the path to the downloaded file.
+ """
os.makedirs(model_dir, exist_ok=True)
if not file_name:
parts = urlparse(url)
@@ -38,6 +42,17 @@
def load_models(model_path: str, model_url: str = None, command_path: str = None, ext_filter=None, download_name=None, ext_blacklist=None, hash_prefix=None) -> list:
+ """
+ A one-and done loader to try finding the desired models in specified directories.
+
+ @param download_name: Specify to download from model_url immediately.
+ @param model_url: If no other models are found, this will be downloaded on upscale.
+ @param model_path: The location to store/find models in.
+ @param command_path: A command-line argument to search for models in first.
+ @param ext_filter: An optional list of filename extensions to filter by
+ @param hash_prefix: the expected sha256 of the model_url
+ @return: A list of paths containing the desired model(s)
+ """
output = []
try:
@@ -129,6 +144,9 @@
def _init_spandrel_extra_archs() -> None:
+ """
+ Try to initialize `spandrel_extra_archs` (exactly once).
+ """
global _spandrel_extra_init_state
if _spandrel_extra_init_state is not None:
return
@@ -176,4 +194,4 @@ "Loaded %s from %s (device=%s, half=%s, dtype=%s)",
arch, path, device, half, dtype,
)
- return model_descriptor+ return model_descriptor
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/modelloader.py |
Write docstrings describing functionality | import torch
from modules import devices, rng_philox, shared
def randn(seed, shape, generator=None):
manual_seed(seed)
if shared.opts.randn_source == "NV":
return torch.asarray((generator or nv_rng).randn(shape), device=devices.device)
if shared.opts.randn_source == "CPU" or devices.device.type == 'mps':
return torch.randn(shape, device=devices.cpu, generator=generator).to(devices.device)
return torch.randn(shape, device=devices.device, generator=generator)
def randn_local(seed, shape):
if shared.opts.randn_source == "NV":
rng = rng_philox.Generator(seed)
return torch.asarray(rng.randn(shape), device=devices.device)
local_device = devices.cpu if shared.opts.randn_source == "CPU" or devices.device.type == 'mps' else devices.device
local_generator = torch.Generator(local_device).manual_seed(int(seed))
return torch.randn(shape, device=local_device, generator=local_generator).to(devices.device)
def randn_like(x):
if shared.opts.randn_source == "NV":
return torch.asarray(nv_rng.randn(x.shape), device=x.device, dtype=x.dtype)
if shared.opts.randn_source == "CPU" or x.device.type == 'mps':
return torch.randn_like(x, device=devices.cpu).to(x.device)
return torch.randn_like(x)
def randn_without_seed(shape, generator=None):
if shared.opts.randn_source == "NV":
return torch.asarray((generator or nv_rng).randn(shape), device=devices.device)
if shared.opts.randn_source == "CPU" or devices.device.type == 'mps':
return torch.randn(shape, device=devices.cpu, generator=generator).to(devices.device)
return torch.randn(shape, device=devices.device, generator=generator)
def manual_seed(seed):
if shared.opts.randn_source == "NV":
global nv_rng
nv_rng = rng_philox.Generator(seed)
return
torch.manual_seed(seed)
def create_generator(seed):
if shared.opts.randn_source == "NV":
return rng_philox.Generator(seed)
device = devices.cpu if shared.opts.randn_source == "CPU" or devices.device.type == 'mps' else devices.device
generator = torch.Generator(device).manual_seed(int(seed))
return generator
# from https://discuss.pytorch.org/t/help-regarding-slerp-function-for-generative-model-sampling/32475/3
def slerp(val, low, high):
low_norm = low/torch.norm(low, dim=1, keepdim=True)
high_norm = high/torch.norm(high, dim=1, keepdim=True)
dot = (low_norm*high_norm).sum(1)
if dot.mean() > 0.9995:
return low * val + high * (1 - val)
omega = torch.acos(dot)
so = torch.sin(omega)
res = (torch.sin((1.0-val)*omega)/so).unsqueeze(1)*low + (torch.sin(val*omega)/so).unsqueeze(1) * high
return res
class ImageRNG:
def __init__(self, shape, seeds, subseeds=None, subseed_strength=0.0, seed_resize_from_h=0, seed_resize_from_w=0):
self.shape = tuple(map(int, shape))
self.seeds = seeds
self.subseeds = subseeds
self.subseed_strength = subseed_strength
self.seed_resize_from_h = seed_resize_from_h
self.seed_resize_from_w = seed_resize_from_w
self.generators = [create_generator(seed) for seed in seeds]
self.is_first = True
def first(self):
noise_shape = self.shape if self.seed_resize_from_h <= 0 or self.seed_resize_from_w <= 0 else (self.shape[0], int(self.seed_resize_from_h) // 8, int(self.seed_resize_from_w // 8))
xs = []
for i, (seed, generator) in enumerate(zip(self.seeds, self.generators)):
subnoise = None
if self.subseeds is not None and self.subseed_strength != 0:
subseed = 0 if i >= len(self.subseeds) else self.subseeds[i]
subnoise = randn(subseed, noise_shape)
if noise_shape != self.shape:
noise = randn(seed, noise_shape)
else:
noise = randn(seed, self.shape, generator=generator)
if subnoise is not None:
noise = slerp(self.subseed_strength, noise, subnoise)
if noise_shape != self.shape:
x = randn(seed, self.shape, generator=generator)
dx = (self.shape[2] - noise_shape[2]) // 2
dy = (self.shape[1] - noise_shape[1]) // 2
w = noise_shape[2] if dx >= 0 else noise_shape[2] + 2 * dx
h = noise_shape[1] if dy >= 0 else noise_shape[1] + 2 * dy
tx = 0 if dx < 0 else dx
ty = 0 if dy < 0 else dy
dx = max(-dx, 0)
dy = max(-dy, 0)
x[:, ty:ty + h, tx:tx + w] = noise[:, dy:dy + h, dx:dx + w]
noise = x
xs.append(noise)
eta_noise_seed_delta = shared.opts.eta_noise_seed_delta or 0
if eta_noise_seed_delta:
self.generators = [create_generator(seed + eta_noise_seed_delta) for seed in self.seeds]
return torch.stack(xs).to(shared.device)
def next(self):
if self.is_first:
self.is_first = False
return self.first()
xs = []
for generator in self.generators:
x = randn_without_seed(self.shape, generator=generator)
xs.append(x)
return torch.stack(xs).to(shared.device)
devices.randn = randn
devices.randn_local = randn_local
devices.randn_like = randn_like
devices.randn_without_seed = randn_without_seed
devices.manual_seed = manual_seed | --- +++ @@ -1,157 +1,170 @@-import torch
-
-from modules import devices, rng_philox, shared
-
-
-def randn(seed, shape, generator=None):
-
- manual_seed(seed)
-
- if shared.opts.randn_source == "NV":
- return torch.asarray((generator or nv_rng).randn(shape), device=devices.device)
-
- if shared.opts.randn_source == "CPU" or devices.device.type == 'mps':
- return torch.randn(shape, device=devices.cpu, generator=generator).to(devices.device)
-
- return torch.randn(shape, device=devices.device, generator=generator)
-
-
-def randn_local(seed, shape):
-
- if shared.opts.randn_source == "NV":
- rng = rng_philox.Generator(seed)
- return torch.asarray(rng.randn(shape), device=devices.device)
-
- local_device = devices.cpu if shared.opts.randn_source == "CPU" or devices.device.type == 'mps' else devices.device
- local_generator = torch.Generator(local_device).manual_seed(int(seed))
- return torch.randn(shape, device=local_device, generator=local_generator).to(devices.device)
-
-
-def randn_like(x):
-
- if shared.opts.randn_source == "NV":
- return torch.asarray(nv_rng.randn(x.shape), device=x.device, dtype=x.dtype)
-
- if shared.opts.randn_source == "CPU" or x.device.type == 'mps':
- return torch.randn_like(x, device=devices.cpu).to(x.device)
-
- return torch.randn_like(x)
-
-
-def randn_without_seed(shape, generator=None):
-
- if shared.opts.randn_source == "NV":
- return torch.asarray((generator or nv_rng).randn(shape), device=devices.device)
-
- if shared.opts.randn_source == "CPU" or devices.device.type == 'mps':
- return torch.randn(shape, device=devices.cpu, generator=generator).to(devices.device)
-
- return torch.randn(shape, device=devices.device, generator=generator)
-
-
-def manual_seed(seed):
-
- if shared.opts.randn_source == "NV":
- global nv_rng
- nv_rng = rng_philox.Generator(seed)
- return
-
- torch.manual_seed(seed)
-
-
-def create_generator(seed):
- if shared.opts.randn_source == "NV":
- return rng_philox.Generator(seed)
-
- device = devices.cpu if shared.opts.randn_source == "CPU" or devices.device.type == 'mps' else devices.device
- generator = torch.Generator(device).manual_seed(int(seed))
- return generator
-
-
-# from https://discuss.pytorch.org/t/help-regarding-slerp-function-for-generative-model-sampling/32475/3
-def slerp(val, low, high):
- low_norm = low/torch.norm(low, dim=1, keepdim=True)
- high_norm = high/torch.norm(high, dim=1, keepdim=True)
- dot = (low_norm*high_norm).sum(1)
-
- if dot.mean() > 0.9995:
- return low * val + high * (1 - val)
-
- omega = torch.acos(dot)
- so = torch.sin(omega)
- res = (torch.sin((1.0-val)*omega)/so).unsqueeze(1)*low + (torch.sin(val*omega)/so).unsqueeze(1) * high
- return res
-
-
-class ImageRNG:
- def __init__(self, shape, seeds, subseeds=None, subseed_strength=0.0, seed_resize_from_h=0, seed_resize_from_w=0):
- self.shape = tuple(map(int, shape))
- self.seeds = seeds
- self.subseeds = subseeds
- self.subseed_strength = subseed_strength
- self.seed_resize_from_h = seed_resize_from_h
- self.seed_resize_from_w = seed_resize_from_w
-
- self.generators = [create_generator(seed) for seed in seeds]
-
- self.is_first = True
-
- def first(self):
- noise_shape = self.shape if self.seed_resize_from_h <= 0 or self.seed_resize_from_w <= 0 else (self.shape[0], int(self.seed_resize_from_h) // 8, int(self.seed_resize_from_w // 8))
-
- xs = []
-
- for i, (seed, generator) in enumerate(zip(self.seeds, self.generators)):
- subnoise = None
- if self.subseeds is not None and self.subseed_strength != 0:
- subseed = 0 if i >= len(self.subseeds) else self.subseeds[i]
- subnoise = randn(subseed, noise_shape)
-
- if noise_shape != self.shape:
- noise = randn(seed, noise_shape)
- else:
- noise = randn(seed, self.shape, generator=generator)
-
- if subnoise is not None:
- noise = slerp(self.subseed_strength, noise, subnoise)
-
- if noise_shape != self.shape:
- x = randn(seed, self.shape, generator=generator)
- dx = (self.shape[2] - noise_shape[2]) // 2
- dy = (self.shape[1] - noise_shape[1]) // 2
- w = noise_shape[2] if dx >= 0 else noise_shape[2] + 2 * dx
- h = noise_shape[1] if dy >= 0 else noise_shape[1] + 2 * dy
- tx = 0 if dx < 0 else dx
- ty = 0 if dy < 0 else dy
- dx = max(-dx, 0)
- dy = max(-dy, 0)
-
- x[:, ty:ty + h, tx:tx + w] = noise[:, dy:dy + h, dx:dx + w]
- noise = x
-
- xs.append(noise)
-
- eta_noise_seed_delta = shared.opts.eta_noise_seed_delta or 0
- if eta_noise_seed_delta:
- self.generators = [create_generator(seed + eta_noise_seed_delta) for seed in self.seeds]
-
- return torch.stack(xs).to(shared.device)
-
- def next(self):
- if self.is_first:
- self.is_first = False
- return self.first()
-
- xs = []
- for generator in self.generators:
- x = randn_without_seed(self.shape, generator=generator)
- xs.append(x)
-
- return torch.stack(xs).to(shared.device)
-
-
-devices.randn = randn
-devices.randn_local = randn_local
-devices.randn_like = randn_like
-devices.randn_without_seed = randn_without_seed
-devices.manual_seed = manual_seed+import torch
+
+from modules import devices, rng_philox, shared
+
+
+def randn(seed, shape, generator=None):
+ """Generate a tensor with random numbers from a normal distribution using seed.
+
+ Uses the seed parameter to set the global torch seed; to generate more with that seed, use randn_like/randn_without_seed."""
+
+ manual_seed(seed)
+
+ if shared.opts.randn_source == "NV":
+ return torch.asarray((generator or nv_rng).randn(shape), device=devices.device)
+
+ if shared.opts.randn_source == "CPU" or devices.device.type == 'mps':
+ return torch.randn(shape, device=devices.cpu, generator=generator).to(devices.device)
+
+ return torch.randn(shape, device=devices.device, generator=generator)
+
+
+def randn_local(seed, shape):
+ """Generate a tensor with random numbers from a normal distribution using seed.
+
+ Does not change the global random number generator. You can only generate the seed's first tensor using this function."""
+
+ if shared.opts.randn_source == "NV":
+ rng = rng_philox.Generator(seed)
+ return torch.asarray(rng.randn(shape), device=devices.device)
+
+ local_device = devices.cpu if shared.opts.randn_source == "CPU" or devices.device.type == 'mps' else devices.device
+ local_generator = torch.Generator(local_device).manual_seed(int(seed))
+ return torch.randn(shape, device=local_device, generator=local_generator).to(devices.device)
+
+
+def randn_like(x):
+ """Generate a tensor with random numbers from a normal distribution using the previously initialized generator.
+
+ Use either randn() or manual_seed() to initialize the generator."""
+
+ if shared.opts.randn_source == "NV":
+ return torch.asarray(nv_rng.randn(x.shape), device=x.device, dtype=x.dtype)
+
+ if shared.opts.randn_source == "CPU" or x.device.type == 'mps':
+ return torch.randn_like(x, device=devices.cpu).to(x.device)
+
+ return torch.randn_like(x)
+
+
+def randn_without_seed(shape, generator=None):
+ """Generate a tensor with random numbers from a normal distribution using the previously initialized generator.
+
+ Use either randn() or manual_seed() to initialize the generator."""
+
+ if shared.opts.randn_source == "NV":
+ return torch.asarray((generator or nv_rng).randn(shape), device=devices.device)
+
+ if shared.opts.randn_source == "CPU" or devices.device.type == 'mps':
+ return torch.randn(shape, device=devices.cpu, generator=generator).to(devices.device)
+
+ return torch.randn(shape, device=devices.device, generator=generator)
+
+
+def manual_seed(seed):
+ """Set up a global random number generator using the specified seed."""
+
+ if shared.opts.randn_source == "NV":
+ global nv_rng
+ nv_rng = rng_philox.Generator(seed)
+ return
+
+ torch.manual_seed(seed)
+
+
+def create_generator(seed):
+ if shared.opts.randn_source == "NV":
+ return rng_philox.Generator(seed)
+
+ device = devices.cpu if shared.opts.randn_source == "CPU" or devices.device.type == 'mps' else devices.device
+ generator = torch.Generator(device).manual_seed(int(seed))
+ return generator
+
+
+# from https://discuss.pytorch.org/t/help-regarding-slerp-function-for-generative-model-sampling/32475/3
+def slerp(val, low, high):
+ low_norm = low/torch.norm(low, dim=1, keepdim=True)
+ high_norm = high/torch.norm(high, dim=1, keepdim=True)
+ dot = (low_norm*high_norm).sum(1)
+
+ if dot.mean() > 0.9995:
+ return low * val + high * (1 - val)
+
+ omega = torch.acos(dot)
+ so = torch.sin(omega)
+ res = (torch.sin((1.0-val)*omega)/so).unsqueeze(1)*low + (torch.sin(val*omega)/so).unsqueeze(1) * high
+ return res
+
+
+class ImageRNG:
+ def __init__(self, shape, seeds, subseeds=None, subseed_strength=0.0, seed_resize_from_h=0, seed_resize_from_w=0):
+ self.shape = tuple(map(int, shape))
+ self.seeds = seeds
+ self.subseeds = subseeds
+ self.subseed_strength = subseed_strength
+ self.seed_resize_from_h = seed_resize_from_h
+ self.seed_resize_from_w = seed_resize_from_w
+
+ self.generators = [create_generator(seed) for seed in seeds]
+
+ self.is_first = True
+
+ def first(self):
+ noise_shape = self.shape if self.seed_resize_from_h <= 0 or self.seed_resize_from_w <= 0 else (self.shape[0], int(self.seed_resize_from_h) // 8, int(self.seed_resize_from_w // 8))
+
+ xs = []
+
+ for i, (seed, generator) in enumerate(zip(self.seeds, self.generators)):
+ subnoise = None
+ if self.subseeds is not None and self.subseed_strength != 0:
+ subseed = 0 if i >= len(self.subseeds) else self.subseeds[i]
+ subnoise = randn(subseed, noise_shape)
+
+ if noise_shape != self.shape:
+ noise = randn(seed, noise_shape)
+ else:
+ noise = randn(seed, self.shape, generator=generator)
+
+ if subnoise is not None:
+ noise = slerp(self.subseed_strength, noise, subnoise)
+
+ if noise_shape != self.shape:
+ x = randn(seed, self.shape, generator=generator)
+ dx = (self.shape[2] - noise_shape[2]) // 2
+ dy = (self.shape[1] - noise_shape[1]) // 2
+ w = noise_shape[2] if dx >= 0 else noise_shape[2] + 2 * dx
+ h = noise_shape[1] if dy >= 0 else noise_shape[1] + 2 * dy
+ tx = 0 if dx < 0 else dx
+ ty = 0 if dy < 0 else dy
+ dx = max(-dx, 0)
+ dy = max(-dy, 0)
+
+ x[:, ty:ty + h, tx:tx + w] = noise[:, dy:dy + h, dx:dx + w]
+ noise = x
+
+ xs.append(noise)
+
+ eta_noise_seed_delta = shared.opts.eta_noise_seed_delta or 0
+ if eta_noise_seed_delta:
+ self.generators = [create_generator(seed + eta_noise_seed_delta) for seed in self.seeds]
+
+ return torch.stack(xs).to(shared.device)
+
+ def next(self):
+ if self.is_first:
+ self.is_first = False
+ return self.first()
+
+ xs = []
+ for generator in self.generators:
+ x = randn_without_seed(self.shape, generator=generator)
+ xs.append(x)
+
+ return torch.stack(xs).to(shared.device)
+
+
+devices.randn = randn
+devices.randn_local = randn_local
+devices.randn_like = randn_like
+devices.randn_without_seed = randn_without_seed
+devices.manual_seed = manual_seed
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/rng.py |
Document my Python code with docstrings | ### This file contains impls for MM-DiT, the core model component of SD3
import math
from typing import Dict, Optional
import numpy as np
import torch
import torch.nn as nn
from einops import rearrange, repeat
from modules.models.sd3.other_impls import attention, Mlp
class PatchEmbed(nn.Module):
def __init__(
self,
img_size: Optional[int] = 224,
patch_size: int = 16,
in_chans: int = 3,
embed_dim: int = 768,
flatten: bool = True,
bias: bool = True,
strict_img_size: bool = True,
dynamic_img_pad: bool = False,
dtype=None,
device=None,
):
super().__init__()
self.patch_size = (patch_size, patch_size)
if img_size is not None:
self.img_size = (img_size, img_size)
self.grid_size = tuple([s // p for s, p in zip(self.img_size, self.patch_size)])
self.num_patches = self.grid_size[0] * self.grid_size[1]
else:
self.img_size = None
self.grid_size = None
self.num_patches = None
# flatten spatial dim and transpose to channels last, kept for bwd compat
self.flatten = flatten
self.strict_img_size = strict_img_size
self.dynamic_img_pad = dynamic_img_pad
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias, dtype=dtype, device=device)
def forward(self, x):
B, C, H, W = x.shape
x = self.proj(x)
if self.flatten:
x = x.flatten(2).transpose(1, 2) # NCHW -> NLC
return x
def modulate(x, shift, scale):
if shift is None:
shift = torch.zeros_like(scale)
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
#################################################################################
# Sine/Cosine Positional Embedding Functions #
#################################################################################
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0, scaling_factor=None, offset=None):
grid_h = np.arange(grid_size, dtype=np.float32)
grid_w = np.arange(grid_size, dtype=np.float32)
grid = np.meshgrid(grid_w, grid_h) # here w goes first
grid = np.stack(grid, axis=0)
if scaling_factor is not None:
grid = grid / scaling_factor
if offset is not None:
grid = grid - offset
grid = grid.reshape([2, 1, grid_size, grid_size])
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
if cls_token and extra_tokens > 0:
pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
return pos_embed
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
assert embed_dim % 2 == 0
# use half of dimensions to encode grid_h
emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
return emb
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
assert embed_dim % 2 == 0
omega = np.arange(embed_dim // 2, dtype=np.float64)
omega /= embed_dim / 2.0
omega = 1.0 / 10000**omega # (D/2,)
pos = pos.reshape(-1) # (M,)
out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
emb_sin = np.sin(out) # (M, D/2)
emb_cos = np.cos(out) # (M, D/2)
return np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
#################################################################################
# Embedding Layers for Timesteps and Class Labels #
#################################################################################
class TimestepEmbedder(nn.Module):
def __init__(self, hidden_size, frequency_embedding_size=256, dtype=None, device=None):
super().__init__()
self.mlp = nn.Sequential(
nn.Linear(frequency_embedding_size, hidden_size, bias=True, dtype=dtype, device=device),
nn.SiLU(),
nn.Linear(hidden_size, hidden_size, bias=True, dtype=dtype, device=device),
)
self.frequency_embedding_size = frequency_embedding_size
@staticmethod
def timestep_embedding(t, dim, max_period=10000):
half = dim // 2
freqs = torch.exp(
-math.log(max_period)
* torch.arange(start=0, end=half, dtype=torch.float32)
/ half
).to(device=t.device)
args = t[:, 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)
if torch.is_floating_point(t):
embedding = embedding.to(dtype=t.dtype)
return embedding
def forward(self, t, dtype, **kwargs):
t_freq = self.timestep_embedding(t, self.frequency_embedding_size).to(dtype)
t_emb = self.mlp(t_freq)
return t_emb
class VectorEmbedder(nn.Module):
def __init__(self, input_dim: int, hidden_size: int, dtype=None, device=None):
super().__init__()
self.mlp = nn.Sequential(
nn.Linear(input_dim, hidden_size, bias=True, dtype=dtype, device=device),
nn.SiLU(),
nn.Linear(hidden_size, hidden_size, bias=True, dtype=dtype, device=device),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.mlp(x)
#################################################################################
# Core DiT Model #
#################################################################################
class QkvLinear(torch.nn.Linear):
pass
def split_qkv(qkv, head_dim):
qkv = qkv.reshape(qkv.shape[0], qkv.shape[1], 3, -1, head_dim).movedim(2, 0)
return qkv[0], qkv[1], qkv[2]
def optimized_attention(qkv, num_heads):
return attention(qkv[0], qkv[1], qkv[2], num_heads)
class SelfAttention(nn.Module):
ATTENTION_MODES = ("xformers", "torch", "torch-hb", "math", "debug")
def __init__(
self,
dim: int,
num_heads: int = 8,
qkv_bias: bool = False,
qk_scale: Optional[float] = None,
attn_mode: str = "xformers",
pre_only: bool = False,
qk_norm: Optional[str] = None,
rmsnorm: bool = False,
dtype=None,
device=None,
):
super().__init__()
self.num_heads = num_heads
self.head_dim = dim // num_heads
self.qkv = QkvLinear(dim, dim * 3, bias=qkv_bias, dtype=dtype, device=device)
if not pre_only:
self.proj = nn.Linear(dim, dim, dtype=dtype, device=device)
assert attn_mode in self.ATTENTION_MODES
self.attn_mode = attn_mode
self.pre_only = pre_only
if qk_norm == "rms":
self.ln_q = RMSNorm(self.head_dim, elementwise_affine=True, eps=1.0e-6, dtype=dtype, device=device)
self.ln_k = RMSNorm(self.head_dim, elementwise_affine=True, eps=1.0e-6, dtype=dtype, device=device)
elif qk_norm == "ln":
self.ln_q = nn.LayerNorm(self.head_dim, elementwise_affine=True, eps=1.0e-6, dtype=dtype, device=device)
self.ln_k = nn.LayerNorm(self.head_dim, elementwise_affine=True, eps=1.0e-6, dtype=dtype, device=device)
elif qk_norm is None:
self.ln_q = nn.Identity()
self.ln_k = nn.Identity()
else:
raise ValueError(qk_norm)
def pre_attention(self, x: torch.Tensor):
B, L, C = x.shape
qkv = self.qkv(x)
q, k, v = split_qkv(qkv, self.head_dim)
q = self.ln_q(q).reshape(q.shape[0], q.shape[1], -1)
k = self.ln_k(k).reshape(q.shape[0], q.shape[1], -1)
return (q, k, v)
def post_attention(self, x: torch.Tensor) -> torch.Tensor:
assert not self.pre_only
x = self.proj(x)
return x
def forward(self, x: torch.Tensor) -> torch.Tensor:
(q, k, v) = self.pre_attention(x)
x = attention(q, k, v, self.num_heads)
x = self.post_attention(x)
return x
class RMSNorm(torch.nn.Module):
def __init__(
self, dim: int, elementwise_affine: bool = False, eps: float = 1e-6, device=None, dtype=None
):
super().__init__()
self.eps = eps
self.learnable_scale = elementwise_affine
if self.learnable_scale:
self.weight = nn.Parameter(torch.empty(dim, device=device, dtype=dtype))
else:
self.register_parameter("weight", None)
def _norm(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
x = self._norm(x)
if self.learnable_scale:
return x * self.weight.to(device=x.device, dtype=x.dtype)
else:
return x
class SwiGLUFeedForward(nn.Module):
def __init__(
self,
dim: int,
hidden_dim: int,
multiple_of: int,
ffn_dim_multiplier: Optional[float] = None,
):
super().__init__()
hidden_dim = int(2 * hidden_dim / 3)
# custom dim factor multiplier
if ffn_dim_multiplier is not None:
hidden_dim = int(ffn_dim_multiplier * hidden_dim)
hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
self.w1 = nn.Linear(dim, hidden_dim, bias=False)
self.w2 = nn.Linear(hidden_dim, dim, bias=False)
self.w3 = nn.Linear(dim, hidden_dim, bias=False)
def forward(self, x):
return self.w2(nn.functional.silu(self.w1(x)) * self.w3(x))
class DismantledBlock(nn.Module):
ATTENTION_MODES = ("xformers", "torch", "torch-hb", "math", "debug")
def __init__(
self,
hidden_size: int,
num_heads: int,
mlp_ratio: float = 4.0,
attn_mode: str = "xformers",
qkv_bias: bool = False,
pre_only: bool = False,
rmsnorm: bool = False,
scale_mod_only: bool = False,
swiglu: bool = False,
qk_norm: Optional[str] = None,
dtype=None,
device=None,
**block_kwargs,
):
super().__init__()
assert attn_mode in self.ATTENTION_MODES
if not rmsnorm:
self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
else:
self.norm1 = RMSNorm(hidden_size, elementwise_affine=False, eps=1e-6)
self.attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias, attn_mode=attn_mode, pre_only=pre_only, qk_norm=qk_norm, rmsnorm=rmsnorm, dtype=dtype, device=device)
if not pre_only:
if not rmsnorm:
self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
else:
self.norm2 = RMSNorm(hidden_size, elementwise_affine=False, eps=1e-6)
mlp_hidden_dim = int(hidden_size * mlp_ratio)
if not pre_only:
if not swiglu:
self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=nn.GELU(approximate="tanh"), dtype=dtype, device=device)
else:
self.mlp = SwiGLUFeedForward(dim=hidden_size, hidden_dim=mlp_hidden_dim, multiple_of=256)
self.scale_mod_only = scale_mod_only
if not scale_mod_only:
n_mods = 6 if not pre_only else 2
else:
n_mods = 4 if not pre_only else 1
self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, n_mods * hidden_size, bias=True, dtype=dtype, device=device))
self.pre_only = pre_only
def pre_attention(self, x: torch.Tensor, c: torch.Tensor):
assert x is not None, "pre_attention called with None input"
if not self.pre_only:
if not self.scale_mod_only:
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1)
else:
shift_msa = None
shift_mlp = None
scale_msa, gate_msa, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(4, dim=1)
qkv = self.attn.pre_attention(modulate(self.norm1(x), shift_msa, scale_msa))
return qkv, (x, gate_msa, shift_mlp, scale_mlp, gate_mlp)
else:
if not self.scale_mod_only:
shift_msa, scale_msa = self.adaLN_modulation(c).chunk(2, dim=1)
else:
shift_msa = None
scale_msa = self.adaLN_modulation(c)
qkv = self.attn.pre_attention(modulate(self.norm1(x), shift_msa, scale_msa))
return qkv, None
def post_attention(self, attn, x, gate_msa, shift_mlp, scale_mlp, gate_mlp):
assert not self.pre_only
x = x + gate_msa.unsqueeze(1) * self.attn.post_attention(attn)
x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
return x
def forward(self, x: torch.Tensor, c: torch.Tensor) -> torch.Tensor:
assert not self.pre_only
(q, k, v), intermediates = self.pre_attention(x, c)
attn = attention(q, k, v, self.attn.num_heads)
return self.post_attention(attn, *intermediates)
def block_mixing(context, x, context_block, x_block, c):
assert context is not None, "block_mixing called with None context"
context_qkv, context_intermediates = context_block.pre_attention(context, c)
x_qkv, x_intermediates = x_block.pre_attention(x, c)
o = []
for t in range(3):
o.append(torch.cat((context_qkv[t], x_qkv[t]), dim=1))
q, k, v = tuple(o)
attn = attention(q, k, v, x_block.attn.num_heads)
context_attn, x_attn = (attn[:, : context_qkv[0].shape[1]], attn[:, context_qkv[0].shape[1] :])
if not context_block.pre_only:
context = context_block.post_attention(context_attn, *context_intermediates)
else:
context = None
x = x_block.post_attention(x_attn, *x_intermediates)
return context, x
class JointBlock(nn.Module):
def __init__(self, *args, **kwargs):
super().__init__()
pre_only = kwargs.pop("pre_only")
qk_norm = kwargs.pop("qk_norm", None)
self.context_block = DismantledBlock(*args, pre_only=pre_only, qk_norm=qk_norm, **kwargs)
self.x_block = DismantledBlock(*args, pre_only=False, qk_norm=qk_norm, **kwargs)
def forward(self, *args, **kwargs):
return block_mixing(*args, context_block=self.context_block, x_block=self.x_block, **kwargs)
class FinalLayer(nn.Module):
def __init__(self, hidden_size: int, patch_size: int, out_channels: int, total_out_channels: Optional[int] = None, dtype=None, device=None):
super().__init__()
self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, dtype=dtype, device=device)
self.linear = (
nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True, dtype=dtype, device=device)
if (total_out_channels is None)
else nn.Linear(hidden_size, total_out_channels, bias=True, dtype=dtype, device=device)
)
self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True, dtype=dtype, device=device))
def forward(self, x: torch.Tensor, c: torch.Tensor) -> torch.Tensor:
shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
x = modulate(self.norm_final(x), shift, scale)
x = self.linear(x)
return x
class MMDiT(nn.Module):
def __init__(
self,
input_size: int = 32,
patch_size: int = 2,
in_channels: int = 4,
depth: int = 28,
mlp_ratio: float = 4.0,
learn_sigma: bool = False,
adm_in_channels: Optional[int] = None,
context_embedder_config: Optional[Dict] = None,
register_length: int = 0,
attn_mode: str = "torch",
rmsnorm: bool = False,
scale_mod_only: bool = False,
swiglu: bool = False,
out_channels: Optional[int] = None,
pos_embed_scaling_factor: Optional[float] = None,
pos_embed_offset: Optional[float] = None,
pos_embed_max_size: Optional[int] = None,
num_patches = None,
qk_norm: Optional[str] = None,
qkv_bias: bool = True,
dtype = None,
device = None,
):
super().__init__()
self.dtype = dtype
self.learn_sigma = learn_sigma
self.in_channels = in_channels
default_out_channels = in_channels * 2 if learn_sigma else in_channels
self.out_channels = out_channels if out_channels is not None else default_out_channels
self.patch_size = patch_size
self.pos_embed_scaling_factor = pos_embed_scaling_factor
self.pos_embed_offset = pos_embed_offset
self.pos_embed_max_size = pos_embed_max_size
# apply magic --> this defines a head_size of 64
hidden_size = 64 * depth
num_heads = depth
self.num_heads = num_heads
self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True, strict_img_size=self.pos_embed_max_size is None, dtype=dtype, device=device)
self.t_embedder = TimestepEmbedder(hidden_size, dtype=dtype, device=device)
if adm_in_channels is not None:
assert isinstance(adm_in_channels, int)
self.y_embedder = VectorEmbedder(adm_in_channels, hidden_size, dtype=dtype, device=device)
self.context_embedder = nn.Identity()
if context_embedder_config is not None:
if context_embedder_config["target"] == "torch.nn.Linear":
self.context_embedder = nn.Linear(**context_embedder_config["params"], dtype=dtype, device=device)
self.register_length = register_length
if self.register_length > 0:
self.register = nn.Parameter(torch.randn(1, register_length, hidden_size, dtype=dtype, device=device))
# num_patches = self.x_embedder.num_patches
# Will use fixed sin-cos embedding:
# just use a buffer already
if num_patches is not None:
self.register_buffer(
"pos_embed",
torch.zeros(1, num_patches, hidden_size, dtype=dtype, device=device),
)
else:
self.pos_embed = None
self.joint_blocks = nn.ModuleList(
[
JointBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, attn_mode=attn_mode, pre_only=i == depth - 1, rmsnorm=rmsnorm, scale_mod_only=scale_mod_only, swiglu=swiglu, qk_norm=qk_norm, dtype=dtype, device=device)
for i in range(depth)
]
)
self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels, dtype=dtype, device=device)
def cropped_pos_embed(self, hw):
assert self.pos_embed_max_size is not None
p = self.x_embedder.patch_size[0]
h, w = hw
# patched size
h = h // p
w = w // p
assert h <= self.pos_embed_max_size, (h, self.pos_embed_max_size)
assert w <= self.pos_embed_max_size, (w, self.pos_embed_max_size)
top = (self.pos_embed_max_size - h) // 2
left = (self.pos_embed_max_size - w) // 2
spatial_pos_embed = rearrange(
self.pos_embed,
"1 (h w) c -> 1 h w c",
h=self.pos_embed_max_size,
w=self.pos_embed_max_size,
)
spatial_pos_embed = spatial_pos_embed[:, top : top + h, left : left + w, :]
spatial_pos_embed = rearrange(spatial_pos_embed, "1 h w c -> 1 (h w) c")
return spatial_pos_embed
def unpatchify(self, x, hw=None):
c = self.out_channels
p = self.x_embedder.patch_size[0]
if hw is None:
h = w = int(x.shape[1] ** 0.5)
else:
h, w = hw
h = h // p
w = w // p
assert h * w == x.shape[1]
x = x.reshape(shape=(x.shape[0], h, w, p, p, c))
x = torch.einsum("nhwpqc->nchpwq", x)
imgs = x.reshape(shape=(x.shape[0], c, h * p, w * p))
return imgs
def forward_core_with_concat(self, x: torch.Tensor, c_mod: torch.Tensor, context: Optional[torch.Tensor] = None) -> torch.Tensor:
if self.register_length > 0:
context = torch.cat((repeat(self.register, "1 ... -> b ...", b=x.shape[0]), context if context is not None else torch.Tensor([]).type_as(x)), 1)
# context is B, L', D
# x is B, L, D
for block in self.joint_blocks:
context, x = block(context, x, c=c_mod)
x = self.final_layer(x, c_mod) # (N, T, patch_size ** 2 * out_channels)
return x
def forward(self, x: torch.Tensor, t: torch.Tensor, y: Optional[torch.Tensor] = None, context: Optional[torch.Tensor] = None) -> torch.Tensor:
hw = x.shape[-2:]
x = self.x_embedder(x) + self.cropped_pos_embed(hw)
c = self.t_embedder(t, dtype=x.dtype) # (N, D)
if y is not None:
y = self.y_embedder(y) # (N, D)
c = c + y # (N, D)
context = self.context_embedder(context)
x = self.forward_core_with_concat(x, c, context)
x = self.unpatchify(x, hw=hw) # (N, out_channels, H, W)
return x | --- +++ @@ -10,6 +10,7 @@
class PatchEmbed(nn.Module):
+ """ 2D Image to Patch Embedding"""
def __init__(
self,
img_size: Optional[int] = 224,
@@ -61,6 +62,11 @@
def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0, scaling_factor=None, offset=None):
+ """
+ grid_size: int of the grid height and width
+ return:
+ pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
+ """
grid_h = np.arange(grid_size, dtype=np.float32)
grid_w = np.arange(grid_size, dtype=np.float32)
grid = np.meshgrid(grid_w, grid_h) # here w goes first
@@ -86,6 +92,11 @@
def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
+ """
+ embed_dim: output dimension for each position
+ pos: a list of positions to be encoded: size (M,)
+ out: (M, D)
+ """
assert embed_dim % 2 == 0
omega = np.arange(embed_dim // 2, dtype=np.float64)
omega /= embed_dim / 2.0
@@ -103,6 +114,7 @@
class TimestepEmbedder(nn.Module):
+ """Embeds scalar timesteps into vector representations."""
def __init__(self, hidden_size, frequency_embedding_size=256, dtype=None, device=None):
super().__init__()
@@ -115,6 +127,14 @@
@staticmethod
def timestep_embedding(t, dim, max_period=10000):
+ """
+ Create sinusoidal timestep embeddings.
+ :param t: 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, D) Tensor of positional embeddings.
+ """
half = dim // 2
freqs = torch.exp(
-math.log(max_period)
@@ -136,6 +156,7 @@
class VectorEmbedder(nn.Module):
+ """Embeds a flat vector of dimension input_dim"""
def __init__(self, input_dim: int, hidden_size: int, dtype=None, device=None):
super().__init__()
@@ -227,6 +248,15 @@ def __init__(
self, dim: int, elementwise_affine: bool = False, eps: float = 1e-6, device=None, dtype=None
):
+ """
+ Initialize the RMSNorm normalization layer.
+ Args:
+ dim (int): The dimension of the input tensor.
+ eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6.
+ Attributes:
+ eps (float): A small value added to the denominator for numerical stability.
+ weight (nn.Parameter): Learnable scaling parameter.
+ """
super().__init__()
self.eps = eps
self.learnable_scale = elementwise_affine
@@ -236,9 +266,23 @@ self.register_parameter("weight", None)
def _norm(self, x):
+ """
+ Apply the RMSNorm normalization to the input tensor.
+ Args:
+ x (torch.Tensor): The input tensor.
+ Returns:
+ torch.Tensor: The normalized tensor.
+ """
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
def forward(self, x):
+ """
+ Forward pass through the RMSNorm layer.
+ Args:
+ x (torch.Tensor): The input tensor.
+ Returns:
+ torch.Tensor: The output tensor after applying RMSNorm.
+ """
x = self._norm(x)
if self.learnable_scale:
return x * self.weight.to(device=x.device, dtype=x.dtype)
@@ -254,6 +298,21 @@ multiple_of: int,
ffn_dim_multiplier: Optional[float] = None,
):
+ """
+ Initialize the FeedForward module.
+
+ Args:
+ dim (int): Input dimension.
+ hidden_dim (int): Hidden dimension of the feedforward layer.
+ multiple_of (int): Value to ensure hidden dimension is a multiple of this value.
+ ffn_dim_multiplier (float, optional): Custom multiplier for hidden dimension. Defaults to None.
+
+ Attributes:
+ w1 (ColumnParallelLinear): Linear transformation for the first layer.
+ w2 (RowParallelLinear): Linear transformation for the second layer.
+ w3 (ColumnParallelLinear): Linear transformation for the third layer.
+
+ """
super().__init__()
hidden_dim = int(2 * hidden_dim / 3)
# custom dim factor multiplier
@@ -270,6 +329,7 @@
class DismantledBlock(nn.Module):
+ """A DiT block with gated adaptive layer norm (adaLN) conditioning."""
ATTENTION_MODES = ("xformers", "torch", "torch-hb", "math", "debug")
@@ -371,6 +431,7 @@
class JointBlock(nn.Module):
+ """just a small wrapper to serve as a fsdp unit"""
def __init__(self, *args, **kwargs):
super().__init__()
@@ -384,6 +445,9 @@
class FinalLayer(nn.Module):
+ """
+ The final layer of DiT.
+ """
def __init__(self, hidden_size: int, patch_size: int, out_channels: int, total_out_channels: Optional[int] = None, dtype=None, device=None):
super().__init__()
@@ -403,6 +467,7 @@
class MMDiT(nn.Module):
+ """Diffusion model with a Transformer backbone."""
def __init__(
self,
@@ -504,6 +569,10 @@ return spatial_pos_embed
def unpatchify(self, x, hw=None):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
c = self.out_channels
p = self.x_embedder.patch_size[0]
if hw is None:
@@ -532,6 +601,12 @@ return x
def forward(self, x: torch.Tensor, t: torch.Tensor, y: Optional[torch.Tensor] = None, context: Optional[torch.Tensor] = None) -> torch.Tensor:
+ """
+ Forward pass of DiT.
+ x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)
+ t: (N,) tensor of diffusion timesteps
+ y: (N,) tensor of class labels
+ """
hw = x.shape[-2:]
x = self.x_embedder(x) + self.cropped_pos_embed(hw)
c = self.t_embedder(t, dtype=x.dtype) # (N, D)
@@ -544,4 +619,4 @@ x = self.forward_core_with_concat(x, c, context)
x = self.unpatchify(x, hw=hw) # (N, out_channels, H, W)
- return x+ return x
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/models/sd3/mmdit.py |
Write Python docstrings for this snippet |
# File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
# See more details in LICENSE.
import torch
import torch.nn as nn
import numpy as np
import pytorch_lightning as pl
from torch.optim.lr_scheduler import LambdaLR
from einops import rearrange, repeat
from contextlib import contextmanager
from functools import partial
from tqdm import tqdm
from torchvision.utils import make_grid
from pytorch_lightning.utilities.distributed import rank_zero_only
from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config
from ldm.modules.ema import LitEma
from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution
from ldm.models.autoencoder import IdentityFirstStage, AutoencoderKL
from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like
from ldm.models.diffusion.ddim import DDIMSampler
try:
from ldm.models.autoencoder import VQModelInterface
except Exception:
class VQModelInterface:
pass
__conditioning_keys__ = {'concat': 'c_concat',
'crossattn': 'c_crossattn',
'adm': 'y'}
def disabled_train(self, mode=True):
return self
def uniform_on_device(r1, r2, shape, device):
return (r1 - r2) * torch.rand(*shape, device=device) + r2
class DDPM(pl.LightningModule):
# classic DDPM with Gaussian diffusion, in image space
def __init__(self,
unet_config,
timesteps=1000,
beta_schedule="linear",
loss_type="l2",
ckpt_path=None,
ignore_keys=None,
load_only_unet=False,
monitor="val/loss",
use_ema=True,
first_stage_key="image",
image_size=256,
channels=3,
log_every_t=100,
clip_denoised=True,
linear_start=1e-4,
linear_end=2e-2,
cosine_s=8e-3,
given_betas=None,
original_elbo_weight=0.,
v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
l_simple_weight=1.,
conditioning_key=None,
parameterization="eps", # all assuming fixed variance schedules
scheduler_config=None,
use_positional_encodings=False,
learn_logvar=False,
logvar_init=0.,
load_ema=True,
):
super().__init__()
assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"'
self.parameterization = parameterization
print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
self.cond_stage_model = None
self.clip_denoised = clip_denoised
self.log_every_t = log_every_t
self.first_stage_key = first_stage_key
self.image_size = image_size # try conv?
self.channels = channels
self.use_positional_encodings = use_positional_encodings
self.model = DiffusionWrapper(unet_config, conditioning_key)
count_params(self.model, verbose=True)
self.use_ema = use_ema
self.use_scheduler = scheduler_config is not None
if self.use_scheduler:
self.scheduler_config = scheduler_config
self.v_posterior = v_posterior
self.original_elbo_weight = original_elbo_weight
self.l_simple_weight = l_simple_weight
if monitor is not None:
self.monitor = monitor
if self.use_ema and load_ema:
self.model_ema = LitEma(self.model)
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
if ckpt_path is not None:
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys or [], only_model=load_only_unet)
# If initialing from EMA-only checkpoint, create EMA model after loading.
if self.use_ema and not load_ema:
self.model_ema = LitEma(self.model)
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
self.loss_type = loss_type
self.learn_logvar = learn_logvar
self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
if self.learn_logvar:
self.logvar = nn.Parameter(self.logvar, requires_grad=True)
def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
if exists(given_betas):
betas = given_betas
else:
betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
cosine_s=cosine_s)
alphas = 1. - betas
alphas_cumprod = np.cumprod(alphas, axis=0)
alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
timesteps, = betas.shape
self.num_timesteps = int(timesteps)
self.linear_start = linear_start
self.linear_end = linear_end
assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
to_torch = partial(torch.tensor, dtype=torch.float32)
self.register_buffer('betas', to_torch(betas))
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
# calculations for diffusion q(x_t | x_{t-1}) and others
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
# calculations for posterior q(x_{t-1} | x_t, x_0)
posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
1. - alphas_cumprod) + self.v_posterior * betas
# above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
self.register_buffer('posterior_variance', to_torch(posterior_variance))
# below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
self.register_buffer('posterior_mean_coef1', to_torch(
betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
self.register_buffer('posterior_mean_coef2', to_torch(
(1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
if self.parameterization == "eps":
lvlb_weights = self.betas ** 2 / (
2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
elif self.parameterization == "x0":
lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
else:
raise NotImplementedError("mu not supported")
# TODO how to choose this term
lvlb_weights[0] = lvlb_weights[1]
self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
assert not torch.isnan(self.lvlb_weights).all()
@contextmanager
def ema_scope(self, context=None):
if self.use_ema:
self.model_ema.store(self.model.parameters())
self.model_ema.copy_to(self.model)
if context is not None:
print(f"{context}: Switched to EMA weights")
try:
yield None
finally:
if self.use_ema:
self.model_ema.restore(self.model.parameters())
if context is not None:
print(f"{context}: Restored training weights")
def init_from_ckpt(self, path, ignore_keys=None, only_model=False):
ignore_keys = ignore_keys or []
sd = torch.load(path, map_location="cpu")
if "state_dict" in list(sd.keys()):
sd = sd["state_dict"]
keys = list(sd.keys())
# Our model adds additional channels to the first layer to condition on an input image.
# For the first layer, copy existing channel weights and initialize new channel weights to zero.
input_keys = [
"model.diffusion_model.input_blocks.0.0.weight",
"model_ema.diffusion_modelinput_blocks00weight",
]
self_sd = self.state_dict()
for input_key in input_keys:
if input_key not in sd or input_key not in self_sd:
continue
input_weight = self_sd[input_key]
if input_weight.size() != sd[input_key].size():
print(f"Manual init: {input_key}")
input_weight.zero_()
input_weight[:, :4, :, :].copy_(sd[input_key])
ignore_keys.append(input_key)
for k in keys:
for ik in ignore_keys:
if k.startswith(ik):
print(f"Deleting key {k} from state_dict.")
del sd[k]
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
sd, strict=False)
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
if missing:
print(f"Missing Keys: {missing}")
if unexpected:
print(f"Unexpected Keys: {unexpected}")
def q_mean_variance(self, x_start, t):
mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
return mean, variance, log_variance
def predict_start_from_noise(self, x_t, t, noise):
return (
extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
)
def q_posterior(self, x_start, x_t, t):
posterior_mean = (
extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
)
posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
return posterior_mean, posterior_variance, posterior_log_variance_clipped
def p_mean_variance(self, x, t, clip_denoised: bool):
model_out = self.model(x, t)
if self.parameterization == "eps":
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
elif self.parameterization == "x0":
x_recon = model_out
if clip_denoised:
x_recon.clamp_(-1., 1.)
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
return model_mean, posterior_variance, posterior_log_variance
@torch.no_grad()
def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
b, *_, device = *x.shape, x.device
model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
noise = noise_like(x.shape, device, repeat_noise)
# no noise when t == 0
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
@torch.no_grad()
def p_sample_loop(self, shape, return_intermediates=False):
device = self.betas.device
b = shape[0]
img = torch.randn(shape, device=device)
intermediates = [img]
for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
clip_denoised=self.clip_denoised)
if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
intermediates.append(img)
if return_intermediates:
return img, intermediates
return img
@torch.no_grad()
def sample(self, batch_size=16, return_intermediates=False):
image_size = self.image_size
channels = self.channels
return self.p_sample_loop((batch_size, channels, image_size, image_size),
return_intermediates=return_intermediates)
def q_sample(self, x_start, t, noise=None):
noise = default(noise, lambda: torch.randn_like(x_start))
return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
def get_loss(self, pred, target, mean=True):
if self.loss_type == 'l1':
loss = (target - pred).abs()
if mean:
loss = loss.mean()
elif self.loss_type == 'l2':
if mean:
loss = torch.nn.functional.mse_loss(target, pred)
else:
loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
else:
raise NotImplementedError("unknown loss type '{loss_type}'")
return loss
def p_losses(self, x_start, t, noise=None):
noise = default(noise, lambda: torch.randn_like(x_start))
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
model_out = self.model(x_noisy, t)
loss_dict = {}
if self.parameterization == "eps":
target = noise
elif self.parameterization == "x0":
target = x_start
else:
raise NotImplementedError(f"Parameterization {self.parameterization} not yet supported")
loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
log_prefix = 'train' if self.training else 'val'
loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
loss_simple = loss.mean() * self.l_simple_weight
loss_vlb = (self.lvlb_weights[t] * loss).mean()
loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
loss = loss_simple + self.original_elbo_weight * loss_vlb
loss_dict.update({f'{log_prefix}/loss': loss})
return loss, loss_dict
def forward(self, x, *args, **kwargs):
# b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
# assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
return self.p_losses(x, t, *args, **kwargs)
def get_input(self, batch, k):
return batch[k]
def shared_step(self, batch):
x = self.get_input(batch, self.first_stage_key)
loss, loss_dict = self(x)
return loss, loss_dict
def training_step(self, batch, batch_idx):
loss, loss_dict = self.shared_step(batch)
self.log_dict(loss_dict, prog_bar=True,
logger=True, on_step=True, on_epoch=True)
self.log("global_step", self.global_step,
prog_bar=True, logger=True, on_step=True, on_epoch=False)
if self.use_scheduler:
lr = self.optimizers().param_groups[0]['lr']
self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
return loss
@torch.no_grad()
def validation_step(self, batch, batch_idx):
_, loss_dict_no_ema = self.shared_step(batch)
with self.ema_scope():
_, loss_dict_ema = self.shared_step(batch)
loss_dict_ema = {f"{key}_ema": loss_dict_ema[key] for key in loss_dict_ema}
self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
def on_train_batch_end(self, *args, **kwargs):
if self.use_ema:
self.model_ema(self.model)
def _get_rows_from_list(self, samples):
n_imgs_per_row = len(samples)
denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
return denoise_grid
@torch.no_grad()
def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
log = {}
x = self.get_input(batch, self.first_stage_key)
N = min(x.shape[0], N)
n_row = min(x.shape[0], n_row)
x = x.to(self.device)[:N]
log["inputs"] = x
# get diffusion row
diffusion_row = []
x_start = x[:n_row]
for t in range(self.num_timesteps):
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
t = t.to(self.device).long()
noise = torch.randn_like(x_start)
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
diffusion_row.append(x_noisy)
log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
if sample:
# get denoise row
with self.ema_scope("Plotting"):
samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
log["samples"] = samples
log["denoise_row"] = self._get_rows_from_list(denoise_row)
if return_keys:
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
return log
else:
return {key: log[key] for key in return_keys}
return log
def configure_optimizers(self):
lr = self.learning_rate
params = list(self.model.parameters())
if self.learn_logvar:
params = params + [self.logvar]
opt = torch.optim.AdamW(params, lr=lr)
return opt
class LatentDiffusion(DDPM):
def __init__(self,
first_stage_config,
cond_stage_config,
num_timesteps_cond=None,
cond_stage_key="image",
cond_stage_trainable=False,
concat_mode=True,
cond_stage_forward=None,
conditioning_key=None,
scale_factor=1.0,
scale_by_std=False,
load_ema=True,
*args, **kwargs):
self.num_timesteps_cond = default(num_timesteps_cond, 1)
self.scale_by_std = scale_by_std
assert self.num_timesteps_cond <= kwargs['timesteps']
# for backwards compatibility after implementation of DiffusionWrapper
if conditioning_key is None:
conditioning_key = 'concat' if concat_mode else 'crossattn'
if cond_stage_config == '__is_unconditional__':
conditioning_key = None
ckpt_path = kwargs.pop("ckpt_path", None)
ignore_keys = kwargs.pop("ignore_keys", [])
super().__init__(*args, conditioning_key=conditioning_key, load_ema=load_ema, **kwargs)
self.concat_mode = concat_mode
self.cond_stage_trainable = cond_stage_trainable
self.cond_stage_key = cond_stage_key
try:
self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
except Exception:
self.num_downs = 0
if not scale_by_std:
self.scale_factor = scale_factor
else:
self.register_buffer('scale_factor', torch.tensor(scale_factor))
self.instantiate_first_stage(first_stage_config)
self.instantiate_cond_stage(cond_stage_config)
self.cond_stage_forward = cond_stage_forward
self.clip_denoised = False
self.bbox_tokenizer = None
self.restarted_from_ckpt = False
if ckpt_path is not None:
self.init_from_ckpt(ckpt_path, ignore_keys)
self.restarted_from_ckpt = True
if self.use_ema and not load_ema:
self.model_ema = LitEma(self.model)
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
def make_cond_schedule(self, ):
self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
self.cond_ids[:self.num_timesteps_cond] = ids
@rank_zero_only
@torch.no_grad()
def on_train_batch_start(self, batch, batch_idx, dataloader_idx):
# only for very first batch
if self.scale_by_std and self.current_epoch == 0 and self.global_step == 0 and batch_idx == 0 and not self.restarted_from_ckpt:
assert self.scale_factor == 1., 'rather not use custom rescaling and std-rescaling simultaneously'
# set rescale weight to 1./std of encodings
print("### USING STD-RESCALING ###")
x = super().get_input(batch, self.first_stage_key)
x = x.to(self.device)
encoder_posterior = self.encode_first_stage(x)
z = self.get_first_stage_encoding(encoder_posterior).detach()
del self.scale_factor
self.register_buffer('scale_factor', 1. / z.flatten().std())
print(f"setting self.scale_factor to {self.scale_factor}")
print("### USING STD-RESCALING ###")
def register_schedule(self,
given_betas=None, beta_schedule="linear", timesteps=1000,
linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
self.shorten_cond_schedule = self.num_timesteps_cond > 1
if self.shorten_cond_schedule:
self.make_cond_schedule()
def instantiate_first_stage(self, config):
model = instantiate_from_config(config)
self.first_stage_model = model.eval()
self.first_stage_model.train = disabled_train
for param in self.first_stage_model.parameters():
param.requires_grad = False
def instantiate_cond_stage(self, config):
if not self.cond_stage_trainable:
if config == "__is_first_stage__":
print("Using first stage also as cond stage.")
self.cond_stage_model = self.first_stage_model
elif config == "__is_unconditional__":
print(f"Training {self.__class__.__name__} as an unconditional model.")
self.cond_stage_model = None
# self.be_unconditional = True
else:
model = instantiate_from_config(config)
self.cond_stage_model = model.eval()
self.cond_stage_model.train = disabled_train
for param in self.cond_stage_model.parameters():
param.requires_grad = False
else:
assert config != '__is_first_stage__'
assert config != '__is_unconditional__'
model = instantiate_from_config(config)
self.cond_stage_model = model
def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):
denoise_row = []
for zd in tqdm(samples, desc=desc):
denoise_row.append(self.decode_first_stage(zd.to(self.device),
force_not_quantize=force_no_decoder_quantization))
n_imgs_per_row = len(denoise_row)
denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W
denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
return denoise_grid
def get_first_stage_encoding(self, encoder_posterior):
if isinstance(encoder_posterior, DiagonalGaussianDistribution):
z = encoder_posterior.sample()
elif isinstance(encoder_posterior, torch.Tensor):
z = encoder_posterior
else:
raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
return self.scale_factor * z
def get_learned_conditioning(self, c):
if self.cond_stage_forward is None:
if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
c = self.cond_stage_model.encode(c)
if isinstance(c, DiagonalGaussianDistribution):
c = c.mode()
else:
c = self.cond_stage_model(c)
else:
assert hasattr(self.cond_stage_model, self.cond_stage_forward)
c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
return c
def meshgrid(self, h, w):
y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
arr = torch.cat([y, x], dim=-1)
return arr
def delta_border(self, h, w):
lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
arr = self.meshgrid(h, w) / lower_right_corner
dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
return edge_dist
def get_weighting(self, h, w, Ly, Lx, device):
weighting = self.delta_border(h, w)
weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"],
self.split_input_params["clip_max_weight"], )
weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
if self.split_input_params["tie_braker"]:
L_weighting = self.delta_border(Ly, Lx)
L_weighting = torch.clip(L_weighting,
self.split_input_params["clip_min_tie_weight"],
self.split_input_params["clip_max_tie_weight"])
L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
weighting = weighting * L_weighting
return weighting
def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
bs, nc, h, w = x.shape
# number of crops in image
Ly = (h - kernel_size[0]) // stride[0] + 1
Lx = (w - kernel_size[1]) // stride[1] + 1
if uf == 1 and df == 1:
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
unfold = torch.nn.Unfold(**fold_params)
fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)
normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
elif uf > 1 and df == 1:
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
unfold = torch.nn.Unfold(**fold_params)
fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
dilation=1, padding=0,
stride=(stride[0] * uf, stride[1] * uf))
fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)
normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
elif df > 1 and uf == 1:
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
unfold = torch.nn.Unfold(**fold_params)
fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
dilation=1, padding=0,
stride=(stride[0] // df, stride[1] // df))
fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)
normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
else:
raise NotImplementedError
return fold, unfold, normalization, weighting
@torch.no_grad()
def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
cond_key=None, return_original_cond=False, bs=None, uncond=0.05):
x = super().get_input(batch, k)
if bs is not None:
x = x[:bs]
x = x.to(self.device)
encoder_posterior = self.encode_first_stage(x)
z = self.get_first_stage_encoding(encoder_posterior).detach()
cond_key = cond_key or self.cond_stage_key
xc = super().get_input(batch, cond_key)
if bs is not None:
xc["c_crossattn"] = xc["c_crossattn"][:bs]
xc["c_concat"] = xc["c_concat"][:bs]
cond = {}
# To support classifier-free guidance, randomly drop out only text conditioning 5%, only image conditioning 5%, and both 5%.
random = torch.rand(x.size(0), device=x.device)
prompt_mask = rearrange(random < 2 * uncond, "n -> n 1 1")
input_mask = 1 - rearrange((random >= uncond).float() * (random < 3 * uncond).float(), "n -> n 1 1 1")
null_prompt = self.get_learned_conditioning([""])
cond["c_crossattn"] = [torch.where(prompt_mask, null_prompt, self.get_learned_conditioning(xc["c_crossattn"]).detach())]
cond["c_concat"] = [input_mask * self.encode_first_stage((xc["c_concat"].to(self.device))).mode().detach()]
out = [z, cond]
if return_first_stage_outputs:
xrec = self.decode_first_stage(z)
out.extend([x, xrec])
if return_original_cond:
out.append(xc)
return out
@torch.no_grad()
def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
if predict_cids:
if z.dim() == 4:
z = torch.argmax(z.exp(), dim=1).long()
z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
z = rearrange(z, 'b h w c -> b c h w').contiguous()
z = 1. / self.scale_factor * z
if hasattr(self, "split_input_params"):
if self.split_input_params["patch_distributed_vq"]:
ks = self.split_input_params["ks"] # eg. (128, 128)
stride = self.split_input_params["stride"] # eg. (64, 64)
uf = self.split_input_params["vqf"]
bs, nc, h, w = z.shape
if ks[0] > h or ks[1] > w:
ks = (min(ks[0], h), min(ks[1], w))
print("reducing Kernel")
if stride[0] > h or stride[1] > w:
stride = (min(stride[0], h), min(stride[1], w))
print("reducing stride")
fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
z = unfold(z) # (bn, nc * prod(**ks), L)
# 1. Reshape to img shape
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
# 2. apply model loop over last dim
if isinstance(self.first_stage_model, VQModelInterface):
output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
force_not_quantize=predict_cids or force_not_quantize)
for i in range(z.shape[-1])]
else:
output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
for i in range(z.shape[-1])]
o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
o = o * weighting
# Reverse 1. reshape to img shape
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
# stitch crops together
decoded = fold(o)
decoded = decoded / normalization # norm is shape (1, 1, h, w)
return decoded
else:
if isinstance(self.first_stage_model, VQModelInterface):
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
else:
return self.first_stage_model.decode(z)
else:
if isinstance(self.first_stage_model, VQModelInterface):
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
else:
return self.first_stage_model.decode(z)
# same as above but without decorator
def differentiable_decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
if predict_cids:
if z.dim() == 4:
z = torch.argmax(z.exp(), dim=1).long()
z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
z = rearrange(z, 'b h w c -> b c h w').contiguous()
z = 1. / self.scale_factor * z
if hasattr(self, "split_input_params"):
if self.split_input_params["patch_distributed_vq"]:
ks = self.split_input_params["ks"] # eg. (128, 128)
stride = self.split_input_params["stride"] # eg. (64, 64)
uf = self.split_input_params["vqf"]
bs, nc, h, w = z.shape
if ks[0] > h or ks[1] > w:
ks = (min(ks[0], h), min(ks[1], w))
print("reducing Kernel")
if stride[0] > h or stride[1] > w:
stride = (min(stride[0], h), min(stride[1], w))
print("reducing stride")
fold, unfold, normalization, weighting = self.get_fold_unfold(z, ks, stride, uf=uf)
z = unfold(z) # (bn, nc * prod(**ks), L)
# 1. Reshape to img shape
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
# 2. apply model loop over last dim
if isinstance(self.first_stage_model, VQModelInterface):
output_list = [self.first_stage_model.decode(z[:, :, :, :, i],
force_not_quantize=predict_cids or force_not_quantize)
for i in range(z.shape[-1])]
else:
output_list = [self.first_stage_model.decode(z[:, :, :, :, i])
for i in range(z.shape[-1])]
o = torch.stack(output_list, axis=-1) # # (bn, nc, ks[0], ks[1], L)
o = o * weighting
# Reverse 1. reshape to img shape
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
# stitch crops together
decoded = fold(o)
decoded = decoded / normalization # norm is shape (1, 1, h, w)
return decoded
else:
if isinstance(self.first_stage_model, VQModelInterface):
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
else:
return self.first_stage_model.decode(z)
else:
if isinstance(self.first_stage_model, VQModelInterface):
return self.first_stage_model.decode(z, force_not_quantize=predict_cids or force_not_quantize)
else:
return self.first_stage_model.decode(z)
@torch.no_grad()
def encode_first_stage(self, x):
if hasattr(self, "split_input_params"):
if self.split_input_params["patch_distributed_vq"]:
ks = self.split_input_params["ks"] # eg. (128, 128)
stride = self.split_input_params["stride"] # eg. (64, 64)
df = self.split_input_params["vqf"]
self.split_input_params['original_image_size'] = x.shape[-2:]
bs, nc, h, w = x.shape
if ks[0] > h or ks[1] > w:
ks = (min(ks[0], h), min(ks[1], w))
print("reducing Kernel")
if stride[0] > h or stride[1] > w:
stride = (min(stride[0], h), min(stride[1], w))
print("reducing stride")
fold, unfold, normalization, weighting = self.get_fold_unfold(x, ks, stride, df=df)
z = unfold(x) # (bn, nc * prod(**ks), L)
# Reshape to img shape
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
output_list = [self.first_stage_model.encode(z[:, :, :, :, i])
for i in range(z.shape[-1])]
o = torch.stack(output_list, axis=-1)
o = o * weighting
# Reverse reshape to img shape
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
# stitch crops together
decoded = fold(o)
decoded = decoded / normalization
return decoded
else:
return self.first_stage_model.encode(x)
else:
return self.first_stage_model.encode(x)
def shared_step(self, batch, **kwargs):
x, c = self.get_input(batch, self.first_stage_key)
loss = self(x, c)
return loss
def forward(self, x, c, *args, **kwargs):
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
if self.model.conditioning_key is not None:
assert c is not None
if self.cond_stage_trainable:
c = self.get_learned_conditioning(c)
if self.shorten_cond_schedule: # TODO: drop this option
tc = self.cond_ids[t].to(self.device)
c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float()))
return self.p_losses(x, c, t, *args, **kwargs)
def apply_model(self, x_noisy, t, cond, return_ids=False):
if isinstance(cond, dict):
# hybrid case, cond is expected to be a dict
pass
else:
if not isinstance(cond, list):
cond = [cond]
key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
cond = {key: cond}
if hasattr(self, "split_input_params"):
assert len(cond) == 1 # todo can only deal with one conditioning atm
assert not return_ids
ks = self.split_input_params["ks"] # eg. (128, 128)
stride = self.split_input_params["stride"] # eg. (64, 64)
h, w = x_noisy.shape[-2:]
fold, unfold, normalization, weighting = self.get_fold_unfold(x_noisy, ks, stride)
z = unfold(x_noisy) # (bn, nc * prod(**ks), L)
# Reshape to img shape
z = z.view((z.shape[0], -1, ks[0], ks[1], z.shape[-1])) # (bn, nc, ks[0], ks[1], L )
z_list = [z[:, :, :, :, i] for i in range(z.shape[-1])]
if self.cond_stage_key in ["image", "LR_image", "segmentation",
'bbox_img'] and self.model.conditioning_key: # todo check for completeness
c_key = next(iter(cond.keys())) # get key
c = next(iter(cond.values())) # get value
assert (len(c) == 1) # todo extend to list with more than one elem
c = c[0] # get element
c = unfold(c)
c = c.view((c.shape[0], -1, ks[0], ks[1], c.shape[-1])) # (bn, nc, ks[0], ks[1], L )
cond_list = [{c_key: [c[:, :, :, :, i]]} for i in range(c.shape[-1])]
elif self.cond_stage_key == 'coordinates_bbox':
assert 'original_image_size' in self.split_input_params, 'BoundingBoxRescaling is missing original_image_size'
# assuming padding of unfold is always 0 and its dilation is always 1
n_patches_per_row = int((w - ks[0]) / stride[0] + 1)
full_img_h, full_img_w = self.split_input_params['original_image_size']
# as we are operating on latents, we need the factor from the original image size to the
# spatial latent size to properly rescale the crops for regenerating the bbox annotations
num_downs = self.first_stage_model.encoder.num_resolutions - 1
rescale_latent = 2 ** (num_downs)
# get top left positions of patches as conforming for the bbbox tokenizer, therefore we
# need to rescale the tl patch coordinates to be in between (0,1)
tl_patch_coordinates = [(rescale_latent * stride[0] * (patch_nr % n_patches_per_row) / full_img_w,
rescale_latent * stride[1] * (patch_nr // n_patches_per_row) / full_img_h)
for patch_nr in range(z.shape[-1])]
# patch_limits are tl_coord, width and height coordinates as (x_tl, y_tl, h, w)
patch_limits = [(x_tl, y_tl,
rescale_latent * ks[0] / full_img_w,
rescale_latent * ks[1] / full_img_h) for x_tl, y_tl in tl_patch_coordinates]
# patch_values = [(np.arange(x_tl,min(x_tl+ks, 1.)),np.arange(y_tl,min(y_tl+ks, 1.))) for x_tl, y_tl in tl_patch_coordinates]
# tokenize crop coordinates for the bounding boxes of the respective patches
patch_limits_tknzd = [torch.LongTensor(self.bbox_tokenizer._crop_encoder(bbox))[None].to(self.device)
for bbox in patch_limits] # list of length l with tensors of shape (1, 2)
print(patch_limits_tknzd[0].shape)
# cut tknzd crop position from conditioning
assert isinstance(cond, dict), 'cond must be dict to be fed into model'
cut_cond = cond['c_crossattn'][0][..., :-2].to(self.device)
print(cut_cond.shape)
adapted_cond = torch.stack([torch.cat([cut_cond, p], dim=1) for p in patch_limits_tknzd])
adapted_cond = rearrange(adapted_cond, 'l b n -> (l b) n')
print(adapted_cond.shape)
adapted_cond = self.get_learned_conditioning(adapted_cond)
print(adapted_cond.shape)
adapted_cond = rearrange(adapted_cond, '(l b) n d -> l b n d', l=z.shape[-1])
print(adapted_cond.shape)
cond_list = [{'c_crossattn': [e]} for e in adapted_cond]
else:
cond_list = [cond for i in range(z.shape[-1])] # Todo make this more efficient
# apply model by loop over crops
output_list = [self.model(z_list[i], t, **cond_list[i]) for i in range(z.shape[-1])]
assert not isinstance(output_list[0],
tuple) # todo cant deal with multiple model outputs check this never happens
o = torch.stack(output_list, axis=-1)
o = o * weighting
# Reverse reshape to img shape
o = o.view((o.shape[0], -1, o.shape[-1])) # (bn, nc * ks[0] * ks[1], L)
# stitch crops together
x_recon = fold(o) / normalization
else:
x_recon = self.model(x_noisy, t, **cond)
if isinstance(x_recon, tuple) and not return_ids:
return x_recon[0]
else:
return x_recon
def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
def _prior_bpd(self, x_start):
batch_size = x_start.shape[0]
t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
return mean_flat(kl_prior) / np.log(2.0)
def p_losses(self, x_start, cond, t, noise=None):
noise = default(noise, lambda: torch.randn_like(x_start))
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
model_output = self.apply_model(x_noisy, t, cond)
loss_dict = {}
prefix = 'train' if self.training else 'val'
if self.parameterization == "x0":
target = x_start
elif self.parameterization == "eps":
target = noise
else:
raise NotImplementedError()
loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])
loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
logvar_t = self.logvar[t].to(self.device)
loss = loss_simple / torch.exp(logvar_t) + logvar_t
# loss = loss_simple / torch.exp(self.logvar) + self.logvar
if self.learn_logvar:
loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
loss_dict.update({'logvar': self.logvar.data.mean()})
loss = self.l_simple_weight * loss.mean()
loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))
loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
loss += (self.original_elbo_weight * loss_vlb)
loss_dict.update({f'{prefix}/loss': loss})
return loss, loss_dict
def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
return_x0=False, score_corrector=None, corrector_kwargs=None):
t_in = t
model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
if score_corrector is not None:
assert self.parameterization == "eps"
model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
if return_codebook_ids:
model_out, logits = model_out
if self.parameterization == "eps":
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
elif self.parameterization == "x0":
x_recon = model_out
else:
raise NotImplementedError()
if clip_denoised:
x_recon.clamp_(-1., 1.)
if quantize_denoised:
x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
if return_codebook_ids:
return model_mean, posterior_variance, posterior_log_variance, logits
elif return_x0:
return model_mean, posterior_variance, posterior_log_variance, x_recon
else:
return model_mean, posterior_variance, posterior_log_variance
@torch.no_grad()
def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
return_codebook_ids=False, quantize_denoised=False, return_x0=False,
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
b, *_, device = *x.shape, x.device
outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
return_codebook_ids=return_codebook_ids,
quantize_denoised=quantize_denoised,
return_x0=return_x0,
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
if return_codebook_ids:
raise DeprecationWarning("Support dropped.")
model_mean, _, model_log_variance, logits = outputs
elif return_x0:
model_mean, _, model_log_variance, x0 = outputs
else:
model_mean, _, model_log_variance = outputs
noise = noise_like(x.shape, device, repeat_noise) * temperature
if noise_dropout > 0.:
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
# no noise when t == 0
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
if return_codebook_ids:
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
if return_x0:
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
else:
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
@torch.no_grad()
def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
log_every_t=None):
if not log_every_t:
log_every_t = self.log_every_t
timesteps = self.num_timesteps
if batch_size is not None:
b = batch_size if batch_size is not None else shape[0]
shape = [batch_size] + list(shape)
else:
b = batch_size = shape[0]
if x_T is None:
img = torch.randn(shape, device=self.device)
else:
img = x_T
intermediates = []
if cond is not None:
if isinstance(cond, dict):
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
[x[:batch_size] for x in cond[key]] for key in cond}
else:
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
if start_T is not None:
timesteps = min(timesteps, start_T)
iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
total=timesteps) if verbose else reversed(
range(0, timesteps))
if type(temperature) == float:
temperature = [temperature] * timesteps
for i in iterator:
ts = torch.full((b,), i, device=self.device, dtype=torch.long)
if self.shorten_cond_schedule:
assert self.model.conditioning_key != 'hybrid'
tc = self.cond_ids[ts].to(cond.device)
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
img, x0_partial = self.p_sample(img, cond, ts,
clip_denoised=self.clip_denoised,
quantize_denoised=quantize_denoised, return_x0=True,
temperature=temperature[i], noise_dropout=noise_dropout,
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
if mask is not None:
assert x0 is not None
img_orig = self.q_sample(x0, ts)
img = img_orig * mask + (1. - mask) * img
if i % log_every_t == 0 or i == timesteps - 1:
intermediates.append(x0_partial)
if callback:
callback(i)
if img_callback:
img_callback(img, i)
return img, intermediates
@torch.no_grad()
def p_sample_loop(self, cond, shape, return_intermediates=False,
x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
mask=None, x0=None, img_callback=None, start_T=None,
log_every_t=None):
if not log_every_t:
log_every_t = self.log_every_t
device = self.betas.device
b = shape[0]
if x_T is None:
img = torch.randn(shape, device=device)
else:
img = x_T
intermediates = [img]
if timesteps is None:
timesteps = self.num_timesteps
if start_T is not None:
timesteps = min(timesteps, start_T)
iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
range(0, timesteps))
if mask is not None:
assert x0 is not None
assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
for i in iterator:
ts = torch.full((b,), i, device=device, dtype=torch.long)
if self.shorten_cond_schedule:
assert self.model.conditioning_key != 'hybrid'
tc = self.cond_ids[ts].to(cond.device)
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
img = self.p_sample(img, cond, ts,
clip_denoised=self.clip_denoised,
quantize_denoised=quantize_denoised)
if mask is not None:
img_orig = self.q_sample(x0, ts)
img = img_orig * mask + (1. - mask) * img
if i % log_every_t == 0 or i == timesteps - 1:
intermediates.append(img)
if callback:
callback(i)
if img_callback:
img_callback(img, i)
if return_intermediates:
return img, intermediates
return img
@torch.no_grad()
def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
verbose=True, timesteps=None, quantize_denoised=False,
mask=None, x0=None, shape=None,**kwargs):
if shape is None:
shape = (batch_size, self.channels, self.image_size, self.image_size)
if cond is not None:
if isinstance(cond, dict):
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
[x[:batch_size] for x in cond[key]] for key in cond}
else:
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
return self.p_sample_loop(cond,
shape,
return_intermediates=return_intermediates, x_T=x_T,
verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
mask=mask, x0=x0)
@torch.no_grad()
def sample_log(self,cond,batch_size,ddim, ddim_steps,**kwargs):
if ddim:
ddim_sampler = DDIMSampler(self)
shape = (self.channels, self.image_size, self.image_size)
samples, intermediates =ddim_sampler.sample(ddim_steps,batch_size,
shape,cond,verbose=False,**kwargs)
else:
samples, intermediates = self.sample(cond=cond, batch_size=batch_size,
return_intermediates=True,**kwargs)
return samples, intermediates
@torch.no_grad()
def log_images(self, batch, N=4, n_row=4, sample=True, ddim_steps=200, ddim_eta=1., return_keys=None,
quantize_denoised=True, inpaint=False, plot_denoise_rows=False, plot_progressive_rows=False,
plot_diffusion_rows=False, **kwargs):
use_ddim = False
log = {}
z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
return_first_stage_outputs=True,
force_c_encode=True,
return_original_cond=True,
bs=N, uncond=0)
N = min(x.shape[0], N)
n_row = min(x.shape[0], n_row)
log["inputs"] = x
log["reals"] = xc["c_concat"]
log["reconstruction"] = xrec
if self.model.conditioning_key is not None:
if hasattr(self.cond_stage_model, "decode"):
xc = self.cond_stage_model.decode(c)
log["conditioning"] = xc
elif self.cond_stage_key in ["caption"]:
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["caption"])
log["conditioning"] = xc
elif self.cond_stage_key == 'class_label':
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"])
log['conditioning'] = xc
elif isimage(xc):
log["conditioning"] = xc
if ismap(xc):
log["original_conditioning"] = self.to_rgb(xc)
if plot_diffusion_rows:
# get diffusion row
diffusion_row = []
z_start = z[:n_row]
for t in range(self.num_timesteps):
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
t = t.to(self.device).long()
noise = torch.randn_like(z_start)
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
diffusion_row.append(self.decode_first_stage(z_noisy))
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
log["diffusion_row"] = diffusion_grid
if sample:
# get denoise row
with self.ema_scope("Plotting"):
samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
ddim_steps=ddim_steps,eta=ddim_eta)
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
x_samples = self.decode_first_stage(samples)
log["samples"] = x_samples
if plot_denoise_rows:
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
log["denoise_row"] = denoise_grid
if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
self.first_stage_model, IdentityFirstStage):
# also display when quantizing x0 while sampling
with self.ema_scope("Plotting Quantized Denoised"):
samples, z_denoise_row = self.sample_log(cond=c,batch_size=N,ddim=use_ddim,
ddim_steps=ddim_steps,eta=ddim_eta,
quantize_denoised=True)
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
# quantize_denoised=True)
x_samples = self.decode_first_stage(samples.to(self.device))
log["samples_x0_quantized"] = x_samples
if inpaint:
# make a simple center square
h, w = z.shape[2], z.shape[3]
mask = torch.ones(N, h, w).to(self.device)
# zeros will be filled in
mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
mask = mask[:, None, ...]
with self.ema_scope("Plotting Inpaint"):
samples, _ = self.sample_log(cond=c,batch_size=N,ddim=use_ddim, eta=ddim_eta,
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
x_samples = self.decode_first_stage(samples.to(self.device))
log["samples_inpainting"] = x_samples
log["mask"] = mask
# outpaint
with self.ema_scope("Plotting Outpaint"):
samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,eta=ddim_eta,
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
x_samples = self.decode_first_stage(samples.to(self.device))
log["samples_outpainting"] = x_samples
if plot_progressive_rows:
with self.ema_scope("Plotting Progressives"):
img, progressives = self.progressive_denoising(c,
shape=(self.channels, self.image_size, self.image_size),
batch_size=N)
prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
log["progressive_row"] = prog_row
if return_keys:
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
return log
else:
return {key: log[key] for key in return_keys}
return log
def configure_optimizers(self):
lr = self.learning_rate
params = list(self.model.parameters())
if self.cond_stage_trainable:
print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
params = params + list(self.cond_stage_model.parameters())
if self.learn_logvar:
print('Diffusion model optimizing logvar')
params.append(self.logvar)
opt = torch.optim.AdamW(params, lr=lr)
if self.use_scheduler:
assert 'target' in self.scheduler_config
scheduler = instantiate_from_config(self.scheduler_config)
print("Setting up LambdaLR scheduler...")
scheduler = [
{
'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
'interval': 'step',
'frequency': 1
}]
return [opt], scheduler
return opt
@torch.no_grad()
def to_rgb(self, x):
x = x.float()
if not hasattr(self, "colorize"):
self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
x = nn.functional.conv2d(x, weight=self.colorize)
x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
return x
class DiffusionWrapper(pl.LightningModule):
def __init__(self, diff_model_config, conditioning_key):
super().__init__()
self.diffusion_model = instantiate_from_config(diff_model_config)
self.conditioning_key = conditioning_key
assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm']
def forward(self, x, t, c_concat: list = None, c_crossattn: list = None):
if self.conditioning_key is None:
out = self.diffusion_model(x, t)
elif self.conditioning_key == 'concat':
xc = torch.cat([x] + c_concat, dim=1)
out = self.diffusion_model(xc, t)
elif self.conditioning_key == 'crossattn':
cc = torch.cat(c_crossattn, 1)
out = self.diffusion_model(x, t, context=cc)
elif self.conditioning_key == 'hybrid':
xc = torch.cat([x] + c_concat, dim=1)
cc = torch.cat(c_crossattn, 1)
out = self.diffusion_model(xc, t, context=cc)
elif self.conditioning_key == 'adm':
cc = c_crossattn[0]
out = self.diffusion_model(x, t, y=cc)
else:
raise NotImplementedError()
return out
class Layout2ImgDiffusion(LatentDiffusion):
# TODO: move all layout-specific hacks to this class
def __init__(self, cond_stage_key, *args, **kwargs):
assert cond_stage_key == 'coordinates_bbox', 'Layout2ImgDiffusion only for cond_stage_key="coordinates_bbox"'
super().__init__(*args, cond_stage_key=cond_stage_key, **kwargs)
def log_images(self, batch, N=8, *args, **kwargs):
logs = super().log_images(*args, batch=batch, N=N, **kwargs)
key = 'train' if self.training else 'validation'
dset = self.trainer.datamodule.datasets[key]
mapper = dset.conditional_builders[self.cond_stage_key]
bbox_imgs = []
map_fn = lambda catno: dset.get_textual_label(dset.get_category_id(catno))
for tknzd_bbox in batch[self.cond_stage_key][:N]:
bboximg = mapper.plot(tknzd_bbox.detach().cpu(), map_fn, (256, 256))
bbox_imgs.append(bboximg)
cond_img = torch.stack(bbox_imgs, dim=0)
logs['bbox_image'] = cond_img
return logs | --- +++ @@ -1,3 +1,10 @@+"""
+wild mixture of
+https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
+https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
+https://github.com/CompVis/taming-transformers
+-- merci
+"""
# File modified by authors of InstructPix2Pix from original (https://github.com/CompVis/stable-diffusion).
# See more details in LICENSE.
@@ -33,6 +40,8 @@
def disabled_train(self, mode=True):
+ """Overwrite model.train with this function to make sure train/eval mode
+ does not change anymore."""
return self
@@ -232,6 +241,12 @@ print(f"Unexpected Keys: {unexpected}")
def q_mean_variance(self, x_start, t):
+ """
+ Get the distribution q(x_t | x_0).
+ :param x_start: the [N x C x ...] tensor of noiseless inputs.
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
+ :return: A tuple (mean, variance, log_variance), all of x_start's shape.
+ """
mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
@@ -441,6 +456,7 @@
class LatentDiffusion(DDPM):
+ """main class"""
def __init__(self,
first_stage_config,
cond_stage_config,
@@ -592,6 +608,12 @@ return arr
def delta_border(self, h, w):
+ """
+ :param h: height
+ :param w: width
+ :return: normalized distance to image border,
+ wtith min distance = 0 at border and max dist = 0.5 at image center
+ """
lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
arr = self.meshgrid(h, w) / lower_right_corner
dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
@@ -616,6 +638,10 @@ return weighting
def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
+ """
+ :param x: img of size (bs, c, h, w)
+ :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
+ """
bs, nc, h, w = x.shape
# number of crops in image
@@ -980,6 +1006,13 @@ extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
def _prior_bpd(self, x_start):
+ """
+ Get the prior KL term for the variational lower-bound, measured in
+ bits-per-dim.
+ This term can't be optimized, as it only depends on the encoder.
+ :param x_start: the [N x C x ...] tensor of inputs.
+ :return: a batch of [N] KL values (in bits), one per batch element.
+ """
batch_size = x_start.shape[0]
t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
@@ -1424,4 +1457,4 @@
cond_img = torch.stack(bbox_imgs, dim=0)
logs['bbox_image'] = cond_img
- return logs+ return logs
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/models/diffusion/ddpm_edit.py |
Write reusable docstrings | ### Impls of the SD3 core diffusion model and VAE
import torch
import math
import einops
from modules.models.sd3.mmdit import MMDiT
from PIL import Image
#################################################################################################
### MMDiT Model Wrapping
#################################################################################################
class ModelSamplingDiscreteFlow(torch.nn.Module):
def __init__(self, shift=1.0):
super().__init__()
self.shift = shift
timesteps = 1000
ts = self.sigma(torch.arange(1, timesteps + 1, 1))
self.register_buffer('sigmas', ts)
@property
def sigma_min(self):
return self.sigmas[0]
@property
def sigma_max(self):
return self.sigmas[-1]
def timestep(self, sigma):
return sigma * 1000
def sigma(self, timestep: torch.Tensor):
timestep = timestep / 1000.0
if self.shift == 1.0:
return timestep
return self.shift * timestep / (1 + (self.shift - 1) * timestep)
def calculate_denoised(self, sigma, model_output, model_input):
sigma = sigma.view(sigma.shape[:1] + (1,) * (model_output.ndim - 1))
return model_input - model_output * sigma
def noise_scaling(self, sigma, noise, latent_image, max_denoise=False):
return sigma * noise + (1.0 - sigma) * latent_image
class BaseModel(torch.nn.Module):
def __init__(self, shift=1.0, device=None, dtype=torch.float32, state_dict=None, prefix=""):
super().__init__()
# Important configuration values can be quickly determined by checking shapes in the source file
# Some of these will vary between models (eg 2B vs 8B primarily differ in their depth, but also other details change)
patch_size = state_dict[f"{prefix}x_embedder.proj.weight"].shape[2]
depth = state_dict[f"{prefix}x_embedder.proj.weight"].shape[0] // 64
num_patches = state_dict[f"{prefix}pos_embed"].shape[1]
pos_embed_max_size = round(math.sqrt(num_patches))
adm_in_channels = state_dict[f"{prefix}y_embedder.mlp.0.weight"].shape[1]
context_shape = state_dict[f"{prefix}context_embedder.weight"].shape
context_embedder_config = {
"target": "torch.nn.Linear",
"params": {
"in_features": context_shape[1],
"out_features": context_shape[0]
}
}
self.diffusion_model = MMDiT(input_size=None, pos_embed_scaling_factor=None, pos_embed_offset=None, pos_embed_max_size=pos_embed_max_size, patch_size=patch_size, in_channels=16, depth=depth, num_patches=num_patches, adm_in_channels=adm_in_channels, context_embedder_config=context_embedder_config, device=device, dtype=dtype)
self.model_sampling = ModelSamplingDiscreteFlow(shift=shift)
self.depth = depth
def apply_model(self, x, sigma, c_crossattn=None, y=None):
dtype = self.get_dtype()
timestep = self.model_sampling.timestep(sigma).float()
model_output = self.diffusion_model(x.to(dtype), timestep, context=c_crossattn.to(dtype), y=y.to(dtype)).float()
return self.model_sampling.calculate_denoised(sigma, model_output, x)
def forward(self, *args, **kwargs):
return self.apply_model(*args, **kwargs)
def get_dtype(self):
return self.diffusion_model.dtype
class CFGDenoiser(torch.nn.Module):
def __init__(self, model):
super().__init__()
self.model = model
def forward(self, x, timestep, cond, uncond, cond_scale):
# Run cond and uncond in a batch together
batched = self.model.apply_model(torch.cat([x, x]), torch.cat([timestep, timestep]), c_crossattn=torch.cat([cond["c_crossattn"], uncond["c_crossattn"]]), y=torch.cat([cond["y"], uncond["y"]]))
# Then split and apply CFG Scaling
pos_out, neg_out = batched.chunk(2)
scaled = neg_out + (pos_out - neg_out) * cond_scale
return scaled
class SD3LatentFormat:
def __init__(self):
self.scale_factor = 1.5305
self.shift_factor = 0.0609
def process_in(self, latent):
return (latent - self.shift_factor) * self.scale_factor
def process_out(self, latent):
return (latent / self.scale_factor) + self.shift_factor
def decode_latent_to_preview(self, x0):
factors = torch.tensor([
[-0.0645, 0.0177, 0.1052], [ 0.0028, 0.0312, 0.0650],
[ 0.1848, 0.0762, 0.0360], [ 0.0944, 0.0360, 0.0889],
[ 0.0897, 0.0506, -0.0364], [-0.0020, 0.1203, 0.0284],
[ 0.0855, 0.0118, 0.0283], [-0.0539, 0.0658, 0.1047],
[-0.0057, 0.0116, 0.0700], [-0.0412, 0.0281, -0.0039],
[ 0.1106, 0.1171, 0.1220], [-0.0248, 0.0682, -0.0481],
[ 0.0815, 0.0846, 0.1207], [-0.0120, -0.0055, -0.0867],
[-0.0749, -0.0634, -0.0456], [-0.1418, -0.1457, -0.1259]
], device="cpu")
latent_image = x0[0].permute(1, 2, 0).cpu() @ factors
latents_ubyte = (((latent_image + 1) / 2)
.clamp(0, 1) # change scale from -1..1 to 0..1
.mul(0xFF) # to 0..255
.byte()).cpu()
return Image.fromarray(latents_ubyte.numpy())
#################################################################################################
### K-Diffusion Sampling
#################################################################################################
def append_dims(x, target_dims):
dims_to_append = target_dims - x.ndim
return x[(...,) + (None,) * dims_to_append]
def to_d(x, sigma, denoised):
return (x - denoised) / append_dims(sigma, x.ndim)
@torch.no_grad()
@torch.autocast("cuda", dtype=torch.float16)
def sample_euler(model, x, sigmas, extra_args=None):
extra_args = {} if extra_args is None else extra_args
s_in = x.new_ones([x.shape[0]])
for i in range(len(sigmas) - 1):
sigma_hat = sigmas[i]
denoised = model(x, sigma_hat * s_in, **extra_args)
d = to_d(x, sigma_hat, denoised)
dt = sigmas[i + 1] - sigma_hat
# Euler method
x = x + d * dt
return x
#################################################################################################
### VAE
#################################################################################################
def Normalize(in_channels, num_groups=32, dtype=torch.float32, device=None):
return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True, dtype=dtype, device=device)
class ResnetBlock(torch.nn.Module):
def __init__(self, *, in_channels, out_channels=None, dtype=torch.float32, device=None):
super().__init__()
self.in_channels = in_channels
out_channels = in_channels if out_channels is None else out_channels
self.out_channels = out_channels
self.norm1 = Normalize(in_channels, dtype=dtype, device=device)
self.conv1 = torch.nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1, dtype=dtype, device=device)
self.norm2 = Normalize(out_channels, dtype=dtype, device=device)
self.conv2 = torch.nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, dtype=dtype, device=device)
if self.in_channels != self.out_channels:
self.nin_shortcut = torch.nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, dtype=dtype, device=device)
else:
self.nin_shortcut = None
self.swish = torch.nn.SiLU(inplace=True)
def forward(self, x):
hidden = x
hidden = self.norm1(hidden)
hidden = self.swish(hidden)
hidden = self.conv1(hidden)
hidden = self.norm2(hidden)
hidden = self.swish(hidden)
hidden = self.conv2(hidden)
if self.in_channels != self.out_channels:
x = self.nin_shortcut(x)
return x + hidden
class AttnBlock(torch.nn.Module):
def __init__(self, in_channels, dtype=torch.float32, device=None):
super().__init__()
self.norm = Normalize(in_channels, dtype=dtype, device=device)
self.q = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0, dtype=dtype, device=device)
self.k = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0, dtype=dtype, device=device)
self.v = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0, dtype=dtype, device=device)
self.proj_out = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0, dtype=dtype, device=device)
def forward(self, x):
hidden = self.norm(x)
q = self.q(hidden)
k = self.k(hidden)
v = self.v(hidden)
b, c, h, w = q.shape
q, k, v = [einops.rearrange(x, "b c h w -> b 1 (h w) c").contiguous() for x in (q, k, v)]
hidden = torch.nn.functional.scaled_dot_product_attention(q, k, v) # scale is dim ** -0.5 per default
hidden = einops.rearrange(hidden, "b 1 (h w) c -> b c h w", h=h, w=w, c=c, b=b)
hidden = self.proj_out(hidden)
return x + hidden
class Downsample(torch.nn.Module):
def __init__(self, in_channels, dtype=torch.float32, device=None):
super().__init__()
self.conv = torch.nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0, dtype=dtype, device=device)
def forward(self, x):
pad = (0,1,0,1)
x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
x = self.conv(x)
return x
class Upsample(torch.nn.Module):
def __init__(self, in_channels, dtype=torch.float32, device=None):
super().__init__()
self.conv = torch.nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1, dtype=dtype, device=device)
def forward(self, x):
x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
x = self.conv(x)
return x
class VAEEncoder(torch.nn.Module):
def __init__(self, ch=128, ch_mult=(1,2,4,4), num_res_blocks=2, in_channels=3, z_channels=16, dtype=torch.float32, device=None):
super().__init__()
self.num_resolutions = len(ch_mult)
self.num_res_blocks = num_res_blocks
# downsampling
self.conv_in = torch.nn.Conv2d(in_channels, ch, kernel_size=3, stride=1, padding=1, dtype=dtype, device=device)
in_ch_mult = (1,) + tuple(ch_mult)
self.in_ch_mult = in_ch_mult
self.down = torch.nn.ModuleList()
for i_level in range(self.num_resolutions):
block = torch.nn.ModuleList()
attn = torch.nn.ModuleList()
block_in = ch*in_ch_mult[i_level]
block_out = ch*ch_mult[i_level]
for _ in range(num_res_blocks):
block.append(ResnetBlock(in_channels=block_in, out_channels=block_out, dtype=dtype, device=device))
block_in = block_out
down = torch.nn.Module()
down.block = block
down.attn = attn
if i_level != self.num_resolutions - 1:
down.downsample = Downsample(block_in, dtype=dtype, device=device)
self.down.append(down)
# middle
self.mid = torch.nn.Module()
self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in, dtype=dtype, device=device)
self.mid.attn_1 = AttnBlock(block_in, dtype=dtype, device=device)
self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in, dtype=dtype, device=device)
# end
self.norm_out = Normalize(block_in, dtype=dtype, device=device)
self.conv_out = torch.nn.Conv2d(block_in, 2 * z_channels, kernel_size=3, stride=1, padding=1, dtype=dtype, device=device)
self.swish = torch.nn.SiLU(inplace=True)
def forward(self, x):
# downsampling
hs = [self.conv_in(x)]
for i_level in range(self.num_resolutions):
for i_block in range(self.num_res_blocks):
h = self.down[i_level].block[i_block](hs[-1])
hs.append(h)
if i_level != self.num_resolutions-1:
hs.append(self.down[i_level].downsample(hs[-1]))
# middle
h = hs[-1]
h = self.mid.block_1(h)
h = self.mid.attn_1(h)
h = self.mid.block_2(h)
# end
h = self.norm_out(h)
h = self.swish(h)
h = self.conv_out(h)
return h
class VAEDecoder(torch.nn.Module):
def __init__(self, ch=128, out_ch=3, ch_mult=(1, 2, 4, 4), num_res_blocks=2, resolution=256, z_channels=16, dtype=torch.float32, device=None):
super().__init__()
self.num_resolutions = len(ch_mult)
self.num_res_blocks = num_res_blocks
block_in = ch * ch_mult[self.num_resolutions - 1]
curr_res = resolution // 2 ** (self.num_resolutions - 1)
# z to block_in
self.conv_in = torch.nn.Conv2d(z_channels, block_in, kernel_size=3, stride=1, padding=1, dtype=dtype, device=device)
# middle
self.mid = torch.nn.Module()
self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in, dtype=dtype, device=device)
self.mid.attn_1 = AttnBlock(block_in, dtype=dtype, device=device)
self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in, dtype=dtype, device=device)
# upsampling
self.up = torch.nn.ModuleList()
for i_level in reversed(range(self.num_resolutions)):
block = torch.nn.ModuleList()
block_out = ch * ch_mult[i_level]
for _ in range(self.num_res_blocks + 1):
block.append(ResnetBlock(in_channels=block_in, out_channels=block_out, dtype=dtype, device=device))
block_in = block_out
up = torch.nn.Module()
up.block = block
if i_level != 0:
up.upsample = Upsample(block_in, dtype=dtype, device=device)
curr_res = curr_res * 2
self.up.insert(0, up) # prepend to get consistent order
# end
self.norm_out = Normalize(block_in, dtype=dtype, device=device)
self.conv_out = torch.nn.Conv2d(block_in, out_ch, kernel_size=3, stride=1, padding=1, dtype=dtype, device=device)
self.swish = torch.nn.SiLU(inplace=True)
def forward(self, z):
# z to block_in
hidden = self.conv_in(z)
# middle
hidden = self.mid.block_1(hidden)
hidden = self.mid.attn_1(hidden)
hidden = self.mid.block_2(hidden)
# upsampling
for i_level in reversed(range(self.num_resolutions)):
for i_block in range(self.num_res_blocks + 1):
hidden = self.up[i_level].block[i_block](hidden)
if i_level != 0:
hidden = self.up[i_level].upsample(hidden)
# end
hidden = self.norm_out(hidden)
hidden = self.swish(hidden)
hidden = self.conv_out(hidden)
return hidden
class SDVAE(torch.nn.Module):
def __init__(self, dtype=torch.float32, device=None):
super().__init__()
self.encoder = VAEEncoder(dtype=dtype, device=device)
self.decoder = VAEDecoder(dtype=dtype, device=device)
@torch.autocast("cuda", dtype=torch.float16)
def decode(self, latent):
return self.decoder(latent)
@torch.autocast("cuda", dtype=torch.float16)
def encode(self, image):
hidden = self.encoder(image)
mean, logvar = torch.chunk(hidden, 2, dim=1)
logvar = torch.clamp(logvar, -30.0, 20.0)
std = torch.exp(0.5 * logvar)
return mean + std * torch.randn_like(mean) | --- +++ @@ -13,6 +13,7 @@
class ModelSamplingDiscreteFlow(torch.nn.Module):
+ """Helper for sampler scheduling (ie timestep/sigma calculations) for Discrete Flow models"""
def __init__(self, shift=1.0):
super().__init__()
self.shift = shift
@@ -46,6 +47,7 @@
class BaseModel(torch.nn.Module):
+ """Wrapper around the core MM-DiT model"""
def __init__(self, shift=1.0, device=None, dtype=torch.float32, state_dict=None, prefix=""):
super().__init__()
# Important configuration values can be quickly determined by checking shapes in the source file
@@ -81,6 +83,7 @@
class CFGDenoiser(torch.nn.Module):
+ """Helper for applying CFG Scaling to diffusion outputs"""
def __init__(self, model):
super().__init__()
self.model = model
@@ -95,6 +98,7 @@
class SD3LatentFormat:
+ """Latents are slightly shifted from center - this class must be called after VAE Decode to correct for the shift"""
def __init__(self):
self.scale_factor = 1.5305
self.shift_factor = 0.0609
@@ -106,6 +110,7 @@ return (latent / self.scale_factor) + self.shift_factor
def decode_latent_to_preview(self, x0):
+ """Quick RGB approximate preview of sd3 latents"""
factors = torch.tensor([
[-0.0645, 0.0177, 0.1052], [ 0.0028, 0.0312, 0.0650],
[ 0.1848, 0.0762, 0.0360], [ 0.0944, 0.0360, 0.0889],
@@ -132,17 +137,20 @@
def append_dims(x, target_dims):
+ """Appends dimensions to the end of a tensor until it has target_dims dimensions."""
dims_to_append = target_dims - x.ndim
return x[(...,) + (None,) * dims_to_append]
def to_d(x, sigma, denoised):
+ """Converts a denoiser output to a Karras ODE derivative."""
return (x - denoised) / append_dims(sigma, x.ndim)
@torch.no_grad()
@torch.autocast("cuda", dtype=torch.float16)
def sample_euler(model, x, sigmas, extra_args=None):
+ """Implements Algorithm 2 (Euler steps) from Karras et al. (2022)."""
extra_args = {} if extra_args is None else extra_args
s_in = x.new_ones([x.shape[0]])
for i in range(len(sigmas) - 1):
@@ -363,4 +371,4 @@ mean, logvar = torch.chunk(hidden, 2, dim=1)
logvar = torch.clamp(logvar, -30.0, 20.0)
std = torch.exp(0.5 * logvar)
- return mean + std * torch.randn_like(mean)+ return mean + std * torch.randn_like(mean)
| https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/models/sd3/sd3_impls.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.