instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Create Google-style docstrings for my code
from __future__ import annotations import os from dataclasses import dataclass, field from typing import Optional, List from pathlib import Path def _default_workspace(): from common.utils import expand_path return expand_path("~/cow") @dataclass class MemoryConfig: # Storage paths (default: ~/cow...
--- +++ @@ -1,3 +1,8 @@+""" +Memory configuration module + +Provides global memory configuration with simplified workspace structure +""" from __future__ import annotations import os @@ -7,12 +12,14 @@ def _default_workspace(): + """Get default workspace path with proper Windows support""" from common.u...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/memory/config.py
Expand my code with proper documentation strings
import importlib import importlib.util from pathlib import Path from typing import Dict, Any, Type from agent.tools.base_tool import BaseTool from common.log import logger from config import conf class ToolManager: _instance = None def __new__(cls): if cls._instance is None: cls._instance...
--- +++ @@ -8,9 +8,13 @@ class ToolManager: + """ + Tool manager for managing tools. + """ _instance = None def __new__(cls): + """Singleton pattern to ensure only one instance of ToolManager exists.""" if cls._instance is None: cls._instance = super(ToolManager, cl...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/tool_manager.py
Create docstrings for each class method
import os from typing import Dict, Any from pathlib import Path from agent.tools.base_tool import BaseTool, ToolResult from common.utils import expand_path class Write(BaseTool): name: str = "write" description: str = "Write content to a file. Creates the file if it doesn't exist, overwrites if it does...
--- +++ @@ -1,3 +1,7 @@+""" +Write tool - Write file content +Creates or overwrites files, automatically creates parent directories +""" import os from typing import Dict, Any @@ -8,6 +12,7 @@ class Write(BaseTool): + """Tool for writing file content""" name: str = "write" description: str = ...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/write/write.py
Add docstrings following best practices
from bridge.context import Context, ContextType from bridge.reply import Reply, ReplyType from common.log import logger from linkai import LinkAIClient, PushMsg from config import conf, pconf, plugin_config, available_setting, write_plugin_config, get_root from plugins import PluginManager import threading import time...
--- +++ @@ -1,3 +1,9 @@+""" +Cloud management client for connecting to the LinkAI control console. + +Handles remote configuration sync, message push, and skill management +via the LinkAI socket protocol. +""" from bridge.context import Context, ContextType from bridge.reply import Reply, ReplyType @@ -40,6 +46,7 @...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/common/cloud_client.py
Add well-formatted docstrings
import importlib.util import json import logging import os import ssl import threading # -*- coding=utf-8 -*- import uuid import requests import web from bridge.context import Context from bridge.context import ContextType from bridge.reply import Reply, ReplyType from channel.chat_channel import ChatChannel, check_...
--- +++ @@ -1,3 +1,15 @@+""" +飞书通道接入 + +支持两种事件接收模式: +1. webhook模式: 通过HTTP服务器接收事件(需要公网IP) +2. websocket模式: 通过长连接接收事件(本地开发友好) + +通过配置项 feishu_event_mode 选择模式: "webhook" 或 "websocket" + +@author Saboteur7 +@Date 2023/11/19 +""" import importlib.util import json @@ -35,6 +47,7 @@ def _ensure_lark_imported(): + "...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/channel/feishu/feishu_channel.py
Add docstrings that explain logic
import os import shutil import zipfile import tempfile from typing import Dict, List, Optional from common.log import logger from agent.skills.types import Skill, SkillEntry from agent.skills.manager import SkillManager try: import requests except ImportError: requests = None class SkillService: def __...
--- +++ @@ -1,3 +1,10 @@+""" +Skill service for handling skill CRUD operations. + +This service provides a unified interface for managing skills, which can be +called from the cloud control client (LinkAI), the local web console, or any +other management entry point. +""" import os import shutil @@ -15,14 +22,28 @@...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/skills/service.py
Create structured documentation for my script
import json import os import threading from datetime import datetime from typing import Dict, List, Optional from pathlib import Path from common.utils import expand_path class TaskStore: def __init__(self, store_path: str = None): if store_path is None: # Default to ~/cow/scheduler/task...
--- +++ @@ -1,3 +1,6 @@+""" +Task storage management for scheduler +""" import json import os @@ -9,8 +12,17 @@ class TaskStore: + """ + Manages persistent storage of scheduled tasks + """ def __init__(self, store_path: str = None): + """ + Initialize task store + + ...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/scheduler/task_store.py
Document my Python code with docstrings
from __future__ import annotations import sqlite3 import json import hashlib from typing import List, Dict, Optional, Any from pathlib import Path from dataclasses import dataclass @dataclass class MemoryChunk: id: str user_id: Optional[str] scope: str # "shared" | "user" | "session" source: str # ...
--- +++ @@ -1,3 +1,8 @@+""" +Storage layer for memory using SQLite + FTS5 + +Provides vector and keyword search capabilities +""" from __future__ import annotations import sqlite3 @@ -10,6 +15,7 @@ @dataclass class MemoryChunk: + """Represents a memory chunk with text and embedding""" id: str user_i...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/memory/storage.py
Create documentation for each function signature
import os from pathlib import Path from typing import List, Optional, Dict from common.log import logger from agent.skills.types import Skill, SkillEntry, LoadSkillsResult, SkillMetadata from agent.skills.frontmatter import parse_frontmatter, parse_metadata, parse_boolean_value, get_frontmatter_value class SkillLoad...
--- +++ @@ -1,3 +1,6 @@+""" +Skill loader for discovering and loading skills from directories. +""" import os from pathlib import Path @@ -8,11 +11,23 @@ class SkillLoader: + """Loads skills from various directories.""" def __init__(self): pass def load_skills_from_dir(self, dir_pa...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/skills/loader.py
Annotate my code with docstrings
import hashlib from abc import ABC, abstractmethod from typing import List, Optional class EmbeddingProvider(ABC): @abstractmethod def embed(self, text: str) -> List[float]: pass @abstractmethod def embed_batch(self, texts: List[str]) -> List[List[float]]: pass @property ...
--- +++ @@ -1,3 +1,8 @@+""" +Embedding providers for memory + +Supports OpenAI and local embedding models +""" import hashlib from abc import ABC, abstractmethod @@ -5,24 +10,37 @@ class EmbeddingProvider(ABC): + """Base class for embedding providers""" @abstractmethod def embed(self, text: str) ...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/memory/embedding.py
Generate documentation strings for clarity
import time import logging logger = logging.getLogger(__name__) class FileCache: def __init__(self, ttl=120): self.cache = {} self.ttl = ttl def add(self, session_id: str, file_path: str, file_type: str = "image"): if session_id not in self.cache: self.cache[sess...
--- +++ @@ -1,3 +1,7 @@+""" +文件缓存管理器 +用于缓存单独发送的文件消息(图片、视频、文档等),在用户提问时自动附加 +""" import time import logging @@ -5,12 +9,25 @@ class FileCache: + """文件缓存管理器,按 session_id 缓存文件,TTL=2分钟""" def __init__(self, ttl=120): + """ + Args: + ttl: 缓存过期时间(秒),默认2分钟 + """ se...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/channel/file_cache.py
Generate docstrings for script automation
import re import json from typing import Dict, Any, Optional, List from agent.skills.types import SkillMetadata, SkillInstallSpec def parse_frontmatter(content: str) -> Dict[str, Any]: frontmatter = {} # Match frontmatter block between --- markers match = re.match(r'^---\s*\n(.*?)\n---\s*\n', conten...
--- +++ @@ -1,3 +1,6 @@+""" +Frontmatter parsing for skills. +""" import re import json @@ -6,6 +9,11 @@ def parse_frontmatter(content: str) -> Dict[str, Any]: + """ + Parse YAML-style frontmatter from markdown content. + + Returns a dictionary of frontmatter fields. + """ frontmatter = {} ...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/skills/frontmatter.py
Create structured documentation for my script
from models.bot_factory import create_bot from bridge.context import Context from bridge.reply import Reply from common import const from common.log import logger from common.singleton import singleton from config import conf from translate.factory import create_translator from voice.factory import create_voice @sing...
--- +++ @@ -114,9 +114,15 @@ return self.chat_bots.get(bot_type) def reset_bot(self): + """ + 重置bot路由 + """ self.__init__() def get_agent_bridge(self): + """ + Get agent bridge for agent-based conversations + """ if self._agent_bridge is ...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/bridge/bridge.py
Add missing documentation to my Python functions
import os import json from typing import Dict, Any, Optional import requests from agent.tools.base_tool import BaseTool, ToolResult from common.log import logger from config import conf # Default timeout for API requests (seconds) DEFAULT_TIMEOUT = 30 class WebSearch(BaseTool): name: str = "web_search" ...
--- +++ @@ -1,3 +1,9 @@+""" +Web Search tool - Search the web using Bocha or LinkAI search API. +Supports two backends with unified response format: + 1. Bocha Search (primary, requires BOCHA_API_KEY) + 2. LinkAI Search (fallback, requires LINKAI_API_KEY) +""" import os import json @@ -15,6 +21,7 @@ class Web...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/web_search/web_search.py
Fill in missing docstrings in my code
import json import time from typing import List, Dict, Any, Optional, Callable, Tuple from agent.protocol.models import LLMRequest, LLMModel from agent.protocol.message_utils import sanitize_claude_messages, compress_turn_to_text_only from agent.tools.base_tool import BaseTool, ToolResult from common.log import logger...
--- +++ @@ -1,3 +1,8 @@+""" +Agent Stream Execution Module - Multi-turn reasoning based on tool-call + +Provides streaming output, event system, and complete tool-call loop +""" import json import time from typing import List, Dict, Any, Optional, Callable, Tuple @@ -9,6 +14,15 @@ class AgentStreamExecutor: + ...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/protocol/agent_stream.py
Add standardized docstrings across the file
import os import requests from bridge.context import ContextType from channel.chat_message import ChatMessage from common.log import logger from common.utils import expand_path from config import conf def _get_tmp_dir() -> str: ws_root = expand_path(conf().get("agent_workspace", "~/cow")) tmp_dir = os.path.j...
--- +++ @@ -9,6 +9,7 @@ def _get_tmp_dir() -> str: + """Return the workspace tmp directory (absolute path), creating it if needed.""" ws_root = expand_path(conf().get("agent_workspace", "~/cow")) tmp_dir = os.path.join(ws_root, "tmp") os.makedirs(tmp_dir, exist_ok=True) @@ -16,6 +17,7 @@ class...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/channel/qq/qq_message.py
Add concise docstrings to each method
# encoding:utf-8 import os import signal import sys import time from channel import channel_factory from common import const from common.log import logger from config import load_config, conf from plugins import * import threading _channel_mgr = None def get_channel_manager(): return _channel_mgr def _parse...
--- +++ @@ -21,6 +21,13 @@ def _parse_channel_type(raw) -> list: + """ + Parse channel_type config value into a list of channel names. + Supports: + - single string: "feishu" + - comma-separated string: "feishu, dingtalk" + - list: ["feishu", "dingtalk"] + """ if isinstance(raw, list...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/app.py
Add return value explanations in docstrings
import os from datetime import datetime from typing import Dict, List, Optional from pathlib import Path from common.log import logger class MemoryService: def __init__(self, workspace_root: str): self.workspace_root = workspace_root self.memory_dir = os.path.join(workspace_root, "memory") ...
--- +++ @@ -1,3 +1,13 @@+""" +Memory service for handling memory query operations via cloud protocol. + +Provides a unified interface for listing and reading memory files, +callable from the cloud client (LinkAI) or a future web console. + +Memory file layout (under workspace_root): + MEMORY.md -> type...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/memory/service.py
Fully document this Python code with docstrings
import os import re from typing import Dict, Any from pathlib import Path from agent.tools.base_tool import BaseTool, ToolResult from common.log import logger from common.utils import expand_path # API Key 知识库:常见的环境变量及其描述 API_KEY_REGISTRY = { # AI 模型服务 "OPENAI_API_KEY": "OpenAI API 密钥 (用于GPT模型、Embedding模型)"...
--- +++ @@ -1,3 +1,6 @@+""" +Environment Configuration Tool - Manage API keys and environment variables +""" import os import re @@ -21,6 +24,7 @@ } class EnvConfig(BaseTool): + """Tool for managing environment variables (API keys, etc.)""" name: str = "env_config" description: str = ( @@ -70,...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/tools/env_config/env_config.py
Write docstrings for algorithm functions
from typing import Any, Dict, List, Optional class LLMRequest: def __init__(self, messages: List[Dict[str, str]] = None, model: Optional[str] = None, temperature: float = 0.7, max_tokens: Optional[int] = None, stream: bool = False, tools: Optional[List] = None, **kwargs): ...
--- +++ @@ -1,8 +1,13 @@+""" +Models module for agent system. +Provides basic model classes needed by tools and bridge integration. +""" from typing import Any, Dict, List, Optional class LLMRequest: + """Request model for LLM operations""" def __init__(self, messages: List[Dict[str, str]] = None,...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/agent/protocol/models.py
Create Google-style docstrings for my code
# encoding:utf-8 import json import time import requests from models.baidu.baidu_wenxin_session import BaiduWenxinSession from models.bot import Bot from models.session_manager import SessionManager from bridge.context import ContextType from bridge.reply import Reply, ReplyType from common import const from common....
--- +++ @@ -209,6 +209,13 @@ return model def _get_max_tokens(self, model: str) -> int: + """ + Get max_tokens for the model. + Reference from pi-mono: + - Claude 3.5/3.7: 8192 + - Claude 3 Opus: 4096 + - Default: 8192 + """ if model and (model.st...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/models/claudeapi/claude_api_bot.py
Annotate my code with docstrings
# encoding:utf-8 import json import time import requests from models.bot import Bot from models.session_manager import SessionManager from bridge.context import ContextType from bridge.reply import Reply, ReplyType from common.log import logger from config import conf, load_config from .doubao_session import DoubaoSe...
--- +++ @@ -86,6 +86,13 @@ return reply def reply_text(self, session: DoubaoSession, args=None, retry_count: int = 0) -> dict: + """ + Call Doubao chat completion API to get the answer + :param session: a conversation session + :param args: model args + :param retry...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/models/doubao/doubao_bot.py
Write docstrings that follow conventions
# encoding:utf-8 import time import json import openai from models.bot import Bot from models.session_manager import SessionManager from bridge.context import ContextType from bridge.reply import Reply, ReplyType from common.log import logger from config import conf, load_config from .modelscope_session import ModelSc...
--- +++ @@ -105,6 +105,13 @@ return reply def reply_text(self, session: ModelScopeSession, args=None, retry_count=0) -> dict: + """ + call openai's ChatCompletion to get the answer + :param session: a conversation session + :param session_id: session id + :param ret...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/models/modelscope/modelscope_bot.py
Document this code for team use
from bridge.context import Context from bridge.reply import Reply class Bot(object): def reply(self, query, context: Context = None) -> Reply: raise NotImplementedError
--- +++ @@ -1,3 +1,6 @@+""" +Auto-replay chat robot abstract class +""" from bridge.context import Context @@ -6,4 +9,9 @@ class Bot(object): def reply(self, query, context: Context = None) -> Reply: - raise NotImplementedError+ """ + bot auto-reply content + :param req: received...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/models/bot.py
Add docstrings for production code
from models.session_manager import Session from common.log import logger class OpenAISession(Session): def __init__(self, session_id, system_prompt=None, model="text-davinci-003"): super().__init__(session_id, system_prompt) self.model = model self.reset() def __str__(self): #...
--- +++ @@ -10,6 +10,11 @@ def __str__(self): # 构造对话模型的输入 + """ + e.g. Q: xxx + A: xxx + Q: xxx + """ prompt = "" for item in self.messages: if item["role"] == "system": @@ -60,8 +65,9 @@ # refer to https://github.com/openai...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/models/openai/open_ai_session.py
Add docstrings to clarify complex logic
# encoding:utf-8 import time import json import requests from models.bot import Bot from models.minimax.minimax_session import MinimaxSession from models.session_manager import SessionManager from bridge.context import Context, ContextType from bridge.reply import Reply, ReplyType from common.log import logger from c...
--- +++ @@ -86,6 +86,13 @@ return reply def reply_text(self, session: MinimaxSession, args=None, retry_count=0) -> dict: + """ + Call MiniMax API to get the answer using REST API + :param session: a conversation session + :param args: request arguments + :param retr...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/models/minimax/minimax_bot.py
Generate documentation strings for clarity
#!/usr/bin/env python3 import sys import os import zipfile from pathlib import Path # Add script directory to path for imports script_dir = Path(__file__).parent sys.path.insert(0, str(script_dir)) from quick_validate import validate_skill def package_skill(skill_path, output_dir=None): skill_path = Path(skill...
--- +++ @@ -1,4 +1,14 @@ #!/usr/bin/env python3 +""" +Skill Packager - Creates a distributable .skill file of a skill folder + +Usage: + python utils/package_skill.py <path/to/skill-folder> [output-directory] + +Example: + python utils/package_skill.py skills/public/my-skill + python utils/package_skill.py ski...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/skills/skill-creator/scripts/package_skill.py
Write docstrings describing functionality
# encoding:utf-8 import json import openai from common.log import logger from agent.protocol.message_utils import drop_orphaned_tool_results_openai class OpenAICompatibleBot: def get_api_config(self): raise NotImplementedError("Subclasses must implement get_api_config()") def call_with_too...
--- +++ @@ -1,5 +1,11 @@ # encoding:utf-8 +""" +OpenAI-Compatible Bot Base Class + +Provides a common implementation for bots that are compatible with OpenAI's API format. +This includes: OpenAI, LinkAI, Azure OpenAI, and many third-party providers. +""" import json import openai @@ -8,11 +14,57 @@ class Open...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/models/openai_compatible_bot.py
Help me add docstrings to my project
import plugins from bridge.context import ContextType from bridge.reply import Reply, ReplyType from plugins import * from .midjourney import MJBot from .summary import LinkSummary from bridge import bridge from common.expired_dict import ExpiredDict from common import const import os from .utils import Util from confi...
--- +++ @@ -35,6 +35,10 @@ logger.debug(f"[LinkAI] inited, config={self.config}") def on_handle_context(self, e_context: EventContext): + """ + 消息处理逻辑 + :param e_context: 消息上下文 + """ if not self.config: return @@ -228,6 +232,10 @@ return self.co...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/plugins/linkai/linkai.py
Document all public functions with docstrings
# coding=utf-8 import http.client import json import time import requests import datetime import hashlib import hmac import base64 import urllib.parse import uuid from common.log import logger from common.tmp_dir import TmpDir def text_to_speech_aliyun(url, text, appkey, token): headers = { "Content-Typ...
--- +++ @@ -1,4 +1,12 @@ # coding=utf-8 +""" +Author: chazzjimel +Email: chazzjimel@gmail.com +wechat:cheung-z-x + +Description: + +""" import http.client import json @@ -16,6 +24,18 @@ def text_to_speech_aliyun(url, text, appkey, token): + """ + 使用阿里云的文本转语音服务将文本转换为语音。 + + 参数: + - url (str): 阿里云文本转语...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/voice/ali/ali_api.py
Auto-generate documentation strings for this file
# encoding:utf-8 import json from models.bot import Bot from models.session_manager import SessionManager from bridge.context import ContextType from bridge.reply import Reply, ReplyType from common.log import logger from config import conf, load_config from .dashscope_session import DashscopeSession import os import ...
--- +++ @@ -46,6 +46,7 @@ @staticmethod def _is_multimodal_model(model_name: str) -> bool: + """Check if the model requires MultiModalConversation API""" return model_name.startswith(MULTIMODAL_MODEL_PREFIXES) def reply(self, query, context=None): @@ -93,6 +94,13 @@ return ...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/models/dashscope/dashscope_bot.py
Add docstrings to improve collaboration
# access LinkAI knowledge base platform # docs: https://link-ai.tech/platform/link-app/wechat import re import time import requests import json import config from models.bot import Bot from models.openai_compatible_bot import OpenAICompatibleBot from models.chatgpt.chat_gpt_session import ChatGPTSession from models.se...
--- +++ @@ -30,6 +30,7 @@ self.args = {} def get_api_config(self): + """Get API configuration for OpenAI-compatible base class""" return { 'api_key': conf().get("open_ai_api_key"), # LinkAI uses OpenAI-compatible key 'api_base': conf().get("open_ai_api_base"...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/models/linkai/link_ai_bot.py
Write proper docstrings for these functions
import os import yaml from typing import Dict, List, Optional from agentmesh import AgentTeam, Agent, LLMModel from agentmesh.models import ClaudeModel from agentmesh.tools import ToolManager from config import conf import plugins from plugins import Plugin, Event, EventContext, EventAction from bridge.context import...
--- +++ @@ -22,6 +22,7 @@ desire_priority=1, ) class AgentPlugin(Plugin): + """Plugin for integrating AgentMesh framework.""" def __init__(self): super().__init__() @@ -34,6 +35,7 @@ logger.debug("[agent] inited") def _load_config(self) -> Dict: + """Load configura...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/plugins/agent/agent.py
Fill in missing docstrings in my code
# encoding:utf-8 import json import time import requests from models.bot import Bot from models.session_manager import SessionManager from bridge.context import ContextType from bridge.reply import Reply, ReplyType from common.log import logger from config import conf, load_config from .moonshot_session import Moonsh...
--- +++ @@ -88,6 +88,13 @@ return reply def reply_text(self, session: MoonshotSession, args=None, retry_count: int = 0) -> dict: + """ + Call Moonshot chat completion API to get the answer + :param session: a conversation session + :param args: model args + :param r...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/models/moonshot/moonshot_bot.py
Document all endpoints with docstrings
# -*- coding: utf-8 -*- import json import os import re import time from bridge.reply import Reply, ReplyType from common.log import logger from voice.voice import Voice from voice.ali.ali_api import AliyunTokenGenerator, speech_to_text_aliyun, text_to_speech_aliyun from config import conf try: from voice.audio_c...
--- +++ @@ -1,4 +1,13 @@ # -*- coding: utf-8 -*- +""" +Author: chazzjimel +Email: chazzjimel@gmail.com +wechat:cheung-z-x + +Description: +ali voice service + +""" import json import os import re @@ -18,6 +27,9 @@ class AliVoice(Voice): def __init__(self): + """ + 初始化AliVoice类,从配置文件加载必要的配置。 + ...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/voice/ali/ali_voice.py
Create structured documentation for my script
#!/usr/bin/env python3 import sys from pathlib import Path SKILL_TEMPLATE = """--- name: {skill_name} description: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger it.] --- # {skill_title} #...
--- +++ @@ -1,4 +1,15 @@ #!/usr/bin/env python3 +""" +Skill Initializer - Creates a new skill from template + +Usage: + init_skill.py <skill-name> --path <path> + +Examples: + init_skill.py my-new-skill --path skills/public + init_skill.py my-api-helper --path skills/private + init_skill.py custom-skill --p...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/skills/skill-creator/scripts/init_skill.py
Write docstrings for algorithm functions
# encoding:utf-8 import time import json from models.bot import Bot from models.zhipuai.zhipu_ai_session import ZhipuAISession from models.zhipuai.zhipu_ai_image import ZhipuAIImage from models.session_manager import SessionManager from bridge.context import ContextType from bridge.reply import Reply, ReplyType from ...
--- +++ @@ -93,6 +93,13 @@ return reply def reply_text(self, session: ZhipuAISession, args=None, retry_count=0) -> dict: + """ + Call ZhipuAI API to get the answer + :param session: a conversation session + :param args: request arguments + :param retry_count: retry ...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/models/zhipuai/zhipuai_bot.py
Generate docstrings with parameter types
# encoding:utf-8 import copy import json import logging import os import pickle from common.log import logger # 将所有可用的配置项写在字典里, 请使用小写字母 # 此处的配置值无实际意义,程序不会读取此处的配置,仅用于提示格式,请将配置加入到config.json中 available_setting = { # openai api配置 "open_ai_api_key": "", # openai api key # openai apibase,当use_azure_chatgpt为t...
--- +++ @@ -429,18 +429,31 @@ def write_plugin_config(pconf: dict): + """ + 写入插件全局配置 + :param pconf: 全量插件配置 + """ global plugin_config for k in pconf: plugin_config[k.lower()] = pconf[k] def remove_plugin_config(name: str): + """ + 移除待重新加载的插件全局配置 + :param name: 待重载的插件名 + ...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/config.py
Create simple docstrings for beginners
# encoding:utf-8 import base64 import json import mimetypes import os import re import time import requests from models.bot import Bot from models.session_manager import SessionManager from bridge.context import ContextType, Context from bridge.reply import Reply, ReplyType from common.log import logger from config im...
--- +++ @@ -1,3 +1,9 @@+""" +Google gemini bot + +@author zhayujie +@Date 2023/12/15 +""" # encoding:utf-8 import base64 @@ -213,6 +219,18 @@ return None def call_with_tools(self, messages, tools=None, stream=False, **kwargs): + """ + Call Gemini API with tool support using REST API (fo...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/models/gemini/google_gemini_bot.py
Auto-generate documentation strings for this file
from enum import Enum from config import conf from common.log import logger import requests import threading import time from bridge.reply import Reply, ReplyType import asyncio from bridge.context import ContextType from plugins import EventContext, EventAction from .utils import Util INVALID_REQUEST = 410 NOT_FOUND...
--- +++ @@ -79,6 +79,11 @@ self.event_loop = asyncio.new_event_loop() def judge_mj_task_type(self, e_context: EventContext): + """ + 判断MJ任务的类型 + :param e_context: 上下文 + :return: 任务类型枚举 + """ if not self.config: return None trigger_prefix =...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/plugins/linkai/midjourney.py
Add docstrings for internal functions
from models.session_manager import Session from common.log import logger from common import const """ e.g. [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"}, {"role": "assistant", "content": "The Los Angeles Do...
--- +++ @@ -55,6 +55,7 @@ # refer to https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb def num_tokens_from_messages(messages, model): + """Returns the number of tokens used by a list of messages.""" if model in ["wenxin", "xunfei"] or model.startswith(cons...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/models/chatgpt/chat_gpt_session.py
Add docstrings including usage examples
# encoding:utf-8 import time import openai from models.openai.openai_compat import RateLimitError, Timeout, APIConnectionError from models.bot import Bot from models.openai_compatible_bot import OpenAICompatibleBot from models.openai.open_ai_image import OpenAIImage from models.openai.open_ai_session import OpenAISe...
--- +++ @@ -43,6 +43,7 @@ } def get_api_config(self): + """Get API configuration for OpenAI-compatible base class""" return { 'api_key': conf().get("open_ai_api_key"), 'api_base': conf().get("open_ai_api_base"), @@ -134,6 +135,22 @@ return res...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/models/openai/open_ai_bot.py
Add professional docstrings to my codebase
# encoding:utf-8 import time import json import openai from models.openai.openai_compat import error as openai_error, RateLimitError, Timeout, APIError, APIConnectionError import requests from common import const from models.bot import Bot from models.openai_compatible_bot import OpenAICompatibleBot from models.chatg...
--- +++ @@ -55,6 +55,7 @@ self.sessions = SessionManager(BaiduWenxinSession, model=conf().get("model") or const.O1_MINI) def get_api_config(self): + """Get API configuration for OpenAI-compatible base class""" return { 'api_key': conf().get("open_ai_api_key"), ...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/models/chatgpt/chat_gpt_bot.py
Write docstrings describing functionality
class Voice(object): def voiceToText(self, voice_file): raise NotImplementedError def textToVoice(self, text): raise NotImplementedError
--- +++ @@ -1,8 +1,17 @@+""" +Voice service abstract class +""" class Voice(object): def voiceToText(self, voice_file): + """ + Send voice to voice service and get text + """ raise NotImplementedError def textToVoice(self, text): - raise NotImplementedError+ ...
https://raw.githubusercontent.com/zhayujie/chatgpt-on-wechat/HEAD/voice/voice.py
Create documentation strings for testing functions
import os os.environ["PYTORCH_ALLOC_CONF"] = "expandable_segments:True" os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1" import gc import math import time from dataclasses import dataclass, asdict import torch import torch.nn as nn import torch.nn.functional as F from kernels import get_kernel cap = torch.cuda.get_...
--- +++ @@ -1,3 +1,8 @@+""" +Autoresearch pretraining script. Single-GPU, single-file. +Cherry-picked and simplified from nanochat. +Usage: uv run train.py +""" import os os.environ["PYTORCH_ALLOC_CONF"] = "expandable_segments:True" @@ -40,6 +45,7 @@ def has_ve(layer_idx, n_layer): + """Returns True if layer...
https://raw.githubusercontent.com/karpathy/autoresearch/HEAD/train.py
Add structured docstrings to improve clarity
import os import sys import time import math import argparse import pickle from multiprocessing import Pool import requests import pyarrow.parquet as pq import rustbpe import tiktoken import torch # --------------------------------------------------------------------------- # Constants (fixed, do not modify) # -----...
--- +++ @@ -1,3 +1,13 @@+""" +One-time data preparation for autoresearch experiments. +Downloads data shards and trains a BPE tokenizer. + +Usage: + python prepare.py # full prep (download + tokenizer) + python prepare.py --num-shards 8 # download only 8 shards (for testing) + +Data and tokeniz...
https://raw.githubusercontent.com/karpathy/autoresearch/HEAD/prepare.py
Write beginner-friendly docstrings
import ast import sys import warnings from collections.abc import Collection, Iterator from black.mode import VERSION_TO_FEATURES, Feature, TargetVersion, supports_feature from black.nodes import syms from blib2to3 import pygram from blib2to3.pgen2 import driver from blib2to3.pgen2.grammar import Grammar from blib2to...
--- +++ @@ -1,3 +1,6 @@+""" +Parse Python code and perform AST validation. +""" import ast import sys @@ -15,6 +18,7 @@ class InvalidInput(ValueError): + """Raised when input source code fails all parse attempts.""" def get_grammars(target_versions: set[TargetVersion]) -> list[Grammar]: @@ -51,6 +55,7 @...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/parsing.py
Document this code for team use
#!/usr/bin/env python3 from __future__ import annotations import argparse import logging import re import sys from datetime import datetime from pathlib import Path from subprocess import run LOG = logging.getLogger(__name__) NEW_VERSION_CHANGELOG_TEMPLATE = """\ ## Unreleased <!-- PR authors: Please include ...
--- +++ @@ -1,5 +1,8 @@ #!/usr/bin/env python3 +""" +Tool to help automate changes needed in commits during and after releases +""" from __future__ import annotations @@ -71,6 +74,7 @@ # TODO: Do better with alpha + beta releases # Maybe we vendor packaging library def get_git_tags(versions_only: bool = True) ...
https://raw.githubusercontent.com/psf/black/HEAD/scripts/release.py
Create docstrings for reusable components
import re import sys from functools import lru_cache from re import Match, Pattern from typing import Final from black._width_table import WIDTH_TABLE from blib2to3.pytree import Leaf STRING_PREFIX_CHARS: Final = "fturbFTURB" # All possible string prefix characters. STRING_PREFIX_RE: Final = re.compile( r"^([" ...
--- +++ @@ -1,3 +1,6 @@+""" +Simple formatting on strings. Further string formatting code is in trans.py. +""" import re import sys @@ -24,15 +27,28 @@ def sub_twice(regex: Pattern[str], replacement: str, original: str) -> str: + """Replace `regex` with `replacement` twice on `original`. + + This is used ...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/strings.py
Add detailed docstrings explaining each function
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. # Python imports import os import pickle import tempfile from typing import Any, Optional, TypeVar, Union # Local imports from . import token _P = TypeVar("_P", bound="Grammar") Label = tuple[int, Op...
--- +++ @@ -1,6 +1,16 @@ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. +"""This module defines the data structures used to represent a grammar. + +These are a bit arcane because they are derived from the data +structures used by Python's 'pgen' p...
https://raw.githubusercontent.com/psf/black/HEAD/src/blib2to3/pgen2/grammar.py
Add detailed docstrings explaining each function
import json import re import tempfile from typing import Any from click import echo, style from mypy_extensions import mypyc_attr @mypyc_attr(patchable=True) def _out(message: str | None = None, nl: bool = True, **styles: Any) -> None: if message is not None: if "bold" not in styles: styles[...
--- +++ @@ -1,3 +1,7 @@+"""Nice output for Black. + +The double calls are for patching purposes in tests. +""" import json import re @@ -36,6 +40,7 @@ def ipynb_diff(a: str, b: str, a_name: str, b_name: str) -> str: + """Return a unified diff string between each cell in notebooks `a` and `b`.""" a_nb = ...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/output.py
Add docstrings to improve readability
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. # Python imports import os from typing import Union # Local imports from .pgen2 import driver from .pgen2.grammar import Grammar # Moved into initialize because mypyc can't handle __file__ (XXX bug) # # The grammar f...
--- +++ @@ -1,6 +1,7 @@ # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. +"""Export the Python grammar and symbols.""" # Python imports import os @@ -19,6 +20,11 @@ class Symbols: def __init__(self, grammar: Grammar) -> None: + """Initializer. + + ...
https://raw.githubusercontent.com/psf/black/HEAD/src/blib2to3/pygram.py
Write beginner-friendly docstrings
from dataclasses import dataclass, field from enum import Enum, auto from hashlib import sha256 from operator import attrgetter from typing import Final from black.const import DEFAULT_LINE_LENGTH class TargetVersion(Enum): PY33 = 3 PY34 = 4 PY35 = 5 PY36 = 6 PY37 = 7 PY38 = 8 PY39 = 9 ...
--- +++ @@ -1,3 +1,8 @@+"""Data structures configuring Black behavior. + +Mostly around Python language feature support per version and Black configuration +chosen by the user. +""" from dataclasses import dataclass, field from enum import Enum, auto @@ -215,6 +220,7 @@ class Preview(Enum): + """Individual p...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/mode.py
Add detailed docstrings explaining each function
import difflib from collections.abc import Collection, Iterator, Sequence from dataclasses import dataclass from black.nodes import ( LN, STANDALONE_COMMENT, Leaf, Node, Visitor, first_leaf, furthest_ancestor_with_last_leaf, last_leaf, syms, ) from blib2to3.pgen2.token import ASYNC...
--- +++ @@ -1,3 +1,4 @@+"""Functions related to Black's formatting by line ranges feature.""" import difflib from collections.abc import Collection, Iterator, Sequence @@ -40,12 +41,20 @@ def is_valid_line_range(lines: tuple[int, int]) -> bool: + """Returns whether the line range is valid.""" return not...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/ranges.py
Create docstrings for all classes and functions
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. # mypy: allow-untyped-defs, allow-incomplete-defs from collections.abc import Iterable, Iterator from typing import Any, Optional, TypeVar, Union from blib2to3.pgen2.grammar import Grammar __author__ = "Guido van Ro...
--- +++ @@ -1,6 +1,14 @@ # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. +""" +Python parse tree definitions. + +This is a very concrete parse tree; we need to keep every token and +even the comments and whitespace between tokens. + +There's also a pattern matching...
https://raw.githubusercontent.com/psf/black/HEAD/src/blib2to3/pytree.py
Add documentation for all methods
import re from abc import ABC, abstractmethod from collections import defaultdict from collections.abc import Callable, Collection, Iterable, Iterator, Sequence from dataclasses import dataclass from typing import Any, ClassVar, Final, Literal, TypeVar, Union from mypy_extensions import trait from black.comments imp...
--- +++ @@ -1,3 +1,6 @@+""" +String transformers that can split and merge strings. +""" import re from abc import ABC, abstractmethod @@ -37,6 +40,7 @@ class CannotTransform(Exception): + """Base class for errors raised by Transformers.""" # types @@ -54,6 +58,10 @@ def TErr(err_msg: str) -> Err[Can...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/trans.py
Add clean documentation to messy code
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. # mypy: ignore-errors # Python imports import re # Local imports from blib2to3.pgen2 import grammar, token class Converter(grammar.Grammar): def run(self, graminit_h, graminit_c): self...
--- +++ @@ -3,6 +3,30 @@ # mypy: ignore-errors +"""Convert graminit.[ch] spit out by pgen to Python code. + +Pgen is the Python parser generator. It is useful to quickly create a +parser from a grammar file in Python's grammar notation. But I don't +want my parsers to be written in C (yet), so I'm translating the...
https://raw.githubusercontent.com/psf/black/HEAD/src/blib2to3/pgen2/conv.py
Generate docstrings with parameter types
from collections.abc import Iterable, Sequence from dataclasses import dataclass, field from typing import Final, Union from black.nodes import ( BRACKET, CLOSING_BRACKETS, COMPARATORS, LOGIC_OPERATORS, MATH_OPERATORS, OPENING_BRACKETS, UNPACKING_PARENTS, VARARGS_PARENTS, is_vararg...
--- +++ @@ -1,3 +1,4 @@+"""Builds on top of nodes.py to track brackets.""" from collections.abc import Iterable, Sequence from dataclasses import dataclass, field @@ -52,10 +53,12 @@ class BracketMatchError(Exception): + """Raised when an opening bracket is unable to be matched to a closing bracket.""" ...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/brackets.py
Create documentation strings for testing functions
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. from collections.abc import Callable, Iterator from contextlib import contextmanager from typing import TYPE_CHECKING, Union, cast from blib2to3.pgen2.grammar import Grammar from blib2to3.pytree impor...
--- +++ @@ -1,6 +1,14 @@ # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. +"""Parser engine for the grammar tables generated by pgen. + +The grammar table must be loaded first. + +See Parser/parser.c in the Python distribution for additional info on...
https://raw.githubusercontent.com/psf/black/HEAD/src/blib2to3/pgen2/parse.py
Turn comments into proper docstrings
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation. # All rights reserved. # mypy: allow-untyped-defs, allow-untyped-calls import sys from collections.abc import Iterator from blib2to3.pgen2.grammar import Grammar from blib2to3.pgen2.token import ( ASYNC, AWAIT, COMMENT, D...
--- +++ @@ -3,6 +3,29 @@ # mypy: allow-untyped-defs, allow-untyped-calls +"""Tokenization help for Python programs. + +generate_tokens(readline) is a generator that breaks a stream of +text into Python tokens. It accepts a readline-like method which is called +repeatedly to get the next line of input (or "" for EO...
https://raw.githubusercontent.com/psf/black/HEAD/src/blib2to3/pgen2/tokenize.py
Generate docstrings for each module
import io import json import platform import re import sys import tokenize import traceback from collections.abc import ( Collection, Generator, MutableMapping, Sequence, ) from contextlib import nullcontext from dataclasses import replace from datetime import datetime, timezone from enum import Enum fr...
--- +++ @@ -115,6 +115,11 @@ def read_pyproject_toml( ctx: click.Context, param: click.Parameter, value: str | None ) -> str | None: + """Inject Black configuration from "pyproject.toml" into defaults in `ctx`. + + Returns the path to a successfully found and read configuration file, None + otherwise. + ...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/__init__.py
Add docstrings to make code maintainable
import hashlib import os import pickle import sys import tempfile from collections.abc import Iterable from dataclasses import dataclass, field from pathlib import Path from typing import NamedTuple from platformdirs import user_cache_dir from _black_version import version as __version__ from black.mode import Mode ...
--- +++ @@ -1,3 +1,4 @@+"""Caching of formatted files with feature-based invalidation.""" import hashlib import os @@ -28,6 +29,15 @@ def get_cache_dir() -> Path: + """Get the cache directory used by black. + + Users can customize this directory on all systems using `BLACK_CACHE_DIR` + environment vari...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/cache.py
Add docstrings for utility scripts
# # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/stable/config # -- Path setup -------------------------------------------------------------- # If extensions (or ...
--- +++ @@ -33,6 +33,7 @@ def replace_pr_numbers_with_links(content: str) -> str: + """Replaces all PR numbers with the corresponding GitHub link.""" return re.sub(r"#(\d+)", r"[#\1](https://github.com/psf/black/pull/\1)", content) @@ -42,11 +43,13 @@ parent_docname: str, content: list[str], )...
https://raw.githubusercontent.com/psf/black/HEAD/docs/conf.py
Generate docstrings with parameter types
from __future__ import annotations import asyncio import logging import os import signal import sys import traceback from collections.abc import Iterable from concurrent.futures import Executor, ProcessPoolExecutor, ThreadPoolExecutor from multiprocessing import Manager from pathlib import Path from typing import Any...
--- +++ @@ -1,3 +1,8 @@+""" +Formatting many files at once via multiprocessing. Contains entrypoint and utilities. + +NOTE: this module is only imported if we need to format several files at once. +""" from __future__ import annotations @@ -23,6 +28,12 @@ def maybe_use_uvloop() -> asyncio.AbstractEventLoop: + ...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/concurrency.py
Annotate my code with docstrings
import re from collections.abc import Collection, Iterator from dataclasses import dataclass from functools import lru_cache from typing import Final, Union from black.mode import Mode from black.nodes import ( CLOSING_BRACKETS, STANDALONE_COMMENT, STATEMENT, WHITESPACE, container_of, first_lea...
--- +++ @@ -38,6 +38,15 @@ @dataclass class ProtoComment: + """Describes a piece of syntax that is a comment. + + It's not a :class:`blib2to3.pytree.Leaf` so that: + + * it can be cached (`Leaf` objects should not be reused more than once as + they store their lineno, column, prefix, and parent informa...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/comments.py
Write docstrings describing functionality
from dataclasses import dataclass from enum import Enum from pathlib import Path from click import style from black.output import err, out class Changed(Enum): NO = 0 CACHED = 1 YES = 2 class NothingChanged(UserWarning): @dataclass class Report: check: bool = False diff: bool = False q...
--- +++ @@ -1,3 +1,6 @@+""" +Summarize Black runs to users. +""" from dataclasses import dataclass from enum import Enum @@ -15,10 +18,12 @@ class NothingChanged(UserWarning): + """Raised when reformatted code is the same as source.""" @dataclass class Report: + """Provides a reformatting counter. C...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/report.py
Generate consistent documentation across files
import re import sys from collections.abc import Collection, Iterator from dataclasses import replace from enum import Enum, auto from functools import partial, wraps from typing import Union, cast from black.brackets import ( COMMA_PRIORITY, DOT_PRIORITY, STRING_PRIORITY, get_leaves_inside_matching_b...
--- +++ @@ -1,3 +1,6 @@+""" +Generating lines of code. +""" import re import sys @@ -96,11 +99,17 @@ class CannotSplit(CannotTransform): + """A readable split that fits the allotted line length is impossible.""" # This isn't a dataclass because @dataclass + Generic breaks mypyc. # See also https://gith...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/linegen.py
Generate NumPy-style docstrings
import io import os import sys from collections.abc import Iterable, Iterator, Sequence from functools import lru_cache from pathlib import Path from re import Pattern from typing import TYPE_CHECKING, Any, Union from mypy_extensions import mypyc_attr from packaging.specifiers import InvalidSpecifier, Specifier, Speci...
--- +++ @@ -47,6 +47,21 @@ def find_project_root( srcs: Sequence[str], stdin_filename: str | None = None ) -> tuple[Path, str]: + """Return a directory containing .git, .hg, or pyproject.toml. + + pyproject.toml files are only considered if they contain a [tool.black] + section and are ignored otherwise....
https://raw.githubusercontent.com/psf/black/HEAD/src/black/files.py
Document functions with clear intent
from blib2to3.pytree import Leaf def format_hex(text: str) -> str: before, after = text[:2], text[2:] return f"{before}{after.upper()}" def format_scientific_notation(text: str) -> str: before, after = text.split("e") sign = "" if after.startswith("-"): after = after[1:] sign = ...
--- +++ @@ -1,13 +1,20 @@+""" +Formatting numeric literals. +""" from blib2to3.pytree import Leaf def format_hex(text: str) -> str: + """ + Formats a hexadecimal string like "0x12B3" + """ before, after = text[:2], text[2:] return f"{before}{after.upper()}" def format_scientific_notation...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/numerics.py
Add professional docstrings to my codebase
from collections.abc import Iterator from typing import Final, Generic, Literal, TypeGuard, TypeVar, Union from mypy_extensions import mypyc_attr from black.cache import CACHE_DIR from black.mode import Mode, Preview from black.strings import get_string_prefix, has_triple_quotes from blib2to3 import pygram from blib...
--- +++ @@ -1,3 +1,6 @@+""" +blib2to3 Node/Leaf transformation-related utility functions. +""" from collections.abc import Iterator from typing import Final, Generic, Literal, TypeGuard, TypeVar, Union @@ -141,8 +144,18 @@ @mypyc_attr(allow_interpreted_subclasses=True) class Visitor(Generic[T]): + """Basic li...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/nodes.py
Add standardized docstrings across the file
import itertools import math from collections.abc import Callable, Iterator, Sequence from dataclasses import dataclass, field from typing import Optional, TypeVar, Union, cast from black.brackets import COMMA_PRIORITY, DOT_PRIORITY, BracketTracker from black.mode import Mode from black.nodes import ( BRACKETS, ...
--- +++ @@ -38,6 +38,7 @@ @dataclass class Line: + """Holds leaves and comments. Can be printed with `str(line)`.""" mode: Mode = field(repr=False) depth: int = 0 @@ -52,6 +53,15 @@ def append( self, leaf: Leaf, preformatted: bool = False, track_bracket: bool = False ) -> None: + ...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/lines.py
Add detailed docstrings explaining each function
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. # Modifications: # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. __author__ = "Guido van Rossum <guido@python.org>" __all__ = ["Driver", "load_gram...
--- +++ @@ -5,6 +5,11 @@ # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. +"""Parser driver. + +This provides a high-level interface to parse a file into a syntax tree. + +""" __author__ = "Guido van Rossum <guido@python.org>" @@ -108,6 +113,7 @@ self.l...
https://raw.githubusercontent.com/psf/black/HEAD/src/blib2to3/pgen2/driver.py
Add docstrings to make code maintainable
import ast import collections import dataclasses import re import secrets import string from collections.abc import Collection from functools import lru_cache from importlib.util import find_spec from typing import TypeGuard from black.mode import Mode from black.output import out from black.report import NothingChan...
--- +++ @@ -1,3 +1,4 @@+"""Functions to process IPython magics with.""" import ast import collections @@ -61,6 +62,22 @@ def validate_cell(src: str, mode: Mode) -> None: + r"""Check that cell does not already contain TransformerManager transformations, + or non-Python cell magics, which might cause tokeni...
https://raw.githubusercontent.com/psf/black/HEAD/src/black/handle_ipynb_magics.py
Add docstrings to improve collaboration
# Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
--- +++ @@ -35,6 +35,37 @@ metric_key_prefix: str = "eval", **gen_kwargs ) -> Dict[str, float]: + """ + Run evaluation and returns metrics. + + The calling script will be responsible for providing a method to compute metrics, as they are task-dependent + (pass it to the...
https://raw.githubusercontent.com/zai-org/ChatGLM-6B/HEAD/ptuning/trainer_seq2seq.py
Generate docstrings with examples
from dataclasses import dataclass, field from typing import Optional @dataclass class ModelArguments: model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) ptuning_checkpoint: str = field( default=None, metadata={"h...
--- +++ @@ -4,6 +4,9 @@ @dataclass class ModelArguments: + """ + Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. + """ model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} @@ -60,6 +...
https://raw.githubusercontent.com/zai-org/ChatGLM-6B/HEAD/ptuning/arguments.py
Add docstrings for better understanding
# coding=utf-8 # Copyright 2020-present the HuggingFace Inc. team. # # 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 ap...
--- +++ @@ -12,6 +12,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task. +""" impo...
https://raw.githubusercontent.com/zai-org/ChatGLM-6B/HEAD/ptuning/trainer.py
Generate missing documentation strings
import cache def save_query(client_id, query): cache.put("l:%s" % client_id, query) def last_query(client_id): return cache.get("l:%s" % client_id)
--- +++ @@ -1,10 +1,19 @@+""" +Support for the stateful queries +""" import cache def save_query(client_id, query): + """ + Save the last query `query` for the client `client_id` + """ cache.put("l:%s" % client_id, query) def last_query(client_id): - return cache.get("l:%s" % client_id)+ ...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/stateful_queries.py
Write docstrings for utility functions
import glob import os from .adapter import Adapter # pylint: disable=relative-import def _get_filenames(path): return [os.path.split(topic)[1] for topic in glob.glob(path)] class RepositoryAdapter(Adapter): def _get_list(self, prefix=None): answer = _get_filenames( os.path.join( ...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation of `GitRepositoryAdapter`, adapter that is used to handle git repositories +""" import glob import os @@ -10,8 +13,16 @@ class RepositoryAdapter(Adapter): + """ + Implements methods needed to handle standard + repository based adapters. + """ def _g...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/adapter/git_adapter.py
Document all public functions with docstrings
import time from globals import log _WHITELIST = ["5.9.243.177"] def _time_caps(minutes, hours, days): return { "min": minutes, "hour": hours, "day": days, } class Limits(object): def __init__(self): self.intervals = ["min", "hour", "day"] self.divisor = _time...
--- +++ @@ -1,3 +1,20 @@+""" +Connection limitation. + +Number of connections from one IP is limited. +We have nothing against scripting and automated queries. +Even the opposite, we encourage them. But there are some +connection limits that even we can't handle. +Currently the limits are quite restrictive, but they wi...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/limits.py
Write docstrings for backend logic
import abc import os from six import with_metaclass from config import CONFIG class AdapterMC(type): def __repr__(cls): if hasattr(cls, "_class_repr"): return getattr(cls, "_class_repr")() return super(AdapterMC, cls).__repr__() class Adapter(with_metaclass(AdapterMC, object)): ...
--- +++ @@ -1,3 +1,10 @@+""" +`Adapter`, base class of the adapters. + +Configuration parameters: + + path.repositories +""" import abc import os @@ -6,6 +13,10 @@ class AdapterMC(type): + """ + Adapter Metaclass. + Defines string representation of adapters + """ def __repr__(cls): ...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/adapter/adapter.py
Write docstrings for data processing functions
from __future__ import print_function import os from pygments.styles import get_all_styles # def get_all_styles(): # return [] _ENV_VAR_PREFIX = "CHEATSH" _MYDIR = os.path.abspath(os.path.join(__file__, "..", "..")) def _config_locations(): var = _ENV_VAR_PREFIX + "_PATH_WORKDIR" workdir = ( ...
--- +++ @@ -1,3 +1,45 @@+""" +Global configuration of the project. + +All configurable parameters are stored in the global variable CONFIG, +the only variable which is exported from the module. + +Default values of all configuration parameters are specified +in the `_CONFIG` dictionary. Those parameters can be overridd...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/config.py
Generate missing documentation strings
import os import json from config import CONFIG _REDIS = None if CONFIG["cache.type"] == "redis": import redis _REDIS = redis.Redis( host=CONFIG["cache.redis.host"], port=CONFIG["cache.redis.port"], db=CONFIG["cache.redis.db"], ) _REDIS_PREFIX = "" if CONFIG.get("cache.redis.pref...
--- +++ @@ -1,3 +1,16 @@+""" +Cache implementation. +Currently only two types of cache are allowed: + * "none" cache switched off + * "redis" use redis for cache + +Configuration parameters: + + cache.type = redis | none + cache.redis.db + cache.redis.host + cache.redis.port +""" import os im...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/cache.py
Add well-formatted docstrings
import re import json from routing import get_answers, get_topics_list from search import find_answers_by_keyword from languages_data import LANGUAGE_ALIAS, rewrite_editor_section_name import postprocessing import frontend.html import frontend.ansi def _add_section_name(query): # temporary solution before we d...
--- +++ @@ -1,3 +1,12 @@+""" +Main cheat.sh wrapper. +Parse the query, get answers from getters (using get_answer), +visualize it using frontends and return the result. + +Exports: + + cheat_wrapper() +""" import re import json @@ -25,6 +34,11 @@ def cheat_wrapper(query, request_options=None, output_format="...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/cheat_wrapper.py
Write docstrings for this repository
import string import os import random from config import CONFIG def _save_cheatsheet(topic_name, cheatsheet): nonce = "".join( random.choice(string.ascii_uppercase + string.digits) for _ in range(9) ) filename = topic_name.replace("/", ".") + "." + nonce filename = os.path.join(CONFIG["path....
--- +++ @@ -1,3 +1,11 @@+""" +POST requests processing. +Currently used only for new cheat sheets submission. + +Configuration parameters: + + path.spool +""" import string import os @@ -6,6 +14,10 @@ def _save_cheatsheet(topic_name, cheatsheet): + """ + Save posted cheat sheet `cheatsheet` with `topic...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/post.py
Replace inline comments with docstrings
#!/usr/bin/env python # vim: set encoding=utf-8 # pylint: disable=wrong-import-position,wrong-import-order from __future__ import print_function import sys if sys.version_info[0] < 3: reload(sys) sys.setdefaultencoding("utf8") import sys import logging import os import requests import jinja2 from flask imp...
--- +++ @@ -2,6 +2,17 @@ # vim: set encoding=utf-8 # pylint: disable=wrong-import-position,wrong-import-order +""" +Main server program. + +Configuration parameters: + + path.internal.malformed + path.internal.static + path.internal.templates + path.log.main + path.log.queries +""" from __future__ ...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/bin/app.py
Generate docstrings for this script
# vim: encoding=utf-8 import os import sys import colored import itertools from globals import MYDIR """ After panela will be ready for it, it will be split out in a separate project, that will be used for all chubin's console services. There are several features that not yet implemented (see ___doc___ in Panela) T...
--- +++ @@ -37,6 +37,9 @@ class Point(object): + """ + One point (character) on a terminal + """ def __init__(self, char=None, foreground=None, background=None): self.foreground = foreground @@ -45,6 +48,40 @@ class Panela: + """ + To implement: + + Blocks manipulation: + + ...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/panela/panela_colors.py
Write docstrings for this repository
# pylint: disable=relative-import from __future__ import print_function import os import re from subprocess import Popen, PIPE from polyglot.detect import Detector from polyglot.detect.base import UnknownLanguage from config import CONFIG from languages_data import SO_NAME from .upstream import UpstreamAdapter NO...
--- +++ @@ -1,3 +1,8 @@+""" +Configuration parameters: + + path.internal.bin.upstream +""" # pylint: disable=relative-import @@ -35,12 +40,24 @@ class Question(UpstreamAdapter): + """ + Answer to a programming language question, using Stackoverflow + as the main data source. Heavy lifting is done b...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/adapter/question.py
Add concise docstrings to each method
import random import re from typing import Any, Dict, List import cache import adapter.cheat_sheets import adapter.cmd import adapter.internal import adapter.latenz import adapter.learnxiny import adapter.question import adapter.rosetta from config import CONFIG class Router(object): def __init__(self): ...
--- +++ @@ -1,3 +1,11 @@+""" +Queries routing and caching. + +Exports: + + get_topics_list() + get_answers() +""" import random import re @@ -15,6 +23,13 @@ class Router(object): + """ + Implementation of query routing. Routing is based on `routing_table` + and the data exported by the adapters (...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/routing.py
Generate helpful docstrings for debugging
import sys import os import re from subprocess import Popen, PIPE MYDIR = os.path.abspath(os.path.join(__file__, "..", "..")) sys.path.append("%s/lib/" % MYDIR) # pylint: disable=wrong-import-position from config import CONFIG from globals import error from buttons import TWITTER_BUTTON, GITHUB_BUTTON, GITHUB_BUTTON...
--- +++ @@ -1,3 +1,9 @@+""" + +Configuration parameters: + + path.internal.ansi2html +""" import sys import os @@ -73,6 +79,9 @@ ): def _html_wrapper(data): + """ + Convert ANSI text `data` to HTML + """ cmd = [ "bash", CONFIG["path.internal.ansi2htm...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/frontend/html.py
Write proper docstrings for these functions
# pylint: disable=relative-import,abstract-method import re import os from .git_adapter import GitRepositoryAdapter class Tldr(GitRepositoryAdapter): _adapter_name = "tldr" _output_format = "code" _cache_needed = True _repository_url = "https://github.com/tldr-pages/tldr" _cheatsheet_files_pre...
--- +++ @@ -1,3 +1,11 @@+""" +Adapter for https://github.com/cheat/cheat + +Cheatsheets are located in `pages/*/` +Each cheat sheet is a separate file with extension .md + +The pages are formatted with a markdown dialect +""" # pylint: disable=relative-import,abstract-method @@ -8,6 +16,9 @@ class Tldr(GitRepo...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/adapter/tldr.py
Add docstrings to clarify complex logic
from __future__ import print_function import sys import textwrap try: import urlparse except ModuleNotFoundError: import urllib.parse as urlparse import config config.CONFIG["cache.type"] = "none" import cheat_wrapper import options def show_usage(): print( textwrap.dedent( """ ...
--- +++ @@ -1,3 +1,6 @@+""" +Standalone wrapper for the cheat.sh server. +""" from __future__ import print_function @@ -18,6 +21,9 @@ def show_usage(): + """ + Show how to use the program in the standalone mode + """ print( textwrap.dedent( @@ -33,6 +39,10 @@ def parse_cmdline(args...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/standalone.py
Annotate my code with docstrings
# pylint: disable=unused-argument,abstract-method import os.path import re from subprocess import Popen, PIPE from .adapter import Adapter def _get_abspath(path): if path.startswith("/"): return path import __main__ return os.path.join(os.path.dirname(os.path.dirname(__main__.__file__)), pat...
--- +++ @@ -1,3 +1,4 @@+""" """ # pylint: disable=unused-argument,abstract-method @@ -9,6 +10,9 @@ def _get_abspath(path): + """Find absolute path of the specified `path` + according to its + """ if path.startswith("/"): return path @@ -19,6 +23,7 @@ class CommandAdapter(Adapter): ...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/adapter/cmd.py
Add clean documentation to messy code
from __future__ import print_function import sys import logging import os import subprocess import textwrap from globals import fatal import adapter import cache from config import CONFIG def _log(*message): logging.info(*message) if len(message) > 1: message = message[0].rstrip("\n") % tuple(mess...
--- +++ @@ -1,3 +1,14 @@+""" +Repositories fetch and update + +This module makes real network and OS interaction, +and the adapters only say how exctly this interaction +should be done. + +Configuration parameters: + + * path.log.fetch +""" from __future__ import print_function @@ -34,6 +45,9 @@ def fetch_a...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/fetch.py
Create docstrings for all classes and functions
# pylint: disable=relative-import import os import glob from .git_adapter import GitRepositoryAdapter def _remove_initial_underscore(filename): if filename.startswith("_"): filename = filename[1:] return filename def _sanitize_dirnames(filename, restore=False): parts = filename.split("/") ...
--- +++ @@ -1,3 +1,8 @@+""" +Implementation of the adapter for the native cheat.sh cheat sheets repository, +cheat.sheets. The cheat sheets repository is hierarchically structured: cheat +sheets covering programming languages are are located in subdirectories. +""" # pylint: disable=relative-import @@ -14,6 +19,1...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/adapter/cheat_sheets.py
Add detailed documentation for each class
# pylint: disable=relative-import import textwrap import requests from config import CONFIG from .adapter import Adapter def _are_you_offline(): return textwrap.dedent( """ . Are you offline? _________________ | | ___________ |o| Though it coul...
--- +++ @@ -1,3 +1,11 @@+""" +Adapter for an external cheat sheets service (i.e. for cheat.sh) + +Configuration parameters: + + upstream.url + upstream.timeout +""" # pylint: disable=relative-import @@ -30,6 +38,15 @@ class UpstreamAdapter(Adapter): + """ + Connect to the upstream server `CONFIG["u...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/adapter/upstream.py
Add verbose docstrings with examples
import os import sys import re import colored from pygments import highlight as pygments_highlight from pygments.formatters import ( Terminal256Formatter, ) # pylint: disable=no-name-in-module # pylint: disable=wrong-import-position sys.path.append(os.path.abspath(os.path.join(__file__, ".."))) from config impo...
--- +++ @@ -1,3 +1,26 @@+""" +ANSI frontend. + +Exports: + visualize(answer_data, request_options) + +Format: + answer_data = { + 'answers': '...',} + + answers = [answer,...] + + answer = { + 'topic': '...', + 'topic_type': '...', + 'answer': '...', + 'form...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/frontend/ansi.py
Include argument descriptions in docstrings
import re import ansiwrap import colored def format_text(text, config=None, highlighter=None): return _format_section(text, config=config, highlighter=highlighter) def _split_into_paragraphs(text): return re.split("\n\n+", text) def _colorize(text): return re.sub( r"`(.*?)`", colored....
--- +++ @@ -1,3 +1,11 @@+""" +Markdown support. + +Exports: + format_text(text, config=None, highlighter=None): + +Uses external pygments formatters for highlighting (passed as an argument). +""" import re import ansiwrap @@ -5,6 +13,11 @@ def format_text(text, config=None, highlighter=None): + """ + R...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/fmt/markdown.py
Write docstrings describing each step
import re from colorama import Fore, Back, Style import colored PALETTES = { 0: { 1: Fore.WHITE, 2: Style.DIM, }, 1: { 1: Fore.CYAN, 2: Fore.GREEN, 3: colored.fg("orange_3"), 4: Style.DIM, 5: Style.DIM, }, 2: { 1: Fore.RED, 2...
--- +++ @@ -1,3 +1,7 @@+""" +Colorize internal cheat sheets. +Will be merged with panela later. +""" import re @@ -39,6 +43,9 @@ def colorize_internal(text, palette_number=1): + """ + Colorize `text`, use `palette` + """ palette = PALETTES[palette_number] palette_reverse = _reverse_palette...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/fmt/internal.py
Write docstrings that follow conventions
import pygments.lexers LEXER = { "assembly": pygments.lexers.NasmLexer, "awk": pygments.lexers.AwkLexer, "bash": pygments.lexers.BashLexer, "basic": pygments.lexers.QBasicLexer, "bf": pygments.lexers.BrainfuckLexer, "chapel": pygments.lexers.ChapelLexer, "clojure": pygments.lexers.ClojureL...
--- +++ @@ -1,3 +1,10 @@+""" + +Programming languages information. +Will be (probably) moved to a separate file/directory +from the project tree. + +""" import pygments.lexers @@ -218,6 +225,24 @@ def rewrite_editor_section_name(section_name): + """ + section name cen be specified in form "editor:editor-...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/languages_data.py
Document functions with clear intent
import re from config import CONFIG from routing import get_answers, get_topics_list def _limited_entry(): return { "topic_type": "LIMITED", "topic": "LIMITED", "answer": "LIMITED TO %s ANSWERS" % CONFIG["search.limit"], "format": "code", } def _parse_options(options): ...
--- +++ @@ -1,3 +1,23 @@+""" +Very naive search implementation. Just a placeholder. + +Exports: + + find_answer_by_keyword() + +It should be implemented on the adapter basis: + + 1. adapter.search(keyword) returns list of matching answers + * maybe with some initial weight + 2. ranking is done + 3. s...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/search.py