instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Add clean documentation to messy code | # Copyright 2025 Google LLC.
#
# 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 applicable law or agreed to in writing, ... | --- +++ @@ -12,6 +12,16 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Provides functionality for annotating medical text using a language model.
+
+The annotation process involves tokenizing the input text, generating prompts
+for the language model, an... | https://raw.githubusercontent.com/google/langextract/HEAD/langextract/annotation.py |
Add docstrings to incomplete code | # Copyright 2025 Google LLC.
#
# 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 applicable law or agreed to in writing, ... | --- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Centralized format handler for prompts and parsing."""
from __future__ import annotations
@@ -46,6 +47,21 @@
class FormatHandler:
+ """Handles all format-specific logic for p... | https://raw.githubusercontent.com/google/langextract/HEAD/langextract/core/format_handler.py |
Create documentation strings for testing functions | # Copyright 2025 Google LLC.
#
# 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 applicable law or agreed to in writing, ... | --- +++ @@ -12,6 +12,11 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Schema compatibility layer.
+
+This module provides backward compatibility for the schema module.
+New code should import from langextract.core.schema instead.
+"""
from __future__... | https://raw.githubusercontent.com/google/langextract/HEAD/langextract/schema.py |
Replace inline comments with docstrings | # Copyright 2025 Google LLC.
#
# 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 applicable law or agreed to in writing, ... | --- +++ @@ -12,6 +12,11 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Runtime registry that maps model-ID patterns to provider classes.
+
+This module provides a lazy registration system for LLM providers, allowing
+providers to be registered without im... | https://raw.githubusercontent.com/google/langextract/HEAD/langextract/providers/router.py |
Provide clean and structured docstrings | import cv2
import math
import numpy as np
import os
import queue
import threading
import torch
from basicsr.utils.download_util import load_file_from_url
from torch.nn import functional as F
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
class RealESRGANer():
def __init__(self,
... | --- +++ @@ -12,6 +12,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 au... | https://raw.githubusercontent.com/xinntao/Real-ESRGAN/HEAD/realesrgan/utils.py |
Add docstrings to make code maintainable | # Copyright 2025 Google LLC.
#
# 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 applicable law or agreed to in writing, ... | --- +++ @@ -12,6 +12,73 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Ollama provider for LangExtract.
+
+This provider enables using local Ollama models with LangExtract's extract() function.
+No API key is required since Ollama runs locally on your ma... | https://raw.githubusercontent.com/google/langextract/HEAD/langextract/providers/ollama.py |
Generate descriptive docstrings automatically |
import asyncio
import os
import re
from pathlib import Path
from typing import Any
from nanobot.agent.tools.base import Tool
class ExecTool(Tool):
def __init__(
self,
timeout: int = 60,
working_dir: str | None = None,
deny_patterns: list[str] | None = None,
allow_pattern... | --- +++ @@ -1,3 +1,4 @@+"""Shell execution tool."""
import asyncio
import os
@@ -9,6 +10,7 @@
class ExecTool(Tool):
+ """Tool to execute shell commands."""
def __init__(
self,
@@ -140,6 +142,7 @@ return f"Error executing command: {str(e)}"
def _guard_command(self, command: ... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/agent/tools/shell.py |
Replace inline comments with docstrings |
from __future__ import annotations
import asyncio
import json
import os
import re
import sys
from contextlib import AsyncExitStack
from pathlib import Path
from typing import TYPE_CHECKING, Any, Awaitable, Callable
from loguru import logger
from nanobot.agent.context import ContextBuilder
from nanobot.agent.memory ... | --- +++ @@ -1,3 +1,4 @@+"""Agent loop: the core processing engine."""
from __future__ import annotations
@@ -34,6 +35,16 @@
class AgentLoop:
+ """
+ The agent loop is the core processing engine.
+
+ It:
+ 1. Receives messages from the bus
+ 2. Builds context with history, memory, skills
+ 3. ... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/agent/loop.py |
Create documentation strings for testing functions | import argparse
import cv2
import numpy as np
import os
import sys
from basicsr.utils import scandir
from multiprocessing import Pool
from os import path as osp
from tqdm import tqdm
def main(args):
opt = {}
opt['n_thread'] = args.n_thread
opt['compression_level'] = args.compression_level
opt['input_... | --- +++ @@ -10,6 +10,24 @@
def main(args):
+ """A multi-thread tool to crop large images to sub-images for faster IO.
+
+ opt (dict): Configuration dict. It contains:
+ n_thread (int): Thread number.
+ compression_level (int): CV_IMWRITE_PNG_COMPRESSION from 0 to 9. A higher value means a small... | https://raw.githubusercontent.com/xinntao/Real-ESRGAN/HEAD/scripts/extract_subimages.py |
Provide docstrings following PEP 257 |
from contextvars import ContextVar
from datetime import datetime, timezone
from typing import Any
from nanobot.agent.tools.base import Tool
from nanobot.cron.service import CronService
from nanobot.cron.types import CronJobState, CronSchedule
class CronTool(Tool):
def __init__(self, cron_service: CronService):... | --- +++ @@ -1,3 +1,4 @@+"""Cron tool for scheduling reminders and tasks."""
from contextvars import ContextVar
from datetime import datetime, timezone
@@ -9,6 +10,7 @@
class CronTool(Tool):
+ """Tool to schedule reminders and recurring tasks."""
def __init__(self, cron_service: CronService):
... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/agent/tools/cron.py |
Document classes and their methods | # Copyright 2025 Google LLC.
#
# 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 applicable law or agreed to in writing, ... | --- +++ @@ -12,6 +12,15 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Gemini Batch API helper module for LangExtract.
+
+This module provides batch inference support using the google-genai SDK.
+It handles:
+- File-based batch submission for all batch s... | https://raw.githubusercontent.com/google/langextract/HEAD/langextract/providers/gemini_batch.py |
Add docstrings that explain purpose and usage | import numpy as np
import random
import torch
from basicsr.data.degradations import random_add_gaussian_noise_pt, random_add_poisson_noise_pt
from basicsr.data.transforms import paired_random_crop
from basicsr.models.srgan_model import SRGANModel
from basicsr.utils import DiffJPEG, USMSharp
from basicsr.utils.img_proce... | --- +++ @@ -13,6 +13,12 @@
@MODEL_REGISTRY.register()
class RealESRGANModel(SRGANModel):
+ """RealESRGAN Model for Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data.
+
+ It mainly performs:
+ 1. randomly synthesize LQ images in GPU tensors
+ 2. optimize the networks with GA... | https://raw.githubusercontent.com/xinntao/Real-ESRGAN/HEAD/realesrgan/models/realesrgan_model.py |
Help me write clear docstrings |
import asyncio
import json
import uuid
from pathlib import Path
from typing import Any
from loguru import logger
from nanobot.agent.skills import BUILTIN_SKILLS_DIR
from nanobot.agent.tools.filesystem import EditFileTool, ListDirTool, ReadFileTool, WriteFileTool
from nanobot.agent.tools.registry import ToolRegistry
... | --- +++ @@ -1,3 +1,4 @@+"""Subagent manager for background task execution."""
import asyncio
import json
@@ -20,6 +21,7 @@
class SubagentManager:
+ """Manages background subagent execution."""
def __init__(
self,
@@ -53,6 +55,7 @@ origin_chat_id: str = "direct",
session_key: ... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/agent/subagent.py |
Add docstrings to improve code quality |
from typing import Any, Awaitable, Callable
from nanobot.agent.tools.base import Tool
from nanobot.bus.events import OutboundMessage
class MessageTool(Tool):
def __init__(
self,
send_callback: Callable[[OutboundMessage], Awaitable[None]] | None = None,
default_channel: str = "",
... | --- +++ @@ -1,3 +1,4 @@+"""Message tool for sending messages to users."""
from typing import Any, Awaitable, Callable
@@ -6,6 +7,7 @@
class MessageTool(Tool):
+ """Tool to send messages to users on chat channels."""
def __init__(
self,
@@ -21,14 +23,17 @@ self._sent_in_turn: bool = F... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/agent/tools/message.py |
Add detailed docstrings explaining each function | #!/usr/bin/env python3
# Copyright 2025 Google LLC.
#
# 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 applicable law or... | --- +++ @@ -13,6 +13,24 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Create a new LangExtract provider plugin with all boilerplate code.
+
+This script automates steps 1-6 of the provider creation checklist:
+1. Setup Package Structure
+2. Configure En... | https://raw.githubusercontent.com/google/langextract/HEAD/scripts/create_provider_plugin.py |
Add docstrings explaining edge cases |
from __future__ import annotations
import asyncio
import json
import weakref
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable
from loguru import logger
from nanobot.utils.helpers import ensure_dir, estimate_message_tokens, estimate_prompt_tokens_chain
if TYPE_C... | --- +++ @@ -1,3 +1,4 @@+"""Memory system for persistent agent memory."""
from __future__ import annotations
@@ -45,10 +46,12 @@
def _ensure_text(value: Any) -> str:
+ """Normalize tool-call payload values to text for file storage."""
return value if isinstance(value, str) else json.dumps(value, ensure_... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/agent/memory.py |
Generate docstrings for script automation |
from typing import TYPE_CHECKING, Any
from nanobot.agent.tools.base import Tool
if TYPE_CHECKING:
from nanobot.agent.subagent import SubagentManager
class SpawnTool(Tool):
def __init__(self, manager: "SubagentManager"):
self._manager = manager
self._origin_channel = "cli"
self._ori... | --- +++ @@ -1,3 +1,4 @@+"""Spawn tool for creating background subagents."""
from typing import TYPE_CHECKING, Any
@@ -8,6 +9,7 @@
class SpawnTool(Tool):
+ """Tool to spawn a subagent for background task execution."""
def __init__(self, manager: "SubagentManager"):
self._manager = manager
@@ ... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/agent/tools/spawn.py |
Generate missing documentation strings |
from __future__ import annotations
import asyncio
import html
import json
import os
import re
from typing import TYPE_CHECKING, Any
from urllib.parse import urlparse
import httpx
from loguru import logger
from nanobot.agent.tools.base import Tool
if TYPE_CHECKING:
from nanobot.config.schema import WebSearchCon... | --- +++ @@ -1,3 +1,4 @@+"""Web tools: web_search and web_fetch."""
from __future__ import annotations
@@ -24,6 +25,7 @@
def _strip_tags(text: str) -> str:
+ """Remove HTML tags and decode entities."""
text = re.sub(r'<script[\s\S]*?</script>', '', text, flags=re.I)
text = re.sub(r'<style[\s\S]*?</... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/agent/tools/web.py |
Create structured documentation for my script |
import difflib
from pathlib import Path
from typing import Any
from nanobot.agent.tools.base import Tool
def _resolve_path(
path: str,
workspace: Path | None = None,
allowed_dir: Path | None = None,
extra_allowed_dirs: list[Path] | None = None,
) -> Path:
p = Path(path).expanduser()
if not p... | --- +++ @@ -1,3 +1,4 @@+"""File system tools: read, write, edit, list."""
import difflib
from pathlib import Path
@@ -12,6 +13,7 @@ allowed_dir: Path | None = None,
extra_allowed_dirs: list[Path] | None = None,
) -> Path:
+ """Resolve path against workspace (if relative) and enforce directory restricti... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/agent/tools/filesystem.py |
Add docstrings for internal functions |
import asyncio
from contextlib import contextmanager, nullcontext
import os
import select
import signal
import sys
from pathlib import Path
from typing import Any
# Force UTF-8 encoding for Windows console
if sys.platform == "win32":
if sys.stdout.encoding != "utf-8":
os.environ["PYTHONIOENCODING"] = "utf... | --- +++ @@ -1,3 +1,4 @@+"""CLI commands for nanobot."""
import asyncio
from contextlib import contextmanager, nullcontext
@@ -54,6 +55,7 @@
def _flush_pending_tty_input() -> None:
+ """Drop unread keypresses typed while the model was generating output."""
try:
fd = sys.stdin.fileno()
i... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/cli/commands.py |
Add clean documentation to messy code |
import asyncio
from collections import deque
from typing import TYPE_CHECKING, Any, Literal
from loguru import logger
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.config.schema import Base
from pydantic import Field... | --- +++ @@ -1,3 +1,4 @@+"""QQ channel implementation using botpy SDK."""
import asyncio
from collections import deque
@@ -27,6 +28,7 @@
def _make_bot_class(channel: "QQChannel") -> "type[botpy.Client]":
+ """Create a botpy Client subclass bound to the given channel."""
intents = botpy.Intents(public_mes... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/channels/qq.py |
Document all endpoints with docstrings |
import json
import os
import re
import shutil
from pathlib import Path
# Default builtin skills directory (relative to this file)
BUILTIN_SKILLS_DIR = Path(__file__).parent.parent / "skills"
class SkillsLoader:
def __init__(self, workspace: Path, builtin_skills_dir: Path | None = None):
self.workspace ... | --- +++ @@ -1,3 +1,4 @@+"""Skills loader for agent capabilities."""
import json
import os
@@ -10,6 +11,12 @@
class SkillsLoader:
+ """
+ Loader for agent skills.
+
+ Skills are markdown files (SKILL.md) that teach the agent how to use
+ specific tools or perform certain tasks.
+ """
def __... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/agent/skills.py |
Add docstrings to improve collaboration | # Copyright 2025 Google LLC.
#
# 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 applicable law or agreed to in writing, ... | --- +++ @@ -12,6 +12,11 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Compatibility shim for langextract.registry imports.
+
+This module redirects to langextract.plugins for backward compatibility.
+Will be removed in v2.0.0.
+"""
from __future__ im... | https://raw.githubusercontent.com/google/langextract/HEAD/langextract/registry.py |
Can you add docstrings to this Python file? |
import asyncio
from nanobot.bus.events import InboundMessage, OutboundMessage
class MessageBus:
def __init__(self):
self.inbound: asyncio.Queue[InboundMessage] = asyncio.Queue()
self.outbound: asyncio.Queue[OutboundMessage] = asyncio.Queue()
async def publish_inbound(self, msg: InboundMess... | --- +++ @@ -1,3 +1,4 @@+"""Async message queue for decoupled channel-agent communication."""
import asyncio
@@ -5,27 +6,39 @@
class MessageBus:
+ """
+ Async message bus that decouples chat channels from the agent core.
+
+ Channels push messages to the inbound queue, and the agent processes
+ them... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/bus/queue.py |
Document my Python code with docstrings | # Copyright 2025 Google LLC.
#
# 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 applicable law or agreed to in writing, ... | --- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""OpenAI provider for LangExtract."""
# pylint: disable=duplicate-code
from __future__ import annotations
@@ -35,6 +36,7 @@ )
@dataclasses.dataclass(init=False)
class OpenAILanguag... | https://raw.githubusercontent.com/google/langextract/HEAD/langextract/providers/openai.py |
Generate consistent docstrings |
import base64
import mimetypes
import platform
from pathlib import Path
from typing import Any
from nanobot.utils.helpers import current_time_str
from nanobot.agent.memory import MemoryStore
from nanobot.agent.skills import SkillsLoader
from nanobot.utils.helpers import build_assistant_message, detect_image_mime
c... | --- +++ @@ -1,3 +1,4 @@+"""Context builder for assembling agent prompts."""
import base64
import mimetypes
@@ -13,6 +14,7 @@
class ContextBuilder:
+ """Builds the context (system prompt + messages) for the agent."""
BOOTSTRAP_FILES = ["AGENTS.md", "SOUL.md", "USER.md", "TOOLS.md"]
_RUNTIME_CONTEX... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/agent/context.py |
Document helper functions with docstrings |
from typing import Any
from nanobot.agent.tools.base import Tool
class ToolRegistry:
def __init__(self):
self._tools: dict[str, Tool] = {}
def register(self, tool: Tool) -> None:
self._tools[tool.name] = tool
def unregister(self, name: str) -> None:
self._tools.pop(name, None)... | --- +++ @@ -1,3 +1,4 @@+"""Tool registry for dynamic tool management."""
from typing import Any
@@ -5,26 +6,37 @@
class ToolRegistry:
+ """
+ Registry for agent tools.
+
+ Allows dynamic registration and execution of tools.
+ """
def __init__(self):
self._tools: dict[str, Tool] = {}... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/agent/tools/registry.py |
Improve documentation using docstrings |
from abc import ABC, abstractmethod
from typing import Any
class Tool(ABC):
_TYPE_MAP = {
"string": str,
"integer": int,
"number": (int, float),
"boolean": bool,
"array": list,
"object": dict,
}
@property
@abstractmethod
def name(self) -> str:
... | --- +++ @@ -1,9 +1,16 @@+"""Base class for agent tools."""
from abc import ABC, abstractmethod
from typing import Any
class Tool(ABC):
+ """
+ Abstract base class for agent tools.
+
+ Tools are capabilities that the agent can use to interact with
+ the environment, such as reading files, executing ... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/agent/tools/base.py |
Help me comply with documentation standards |
from __future__ import annotations
from pathlib import Path
from nanobot.config.loader import get_config_path
from nanobot.utils.helpers import ensure_dir
def get_data_dir() -> Path:
return ensure_dir(get_config_path().parent)
def get_runtime_subdir(name: str) -> Path:
return ensure_dir(get_data_dir() / ... | --- +++ @@ -1,3 +1,4 @@+"""Runtime path helpers derived from the active config context."""
from __future__ import annotations
@@ -8,38 +9,47 @@
def get_data_dir() -> Path:
+ """Return the instance-level runtime data directory."""
return ensure_dir(get_config_path().parent)
def get_runtime_subdir(n... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/config/paths.py |
Document classes and their methods |
import asyncio
import importlib.util
import os
from collections import OrderedDict
from typing import Any
from loguru import logger
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_media_dir
from... | --- +++ @@ -1,3 +1,4 @@+"""WeCom (Enterprise WeChat) channel implementation using wecom_aibot_sdk."""
import asyncio
import importlib.util
@@ -17,6 +18,7 @@ WECOM_AVAILABLE = importlib.util.find_spec("wecom_aibot_sdk") is not None
class WecomConfig(Base):
+ """WeCom (Enterprise WeChat) AI Bot channel configur... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/channels/wecom.py |
Create docstrings for reusable components |
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
@dataclass
class InboundMessage:
channel: str # telegram, discord, slack, whatsapp
sender_id: str # User identifier
chat_id: str # Chat/channel identifier
content: str # Message text
timestamp: date... | --- +++ @@ -1,3 +1,4 @@+"""Event types for the message bus."""
from dataclasses import dataclass, field
from datetime import datetime
@@ -6,6 +7,7 @@
@dataclass
class InboundMessage:
+ """Message received from a chat channel."""
channel: str # telegram, discord, slack, whatsapp
sender_id: str # ... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/bus/events.py |
Add inline docstrings for readability |
import asyncio
from contextlib import AsyncExitStack
from typing import Any
import httpx
from loguru import logger
from nanobot.agent.tools.base import Tool
from nanobot.agent.tools.registry import ToolRegistry
class MCPToolWrapper(Tool):
def __init__(self, session, server_name: str, tool_def, tool_timeout: i... | --- +++ @@ -1,3 +1,4 @@+"""MCP client: connects to MCP servers and wraps their tools as native nanobot tools."""
import asyncio
from contextlib import AsyncExitStack
@@ -11,6 +12,7 @@
class MCPToolWrapper(Tool):
+ """Wraps a single MCP server tool as a nanobot Tool."""
def __init__(self, session, serv... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/agent/tools/mcp.py |
Add docstrings to clarify complex logic |
from __future__ import annotations
from importlib import import_module
from typing import TYPE_CHECKING
from nanobot.providers.base import LLMProvider, LLMResponse
__all__ = ["LLMProvider", "LLMResponse", "LiteLLMProvider", "OpenAICodexProvider", "AzureOpenAIProvider"]
_LAZY_IMPORTS = {
"LiteLLMProvider": ".li... | --- +++ @@ -1,3 +1,4 @@+"""LLM provider abstraction module."""
from __future__ import annotations
@@ -21,8 +22,9 @@
def __getattr__(name: str):
+ """Lazily expose provider implementations without importing all backends up front."""
module_name = _LAZY_IMPORTS.get(name)
if module_name is None:
... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/providers/__init__.py |
Add docstrings to clarify complex logic |
from __future__ import annotations
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Any
from loguru import logger
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.queue import MessageBus
class BaseChannel(ABC):
name: str = "base"
display_name:... | --- +++ @@ -1,3 +1,4 @@+"""Base channel interface for chat platforms."""
from __future__ import annotations
@@ -12,17 +13,31 @@
class BaseChannel(ABC):
+ """
+ Abstract base class for chat channel implementations.
+
+ Each channel (Telegram, Discord, etc.) should implement this interface
+ to integ... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/channels/base.py |
Create structured documentation for my script |
import asyncio
import json
import mimetypes
import os
import time
from pathlib import Path
from typing import Any
from urllib.parse import unquote, urlparse
import httpx
from loguru import logger
from pydantic import Field
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from n... | --- +++ @@ -1,3 +1,4 @@+"""DingTalk/DingDing channel implementation using Stream Mode."""
import asyncio
import json
@@ -38,12 +39,17 @@
class NanobotDingTalkHandler(CallbackHandler):
+ """
+ Standard DingTalk Stream SDK Callback Handler.
+ Parses incoming messages and forwards them to the Nanobot chan... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/channels/dingtalk.py |
Write docstrings describing each step |
import asyncio
import json
from pathlib import Path
from typing import Any, Literal
import httpx
from pydantic import Field
import websockets
from loguru import logger
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.co... | --- +++ @@ -1,3 +1,4 @@+"""Discord channel implementation using Discord Gateway websocket."""
import asyncio
import json
@@ -22,6 +23,7 @@
class DiscordConfig(Base):
+ """Discord channel configuration."""
enabled: bool = False
token: str = ""
@@ -32,6 +34,7 @@
class DiscordChannel(BaseChannel... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/channels/discord.py |
Write clean docstrings for readability |
import asyncio
import json
import os
import re
import threading
from collections import OrderedDict
from pathlib import Path
from typing import Any, Literal
from loguru import logger
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
... | --- +++ @@ -1,3 +1,4 @@+"""Feishu/Lark channel implementation using lark-oapi SDK with WebSocket long connection."""
import asyncio
import json
@@ -31,6 +32,7 @@
def _extract_share_card_content(content_json: dict, msg_type: str) -> str:
+ """Extract text representation from share cards and interactive messag... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/channels/feishu.py |
Add docstrings to improve readability |
import asyncio
import html
import imaplib
import re
import smtplib
import ssl
from datetime import date
from email import policy
from email.header import decode_header, make_header
from email.message import EmailMessage
from email.parser import BytesParser
from email.utils import parseaddr
from typing import Any
from... | --- +++ @@ -1,3 +1,4 @@+"""Email channel implementation using IMAP polling + SMTP replies."""
import asyncio
import html
@@ -23,6 +24,7 @@
class EmailConfig(Base):
+ """Email channel configuration (IMAP inbound + SMTP outbound)."""
enabled: bool = False
consent_granted: bool = False
@@ -51,6 +53,... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/channels/email.py |
Add minimal docstrings for each function |
import asyncio
import re
from typing import Any
from loguru import logger
from slack_sdk.socket_mode.request import SocketModeRequest
from slack_sdk.socket_mode.response import SocketModeResponse
from slack_sdk.socket_mode.websockets import SocketModeClient
from slack_sdk.web.async_client import AsyncWebClient
from s... | --- +++ @@ -1,3 +1,4 @@+"""Slack channel implementation using Socket Mode."""
import asyncio
import re
@@ -19,6 +20,7 @@
class SlackDMConfig(Base):
+ """Slack DM policy configuration."""
enabled: bool = True
policy: str = "open"
@@ -26,6 +28,7 @@
class SlackConfig(Base):
+ """Slack channel... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/channels/slack.py |
Create structured documentation for my script |
from __future__ import annotations
import importlib
import pkgutil
from typing import TYPE_CHECKING
from loguru import logger
if TYPE_CHECKING:
from nanobot.channels.base import BaseChannel
_INTERNAL = frozenset({"base", "manager", "registry"})
def discover_channel_names() -> list[str]:
import nanobot.ch... | --- +++ @@ -1,3 +1,4 @@+"""Auto-discovery for built-in channel modules and external plugins."""
from __future__ import annotations
@@ -14,6 +15,7 @@
def discover_channel_names() -> list[str]:
+ """Return all built-in channel module names by scanning the package (zero imports)."""
import nanobot.channel... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/channels/registry.py |
Add standardized docstrings across the file |
from __future__ import annotations
import asyncio
import json
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
import httpx
from loguru import logger
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
fro... | --- +++ @@ -1,3 +1,4 @@+"""Mochat channel implementation using Socket.IO with HTTP polling fallback."""
from __future__ import annotations
@@ -41,6 +42,7 @@
@dataclass
class MochatBufferedEntry:
+ """Buffered inbound entry for delayed dispatch."""
raw_body: str
author: str
sender_name: str = "... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/channels/mochat.py |
Generate helpful docstrings for debugging |
import json
import shutil
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any
from loguru import logger
from nanobot.config.paths import get_legacy_sessions_dir
from nanobot.utils.helpers import ensure_dir, safe_filename
@dataclass
class Session:
... | --- +++ @@ -1,3 +1,4 @@+"""Session management for conversation history."""
import json
import shutil
@@ -14,6 +15,15 @@
@dataclass
class Session:
+ """
+ A conversation session.
+
+ Stores messages in JSONL format for easy reading and persistence.
+
+ Important: Messages are append-only for LLM cache... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/session/manager.py |
Add docstrings to make code maintainable |
from __future__ import annotations
import asyncio
from typing import Any
from loguru import logger
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.config.schema import Config
class ChannelManager:
def __init__(self, config: Config, bus: MessageBus):
... | --- +++ @@ -1,3 +1,4 @@+"""Channel manager for coordinating chat channels."""
from __future__ import annotations
@@ -12,6 +13,14 @@
class ChannelManager:
+ """
+ Manages chat channels and coordinates message routing.
+
+ Responsibilities:
+ - Initialize enabled channels (Telegram, WhatsApp, etc.)
+... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/channels/manager.py |
Generate consistent docstrings |
import asyncio
import logging
import mimetypes
from pathlib import Path
from typing import Any, Literal, TypeAlias
from loguru import logger
from pydantic import Field
try:
import nh3
from mistune import create_markdown
from nio import (
AsyncClient,
AsyncClientConfig,
ContentRepo... | --- +++ @@ -1,3 +1,4 @@+"""Matrix (Element) channel — inbound sync + outbound message/media delivery."""
import asyncio
import logging
@@ -76,6 +77,7 @@
def _filter_matrix_html_attribute(tag: str, attr: str, value: str) -> str | None:
+ """Filter attribute values to a safe Matrix-compatible subset."""
i... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/channels/matrix.py |
Document functions with detailed explanations |
from __future__ import annotations
import asyncio
import re
import time
import unicodedata
from typing import Any, Literal
from loguru import logger
from pydantic import Field
from telegram import BotCommand, ReplyParameters, Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, ... | --- +++ @@ -1,3 +1,4 @@+"""Telegram channel implementation using python-telegram-bot."""
from __future__ import annotations
@@ -26,6 +27,7 @@
def _strip_md(s: str) -> str:
+ """Strip markdown inline formatting from text."""
s = re.sub(r'\*\*(.+?)\*\*', r'\1', s)
s = re.sub(r'__(.+?)__', r'\1', s)
... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/channels/telegram.py |
Add detailed docstrings explaining each function |
from __future__ import annotations
import asyncio
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Coroutine
from loguru import logger
if TYPE_CHECKING:
from nanobot.providers.base import LLMProvider
_HEARTBEAT_TOOL = [
{
"type": "function",
"function": {
... | --- +++ @@ -1,3 +1,4 @@+"""Heartbeat service - periodic agent wake-up to check for tasks."""
from __future__ import annotations
@@ -37,6 +38,17 @@
class HeartbeatService:
+ """
+ Periodic heartbeat service that wakes the agent to check for tasks.
+
+ Phase 1 (decision): reads HEARTBEAT.md and asks the... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/heartbeat/service.py |
Create Google-style docstrings for my code | #!/usr/bin/env python3
import re
import sys
from pathlib import Path
from typing import Optional
try:
import yaml
except ModuleNotFoundError:
yaml = None
MAX_SKILL_NAME_LENGTH = 64
ALLOWED_FRONTMATTER_KEYS = {
"name",
"description",
"metadata",
"always",
"license",
"allowed-tools",
}
... | --- +++ @@ -1,4 +1,7 @@ #!/usr/bin/env python3
+"""
+Minimal validator for nanobot skill folders.
+"""
import re
import sys
@@ -34,6 +37,7 @@
def _parse_simple_frontmatter(frontmatter_text: str) -> Optional[dict[str, str]]:
+ """Fallback parser for simple frontmatter when PyYAML is unavailable."""
parse... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/skills/skill-creator/scripts/quick_validate.py |
Add standardized docstrings across the file |
from __future__ import annotations
import uuid
from typing import Any
from urllib.parse import urljoin
import httpx
import json_repair
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
_AZURE_MSG_KEYS = frozenset({"role", "content", "tool_calls", "tool_call_id", "name"})
class AzureOpe... | --- +++ @@ -1,3 +1,4 @@+"""Azure OpenAI provider implementation with API version 2024-10-21."""
from __future__ import annotations
@@ -14,6 +15,16 @@
class AzureOpenAIProvider(LLMProvider):
+ """
+ Azure OpenAI provider with API version 2024-10-21 compliance.
+
+ Features:
+ - Hardcoded API ver... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/providers/azure_openai_provider.py |
Write docstrings that follow conventions |
import json
import re
import time
from datetime import datetime
from pathlib import Path
from typing import Any
import tiktoken
def detect_image_mime(data: bytes) -> str | None:
if data[:8] == b"\x89PNG\r\n\x1a\n":
return "image/png"
if data[:3] == b"\xff\xd8\xff":
return "image/jpeg"
if... | --- +++ @@ -1,3 +1,4 @@+"""Utility functions for nanobot."""
import json
import re
@@ -10,6 +11,7 @@
def detect_image_mime(data: bytes) -> str | None:
+ """Detect image MIME type from magic bytes, ignoring file extension."""
if data[:8] == b"\x89PNG\r\n\x1a\n":
return "image/png"
if data[:... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/utils/helpers.py |
Generate descriptive docstrings automatically |
import asyncio
import json
import mimetypes
from collections import OrderedDict
from typing import Any
from loguru import logger
from pydantic import Field
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.config.schema... | --- +++ @@ -1,3 +1,4 @@+"""WhatsApp channel implementation using Node.js bridge."""
import asyncio
import json
@@ -16,6 +17,7 @@
class WhatsAppConfig(Base):
+ """WhatsApp channel configuration."""
enabled: bool = False
bridge_url: str = "ws://localhost:3001"
@@ -24,6 +26,12 @@
class WhatsAppC... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/channels/whatsapp.py |
Add docstrings to incomplete code |
import json
from pathlib import Path
from nanobot.config.schema import Config
# Global variable to store current config path (for multi-instance support)
_current_config_path: Path | None = None
def set_config_path(path: Path) -> None:
global _current_config_path
_current_config_path = path
def get_conf... | --- +++ @@ -1,3 +1,4 @@+"""Configuration loading utilities."""
import json
from pathlib import Path
@@ -10,17 +11,28 @@
def set_config_path(path: Path) -> None:
+ """Set the current config path (used to derive data directory)."""
global _current_config_path
_current_config_path = path
def get_... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/config/loader.py |
Write Python docstrings for this snippet |
from pathlib import Path
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field
from pydantic.alias_generators import to_camel
from pydantic_settings import BaseSettings
class Base(BaseModel):
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
class ChannelsConfig... | --- +++ @@ -1,3 +1,4 @@+"""Configuration schema using Pydantic."""
from pathlib import Path
from typing import Literal
@@ -8,10 +9,16 @@
class Base(BaseModel):
+ """Base model that accepts both camelCase and snake_case keys."""
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/config/schema.py |
Write docstrings describing each step |
import os
from pathlib import Path
import httpx
from loguru import logger
class GroqTranscriptionProvider:
def __init__(self, api_key: str | None = None):
self.api_key = api_key or os.environ.get("GROQ_API_KEY")
self.api_url = "https://api.groq.com/openai/v1/audio/transcriptions"
async def... | --- +++ @@ -1,3 +1,4 @@+"""Voice transcription provider using Groq."""
import os
from pathlib import Path
@@ -7,12 +8,26 @@
class GroqTranscriptionProvider:
+ """
+ Voice transcription provider using Groq's Whisper API.
+
+ Groq offers extremely fast transcription with a generous free tier.
+ """
... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/providers/transcription.py |
Add docstrings with type hints explained |
from dataclasses import dataclass, field
from typing import Literal
@dataclass
class CronSchedule:
kind: Literal["at", "every", "cron"]
# For "at": timestamp in ms
at_ms: int | None = None
# For "every": interval in ms
every_ms: int | None = None
# For "cron": cron expression (e.g. "0 9 * * *... | --- +++ @@ -1,3 +1,4 @@+"""Cron types."""
from dataclasses import dataclass, field
from typing import Literal
@@ -5,6 +6,7 @@
@dataclass
class CronSchedule:
+ """Schedule definition for a cron job."""
kind: Literal["at", "every", "cron"]
# For "at": timestamp in ms
at_ms: int | None = None
@@ -... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/cron/types.py |
Help me document legacy Python code |
import asyncio
import json
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Any
from loguru import logger
@dataclass
class ToolCallRequest:
id: str
name: str
arguments: dict[str, Any]
provider_specific_fields: dict[str, Any] | None = None
function_p... | --- +++ @@ -1,3 +1,4 @@+"""Base LLM provider interface."""
import asyncio
import json
@@ -10,6 +11,7 @@
@dataclass
class ToolCallRequest:
+ """A tool call request from the LLM."""
id: str
name: str
arguments: dict[str, Any]
@@ -17,6 +19,7 @@ function_provider_specific_fields: dict[str, Any]... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/providers/base.py |
Add concise docstrings to each method |
from __future__ import annotations
from typing import TYPE_CHECKING
from loguru import logger
if TYPE_CHECKING:
from nanobot.providers.base import LLMProvider
_EVALUATE_TOOL = [
{
"type": "function",
"function": {
"name": "evaluate_notification",
"description": "Deci... | --- +++ @@ -1,3 +1,8 @@+"""Post-run evaluation for background tasks (heartbeat & cron).
+
+After the agent executes a background task, this module makes a lightweight
+LLM call to decide whether the result warrants notifying the user.
+"""
from __future__ import annotations
@@ -51,6 +56,12 @@ provider: LLMProv... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/utils/evaluator.py |
Add docstrings to existing functions |
import asyncio
import json
import time
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Coroutine
from loguru import logger
from nanobot.cron.types import CronJob, CronJobState, CronPayload, CronSchedule, CronStore
def _now_ms() -> int:
return int(time.time()... | --- +++ @@ -1,3 +1,4 @@+"""Cron service for scheduling agent tasks."""
import asyncio
import json
@@ -17,6 +18,7 @@
def _compute_next_run(schedule: CronSchedule, now_ms: int) -> int | None:
+ """Compute next run time in ms."""
if schedule.kind == "at":
return schedule.at_ms if schedule.at_ms an... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/cron/service.py |
Document my Python code with docstrings |
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
@dataclass(frozen=True)
class ProviderSpec:
# identity
name: str # config field name, e.g. "dashscope"
keywords: tuple[str, ...] # model-name keywords for matching (lowercase)
env_key: str # LiteLL... | --- +++ @@ -1,3 +1,14 @@+"""
+Provider Registry — single source of truth for LLM provider metadata.
+
+Adding a new provider:
+ 1. Add a ProviderSpec to PROVIDERS below.
+ 2. Add a field to ProvidersConfig in config/schema.py.
+ Done. Env vars, prefixing, config matching, status display all derive from here.
+
+Orde... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/providers/registry.py |
Add docstrings with type hints explained | #!/usr/bin/env python3
import sys
import zipfile
from pathlib import Path
from quick_validate import validate_skill
def _is_within(path: Path, root: Path) -> bool:
try:
path.relative_to(root)
return True
except ValueError:
return False
def _cleanup_partial_archive(skill_filename: P... | --- +++ @@ -1,4 +1,14 @@ #!/usr/bin/env python3
+"""
+Skill Packager - Creates a distributable .skill file of a skill folder
+
+Usage:
+ python package_skill.py <path/to/skill-folder> [output-directory]
+
+Example:
+ python package_skill.py skills/public/my-skill
+ python package_skill.py skills/public/my-skil... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/skills/skill-creator/scripts/package_skill.py |
Create simple docstrings for beginners |
import hashlib
import os
import secrets
import string
from typing import Any
import json_repair
import litellm
from litellm import acompletion
from loguru import logger
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
from nanobot.providers.registry import find_by_model, find_gateway
# S... | --- +++ @@ -1,3 +1,4 @@+"""LiteLLM provider implementation for multi-provider support."""
import hashlib
import os
@@ -19,10 +20,18 @@ _ALNUM = string.ascii_letters + string.digits
def _short_tool_id() -> str:
+ """Generate a 9-char alphanumeric ID compatible with all providers (incl. Mistral)."""
return... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/providers/litellm_provider.py |
Create structured documentation for my script |
from __future__ import annotations
import asyncio
import hashlib
import json
from typing import Any, AsyncGenerator
import httpx
from loguru import logger
from oauth_cli_kit import get_token as get_codex_token
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
DEFAULT_CODEX_URL = "https:/... | --- +++ @@ -1,3 +1,4 @@+"""OpenAI Codex Responses Provider."""
from __future__ import annotations
@@ -17,6 +18,7 @@
class OpenAICodexProvider(LLMProvider):
+ """Use Codex OAuth to call the Responses API."""
def __init__(self, default_model: str = "openai-codex/gpt-5.1-codex"):
super().__init... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/providers/openai_codex_provider.py |
Provide docstrings following PEP 257 |
from __future__ import annotations
import ipaddress
import re
import socket
from urllib.parse import urlparse
_BLOCKED_NETWORKS = [
ipaddress.ip_network("0.0.0.0/8"),
ipaddress.ip_network("10.0.0.0/8"),
ipaddress.ip_network("100.64.0.0/10"), # carrier-grade NAT
ipaddress.ip_network("127.0.0.0/8"),
... | --- +++ @@ -1,3 +1,4 @@+"""Network security utilities — SSRF protection and internal URL detection."""
from __future__ import annotations
@@ -27,6 +28,10 @@
def validate_url_target(url: str) -> tuple[bool, str]:
+ """Validate a URL is safe to fetch: scheme, hostname, and resolved IPs.
+
+ Returns (ok, er... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/security/network.py |
Add docstrings for internal functions | from __future__ import annotations
import argparse
import logging
from contextlib import suppress
from importlib import import_module
from pathlib import Path
from typing import TYPE_CHECKING
from typing import cast
from cleo._utils import find_similar_names
from cleo.application import Application as BaseApplicatio... | --- +++ @@ -322,6 +322,16 @@ )
def _configure_global_options(self, io: IO) -> None:
+ """
+ Configures global options for the application by setting up the relevant
+ directories, disabling plugins or cache, and managing the working and
+ project directories. This method ensur... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/console/application.py |
Fully document this Python code with docstrings | from __future__ import annotations
from collections import defaultdict
from typing import TYPE_CHECKING
from cleo.helpers import option
from packaging.utils import NormalizedName
from packaging.utils import canonicalize_name
from poetry.console.commands.command import Command
from poetry.console.exceptions import Gr... | --- +++ @@ -54,10 +54,21 @@
@property
def default_group(self) -> str | None:
+ """
+ The default group to use when no group is specified. This is useful
+ for command that have the `--group` option, eg: add, remove.
+
+ Can be overridden to adapt behavior.
+ """
re... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/console/commands/group_command.py |
Write docstrings for this repository | #!/usr/bin/env python3
import argparse
import re
import sys
from pathlib import Path
MAX_SKILL_NAME_LENGTH = 64
ALLOWED_RESOURCES = {"scripts", "references", "assets"}
SKILL_TEMPLATE = """---
name: {skill_name}
description: [TODO: Complete and informative explanation of what the skill does and when to use it. Includ... | --- +++ @@ -1,4 +1,16 @@ #!/usr/bin/env python3
+"""
+Skill Initializer - Creates a new skill from template
+
+Usage:
+ init_skill.py <skill-name> --path <path> [--resources scripts,references,assets] [--examples]
+
+Examples:
+ init_skill.py my-new-skill --path skills/public
+ init_skill.py my-new-skill --pat... | https://raw.githubusercontent.com/HKUDS/nanobot/HEAD/nanobot/skills/skill-creator/scripts/init_skill.py |
Generate docstrings for script automation | from __future__ import annotations
import typing
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
from packaging.utils import canonicalize_name
from poetry.core.packages.dependency import Dependency
from poetry.core.packages.project_package import ProjectPackage
from poetry.__version... | --- +++ @@ -114,10 +114,23 @@ return self._poetry
def _system_project_handle(self) -> int:
+ """
+ This is a helper method that by default calls the handle method implemented in
+ the child class's next MRO sibling. Override this if you want special handling
+ either before ca... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/console/commands/self/self_command.py |
Add docstrings to my Python code | from __future__ import annotations
from typing import TYPE_CHECKING
from typing import Any
from typing import ClassVar
from cleo.helpers import option
from poetry.console.commands.command import Command
if TYPE_CHECKING:
from pathlib import Path
from cleo.io.inputs.option import Option
class CheckComman... | --- +++ @@ -39,6 +39,18 @@ def _validate_classifiers(
self, project_classifiers: set[str]
) -> tuple[list[str], list[str]]:
+ """Identify unrecognized and deprecated trove classifiers.
+
+ A fully-qualified classifier is a string delimited by `` :: `` separators. To
+ make the err... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/console/commands/check.py |
Document functions with detailed explanations |
from __future__ import annotations
import io
import logging
import re
from bisect import bisect_left
from bisect import bisect_right
from contextlib import contextmanager
from tempfile import NamedTemporaryFile
from typing import IO
from typing import TYPE_CHECKING
from typing import Any
from typing import ClassVar
... | --- +++ @@ -1,3 +1,4 @@+"""Lazy ZIP over HTTP"""
from __future__ import annotations
@@ -40,18 +41,24 @@
class LazyWheelUnsupportedError(Exception):
+ """Raised when a lazy wheel is unsupported."""
class HTTPRangeRequestUnsupportedError(LazyWheelUnsupportedError):
+ """Raised when the remote server a... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/inspection/lazy_wheel.py |
Add docstrings to improve code quality | from __future__ import annotations
import contextlib
import functools
import glob
import logging
import tempfile
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import TYPE_CHECKING
from typing import Any
import pkginfo
from poetry.core.constraints.version import Version
from poetry.cor... | --- +++ @@ -88,6 +88,9 @@ return self
def asdict(self) -> dict[str, Any]:
+ """
+ Helper method to convert package info into a dictionary used for caching.
+ """
return {
"name": self.name,
"version": self.version,
@@ -101,12 +104,28 @@
@class... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/inspection/info.py |
Generate docstrings for script automation | from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from poetry.mixology.incompatibility import Incompatibility
class IncompatibilityCauseError(Exception):
class RootCauseError(IncompatibilityCauseError):
pass
class NoVersionsCauseError(IncompatibilityCauseError):
... | --- +++ @@ -8,6 +8,9 @@
class IncompatibilityCauseError(Exception):
+ """
+ The reason and Incompatibility's terms are incompatible.
+ """
class RootCauseError(IncompatibilityCauseError):
@@ -23,6 +26,10 @@
class ConflictCauseError(IncompatibilityCauseError):
+ """
+ The incompatibility was ... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/mixology/incompatibility_cause.py |
Generate docstrings with parameter types | from __future__ import annotations
import collections
import functools
import time
from enum import IntEnum
from typing import TYPE_CHECKING
from poetry.core.packages.dependency import Dependency
from poetry.mixology.failure import SolveFailureError
from poetry.mixology.incompatibility import Incompatibility
from p... | --- +++ @@ -32,6 +32,11 @@
class Preference(IntEnum):
+ """
+ Preference is one of the criteria for choosing which dependency to solve
+ first. A higher value means that there are "more options" to satisfy
+ a dependency. A lower value takes precedence.
+ """
DIRECT_ORIGIN = 0
NO_CHOICE =... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/mixology/version_solver.py |
Generate NumPy-style docstrings | from __future__ import annotations
from typing import TYPE_CHECKING
from poetry.mixology.assignment import Assignment
from poetry.mixology.set_relation import SetRelation
if TYPE_CHECKING:
from poetry.core.packages.dependency import Dependency
from poetry.core.packages.package import Package
from poetr... | --- +++ @@ -15,6 +15,14 @@
class PartialSolution:
+ """
+ # A list of Assignments that represent the solver's current best guess about
+ # what's true for the eventual set of package versions that will comprise the
+ # total solution.
+ #
+ # See:
+ # https://github.com/dart-lang/mixology/tree/... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/mixology/partial_solution.py |
Generate helpful docstrings for debugging | from __future__ import annotations
import dataclasses
import shlex
from dataclasses import InitVar
from subprocess import CalledProcessError
from typing import TYPE_CHECKING
from cleo.exceptions import CleoError
from poetry.utils._compat import decode
if TYPE_CHECKING:
from cleo.io.io import IO
class Poetry... | --- +++ @@ -26,6 +26,15 @@
@dataclasses.dataclass
class ConsoleMessage:
+ """
+ Representation of a console message, providing utilities for formatting text
+ with tags, indentation, and sections.
+
+ The ConsoleMessage class is designed to represent text messages that might be
+ displayed in a consol... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/console/exceptions.py |
Create docstrings for all classes and functions | from __future__ import annotations
import functools
from typing import TYPE_CHECKING
from poetry.mixology.set_relation import SetRelation
if TYPE_CHECKING:
from poetry.core.constraints.version import VersionConstraint
from poetry.core.packages.dependency import Dependency
class Term:
def __init__(se... | --- +++ @@ -13,6 +13,12 @@
class Term:
+ """
+ A statement about a package which is true or false for a given selection of
+ package versions.
+
+ See https://github.com/dart-lang/pub/tree/master/doc/solver.md#term.
+ """
def __init__(self, dependency: Dependency, is_positive: bool) -> None:
... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/mixology/term.py |
Create docstrings for all classes and functions | from __future__ import annotations
import logging
import re
from typing import TYPE_CHECKING
from typing import Any
from poetry.config.config import Config
from poetry.config.config import PackageFilterPolicy
from poetry.console.exceptions import ConsoleMessage
from poetry.console.exceptions import PoetryRuntimeErro... | --- +++ @@ -28,6 +28,9 @@
class Chooser:
+ """
+ A Chooser chooses an appropriate release archive for packages.
+ """
def __init__(
self, pool: RepositoryPool, env: Env, config: Config | None = None
@@ -43,6 +46,9 @@ )
def choose_for(self, package: Package) -> Link:
+ ... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/installation/chooser.py |
Create docstrings for reusable components | from __future__ import annotations
import functools
import itertools
import logging
import re
import time
from collections import defaultdict
from contextlib import contextmanager
from typing import TYPE_CHECKING
from typing import Any
from typing import ClassVar
from typing import cast
from cleo.ui.progress_indicat... | --- +++ @@ -61,6 +61,9 @@
class IncompatibleConstraintsError(Exception):
+ """
+ Exception when there are duplicate dependencies with incompatible constraints.
+ """
def __init__(
self, package: Package, *dependencies: Dependency, with_sources: bool = False
@@ -273,6 +276,12 @@ retu... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/puzzle/provider.py |
Add docstrings to improve readability | from __future__ import annotations
import csv
import functools
import itertools
import json
import threading
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import wait
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
from ... | --- +++ @@ -853,6 +853,9 @@ )
def _save_url_reference(self, operation: Operation) -> None:
+ """
+ Create and store a PEP-610 `direct_url.json` file, if needed.
+ """
if operation.job_type not in {"install", "update"}:
return
@@ -929,10 +932,18 @@ }
... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/installation/executor.py |
Create simple docstrings for beginners | from __future__ import annotations
import logging
import re
from functools import cached_property
from typing import TYPE_CHECKING
from typing import ClassVar
from poetry.core.constraints.version import Version
from poetry.core.packages.package import Package
from poetry.core.version.exceptions import InvalidVersion... | --- +++ @@ -102,6 +102,9 @@ yield from self._link_cache[name][version]
def clean_link(self, url: str) -> str:
+ """Makes sure a link is fully encoded. That is, if a ' ' shows up in
+ the link, it will be rewritten to %20 (while not over-quoting
+ % or other characters)."""
... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/repositories/link_sources/base.py |
Create docstrings for reusable components | from __future__ import annotations
import dataclasses
import hashlib
import json
import logging
import shutil
import threading
import time
from collections import defaultdict
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
from typing import Generic
from typing import TypeVar
from typ... | --- +++ @@ -39,6 +39,11 @@
def _expiration(minutes: int) -> int:
+ """
+ Calculates the time in seconds since epoch that occurs 'minutes' from now.
+
+ :param minutes: The number of minutes to count forward
+ """
return round(time.time()) + minutes * 60
@@ -51,17 +56,29 @@
@dataclasses.datacl... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/utils/cache.py |
Replace inline comments with docstrings | from __future__ import annotations
import contextlib
import logging
from typing import TYPE_CHECKING
from typing import Any
import requests
import requests.adapters
from cachecontrol.controller import logger as cache_control_logger
from poetry.core.packages.dependency import Dependency
from poetry.core.packages.pac... | --- +++ @@ -94,11 +94,20 @@ return results
def get_package_info(self, name: NormalizedName) -> dict[str, Any]:
+ """
+ Return the package information given its name.
+
+ The information is returned from the cache if it exists
+ or retrieved from the remote server.
+ """... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/repositories/pypi_repository.py |
Auto-generate documentation strings for this file | from __future__ import annotations
import urllib.parse
from collections import defaultdict
from functools import cached_property
from typing import TYPE_CHECKING
from typing import Any
from poetry.core.packages.utils.link import Link
from poetry.repositories.link_sources.base import LinkSource
from poetry.repositor... | --- +++ @@ -18,6 +18,7 @@
class SimpleJsonPage(LinkSource):
+ """Links as returned by PEP 691 compatible JSON-based Simple API."""
def __init__(self, url: str, content: dict[str, Any]) -> None:
super().__init__(url=url)
@@ -67,6 +68,13 @@
class SimpleRepositoryJsonRootPage(SimpleRepositoryRoo... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/repositories/link_sources/json.py |
Add docstrings to meet PEP guidelines | from __future__ import annotations
import contextlib
import os
import re
import subprocess
import sys
import sysconfig
from abc import ABC
from abc import abstractmethod
from functools import cached_property
from pathlib import Path
from subprocess import CalledProcessError
from typing import TYPE_CHECKING
from typin... | --- +++ @@ -55,6 +55,9 @@
class Env(ABC):
+ """
+ An abstract Python environment.
+ """
def __init__(self, path: Path, base: Path | None = None) -> None:
self._is_windows = sys.platform == "win32"
@@ -108,6 +111,9 @@
@property
def python(self) -> Path:
+ """
+ Path ... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/utils/env/base_env.py |
Provide clean and structured docstrings | from __future__ import annotations
import contextlib
import os
import sys
from functools import cached_property
from pathlib import Path
from typing import TYPE_CHECKING
from typing import NamedTuple
from typing import cast
from typing import overload
import findpython
import packaging.version
from cleo.io.null_io ... | --- +++ @@ -216,6 +216,21 @@
@classmethod
def get_active_python(cls) -> Python | None:
+ """
+ Fetches the active Python interpreter from available system paths or falls
+ back to finding the first valid Python executable named "python".
+
+ An "active Python interpreter" in this ... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/utils/env/python/manager.py |
Write documentation strings for class attributes | from __future__ import annotations
import dataclasses
import functools
import logging
from contextlib import suppress
from typing import TYPE_CHECKING
from poetry.config.config import Config
from poetry.utils.threading import atomic_cached_property
if TYPE_CHECKING:
import keyring.backend
from cleo.io.io ... | --- +++ @@ -43,6 +43,17 @@
@staticmethod
def preflight_check(io: IO | None = None, config: Config | None = None) -> None:
+ """
+ Performs a preflight check to determine the availability of the keyring service
+ and logs the status if verbosity is enabled. This method is used to validate... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/utils/password_manager.py |
Create simple docstrings for beginners | from __future__ import annotations
import json
import logging
import os
import re
import warnings
from hashlib import sha256
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Any
from typing import ClassVar
from typing import cast
from packaging.utils import canonicalize_name
from poetry.c... | --- +++ @@ -87,9 +87,15 @@ return self._lock_data
def is_locked(self) -> bool:
+ """
+ Checks whether the locker has been locked (lockfile found).
+ """
return self._lock.exists()
def is_fresh(self) -> bool:
+ """
+ Checks whether the lock file is still ... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/packages/locker.py |
Generate consistent documentation across files | from __future__ import annotations
import contextlib
import dataclasses
import logging
import os
import re
from pathlib import Path
from subprocess import CalledProcessError
from typing import TYPE_CHECKING
from urllib.parse import urljoin
from urllib.parse import urlparse
from urllib.parse import urlunparse
from du... | --- +++ @@ -95,10 +95,18 @@ ref: Ref = dataclasses.field(default_factory=lambda: Ref(b"HEAD"))
def resolve(self, remote_refs: FetchPackResult, repo: Repo) -> None:
+ """
+ Resolve the ref using the provided remote refs.
+ """
self._normalise(remote_refs=remote_refs, repo=repo)
... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/vcs/git/backend.py |
Add inline docstrings for readability | from __future__ import annotations
from abc import ABC
from abc import abstractmethod
class BasePlugin(ABC):
PLUGIN_API_VERSION = "1.0.0"
@property
@abstractmethod
def group(self) -> str: | --- +++ @@ -5,9 +5,17 @@
class BasePlugin(ABC):
+ """
+ Base class for all plugin types
+
+ The `activate()` method must be implemented and receives the Poetry instance.
+ """
PLUGIN_API_VERSION = "1.0.0"
@property
@abstractmethod
- def group(self) -> str:+ def group(self) -> st... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/plugins/base_plugin.py |
Generate docstrings for script automation | from __future__ import annotations
from contextlib import suppress
from functools import cached_property
from typing import TYPE_CHECKING
from typing import Any
import requests.adapters
from poetry.core.packages.package import Package
from poetry.inspection.info import PackageInfo
from poetry.repositories.exception... | --- +++ @@ -48,6 +48,17 @@ )
def package(self, name: str, version: Version) -> Package:
+ """
+ Retrieve the release information.
+
+ This is a heavy task which takes time.
+ We have to download a package to get the dependencies.
+ We also need to download every file ma... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/repositories/legacy_repository.py |
Create docstrings for each class method | # Copyright (c) Facebook, Inc. and its affiliates.
import logging
from typing import List, Optional, Tuple
from .config import CfgNode as CN
from .defaults import _C
__all__ = ["upgrade_config", "downgrade_config"]
def upgrade_config(cfg: CN, to_version: Optional[int] = None) -> CN:
cfg = cfg.clone()
if to... | --- +++ @@ -1,4 +1,25 @@ # Copyright (c) Facebook, Inc. and its affiliates.
+"""
+Backward compatibility of configs.
+
+Instructions to bump version:
++ It's not needed to bump version if new keys are added.
+ It's only needed when backward-incompatible changes happen
+ (i.e., some existing keys disappear, or the mea... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/config/compat.py |
Help me document legacy Python code | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
import functools
import inspect
import logging
from fvcore.common.config import CfgNode as _CfgNode
from detectron2.utils.file_io import PathManager
class CfgNode(_CfgNode):
@classmethod
def _open_cfg(cls, filename):
return ... | --- +++ @@ -10,6 +10,24 @@
class CfgNode(_CfgNode):
+ """
+ The same as `fvcore.common.config.CfgNode`, but different in:
+
+ 1. Use unsafe yaml loading by default.
+ Note that this may lead to arbitrary code execution: you must not
+ load a config file from untrusted sources before manually in... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/config/config.py |
Provide docstrings following PEP 257 | # Copyright (c) Facebook, Inc. and its affiliates.
import functools
import json
import logging
import multiprocessing as mp
import numpy as np
import os
from itertools import chain
import pycocotools.mask as mask_util
from PIL import Image
from detectron2.structures import BoxMode
from detectron2.utils.comm import get... | --- +++ @@ -51,6 +51,18 @@
def load_cityscapes_instances(image_dir, gt_dir, from_json=True, to_polygons=True):
+ """
+ Args:
+ image_dir (str): path to the raw dataset. e.g., "~/cityscapes/leftImg8bit/train".
+ gt_dir (str): path to the raw annotations. e.g., "~/cityscapes/gtFine/train".
+ ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/data/datasets/cityscapes.py |
Write documentation strings for class attributes | # Copyright (c) Facebook, Inc. and its affiliates.
import logging
import numpy as np
from itertools import count
from typing import List, Tuple
import torch
import tqdm
from fvcore.common.timer import Timer
from detectron2.utils import comm
from .build import build_batch_data_loader
from .common import DatasetFromLis... | --- +++ @@ -17,6 +17,9 @@
class _EmptyMapDataset(torch.utils.data.Dataset):
+ """
+ Map anything to emptiness.
+ """
def __init__(self, dataset):
self.ds = dataset
@@ -32,6 +35,15 @@ def iter_benchmark(
iterator, num_iter: int, warmup: int = 5, max_time_seconds: float = 60
) -> Tuple[... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/data/benchmark.py |
Add docstrings to incomplete code | # Copyright (c) Facebook, Inc. and its affiliates.
import copy
import logging
import numpy as np
from typing import List, Optional, Union
import torch
from detectron2.config import configurable
from . import detection_utils as utils
from . import transforms as T
"""
This file contains the default mapping that's appl... | --- +++ @@ -18,6 +18,21 @@
class DatasetMapper:
+ """
+ A callable which takes a dataset dict in Detectron2 Dataset format,
+ and map it into a format used by the model.
+
+ This is the default callable to be used to map your dataset dict into training data.
+ You may need to follow it to implement y... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/data/dataset_mapper.py |
Create documentation strings for testing functions | # Copyright (c) Facebook, Inc. and its affiliates.
import contextlib
import copy
import itertools
import logging
import numpy as np
import pickle
import random
from typing import Callable, Union
import torch
import torch.utils.data as data
from torch.utils.data.sampler import Sampler
from detectron2.utils.serialize im... | --- +++ @@ -20,6 +20,7 @@
# copied from: https://docs.python.org/3/library/itertools.html#recipes
def _roundrobin(*iterables):
+ "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
num_active = len(iterables)
nexts = itertools.cycle(iter(it).__next__ for it in iterable... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/data/common.py |
Create simple docstrings for beginners | from __future__ import annotations
import base64
import hashlib
import os
import plistlib
import re
import subprocess
import sys
from functools import cached_property
from pathlib import Path
from subprocess import CalledProcessError
from typing import TYPE_CHECKING
import tomlkit
import virtualenv
from cleo.io.nul... | --- +++ @@ -46,8 +46,31 @@
class EnvsFile(TOMLFile):
+ """
+ This file contains one section per project with the project's base env name
+ as section name. Each section contains the minor and patch version of the
+ python executable used to create the currently active virtualenv.
+
+ Example:
+
+ ... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/utils/env/env_manager.py |
Add documentation for all methods | from __future__ import annotations
import hashlib
import io
import logging
import os
import shutil
import stat
import sys
import tarfile
import tempfile
import zipfile
from collections.abc import Mapping
from contextlib import contextmanager
from contextlib import suppress
from functools import cached_property
from p... | --- +++ @@ -99,6 +99,13 @@
def remove_directory(path: Path, force: bool = False) -> None:
+ """
+ Helper function handle safe removal, and optionally forces stubborn file removal.
+ This is particularly useful when dist files are read-only or git writes read-only
+ files on Windows.
+
+ Internally, a... | https://raw.githubusercontent.com/python-poetry/poetry/HEAD/src/poetry/utils/helpers.py |
Help me document legacy Python code | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
import argparse
import logging
import os
import sys
import weakref
from collections import OrderedDict
from typing import Optional
import torch
from fvcore.nn.precise_bn import get_bn_modules
from omegaconf import OmegaConf
from torch.nn.paral... | --- +++ @@ -1,6 +1,13 @@ # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
+"""
+This file contains components with some default boilerplate logic user may need
+in training / testing. They will not work for everyone, but many users may find them useful.
+
+The behavior of functions/classes ... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/engine/defaults.py |
Add docstrings that explain purpose and usage | # Copyright (c) Facebook, Inc. and its affiliates.
import copy
import logging
import types
from collections import UserDict
from typing import List
from detectron2.utils.logger import log_first_n
__all__ = ["DatasetCatalog", "MetadataCatalog", "Metadata"]
class _DatasetCatalog(UserDict):
def register(self, nam... | --- +++ @@ -11,13 +11,42 @@
class _DatasetCatalog(UserDict):
+ """
+ A global dictionary that stores information about the datasets and how to obtain them.
+
+ It contains a mapping from strings
+ (which are names that identify a dataset, e.g. "coco_2014_train")
+ to a function which parses the datas... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/data/catalog.py |
Generate descriptive docstrings automatically | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
import inspect
import numpy as np
import pprint
from typing import Any, List, Optional, Tuple, Union
from fvcore.transforms.transform import Transform, TransformList
"""
See "Data Augmentation" tutorial for an overview of the system:
https://d... | --- +++ @@ -37,6 +37,9 @@
def _get_aug_input_args(aug, aug_input) -> List[Any]:
+ """
+ Get the arguments to be passed to ``aug.get_transform`` from the input ``aug_input``.
+ """
if aug.input_args is None:
# Decide what attributes are needed automatically
prms = list(inspect.signatu... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/data/transforms/augmentation.py |
Document functions with clear intent | # Copyright (c) Facebook, Inc. and its affiliates.
import itertools
import logging
import numpy as np
import operator
import pickle
from collections import OrderedDict, defaultdict
from typing import Any, Callable, Dict, List, Optional, Union
import torch
import torch.utils.data as torchdata
from tabulate import tabula... | --- +++ @@ -44,6 +44,17 @@
def filter_images_with_only_crowd_annotations(dataset_dicts):
+ """
+ Filter out images with none annotations or only crowd annotations
+ (i.e., images without non-crowd annotations).
+ A common training-time preprocessing on COCO dataset.
+
+ Args:
+ dataset_dicts (... | https://raw.githubusercontent.com/facebookresearch/detectron2/HEAD/detectron2/data/build.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.