instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Create documentation for each function signature
def build_fact_text_from_triple_entry(entry: dict) -> str | None: content = entry.get("content") if isinstance(content, str) and content: return content subject = entry.get("subject") or {} predicate = entry.get("predicate") object_ = entry.get("object") or {} subject_name = subject....
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" def build_fact_...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/memory/_struct.py
Add standardized docstrings across the file
import logging from dataclasses import asdict, is_dataclass from memori._network import Api from memori.embeddings import embed_texts from memori.memory._struct import Memories, build_fact_text_from_triple_entry from memori.memory.augmentation._base import AugmentationContext, BaseAugmentation from memori.memory.augm...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" import logging f...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/memory/augmentation/augmentations/memori/_augmentation.py
Can you add docstrings to this Python file?
import random import string random.seed(42) def generate_random_string(length: int = 10) -> str: return "".join(random.choices(string.ascii_letters + string.digits, k=length)) def generate_sample_fact() -> str: templates = [ "User likes {item}", "User lives in {location}", "User wo...
--- +++ @@ -1,3 +1,4 @@+"""Helper functions for generating sample test data for benchmarks.""" import random import string @@ -6,10 +7,12 @@ def generate_random_string(length: int = 10) -> str: + """Generate a random string of specified length.""" return "".join(random.choices(string.ascii_letters + str...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/benchmarks/perf/fixtures/sample_data.py
Improve documentation using docstrings
import json import sys from pathlib import Path def calculate_percentile(data, percentile): if not data: return None sorted_data = sorted(data) index = (len(sorted_data) - 1) * percentile / 100 lower = int(index) upper = lower + 1 weight = index - lower if upper >= len(sorted_dat...
--- +++ @@ -1,3 +1,4 @@+"""Generate percentile report (p50/p95/p99) from benchmark JSON results.""" import json import sys @@ -5,6 +6,7 @@ def calculate_percentile(data, percentile): + """Calculate percentile from sorted data.""" if not data: return None sorted_data = sorted(data) @@ -20,6...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/benchmarks/perf/generate_percentile_report.py
Add clean documentation to messy code
from collections.abc import Callable from typing import Any from memori._exceptions import UnsupportedLLMProviderError from memori.llm._base import BaseClient, BaseLlmAdaptor class Registry: _clients: dict[Callable[[Any], bool], type[BaseClient]] = {} _adapters: dict[Callable[[str | None, str | None], bool]...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from collections....
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/llm/_registry.py
Write clean docstrings for readability
from __future__ import annotations from typing import Any from memori.search._core import ( search_entity_facts_core, ) from memori.search._faiss import find_similar_embeddings from memori.search._lexical import dense_lexical_weights, lexical_scores_for_ids from memori.search._types import FactCandidate, FactSea...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from __future__ i...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/search/_api.py
Add docstrings to my Python code
import asyncio import json import time from google.protobuf import json_format from memori.llm._constants import XAI_LLM_PROVIDER class XAiWrappers: def __init__(self, config): self.config = config def _ensure_cached_conversation_id(self) -> bool: if self.config.storage is None or self.co...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" import asyncio imp...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/llm/_xai_wrappers.py
Expand my code with proper documentation strings
from dataclasses import dataclass from memori.memory.augmentation._message import ConversationMessage @dataclass class AugmentationInput: conversation_id: str | None entity_id: str | None process_id: str | None conversation_messages: list[ConversationMessage] system_prompt: str | None = None
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from dataclasses ...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/memory/augmentation/input.py
Add docstrings to improve code quality
from memori.llm._base import BaseLlmAdaptor from memori.llm._registry import Registry from memori.llm._utils import agno_is_google, llm_is_google @Registry.register_adapter(llm_is_google) @Registry.register_adapter(agno_is_google) class Adapter(BaseLlmAdaptor): def get_formatted_query(self, payload): me...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from memori.llm._...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/llm/adapters/google/_adapter.py
Fully document this Python code with docstrings
from __future__ import annotations import logging from typing import Any logger = logging.getLogger(__name__) def chunk_text_by_tokens( *, text: str, tokenizer: Any, chunk_size: int, ) -> list[str]: if chunk_size <= 0: raise ValueError("chunk_size must be > 0") tokens = tokenizer(t...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from __future__ i...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/embeddings/_chunking.py
Add docstrings to improve collaboration
import asyncio import logging from collections.abc import Callable from concurrent.futures import Future from typing import Any from memori._config import Config from memori.memory.augmentation._base import AugmentationContext from memori.memory.augmentation._db_writer import WriteTask, get_db_writer from memori.memo...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" import asyncio imp...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/memory/augmentation/_manager.py
Add docstrings that explain purpose and usage
from pymongo.synchronous.mongo_client import MongoClient from memori.storage._base import BaseStorageAdapter from memori.storage._registry import Registry @Registry.register_adapter( lambda conn: hasattr(conn, "database") and hasattr(conn, "list_collection_names") ) class Adapter(BaseStorageAdapter): def e...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from pymongo.sync...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/storage/adapters/mongodb/_adapter.py
Generate helpful docstrings for debugging
from __future__ import annotations import asyncio import logging from collections.abc import Awaitable from functools import partial from typing import Literal, overload from memori.embeddings._sentence_transformers import get_sentence_transformers_embedder from memori.embeddings._tei import TEI from memori.embeddin...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from __future__ i...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/embeddings/_api.py
Write clean docstrings for readability
import warnings from importlib.metadata import PackageNotFoundError, distribution class QuotaExceededError(Exception): def __init__( self, message=( "your IP address is over quota; register for an API key now: " + "https://app.memorilabs.ai/signup" ), ): ...
--- +++ @@ -1,3 +1,12 @@+r""" + _ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" import warnings fro...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/_exceptions.py
Generate docstrings for exported functions
from memori.llm._base import BaseClient from memori.llm._constants import ( AGNO_FRAMEWORK_PROVIDER, AGNO_GOOGLE_LLM_PROVIDER, ATHROPIC_LLM_PROVIDER, GOOGLE_LLM_PROVIDER, LANGCHAIN_CHATBEDROCK_LLM_PROVIDER, LANGCHAIN_CHATGOOGLEGENAI_LLM_PROVIDER, LANGCHAIN_CHATVERTEXAI_LLM_PROVIDER, LAN...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from memori.llm._...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/llm/_clients.py
Add docstrings to improve collaboration
from memori.llm._base import BaseLlmAdaptor from memori.llm._registry import Registry from memori.llm._utils import agno_is_anthropic, llm_is_anthropic @Registry.register_adapter(llm_is_anthropic) @Registry.register_adapter(agno_is_anthropic) class Adapter(BaseLlmAdaptor): def get_formatted_query(self, payload):...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from memori.llm._...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/llm/adapters/anthropic/_adapter.py
Add docstrings to improve readability
import os from collections.abc import Callable from typing import Any from uuid import uuid4 from memori._config import Config from memori._exceptions import ( MissingMemoriApiKeyError, MissingPsycopgError, QuotaExceededError, UnsupportedLLMProviderError, warn_if_legacy_memorisdk_installed, ) from...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" import os from c...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/__init__.py
Create documentation strings for testing functions
from memori.llm._base import BaseLlmAdaptor from memori.llm._registry import Registry from memori.llm._utils import agno_is_openai, llm_is_openai @Registry.register_adapter(llm_is_openai) @Registry.register_adapter(agno_is_openai) class Adapter(BaseLlmAdaptor): def get_formatted_query(self, payload): tr...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from memori.llm._...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/llm/adapters/openai/_adapter.py
Add return value explanations in docstrings
import copy import inspect import json import logging from collections.abc import Mapping from typing import Any, cast from google.protobuf import json_format from memori._config import Config from memori._logging import truncate from memori._utils import format_date_created, merge_chunk from memori.llm._utils impor...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" import copy impo...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/llm/_base.py
Add docstrings following best practices
import logging import time from sqlalchemy.exc import OperationalError from memori._config import Config logger = logging.getLogger(__name__) MAX_RETRIES = 3 RETRY_BACKOFF_BASE = 0.1 class Writer: def __init__(self, config: Config): self.config = config def execute(self, payload: dict, max_retri...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" import logging imp...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/memory/_writer.py
Add docstrings that explain inputs and outputs
import copy import logging logger = logging.getLogger(__name__) # Global setting for truncation (controlled by Config.debug_truncate) _truncate_enabled = True def set_truncate_enabled(enabled: bool) -> None: global _truncate_enabled _truncate_enabled = enabled logger.debug("Debug truncation %s", "enabl...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" import copy import...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/_logging.py
Improve my code by adding docstrings
import json from collections.abc import Iterator from typing import Any, TypedDict class ConversationMessage(TypedDict): role: str type: str | None text: str def _stringify_content(content: Any) -> str: if isinstance(content, dict | list): return json.dumps(content) return str(content) ...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" import json from...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/memory/_conversation_messages.py
Add docstrings to improve collaboration
from __future__ import annotations import logging from typing import Any import numpy as np from memori.embeddings._chunking import chunk_text_by_tokens from memori.embeddings._tei import TEI logger = logging.getLogger(__name__) def embed_texts_via_tei( *, text: str, model: str, tei: TEI, tok...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from __future__ i...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/embeddings/_tei_embed.py
Add return value explanations in docstrings
from memori.llm._base import BaseLlmAdaptor from memori.llm._registry import Registry from memori.llm._utils import llm_is_bedrock @Registry.register_adapter(llm_is_bedrock) class Adapter(BaseLlmAdaptor): def get_formatted_query(self, payload): try: messages = payload["conversation"]["query"...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from memori.llm._...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/llm/adapters/bedrock/_adapter.py
Add docstrings for better understanding
from __future__ import annotations import json from typing import Any import numpy as np def parse_embedding(raw: Any) -> np.ndarray: if isinstance(raw, bytes | memoryview): return np.frombuffer(raw, dtype="<f4") if isinstance(raw, str): return np.array(json.loads(raw), dtype=np.float32) ...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from __future__ i...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/search/_parsing.py
Generate docstrings for each module
import logging import queue as queue_module import threading import time from collections.abc import Callable from memori.storage._connection import connection_context logger = logging.getLogger(__name__) class WriteTask: def __init__( self, *, conn_factory: Callable, method_pat...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" import logging i...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/memory/augmentation/_db_writer.py
Add docstrings to incomplete code
from __future__ import annotations import logging import math import os import re from collections import Counter from memori.search._types import FactId logger = logging.getLogger(__name__) _TOKEN_RE = re.compile(r"[a-z0-9]+") _STOPWORDS = { "a", "an", "and", "are", "as", "at", "be", ...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from __future__ i...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/search/_lexical.py
Document helper functions with docstrings
from __future__ import annotations import logging from typing import Any import faiss import numpy as np from memori.search._parsing import parse_embedding from memori.search._types import FactId logger = logging.getLogger(__name__) def _query_dim(query_embedding: list[float]) -> int: return len(query_embedd...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from __future__ i...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/search/_faiss.py
Turn comments into proper docstrings
from __future__ import annotations import datetime import json import os import sqlite3 from dataclasses import dataclass from pathlib import Path from uuid import uuid4 from benchmarks.locomo._types import LoCoMoSample from benchmarks.locomo.loader import load_locomo_json from benchmarks.locomo.provenance import ( ...
--- +++ @@ -701,6 +701,9 @@ def _speaker_to_role(sample) -> dict[str, str]: + """ + Heuristic mapping: first unique speaker => user, second => assistant, others => assistant. + """ out: dict[str, str] = {} ordered: list[str] = [] for session in sample.sessions: @@ -774,6 +777,11 @@ entit...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/benchmarks/locomo/_run_impl.py
Generate descriptive docstrings automatically
from datetime import datetime, timezone from uuid import uuid4 from memori.storage._base import ( BaseConversation, BaseConversationMessage, BaseConversationMessages, BaseEntity, BaseEntityFact, BaseKnowledgeGraph, BaseProcess, BaseProcessAttribute, BaseSchema, BaseSchemaVersio...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from datetime imp...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/storage/drivers/mongodb/_driver.py
Create documentation for each function signature
from uuid import uuid4 from memori.storage._base import ( BaseConversation, BaseConversationMessage, BaseConversationMessages, BaseEntity, BaseEntityFact, BaseKnowledgeGraph, BaseProcess, BaseProcessAttribute, BaseSchema, BaseSchemaVersion, BaseSession, BaseStorageAdapt...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from uuid import ...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/storage/drivers/postgresql/_driver.py
Document my Python code with docstrings
from uuid import uuid4 from memori.storage._base import ( BaseConversation, BaseConversationMessage, BaseConversationMessages, BaseEntity, BaseEntityFact, BaseKnowledgeGraph, BaseProcess, BaseProcessAttribute, BaseSchema, BaseSchemaVersion, BaseSession, BaseStorageAdapt...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from uuid import ...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/storage/drivers/oracle/_driver.py
Generate docstrings for this script
from uuid import uuid4 from memori._utils import generate_uniq from memori.storage._base import ( BaseConversation, BaseConversationMessage, BaseConversationMessages, BaseEntity, BaseEntityFact, BaseKnowledgeGraph, BaseProcess, BaseProcessAttribute, BaseSchema, BaseSchemaVersio...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from uuid import ...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/storage/drivers/mysql/_driver.py
Add docstrings to clarify complex logic
from uuid import uuid4 from memori._utils import generate_uniq from memori.storage._registry import Registry from memori.storage.drivers.mysql._driver import Driver as MysqlDriver from memori.storage.drivers.mysql._driver import EntityFact as MysqlEntityFact from memori.storage.migrations._oceanbase import migrations...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from uuid import ...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/storage/drivers/oceanbase/_driver.py
Create documentation strings for testing functions
from uuid import uuid4 from memori.storage._base import ( BaseConversation, BaseConversationMessage, BaseConversationMessages, BaseEntity, BaseEntityFact, BaseKnowledgeGraph, BaseProcess, BaseProcessAttribute, BaseSchema, BaseSchemaVersion, BaseSession, BaseStorageAdapt...
--- +++ @@ -1,3 +1,12 @@+r""" + __ __ _ +| \/ | ___ _ __ ___ ___ _ __(_) +| |\/| |/ _ \ '_ ` _ \ / _ \| '__| | +| | | | __/ | | | | | (_) | | | | +|_| |_|\___|_| |_| |_|\___/|_| |_| + perfectam memoriam + memorilabs.ai +""" from uuid import ...
https://raw.githubusercontent.com/MemoriLabs/Memori/HEAD/memori/storage/drivers/sqlite/_driver.py
Add docstrings including usage examples
# Windows implementation of PyAutoGUI functions. # BSD license # Al Sweigart al@inventwithpython.com import ctypes import ctypes.wintypes import pyautogui from pyautogui import LEFT, MIDDLE, RIGHT import sys if sys.platform != 'win32': raise Exception('The pyautogui_win module should only be loaded on a Windows ...
--- +++ @@ -248,6 +248,19 @@ def _keyDown(key): + """Performs a keyboard key press without the release. This will put that + key in a held down state. + + NOTE: For some reason, this does not seem to cause key repeats like would + happen if a keyboard key was held down on a text field. + + Args: + ...
https://raw.githubusercontent.com/asweigart/pyautogui/HEAD/pyautogui/_pyautogui_win.py
Add structured docstrings to improve clarity
# PyAutoGUI lets Python control the mouse and keyboard, and other GUI automation tasks. For Windows, macOS, and Linux, # on Python 3 and 2. # https://github.com/asweigart/pyautogui # Al Sweigart al@inventwithpython.com (Send me feedback & suggestions!) # TODO - the following features are half-implemented right now: #...
--- +++ @@ -27,16 +27,32 @@ class PyAutoGUIException(Exception): + """ + PyAutoGUI code will raise this exception class for any invalid actions. If PyAutoGUI raises some other exception, + you should assume that this is caused by a bug in PyAutoGUI itself. (Including a failure to catch potential + excep...
https://raw.githubusercontent.com/asweigart/pyautogui/HEAD/pyautogui/__init__.py
Improve my code by adding docstrings
# NOTE - It is a known issue that the keyboard-related functions don't work on Ubuntu VMs in Virtualbox. import pyautogui import sys import os import subprocess from pyautogui import LEFT, MIDDLE, RIGHT from Xlib.display import Display from Xlib import X from Xlib.ext.xtest import fake_input import Xlib.XK BUTTON_NA...
--- +++ @@ -24,6 +24,12 @@ """ def _position(): + """Returns the current xy coordinates of the mouse cursor as a two-integer + tuple. + + Returns: + (x, y) tuple of the current xy coordinates of the mouse cursor. + """ coord = _display.screen().root.query_pointer()._data return coord["root...
https://raw.githubusercontent.com/asweigart/pyautogui/HEAD/pyautogui/_pyautogui_x11.py
Expand my code with proper documentation strings
### This file contains impls for MM-DiT, the core model component of SD3 ## source https://github.com/Stability-AI/sd3.5 ## attention, Mlp : other_impls.py ## all else : mmditx.py ## minor modifications to MMDiTX.__init__() and MMDiTX.forward() import math from typing import Dict, List, Optional import numpy as np ...
--- +++ @@ -1,894 +1,971 @@-### This file contains impls for MM-DiT, the core model component of SD3 - -## source https://github.com/Stability-AI/sd3.5 -## attention, Mlp : other_impls.py -## all else : mmditx.py - -## minor modifications to MMDiTX.__init__() and MMDiTX.forward() - -import math -from typing import Dict...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/backend/nn/mmditx.py
Document functions with clear intent
import torch import torch.nn as nn from collections import OrderedDict def conv_nd(dims, *args, **kwargs): if dims == 1: return nn.Conv1d(*args, **kwargs) elif dims == 2: return nn.Conv2d(*args, **kwargs) elif dims == 3: return nn.Conv3d(*args, **kwargs) raise ValueError(f"uns...
--- +++ @@ -5,6 +5,9 @@ def conv_nd(dims, *args, **kwargs): + """ + Create a 1D, 2D, or 3D convolution module. + """ if dims == 1: return nn.Conv1d(*args, **kwargs) elif dims == 2: @@ -15,6 +18,9 @@ def avg_pool_nd(dims, *args, **kwargs): + """ + Create a 1D, 2D, or 3D average ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/backend/nn/cnets/t2i_adapter.py
Add docstrings including usage examples
import numpy as np import torch import torch.nn as nn import functools import os import cv2 from einops import rearrange from modules import devices from annotator.annotator_path import models_path class UnetGenerator(nn.Module): def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm...
--- +++ @@ -11,8 +11,20 @@ class UnetGenerator(nn.Module): + """Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): + """Construct a Unet generator + Parameters: + input_nc (int) -- the number ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_legacy_preprocessors/annotator/lineart_anime/__init__.py
Write docstrings for utility functions
# Openpose # Original from CMU https://github.com/CMU-Perceptual-Computing-Lab/openpose # 2nd Edited by https://github.com/Hzzone/pytorch-openpose # 3rd Edited by ControlNet # 4th Edited by ControlNet (added face and correct hands) # 5th Edited by ControlNet (Improved JSON serialization/deserialization, and lots of bug...
--- +++ @@ -45,6 +45,20 @@ def draw_poses( poses: List[HumanPoseResult], H, W, draw_body=True, draw_hand=True, draw_face=True ): + """ + Draw the detected poses on an empty canvas. + + Args: + poses (List[HumanPoseResult]): A list of HumanPoseResult objects containing the detected poses. + ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_legacy_preprocessors/annotator/openpose/__init__.py
Add docstrings that explain purpose and usage
import math import cv2 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from modules import devices nets = { 'baseline': { 'layer0': 'cv', 'layer1': 'cv', 'layer2': 'cv', 'layer3': 'cv', 'layer4': 'cv', 'layer5': 'cv', ...
--- +++ @@ -1,3 +1,7 @@+""" +Author: Zhuo Su, Wenzhe Liu +Date: Feb 18, 2021 +""" import math @@ -348,6 +352,9 @@ return self.pdc(input, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups) class CSAM(nn.Module): + """ + Compact Spatial Attention Module + """ def ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_legacy_preprocessors/annotator/pidinet/model.py
Document this code for team use
import os import glob import torch import utils import cv2 import argparse import time import numpy as np from imutils.video import VideoStream from midas.model_loader import default_models, load_model first_execution = True def process(device, model, model_type, image, input_size, target_size, optimize, use_camera)...
--- +++ @@ -1,3 +1,5 @@+"""Compute depth maps for images in the input folder. +""" import os import glob import torch @@ -13,6 +15,22 @@ first_execution = True def process(device, model, model_type, image, input_size, target_size, optimize, use_camera): + """ + Run the inference and interpolate. + + Args...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_legacy_preprocessors/annotator/zoe/zoedepth/models/base_models/midas_repo/run.py
Help me document legacy Python code
import os import cv2 import numpy as np import torch import math import functools from dataclasses import dataclass from transformers.models.clip.modeling_clip import CLIPVisionModelOutput from annotator.util import HWC3 from typing import Callable, Tuple, Union from modules import devices import contextlib Extra ...
--- +++ @@ -19,6 +19,7 @@ def torch_handler(module: str, name: str): + """ Allow all torch access. Bypass A1111 safety whitelist. """ if module == 'torch': return getattr(torch, name) if module == 'torch._tensor': @@ -292,6 +293,12 @@ res: int = 512, **kwargs # Ignore...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_legacy_preprocessors/legacy_preprocessors/preprocessor.py
Add docstrings to meet PEP guidelines
import torch import torch.nn as nn import torch.nn.functional as F from .constants import weights as constant_weights class CrossEntropy2d(nn.Module): def __init__(self, reduction="mean", ignore_label=255, weights=None, *args, **kwargs): super(CrossEntropy2d, self).__init__() self.reduction = red...
--- +++ @@ -7,6 +7,10 @@ class CrossEntropy2d(nn.Module): def __init__(self, reduction="mean", ignore_label=255, weights=None, *args, **kwargs): + """ + weight (Tensor, optional): a manual rescaling weight given to each class. + If given, has to be a Tensor of size "nclasses" + ""...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_preprocessor_inpaint/annotator/lama/saicinpainting/training/losses/segmentation.py
Can you add docstrings to this Python file?
import launch import pkg_resources import sys import os import shutil import platform from pathlib import Path from typing import Tuple, Optional repo_root = Path(__file__).parent main_req_file = repo_root / "requirements.txt" def comparable_version(version: str) -> Tuple: return tuple(map(int, version.split("....
--- +++ @@ -83,6 +83,9 @@ def try_install_insight_face(): + """Attempt to install insightface library. The library is necessary to use ip-adapter faceid. + Note: Building insightface library from source requires compiling C++ code, which should be avoided + in principle. Here the solution is to download a ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_legacy_preprocessors/install.py
Auto-generate documentation strings for this file
# Test align depth images # Author: Bingxin Ke # Last modified: 2023-12-11 import numpy as np import torch from scipy.optimize import minimize def inter_distances(tensors): distances = [] for i, j in torch.combinations(torch.arange(tensors.shape[0])): arr1 = tensors[i:i+1] arr2 = tensors[j:j+...
--- +++ @@ -8,6 +8,9 @@ from scipy.optimize import minimize def inter_distances(tensors): + """ + To calculate the distance between each two depth maps. + """ distances = [] for i, j in torch.combinations(torch.arange(tensors.shape[0])): arr1 = tensors[i:i+1] @@ -18,6 +21,10 @@ def en...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_preprocessor_marigold/marigold/util/ensemble.py
Create simple docstrings for beginners
# A reimplemented version in public environments by Xiao Fu and Mu Hu import numpy as np import cv2 def kitti_colormap(disparity, maxval=-1): if maxval < 0: maxval = np.max(disparity) colormap = np.asarray([[0,0,0,114],[0,0,1,185],[1,0,0,114],[1,0,1,174],[0,1,0,114],[0,1,1,185],[1,1,0,114],[1,1,1,0]]) weights =...
--- +++ @@ -4,6 +4,14 @@ import cv2 def kitti_colormap(disparity, maxval=-1): + """ + A utility function to reproduce KITTI fake colormap + Arguments: + - disparity: numpy float32 array of dimension HxW + - maxval: maximum disparity value for normalization (if equal to -1, the maximum value in disparity will be ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_geowizard/geo_utils/colormap.py
Generate docstrings for script automation
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
--- +++ @@ -33,11 +33,45 @@ @dataclass class Transformer2DModelOutput(BaseOutput): + """ + The output of [`Transformer2DModel`]. + + Args: + sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DM...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_geowizard/geo_models/transformer_2d.py
Generate docstrings for this script
# A reimplemented version in public environments by Xiao Fu and Mu Hu from typing import Any, Dict, Union import torch from torch.utils.data import DataLoader, TensorDataset import numpy as np from tqdm.auto import tqdm from PIL import Image from diffusers import ( DiffusionPipeline, DDIMScheduler, Autoen...
--- +++ @@ -27,6 +27,21 @@ import cv2 class DepthNormalPipelineOutput(BaseOutput): + """ + Output class for Marigold monocular depth prediction pipeline. + + Args: + depth_np (`np.ndarray`): + Predicted depth map, with depth values in the range of [0, 1]. + depth_colored (`PIL.Image...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_geowizard/geo_models/geowizard_pipeline.py
Please document this code using docstrings
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
--- +++ @@ -469,6 +469,20 @@ class AutoencoderTinyBlock(nn.Module): + """ + Tiny Autoencoder block used in [`AutoencoderTiny`]. It is a mini residual module consisting of plain conv + ReLU + blocks. + + Args: + in_channels (`int`): The number of input channels. + out_channels (`int`): The ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_geowizard/geo_models/unet_2d_blocks.py
Add docstrings that explain inputs and outputs
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
--- +++ @@ -53,6 +53,15 @@ @maybe_allow_in_graph class GatedSelfAttentionDense(nn.Module): + r""" + A gated self-attention dense layer that combines visual features and object features. + + Parameters: + query_dim (`int`): The number of channels in the query. + context_dim (`int`): The number ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_idm_vton/src/attentionhacked_garmnet.py
Add docstrings for internal functions
# A reimplemented version in public environments by Xiao Fu and Mu Hu import numpy as np import torch from scipy.optimize import minimize def inter_distances(tensors: torch.Tensor): distances = [] for i, j in torch.combinations(torch.arange(tensors.shape[0])): arr1 = tensors[i : i + 1] arr2 =...
--- +++ @@ -6,6 +6,9 @@ from scipy.optimize import minimize def inter_distances(tensors: torch.Tensor): + """ + To calculate the distance between each two depth maps. + """ distances = [] for i, j in torch.combinations(torch.arange(tensors.shape[0])): arr1 = tensors[i : i + 1] @@ -21,6 +2...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_geowizard/geo_utils/depth_ensemble.py
Add docstrings that explain purpose and usage
# A reimplemented version in public environments by Xiao Fu and Mu Hu import torch import numpy as np import torch.nn as nn def init_image_coor(height, width): x_row = np.arange(0, width) x = np.tile(x_row, (height, 1)) x = x[np.newaxis, :, :] x = x.astype(np.float32) x = torch.from_numpy(x.copy(...
--- +++ @@ -94,6 +94,14 @@ return n_img_norm def get_surface_normalv2(xyz, patch_size=3): + """ + xyz: xyz coordinates + patch: [p1, p2, p3, + p4, p5, p6, + p7, p8, p9] + surface_normal = [(p9-p1) x (p3-p7)] + [(p6-p4) - (p8-p2)] + return: normal [h, w, 3, b] + """ b,...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_geowizard/geo_utils/surface_normal.py
Turn comments into proper docstrings
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
--- +++ @@ -61,11 +61,110 @@ @dataclass class UNet2DConditionOutput(BaseOutput): + """ + The output of [`UNet2DConditionModel`]. + + Args: + sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): + The hidden states output conditioned on `encoder_hidden_states` ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_geowizard/geo_models/unet_2d_condition.py
Document this module using docstrings
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
--- +++ @@ -100,6 +100,10 @@ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0): + """ + Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedule...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_idm_vton/src/tryon_pipeline.py
Add docstrings to make code maintainable
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
--- +++ @@ -466,6 +466,20 @@ class AutoencoderTinyBlock(nn.Module): + """ + Tiny Autoencoder block used in [`AutoencoderTiny`]. It is a mini residual module consisting of plain conv + ReLU + blocks. + + Args: + in_channels (`int`): The number of input channels. + out_channels (`int`): The ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_idm_vton/src/unet_block_hacked_garmnet.py
Add docstrings that explain logic
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
--- +++ @@ -66,11 +66,110 @@ @dataclass class UNet2DConditionOutput(BaseOutput): + """ + The output of [`UNet2DConditionModel`]. + + Args: + sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): + The hidden states output conditioned on `encoder_hidden_states` ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_idm_vton/src/unet_hacked_garmnet.py
Write docstrings for utility functions
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
--- +++ @@ -190,11 +190,110 @@ @dataclass class UNet2DConditionOutput(BaseOutput): + """ + The output of [`UNet2DConditionModel`]. + + Args: + sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): + The hidden states output conditioned on `encoder_hidden_states...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_idm_vton/src/unet_hacked_tryon.py
Add docstrings for production code
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
--- +++ @@ -53,6 +53,15 @@ @maybe_allow_in_graph class GatedSelfAttentionDense(nn.Module): + r""" + A gated self-attention dense layer that combines visual features and object features. + + Parameters: + query_dim (`int`): The number of channels in the query. + context_dim (`int`): The number ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_idm_vton/src/attentionhacked_tryon.py
Improve documentation using docstrings
import json import gradio as gr import functools from copy import copy from typing import List, Optional, Union, Callable, Dict, Tuple, Literal from dataclasses import dataclass import numpy as np from lib_controlnet.utils import svg_preprocess, read_image, judge_image_type from lib_controlnet import ( global_stat...
--- +++ @@ -26,6 +26,7 @@ @dataclass class A1111Context: + """Contains all components from A1111.""" img2img_batch_input_dir = None img2img_batch_output_dir = None @@ -230,6 +231,17 @@ ControlNetUiGroup.all_ui_groups.append(self) def render(self, tabname: str, elem_id_tabname: str) -> N...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/sd_forge_controlnet/lib_controlnet/controlnet_ui/controlnet_ui_group.py
Document classes and their methods
from typing import Optional from modules import processing from lib_controlnet import external_code from modules_forge.utils import HWC3 from PIL import Image, ImageFilter, ImageOps from lib_controlnet.lvminthin import lvmin_thin, nake_nms import torch import os import functools import time import base64 import num...
--- +++ @@ -38,8 +38,20 @@ def ndarray_lru_cache(max_size: int = 128, typed: bool = False): + """ + Decorator to enable caching for functions with numpy array arguments. + Numpy arrays are mutable, and thus not directly usable as hash keys. + + The idea here is to wrap the incoming arguments with type `...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/sd_forge_controlnet/lib_controlnet/utils.py
Add docstrings that explain inputs and outputs
import base64 import gradio as gr import json from typing import List, Dict, Any, Tuple from annotator.openpose import decode_json_as_poses, draw_poses from annotator.openpose.animalpose import draw_animalposes from lib_controlnet.controlnet_ui.modal import ModalInterface from modules import shared from lib_controlnet...
--- +++ @@ -40,6 +40,7 @@ self.modal = None def render_edit(self): + """Renders the buttons in preview image control button group.""" # The hidden button to trigger a re-render of generated image. self.render_button = gr.Button(visible=False, elem_classes=["cnet-render-pose"]) ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/sd_forge_controlnet/lib_controlnet/controlnet_ui/openpose_editor.py
Add docstrings including usage examples
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import random # Set manual seeds for noise # rand(n)_like. but with generator support def gen_like(f, input, generator=None): return f(input.size(), generator=generator).to(input) ''' The following snippet is utilized from h...
--- +++ @@ -285,6 +285,15 @@ from math import pi def get_positions(block_shape: Tuple[int, int]) -> Tensor: + """ + Generate position tensor. + + Arguments: + block_shape -- (height, width) of position tensor + + Returns: + position vector shaped (1, height, width, 1, 1, 2) + """ bh...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/sd_forge_latent_modifier/lib_latent_modifier/sampler_mega_modifier.py
Document helper functions with docstrings
# Tiled Diffusion # 1st edit by https://github.com/pkuliyi2015/multidiffusion-upscaler-for-automatic1111 # 2nd edit by https://github.com/shiimizu/ComfyUI-TiledDiffusion # 3rd edit by Forge Official from __future__ import division import torch from torch import Tensor from backend import memory_management from backen...
--- +++ @@ -75,6 +75,7 @@ class BBox: + ''' grid bbox ''' def __init__(self, x: int, y: int, w: int, h: int): self.x = x @@ -109,6 +110,7 @@ class CustomBBox(BBox): + ''' region control bbox ''' pass @@ -184,6 +186,7 @@ self.tile_batch_size = tile_batch_size def rep...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/sd_forge_multidiffusion/lib_multidiffusion/tiled_diffusion.py
Add minimal docstrings for each function
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 from concurrent.futures import ThreadPoolExecutor from scipy.ndimage import convolve from joblib import Parallel, delayed, cpu_count class SoftI...
--- +++ @@ -51,6 +51,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...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/soft-inpainting/scripts/soft_inpainting.py
Document all public functions with docstrings
from contextlib import contextmanager import hashlib import math from pathlib import Path import shutil import threading import time import urllib import warnings from PIL import Image import safetensors import torch from torch import nn, optim from torch.utils import data from torchvision.transforms import functional...
--- +++ @@ -17,6 +17,7 @@ def from_pil_image(x): + """Converts from a PIL image to a tensor.""" x = TF.to_tensor(x) if x.ndim == 2: x = x[..., None] @@ -24,6 +25,7 @@ def to_pil_image(x): + """Converts from a tensor to a PIL image.""" if x.ndim == 4: assert x.shape[0] == 1...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/k_diffusion/utils.py
Document helper functions with docstrings
import math import torch from torch import nn from . import sampling, utils class VDenoiser(nn.Module): def __init__(self, inner_model): super().__init__() self.inner_model = inner_model self.sigma_data = 1. def get_scalings(self, sigma): c_skip = self.sigma_data ** 2 / (si...
--- +++ @@ -7,6 +7,7 @@ class VDenoiser(nn.Module): + """A v-diffusion-pytorch model wrapper for k-diffusion.""" def __init__(self, inner_model): super().__init__() @@ -73,6 +74,8 @@ class DiscreteSchedule(nn.Module): + """A mapping between continuous noise levels (sigmas) and a list of di...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/k_diffusion/external.py
Add docstrings to clarify complex logic
import inspect from pydantic import BaseModel, Field, create_model, ConfigDict 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_ALL...
--- +++ @@ -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: + ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/api/models.py
Write docstrings for backend logic
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...
--- +++ @@ -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 @@ -362,6 +363,12 @@ return script_args def apply_infotext(self, request, tabname, *, script_runner=None, mentioned_script_args=No...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/api/api.py
Write beginner-friendly docstrings
import math from scipy import integrate import torch from torch import nn from torchdiffeq import odeint import torchsde from tqdm.auto import trange, tqdm from k_diffusion import deis from backend.modules.k_prediction import PredictionFlux from . import utils def append_zero(x): return torch.cat([x, x.new_zero...
--- +++ @@ -17,6 +17,7 @@ def get_sigmas_karras(n, sigma_min, sigma_max, rho=7., device='cpu'): + """Constructs the noise schedule of Karras et al. (2022).""" ramp = torch.linspace(0, 1, n) min_inv_rho = sigma_min ** (1 / rho) max_inv_rho = sigma_max ** (1 / rho) @@ -25,27 +26,33 @@ def get_si...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/k_diffusion/sampling.py
Document all public functions with docstrings
from __future__ import annotations import configparser import dataclasses import os import threading import re import json 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 fro...
--- +++ @@ -1,313 +1,318 @@-from __future__ import annotations - -import configparser -import dataclasses -import os -import threading -import re -import json - -from modules import shared, errors, cache, scripts -from modules.gitpython_hack import Repo -from modules.paths_internal import extensions_dir, extensions_bui...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/extensions.py
Add detailed docstrings explaining each function
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 from modules_forge.utils import prepare_free_memory if TYPE_CHECKING: ...
--- +++ @@ -19,6 +19,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") @@ -27,6 +28,9 @@ ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/face_restoration_utils.py
Write docstrings for algorithm functions
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...
--- +++ @@ -1,831 +1,898 @@-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, PngImage...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/images.py
Create Google-style docstrings for my code
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
--- +++ @@ -30,11 +30,45 @@ @dataclass class Transformer2DModelOutput(BaseOutput): + """ + The output of [`Transformer2DModel`]. + + Args: + sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DM...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_idm_vton/src/transformerhacked_tryon.py
Document functions with detailed explanations
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
--- +++ @@ -30,11 +30,45 @@ @dataclass class Transformer2DModelOutput(BaseOutput): + """ + The output of [`Transformer2DModel`]. + + Args: + sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DM...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_idm_vton/src/transformerhacked_garmnet.py
Document all public functions with docstrings
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
--- +++ @@ -59,6 +59,15 @@ @maybe_allow_in_graph class GatedSelfAttentionDense(nn.Module): + r""" + A gated self-attention dense layer that combines visual features and object features. + + Parameters: + query_dim (`int`): The number of channels in the query. + context_dim (`int`): The number ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_geowizard/geo_models/attention.py
Write docstrings including parameters and return values
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 from modules_forge ...
--- +++ @@ -1,607 +1,643 @@-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 -fro...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/infotext_utils.py
Create docstrings for reusable components
# this scripts installs necessary requirements and launches main program in webui.py import logging import re import subprocess import os import shutil import sys import importlib.util import importlib.metadata import platform import json import shlex from functools import lru_cache from typing import NamedTuple from p...
--- +++ @@ -1,563 +1,568 @@-# this scripts installs necessary requirements and launches main program in webui.py -import logging -import re -import subprocess -import os -import shutil -import sys -import importlib.util -import importlib.metadata -import platform -import json -import shlex -from functools import lru_ca...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/launch_utils.py
Provide docstrings following PEP 257
import json import os import signal import sys import re import starlette 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...
--- +++ @@ -1,200 +1,218 @@-import json -import os -import signal -import sys -import re - -import starlette - -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: - ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/initialize_util.py
Provide docstrings following PEP 257
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
--- +++ @@ -466,6 +466,20 @@ class AutoencoderTinyBlock(nn.Module): + """ + Tiny Autoencoder block used in [`AutoencoderTiny`]. It is a mini residual module consisting of plain conv + ReLU + blocks. + + Args: + in_channels (`int`): The number of input channels. + out_channels (`int`): The ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/forge_space_idm_vton/src/unet_block_hacked_tryon.py
Add docstrings for internal functions
# this code is adapted from the script contributed by anon from /h/ import pickle import collections import torch import numpy import _codecs import zipfile import re # PyTorch 1.13 and later have _TypedStorage renamed to TypedStorage from modules import errors TypedStorage = torch.storage.TypedStorage if hasattr(...
--- +++ @@ -1,158 +1,196 @@-# this code is adapted from the script contributed by anon from /h/ - -import pickle -import collections - -import torch -import numpy -import _codecs -import zipfile -import re - - -# PyTorch 1.13 and later have _TypedStorage renamed to TypedStorage -from modules import errors - -TypedStora...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/safe.py
Create docstrings for API functions
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 from modules.util import load_file_from_url # n...
--- +++ @@ -19,6 +19,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...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/modelloader.py
Write docstrings for utility functions
from __future__ import annotations import json import logging import math import os import sys import hashlib from dataclasses import dataclass, field import torch import numpy as np from PIL import Image, ImageOps import random import cv2 from skimage import exposure from typing import Any import modules.sd_hijack f...
--- +++ @@ -1,1822 +1,1883 @@-from __future__ import annotations -import json -import logging -import math -import os -import sys -import hashlib -from dataclasses import dataclass, field - -import torch -import numpy as np -from PIL import Image, ImageOps -import random -import cv2 -from skimage import exposure -from ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/processing.py
Document this code for team use
from __future__ import annotations import re from collections import namedtuple import lark # a prompt like this: "fantasy landscape with a [mountain:lake:0.25] and [an oak:a christmas tree:0.75][ in foreground::0.6][: in background:0.25] [shoddy:masterful:0.5]" # will be represented with prompt_schedule like this (a...
--- +++ @@ -1,384 +1,480 @@-from __future__ import annotations - -import re -from collections import namedtuple -import lark - -# a prompt like this: "fantasy landscape with a [mountain:lake:0.25] and [an oak:a christmas tree:0.75][ in foreground::0.6][: in background:0.25] [shoddy:masterful:0.5]" -# will be represente...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/prompt_parser.py
Write docstrings describing each step
from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union, Dict, TypedDict import numpy as np from modules import shared from lib_controlnet.logging import logger from lib_controlnet.enums import InputMode, HiResFixOption from modules.api import api def get_api_version() -> int:...
--- +++ @@ -13,6 +13,9 @@ class ControlMode(Enum): + """ + The improved guess mode. + """ BALANCED = "Balanced" PROMPT = "My prompt is more important" @@ -25,6 +28,9 @@ class ResizeMode(Enum): + """ + Resize modes for ControlNet input images. + """ RESIZE = "Just Resize" ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/sd_forge_controlnet/lib_controlnet/external_code.py
Add docstrings explaining edge cases
from typing import List, Tuple, Union import gradio as gr from modules.processing import StableDiffusionProcessing from lib_controlnet import external_code from lib_controlnet.logging import logger def field_to_displaytext(fieldname: str) -> str: return " ".join([word.capitalize() for word in fieldname.split("...
--- +++ @@ -63,6 +63,14 @@ return f"ControlNet {unit_index}" def register_unit(self, unit_index: int, uigroup) -> None: + """Register the unit's UI group. By regsitering the unit, A1111 will be + able to paste values from infotext to IOComponents. + + Args: + unit_index: T...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/extensions-builtin/sd_forge_controlnet/lib_controlnet/infotext.py
Insert docstrings into my code
import os import re import sys import inspect from collections import namedtuple from dataclasses import dataclass import gradio as gr from modules import shared, paths, script_callbacks, extensions, script_loading, scripts_postprocessing, errors, timer, util topological_sort = util.topological_sort AlwaysVisible =...
--- +++ @@ -1,908 +1,1068 @@-import os -import re -import sys -import inspect -from collections import namedtuple -from dataclasses import dataclass - -import gradio as gr - -from modules import shared, paths, script_callbacks, extensions, script_loading, scripts_postprocessing, errors, timer, util - -topological_sort ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/scripts.py
Insert docstrings into my code
from pathlib import Path from modules import errors import csv import os import typing import shutil import modules.processing_scripts.comments as comments class PromptStyle(typing.NamedTuple): name: str prompt: str | None negative_prompt: str | None path: str | None = None def apply_styles_to_promp...
--- +++ @@ -1,219 +1,235 @@-from pathlib import Path -from modules import errors -import csv -import os -import typing -import shutil -import modules.processing_scripts.comments as comments - - -class PromptStyle(typing.NamedTuple): - name: str - prompt: str | None - negative_prompt: str | None - path: str ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/styles.py
Document this code for team use
import collections import importlib import os import sys import math import threading import enum import torch import re import safetensors.torch from omegaconf import OmegaConf, ListConfig from urllib import request import gc import contextlib from modules import paths, shared, modelloader, devices, script_callbacks...
--- +++ @@ -1,518 +1,526 @@-import collections -import importlib -import os -import sys -import math -import threading -import enum - -import torch -import re -import safetensors.torch -from omegaconf import OmegaConf, ListConfig -from urllib import request -import gc -import contextlib - -from modules import paths, sh...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/sd_models.py
Generate docstrings for exported functions
import datetime import logging import threading import time import traceback import torch from contextlib import nullcontext from modules import errors, shared, devices from backend.args import args from typing import Optional log = logging.getLogger(__name__) class State: skipped = False interrupted = Fals...
--- +++ @@ -1,182 +1,189 @@-import datetime -import logging -import threading -import time -import traceback -import torch -from contextlib import nullcontext - -from modules import errors, shared, devices -from backend.args import args -from typing import Optional - -log = logging.getLogger(__name__) - - -class State:...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/shared_state.py
Add docstrings to existing functions
import torch from modules import devices, rng_philox, shared def get_noise_source_type(): if shared.opts.forge_try_reproduce in ['ComfyUI', 'DrawThings']: return "CPU" return shared.opts.randn_source def randn(seed, shape, generator=None): if generator is not None: # Forge Note: ...
--- +++ @@ -1,171 +1,184 @@-import torch - -from modules import devices, rng_philox, shared - - -def get_noise_source_type(): - if shared.opts.forge_try_reproduce in ['ComfyUI', 'DrawThings']: - return "CPU" - - return shared.opts.randn_source - - -def randn(seed, shape, generator=None): - - if generato...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/rng.py
Fill in missing docstrings in my code
import torch from modules import prompt_parser, sd_samplers_common from modules.shared import opts, state import modules.shared as shared from modules.script_callbacks import CFGDenoiserParams, cfg_denoiser_callback from modules.script_callbacks import CFGDenoisedParams, cfg_denoised_callback from modules.script_callb...
--- +++ @@ -1,200 +1,228 @@-import torch -from modules import prompt_parser, sd_samplers_common - -from modules.shared import opts, state -import modules.shared as shared -from modules.script_callbacks import CFGDenoiserParams, cfg_denoiser_callback -from modules.script_callbacks import CFGDenoisedParams, cfg_denoised_...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/sd_samplers_cfg_denoiser.py
Write Python docstrings for this snippet
import json import os import gradio as gr from modules import errors from modules.ui_components import ToolButton, InputAccordion def radio_choices(comp): # gradio 3.41 changes choices from list of values to list of pairs return [x[0] if isinstance(x, tuple) else x for x in getattr(comp, 'choices', [])] clas...
--- +++ @@ -1,230 +1,241 @@-import json -import os - -import gradio as gr - -from modules import errors -from modules.ui_components import ToolButton, InputAccordion - - -def radio_choices(comp): # gradio 3.41 changes choices from list of values to list of pairs - return [x[0] if isinstance(x, tuple) else x for x i...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/ui_loadsave.py
Generate consistent docstrings
import inspect from collections import namedtuple import numpy as np import torch from PIL import Image from modules import devices, images, sd_vae_approx, sd_samplers, sd_vae_taesd, shared, sd_models from modules.shared import opts, state from backend.sampling.sampling_function import sampling_prepare, sampling_cleanu...
--- +++ @@ -1,354 +1,364 @@-import inspect -from collections import namedtuple -import numpy as np -import torch -from PIL import Image -from modules import devices, images, sd_vae_approx, sd_samplers, sd_vae_taesd, shared, sd_models -from modules.shared import opts, state -from backend.sampling.sampling_function impor...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/sd_samplers_common.py
Improve my code by adding docstrings
import os import torch import torch.nn as nn from modules import devices, paths_internal, shared sd_vae_taesd_models = {} def conv(n_in, n_out, **kwargs): return nn.Conv2d(n_in, n_out, 3, padding=1, **kwargs) class Clamp(nn.Module): @staticmethod def forward(x): return torch.tanh(x / 3) * 3 ...
--- +++ @@ -1,3 +1,9 @@+""" +Tiny AutoEncoder for Stable Diffusion +(DNN for encoding / decoding SD's latent space) + +https://github.com/madebyollin/taesd +""" import os import torch import torch.nn as nn @@ -53,6 +59,7 @@ latent_shift = 0.5 def __init__(self, decoder_path="taesd_decoder.pth", latent_cha...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/sd_vae_taesd.py
Expand my code with proper documentation strings
import functools import os.path import urllib.parse from base64 import b64decode from io import BytesIO from pathlib import Path from typing import Optional, Union from dataclasses import dataclass from modules import shared, ui_extra_networks_user_metadata, errors, extra_networks, util from modules.images import read...
--- +++ @@ -1,738 +1,855 @@-import functools -import os.path -import urllib.parse -from base64 import b64decode -from io import BytesIO -from pathlib import Path -from typing import Optional, Union -from dataclasses import dataclass - -from modules import shared, ui_extra_networks_user_metadata, errors, extra_networks,...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/ui_extra_networks.py
Create docstrings for reusable components
import dataclasses import torch import k_diffusion import numpy as np from scipy import stats from modules import shared def to_d(x, sigma, denoised): return (x - denoised) / sigma k_diffusion.sampling.to_d = to_d @dataclasses.dataclass class Scheduler: name: str label: str function: any def...
--- +++ @@ -8,6 +8,7 @@ def to_d(x, sigma, denoised): + """Converts a denoiser output to a Karras ODE derivative.""" return (x - denoised) / sigma @@ -43,6 +44,9 @@ def get_align_your_steps_sigmas(n, sigma_min, sigma_max, device): # https://research.nvidia.com/labs/toronto-ai/AlignYourSteps/howto.h...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/sd_schedulers.py
Add docstrings for internal functions
from functools import wraps import gradio as gr from modules import gradio_extensions # noqa: F401 class FormComponent: webui_do_not_create_gradio_pyi_thank_you = True def get_expected_parent(self): return gr.components.Form gr.Dropdown.get_expected_parent = FormComponent.get_expected_parent cl...
--- +++ @@ -1,145 +1,170 @@-from functools import wraps - -import gradio as gr -from modules import gradio_extensions # noqa: F401 - - -class FormComponent: - webui_do_not_create_gradio_pyi_thank_you = True - - def get_expected_parent(self): - return gr.components.Form - - -gr.Dropdown.get_expected_parent...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/ui_components.py