Find and return the code source code of `object_name`.
(object_name)
| 31 | |
| 32 | |
| 33 | def find_code_in_diffusers(object_name): |
| 34 | """Find and return the code source code of `object_name`.""" |
| 35 | parts = object_name.split(".") |
| 36 | i = 0 |
| 37 | |
| 38 | # First let's find the module where our object lives. |
| 39 | module = parts[i] |
| 40 | while i < len(parts) and not os.path.isfile(os.path.join(DIFFUSERS_PATH, f"{module}.py")): |
| 41 | i += 1 |
| 42 | if i < len(parts): |
| 43 | module = os.path.join(module, parts[i]) |
| 44 | if i >= len(parts): |
| 45 | raise ValueError(f"`object_name` should begin with the name of a module of diffusers but got {object_name}.") |
| 46 | |
| 47 | with open( |
| 48 | os.path.join(DIFFUSERS_PATH, f"{module}.py"), |
| 49 | "r", |
| 50 | encoding="utf-8", |
| 51 | newline="\n", |
| 52 | ) as f: |
| 53 | lines = f.readlines() |
| 54 | |
| 55 | # Now let's find the class / func in the code! |
| 56 | indent = "" |
| 57 | line_index = 0 |
| 58 | for name in parts[i + 1 :]: |
| 59 | while ( |
| 60 | line_index < len(lines) and re.search(rf"^{indent}(class|def)\s+{name}(\(|\:)", lines[line_index]) is None |
| 61 | ): |
| 62 | line_index += 1 |
| 63 | indent += " " |
| 64 | line_index += 1 |
| 65 | |
| 66 | if line_index >= len(lines): |
| 67 | raise ValueError(f" {object_name} does not match any function or class in {module}.") |
| 68 | |
| 69 | # We found the beginning of the class / func, now let's find the end (when the indent diminishes). |
| 70 | start_index = line_index |
| 71 | while line_index < len(lines) and _should_continue(lines[line_index], indent): |
| 72 | line_index += 1 |
| 73 | # Clean up empty lines at the end (if any). |
| 74 | while len(lines[line_index - 1]) <= 1: |
| 75 | line_index -= 1 |
| 76 | |
| 77 | code_lines = lines[start_index:line_index] |
| 78 | return "".join(code_lines) |
| 79 | |
| 80 | |
| 81 | _re_copy_warning = re.compile(r"^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)") |
no test coverage detected