instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Add docstrings for better understanding | from __future__ import annotations
import sqlalchemy
import traceback
from . import requester
from ...core import app
from ...discover import engine
from . import token
from ...entity.persistence import model as persistence_model
from ...entity.errors import provider as provider_errors
from async_lru import alru_cach... | --- +++ @@ -13,6 +13,7 @@
class ModelManager:
+ """Model manager"""
ap: app.Application
@@ -58,6 +59,7 @@ self.ap.logger.warning(f' - Error: {e}')
async def load_models_from_db(self):
+ """Load models from database"""
self.ap.logger.info('Loading models from db...')
... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/provider/modelmgr/modelmgr.py |
Document my Python code with docstrings | from __future__ import annotations
import asyncio
import typing
import openai
import openai.types.chat.chat_completion as chat_completion_module
import httpx
from .. import errors, requester
import langbot_plugin.api.entities.builtin.resource.tool as resource_tool
import langbot_plugin.api.entities.builtin.pipeline.... | --- +++ @@ -14,6 +14,7 @@
class OpenAIChatCompletions(requester.ProviderAPIRequester):
+ """OpenAI ChatCompletion API 请求器"""
client: openai.AsyncClient
@@ -83,6 +84,16 @@ reasoning_content: str = None,
remove_think: bool = False,
) -> tuple[str, str]:
+ """处理思维链内容
+
+ ... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/provider/modelmgr/requesters/chatcmpl.py |
Help me add docstrings to my project | from __future__ import annotations
import typing
from .. import requester
REQUESTER_NAME: str = 'seekdb-embedding'
class SeekDBEmbedding(requester.ProviderAPIRequester):
default_config: dict[str, typing.Any] = {
'base_url': '',
}
_embedding_function = None
async def initialize(self):
... | --- +++ @@ -8,6 +8,11 @@
class SeekDBEmbedding(requester.ProviderAPIRequester):
+ """SeekDB built-in embedding requester.
+
+ Uses pyseekdb's local embedding function (all-MiniLM-L6-v2).
+ The base_url config is reserved for future remote embedding support.
+ """
default_config: dict[str, typing.... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/provider/modelmgr/requesters/seekdbembed.py |
Document all public functions with docstrings | from __future__ import annotations
import typing
import json
import uuid
import aiohttp
from langbot.pkg.utils import httpclient
from .. import runner
from ...core import app
import langbot_plugin.api.entities.builtin.pipeline.query as pipeline_query
import langbot_plugin.api.entities.builtin.provider.message as pro... | --- +++ @@ -14,6 +14,7 @@
class N8nAPIError(Exception):
+ """N8n API 请求失败"""
def __init__(self, message: str):
self.message = message
@@ -22,6 +23,7 @@
@runner.runner_class('n8n-service-api')
class N8nServiceAPIRunner(runner.RequestRunner):
+ """N8n Service API 工作流请求器"""
def __init__... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/provider/runners/n8nsvapi.py |
Add standardized docstrings across the file | from __future__ import annotations
import typing
import json
import httpx
import uuid
import traceback
from .. import runner
from ...core import app
import langbot_plugin.api.entities.builtin.pipeline.query as pipeline_query
import langbot_plugin.api.entities.builtin.provider.message as provider_message
@runner.run... | --- +++ @@ -14,12 +14,21 @@
@runner.runner_class('langflow-api')
class LangflowAPIRunner(runner.RequestRunner):
+ """Langflow API 对话请求器"""
def __init__(self, ap: app.Application, pipeline_config: dict):
self.ap = ap
self.pipeline_config = pipeline_config
async def _build_request_pa... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/provider/runners/langflowapi.py |
Insert docstrings into my code | from __future__ import annotations
import json
import copy
import typing
from .. import runner
from ..modelmgr import requester as modelmgr_requester
import langbot_plugin.api.entities.builtin.pipeline.query as pipeline_query
import langbot_plugin.api.entities.builtin.provider.message as provider_message
import langbo... | --- +++ @@ -27,11 +27,13 @@
@runner.runner_class('local-agent')
class LocalAgentRunner(runner.RequestRunner):
+ """Local agent request runner"""
async def _get_model_candidates(
self,
query: pipeline_query.Query,
) -> list[modelmgr_requester.RuntimeLLMModel]:
+ """Build ordere... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/provider/runners/localagent.py |
Add docstrings with type hints explained | from __future__ import annotations
import mimetypes
import os.path
import traceback
import uuid
import zipfile
import io
from typing import Any
from langbot.pkg.core import app
import sqlalchemy
from langbot.pkg.entity.persistence import rag as persistence_rag
from langbot.pkg.core import taskmgr
from langbot_plugin.... | --- +++ @@ -140,6 +140,7 @@ return wrapper.id
async def _store_zip_file(self, zip_file_id: str, parser_plugin_id: str | None = None) -> str:
+ """Handle ZIP file by extracting each document and storing them separately."""
self.ap.logger.info(f'Processing ZIP file: {zip_file_id}')
... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/rag/knowledge/kbmgr.py |
Create simple docstrings for beginners |
from __future__ import annotations
import abc
from langbot.pkg.core import app
from langbot_plugin.api.entities.builtin.rag import context as rag_context
class KnowledgeBaseInterface(metaclass=abc.ABCMeta):
ap: app.Application
def __init__(self, ap: app.Application):
self.ap = ap
@abc.abstra... | --- +++ @@ -1,3 +1,4 @@+"""Base classes and interfaces for knowledge bases"""
from __future__ import annotations
@@ -8,6 +9,7 @@
class KnowledgeBaseInterface(metaclass=abc.ABCMeta):
+ """Abstract interface for all knowledge base types"""
ap: app.Application
@@ -16,24 +18,38 @@
@abc.abstractme... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/rag/knowledge/base.py |
Annotate my code with docstrings | from __future__ import annotations
import posixpath
from typing import Any
from langbot.pkg.core import app
class RAGRuntimeService:
def __init__(self, ap: app.Application):
self.ap = ap
async def vector_upsert(
self,
collection_id: str,
vectors: list[list[float]],
i... | --- +++ @@ -6,6 +6,11 @@
class RAGRuntimeService:
+ """Service to handle RAG-related requests from plugins (Runtime).
+
+ This service acts as the bridge between plugin RPC requests and
+ LangBot's infrastructure (embedding models, vector databases, file storage).
+ """
def __init__(self, ap: app... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/rag/service/runtime.py |
Create docstrings for each class method | from __future__ import annotations
import enum
import typing
from contextlib import AsyncExitStack
import traceback
from langbot_plugin.api.entities.events import pipeline_query
import sqlalchemy
import asyncio
import httpx
import uuid as uuid_module
from mcp import ClientSession, StdioServerParameters
from mcp.clien... | --- +++ @@ -29,6 +29,7 @@
class RuntimeMCPSession:
+ """运行时 MCP 会话"""
ap: app.Application
@@ -124,6 +125,7 @@ await self.session.initialize()
async def _lifecycle_loop(self):
+ """在后台任务中管理整个MCP会话的生命周期"""
try:
if self.server_config['mode'] == 'stdio':
... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/provider/tools/loaders/mcp.py |
Add docstrings to existing functions | from __future__ import annotations
import typing
import json
import uuid
import base64
import mimetypes
from langbot.pkg.provider import runner
from langbot.pkg.core import app
import langbot_plugin.api.entities.builtin.provider.message as provider_message
from langbot.pkg.utils import image
import langbot_plugin.ap... | --- +++ @@ -18,6 +18,7 @@
@runner.runner_class('dify-service-api')
class DifyServiceAPIRunner(runner.RequestRunner):
+ """Dify Service API 对话请求器"""
dify_client: client.AsyncDifyServiceClient
@@ -42,6 +43,13 @@ self,
content: str,
) -> tuple[str, str]:
+ """处理思维链内容
+
+ ... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/provider/runners/difysvapi.py |
Add detailed documentation for each class | from __future__ import annotations
import typing
import re
import dashscope
from .. import runner
from ...core import app
import langbot_plugin.api.entities.builtin.pipeline.query as pipeline_query
import langbot_plugin.api.entities.builtin.provider.message as provider_message
class DashscopeAPIError(Exception):
... | --- +++ @@ -12,6 +12,7 @@
class DashscopeAPIError(Exception):
+ """Dashscope API 请求失败"""
def __init__(self, message: str):
self.message = message
@@ -20,6 +21,7 @@
@runner.runner_class('dashscope-app-api')
class DashScopeAPIRunner(runner.RequestRunner):
+ "阿里云百炼DashsscopeAPI对话请求器"
# ... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/provider/runners/dashscopeapi.py |
Document classes and their methods | from __future__ import annotations
import boto3
from botocore.exceptions import ClientError
from ...core import app
from .. import provider
class S3StorageProvider(provider.StorageProvider):
def __init__(self, ap: app.Application):
super().__init__(ap)
self.s3_client = None
self.bucket_... | --- +++ @@ -8,6 +8,7 @@
class S3StorageProvider(provider.StorageProvider):
+ """S3 object storage provider"""
def __init__(self, ap: app.Application):
super().__init__(ap)
@@ -15,6 +16,7 @@ self.bucket_name = None
async def initialize(self):
+ """Initialize S3 client with co... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/storage/providers/s3storage.py |
Write clean docstrings for readability |
from __future__ import annotations
import aiohttp
_sessions: dict[str, aiohttp.ClientSession] = {}
def get_session(*, trust_env: bool = False) -> aiohttp.ClientSession:
key = f'trust_env={trust_env}'
session = _sessions.get(key)
if session is None or session.closed:
session = aiohttp.ClientSes... | --- +++ @@ -1,3 +1,13 @@+"""Shared aiohttp.ClientSession to avoid repeated SSL context creation.
+
+Each call to `aiohttp.ClientSession()` creates a new `TCPConnector` which in turn
+creates a new `ssl.SSLContext` and loads all system root certificates. This is
+extremely expensive in both CPU and memory (~270MB total ... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/utils/httpclient.py |
Help me write clear docstrings | import base64
import typing
import io
from urllib.parse import urlparse, parse_qs
import ssl
import aiohttp
from langbot.pkg.utils import httpclient
import PIL.Image
import httpx
import asyncio
async def get_gewechat_image_base64(
gewechat_url: str,
gewechat_file_url: str,
app_id: str,
xml_content:... | --- +++ @@ -21,6 +21,23 @@ token: str,
image_type: int = 2,
) -> typing.Tuple[str, str]:
+ """从gewechat服务器获取图片并转换为base64格式
+
+ Args:
+ gewechat_url (str): gewechat服务器地址(用于获取图片URL)
+ gewechat_file_url (str): gewechat文件下载服务地址
+ app_id (str): gewechat应用ID
+ xml_content (str): 图片... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/utils/image.py |
Add professional docstrings to my codebase |
from __future__ import annotations
import asyncio
import json
import typing
import httpx
import sqlalchemy
from ..core import app as core_app
from ..entity.persistence.metadata import Metadata
from ..utils import constants
SURVEY_TRIGGERED_KEY = 'survey_triggered_events'
class SurveyManager:
def __init__(sel... | --- +++ @@ -1,3 +1,4 @@+"""Survey manager: tracks events, communicates with Space to fetch/submit surveys."""
from __future__ import annotations
@@ -15,6 +16,7 @@
class SurveyManager:
+ """Manages survey lifecycle: event tracking, pending survey fetch, submission."""
def __init__(self, ap: core_app.A... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/survey/manager.py |
Write docstrings for utility functions |
import os
from pathlib import Path
_is_source_install = None
def _check_if_source_install() -> bool:
global _is_source_install
if _is_source_install is not None:
return _is_source_install
# Check if main.py exists in current directory with LangBot marker
if os.path.exists('main.py'):
... | --- +++ @@ -1,3 +1,4 @@+"""Utility functions for finding package resources"""
import os
from pathlib import Path
@@ -7,6 +8,10 @@
def _check_if_source_install() -> bool:
+ """
+ Check if we're running from source directory or an installed package.
+ Cached to avoid repeated file I/O.
+ """
glob... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/utils/paths.py |
Create documentation strings for testing functions | from __future__ import annotations
from ..core import app
from .vdb import VectorDatabase, SearchType
from .vdbs.chroma import ChromaVectorDatabase
from .vdbs.qdrant import QdrantVectorDatabase
from .vdbs.seekdb import SeekDBVectorDatabase
from .vdbs.milvus import MilvusVectorDatabase
from .vdbs.pgvector_db import PgV... | --- +++ @@ -67,6 +67,7 @@ self.ap.logger.warning('No vector database backend configured, defaulting to Chroma.')
def get_supported_search_types(self) -> list[str]:
+ """Return the search types supported by the current VDB backend."""
if self.vector_db is None:
return [Sea... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/vector/mgr.py |
Help me write clear docstrings | from __future__ import annotations
import asyncio
import httpx
from ..core import app as core_app
class TelemetryManager:
send_tasks: list[asyncio.Task] = []
def __init__(self, ap: core_app.Application):
self.ap = ap
self.telemetry_config = {}
async def initialize(self):
self.... | --- +++ @@ -6,6 +6,12 @@
class TelemetryManager:
+ """TelemetryManager handles sending telemetry for a given application instance.
+
+ Usage:
+ telemetry = TelemetryManager(ap)
+ await telemetry.send({ ... })
+ """
send_tasks: list[asyncio.Task] = []
@@ -22,6 +28,15 @@ self.s... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/telemetry/telemetry.py |
Create docstrings for API functions |
from __future__ import annotations
import logging
from typing import Any
SUPPORTED_OPS = frozenset({'$eq', '$ne', '$gt', '$gte', '$lt', '$lte', '$in', '$nin'})
logger = logging.getLogger(__name__)
def normalize_filter(
raw: dict[str, Any] | None,
) -> list[tuple[str, str, Any]]:
if not raw:
return... | --- +++ @@ -1,3 +1,15 @@+"""Shared utilities for metadata filter handling across VDB backends.
+
+Canonical filter format (Chroma-style ``where`` syntax):
+
+ {"file_id": "abc"} # implicit $eq
+ {"file_id": {"$eq": "abc"}} # explicit $eq
+ {"created_at": {"$gte": 1700000000}} ... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/vector/filter_utils.py |
Write docstrings for this repository | from __future__ import annotations
import abc
import enum
from typing import Any, Dict
import numpy as np
class SearchType(str, enum.Enum):
VECTOR = 'vector'
FULL_TEXT = 'full_text'
HYBRID = 'hybrid'
class VectorDatabase(abc.ABC):
@classmethod
def supported_search_types(cls) -> list[SearchType]... | --- +++ @@ -6,6 +6,7 @@
class SearchType(str, enum.Enum):
+ """Supported search types for vector databases."""
VECTOR = 'vector'
FULL_TEXT = 'full_text'
@@ -15,6 +16,11 @@ class VectorDatabase(abc.ABC):
@classmethod
def supported_search_types(cls) -> list[SearchType]:
+ """Return the... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/vector/vdb.py |
Write proper docstrings for these functions | from __future__ import annotations
from typing import Any, Dict
from sqlalchemy import create_engine, text, Column, String, Text
from sqlalchemy.orm import declarative_base
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from pgvector.sqlalchemy import Vector
from langbot.pkg.ve... | --- +++ @@ -25,6 +25,7 @@
class PgVectorEntry(Base):
+ """SQLAlchemy model for pgvector entries"""
__tablename__ = 'langbot_vectors'
@@ -37,6 +38,7 @@
def _build_pg_conditions(filter_dict: dict[str, Any]) -> list:
+ """Translate canonical filter dict into a list of SQLAlchemy conditions."""
... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/vector/vdbs/pgvector_db.py |
Document all endpoints with docstrings | from __future__ import annotations
import typing
import asyncio
import json
import base64
import zlib
import traceback
import time
import aiohttp
from langbot.pkg.utils import httpclient
import websockets
import pydantic
import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter
imp... | --- +++ @@ -22,9 +22,18 @@
class KookMessageConverter(abstract_platform_adapter.AbstractMessageConverter):
+ """Convert between LangBot MessageChain and KOOK message format"""
@staticmethod
async def yiri2target(message_chain: platform_message.MessageChain) -> tuple[str, int]:
+ """
+ C... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/platform/sources/kook.py |
Add standardized docstrings across the file | from __future__ import annotations
import asyncio
from typing import Any, Dict, List
from langbot.pkg.core import app
from langbot.pkg.vector.vdb import VectorDatabase, SearchType
try:
import pyseekdb
from pyseekdb import HNSWConfiguration
SEEKDB_AVAILABLE = True
except ImportError:
SEEKDB_AVAILABL... | --- +++ @@ -20,6 +20,13 @@
class SeekDBVectorDatabase(VectorDatabase):
+ """SeekDB vector database adapter for LangBot.
+
+ SeekDB is an AI-native search database by OceanBase that unifies
+ relational, vector, text, JSON and GIS in a single engine.
+
+ Supports embedded mode, remote server mode, and fu... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/vector/vdbs/seekdb.py |
Write proper docstrings for these functions | from __future__ import annotations
import discord
import typing
import re
import base64
import uuid
import os
import datetime
# 使用BytesIO创建文件对象,避免路径问题
import io
import asyncio
from enum import Enum
from langbot.pkg.utils import httpclient
import pydantic
import langbot_plugin.api.definition.abstract.platform.adapt... | --- +++ @@ -27,6 +27,7 @@
# 语音功能相关异常定义
class VoiceConnectionError(Exception):
+ """语音连接基础异常"""
def __init__(self, message: str, error_code: str = None, guild_id: int = None):
super().__init__(message)
@@ -36,6 +37,7 @@
class VoicePermissionError(VoiceConnectionError):
+ """语音权限异常"""
... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/platform/sources/discord.py |
Write proper docstrings for these functions | import ollama
from config import get_ollama_base_url
_selected_model: str | None = None
def _client() -> ollama.Client:
return ollama.Client(host=get_ollama_base_url())
def list_models() -> list[str]:
response = _client().list()
return sorted(m.model for m in response.models)
def select_model(model:... | --- +++ @@ -10,20 +10,45 @@
def list_models() -> list[str]:
+ """
+ Lists all models available on the local Ollama server.
+
+ Returns:
+ models (list[str]): Sorted list of model names.
+ """
response = _client().list()
return sorted(m.model for m in response.models)
def select_mod... | https://raw.githubusercontent.com/FujiwaraChoki/MoneyPrinterV2/HEAD/src/llm_provider.py |
Write docstrings that follow conventions |
import asyncio
import logging
import typing
from datetime import datetime
import pydantic
import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter
import langbot_plugin.api.entities.builtin.platform.message as platform_message
import langbot_plugin.api.entities.builtin.platform.eve... | --- +++ @@ -1,3 +1,4 @@+"""WebSocket适配器 - 支持双向通信的IM系统"""
import asyncio
import logging
@@ -18,6 +19,7 @@
class WebSocketMessage(pydantic.BaseModel):
+ """WebSocket消息格式"""
id: int
role: str # 'user' or 'assistant'
@@ -30,6 +32,7 @@
class WebSocketSession:
+ """WebSocket会话 - 管理单个会话的消息历史"""
... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/platform/sources/websocket_adapter.py |
Write docstrings that follow conventions | from __future__ import annotations
import typing
import time
import datetime
import json
import asyncio
import traceback
import re
import base64
import aiohttp
import pydantic
import websockets
import langbot_plugin.api.definition.abstract.platform.adapter as abstract_platform_adapter
import langbot_plugin.api.entit... | --- +++ @@ -1,1039 +1,1090 @@-from __future__ import annotations
-
-import typing
-import time
-import datetime
-import json
-import asyncio
-import traceback
-import re
-import base64
-
-import aiohttp
-import pydantic
-import websockets
-
-import langbot_plugin.api.definition.abstract.platform.adapter as abstract_pla... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/platform/sources/satori.py |
Add docstrings for better understanding | from __future__ import annotations
import typing
import json
import base64
from langbot.pkg.provider import runner
from langbot.pkg.core import app
import langbot_plugin.api.entities.builtin.provider.message as provider_message
from langbot.pkg.utils import image
import langbot_plugin.api.entities.builtin.pipeline.qu... | --- +++ @@ -14,6 +14,7 @@
@runner.runner_class('coze-api')
class CozeAPIRunner(runner.RequestRunner):
+ """Coze API 对话请求器"""
def __init__(self, ap: app.Application, pipeline_config: dict):
self.pipeline_config = pipeline_config
@@ -30,6 +31,13 @@ self,
content: str,
) -> tupl... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/provider/runners/cozeapi.py |
Add docstrings to improve readability |
import asyncio
import logging
import typing
import uuid
from datetime import datetime
import pydantic
logger = logging.getLogger(__name__)
class WebSocketConnection(pydantic.BaseModel):
model_config = pydantic.ConfigDict(arbitrary_types_allowed=True)
connection_id: str = pydantic.Field(default_factory=la... | --- +++ @@ -1,3 +1,4 @@+"""WebSocket连接管理器 - 管理多个并发WebSocket连接"""
import asyncio
import logging
@@ -11,6 +12,7 @@
class WebSocketConnection(pydantic.BaseModel):
+ """单个WebSocket连接"""
model_config = pydantic.ConfigDict(arbitrary_types_allowed=True)
@@ -43,6 +45,7 @@
class WebSocketConnectionManage... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/platform/sources/websocket_manager.py |
Create simple docstrings for beginners | from __future__ import annotations
import asyncio
from typing import Any, Dict
from pymilvus import MilvusClient, DataType, CollectionSchema, FieldSchema
from pymilvus.milvus_client.index import IndexParams
from langbot.pkg.vector.vdb import VectorDatabase
from langbot.pkg.vector.filter_utils import normalize_filter, s... | --- +++ @@ -16,6 +16,7 @@
def _build_milvus_expr(filter_dict: dict[str, Any]) -> str:
+ """Translate canonical filter dict into a Milvus boolean expression string."""
triples = normalize_filter(filter_dict)
triples = strip_unsupported_fields(triples, _MILVUS_SUPPORTED_FIELDS, _MILVUS_FIELD_ALIASES)
... | https://raw.githubusercontent.com/langbot-app/LangBot/HEAD/src/langbot/pkg/vector/vdbs/milvus.py |
Write docstrings for backend logic | import os
import json
from typing import List
from config import ROOT_DIR
def get_cache_path() -> str:
return os.path.join(ROOT_DIR, '.mp')
def get_afm_cache_path() -> str:
return os.path.join(get_cache_path(), 'afm.json')
def get_twitter_cache_path() -> str:
return os.path.join(get_cache_path(), 'twitt... | --- +++ @@ -5,18 +5,54 @@ from config import ROOT_DIR
def get_cache_path() -> str:
+ """
+ Gets the path to the cache file.
+
+ Returns:
+ path (str): The path to the cache folder
+ """
return os.path.join(ROOT_DIR, '.mp')
def get_afm_cache_path() -> str:
+ """
+ Gets the path to the... | https://raw.githubusercontent.com/FujiwaraChoki/MoneyPrinterV2/HEAD/src/cache.py |
Generate docstrings with parameter types | import os
from urllib.parse import urlparse
from typing import Any
from status import *
from config import *
from constants import *
from llm_provider import generate_text
from .Twitter import Twitter
from selenium_firefox import *
from selenium import webdriver
from selenium.webdriver.common.by import By
from seleniu... | --- +++ @@ -16,6 +16,9 @@
class AffiliateMarketing:
+ """
+ This class will be used to handle all the affiliate marketing related operations.
+ """
def __init__(
self,
@@ -25,6 +28,19 @@ account_nickname: str,
topic: str,
) -> None:
+ """
+ Initializes th... | https://raw.githubusercontent.com/FujiwaraChoki/MoneyPrinterV2/HEAD/src/classes/AFM.py |
Generate docstrings for script automation | import re
import sys
import time
import os
import json
from cache import *
from config import *
from status import *
from llm_provider import generate_text
from typing import List, Optional
from datetime import datetime
from termcolor import colored
from selenium_firefox import *
from selenium import webdriver
from se... | --- +++ @@ -22,10 +22,24 @@
class Twitter:
+ """
+ Class for the Bot, that grows a Twitter account.
+ """
def __init__(
self, account_uuid: str, account_nickname: str, fp_profile_path: str, topic: str
) -> None:
+ """
+ Initializes the Twitter Bot.
+
+ Args:
+ ... | https://raw.githubusercontent.com/FujiwaraChoki/MoneyPrinterV2/HEAD/src/classes/Twitter.py |
Write docstrings for data processing functions | import os
import io
import re
import csv
import time
import glob
import shlex
import zipfile
import yagmail
import requests
import subprocess
import platform
from cache import *
from status import *
from config import *
class Outreach:
def __init__(self) -> None:
# Check if go is installed
self.... | --- +++ @@ -17,8 +17,17 @@
class Outreach:
+ """
+ Class that houses the methods to reach out to businesses.
+ """
def __init__(self) -> None:
+ """
+ Constructor for the Outreach class.
+
+ Returns:
+ None
+ """
# Check if go is installed
sel... | https://raw.githubusercontent.com/FujiwaraChoki/MoneyPrinterV2/HEAD/src/classes/Outreach.py |
Document this module using docstrings | import os
import random
import zipfile
import requests
import platform
from status import *
from config import *
DEFAULT_SONG_ARCHIVE_URLS = []
def close_running_selenium_instances() -> None:
try:
info(" => Closing running Selenium instances...")
# Kill all running Firefox instances
if ... | --- +++ @@ -11,6 +11,12 @@
def close_running_selenium_instances() -> None:
+ """
+ Closes any running Selenium instances.
+
+ Returns:
+ None
+ """
try:
info(" => Closing running Selenium instances...")
@@ -27,10 +33,25 @@
def build_url(youtube_video_id: str) -> str:
+ """
... | https://raw.githubusercontent.com/FujiwaraChoki/MoneyPrinterV2/HEAD/src/utils.py |
Document helper functions with docstrings | import os
import sys
import json
import srt_equalizer
from termcolor import colored
ROOT_DIR = os.path.dirname(sys.path[0])
def assert_folder_structure() -> None:
# Create the .mp folder
if not os.path.exists(os.path.join(ROOT_DIR, ".mp")):
if get_verbose():
print(colored(f"=> Creating .m... | --- +++ @@ -8,6 +8,12 @@ ROOT_DIR = os.path.dirname(sys.path[0])
def assert_folder_structure() -> None:
+ """
+ Make sure that the nessecary folder structure is present.
+
+ Returns:
+ None
+ """
# Create the .mp folder
if not os.path.exists(os.path.join(ROOT_DIR, ".mp")):
if ge... | https://raw.githubusercontent.com/FujiwaraChoki/MoneyPrinterV2/HEAD/src/config.py |
Add docstrings to make code maintainable | import re
import base64
import json
import time
import os
import requests
import assemblyai as aai
from utils import *
from cache import *
from .Tts import TTS
from llm_provider import generate_text
from config import *
from status import *
from uuid import uuid4
from constants import *
from typing import List
from mo... | --- +++ @@ -33,6 +33,19 @@
class YouTube:
+ """
+ Class for YouTube Automation.
+
+ Steps to create a YouTube Short:
+ 1. Generate a topic [DONE]
+ 2. Generate a script [DONE]
+ 3. Generate metadata (Title, Description, Tags) [DONE]
+ 4. Generate AI Image Prompts [DONE]
+ 4. Generate Images ... | https://raw.githubusercontent.com/FujiwaraChoki/MoneyPrinterV2/HEAD/src/classes/YouTube.py |
Add detailed documentation for each class | from termcolor import colored
def error(message: str, show_emoji: bool = True) -> None:
emoji = "❌" if show_emoji else ""
print(colored(f"{emoji} {message}", "red"))
def success(message: str, show_emoji: bool = True) -> None:
emoji = "✅" if show_emoji else ""
print(colored(f"{emoji} {message}", "green... | --- +++ @@ -1,21 +1,71 @@ from termcolor import colored
def error(message: str, show_emoji: bool = True) -> None:
+ """
+ Prints an error message.
+
+ Args:
+ message (str): The error message
+ show_emoji (bool): Whether to show the emoji
+
+ Returns:
+ None
+ """
emoji = "❌"... | https://raw.githubusercontent.com/FujiwaraChoki/MoneyPrinterV2/HEAD/src/status.py |
Document all endpoints with docstrings | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -138,6 +138,14 @@ return flags + standard + specific
def get_readable_ntace_flags(self):
+ """
+ Return the NTACE flags in readable format
+ (OI) - object inherit
+ (CI) - container inherit
+ (IO) - inherit only
+ (NP) - don't propagate inherit
+ ... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/acl.py |
Create documentation for each function signature | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -55,35 +55,50 @@ return repr(self.value)
class PacketBuffer(object):
+ """Implement the basic operations utilized to operate on a
+ packet's raw buffer. All the packet classes derive from this one.
+
+ The byte, word, long and ip_address getters and setters accept
+ negative indexes, h... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/ImpactPacket.py |
Can you add docstrings to this Python file? | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -199,17 +199,20 @@ return self.__remoteName
def setRemoteName(self, remoteName):
+ """This method only makes sense before connection for most protocols."""
self.__remoteName = remoteName
def getRemoteHost(self):
return self.__remoteHost
def setRemoteHost(... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/dcerpc/v5/transport.py |
Add docstrings that explain logic | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
im... | --- +++ @@ -8,6 +8,7 @@ # of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
+"""Python Enumerations"""
import sys as _sys
@@ -26,6 +27,14 @@
class _RouteClassAttributeToGetattr(object):
+ """Route attribute access on a class to __getattr__.
+
+ This is a descri... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/dcerpc/v5/enum.py |
Add structured docstrings to improve clarity | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -20,6 +20,7 @@ DOT1X_AUTHENTICATION = 0x888E
class EAPExpanded(ProtocolPacket):
+ """EAP expanded data according to RFC 3748, section 5.7"""
WFA_SMI = 0x00372a
SIMPLE_CONFIG = 0x00000001
@@ -31,6 +32,7 @@ vendor_type = Long(3, ">")
class EAPR(ProtocolPacket):
+ """It represent... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/eap.py |
Generate docstrings for each module | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -39,6 +39,7 @@
class DNSFlags():
+ 'Bitmap with the flags of a dns packet.'
# QR - Query/Response - 1 bit
QR_QUERY = int("0000000000000000", 2)
QR_RESPONSE = int("1000000000000000", 2)
@@ -176,6 +177,8 @@ return item
class DNS(ProtocolPacket... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/dns.py |
Create documentation for each function signature | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -460,6 +460,15 @@ return string
def hRpcAsyncClosePrinter(dce, phPrinter):
+ """
+ RpcClosePrinter closes a handle to a printer object, server object, job object, or port object.
+ Full Documentation: https://msdn.microsoft.com/en-us/library/cc244768.aspx
+
+ :param DCERPC_v5 dce: a co... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/dcerpc/v5/par.py |
Generate docstrings for this script | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -1001,7 +1001,17 @@ MSRPC_STANDARD_NDR_SYNTAX = ('8A885D04-1CEB-11C9-9FE8-08002B104860', '2.0')
class DCERPCException(Exception):
+ """
+ This is the exception every client should catch regardless of the underlying
+ DCERPC Transport used.
+ """
def __init__(self, error_string=None, error... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/dcerpc/v5/rpcrt.py |
Create documentation for each function signature | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -302,10 +302,12 @@ self.load_packet(aBuffer)
def get_order(self):
+ "Return 802.11 frame 'Order' field"
b = self.header.get_byte(1)
return ((b >> 7) & 0x01)
def set_order(self, value):
+ "Set 802.11 frame 'Order' field"
# clear the bi... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/dot11.py |
Expand my code with proper documentation strings | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -491,6 +491,23 @@ return string
def hRpcOpenPrinter(dce, printerName, pDatatype = NULL, pDevModeContainer = NULL, accessRequired = SERVER_READ):
+ """
+ RpcOpenPrinter retrieves a handle for a printer, port, port monitor, print job, or print server.
+ Full Documentation: https://msdn.micr... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/dcerpc/v5/rprn.py |
Write clean docstrings for readability | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -187,6 +187,17 @@
# 2.2.2.15.1.1 TS_UNICODE_STRING
class TS_UNICODE_STRING(NDRSTRUCT):
+ '''
+ typedef struct _TS_UNICODE_STRING {
+ USHORT Length;
+ USHORT MaximumLength;
+ #ifdef __midl
+ [size_is(MaximumLength),length_is(Length)]PWSTR Buffer;
+ #else
+ ... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/dcerpc/v5/tsts.py |
Add concise docstrings to each method | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# A... | --- +++ @@ -165,6 +165,15 @@ ################################################################################
def encode_name(name, nametype, scope):
# ToDo: Rewrite this simpler, we're using less than written
+ """
+ Perform first and second level encoding of name as specified in RFC 1001 (Section 4)
+ ... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/nmb.py |
Add docstrings with type hints explained | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -680,6 +680,12 @@
class SessionKeyDecryptionError(Exception):
+ """
+ Exception risen when we fail to decrypt a session key within an AS-REP
+ message.
+ It provides context information such as full AS-REP message but also the
+ cipher, key and cipherText used when the error occurred.
+ ... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/krb5/kerberosv5.py |
Add minimal docstrings for each function | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -284,6 +284,29 @@ def changePassword(clientName, domain, newPasswd,
oldPasswd="", oldLmhash="", oldNthash="", aesKey="", TGT=None,
kdcHost=None, kpasswdHost=None, kpasswdPort=KRB5_KPASSWD_PORT, subKey=None):
+ """
+ Change the password of the requesting user with... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/krb5/kpasswd.py |
Write Python docstrings for this snippet | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -76,6 +76,15 @@
class LDAPConnection:
def __init__(self, url, baseDN='', dstIp=None, signing=True):
+ """
+ LDAPConnection class
+
+ :param string url:
+ :param string baseDN:
+ :param string dstIp:
+
+ :return: a LDAP instance, if not raises a LDAPSessionErro... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/ldap/ldap.py |
Document this module using docstrings | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -40,6 +40,10 @@
class CountedOctetString(Structure):
+ """
+ Note: This is very similar to the CountedOctetString structure in ccache, except:
+ * `length` is uint16 instead of uint32
+ """
structure = (
('length','!H=0'),
('_data','_-data','self["length"]'),
@@ -70,6... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/krb5/keytab.py |
Document classes and their methods | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# A... | --- +++ @@ -628,6 +628,13 @@
# Add basic filetime conversion helper methods.
def POSIXtoFT(t):
+ """
+ Helper method that converts POSIX timestamps to FILETIME timestamps.
+
+ :param int t: POSIX timestamp - can be retrieved from datetime library.
+
+ :return int: FILETIME timestamp representing ... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/smb.py |
Provide clean and structured docstrings | #!/usr/bin/env python
# Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for m... | --- +++ @@ -207,6 +207,9 @@ self['PacketType'] = PACKET_UNSUBSCRIBE
class MQTTSessionError(Exception):
+ """
+ This is the exception every client should catch
+ """
def __init__(self, error=0, packet=0, errorString=''):
Exception.__init__(self)
@@ -284,6 +287,17 @@ return... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/mqtt.py |
Document this module using docstrings | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# De... | --- +++ @@ -44,6 +44,22 @@
class SMBConnection:
+ """
+ SMBConnection class
+
+ :param str remoteName: The name of the remote host, can be its NETBIOS name, IP or *\\*SMBSERVER*.
+ If the later, and port is 139, the library will try to get the target's server name.
+ :param s... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/smbconnection.py |
Insert docstrings into my code | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -47,8 +47,10 @@ return array.array('B', value)
class NumBuilder(object):
+ """Converts back and forth between arrays and numbers in network byte-order"""
def __init__(self, size):
+ """size: number of bytes in the field"""
self.size = size
def from_ary(... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/wps.py |
Add docstrings to my Python code | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# De... | --- +++ @@ -504,6 +504,55 @@
class TDS_SSVARIANT(Structure):
+ """
+ SQL Server Variant Type Structure.
+
+ As defined in [MS-TDS] 2.2.5.5.4 sql_variant Values:
+
+ The SSVARIANTTYPE is a special data type that acts as a place holder for other data types.
+ When a SSVARIANTTYPE is filled with a data ... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/tds.py |
Create simple docstrings for beginners |
import shutil
from pathlib import Path
from typing import Any
class MemoryToolHandler:
def __init__(self, base_path: str = "./memory_storage"):
self.base_path = Path(base_path).resolve()
self.memory_root = self.base_path / "memories"
self.memory_root.mkdir(parents=True, exist_ok=True)
... | --- +++ @@ -1,3 +1,9 @@+"""
+Production-ready memory tool handler for Claude's memory_20250818 tool.
+
+This implementation provides secure, client-side execution of memory operations
+with path validation, error handling, and comprehensive security measures.
+"""
import shutil
from pathlib import Path
@@ -5,13 +11... | https://raw.githubusercontent.com/2025Emma/vibe-coding-cn/HEAD/i18n/zh/skills/claude-cookbooks/scripts/memory_tool.py |
Generate docstrings with examples | # Impacket - Collection of Python classes for working with network protocols.
#
# Copyright Fortra, LLC and its affiliated companies
#
# All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# D... | --- +++ @@ -507,6 +507,11 @@ return resp
def getValue(self, keyValue, valueName=None):
+ """ returns a tuple with (ValueType, ValueData) for the requested keyValue
+ valueName is the name of the value (which can contain '\\')
+ if valueName is not given, keyValue must be a s... | https://raw.githubusercontent.com/fortra/impacket/HEAD/impacket/winregistry.py |
Generate helpful docstrings for debugging | #!/usr/bin/env python3
import zipfile
import os
import re
from PIL import Image
import shutil
def 自然排序键(文件名):
return [int(text) if text.isdigit() else text.lower() for text in re.split(r'(\d+)', 文件名)]
def zip转pdf(zip路径):
try:
# 获取ZIP文件名(不含扩展名)
zip目录, zip文件名 = os.path.split(zip路径)
pdf名... | --- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3
+"""
+图片ZIP转PDF脚本
+将ZIP文件中的图片按序号排序并拼接成PDF文件
+"""
import zipfile
import os
@@ -7,9 +11,19 @@ import shutil
def 自然排序键(文件名):
+ """将文件名转换为自然排序键,支持数字排序"""
return [int(text) if text.isdigit() else text.lower() for text in re.split(r'(\d+)', 文件名)]
def zip转pdf(zi... | https://raw.githubusercontent.com/2025Emma/vibe-coding-cn/HEAD/libs/external/XHS-image-to-PDF-conversion/pdf.py |
Turn comments into proper docstrings | #!/usr/bin/env python3
import os
import tarfile
import fnmatch
from pathlib import Path
from datetime import datetime
import argparse
import sys
class GitignoreFilter:
def __init__(self, gitignore_path: Path, project_root: Path):
self.project_root = project_root
# 规则按照出现顺序存储,支持取反(!)语义,后匹配覆盖前匹配
... | --- +++ @@ -1,4 +1,31 @@ #!/usr/bin/env python3
+"""
+快速备份项目工具
+读取 .gitignore 规则并打包项目文件(排除匹配的文件)
+
+bash backups/一键备份.sh
+
+文件位置:
+ backups/快速备份.py
+
+工具清单(backups/目录):
+ • 快速备份.py - 核心备份引擎(7.3 KB)
+ • 一键备份.sh - 一键执行脚本(2.4 KB)
+
+使用方法:
+ $ bash backups/一键备份.sh
+ 或
+ $ python3 backups/快速备份.py
+
+备份... | https://raw.githubusercontent.com/2025Emma/vibe-coding-cn/HEAD/libs/common/utils/backups/快速备份.py |
Insert docstrings into my code | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations
import argparse
import os
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional, Sequence, Tuple
# Optional Rich UI imports (fallback to plain if unavailable)
try:
... | --- +++ @@ -1,5 +1,37 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+r"""
+main.py
+
+Unified controller for prompt-library conversions.
+
+Capabilities
+- Scan default folders and let user select a source to convert
+ - If you select an Excel file (.xlsx), it will convert Excel → Docs
+ - If you select a prompt... | https://raw.githubusercontent.com/2025Emma/vibe-coding-cn/HEAD/libs/external/prompts-library/main.py |
Create documentation for each function signature | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations
import argparse
import json
import re
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import pandas as pd
try:
import yaml # type: ignore
exce... | --- +++ @@ -1,5 +1,29 @@ #!/usr/bin/env python3
# -*- coding: utf-8 -*-
+"""
+convert_local.py
+
+Reads a local Excel file and converts its contents into a structured prompt library
+under `prompt-library/` per the development guide. It generates:
+- prompts/<category>/ (one file per non-empty cell across columns for ... | https://raw.githubusercontent.com/2025Emma/vibe-coding-cn/HEAD/libs/external/prompts-library/scripts/convert_local.py |
Add docstrings to improve readability |
import argparse
import os
from functools import lru_cache
from dvc import __version__
from dvc.commands import (
add,
artifacts,
cache,
check_ignore,
checkout,
commit,
completion,
config,
daemon,
dag,
data,
data_sync,
dataset,
destroy,
diff,
du,
expe... | --- +++ @@ -1,3 +1,4 @@+"""Main parser for the dvc cli."""
import argparse
import os
@@ -118,6 +119,7 @@
class DvcParser(argparse.ArgumentParser):
+ """Custom parser class for dvc CLI."""
def error(self, message, cmd_cls=None):
logger.error(message)
@@ -135,6 +137,12 @@
def get_parent_par... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/cli/parser.py |
Create documentation strings for testing functions |
import logging
import sys
from typing import Optional
from dvc.log import logger
# Workaround for CPython bug. See [1] and [2] for more info.
# [1] https://github.com/aws/aws-cli/blob/1.16.277/awscli/clidriver.py#L55
# [2] https://bugs.python.org/issue29288
"".encode("idna")
logger = logger.getChild(__name__)
cl... | --- +++ @@ -1,3 +1,4 @@+"""This module provides an entrypoint to the dvc cli and parsing utils."""
import logging
import sys
@@ -15,12 +16,21 @@
class DvcParserError(Exception):
+ """Base class for CLI parser errors."""
def __init__(self):
super().__init__("parser error")
def parse_args(... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/cli/__init__.py |
Write docstrings that follow conventions | import os
from typing import TYPE_CHECKING, Optional
from dvc.fs import GitFileSystem, Schemes
from dvc_data.hashfile.db import get_odb
from dvc_data.hashfile.hash import DEFAULT_ALGORITHM
if TYPE_CHECKING:
from dvc.repo import Repo
LEGACY_HASH_NAMES = {"md5-dos2unix", "params"}
def _get_odb(
repo,
set... | --- +++ @@ -76,6 +76,11 @@
@property
def fs_cache(self):
+ """Filesystem-based cache.
+
+ Currently used as a temporary location to download files that we don't
+ yet have a regular oid (e.g. md5) for.
+ """
from dvc_data.index import FileStorage
return FileSto... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/cachemgr.py |
Generate consistent documentation across files | from typing import Optional
from dvc.repo import Repo
def all_branches(repo: Optional[str] = None) -> list[str]:
with Repo.open(repo) as _repo:
return _repo.scm.list_branches()
def all_commits(repo: Optional[str] = None) -> list[str]:
with Repo.open(repo) as _repo:
return _repo.scm.list_all... | --- +++ @@ -4,15 +4,51 @@
def all_branches(repo: Optional[str] = None) -> list[str]:
+ """Get all Git branches in a DVC repository.
+
+ Args:
+ repo (str, optional): location of the DVC repository.
+ Defaults to the current project (found by walking up from the
+ current working d... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/api/scm.py |
Add well-formatted docstrings | from contextlib import _GeneratorContextManager as GCM
from contextlib import contextmanager
from typing import Any, Optional
from funcy import reraise
from dvc.exceptions import FileMissingError, OutputNotFoundError, PathMissingError
from dvc.repo import Repo
@contextmanager
def _wrap_exceptions(repo, url):
fr... | --- +++ @@ -33,6 +33,42 @@ config: Optional[dict[str, Any]] = None,
remote_config: Optional[dict[str, Any]] = None,
):
+ """
+ Returns the URL to the storage location of a data file or directory tracked
+ in a DVC repo. For Git repos, HEAD is used unless a rev argument is
+ supplied. The default r... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/api/data.py |
Write docstrings for this repository | import json
import os
from typing import TYPE_CHECKING, Optional
from dvc.log import logger
from .env import DVC_ANALYTICS_ENDPOINT, DVC_NO_ANALYTICS
if TYPE_CHECKING:
from dvc.scm import Base
logger = logger.getChild(__name__)
def collect_and_send_report(args=None, return_code=None):
import tempfile
... | --- +++ @@ -13,6 +13,17 @@
def collect_and_send_report(args=None, return_code=None):
+ """
+ Collect information from the runtime/environment and the command
+ being executed into a report and send it over the network.
+
+ To prevent analytics from blocking the execution of the main thread,
+ sending... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/analytics.py |
Generate documentation strings for clarity |
import ntpath
import os
import posixpath
import re
from contextlib import contextmanager
from functools import partial
from typing import TYPE_CHECKING, Optional
from funcy import compact, memoize, re_find
from dvc.exceptions import DvcException, NotDvcRepoError
from dvc.log import logger
from .utils.objects import... | --- +++ @@ -1,3 +1,4 @@+"""DVC config objects."""
import ntpath
import os
@@ -22,6 +23,7 @@
class ConfigError(DvcException):
+ """DVC config exception."""
def __init__(self, msg):
super().__init__(f"config file error: {msg}")
@@ -55,6 +57,18 @@
class Config(dict):
+ """Class that manag... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/config.py |
Create docstrings for API functions | import typing
from collections import Counter
from collections.abc import Iterable
from typing import Optional, Union
from funcy import first
from dvc.repo import Repo
def _postprocess(results):
processed: dict[str, dict] = {}
for rev, rev_data in results.items():
if not rev_data:
contin... | --- +++ @@ -38,6 +38,101 @@ rev: Optional[str] = None,
config: Optional[dict] = None,
) -> dict:
+ """Get metrics tracked in `repo`.
+
+ Without arguments, this function will retrieve all metrics from all tracked
+ metric files, for the current working tree.
+
+ See the options below to restrict t... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/api/show.py |
Include argument descriptions in docstrings | from typing import Optional, Union
from rich.text import Text
from dvc.repo import Repo
from dvc.repo.experiments.show import tabulate
def exp_save(
name: Optional[str] = None,
force: bool = False,
include_untracked: Optional[list[str]] = None,
):
with Repo() as repo:
return repo.experiments... | --- +++ @@ -11,6 +11,32 @@ force: bool = False,
include_untracked: Optional[list[str]] = None,
):
+ """
+ Create a new DVC experiment using `exp save`.
+
+ See https://dvc.org/doc/command-reference/exp/save.
+
+ Args:
+ name (str, optional): specify a name for this experiment.
+ ... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/api/experiments.py |
Generate docstrings with examples |
import math
import os
from grandalf.graphs import Edge, Graph, Vertex
from grandalf.layouts import SugiyamaLayout
from grandalf.routing import EdgeViewer, route_with_lines
from dvc.log import logger
logger = logger.getChild(__name__)
class VertexViewer:
HEIGHT = 3 # top and bottom box edges + text
def ... | --- +++ @@ -1,3 +1,4 @@+"""Draws DAG in ASCII."""
import math
import os
@@ -12,6 +13,12 @@
class VertexViewer:
+ """Class to define vertex box boundaries that will be accounted for during
+ graph building by grandalf.
+
+ Args:
+ name (str): name of the vertex.
+ """
HEIGHT = 3 # top ... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/dagascii.py |
Include argument descriptions in docstrings | import os
from typing import TYPE_CHECKING
from urllib.parse import urlparse
from funcy import once, walk_values
from voluptuous import (
REMOVE_EXTRA,
All,
Any,
Coerce,
Exclusive,
Invalid,
Lower,
Marker,
Optional,
Range,
Schema,
)
from dvc.log import logger
if TYPE_CHECKI... | --- +++ @@ -33,6 +33,11 @@
def supported_cache_type(types):
+ """Checks if link type config option consists only of valid values.
+
+ Args:
+ types (list/string): type(s) of links that dvc should try out.
+ """
if types is None:
return None
if isinstance(types, str):
@@ -46,6 +51,... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/config_schema.py |
Write docstrings including parameters and return values |
import inspect
import logging
import os
import subprocess
import sys
from collections.abc import Mapping, Sequence
from contextlib import nullcontext
from typing import TYPE_CHECKING, Any, Optional, Union
from dvc.log import logger
if TYPE_CHECKING:
from contextlib import AbstractContextManager
from dvc.env imp... | --- +++ @@ -1,3 +1,4 @@+"""Launch `dvc daemon` command in a separate detached process."""
import inspect
import logging
@@ -21,6 +22,7 @@
def _suppress_resource_warning(popen: subprocess.Popen) -> None:
+ """Sets the returncode to avoid ResourceWarning when popen is garbage collected."""
# only use for ... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/daemon.py |
Add docstrings for better understanding |
from collections.abc import Iterable
from typing import TYPE_CHECKING, Optional
from dvc.config import NoRemoteError, RemoteConfigError
from dvc.log import logger
from dvc.utils.objects import cached_property
from dvc_data.hashfile.db import get_index
from dvc_data.hashfile.transfer import TransferResult
if TYPE_CHE... | --- +++ @@ -1,3 +1,4 @@+"""Manages dvc remotes that user can use with push/pull/status commands."""
from collections.abc import Iterable
from typing import TYPE_CHECKING, Optional
@@ -64,6 +65,15 @@
class DataCloud:
+ """Class that manages dvc remotes.
+
+ Args:
+ repo (dvc.repo.Repo): repo instanc... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/data_cloud.py |
Write docstrings that follow conventions |
from collections.abc import Collection
from getpass import getpass
from typing import Optional
from dvc.log import logger
logger = logger.getChild(__name__)
def ask(prompt: str, limited_to: Optional[Collection[str]] = None):
from dvc.ui import Console
if not Console.isatty():
return None
whil... | --- +++ @@ -1,3 +1,4 @@+"""Manages user prompts."""
from collections.abc import Collection
from getpass import getpass
@@ -30,11 +31,27 @@
def confirm(statement: str) -> bool:
+ """Ask the user for confirmation about the specified statement.
+
+ Args:
+ statement (unicode): statement to ask the use... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/prompt.py |
Document this module using docstrings | import logging
import os
from collections.abc import Mapping, Sequence
from copy import deepcopy
from itertools import product
from typing import TYPE_CHECKING, Any, NamedTuple, Optional, Union
from funcy import collecting, first, isa, join, reraise
from dvc.exceptions import DvcException
from dvc.log import logger
f... | --- +++ @@ -209,6 +209,7 @@ return definition.resolve_one(key)
def resolve(self):
+ """Used for testing purposes, otherwise use resolve_one()."""
data = join(map(self.resolve_one, self.get_keys()))
logger.trace("Resolved dvc.yaml:\n%s", data)
return {STAGES_KWD: data}
@@... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/parsing/__init__.py |
Annotate my code with docstrings |
import logging
import os
import sys
from collections.abc import Iterator
from contextlib import contextmanager
from typing import ClassVar
import colorama
from dvc.progress import Tqdm
def add_logging_level(level_name, level_num, method_name=None):
if method_name is None:
method_name = level_name.lower... | --- +++ @@ -1,3 +1,4 @@+"""Manages logging configuration for DVC repo."""
import logging
import os
@@ -12,6 +13,14 @@
def add_logging_level(level_name, level_num, method_name=None):
+ """
+ Adds a new logging level to the `logging` module and the
+ currently configured logging class.
+
+ Uses the ex... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/logger.py |
Generate consistent docstrings |
import logging
import sys
from threading import RLock
from typing import TYPE_CHECKING, Any, ClassVar
from tqdm import tqdm
from dvc.env import DVC_IGNORE_ISATTY
from dvc.utils import env2bool
if TYPE_CHECKING:
from dvc.fs.callbacks import TqdmCallback
logger = logging.getLogger(__name__)
tqdm.set_lock(RLock()... | --- +++ @@ -1,3 +1,4 @@+"""Manages progress bars for DVC repo."""
import logging
import sys
@@ -17,6 +18,9 @@
class Tqdm(tqdm):
+ """
+ maximum-compatibility tqdm-based progressbars
+ """
BAR_FMT_DEFAULT = (
"{percentage:3.0f}% {desc}|{bar}|"
@@ -51,6 +55,18 @@ postfix=None,
... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/progress.py |
Fully document this Python code with docstrings | from abc import ABC, abstractmethod
from collections import defaultdict
from collections.abc import Mapping, MutableMapping, MutableSequence, Sequence
from contextlib import contextmanager
from copy import deepcopy
from dataclasses import dataclass, field, replace
from typing import Any, Optional, Union
from funcy imp... | --- +++ @@ -293,6 +293,9 @@
class Context(CtxDict):
def __init__(self, *args, **kwargs):
+ """
+ Top level mutable dict, with some helpers to create context and track
+ """
super().__init__(*args, **kwargs)
self._track = False
self._tracked_data: dict[str, dict] = ... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/parsing/context.py |
Create documentation strings for testing functions | import errno
import os
import posixpath
from collections import defaultdict
from contextlib import suppress
from operator import itemgetter
from typing import TYPE_CHECKING, Any, Optional, Union
from urllib.parse import urlparse
import voluptuous as vol
from funcy import collecting, first, project
from dvc import pro... | --- +++ @@ -1113,6 +1113,7 @@ def _collect_used_dir_cache(
self, remote=None, force=False, jobs=None, filter_info=None
) -> Optional["Tree"]:
+ """Fetch dir cache and return used object IDs for this out."""
try:
self.get_dir_cache(jobs=jobs, remote=remote)
@@ -1147,6 +11... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/output.py |
Expand my code with proper documentation strings | import os
from collections.abc import Iterable
from typing import Any, Optional, Union
from funcy import first, last
from dvc.exceptions import DvcException
from dvc.render import FIELD, FILENAME, INDEX, REVISION
from . import Converter
class FieldNotFoundError(DvcException):
def __init__(self, expected_field,... | --- +++ @@ -72,6 +72,10 @@
def _is_datapoints(lst: list[dict]):
+ """
+ check if dict keys match, datapoints with different keys mgiht lead
+ to unexpected behavior
+ """
return all(isinstance(item, dict) for item in lst) and set(first(lst).keys()) == {
key for keys in lst for key in key... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/render/converter/vega.py |
Generate docstrings with parameter types |
import errno
from typing import TYPE_CHECKING, Optional
from dvc.utils import format_link
if TYPE_CHECKING:
from dvc.stage import Stage
class DvcException(Exception): # noqa: N818
def __init__(self, msg, *args):
assert msg
self.msg = msg
super().__init__(msg, *args)
class Invali... | --- +++ @@ -1,3 +1,4 @@+"""Exceptions raised by the dvc."""
import errno
from typing import TYPE_CHECKING, Optional
@@ -9,6 +10,7 @@
class DvcException(Exception): # noqa: N818
+ """Base class for all dvc exceptions."""
def __init__(self, msg, *args):
assert msg
@@ -17,6 +19,7 @@
class I... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/exceptions.py |
Add docstrings to improve code quality | import contextlib
import os
from typing import TYPE_CHECKING, Any, Callable, ClassVar, Optional, TypeVar, Union
from dvc.exceptions import DvcException
from dvc.log import logger
from dvc.stage import serialize
from dvc.stage.exceptions import (
StageFileBadNameError,
StageFileDoesNotExistError,
StageFileI... | --- +++ @@ -191,6 +191,7 @@ return self.LOADER(self, data, raw)
def dump(self, stage, **kwargs) -> None:
+ """Dumps given stage appropriately in the dvcfile."""
from dvc.stage import PipelineStage
assert not isinstance(stage, PipelineStage)
@@ -220,6 +221,7 @@
class Project... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/dvcfile.py |
Create simple docstrings for beginners | import os
import posixpath
from collections import defaultdict, deque
from collections.abc import Iterable, Iterator, Mapping
from typing import TYPE_CHECKING, Optional, TypedDict, Union
from dvc.fs.callbacks import DEFAULT_CALLBACK, Callback, TqdmCallback
from dvc.log import logger
from dvc.ui import ui
from dvc_data... | --- +++ @@ -367,6 +367,7 @@
def _transform_git_paths_to_dvc(repo: "Repo", files: Iterable[str]) -> list[str]:
+ """Transform files rel. to Git root to DVC root, and drop outside files."""
rel = repo.fs.relpath(repo.root_dir, repo.scm.root_dir).rstrip("/")
# if we have repo root in a different locatio... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/repo/data.py |
Add docstrings for internal functions | from typing import TYPE_CHECKING
from scmrepo.exceptions import SCMError
from dvc.log import logger
from dvc.repo.experiments.executor.base import ExecutorInfo, TaskStatus
from dvc.repo.experiments.refs import EXEC_NAMESPACE, EXPS_NAMESPACE, EXPS_STASH
from dvc.repo.experiments.utils import get_exp_rwlock, iter_remot... | --- +++ @@ -17,6 +17,11 @@
def get_remote_executor_refs(scm: "Git", remote_url: str) -> list[str]:
+ """Get result list refs from a remote repository
+
+ Args:
+ remote_url : remote executor's url
+ """
refs = []
for ref in iter_remote_refs(scm, remote_url, base=EXPS_NAMESPACE):
i... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/repo/experiments/queue/utils.py |
Create docstrings for reusable components | import itertools
import os
from collections.abc import Collection, Iterable, Iterator
from dataclasses import fields
from datetime import datetime
from typing import TYPE_CHECKING, Optional, Union
from funcy import first
from scmrepo.exceptions import SCMError as InnerSCMError
from dvc.log import logger
from dvc.scm ... | --- +++ @@ -32,6 +32,11 @@ cache: Optional["ExpCache"] = None,
**kwargs,
) -> ExpState:
+ """Collect experiment state for the given revision.
+
+ Exp will be loaded from cache when available unless rev is 'workspace' or
+ force is set.
+ """
from dvc.fs import LocalFileSystem
cache = c... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/repo/experiments/collect.py |
Create docstrings for all classes and functions | import os
import re
from collections.abc import Iterable
from typing import TYPE_CHECKING, Optional
from funcy import chain, first
from dvc.log import logger
from dvc.ui import ui
from dvc.utils import relpath
from dvc.utils.objects import cached_property
from .cache import ExpCache
from .exceptions import (
Bas... | --- +++ @@ -41,6 +41,11 @@
class Experiments:
+ """Class that manages experiments in a DVC repo.
+
+ Args:
+ repo (dvc.repo.Repo): repo instance that these experiments belong to.
+ """
BRANCH_RE = re.compile(r"^(?P<baseline_rev>[a-f0-9]{7})-(?P<exp_sha>[a-f0-9]+)")
@@ -113,6 +118,7 @@ ... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/repo/experiments/__init__.py |
Generate docstrings for exported functions | import os
import posixpath
from pathlib import Path
from typing import TYPE_CHECKING, Any, Optional, Union
from dvc.annotations import Artifact
from dvc.dvcfile import PROJECT_FILE
from dvc.exceptions import (
ArtifactNotFoundError,
DvcException,
FileExistsLocallyError,
InvalidArgumentError,
)
from dvc... | --- +++ @@ -39,6 +39,10 @@
def name_is_compatible(name: str) -> bool:
+ """
+ Only needed by DVCLive per treeverse/dvclive#715
+ Will be removed in future release.
+ """
from gto.constants import assert_name_is_valid
from gto.exceptions import ValidationError
@@ -92,6 +96,7 @@ return... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/repo/artifacts.py |
Create Google-style docstrings for my code | from collections.abc import Collection, Iterable
from typing import TYPE_CHECKING, Union
from dvc.repo.experiments.exceptions import UnresolvedExpNamesError
from dvc.repo.experiments.queue.base import QueueDoneResult
if TYPE_CHECKING:
from dvc.repo.experiments.queue.base import QueueEntry
from dvc.repo.experi... | --- +++ @@ -14,6 +14,11 @@ celery_queue: "LocalCeleryQueue",
queue_entries: Iterable["QueueEntry"],
):
+ """Remove tasks from task queue.
+
+ Arguments:
+ queue_entries: An iterable list of task to remove
+ """
from celery.result import AsyncResult
stash_revs: dict[str, ExpStashEnt... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/repo/experiments/queue/remove.py |
Write docstrings describing functionality | import re
from collections.abc import Iterable, Iterator
from contextlib import contextmanager
from typing import NamedTuple, Optional
from scmrepo.git import Stash
from dvc.exceptions import DvcException
from dvc.log import logger
from dvc_objects.fs.local import localfs
from dvc_objects.fs.utils import as_atomic
f... | --- +++ @@ -16,6 +16,15 @@
class ExpStashEntry(NamedTuple):
+ """Experiment stash entry.
+
+ stash_index: Stash index for this entry. Can be None if this commit
+ is not pushed onto the stash ref.
+ head_rev: HEAD Git commit to be checked out for this experiment.
+ baseline_rev: Experiment baseli... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/repo/experiments/stash.py |
Add missing documentation to my Python functions | import errno
import functools
import ntpath
import os
import posixpath
import threading
from collections import defaultdict, deque
from contextlib import ExitStack, nullcontext, suppress
from glob import has_magic
from typing import TYPE_CHECKING, Any, Callable, Optional, Union
from fsspec.spec import DEFAULT_CALLBACK... | --- +++ @@ -97,6 +97,44 @@ remote_config: Optional["DictStrAny"] = None,
**kwargs,
) -> None:
+ """DVC + git-tracked files fs.
+
+ Args:
+ repo (str | os.PathLike[str] | Repo, optional): A url or a path to a DVC/Git
+ repository, or a `Repo` instance.
+ ... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/fs/dvc.py |
Write docstrings for algorithm functions | import os
import pickle
import shutil
from abc import ABC, abstractmethod
from collections.abc import Iterable, Iterator
from contextlib import AbstractContextManager, contextmanager
from dataclasses import asdict, dataclass
from enum import IntEnum
from itertools import chain
from typing import TYPE_CHECKING, Any, Cal... | --- +++ @@ -108,6 +108,16 @@
class BaseExecutor(ABC):
+ """Base class for executing experiments in parallel.
+
+ Parameters:
+ root_dir: Path to SCM root.
+ dvc_dir: Path to .dvc dir relative to SCM root.
+ baseline_rev: Experiment baseline revision.
+ wdir: Path to exec working di... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/repo/experiments/executor/base.py |
Generate docstrings with examples | import os
from abc import ABC, abstractmethod
from collections.abc import Collection, Generator, Iterable, Mapping
from dataclasses import asdict, dataclass
from typing import TYPE_CHECKING, Any, NamedTuple, Optional, Union
from funcy import retry
from dvc.dependency import ParamsDependency
from dvc.env import DVC_EX... | --- +++ @@ -81,8 +81,19 @@
class BaseStashQueue(ABC):
+ """Naive Git-stash based experiment queue.
+
+ Maps queued experiments to (Git) stash reflog entries.
+ """
def __init__(self, repo: "Repo", ref: str, failed_ref: Optional[str] = None):
+ """Construct a queue.
+
+ Arguments:
+ ... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/repo/experiments/queue/base.py |
Add docstrings to incomplete code | import fnmatch
import typing
from collections.abc import Iterable
from contextlib import suppress
from functools import wraps
from typing import NamedTuple, Optional, Union
from dvc.exceptions import (
NoOutputOrStageError,
OutputDuplicationError,
OutputNotFoundError,
)
from dvc.log import logger
from dvc.... | --- +++ @@ -151,6 +151,19 @@ force: bool = False,
**stage_data,
) -> Union["Stage", "PipelineStage"]:
+ """Creates a stage.
+
+ Args:
+ single_stage: if true, the .dvc file based stage is created,
+ fname is required in that case
+ fname: name of ... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/repo/stage.py |
Add docstrings for utility scripts | import glob
import hashlib
import locale
import logging
import os
from collections import defaultdict
from collections.abc import Collection, Generator, Mapping
from typing import TYPE_CHECKING, NamedTuple, Optional, Union
from celery.result import AsyncResult
from funcy import first
from dvc.daemon import daemonize
... | --- +++ @@ -54,6 +54,10 @@
class LocalCeleryQueue(BaseStashQueue):
+ """DVC experiment queue.
+
+ Maps queued experiments to (Git) stash reflog entries.
+ """
CELERY_DIR = "celery"
@@ -114,6 +118,12 @@ )
def _spawn_worker(self, num: int = 1):
+ """spawn one single worker to p... | https://raw.githubusercontent.com/treeverse/dvc/HEAD/dvc/repo/experiments/queue/celery.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.