instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Turn comments into proper docstrings |
from typing import Any, Dict, List, Optional
import pandas as pd
from ..capabilities.agent_memory import (
AgentMemory,
TextMemory,
TextMemorySearchResult,
ToolMemory,
ToolMemorySearchResult,
)
from ..capabilities.sql_runner import SqlRunner, RunSqlToolArgs
from ..core.registry import ToolRegistr... | --- +++ @@ -1,3 +1,10 @@+"""
+Legacy VannaBase adapter for the Vanna Agents framework.
+
+This module provides a LegacyVannaAdapter that bridges legacy VannaBase objects
+with the new ToolRegistry system by auto-registering legacy methods as tools
+with appropriate group-based access control.
+"""
from typing import... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/legacy/adapter.py |
Document all public functions with docstrings |
import json
import uuid
from datetime import datetime
from typing import Any, Dict, List, Optional
import asyncio
from concurrent.futures import ThreadPoolExecutor
try:
import weaviate
from weaviate.classes.config import (
Configure,
Property,
DataType as WeaviateDataType,
)
W... | --- +++ @@ -1,3 +1,8 @@+"""
+Weaviate vector database implementation of AgentMemory.
+
+This implementation uses Weaviate for semantic search and storage of tool usage patterns.
+"""
import json
import uuid
@@ -29,6 +34,7 @@
class WeaviateAgentMemory(AgentMemory):
+ """Weaviate-based implementation of AgentM... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/integrations/weaviate/agent_memory.py |
Can you add docstrings to this Python file? |
import json
import os
import re
import sqlite3
import traceback
from abc import ABC, abstractmethod
from typing import List, Tuple, Union
from urllib.parse import urlparse
import pandas as pd
import plotly
import plotly.express as px
import plotly.graph_objects as go
import requests
import sqlparse
from ..exceptions... | --- +++ @@ -1,3 +1,52 @@+r"""
+
+# Nomenclature
+
+| Prefix | Definition | Examples |
+| --- | --- | --- |
+| `vn.get_` | Fetch some data | [`vn.get_related_ddl(...)`][vanna.base.base.VannaBase.get_related_ddl] |
+| `vn.add_` | Adds something to the retrieval layer | [`vn.add_question_sql(...)`][vanna.base.base.VannaBa... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/legacy/base/base.py |
Write beginner-friendly docstrings | import json
from typing import List
import chromadb
import pandas as pd
from chromadb.config import Settings
from chromadb.utils import embedding_functions
from ..base import VannaBase
from ..utils import deterministic_uuid
default_ef = embedding_functions.DefaultEmbeddingFunction()
class ChromaDB_VectorStore(Vann... | --- +++ @@ -178,6 +178,15 @@ return False
def remove_collection(self, collection_name: str) -> bool:
+ """
+ This function can reset the collection to empty state.
+
+ Args:
+ collection_name (str): sql or ddl or documentation
+
+ Returns:
+ bool: Tru... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/legacy/chromadb/chromadb_vector.py |
Add concise docstrings to each method | class ImproperlyConfigured(Exception):
pass
class DependencyError(Exception):
pass
class ConnectionError(Exception):
pass
class OTPCodeError(Exception):
pass
class SQLRemoveError(Exception):
pass
class ExecutionError(Exception):
pass
class ValidationError(Exception):
pass
... | --- +++ @@ -1,38 +1,46 @@ class ImproperlyConfigured(Exception):
+ """Raise for incorrect configuration."""
pass
class DependencyError(Exception):
+ """Raise for missing dependencies."""
pass
class ConnectionError(Exception):
+ """Raise for connection"""
pass
class OTPCodeEr... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/legacy/exceptions/__init__.py |
Add docstrings to clarify complex logic | import json
import logging
import os
import sys
import uuid
from abc import ABC, abstractmethod
from functools import wraps
import importlib.metadata
import flask
import requests
from flasgger import Swagger
from flask import Flask, Response, jsonify, request, send_from_directory
from flask_sock import Sock
from ..ba... | --- +++ @@ -19,25 +19,43 @@
class Cache(ABC):
+ """
+ Define the interface for a cache that can be used to store data in a Flask app.
+ """
@abstractmethod
def generate_id(self, *args, **kwargs):
+ """
+ Generate a unique ID for the cache.
+ """
pass
@abstra... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/legacy/flask/__init__.py |
Add clean documentation to messy code |
from typing import Optional, Type
from pydantic import BaseModel
from ..nodes import FetchNode, SearchLinkNode, SearchLinksWithContext
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
class SearchLinkGraph(AbstractGraph):
def __init__(
self, source: str, config: dict, schema... | --- +++ @@ -1,3 +1,6 @@+"""
+SearchLinkGraph Module
+"""
from typing import Optional, Type
@@ -9,6 +12,29 @@
class SearchLinkGraph(AbstractGraph):
+ """
+ SearchLinkGraph is a scraping pipeline that automates the process of
+ extracting information from web pages using a natural language model
+ to... | https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/search_link_graph.py |
Help me comply with documentation standards |
import logging
from typing import Optional, Type
from pydantic import BaseModel
from ..nodes import (
ConditionalNode,
FetchNode,
GenerateAnswerNode,
ParseNode,
ReasoningNode,
)
from ..prompts import REGEN_ADDITIONAL_INFO
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph... | --- +++ @@ -1,3 +1,6 @@+"""
+SmartScraperGraph Module
+"""
import logging
from typing import Optional, Type
@@ -20,6 +23,37 @@
class SmartScraperGraph(AbstractGraph):
+ """
+ SmartScraper is a scraping pipeline that automates the process of
+ extracting information from web pages
+ using a natural l... | https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/smart_scraper_graph.py |
Generate docstrings for this script |
from typing import Optional, Type
from pydantic import BaseModel
from ..nodes import FetchNode, GenerateScraperNode, ParseNode
from .abstract_graph import AbstractGraph
from .base_graph import BaseGraph
class ScriptCreatorGraph(AbstractGraph):
def __init__(
self,
prompt: str,
source: s... | --- +++ @@ -1,3 +1,6 @@+"""
+ScriptCreatorGraph Module
+"""
from typing import Optional, Type
@@ -9,6 +12,36 @@
class ScriptCreatorGraph(AbstractGraph):
+ """
+ ScriptCreatorGraph defines a scraping pipeline for generating web scraping scripts.
+
+ Attributes:
+ prompt (str): The prompt for the... | https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/graphs/script_creator_graph.py |
Include argument descriptions in docstrings |
from typing import List, Optional
from playwright.sync_api import sync_playwright
from .base_node import BaseNode
class FetchScreenNode(BaseNode):
def __init__(
self,
input: str,
output: List[str],
node_config: Optional[dict] = None,
node_name: str = "FetchScreen",
... | --- +++ @@ -1,3 +1,6 @@+"""
+fetch_screen_node module
+"""
from typing import List, Optional
@@ -7,6 +10,9 @@
class FetchScreenNode(BaseNode):
+ """
+ FetchScreenNode captures screenshots from a given URL and stores the image data as bytes.
+ """
def __init__(
self,
@@ -19,6 +25,9 @@ ... | https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/fetch_screen_node.py |
Create docstrings for API functions |
from typing import List, Optional
from urllib.parse import urljoin
from bs4 import BeautifulSoup
from langchain_core.documents import Document
from ..docloaders import ChromiumLoader
from .base_node import BaseNode
class FetchNodeLevelK(BaseNode):
def __init__(
self,
input: str,
output... | --- +++ @@ -1,3 +1,6 @@+"""
+fetch_node_level_k module
+"""
from typing import List, Optional
from urllib.parse import urljoin
@@ -10,6 +13,29 @@
class FetchNodeLevelK(BaseNode):
+ """
+ A node responsible for fetching the HTML content of a specified URL and all its sub-links
+ recursively up to a cert... | https://raw.githubusercontent.com/ScrapeGraphAI/Scrapegraph-ai/HEAD/scrapegraphai/nodes/fetch_node_level_k.py |
Add clean documentation to messy code |
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING
import pandas as pd
from .models import RunSqlToolArgs
if TYPE_CHECKING:
from vanna.core.tool import ToolContext
class SqlRunner(ABC):
@abstractmethod
async def run_sql(
self, args: RunSqlToolArgs, context: "ToolContext"
... | --- +++ @@ -1,3 +1,8 @@+"""
+SQL runner capability interface.
+
+This module contains the abstract base class for SQL execution.
+"""
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING
@@ -11,9 +16,22 @@
class SqlRunner(ABC):
+ """Interface for SQL execution with different implementations."... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/capabilities/sql_runner/base.py |
Add minimal docstrings for each function | from functools import cached_property
from typing import List, Tuple
import pandas as pd
from qdrant_client import QdrantClient, grpc, models
from ..base import VannaBase
from ..utils import deterministic_uuid
SCROLL_SIZE = 1000
class Qdrant_VectorStore(VannaBase):
def __init__(
self,
config={... | --- +++ @@ -11,6 +11,32 @@
class Qdrant_VectorStore(VannaBase):
+ """
+ Vectorstore implementation using Qdrant - https://qdrant.tech/
+
+ Args:
+ - config (dict, optional): Dictionary of `Qdrant_VectorStore config` options. Defaults to `{}`.
+ - client: A `qdrant_client.QdrantClient` ins... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/legacy/qdrant/qdrant.py |
Expand my code with proper documentation strings | import dataclasses
import json
from io import StringIO
import pandas as pd
import requests
from ..advanced import VannaAdvanced
from ..base import VannaBase
from ..types import (
DataFrameJSON,
NewOrganization,
OrganizationList,
Question,
QuestionSQLPair,
Status,
StatusWithId,
StringDa... | --- +++ @@ -200,6 +200,21 @@ )
def update_function(self, old_function_name: str, updated_function: dict) -> bool:
+ """
+ Update an existing SQL function based on the provided parameters.
+
+ Args:
+ old_function_name (str): The current name of the function to be updat... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/legacy/vannadb/vannadb_vector.py |
Write docstrings for utility functions | from __future__ import annotations
from dataclasses import dataclass
from typing import Dict, List, Union
@dataclass
class Status:
success: bool
message: str
@dataclass
class StatusWithId:
success: bool
message: str
id: str
@dataclass
class QuestionList:
questions: List[FullQuestionDocume... | --- +++ @@ -232,6 +232,17 @@
class TrainingPlan:
+ """
+ A class representing a training plan. You can see what's in it, and remove items from it that you don't want trained.
+
+ **Example:**
+ ```python
+ plan = vn.get_training_plan()
+
+ plan.get_summary()
+ ```
+
+ """
_plan: List[... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/legacy/types/__init__.py |
Add docstrings to make code maintainable |
import uuid
from typing import AsyncGenerator, List
from ...core import Agent
from .models import ChatRequest, ChatResponse, ChatStreamChunk
class ChatHandler:
def __init__(
self,
agent: Agent,
):
self.agent = agent
async def handle_stream(
self, request: ChatRequest
... | --- +++ @@ -1,3 +1,6 @@+"""
+Framework-agnostic chat handling logic.
+"""
import uuid
from typing import AsyncGenerator, List
@@ -7,16 +10,30 @@
class ChatHandler:
+ """Core chat handling logic - framework agnostic."""
def __init__(
self,
agent: Agent,
):
+ """Initialize ... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/servers/base/chat_handler.py |
Generate docstrings for exported functions |
import time
import uuid
from typing import Any, Dict, List, Optional, Union
from pydantic import BaseModel, Field
from ...components import UiComponent, RichComponent
from ...core.component_manager import ComponentUpdate
from ...core.user.request_context import RequestContext
class ChatRequest(BaseModel):
mes... | --- +++ @@ -1,3 +1,6 @@+"""
+Request and response models for server endpoints.
+"""
import time
import uuid
@@ -11,6 +14,7 @@
class ChatRequest(BaseModel):
+ """Request model for chat endpoints."""
message: str = Field(description="User message")
conversation_id: Optional[str] = Field(default=Non... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/servers/base/models.py |
Create structured documentation for my script |
from typing import Optional
def get_vanna_component_script(
dev_mode: bool = False,
static_path: str = "/static",
cdn_url: str = "https://img.vanna.ai/vanna-components.js",
) -> str:
if dev_mode:
return (
f'<script type="module" src="{static_path}/vanna-components.js"></script>'
... | --- +++ @@ -1,3 +1,6 @@+"""
+HTML templates for Vanna Agents servers.
+"""
from typing import Optional
@@ -7,6 +10,16 @@ static_path: str = "/static",
cdn_url: str = "https://img.vanna.ai/vanna-components.js",
) -> str:
+ """Get the script tag for loading Vanna web components.
+
+ Args:
+ de... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/servers/base/templates.py |
Add docstrings to improve collaboration |
from typing import Any, Dict, Optional
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from ...core import Agent
from ..base import ChatHandler
from .routes import register_chat_routes
class VannaFastAPIServer:
def __init__(self, agent... | --- +++ @@ -1,3 +1,6 @@+"""
+FastAPI server factory for Vanna Agents.
+"""
from typing import Any, Dict, Optional
@@ -11,13 +14,25 @@
class VannaFastAPIServer:
+ """FastAPI server factory for Vanna Agents."""
def __init__(self, agent: Agent, config: Optional[Dict[str, Any]] = None):
+ """Initi... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/servers/fastapi/app.py |
Generate docstrings for script automation |
import asyncio
from typing import Any, Dict, Optional
from flask import Flask
from flask_cors import CORS
from ...core import Agent
from ..base import ChatHandler
from .routes import register_chat_routes
class VannaFlaskServer:
def __init__(self, agent: Agent, config: Optional[Dict[str, Any]] = None):
... | --- +++ @@ -1,3 +1,6 @@+"""
+Flask server factory for Vanna Agents.
+"""
import asyncio
from typing import Any, Dict, Optional
@@ -11,13 +14,25 @@
class VannaFlaskServer:
+ """Flask server factory for Vanna Agents."""
def __init__(self, agent: Agent, config: Optional[Dict[str, Any]] = None):
+ ... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/servers/flask/app.py |
Please document this code using docstrings |
import logging
from typing import Any, Dict, List, Optional, Type
from pydantic import BaseModel, Field
logger = logging.getLogger(__name__)
from vanna.core.tool import Tool, ToolContext, ToolResult
from vanna.core.agent.config import UiFeature
from vanna.capabilities.agent_memory import AgentMemory
from vanna.compo... | --- +++ @@ -1,3 +1,10 @@+"""
+Agent memory tools.
+
+This module provides agent memory operations through an abstract AgentMemory interface,
+allowing for different implementations (local vector DB, remote cloud service, etc.).
+The tools access AgentMemory via ToolContext, which is populated by the Agent.
+"""
impo... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/tools/agent_memory.py |
Write docstrings for algorithm functions |
import json
import traceback
from typing import Any, AsyncGenerator, Dict, Optional
from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import StreamingResponse, HTMLResponse
from ..base import ChatHandler, ChatRequest, ChatResponse
from ..base.templates import ... | --- +++ @@ -1,3 +1,6 @@+"""
+FastAPI route implementations for Vanna Agents.
+"""
import json
import traceback
@@ -14,10 +17,18 @@ def register_chat_routes(
app: FastAPI, chat_handler: ChatHandler, config: Optional[Dict[str, Any]] = None
) -> None:
+ """Register chat routes on FastAPI app.
+
+ Args:
+ ... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/servers/fastapi/routes.py |
Write docstrings for utility functions |
from typing import Any, Dict, List, Optional, Type, cast
import uuid
from vanna.core.tool import Tool, ToolContext, ToolResult
from vanna.components import (
UiComponent,
DataFrameComponent,
NotificationComponent,
ComponentType,
SimpleTextComponent,
)
from vanna.capabilities.sql_runner import SqlRu... | --- +++ @@ -1,3 +1,4 @@+"""Generic SQL query execution tool with dependency injection."""
from typing import Any, Dict, List, Optional, Type, cast
import uuid
@@ -15,6 +16,7 @@
class RunSqlTool(Tool[RunSqlToolArgs]):
+ """Tool that executes SQL queries using an injected SqlRunner implementation."""
de... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/tools/run_sql.py |
Help me document legacy Python code |
import asyncio
import json
import traceback
from typing import Any, AsyncGenerator, Dict, Generator, Optional, Union
from flask import Flask, Response, jsonify, request
from ..base import ChatHandler, ChatRequest
from ..base.templates import get_index_html
from ...core.user.request_context import RequestContext
de... | --- +++ @@ -1,3 +1,6 @@+"""
+Flask route implementations for Vanna Agents.
+"""
import asyncio
import json
@@ -14,10 +17,18 @@ def register_chat_routes(
app: Flask, chat_handler: ChatHandler, config: Optional[Dict[str, Any]] = None
) -> None:
+ """Register chat routes on Flask app.
+
+ Args:
+ ap... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/servers/flask/routes.py |
Auto-generate documentation strings for this file |
import os
from pathlib import Path
from typing import Dict
def get_component_files() -> Dict[str, Path]:
component_dir = Path(__file__).parent
return {
"js": component_dir / "index.js",
"css": component_dir / "style.css",
}
def get_component_html() -> str:
files = get_component_file... | --- +++ @@ -1,3 +1,9 @@+"""
+Web components for Vanna Agents.
+
+This module provides web components built with Lit that can be embedded
+in web applications to provide rich UI for Vanna agent interactions.
+"""
import os
from pathlib import Path
@@ -5,6 +11,7 @@
def get_component_files() -> Dict[str, Path]:
+ ... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/web_components/__init__.py |
Write beginner-friendly docstrings |
import asyncio
from abc import ABC, abstractmethod
from dataclasses import dataclass
from pathlib import Path
from typing import Any, List, Optional, Type
import difflib
import hashlib
from pydantic import BaseModel, Field, model_validator
from vanna.core.tool import Tool, ToolContext, ToolResult
from vanna.componen... | --- +++ @@ -1,3 +1,10 @@+"""
+File system tools with dependency injection support.
+
+This module provides file system operations through an abstract FileSystem interface,
+allowing for different implementations (local, remote, sandboxed, etc.).
+The tools accept a FileSystem instance via dependency injection.
+"""
... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/tools/file_system.py |
Add docstrings explaining edge cases | import argparse
import os
import pprint
from typing import Dict, Tuple, List
import re
import sys
import json
def extract_dataset_desc_links(desc:List[str]) -> List:
out = []
md = "".join(desc)
md_links = re.findall("\\[.*\\]\\(.*\\)", md)
for md_link in md_links:
title, link = extract_titl... | --- +++ @@ -8,6 +8,12 @@
def extract_dataset_desc_links(desc:List[str]) -> List:
+ """
+ Extract all the links from the description of datasets
+
+ :param desc: Lines of the description of the dataset
+ :return:
+ """
out = []
md = "".join(desc)
@@ -25,6 +31,12 @@
def sanitize_subdata... | https://raw.githubusercontent.com/sebastianruder/NLP-progress/HEAD/structured/export.py |
Create docstrings for all classes and functions |
from typing import Optional, Type
import logging
import pandas as pd
from pydantic import BaseModel, Field
from vanna.core.tool import Tool, ToolContext, ToolResult
from vanna.components import (
UiComponent,
ChartComponent,
NotificationComponent,
ComponentType,
SimpleTextComponent,
)
from .file_... | --- +++ @@ -1,3 +1,4 @@+"""Tool for visualizing DataFrame data from CSV files."""
from typing import Optional, Type
import logging
@@ -20,6 +21,7 @@
class VisualizeDataArgs(BaseModel):
+ """Arguments for visualize_data tool."""
filename: str = Field(description="Name of the CSV file to visualize")
... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/tools/visualize_data.py |
Fully document this Python code with docstrings | from typing import Iterable, Dict
import gzip
import json
import os
ROOT = os.path.dirname(os.path.abspath(__file__))
HUMAN_EVAL = os.path.join(ROOT, "..", "data", "HumanEval.jsonl.gz")
def read_problems(evalset_file: str = HUMAN_EVAL) -> Dict[str, Dict]:
return {task["task_id"]: task for task in stream_jsonl(e... | --- +++ @@ -13,6 +13,9 @@
def stream_jsonl(filename: str) -> Iterable[Dict]:
+ """
+ Parses each jsonl line and yields it as a dictionary
+ """
if filename.endswith(".gz"):
with open(filename, "rb") as gzfp:
with gzip.open(gzfp, 'rt') as fp:
@@ -27,6 +30,9 @@
def write_jsonl(... | https://raw.githubusercontent.com/deepseek-ai/DeepSeek-Coder/HEAD/Evaluation/HumanEval/human_eval/data.py |
Document functions with clear intent | import os
import sys
import fire
import json
import gzip
import regex
import numpy as np
import itertools
from typing import *
from tqdm.auto import tqdm
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from .data import stream_jsonl
from .execution import check_corre... | --- +++ @@ -73,6 +73,9 @@ dataset_type: str = "humaneval",
num_shot=None,
) -> Dict:
+ """
+ Reads a dataset and returns a dictionary of tasks.
+ """
if num_shot is not None:
print(f"{num_shot}-shot setting...")
if "humaneval" in dataset_type.lower():
@@ -90,8 +93,14 @@ num... | https://raw.githubusercontent.com/deepseek-ai/DeepSeek-Coder/HEAD/Evaluation/HumanEval/human_eval/evaluation.py |
Add docstrings that explain inputs and outputs | import contextlib
import faulthandler
import io
import multiprocessing
import os
import platform
import signal
import random
import subprocess
import tempfile
import gzip
import json
from typing import *
import traceback
java_exec = ""
node_exec = ""
tsc_exec = ""
go_exec = ""
php_exec = ""
cs_exec = ""
def check_cor... | --- +++ @@ -28,6 +28,10 @@ tmp_dir: str = None,
completion_id: Optional[int] = None,
) -> Dict:
+ """
+ Evaluates the functional correctness of a completion by running the test
+ suite provided in the problem.
+ """
def unsafe_execute(tmp_dir):
random_id = random.randint(1,... | https://raw.githubusercontent.com/deepseek-ai/DeepSeek-Coder/HEAD/Evaluation/HumanEval/human_eval/execution.py |
Add docstrings including usage examples | import os
import numpy as np
import json
class HumanEvalDataset:
def __init__(self, root, sample_num=1, language="python", issft=False):
self.root = root
self.data = open(os.path.join(self.root, f"humaneval-{language}.jsonl")).readlines()
tmp = self.get_qa_only_data(self.data, issft)
... | --- +++ @@ -5,6 +5,12 @@ class HumanEvalDataset:
def __init__(self, root, sample_num=1, language="python", issft=False):
+ """
+ root: the path to the HumanEval dataset
+ sample_num: the number of samples for each prompt
+ language: the language of the HumanEval dataset
+ issft... | https://raw.githubusercontent.com/deepseek-ai/DeepSeek-Coder/HEAD/Evaluation/HumanEval/utils/dataset.py |
Document helper functions with docstrings |
from __future__ import annotations
import shlex
import sys
from typing import Any, List, Optional, Sequence, Type
from pydantic import BaseModel, Field
from vanna.components import (
UiComponent,
CardComponent,
ComponentType,
NotificationComponent,
SimpleTextComponent,
)
from vanna.core.tool imp... | --- +++ @@ -1,3 +1,4 @@+"""Python-specific tooling built on top of the file system service."""
from __future__ import annotations
@@ -22,6 +23,7 @@
class RunPythonFileArgs(BaseModel):
+ """Arguments required to execute a Python file."""
filename: str = Field(
description="Python file to exec... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/tools/python.py |
Generate docstrings for script automation | from typing import Iterable, Dict
import gzip
import json
import os
ROOT = os.path.dirname(os.path.abspath(__file__))
HUMAN_EVAL = os.path.join(ROOT, "..", "data", "HumanEval.jsonl.gz")
def read_problems(evalset_file: str = HUMAN_EVAL) -> Dict[str, Dict]:
return {task["task_id"]: task for task in stream_jsonl(e... | --- +++ @@ -13,6 +13,9 @@
def stream_jsonl(filename: str) -> Iterable[Dict]:
+ """
+ Parses each jsonl line and yields it as a dictionary
+ """
if filename.endswith(".gz"):
with open(filename, "rb") as gzfp:
with gzip.open(gzfp, 'rt') as fp:
@@ -27,6 +30,9 @@
def write_jsonl(... | https://raw.githubusercontent.com/deepseek-ai/DeepSeek-Coder/HEAD/Evaluation/LeetCode/human_eval/data.py |
Create Google-style docstrings for my code |
from typing import Dict, Any, List, cast
import json
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import plotly.io as pio
class PlotlyChartGenerator:
# Vanna brand colors from landing page
THEME_COLORS = {
"navy": "#023d60",
"cream": "#e7e1cf",
"t... | --- +++ @@ -1,3 +1,4 @@+"""Plotly-based chart generator with automatic chart type selection."""
from typing import Dict, Any, List, cast
import json
@@ -8,6 +9,7 @@
class PlotlyChartGenerator:
+ """Generate Plotly charts using heuristics based on DataFrame characteristics."""
# Vanna brand colors from... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/integrations/plotly/chart_generator.py |
Add docstrings to existing functions | import os
import json
import gzip
import numpy as np
import itertools
from typing import *
from tqdm.auto import tqdm
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from human_eval.data import stream_jsonl
from human_eval.execution import check_correctness
IMPORT_H... | --- +++ @@ -87,8 +87,14 @@ num_correct: Union[List[int], np.ndarray],
k: int
) -> np.ndarray:
+ """
+ Estimates pass@k of each problem and returns them in an array.
+ """
def estimator(n: int, c: int, k: int) -> float:
+ """
+ Calculates 1 - comb(n - c, k) / comb(n, k).
+... | https://raw.githubusercontent.com/deepseek-ai/DeepSeek-Coder/HEAD/Evaluation/LeetCode/human_eval/evaluation.py |
Document this code for team use |
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from pydantic import BaseModel, Field
# Import AgentMemory at runtime for Pydantic model resolution
from vanna.capabilities.agent_memory import AgentMemory
if TYPE_CHECKING:
from ..components import UiComponent
from ..user.models import User
fr... | --- +++ @@ -1,3 +1,8 @@+"""
+Tool domain models.
+
+This module contains data models for tool execution.
+"""
from typing import TYPE_CHECKING, Any, Dict, List, Optional
@@ -13,6 +18,7 @@
class ToolCall(BaseModel):
+ """Represents a tool call from the LLM."""
id: str = Field(description="Unique ident... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/core/tool/models.py |
Generate docstrings for exported functions | import os
import re
import json
import argparse
import torch
import numpy as np
from utils.parser import *
from utils.grader import *
from utils.python_executor import PythonExecutor
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
def extract_python_block_with_solution(text):
patter... | --- +++ @@ -11,6 +11,11 @@
def extract_python_block_with_solution(text):
+ """
+ Extract the code block from the text that contains the solution function.
+ :param text: The text to search for the code block.
+ :return: The extracted code block.
+ """
pattern = r'```python\n(.*?)def solution\(\)... | https://raw.githubusercontent.com/deepseek-ai/DeepSeek-Coder/HEAD/Evaluation/PAL-Math/run.py |
Write docstrings for utility functions |
import sqlite3
import pandas as pd
from vanna.capabilities.sql_runner import SqlRunner, RunSqlToolArgs
from vanna.core.tool import ToolContext
class SqliteRunner(SqlRunner):
def __init__(self, database_path: str):
self.database_path = database_path
async def run_sql(self, args: RunSqlToolArgs, con... | --- +++ @@ -1,3 +1,4 @@+"""SQLite implementation of SqlRunner interface."""
import sqlite3
import pandas as pd
@@ -7,11 +8,29 @@
class SqliteRunner(SqlRunner):
+ """SQLite implementation of the SqlRunner interface."""
def __init__(self, database_path: str):
+ """Initialize with a SQLite databas... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/integrations/sqlite/sql_runner.py |
Write documentation strings for class attributes | import multiprocessing
from math import isclose
from typing import Union
from sympy import simplify, N
from sympy.parsing.sympy_parser import parse_expr
from sympy.parsing.latex import parse_latex
def is_digit(s):
try:
float(str(s).replace(",", ""))
return True
except ValueError:
retu... | --- +++ @@ -1,3 +1,8 @@+"""
+This logic is largely copied from the Hendrycks' MATH release (math_equivalence), and borrowed from:
+- https://github.com/microsoft/ProphetNet/tree/master/CRITIC
+- https://github.com/openai/prm800k
+"""
import multiprocessing
from math import isclose
from typing import Union
@@ -20,6 +... | https://raw.githubusercontent.com/deepseek-ai/DeepSeek-Coder/HEAD/Evaluation/PAL-Math/utils/grader.py |
Write proper docstrings for these functions |
import json
from datetime import datetime
from typing import Any, Dict, List, Optional
import httpx
from vanna.capabilities.agent_memory import (
AgentMemory,
TextMemory,
TextMemorySearchResult,
ToolMemory,
ToolMemorySearchResult,
)
from vanna.core.tool import ToolContext
class CloudAgentMemory(... | --- +++ @@ -1,3 +1,9 @@+"""
+Cloud-based implementation of AgentMemory.
+
+This implementation uses Vanna's premium cloud service for storing and searching
+tool usage patterns with advanced similarity search and analytics.
+"""
import json
from datetime import datetime
@@ -15,6 +21,7 @@
class CloudAgentMemory(... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/integrations/premium/agent_memory/premium.py |
Generate docstrings for each module | import os
import json
import gzip
import numpy as np
import itertools
from typing import *
from tqdm.auto import tqdm
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from .data import stream_jsonl
from .execution import check_correctness
IMPORT_HELPER = {
"python... | --- +++ @@ -70,6 +70,9 @@ dataset_type: str = "humaneval",
num_shot=None,
) -> Dict:
+ """
+ Reads a dataset and returns a dictionary of tasks.
+ """
if num_shot is not None:
print(f"{num_shot}-shot setting...")
if "humaneval" in dataset_type.lower():
@@ -87,8 +90,14 @@ num... | https://raw.githubusercontent.com/deepseek-ai/DeepSeek-Coder/HEAD/Evaluation/MBPP/human_eval/evaluation.py |
Insert docstrings into my code |
import importlib
import json
from typing import Dict, Optional, Any, cast, TextIO, Union
import click
from ...core import Agent
class ExampleAgentLoader:
@staticmethod
def list_available_examples() -> Dict[str, str]:
return {
"mock_quickstart": "Basic agent with mock LLM service",
... | --- +++ @@ -1,3 +1,6 @@+"""
+CLI for running Vanna Agents servers with example agents.
+"""
import importlib
import json
@@ -9,9 +12,11 @@
class ExampleAgentLoader:
+ """Loads example agents for the CLI."""
@staticmethod
def list_available_examples() -> Dict[str, str]:
+ """Return availabl... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/servers/cli/server_runner.py |
Add docstrings following best practices | import json
import uuid
from typing import List, Optional, Tuple
import oracledb
import pandas as pd
from chromadb.utils import embedding_functions
from ..base import VannaBase
default_ef = embedding_functions.DefaultEmbeddingFunction()
class Oracle_VectorStore(VannaBase):
def __init__(self, config=None):
... | --- +++ @@ -367,6 +367,15 @@
@staticmethod
def _extract_documents(query_results) -> list:
+ """
+ Static method to extract the documents from the results of a query.
+
+ Args:
+ query_results (pd.DataFrame): The dataframe to use.
+
+ Returns:
+ List[str] or N... | https://raw.githubusercontent.com/vanna-ai/vanna/HEAD/src/vanna/legacy/oracle/oracle_vector.py |
Fully document this Python code with docstrings | import copy
import random
from dataclasses import dataclass, field
from typing import Optional, Dict, Sequence
import torch
import torch.distributed
import transformers
from transformers import Trainer
from datasets import load_dataset
IGNORE_INDEX = -100
EOT_TOKEN = "<|EOT|>"
def build_instruction_prompt(instructi... | --- +++ @@ -40,6 +40,7 @@ )
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str):
+ """Collects the state dict and dump to disk."""
state_dict = trainer.model.state_dict()
if trainer.args.should_save:
cpu_state_dict = {key: value.cpu() for key, value in state_d... | https://raw.githubusercontent.com/deepseek-ai/DeepSeek-Coder/HEAD/finetune/finetune_deepseekcoder.py |
Improve documentation using docstrings | import re
from typing import Any, Dict
def _fix_fracs(string):
substrs = string.split("\\frac")
new_str = substrs[0]
if len(substrs) > 1:
substrs = substrs[1:]
for substr in substrs:
new_str += "\\frac"
if len(substr) > 0 and substr[0] == "{":
new_st... | --- +++ @@ -1,3 +1,6 @@+"""
+This file come from: https://github.com/microsoft/ToRA/blob/main/src/utils/parser.py
+"""
import re
from typing import Any, Dict
@@ -202,6 +205,9 @@
def extract_program(result: str, last_only=True):
+ """
+ extract the program after "```python", and before "```"
+ """
... | https://raw.githubusercontent.com/deepseek-ai/DeepSeek-Coder/HEAD/Evaluation/PAL-Math/utils/parser.py |
Generate docstrings for script automation | import torch
import torch.nn as nn
import numpy as np
from torch.nn.init import trunc_normal_, zeros_, ones_
from torch.nn import functional
def drop_path(x, drop_prob=0., training=False):
if drop_prob == 0. or not training:
return x
keep_prob = torch.tensor(1 - drop_prob)
shape = (x.size()[0], ) ... | --- +++ @@ -6,6 +6,10 @@
def drop_path(x, drop_prob=0., training=False):
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
+ the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
+ See discussion: https://github.c... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/anytext/ocr_recog/RecSVTR.py |
Add docstrings following best practices | import base64
import imghdr
import io
import os
import sys
from typing import List, Optional, Dict, Tuple
from urllib.parse import urlparse
import cv2
from PIL import Image, ImageOps, PngImagePlugin
import numpy as np
import torch
from iopaint.const import MPS_UNSUPPORT_MODELS
from loguru import logger
from torch.hub ... | --- +++ @@ -209,6 +209,17 @@ def pad_img_to_modulo(
img: np.ndarray, mod: int, square: bool = False, min_size: Optional[int] = None
):
+ """
+
+ Args:
+ img: [H, W, C]
+ mod:
+ square: 是否为正方形
+ min_size:
+
+ Returns:
+
+ """
if len(img.shape) == 2:
img = img[:... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/helper.py |
Write docstrings for utility functions | import abc
from typing import Optional
import cv2
import torch
import numpy as np
from loguru import logger
from iopaint.helper import (
boxes_from_mask,
resize_max_size,
pad_img_to_modulo,
switch_mps_device,
)
from iopaint.schema import InpaintRequest, HDStrategy, SDSampler
from .helper.g_diffuser_bo... | --- +++ @@ -25,6 +25,11 @@ is_erase_model = False
def __init__(self, device, **kwargs):
+ """
+
+ Args:
+ device:
+ """
device = switch_mps_device(self.name, device)
self.device = device
self.init_model(device, **kwargs)
@@ -39,6 +44,11 @@
@abc... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/base.py |
Add docstrings to clarify complex logic | import gc
import math
import random
import traceback
from typing import Any
import torch
import numpy as np
import collections
from itertools import repeat
from diffusers import (
DDIMScheduler,
PNDMScheduler,
LMSDiscreteScheduler,
EulerDiscreteScheduler,
EulerAncestralDiscreteScheduler,
DPMSo... | --- +++ @@ -116,6 +116,14 @@
def timestep_embedding(device, timesteps, dim, max_period=10000, repeat_only=False):
+ """
+ Create sinusoidal timestep embeddings.
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
+ These may be fractional.
+ :param dim: the dimensi... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/utils.py |
Add detailed documentation for each class | import torch
import torch.nn.functional as F
import math
from tqdm import tqdm
class NoiseScheduleVP:
def __init__(
self,
schedule='discrete',
betas=None,
alphas_cumprod=None,
continuous_beta_0=0.1,
continuous_beta_1=20.,
):
if s... | --- +++ @@ -13,6 +13,62 @@ continuous_beta_0=0.1,
continuous_beta_1=20.,
):
+ """Create a wrapper class for the forward SDE (VP type).
+ ***
+ Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t.
+ ... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/dpm_solver.py |
Generate helpful docstrings for debugging | import importlib
import torch
from torch import optim
import numpy as np
from inspect import isfunction
from PIL import Image, ImageDraw, ImageFont
def log_txt_as_img(wh, xc, size=10):
# wh a tuple of (width, height)
# xc a list of captions to plot
b = len(xc)
txts = list()
for bi in range(b):
... | --- +++ @@ -55,6 +55,10 @@
def mean_flat(tensor):
+ """
+ https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86
+ Take the mean over all non-batch dimensions.
+ """
return tensor.mean(dim=list(range(1, len(tensor.shape))))
@@ -88,6 +... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/anytext/ldm/util.py |
Write beginner-friendly docstrings | from inspect import isfunction
import math
import torch
import torch.nn.functional as F
from torch import nn, einsum
from einops import rearrange, repeat
from typing import Optional, Any
from iopaint.model.anytext.ldm.modules.diffusionmodules.util import checkpoint
# CrossAttn precision handling
import os
_ATTN_PRE... | --- +++ @@ -71,6 +71,9 @@
def zero_module(module):
+ """
+ Zero out the parameters of a module and return it.
+ """
for p in module.parameters():
p.detach().zero_()
return module
@@ -279,6 +282,14 @@
class SpatialTransformer(nn.Module):
+ """
+ Transformer block for image-like ... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/anytext/ldm/modules/attention.py |
Create docstrings for each class method | # https://github.com/TencentARC/BrushNet
import inspect
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
import PIL.Image
import torch
import torch.nn.functional as F
from transformers import (
CLIPImageProcessor,
CLIPTextModel,
CLIPTextModelWithProjection,
CLIPTo... | --- +++ @@ -108,6 +108,48 @@ IPAdapterMixin,
FromSingleFileMixin,
):
+ r"""
+ Pipeline for text-to-image generation using Stable Diffusion XL with BrushNet guidance.
+
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
+ implemented for all... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/brushnet/pipeline_brushnet_sd_xl.py |
Add docstrings that explain purpose and usage | import os
import time
import cv2
import torch
import torch.nn.functional as F
from iopaint.helper import get_cache_path_by_url, load_jit_model, download_model
from iopaint.schema import InpaintRequest
import numpy as np
from .base import InpaintModel
ZITS_INPAINT_MODEL_URL = os.environ.get(
"ZITS_INPAINT_MODEL_... | --- +++ @@ -144,6 +144,15 @@
def load_image(img, mask, device, sigma256=3.0):
+ """
+ Args:
+ img: [H, W, C] RGB
+ mask: [H, W] 255 为 masks 区域
+ sigma256:
+
+ Returns:
+
+ """
h, w, _ = img.shape
imgh, imgw = img.shape[0:2]
img_256 = resize(img, 256, 256)
@@ -220,6 +2... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/zits.py |
Write docstrings describing functionality | import torch
import torch.nn as nn
from torch.utils.checkpoint import checkpoint
from transformers import (
T5Tokenizer,
T5EncoderModel,
CLIPTokenizer,
CLIPTextModel,
AutoProcessor,
CLIPVisionModelWithProjection,
)
from iopaint.model.anytext.ldm.util import count_params
def _expand_mask(mask... | --- +++ @@ -15,6 +15,9 @@
def _expand_mask(mask, dtype, tgt_len=None):
+ """
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
+ """
bsz, src_len = mask.size()
tgt_len = tgt_len if tgt_len is not None else src_len
@@ -80,10 +83,13 @@
def disabled_train(... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/anytext/ldm/modules/encoders/modules.py |
Create structured documentation for my script | import os
import random
import cv2
import torch
import numpy as np
import torch.fft as fft
from iopaint.schema import InpaintRequest
from iopaint.helper import (
load_model,
get_cache_path_by_url,
norm_img,
boxes_from_mask,
resize_max_size,
download_model,
)
from .base import InpaintModel
fro... | --- +++ @@ -44,6 +44,7 @@
def _upfirdn2d_ref(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1):
+ """Slow reference implementation of `upfirdn2d()` using standard PyTorch ops."""
# Validate arguments.
assert isinstance(x, torch.Tensor) and x.ndim == 4
if f is None:
@@ -1665,6 +1666,11 @@
... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/fcf.py |
Generate missing documentation strings | import os
import cv2
import torch
from iopaint.helper import (
load_jit_model,
download_model,
get_cache_path_by_url,
boxes_from_mask,
resize_max_size,
norm_img,
)
from .base import InpaintModel
from iopaint.schema import InpaintRequest
MIGAN_MODEL_URL = os.environ.get(
"MIGAN_MODEL_URL",... | --- +++ @@ -41,6 +41,11 @@
@torch.no_grad()
def __call__(self, image, mask, config: InpaintRequest):
+ """
+ images: [H, W, C] RGB, not normalized
+ masks: [H, W]
+ return: BGR IMAGE
+ """
if image.shape[0] == 512 and image.shape[1] == 512:
return self... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/mi_gan.py |
Add well-formatted docstrings | # adopted from
# https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
# and
# https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
# and
# https://github.com/openai/gu... | --- +++ @@ -75,6 +75,16 @@
def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
+ """
+ Create a beta schedule that discretizes the given alpha_t_bar function,
+ which defines the cumulative product of (1-beta) over time from t = [0,1].
+ :param num_diffusion_timesteps: the numbe... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/anytext/ldm/modules/diffusionmodules/util.py |
Provide docstrings following PEP 257 | import os
from pathlib import Path
from iopaint.model.utils import set_seed
from safetensors.torch import load_file
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import torch
import re
import numpy as np
import cv2
import einops
from PIL import ImageFont
from iopaint.model.anytext.cldm.model import create_model, load_stat... | --- +++ @@ -1,3 +1,9 @@+"""
+AnyText: Multilingual Visual Text Generation And Editing
+Paper: https://arxiv.org/abs/2311.03054
+Code: https://github.com/tyxsspa/AnyText
+Copyright (c) Alibaba, Inc. and its affiliates.
+"""
import os
from pathlib import Path
@@ -78,6 +84,27 @@ sort_priority: str = "y",
... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/anytext/anytext_pipeline.py |
Add missing documentation to my Python functions | import copy
import random
from typing import Any, List, Union
from transformers import CLIPTokenizer
from iopaint.schema import PowerPaintTask
def add_task_to_prompt(prompt, negative_prompt, task: PowerPaintTask):
if task == PowerPaintTask.object_remove:
promptA = prompt + " P_ctxt"
promptB = pro... | --- +++ @@ -78,6 +78,11 @@ )
def try_adding_tokens(self, tokens: Union[str, List[str]], *args, **kwargs):
+ """Attempt to add tokens to the tokenizer.
+
+ Args:
+ tokens (Union[str, List[str]]): The tokens to be added.
+ """
num_added_tokens = self.wrapped... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/power_paint/powerpaint_tokenizer.py |
Add docstrings that explain inputs and outputs | from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple, Union
import torch
from torch import nn
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.utils import BaseOutput, logging
from diffusers.models.attention_processor import (
ADDED_KV_ATTEN... | --- +++ @@ -29,6 +29,23 @@
@dataclass
class BrushNetOutput(BaseOutput):
+ """
+ The output of [`BrushNetModel`].
+
+ Args:
+ up_block_res_samples (`tuple[torch.Tensor]`):
+ A tuple of upsample activations at different resolutions for each upsampling block. Each tensor should
+ b... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/brushnet/brushnet.py |
Can you add docstrings to this Python file? |
import torch
import torch.nn as nn
import numpy as np
from torch.optim.lr_scheduler import LambdaLR
from einops import rearrange, repeat
from contextlib import contextmanager, nullcontext
from functools import partial
import itertools
from tqdm import tqdm
from torchvision.utils import make_grid
from omegaconf import ... | --- +++ @@ -1,3 +1,6 @@+"""
+Part of the implementation is borrowed and modified from ControlNet, publicly available at https://github.com/lllyasviel/ControlNet/blob/main/ldm/models/diffusion/ddpm.py
+"""
import torch
import torch.nn as nn
@@ -59,6 +62,8 @@
def disabled_train(self, mode=True):
+ """Overwrite... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/anytext/ldm/models/diffusion/ddpm.py |
Add missing documentation to my Python functions | # https://github.com/TencentARC/BrushNet
import inspect
from typing import Any, Callable, Dict, List, Optional, Union
import numpy as np
import PIL.Image
import torch
import torch.nn.functional as F
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
from diffusers... | --- +++ @@ -89,6 +89,27 @@ timesteps: Optional[List[int]] = None,
**kwargs,
):
+ """
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
+
+ Args:
+ ... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/brushnet/pipeline_brushnet.py |
Write clean docstrings for readability | from abc import abstractmethod
import math
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from iopaint.model.anytext.ldm.modules.diffusionmodules.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedd... | --- +++ @@ -29,6 +29,9 @@
## go
class AttentionPool2d(nn.Module):
+ """
+ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
+ """
def __init__(
self,
@@ -56,12 +59,22 @@
class TimestepBlock(nn.Module):
+ """
+ Any module where forward() takes timestep embedd... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/anytext/ldm/modules/diffusionmodules/openaimodel.py |
Add docstrings for better understanding | from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple, Union
import torch
from diffusers import UNet2DConditionModel
from diffusers.models.unets.unet_2d_blocks import (
get_down_block,
get_mid_block,
get_up_block,
CrossAttnDownBlock2D,
DownBlock2D,
)
from torch impor... | --- +++ @@ -35,6 +35,23 @@
@dataclass
class BrushNetOutput(BaseOutput):
+ """
+ The output of [`BrushNetModel`].
+
+ Args:
+ up_block_res_samples (`tuple[torch.Tensor]`):
+ A tuple of upsample activations at different resolutions for each upsampling block. Each tensor should
+ b... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/power_paint/v2/BrushNet_CA.py |
Add structured docstrings to improve clarity | import inspect
from typing import Any, Callable, Dict, List, Optional, Union
import numpy as np
import PIL.Image
import torch
import torch.nn.functional as F
from diffusers import StableDiffusionMixin, UNet2DConditionModel
from transformers import (
CLIPImageProcessor,
CLIPTextModel,
CLIPTokenizer,
CLI... | --- +++ @@ -107,6 +107,27 @@ timesteps: Optional[List[int]] = None,
**kwargs,
):
+ """
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
+
+ Args:
+ ... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/power_paint/v2/pipeline_PowerPaint_Brushnet_CA.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... | --- +++ @@ -53,6 +53,33 @@ def prepare_mask_and_masked_image(
image, mask, height, width, return_image: bool = False
):
+ """
+ Prepares a pair (image, mask) to be consumed by the Stable Diffusion pipeline. This means that those inputs will be
+ converted to ``torch.Tensor`` with shapes ``batch x channel... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/power_paint/pipeline_powerpaint.py |
Add detailed documentation for each class | import os
import random
import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
from iopaint.helper import (
load_model,
get_cache_path_by_url,
norm_img,
download_model,
)
from iopaint.schema import InpaintRequest
fro... | --- +++ @@ -596,6 +596,13 @@
def window_partition(x, window_size):
+ """
+ Args:
+ x: (B, H, W, C)
+ window_size (int): window size
+ Returns:
+ windows: (num_windows*B, window_size, window_size, C)
+ """
B, H, W, C = x.shape
x = x.view(B, H // window_size, window_size, W ... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/model/mat.py |
Add inline docstrings for readability | import cv2
import numpy as np
import os
import torch
from torchvision.transforms.functional import normalize
from ..detection import init_detection_model
from ..parsing import init_parsing_model
from ..utils.misc import img2tensor, imwrite
def get_largest_face(det_faces, h, w):
def get_location(val, length):
... | --- +++ @@ -47,6 +47,7 @@
class FaceRestoreHelper(object):
+ """Helper for the face restoration pipeline (base class)."""
def __init__(
self,
@@ -124,6 +125,7 @@ self.upscale_factor = upscale_factor
def read_image(self, img):
+ """img can be image path or cv2 loaded image.""... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/facexlib/utils/face_restoration_helper.py |
Document all public functions with docstrings | import math
import random
import torch
from torch import nn
from torch.nn import functional as F
from .stylegan2_clean_arch import StyleGAN2GeneratorClean
class StyleGAN2GeneratorCSFT(StyleGAN2GeneratorClean):
def __init__(self, out_size, num_style_feat=512, num_mlp=8, channel_multiplier=2, narrow=1, sft_half=F... | --- +++ @@ -8,6 +8,18 @@
class StyleGAN2GeneratorCSFT(StyleGAN2GeneratorClean):
+ """StyleGAN2 Generator with SFT modulation (Spatial Feature Transform).
+
+ It is the clean version without custom compiled CUDA extensions used in StyleGAN2.
+
+ Args:
+ out_size (int): The spatial size of outputs.
+ ... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/gfpgan/archs/gfpganv1_clean_arch.py |
Create docstrings for API functions |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class VectorQuantizer(nn.Module):
def __init__(self, n_e, e_dim, beta):
super(VectorQuantizer, self).__init__()
self.n_e = n_e
self.e_dim = e_dim
self.beta = beta
self.embedding = nn.Em... | --- +++ @@ -1,3 +1,4 @@+"""Modified from https://github.com/wzhouxiff/RestoreFormer"""
import numpy as np
import torch
@@ -6,6 +7,16 @@
class VectorQuantizer(nn.Module):
+ """
+ see https://github.com/MishaLaskin/vqvae/blob/d761a999e2267766400dc646d82d3ac3657771d4/models/quantizer.py
+ ________________... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/gfpgan/archs/restoreformer_arch.py |
Write docstrings that follow conventions | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torch import Tensor, nn
import math
from typing import Tuple, Type
from .common import MLPBlock
clas... | --- +++ @@ -23,6 +23,18 @@ activation: Type[nn.Module] = nn.ReLU,
attention_downsample_rate: int = 2,
) -> None:
+ """
+ A transformer decoder that attends to an input image using
+ queries whose positional embedding is supplied.
+
+ Args:
+ depth (int): number... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything/modeling/transformer.py |
Add docstrings that explain inputs and outputs | from typing import Type, List, Union
import torch
from torch import nn as nn
from torch.nn import init as init
from torch.nn.modules.batchnorm import _BatchNorm
@torch.no_grad()
def default_init_weights(
module_list: Union[List[nn.Module], nn.Module],
scale: float = 1,
bias_fill: float = 0,
**kwargs,... | --- +++ @@ -13,6 +13,15 @@ bias_fill: float = 0,
**kwargs,
) -> None:
+ """Initialize network weights.
+
+ Args:
+ module_list (list[nn.Module] | nn.Module): Modules to be initialized.
+ scale (float): Scale initialized weights, especially for residual
+ blocks. Default: 1.
+ ... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/basicsr/arch_util.py |
Document classes and their methods | import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
from torchvision.models._utils import IntermediateLayerGetter as IntermediateLayerGetter
from .align_trans import get_reference_facial_points, warp_and_crop_face
from .retinaface_net import (
FPN,... | --- +++ @@ -294,6 +294,12 @@
# batched detection
def batched_transform(self, frames, use_origin_size):
+ """
+ Arguments:
+ frames: a list of PIL.Image, or torch.Tensor(shape=[n, h, w, c],
+ type=np.float32, BGR format).
+ use_origin_size: whether to use ori... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/facexlib/detection/retinaface.py |
Add documentation for all methods | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional, Tuple, Type
from .common... | --- +++ @@ -34,6 +34,24 @@ window_size: int = 0,
global_attn_indexes: Tuple[int, ...] = (),
) -> None:
+ """
+ Args:
+ img_size (int): Input image size.
+ patch_size (int): Patch size.
+ in_chans (int): Number of input image channels.
+ emb... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything/modeling/image_encoder_hq.py |
Add detailed documentation for each class | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
def window_partition(x, wi... | --- +++ @@ -4,6 +4,7 @@ # This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
+"""Some utilities for backbones, in particular for windowing"""
from typing import Tuple
@@ -13,6 +14,15 @@
def window_partition(x, window_size):
+ """
+ Par... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything2/modeling/backbones/utils.py |
Generate docstrings for each module | import math
import random
import torch
from torch import nn
from torch.nn import functional as F
from iopaint.plugins.basicsr.arch_util import default_init_weights
class NormStyleCode(nn.Module):
def forward(self, x):
return x * torch.rsqrt(torch.mean(x**2, dim=1, keepdim=True) + 1e-8)
class ModulatedC... | --- +++ @@ -9,10 +9,31 @@
class NormStyleCode(nn.Module):
def forward(self, x):
+ """Normalize the style codes.
+
+ Args:
+ x (Tensor): Style codes with shape (b, c).
+
+ Returns:
+ Tensor: Normalized tensor.
+ """
return x * torch.rsqrt(torch.mean(x**2,... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/gfpgan/archs/stylegan2_clean_arch.py |
Document functions with clear intent | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torch import nn
from torch.nn import functional as F
from typing import List, Tuple, Type
from .common... | --- +++ @@ -24,6 +24,22 @@ iou_head_depth: int = 3,
iou_head_hidden_dim: int = 256,
) -> None:
+ """
+ Predicts masks given an image and prompt embeddings, using a
+ tranformer architecture.
+
+ Arguments:
+ transformer_dim (int): the channel dimension of the t... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything/modeling/mask_decoder.py |
Document functions with detailed explanations | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import math
from typing import Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from .sam2_utils... | --- +++ @@ -15,6 +15,13 @@
class MaskDownSampler(nn.Module):
+ """
+ Progressively downsample a mask by total_stride, each time by stride.
+ Note that LayerNorm is applied per *token*, like in ViT.
+
+ With each downsample (by a factor stride**2), channel capacity increases by the same factor.
+ In t... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything2/modeling/memory_encoder.py |
Document this script properly | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import torch
from torch import nn
from typing import Any, Optional, Tuple, Type
from .common import L... | --- +++ @@ -22,6 +22,20 @@ mask_in_chans: int,
activation: Type[nn.Module] = nn.GELU,
) -> None:
+ """
+ Encodes prompts for input to SAM's mask decoder.
+
+ Arguments:
+ embed_dim (int): The prompts' embedding dimension
+ image_embedding_size (tuple(int, int... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything/modeling/prompt_encoder.py |
Include argument descriptions in docstrings | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import List, Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
class ImageEncoder... | --- +++ @@ -43,6 +43,11 @@
class FpnNeck(nn.Module):
+ """
+ A modified variant of Feature Pyramid Network (FPN) neck
+ (we remove output conv and also do bicubic interpolation similar to ViT
+ pos embed interpolation)
+ """
def __init__(
self,
@@ -56,6 +61,12 @@ fuse_type: st... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything2/modeling/backbones/image_encoder.py |
Add well-formatted docstrings | import math
import cv2
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from loguru import logger
from iopaint.helper import download_model
from iopaint.plugins.base_plugin import BasePlugin
from iopaint.schema import RunPluginRequest, RealESRGANModel
class RealESRGANer:
def... | --- +++ @@ -13,6 +13,19 @@
class RealESRGANer:
+ """A helper class for upsampling images with RealESRGAN.
+
+ Args:
+ scale (int): Upsampling scale factor used in the networks. It is usually 2 or 4.
+ model_path (str): The path to the pretrained model. It can be urls (will first download it auto... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/realesrgan.py |
Create docstrings for each class method | import cv2
import math
import numpy as np
import os
import torch
from torchvision.utils import make_grid
def img2tensor(imgs, bgr2rgb=True, float32=True):
def _totensor(img, bgr2rgb, float32):
if img.shape[2] == 3 and bgr2rgb:
if img.dtype == 'float64':
img = img.astype('float... | --- +++ @@ -7,6 +7,17 @@
def img2tensor(imgs, bgr2rgb=True, float32=True):
+ """Numpy array to tensor.
+
+ Args:
+ imgs (list[ndarray] | ndarray): Input images.
+ bgr2rgb (bool): Whether to change bgr to rgb.
+ float32 (bool): Whether to change to float32.
+
+ Returns:
+ list[te... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/basicsr/img_util.py |
Add docstrings explaining edge cases | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import torch
from torch.nn import functional as F
from torchvision.transforms.functional import resize,... | --- +++ @@ -14,11 +14,19 @@
class ResizeLongestSide:
+ """
+ Resizes images to longest side 'target_length', as well as provides
+ methods for resizing coordinates and boxes. Provides methods for
+ transforming both numpy array and batched torch tensors.
+ """
def __init__(self, target_length:... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything/utils/transforms.py |
Write docstrings including parameters and return values | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import torch
from .modeling import Sam
from typing import Optional, Tuple
from .utils.transforms imp... | --- +++ @@ -19,6 +19,13 @@ self,
sam_model: Sam,
) -> None:
+ """
+ Uses SAM to calculate the image embedding for an image, and then
+ allow repeated, efficient mask prediction given prompts.
+
+ Arguments:
+ sam_model (Sam): The model to use for mask predictio... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything/predictor_hq.py |
Add verbose docstrings with examples | import torch
from torch import nn as nn
from torch.nn import functional as F
from .arch_util import default_init_weights, make_layer, pixel_unshuffle
class ResidualDenseBlock(nn.Module):
def __init__(self, num_feat: int = 64, num_grow_ch: int = 32) -> None:
super(ResidualDenseBlock, self).__init__()
... | --- +++ @@ -6,6 +6,14 @@
class ResidualDenseBlock(nn.Module):
+ """Residual Dense Block.
+
+ Used in RRDB block in ESRGAN.
+
+ Args:
+ num_feat (int): Channel number of intermediate features.
+ num_grow_ch (int): Channels for each growth.
+ """
def __init__(self, num_feat: int = 64,... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/basicsr/rrdbnet_arch.py |
Write reusable docstrings | # --------------------------------------------------------
# TinyViT Model Architecture
# Copyright (c) 2022 Microsoft
# Adapted from LeViT and Swin Transformer
# LeViT: (https://github.com/facebookresearch/levit)
# Swin: (https://github.com/microsoft/swin-transformer)
# Build the TinyViT Model
# ------------------... | --- +++ @@ -69,6 +69,27 @@
def trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0):
# type: (Tensor, float, float, float, float) -> Tensor
+ r"""Fills the input Tensor with values drawn from a truncated
+ normal distribution. The values are effectively drawn from the
+ normal distribution :math:`\ma... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything/modeling/tiny_vit_sam.py |
Include argument descriptions in docstrings | # copy from https://huggingface.co/briaai/RMBG-2.0/tree/main
import os
import math
import numpy as np
import torch
import torch.nn as nn
from functools import partial
import torch.nn.functional as F
from transformers import PreTrainedModel
from transformers import PretrainedConfig
from timm.models.layers import DropP... | --- +++ @@ -443,6 +443,7 @@
class OverlapPatchEmbed(nn.Module):
+ """Image to Patch Embedding"""
def __init__(
self, img_size=224, patch_size=7, stride=4, in_channels=3, embed_dim=768
@@ -865,6 +866,7 @@
class Mlp(nn.Module):
+ """Multilayer perceptron."""
def __init__(
sel... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/briarmbg2.py |
Please document this code using docstrings | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import torch
from .modeling import Sam
from typing import Optional, Tuple
class SamPredictor:
d... | --- +++ @@ -17,6 +17,13 @@ self,
sam_model: Sam,
) -> None:
+ """
+ Uses SAM to calculate the image embedding for an image, and then
+ allow repeated, efficient mask prediction given prompts.
+
+ Arguments:
+ sam_model (Sam): The model to use for mask predictio... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything/predictor.py |
Create documentation strings for testing functions | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import math
from typing import Any, Optional, Tuple
import numpy as np
import torch
from torch import nn
class Positio... | --- +++ @@ -14,6 +14,10 @@
class PositionEmbeddingSine(nn.Module):
+ """
+ This is a more standard version of the position embedding, very similar to the one
+ used by the Attention Is All You Need paper, generalized to work on images.
+ """
def __init__(
self,
@@ -109,6 +113,9 @@
cl... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything2/modeling/position_encoding.py |
Expand my code with proper documentation strings | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional, Tuple, Type
from .common... | --- +++ @@ -34,6 +34,24 @@ window_size: int = 0,
global_attn_indexes: Tuple[int, ...] = (),
) -> None:
+ """
+ Args:
+ img_size (int): Input image size.
+ patch_size (int): Patch size.
+ in_chans (int): Number of input image channels.
+ emb... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything/modeling/image_encoder.py |
Add docstrings that explain inputs and outputs | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torch import nn
from torch.nn import functional as F
from typing import Any, Dict, List, Tuple
from .i... | --- +++ @@ -27,6 +27,18 @@ pixel_mean: List[float] = [123.675, 116.28, 103.53],
pixel_std: List[float] = [58.395, 57.12, 57.375],
) -> None:
+ """
+ SAM predicts object masks from an image and input prompts.
+
+ Arguments:
+ image_encoder (ImageEncoderViT): The backbo... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything/modeling/sam_hq.py |
Add structured docstrings to improve clarity | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torch import nn
from torch.nn import functional as F
from typing import Any, Dict, List, Tuple
from .i... | --- +++ @@ -27,6 +27,18 @@ pixel_mean: List[float] = [123.675, 116.28, 103.53],
pixel_std: List[float] = [58.395, 57.12, 57.375],
) -> None:
+ """
+ SAM predicts object masks from an image and input prompts.
+
+ Arguments:
+ image_encoder (ImageEncoderViT): The backbo... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything/modeling/sam.py |
Create docstrings for reusable components | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import Optional, Tuple, Type
import torch
from torch import nn
from ..position_encoding import PositionEmbed... | --- +++ @@ -23,6 +23,20 @@ mask_in_chans: int,
activation: Type[nn.Module] = nn.GELU,
) -> None:
+ """
+ Encodes prompts for input to SAM's mask decoder.
+
+ Arguments:
+ embed_dim (int): The prompts' embedding dimension
+ image_embedding_size (tuple(int, int... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything2/modeling/sam/prompt_encoder.py |
Generate documentation strings for clarity | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import math
import warnings
from functools import partial
from typing import Tuple, Type
import torch
import torch.nn.fun... | --- +++ @@ -32,6 +32,18 @@ activation: Type[nn.Module] = nn.ReLU,
attention_downsample_rate: int = 2,
) -> None:
+ """
+ A transformer decoder that attends to an input image using
+ queries whose positional embedding is supplied.
+
+ Args:
+ depth (int): number... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything2/modeling/sam/transformer.py |
Add documentation for all methods | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import List, Optional, Tuple, Type
import torch
from torch import nn
from ..sam2_utils import LayerNorm2d, M... | --- +++ @@ -31,6 +31,22 @@ pred_obj_scores_mlp: bool = False,
use_multimask_token_for_obj_ptr: bool = False,
) -> None:
+ """
+ Predicts masks given an image and prompt embeddings, using a
+ transformer architecture.
+
+ Arguments:
+ transformer_dim (int): the ... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything2/modeling/sam/mask_decoder.py |
Write beginner-friendly docstrings | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import copy
from typing import Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as... | --- +++ @@ -17,6 +17,18 @@
def select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num):
+ """
+ Select up to `max_cond_frame_num` conditioning frames from `cond_frame_outputs`
+ that are temporally closest to the current frame at `frame_idx`. Here, we take
+ - a) the closest condit... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything2/modeling/sam2_utils.py |
Generate docstrings for each module | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.distributed
import torch.nn.functional as F
from torch.nn.init import trunc_normal_
from .sam.... | --- +++ @@ -206,6 +206,7 @@ )
def _build_sam_heads(self):
+ """Build SAM-style prompt encoder and mask decoder."""
self.sam_prompt_embed_dim = self.hidden_dim
self.sam_image_embedding_size = self.image_size // self.backbone_stride
@@ -262,6 +263,45 @@ high_res_features=... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything2/modeling/sam2_base.py |
Add well-formatted docstrings | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
from PIL.Image import Ima... | --- +++ @@ -25,6 +25,17 @@ max_hole_area=0.0,
max_sprinkle_area=0.0,
) -> None:
+ """
+ Uses SAM-2 to calculate the image embedding for an image, and then
+ allow repeated, efficient mask prediction given prompts.
+
+ Arguments:
+ sam_model (Sam-2): The model t... | https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything2/sam2_image_predictor.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.