instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Document this script properly |
import time
import random
import functools
from typing import Callable, Any, Optional, Type, Tuple
from ..utils.logger import get_logger
logger = get_logger('mirofish.retry')
def retry_with_backoff(
max_retries: int = 3,
initial_delay: float = 1.0,
max_delay: float = 30.0,
backoff_factor: float = 2.... | --- +++ @@ -1,3 +1,7 @@+"""
+API调用重试机制
+用于处理LLM等外部API调用的重试逻辑
+"""
import time
import random
@@ -17,6 +21,23 @@ exceptions: Tuple[Type[Exception], ...] = (Exception,),
on_retry: Optional[Callable[[Exception, int], None]] = None
):
+ """
+ 带指数退避的重试装饰器
+
+ Args:
+ max_retries: 最大重试次数
+ ... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/utils/retry.py |
Add return value explanations in docstrings |
import argparse
import asyncio
import json
import logging
import os
import random
import signal
import sys
import sqlite3
from datetime import datetime
from typing import Dict, Any, List, Optional
# 全局变量:用于信号处理
_shutdown_event = None
_cleanup_done = False
# 添加项目路径
_scripts_dir = os.path.dirname(os.path.abspath(__fil... | --- +++ @@ -1,3 +1,17 @@+"""
+OASIS Reddit模拟预设脚本
+此脚本读取配置文件中的参数来执行模拟,实现全程自动化
+
+功能特性:
+- 完成模拟后不立即关闭环境,进入等待命令模式
+- 支持通过IPC接收Interview命令
+- 支持单个Agent采访和批量采访
+- 支持远程关闭环境命令
+
+使用方式:
+ python run_reddit_simulation.py --config /path/to/simulation_config.json
+ python run_reddit_simulation.py --config /path/to/simulatio... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/scripts/run_reddit_simulation.py |
Add professional docstrings to my codebase |
import os
import sys
import json
import time
import asyncio
import threading
import subprocess
import signal
import atexit
from typing import Dict, Any, List, Optional, Union
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from queue import Queue
from ..config import Confi... | --- +++ @@ -1,3 +1,7 @@+"""
+OASIS模拟运行器
+在后台运行模拟并记录每个Agent的动作,支持实时状态监控
+"""
import os
import sys
@@ -29,6 +33,7 @@
class RunnerStatus(str, Enum):
+ """运行器状态"""
IDLE = "idle"
STARTING = "starting"
RUNNING = "running"
@@ -41,6 +46,7 @@
@dataclass
class AgentAction:
+ """Agent动作记录"""
r... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/services/simulation_runner.py |
Add detailed docstrings explaining each function |
import json
import os
import logging
from datetime import datetime
from typing import Dict, Any, Optional
class PlatformActionLogger:
def __init__(self, platform: str, base_dir: str):
self.platform = platform
self.base_dir = base_dir
self.log_dir = os.path.join(base_dir, platform)
... | --- +++ @@ -1,3 +1,16 @@+"""
+动作日志记录器
+用于记录OASIS模拟中每个Agent的动作,供后端监控使用
+
+日志结构:
+ sim_xxx/
+ ├── twitter/
+ │ └── actions.jsonl # Twitter 平台动作日志
+ ├── reddit/
+ │ └── actions.jsonl # Reddit 平台动作日志
+ ├── simulation.log # 主模拟进程日志
+ └── run_state.json # 运行状态(API 查询用)
+"""
impor... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/scripts/action_logger.py |
Write beginner-friendly docstrings |
import os
import sys
import logging
from datetime import datetime
from logging.handlers import RotatingFileHandler
def _ensure_utf8_stdout():
if sys.platform == 'win32':
# Windows 下重新配置标准输出为 UTF-8
if hasattr(sys.stdout, 'reconfigure'):
sys.stdout.reconfigure(encoding='utf-8', errors='... | --- +++ @@ -1,3 +1,7 @@+"""
+日志配置模块
+提供统一的日志管理,同时输出到控制台和文件
+"""
import os
import sys
@@ -7,6 +11,10 @@
def _ensure_utf8_stdout():
+ """
+ 确保 stdout/stderr 使用 UTF-8 编码
+ 解决 Windows 控制台中文乱码问题
+ """
if sys.platform == 'win32':
# Windows 下重新配置标准输出为 UTF-8
if hasattr(sys.stdout, 're... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/utils/logger.py |
Add docstrings to clarify complex logic |
from __future__ import annotations
import time
from collections.abc import Callable
from typing import Any
from zep_cloud import InternalServerError
from zep_cloud.client import Zep
from .logger import get_logger
logger = get_logger('mirofish.zep_paging')
_DEFAULT_PAGE_SIZE = 100
_MAX_NODES = 2000
_DEFAULT_MAX_RE... | --- +++ @@ -1,3 +1,8 @@+"""Zep Graph 分页读取工具。
+
+Zep 的 node/edge 列表接口使用 UUID cursor 分页,
+本模块封装自动翻页逻辑(含单页重试),对调用方透明地返回完整列表。
+"""
from __future__ import annotations
@@ -26,6 +31,7 @@ page_description: str = "page",
**kwargs: Any,
) -> list[Any]:
+ """单页请求,失败时指数退避重试。仅重试网络/IO类瞬态错误。"""
if max_retries <... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/utils/zep_paging.py |
Add docstrings that explain inputs and outputs |
import argparse
import asyncio
import json
import logging
import os
import random
import signal
import sys
import sqlite3
from datetime import datetime
from typing import Dict, Any, List, Optional
# 全局变量:用于信号处理
_shutdown_event = None
_cleanup_done = False
# 添加项目路径
_scripts_dir = os.path.dirname(os.path.abspath(__fil... | --- +++ @@ -1,3 +1,17 @@+"""
+OASIS Twitter模拟预设脚本
+此脚本读取配置文件中的参数来执行模拟,实现全程自动化
+
+功能特性:
+- 完成模拟后不立即关闭环境,进入等待命令模式
+- 支持通过IPC接收Interview命令
+- 支持单个Agent采访和批量采访
+- 支持远程关闭环境命令
+
+使用方式:
+ python run_twitter_simulation.py --config /path/to/simulation_config.json
+ python run_twitter_simulation.py --config /path/to/simula... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/scripts/run_twitter_simulation.py |
Add docstrings for internal functions | import getpass
import requests
from rich.console import Console
from rich.panel import Panel
from cli.config import CLI_CONFIG
def fetch_announcements(url: str = None, timeout: float = None) -> dict:
endpoint = url or CLI_CONFIG["announcements_url"]
timeout = timeout or CLI_CONFIG["announcements_timeout"]
... | --- +++ @@ -7,6 +7,7 @@
def fetch_announcements(url: str = None, timeout: float = None) -> dict:
+ """Fetch announcements from endpoint. Returns dict with announcements and settings."""
endpoint = url or CLI_CONFIG["announcements_url"]
timeout = timeout or CLI_CONFIG["announcements_timeout"]
fallb... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/cli/announcements.py |
Write docstrings that follow conventions | from typing import Optional
import datetime
import typer
from pathlib import Path
from functools import wraps
from rich.console import Console
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
from rich.panel import Panel
from rich.spinner import Spinner
from rich.live import Liv... | --- +++ @@ -82,6 +82,11 @@ self._last_message_id = None
def init_for_analysis(self, selected_analysts):
+ """Initialize agent status and report sections based on selected analysts.
+
+ Args:
+ selected_analysts: List of analyst type strings (e.g., ["market", "news"])
+ """... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/cli/main.py |
Add minimal docstrings for each function | import questionary
from typing import List, Optional, Tuple, Dict
from rich.console import Console
from cli.models import AnalystType
console = Console()
ANALYST_ORDER = [
("Market Analyst", AnalystType.MARKET),
("Social Media Analyst", AnalystType.SOCIAL),
("News Analyst", AnalystType.NEWS),
("Fund... | --- +++ @@ -16,6 +16,7 @@
def get_ticker() -> str:
+ """Prompt the user to enter a ticker symbol."""
ticker = questionary.text(
"Enter the ticker symbol to analyze:",
validate=lambda x: len(x.strip()) > 0 or "Please enter a valid ticker symbol.",
@@ -35,6 +36,7 @@
def get_analysis_date... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/cli/utils.py |
Provide docstrings following PEP 257 | import threading
from typing import Any, Dict, List, Union
from langchain_core.callbacks import BaseCallbackHandler
from langchain_core.outputs import LLMResult
from langchain_core.messages import AIMessage
class StatsCallbackHandler(BaseCallbackHandler):
def __init__(self) -> None:
super().__init__()
... | --- +++ @@ -7,6 +7,7 @@
class StatsCallbackHandler(BaseCallbackHandler):
+ """Callback handler that tracks LLM calls, tool calls, and token usage."""
def __init__(self) -> None:
super().__init__()
@@ -22,6 +23,7 @@ prompts: List[str],
**kwargs: Any,
) -> None:
+ """In... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/cli/stats_handler.py |
Add inline docstrings for readability | from .alpha_vantage_common import _make_api_request, format_datetime_for_api
def get_news(ticker, start_date, end_date) -> dict[str, str] | str:
params = {
"tickers": ticker,
"time_from": format_datetime_for_api(start_date),
"time_to": format_datetime_for_api(end_date),
}
return _... | --- +++ @@ -1,6 +1,18 @@ from .alpha_vantage_common import _make_api_request, format_datetime_for_api
def get_news(ticker, start_date, end_date) -> dict[str, str] | str:
+ """Returns live and historical market news & sentiment data from premier news outlets worldwide.
+
+ Covers stocks, cryptocurrencies, forex... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/dataflows/alpha_vantage_news.py |
Add return value explanations in docstrings |
from rank_bm25 import BM25Okapi
from typing import List, Tuple
import re
class FinancialSituationMemory:
def __init__(self, name: str, config: dict = None):
self.name = name
self.documents: List[str] = []
self.recommendations: List[str] = []
self.bm25 = None
def _tokenize(se... | --- +++ @@ -1,3 +1,8 @@+"""Financial situation memory using BM25 for lexical similarity matching.
+
+Uses BM25 (Best Matching 25) algorithm for retrieval - no API calls,
+no token limits, works offline with any LLM provider.
+"""
from rank_bm25 import BM25Okapi
from typing import List, Tuple
@@ -5,19 +10,31 @@
... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/agents/utils/memory.py |
Add well-formatted docstrings | from langchain_core.tools import tool
from typing import Annotated
from tradingagents.dataflows.interface import route_to_vendor
@tool
def get_news(
ticker: Annotated[str, "Ticker symbol"],
start_date: Annotated[str, "Start date in yyyy-mm-dd format"],
end_date: Annotated[str, "End date in yyyy-mm-dd forma... | --- +++ @@ -8,6 +8,16 @@ start_date: Annotated[str, "Start date in yyyy-mm-dd format"],
end_date: Annotated[str, "End date in yyyy-mm-dd format"],
) -> str:
+ """
+ Retrieve news data for a given ticker symbol.
+ Uses the configured news_data vendor.
+ Args:
+ ticker (str): Ticker symbol
+ ... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/agents/utils/news_data_tools.py |
Annotate my code with docstrings | from .alpha_vantage_common import _make_api_request
def get_fundamentals(ticker: str, curr_date: str = None) -> str:
params = {
"symbol": ticker,
}
return _make_api_request("OVERVIEW", params)
def get_balance_sheet(ticker: str, freq: str = "quarterly", curr_date: str = None) -> str:
params ... | --- +++ @@ -2,6 +2,16 @@
def get_fundamentals(ticker: str, curr_date: str = None) -> str:
+ """
+ Retrieve comprehensive fundamental data for a given ticker symbol using Alpha Vantage.
+
+ Args:
+ ticker (str): Ticker symbol of the company
+ curr_date (str): Current date you are trading at, y... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/dataflows/alpha_vantage_fundamentals.py |
Write proper docstrings for these functions | import tradingagents.default_config as default_config
from typing import Dict, Optional
# Use default config but allow it to be overridden
_config: Optional[Dict] = None
def initialize_config():
global _config
if _config is None:
_config = default_config.DEFAULT_CONFIG.copy()
def set_config(config:... | --- +++ @@ -6,12 +6,14 @@
def initialize_config():
+ """Initialize the configuration with default values."""
global _config
if _config is None:
_config = default_config.DEFAULT_CONFIG.copy()
def set_config(config: Dict):
+ """Update the configuration with custom values."""
global ... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/dataflows/config.py |
Please document this code using docstrings | import os
import requests
import pandas as pd
import json
from datetime import datetime
from io import StringIO
API_BASE_URL = "https://www.alphavantage.co/query"
def get_api_key() -> str:
api_key = os.getenv("ALPHA_VANTAGE_API_KEY")
if not api_key:
raise ValueError("ALPHA_VANTAGE_API_KEY environment ... | --- +++ @@ -8,12 +8,14 @@ API_BASE_URL = "https://www.alphavantage.co/query"
def get_api_key() -> str:
+ """Retrieve the API key for Alpha Vantage from environment variables."""
api_key = os.getenv("ALPHA_VANTAGE_API_KEY")
if not api_key:
raise ValueError("ALPHA_VANTAGE_API_KEY environment vari... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/dataflows/alpha_vantage_common.py |
Add docstrings including usage examples | from typing import Annotated
# Import from vendor-specific modules
from .y_finance import (
get_YFin_data_online,
get_stock_stats_indicators_window,
get_fundamentals as get_yfinance_fundamentals,
get_balance_sheet as get_yfinance_balance_sheet,
get_cashflow as get_yfinance_cashflow,
get_income_... | --- +++ @@ -110,12 +110,16 @@ }
def get_category_for_method(method: str) -> str:
+ """Get the category that contains the specified method."""
for category, info in TOOLS_CATEGORIES.items():
if method in info["tools"]:
return category
raise ValueError(f"Method '{method}' not found i... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/dataflows/interface.py |
Help me document legacy Python code | from typing import Annotated
from datetime import datetime
from dateutil.relativedelta import relativedelta
import yfinance as yf
import os
from .stockstats_utils import StockstatsUtils, _clean_dataframe
def get_YFin_data_online(
symbol: Annotated[str, "ticker symbol of the company"],
start_date: Annotated[str... | --- +++ @@ -189,6 +189,11 @@ indicator: Annotated[str, "technical indicator to calculate"],
curr_date: Annotated[str, "current date for reference"]
) -> dict:
+ """
+ Optimized bulk calculation of stock stats indicators.
+ Fetches data once and calculates indicator for all available dates.
+ Retur... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/dataflows/y_finance.py |
Add missing documentation to my Python functions | # TradingAgents/graph/reflection.py
from typing import Dict, Any
from langchain_openai import ChatOpenAI
class Reflector:
def __init__(self, quick_thinking_llm: ChatOpenAI):
self.quick_thinking_llm = quick_thinking_llm
self.reflection_system_prompt = self._get_reflection_prompt()
def _get_r... | --- +++ @@ -5,12 +5,15 @@
class Reflector:
+ """Handles reflection on decisions and updating memory."""
def __init__(self, quick_thinking_llm: ChatOpenAI):
+ """Initialize the reflector with an LLM."""
self.quick_thinking_llm = quick_thinking_llm
self.reflection_system_prompt = se... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/graph/reflection.py |
Generate docstrings for this script |
import yfinance as yf
from datetime import datetime
from dateutil.relativedelta import relativedelta
def _extract_article_data(article: dict) -> dict:
# Handle nested content structure
if "content" in article:
content = article["content"]
title = content.get("title", "No title")
summa... | --- +++ @@ -1,3 +1,4 @@+"""yfinance-based news data fetching functions."""
import yfinance as yf
from datetime import datetime
@@ -5,6 +6,7 @@
def _extract_article_data(article: dict) -> dict:
+ """Extract article data from yfinance news format (handles nested 'content' structure)."""
# Handle nested co... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/dataflows/yfinance_news.py |
Auto-generate documentation strings for this file | # TradingAgents/graph/setup.py
from typing import Dict, Any
from langchain_openai import ChatOpenAI
from langgraph.graph import END, StateGraph, START
from langgraph.prebuilt import ToolNode
from tradingagents.agents import *
from tradingagents.agents.utils.agent_states import AgentState
from .conditional_logic impo... | --- +++ @@ -12,6 +12,7 @@
class GraphSetup:
+ """Handles the setup and configuration of the agent graph."""
def __init__(
self,
@@ -25,6 +26,7 @@ risk_manager_memory,
conditional_logic: ConditionalLogic,
):
+ """Initialize with required components."""
self.qu... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/graph/setup.py |
Document functions with detailed explanations | # TradingAgents/graph/conditional_logic.py
from tradingagents.agents.utils.agent_states import AgentState
class ConditionalLogic:
def __init__(self, max_debate_rounds=1, max_risk_discuss_rounds=1):
self.max_debate_rounds = max_debate_rounds
self.max_risk_discuss_rounds = max_risk_discuss_rounds
... | --- +++ @@ -4,12 +4,15 @@
class ConditionalLogic:
+ """Handles conditional logic for determining graph flow."""
def __init__(self, max_debate_rounds=1, max_risk_discuss_rounds=1):
+ """Initialize with configuration parameters."""
self.max_debate_rounds = max_debate_rounds
self.max... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/graph/conditional_logic.py |
Write docstrings for this repository | from abc import ABC, abstractmethod
from typing import Any, Optional
class BaseLLMClient(ABC):
def __init__(self, model: str, base_url: Optional[str] = None, **kwargs):
self.model = model
self.base_url = base_url
self.kwargs = kwargs
@abstractmethod
def get_llm(self) -> Any:
... | --- +++ @@ -3,6 +3,7 @@
class BaseLLMClient(ABC):
+ """Abstract base class for LLM clients."""
def __init__(self, model: str, base_url: Optional[str] = None, **kwargs):
self.model = model
@@ -11,8 +12,10 @@
@abstractmethod
def get_llm(self) -> Any:
+ """Return the configured LLM... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/llm_clients/base_client.py |
Add detailed docstrings explaining each function | # TradingAgents/graph/propagation.py
from typing import Dict, Any, List, Optional
from tradingagents.agents.utils.agent_states import (
AgentState,
InvestDebateState,
RiskDebateState,
)
class Propagator:
def __init__(self, max_recur_limit=100):
self.max_recur_limit = max_recur_limit
def... | --- +++ @@ -9,13 +9,16 @@
class Propagator:
+ """Handles state initialization and propagation through the graph."""
def __init__(self, max_recur_limit=100):
+ """Initialize with configuration parameters."""
self.max_recur_limit = max_recur_limit
def create_initial_state(
se... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/graph/propagation.py |
Help me document legacy Python code | from typing import Any, Optional
from langchain_anthropic import ChatAnthropic
from .base_client import BaseLLMClient
from .validators import validate_model
class AnthropicClient(BaseLLMClient):
def __init__(self, model: str, base_url: Optional[str] = None, **kwargs):
super().__init__(model, base_url, ... | --- +++ @@ -7,11 +7,13 @@
class AnthropicClient(BaseLLMClient):
+ """Client for Anthropic Claude models."""
def __init__(self, model: str, base_url: Optional[str] = None, **kwargs):
super().__init__(model, base_url, **kwargs)
def get_llm(self) -> Any:
+ """Return configured ChatAnth... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/llm_clients/anthropic_client.py |
Generate consistent documentation across files | # TradingAgents/graph/signal_processing.py
from langchain_openai import ChatOpenAI
class SignalProcessor:
def __init__(self, quick_thinking_llm: ChatOpenAI):
self.quick_thinking_llm = quick_thinking_llm
def process_signal(self, full_signal: str) -> str:
messages = [
(
... | --- +++ @@ -4,11 +4,22 @@
class SignalProcessor:
+ """Processes trading signals to extract actionable decisions."""
def __init__(self, quick_thinking_llm: ChatOpenAI):
+ """Initialize with an LLM for processing."""
self.quick_thinking_llm = quick_thinking_llm
def process_signal(self... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/graph/signal_processing.py |
Generate docstrings for exported functions | # TradingAgents/graph/trading_graph.py
import os
from pathlib import Path
import json
from datetime import date
from typing import Dict, Any, Tuple, List, Optional
from langgraph.prebuilt import ToolNode
from tradingagents.llm_clients import create_llm_client
from tradingagents.agents import *
from tradingagents.de... | --- +++ @@ -41,6 +41,7 @@
class TradingAgentsGraph:
+ """Main class that orchestrates the trading agents framework."""
def __init__(
self,
@@ -49,6 +50,14 @@ config: Dict[str, Any] = None,
callbacks: Optional[List] = None,
):
+ """Initialize the trading agents graph a... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/graph/trading_graph.py |
Document all endpoints with docstrings | from typing import Any, Optional
from langchain_google_genai import ChatGoogleGenerativeAI
from .base_client import BaseLLMClient
from .validators import validate_model
class NormalizedChatGoogleGenerativeAI(ChatGoogleGenerativeAI):
def _normalize_content(self, response):
content = response.content
... | --- +++ @@ -7,6 +7,11 @@
class NormalizedChatGoogleGenerativeAI(ChatGoogleGenerativeAI):
+ """ChatGoogleGenerativeAI with normalized content output.
+
+ Gemini 3 models return content as list: [{'type': 'text', 'text': '...'}]
+ This normalizes to string for consistent downstream handling.
+ """
... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/llm_clients/google_client.py |
Document this module using docstrings | import os
from typing import Any, Optional
from langchain_openai import ChatOpenAI
from .base_client import BaseLLMClient
from .validators import validate_model
class UnifiedChatOpenAI(ChatOpenAI):
def __init__(self, **kwargs):
if "gpt-5" in kwargs.get("model", "").lower():
kwargs.pop("temp... | --- +++ @@ -8,6 +8,16 @@
class UnifiedChatOpenAI(ChatOpenAI):
+ """ChatOpenAI subclass that strips temperature/top_p for GPT-5 family models.
+
+ GPT-5 family models use reasoning natively. temperature/top_p are only
+ accepted when reasoning.effort is 'none'; with any other effort level
+ (or for older... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/llm_clients/openai_client.py |
Improve documentation using docstrings |
VALID_MODELS = {
"openai": [
# GPT-5 series
"gpt-5.4-pro",
"gpt-5.4",
"gpt-5.2",
"gpt-5.1",
"gpt-5",
"gpt-5-mini",
"gpt-5-nano",
# GPT-4.1 series
"gpt-4.1",
"gpt-4.1-mini",
"gpt-4.1-nano",
],
"anthropic": [
... | --- +++ @@ -1,3 +1,8 @@+"""Model name validators for each provider.
+
+Only validates model names - does NOT enforce limits.
+Let LLM providers use their own defaults for unspecified params.
+"""
VALID_MODELS = {
"openai": [
@@ -47,6 +52,10 @@
def validate_model(provider: str, model: str) -> bool:
+ """C... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/llm_clients/validators.py |
Write docstrings describing each step | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import re
import json
from openAIWrapper import OpenAIWrapper
PLANNING_LLM_PREFIX = """Planning LLM is designed to provide a standard operating procedure so that an difficult task will be broken down into several steps, and the task will be easi... | --- +++ @@ -1,100 +1,105 @@-# Copyright (c) Microsoft Corporation.
-# Licensed under the MIT License.
-
-import re
-import json
-from openAIWrapper import OpenAIWrapper
-
-PLANNING_LLM_PREFIX = """Planning LLM is designed to provide a standard operating procedure so that an difficult task will be broken down into sever... | https://raw.githubusercontent.com/chenfei-wu/TaskMatrix/HEAD/LowCodeLLM/src/planningLLM.py |
Document helper functions with docstrings |
import os
import traceback
from flask import request, jsonify, send_file
from . import simulation_bp
from ..config import Config
from ..services.zep_entity_reader import ZepEntityReader
from ..services.oasis_profile_generator import OasisProfileGenerator
from ..services.simulation_manager import SimulationManager, Si... | --- +++ @@ -1,3 +1,7 @@+"""
+模拟相关API路由
+Step2: Zep实体读取与过滤、OASIS模拟准备与运行(全程自动化)
+"""
import os
import traceback
@@ -21,6 +25,15 @@
def optimize_interview_prompt(prompt: str) -> str:
+ """
+ 优化Interview提问,添加前缀避免Agent调用工具
+
+ Args:
+ prompt: 原始提问
+
+ Returns:
+ 优化后的提问
+ """
... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/api/simulation.py |
Write documentation strings for class attributes |
import time
from typing import Dict, Any, List, Optional, Set, Callable, TypeVar
from dataclasses import dataclass, field
from zep_cloud.client import Zep
from ..config import Config
from ..utils.logger import get_logger
from ..utils.zep_paging import fetch_all_nodes, fetch_all_edges
logger = get_logger('mirofish.z... | --- +++ @@ -1,3 +1,7 @@+"""
+Zep实体读取与过滤服务
+从Zep图谱中读取节点,筛选出符合预定义实体类型的节点
+"""
import time
from typing import Dict, Any, List, Optional, Set, Callable, TypeVar
@@ -17,6 +21,7 @@
@dataclass
class EntityNode:
+ """实体节点数据结构"""
uuid: str
name: str
labels: List[str]
@@ -39,6 +44,7 @@ }
... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/services/zep_entity_reader.py |
Write documentation strings for class attributes | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# coding: utf-8
import os
import gradio as gr
import random
import torch
import cv2
import re
import uuid
from PIL import Image, ImageDraw, ImageOps, ImageFont
import math
import numpy as np
import argparse
import inspect
import tempfile
from tra... | --- +++ @@ -260,6 +260,7 @@ "The input to this tool should be a comma separated string of two, "
"representing the image_path and the text. ")
def inference(self, inputs):
+ """Change style of image."""
print("===>Starting InstructPix2Pix Inference... | https://raw.githubusercontent.com/chenfei-wu/TaskMatrix/HEAD/visual_chatgpt.py |
Include argument descriptions in docstrings |
import json
import re
from typing import Optional, Dict, Any, List
from openai import OpenAI
from ..config import Config
class LLMClient:
def __init__(
self,
api_key: Optional[str] = None,
base_url: Optional[str] = None,
model: Optional[str] = None
):
self.api_ke... | --- +++ @@ -1,3 +1,7 @@+"""
+LLM客户端封装
+统一使用OpenAI格式调用
+"""
import json
import re
@@ -8,6 +12,7 @@
class LLMClient:
+ """LLM客户端"""
def __init__(
self,
@@ -34,6 +39,18 @@ max_tokens: int = 4096,
response_format: Optional[Dict] = None
) -> str:
+ """
+ 发送聊... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/utils/llm_client.py |
Add docstrings to meet PEP guidelines |
import json
import math
from typing import Dict, Any, List, Optional, Callable
from dataclasses import dataclass, field, asdict
from datetime import datetime
from openai import OpenAI
from ..config import Config
from ..utils.logger import get_logger
from .zep_entity_reader import EntityNode, ZepEntityReader
logger ... | --- +++ @@ -1,3 +1,14 @@+"""
+模拟配置智能生成器
+使用LLM根据模拟需求、文档内容、图谱信息自动生成细致的模拟参数
+实现全程自动化,无需人工设置参数
+
+采用分步生成策略,避免一次性生成过长内容导致失败:
+1. 生成时间配置
+2. 生成事件配置
+3. 分批生成Agent配置
+4. 生成平台配置
+"""
import json
import math
@@ -38,6 +49,7 @@
@dataclass
class AgentActivityConfig:
+ """单个Agent的活动配置"""
agent_id: int
entity_uui... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/services/simulation_config_generator.py |
Add docstrings to make code maintainable |
# ============================================================
# 解决 Windows 编码问题:在所有 import 之前设置 UTF-8 编码
# 这是为了修复 OASIS 第三方库读取文件时未指定编码的问题
# ============================================================
import sys
import os
if sys.platform == 'win32':
# 设置 Python 默认 I/O 编码为 UTF-8
# 这会影响所有未指定编码的 open() 调用
o... | --- +++ @@ -1,3 +1,29 @@+"""
+OASIS 双平台并行模拟预设脚本
+同时运行Twitter和Reddit模拟,读取相同的配置文件
+
+功能特性:
+- 双平台(Twitter + Reddit)并行模拟
+- 完成模拟后不立即关闭环境,进入等待命令模式
+- 支持通过IPC接收Interview命令
+- 支持单个Agent采访和批量采访
+- 支持远程关闭环境命令
+
+使用方式:
+ python run_parallel_simulation.py --config simulation_config.json
+ python run_parallel_simulation.py ... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/scripts/run_parallel_simulation.py |
Add docstrings explaining edge cases |
import os
import time
import threading
import json
from typing import Dict, Any, List, Optional, Callable
from dataclasses import dataclass
from datetime import datetime
from queue import Queue, Empty
from zep_cloud.client import Zep
from ..config import Config
from ..utils.logger import get_logger
logger = get_log... | --- +++ @@ -1,3 +1,7 @@+"""
+Zep图谱记忆更新服务
+将模拟中的Agent活动动态更新到Zep图谱中
+"""
import os
import time
@@ -18,6 +22,7 @@
@dataclass
class AgentActivity:
+ """Agent活动记录"""
platform: str # twitter / reddit
agent_id: int
agent_name: str
@@ -27,6 +32,12 @@ timestamp: str
def to_episo... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/services/zep_graph_memory_updater.py |
Write docstrings including parameters and return values |
import os
import json
import time
import re
from typing import Dict, Any, List, Optional, Callable
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from ..config import Config
from ..utils.llm_client import LLMClient
from ..utils.logger import get_logger
from .zep_tools imp... | --- +++ @@ -1,3 +1,13 @@+"""
+Report Agent服务
+使用LangChain + Zep实现ReACT模式的模拟报告生成
+
+功能:
+1. 根据模拟需求和Zep图谱信息生成报告
+2. 先规划目录结构,然后分段生成
+3. 每段采用ReACT多轮思考与反思模式
+4. 支持与用户对话,在对话中自主调用检索工具
+"""
import os
import json
@@ -23,8 +33,20 @@
class ReportLogger:
+ """
+ Report Agent 详细日志记录器
+
+ 在报告文件夹中生成 agent_log.jso... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/services/report_agent.py |
Fully document this Python code with docstrings |
import json
from typing import Dict, Any, List, Optional
from ..utils.llm_client import LLMClient
# 本体生成的系统提示词
ONTOLOGY_SYSTEM_PROMPT = """你是一个专业的知识图谱本体设计专家。你的任务是分析给定的文本内容和模拟需求,设计适合**社交媒体舆论模拟**的实体类型和关系类型。
**重要:你必须输出有效的JSON格式数据,不要输出任何其他内容。**
## 核心任务背景
我们正在构建一个**社交媒体舆论模拟系统**。在这个系统中:
- 每个实体都是一个可以在社交媒体上发声、互动、传播信息的"账号... | --- +++ @@ -1,3 +1,7 @@+"""
+本体生成服务
+接口1:分析文本内容,生成适合社会模拟的实体和关系类型定义
+"""
import json
from typing import Dict, Any, List, Optional
@@ -152,6 +156,10 @@
class OntologyGenerator:
+ """
+ 本体生成器
+ 分析文本内容,生成实体和关系类型定义
+ """
def __init__(self, llm_client: Optional[LLMClient] = None):
self... | https://raw.githubusercontent.com/666ghj/MiroFish/HEAD/backend/app/services/ontology_generator.py |
Document all public functions with docstrings | from langchain_core.tools import tool
from typing import Annotated
from tradingagents.dataflows.interface import route_to_vendor
@tool
def get_fundamentals(
ticker: Annotated[str, "ticker symbol"],
curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"],
) -> str:
return route_to_vendor("... | --- +++ @@ -8,6 +8,15 @@ ticker: Annotated[str, "ticker symbol"],
curr_date: Annotated[str, "current date you are trading at, yyyy-mm-dd"],
) -> str:
+ """
+ Retrieve comprehensive fundamental data for a given ticker symbol.
+ Uses the configured fundamental_data vendor.
+ Args:
+ ticker (s... | https://raw.githubusercontent.com/TauricResearch/TradingAgents/HEAD/tradingagents/agents/utils/fundamental_data_tools.py |
Add docstrings to existing functions | import json
from concurrent.futures import ThreadPoolExecutor
from pydantic import BaseModel
from typing import Annotated, Optional, List
from tqdm import tqdm
from marker.extractors import BaseExtractor
from marker.logger import get_logger
logger = get_logger()
class PageExtractionSchema(BaseModel):
descript... | --- +++ @@ -18,6 +18,9 @@
class PageExtractor(BaseExtractor):
+ """
+ An extractor that pulls data from a single page.
+ """
extraction_page_chunk_size: Annotated[
int, "The number of pages to chunk together for extraction."
@@ -96,6 +99,9 @@ """
def chunk_page_markdown(self, page_ma... | https://raw.githubusercontent.com/datalab-to/marker/HEAD/marker/extractors/page.py |
Add docstrings to improve collaboration | import importlib
import inspect
import pkgutil
from functools import cached_property
from typing import Annotated, Dict, Set, Type, get_args, get_origin
from marker.builders import BaseBuilder
from marker.converters import BaseConverter
from marker.extractors import BaseExtractor
from marker.processors import BaseProc... | --- +++ @@ -62,6 +62,10 @@
@staticmethod
def _gather_super_annotations(cls: Type) -> Dict[str, Type]:
+ """
+ Collect all annotated attributes from `cls` and its superclasses, bottom-up.
+ Subclass attributes overwrite superclass attributes with the same name.
+ """
# We'... | https://raw.githubusercontent.com/datalab-to/marker/HEAD/marker/config/crawler.py |
Create docstrings for all classes and functions | import json
import traceback
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Annotated, TypedDict, List, Sequence
from pydantic import BaseModel
from tqdm import tqdm
from PIL import Image
from marker.output import json_to_html
from marker.processors import BaseProcessor
from marker... | --- +++ @@ -35,6 +35,9 @@
class BaseLLMProcessor(BaseProcessor):
+ """
+ A processor for using LLMs to convert blocks.
+ """
max_concurrency: Annotated[
int,
@@ -77,6 +80,9 @@ )
def normalize_block_json(self, block: Block, document: Document, page: PageGroup):
+ """
+ ... | https://raw.githubusercontent.com/datalab-to/marker/HEAD/marker/processors/llm/__init__.py |
Improve documentation using docstrings |
import distance
from apted import APTED, Config
from apted.helpers import Tree
from lxml import html
from collections import deque
def wrap_table_html(table_html:str)->str:
return f'<html><body>{table_html}</body></html>'
class TableTree(Tree):
def __init__(self, tag, colspan=None, rowspan=None, content=None... | --- +++ @@ -1,3 +1,6 @@+""""
+TEDS Code Adapted from https://github.com/ibm-aur-nlp/EDD
+"""
import distance
from apted import APTED, Config
@@ -19,6 +22,7 @@ super().__init__(tag, *children)
def bracket(self):
+ """Show tree using brackets notation"""
if self.tag == 'td':
... | https://raw.githubusercontent.com/datalab-to/marker/HEAD/benchmarks/table/scoring.py |
Write docstrings for data processing functions | import base64
import os
import tempfile
import traceback
from marker.logger import get_logger
from marker.providers.pdf import PdfProvider
logger = get_logger()
css = """
@page {
size: A4 landscape;
margin: 1.5cm;
}
table {
width: 100%;
border-collapse: collapse;
break-inside: auto;
font-siz... | --- +++ @@ -110,6 +110,9 @@ )
def _handle_group(self, group_shape) -> str:
+ """
+ Recursively handle shapes in a group. Returns HTML string for the entire group.
+ """
from pptx.enum.shapes import MSO_SHAPE_TYPE
group_parts = []
@@ -135,6 +138,10 @@ retur... | https://raw.githubusercontent.com/datalab-to/marker/HEAD/marker/providers/powerpoint.py |
Add docstrings that explain inputs and outputs | import inspect
import os
from importlib import import_module
from typing import List, Annotated
import re
import numpy as np
import requests
from pydantic import BaseModel
from marker.schema.polygon import PolygonBox
from marker.settings import settings
OPENING_TAG_REGEX = re.compile(r"<((?:math|i|b))(?:\s+[^>]*)?>"... | --- +++ @@ -160,6 +160,15 @@ f.write(chunk)
def get_opening_tag_type(tag):
+ """
+ Determines if a tag is an opening tag and extracts the tag type.
+
+ Args:
+ tag (str): The tag string to analyze.
+
+ Returns:
+ tuple: (is_opening_tag (bool), tag_type (str or None))
+ ... | https://raw.githubusercontent.com/datalab-to/marker/HEAD/marker/util.py |
Improve my code by adding docstrings | import argparse
import os
from PIL import Image
def resize_image(image, size):
return image.resize(size, Image.ANTIALIAS)
def resize_images(image_dir, output_dir, size):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
images = os.listdir(image_dir)
num_images = len(images)
for... | --- +++ @@ -4,9 +4,11 @@
def resize_image(image, size):
+ """Resize an image to the given size."""
return image.resize(size, Image.ANTIALIAS)
def resize_images(image_dir, output_dir, size):
+ """Resize the images in 'image_dir' and save into 'output_dir'."""
if not os.path.exists(output_dir):
... | https://raw.githubusercontent.com/yunjey/pytorch-tutorial/HEAD/tutorials/03-advanced/image_captioning/resize.py |
Add return value explanations in docstrings | import torch
import torchvision.transforms as transforms
import torch.utils.data as data
import os
import pickle
import numpy as np
import nltk
from PIL import Image
from build_vocab import Vocabulary
from pycocotools.coco import COCO
class CocoDataset(data.Dataset):
def __init__(self, root, json, vocab, transfor... | --- +++ @@ -11,7 +11,16 @@
class CocoDataset(data.Dataset):
+ """COCO Custom Dataset compatible with torch.utils.data.DataLoader."""
def __init__(self, root, json, vocab, transform=None):
+ """Set the path for images, captions and vocabulary wrapper.
+
+ Args:
+ root: image ... | https://raw.githubusercontent.com/yunjey/pytorch-tutorial/HEAD/tutorials/03-advanced/image_captioning/data_loader.py |
Generate docstrings with parameter types | from __future__ import division
from torchvision import models
from torchvision import transforms
from PIL import Image
import argparse
import torch
import torchvision
import torch.nn as nn
import numpy as np
# Device configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def load_image(... | --- +++ @@ -13,6 +13,7 @@ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def load_image(image_path, transform=None, max_size=None, shape=None):
+ """Load an image and convert it to a torch tensor."""
image = Image.open(image_path)
if max_size:
@@ -31,11 +32,13 @@
class VGG... | https://raw.githubusercontent.com/yunjey/pytorch-tutorial/HEAD/tutorials/03-advanced/neural_style_transfer/main.py |
Add well-formatted docstrings | import torch
import torch.nn as nn
import torchvision.models as models
from torch.nn.utils.rnn import pack_padded_sequence
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
super(EncoderCNN, self).__init__()
resnet = models.resnet152(pretrained=True)
modules = list(resnet.childr... | --- +++ @@ -6,6 +6,7 @@
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
+ """Load the pretrained ResNet-152 and replace top fc layer."""
super(EncoderCNN, self).__init__()
resnet = models.resnet152(pretrained=True)
modules = list(resnet.children())[:-1] # delet... | https://raw.githubusercontent.com/yunjey/pytorch-tutorial/HEAD/tutorials/03-advanced/image_captioning/model.py |
Insert docstrings into my code | # Code referenced from https://gist.github.com/gyglim/1f8dfb1b5c82627ae3efcfbbadb9f514
import tensorflow as tf
import numpy as np
import scipy.misc
try:
from StringIO import StringIO # Python 2.7
except ImportError:
from io import BytesIO # Python 3.x
class Logger(object):
def __init__(self... | --- +++ @@ -11,13 +11,16 @@ class Logger(object):
def __init__(self, log_dir):
+ """Create a summary writer logging to log_dir."""
self.writer = tf.summary.FileWriter(log_dir)
def scalar_summary(self, tag, value, step):
+ """Log a scalar variable."""
summary = tf.Summar... | https://raw.githubusercontent.com/yunjey/pytorch-tutorial/HEAD/tutorials/04-utils/tensorboard/logger.py |
Add clean documentation to messy code | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from dataclasses import dataclass, field
from typing import Optional
import torch.nn.functional as F
from fairseq import metrics,... | --- +++ @@ -46,6 +46,17 @@
@register_criterion("speech_dlm_criterion", dataclass=SpeechDLMCriterionConfig)
class SpeechDLMCriterion(FairseqCriterion):
+ """Criteron for the SpeechDLM model as described in the paper:
+ https://arxiv.org/pdf/2203.16502.pdf
+
+ There are 3 possible losses depending on the targ... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/speech_dlm_criterion.py |
Create docstrings for API functions | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from dataclasses import dataclass, field
from typing import Dict, List
import torch
from fairseq import utils
from fairseq.lo... | --- +++ @@ -34,6 +34,17 @@
@register_criterion("model", dataclass=ModelCriterionConfig)
class ModelCriterion(FairseqCriterion):
+ """
+ This criterion relies on the model to supply losses.
+ The losses should be a dictionary of name -> scalar returned by
+ the model either by including it in the net_outp... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/model_criterion.py |
Add concise docstrings to each method | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from dataclasses import dataclass
import torch.nn.functional as F
from fairseq import utils
from fairseq.logging import metrics
f... | --- +++ @@ -26,6 +26,13 @@ self.sentence_avg = sentence_avg
def forward(self, model, sample, reduce=True):
+ """Compute the loss for the given sample.
+
+ Returns a tuple with three elements:
+ 1) the loss
+ 2) the sample size, which is used as the denominator for the gradient... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/cross_entropy.py |
Add standardized docstrings across the file | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from fairseq import utils
from fairseq.criterions import LegacyFairseqCriterion, register_criterion
from torch import nn
@register_criterion... | --- +++ @@ -10,6 +10,8 @@
@register_criterion("composite_loss")
class CompositeLoss(LegacyFairseqCriterion):
+ """This is a composite loss that, given a list of model outputs and a list of targets,
+ computes an average of losses for each output-target pair"""
def __init__(self, args, task):
su... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/composite_loss.py |
Add docstrings to improve code quality | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from dataclasses import dataclass
import math
from omegaconf import II
import torch
from fairseq import modules, utils
from fairseq.logging i... | --- +++ @@ -21,12 +21,22 @@
@register_criterion("masked_lm", dataclass=MaskedLmConfig)
class MaskedLmLoss(FairseqCriterion):
+ """
+ Implementation for the loss used in masked language model (MLM) training.
+ """
def __init__(self, cfg: MaskedLmConfig, task):
super().__init__(task)
... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/masked_lm.py |
Auto-generate documentation strings for this file |
import json
from functools import lru_cache
@lru_cache()
def bytes_to_unicode():
bs = (
list(range(ord("!"), ord("~") + 1))
+ list(range(ord("¡"), ord("¬") + 1))
+ list(range(ord("®"), ord("ÿ") + 1))
)
cs = bs[:]
n = 0
for b in range(2**8):
if b not in bs:
... | --- +++ @@ -1,3 +1,9 @@+"""
+Byte pair encoding utilities from GPT-2.
+
+Original source: https://github.com/openai/gpt-2/blob/master/src/encoder.py
+Original license: MIT
+"""
import json
from functools import lru_cache
@@ -5,6 +11,15 @@
@lru_cache()
def bytes_to_unicode():
+ """
+ Returns list of utf-8 b... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/encoders/gpt2_bpe_utils.py |
Document all public functions with docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import bisect
import numpy as np
from torch.utils.data.dataloader import default_collate
from . import FairseqDataset
class ConcatDataset(... | --- +++ @@ -55,6 +55,9 @@ return default_collate(samples, **extra_args)
def size(self, idx: int):
+ """
+ Return an example's size as a float or tuple.
+ """
dataset_idx, sample_idx = self._get_dataset_and_sample_index(idx)
return self.datasets[dataset_idx].size... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/concat_dataset.py |
Create structured documentation for my script | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import csv
import logging
import re
from argparse import Namespace
from collections import defaultdict
from dataclasses import dataclass
from ... | --- +++ @@ -35,6 +35,14 @@ def _collate_frames(
frames: List[torch.Tensor], is_audio_input: bool = False
) -> torch.Tensor:
+ """
+ Convert a list of 2D frames into a padded 3D tensor
+ Args:
+ frames (list): list of 2D frames of size L[i]*f_dim. Where L[i] is
+ length of i-th frame and... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/audio/speech_to_text_dataset.py |
Create docstrings for API functions | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import torch
import torch.nn.functional as F
from fairseq import utils
from fairseq.logging import metrics
from fairseq.criterion... | --- +++ @@ -13,6 +13,11 @@
def compute_cross_entropy_loss(logits, targets, ignore_index=-100):
+ """
+ Function to compute the cross entropy loss. The default value of
+ ignore_index is the same as the default value for F.cross_entropy in
+ pytorch.
+ """
assert logits.size(0) == targets.size(
... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/legacy_masked_lm.py |
Create docstrings for all classes and functions | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import json
import logging
import os
import random
from pathlib import Path
import numpy as np
import torch
import torch.utils.data
from . ... | --- +++ @@ -47,10 +47,12 @@
@property
def f0_stats(self):
+ """pre-computed f0 statistics path"""
return self.config.get("f0_stats", None)
@property
def f0_vq_type(self):
+ """naive or precomp"""
return self.config["f0_vq_type"]
@property
@@ -73,6 +75,7 @@
... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/codedataset.py |
Add docstrings to incomplete code | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from dataclasses import dataclass, field
from itertools import chain
import numpy as np
import torch
import torch.nn.functional a... | --- +++ @@ -79,6 +79,13 @@ self.label_dict = task.label_dictionary
def forward(self, model, sample, reduce=True):
+ """Compute the loss for the given sample.
+
+ Returns a tuple with three elements:
+ 1) the loss
+ 2) the sample size, which is used as the denominator for the g... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/sentence_prediction.py |
Improve my code by adding docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import mmap
from pathlib import Path
import io
from typing import BinaryIO, List, Optional, Tuple, Union
import numpy as np
import torch
imp... | --- +++ @@ -26,6 +26,22 @@ to_mono: bool = False,
to_sample_rate: Optional[int] = None,
) -> Tuple[Union[np.ndarray, torch.Tensor], int]:
+ """convert a waveform:
+ - to a target sample rate
+ - from multi-channel to mono channel
+ - volume normalization
+
+ Args:
+ waveform (numpy.ndarr... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/audio/audio_utils.py |
Document this script properly | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import shutil
import struct
from functools import lru_cache
import numpy as np
import torch
from fairseq.dataclass.constants import DATASET_I... | --- +++ @@ -144,6 +144,7 @@
class IndexedDataset(FairseqDataset):
+ """Loader for TorchNet IndexedDataset"""
_HDR_MAGIC = b"TNTIDX\x00\x00"
@@ -263,6 +264,8 @@
class IndexedRawTextDataset(FairseqDataset):
+ """Takes a text file as input and binarizes it in memory at instantiation.
+ Original l... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/indexed_dataset.py |
Create documentation strings for testing functions | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from dataclasses import dataclass, field
import torch.nn.functional as F
from fairseq.logging import metrics
from fairseq.tasks ... | --- +++ @@ -58,6 +58,13 @@ self.f0_loss_fn = nll_loss if cfg.discrete_f0 else mae_loss
def forward(self, model, sample, reduce=True):
+ """Compute the loss for the given sample.
+
+ Returns a tuple with three elements:
+ 1) the loss
+ 2) the sample size, which is used as the d... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/speech_ulm_criterion.py |
Document all endpoints with docstrings | # All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import math
from argparse import Namespace
from dataclasses import dataclass, f... | --- +++ @@ -256,6 +256,7 @@
@staticmethod
def reduce_metrics(logging_outputs) -> None:
+ """Aggregate logging outputs from data parallel training."""
loss_sum = utils.item(sum(log.get("loss", 0) for log in logging_outputs))
ntokens = utils.item(sum(log.get("ntokens", 0) for log in ... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/ctc.py |
Help me write clear docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import itertools
import logging
import math
import operator
import os
import queue
import time
from threading import Thread
from typing import... | --- +++ @@ -26,6 +26,18 @@
class CountingIterator(object):
+ """Wrapper around an iterable that maintains the iteration count.
+
+ Args:
+ iterable (iterable): iterable to wrap
+ start (int): starting iteration count. Note that this doesn't
+ actually advance the iterator.
+ to... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/iterators.py |
Document functions with detailed explanations | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import numpy as np
import torch
from fairseq.data import Dictionary, FairseqDataset
from fairseq.tasks import LegacyFairseqTa... | --- +++ @@ -18,6 +18,7 @@ class DummyMTTask(LegacyFairseqTask):
@staticmethod
def add_args(parser):
+ """Add task-specific arguments to the parser."""
parser.add_argument("--dict-size", default=49996, type=int)
parser.add_argument("--dataset-size", default=100000, type=int)
p... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/benchmark/dummy_mt.py |
Help me comply with documentation standards | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import typing as tp
from abc import ABC, abstractmethod
from collections import Counter
from dataclasses import datac... | --- +++ @@ -23,6 +23,9 @@
@dataclass
class BinarizeSummary:
+ """
+ Keep track of what's going on in the binarizer
+ """
num_seq: int = 0
replaced: tp.Optional[Counter] = None
@@ -60,6 +63,9 @@
class Binarizer(ABC):
+ """
+ a binarizer describes how to take a string and build a tensor ... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/binarizer.py |
Add docstrings to existing functions | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import torch
import torch.nn.functional as F
from fairseq import utils
from fairseq.logging import metrics
from fairseq.criterion... | --- +++ @@ -38,6 +38,13 @@ # fmt: on
def forward(self, model, sample, reduce=True):
+ """Compute ranking loss for the given sample.
+
+ Returns a tuple with three elements:
+ 1) the loss
+ 2) the sample size, which is used as the denominator for the gradient
+ 3) loggin... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/sentence_ranking.py |
Fill in missing docstrings in my code | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from fairseq import utils
from . import FairseqDataset
def backtranslate_samples(samples, collate_fn, generate_fn, cuda=True):... | --- +++ @@ -10,6 +10,27 @@
def backtranslate_samples(samples, collate_fn, generate_fn, cuda=True):
+ """Backtranslate a list of samples.
+
+ Given an input (*samples*) of the form:
+
+ [{'id': 1, 'source': 'hallo welt'}]
+
+ this will return:
+
+ [{'id': 1, 'source': 'hello world', 'target': ... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/backtranslation_dataset.py |
Document functions with detailed explanations | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import sys
import time
import io
import numpy as np
import torch
import torch.nn.functional as F
from .. import Fa... | --- +++ @@ -188,11 +188,15 @@ return self.size(index)
def size(self, index):
+ """Return an example's size as a float or tuple. This value is used when
+ filtering a dataset with ``--max-positions``."""
if self.pad:
return self.sizes[index]
return min(self.siz... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/audio/raw_audio_dataset.py |
Add docstrings to meet PEP guidelines | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import numpy as np
import torch
from . import FairseqDataset, data_utils
def collate(
samples,
pad_idx,
eos_idx,
... | --- +++ @@ -93,6 +93,21 @@
class DenoisingDataset(FairseqDataset):
+ """
+ A wrapper around TokenBlockDataset for BART dataset.
+
+ Args:
+ dataset (TokenBlockDataset): dataset to wrap
+ sizes (List[int]): sentence lengths
+ vocab (~fairseq.data.Dictionary): vocabulary
+ mask_id... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/denoising_dataset.py |
Add standardized docstrings across the file | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from pathlib import Path
from typing import Dict, List, NamedTuple, Optional
import torch
from fairseq.data import ConcatData... | --- +++ @@ -21,21 +21,35 @@
class S2TJointDataConfig(S2TDataConfig):
+ """Wrapper class for data config YAML"""
@property
def src_vocab_filename(self):
+ """fairseq vocabulary file under data root"""
return self.config.get("src_vocab_filename", "src_dict.txt")
@property
de... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/audio/speech_to_text_joint_dataset.py |
Replace inline comments with docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import torch
import torch.nn.functional as F
from fairseq import utils
from fairseq.logging import metrics
from fairseq.criterion... | --- +++ @@ -33,6 +33,14 @@ def _compute_loss(
self, outputs, targets, masks=None, label_smoothing=0.0, name="loss", factor=1.0
):
+ """
+ outputs: batch x len x d_model
+ targets: batch x len
+ masks: batch x len
+
+ policy_logprob: if there is some policy
+ ... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/nat_loss.py |
Create structured documentation for my script | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
from collections import Counter
from multiprocessing import Pool
import torch
from fairseq import utils
from fairseq.data import da... | --- +++ @@ -16,6 +16,7 @@
class Dictionary:
+ """A mapping from symbols to consecutive integers"""
def __init__(
self,
@@ -53,12 +54,14 @@ return self.count[idx]
def __len__(self):
+ """Returns the number of symbols in the dictionary"""
return len(self.symbols)
... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/dictionary.py |
Document classes and their methods | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import inspect
from typing import Any, Dict, List
from fairseq import utils
from fairseq.logging import metrics
from fairseq.dataclass import... | --- +++ @@ -23,12 +23,14 @@
@classmethod
def add_args(cls, parser):
+ """Add criterion-specific arguments to the parser."""
dc = getattr(cls, "__dataclass", None)
if dc is not None:
gen_parser_from_dataclass(parser, dc())
@classmethod
def build_criterion(cls,... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/fairseq_criterion.py |
Create docstrings for reusable components | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import ast
import collections
import contextlib
import inspect
import logging
import os
import re
import time
import traceback
from collection... | --- +++ @@ -206,6 +206,12 @@
def load_checkpoint(cfg: CheckpointConfig, trainer, **passthrough_args):
+ """
+ Load a checkpoint and restore the training iterator.
+
+ *passthrough_args* will be passed through to
+ ``trainer.get_train_iterator``.
+ """
reset_optimizer = cfg.reset_optimizer
... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/checkpoint_utils.py |
Document this script properly | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import mmap
import os
import shutil
import struct
import typing as tp
from functools import lru_cache
import numpy as np
import torch
from fa... | --- +++ @@ -18,6 +18,11 @@
class HuffmanMMapIndex:
+ """
+ keep an index of the offsets in the huffman binary file.
+ First a header, then the list of sizes (num tokens) for each instance and finally
+ the addresses of each instance.
+ """
_HDR_MAGIC = b"HUFFIDX\x00\x00"
_VERSION = 1
@@ -... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/huffman/huffman_mmap_indexed_dataset.py |
Generate docstrings for exported functions | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from dataclasses import dataclass, field
import torch
from fairseq import utils
from fairseq.logging import metrics
from fairseq.... | --- +++ @@ -70,6 +70,13 @@ self.report_accuracy = report_accuracy
def forward(self, model, sample, reduce=True):
+ """Compute the loss for the given sample.
+
+ Returns a tuple with three elements:
+ 1) the loss
+ 2) the sample size, which is used as the denominator for the gr... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/label_smoothed_cross_entropy.py |
Include argument descriptions in docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from dataclasses import dataclass, field
from typing import List, Optional
import torch
import torch.nn.functional as F
from fair... | --- +++ @@ -44,6 +44,13 @@ self.log_keys = [] if log_keys is None else log_keys
def forward(self, model, sample, reduce=True):
+ """Compute the loss for the given sample.
+
+ Returns a tuple with three elements:
+ 1) the loss
+ 2) the sample size, which is used as the denomina... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/wav2vec_criterion.py |
Generate docstrings for each module | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from fairseq import utils
from fairseq.logging import metrics
from fairseq.criterions import register_criterion
from .label_smoo... | --- +++ @@ -38,6 +38,13 @@ self.alignment_lambda = alignment_lambda
def forward(self, model, sample, reduce=True):
+ """Compute the loss for the given sample.
+
+ Returns a tuple with three elements:
+ 1) the loss
+ 2) the sample size, which is used as the denominator for the ... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/label_smoothed_cross_entropy_with_alignment.py |
Add concise docstrings to each method | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import re
import typing as tp
from collections import Counter, deque
from dataclasses import dataclass
from bitarray import bitarray, util
fr... | --- +++ @@ -26,17 +26,30 @@ self.bos_word, self.unk_word, self.pad_word, self.eos_word = bos, unk, pad, eos
def _pad(self, a: bitarray) -> bitarray:
+ """
+ bitpadding, 1 then 0.
+
+ If the array is already a multiple of blocksize, we add a full block.
+ """
pad_len =... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/huffman/huffman_coder.py |
Write Python docstrings for this snippet | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from argparse import Namespace
from copy import deepcopy
from pathlib import Path
from typing import Dict, Optional
from fairs... | --- +++ @@ -33,6 +33,7 @@
class S2TDataConfig(object):
+ """Wrapper class for data config YAML"""
def __init__(self, yaml_path: Path):
self.config = get_config_from_yaml(yaml_path)
@@ -48,40 +49,57 @@
@property
def vocab_filename(self):
+ """fairseq vocabulary file under data ro... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/audio/data_cfg.py |
Document classes and their methods | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from dataclasses import dataclass, field
import torch
from fairseq import utils
from fairseq.logging import metrics
from fairseq... | --- +++ @@ -56,6 +56,13 @@ self.rdrop_alpha = rdrop_alpha
def forward(self, model, sample, reduce=True, net_output=None):
+ """Compute the loss for the given sample.
+
+ Returns a tuple with three elements:
+ 1) the loss
+ 2) the sample size, which is used as the denominator f... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/label_smoothed_cross_entropy_with_rdrop.py |
Document functions with detailed explanations | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import re
from dataclasses import dataclass, field
from typing import List, Optional
import torch
import torch.nn.functional as F... | --- +++ @@ -53,6 +53,12 @@ self.log_keys = [] if log_keys is None else log_keys
def forward(self, model, sample, reduce=True, log_pred=False):
+ """Compute the loss for the given sample.
+ Returns a tuple with three elements:
+ 1) the loss
+ 2) the sample size, which is used a... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/hubert_criterion.py |
Generate consistent documentation across files | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from dataclasses import dataclass
import torch.nn.functional as F
from fairseq import utils
from fairseq.logging import metrics
f... | --- +++ @@ -23,6 +23,9 @@
@register_criterion("adaptive_loss", dataclass=AdaptiveLossConfig)
class AdaptiveLoss(FairseqCriterion):
+ """This is an implementation of the loss function accompanying the adaptive softmax approximation for
+ graphical processing units (GPU), described in the paper "Efficient softma... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/criterions/adaptive_loss.py |
Add docstrings to improve readability | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import numpy as np
import torch
from fairseq.data import FairseqDataset, data_utils
logger = logging.getLogger(__name__)
d... | --- +++ @@ -49,6 +49,14 @@ return True
def compute_alignment_weights(alignments):
+ """
+ Given a tensor of shape [:, 2] containing the source-target indices
+ corresponding to the alignments, a weight vector containing the
+ inverse frequency of each target index is computed.... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/language_pair_dataset.py |
Document functions with clear intent | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import numpy as np
import torch.utils.data
from fairseq.data import data_utils
logger = logging.getLogger(__name__)
class Ep... | --- +++ @@ -12,16 +12,28 @@
class EpochListening:
+ """Mixin for receiving updates whenever the epoch increments."""
@property
def can_reuse_epoch_itr_across_epochs(self):
+ """
+ Whether we can reuse the :class:`fairseq.data.EpochBatchIterator` for
+ this dataset across epochs.
... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/fairseq_dataset.py |
Add docstrings with type hints explained | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import subprocess
import threading
from pathlib import Path
import numpy as np
import torch
def fasta_file_path(prefix_path):
... | --- +++ @@ -17,6 +17,9 @@
class FastaDataset(torch.utils.data.Dataset):
+ """
+ For loading protein sequence datasets in the common FASTA data format
+ """
def __init__(self, path: str, cache_indices=False):
self.fn = fasta_file_path(path)
@@ -74,6 +77,10 @@
class EncodedFastaDataset(Fa... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/fasta_dataset.py |
Provide clean and structured docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
import contextlib
import itertools
impo... | --- +++ @@ -26,6 +26,7 @@
def infer_language_pair(path):
+ """Infer language pair from filename: <split>.<lang1>-<lang2>.(...).idx"""
src, dst = None, None
for filename in PathManager.ls(path):
parts = filename.split(".")
@@ -44,6 +45,7 @@ pad_to_multiple=1,
pad_to_bsz=None,
):
+ ... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/data_utils.py |
Help me add docstrings to my project | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import numpy as np
import torch
from fairseq.data import FairseqDataset
class BlockPairDataset(FairseqDataset):
def __init... | --- +++ @@ -11,6 +11,27 @@
class BlockPairDataset(FairseqDataset):
+ """Break a Dataset of tokens into sentence pair blocks for next sentence
+ prediction as well as masked language model.
+
+ High-level logics are:
+ 1. break input tensor to tensor blocks
+ 2. pair the blocks with 50% ne... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/legacy/block_pair_dataset.py |
Replace inline comments with docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import torch
from . import FairseqDataset, data_utils
def collate(samples, pad_idx, eos_idx, fixed_pad_length=None, pad_... | --- +++ @@ -58,6 +58,16 @@
class MonolingualDataset(FairseqDataset):
+ """
+ A wrapper around torch.utils.data.Dataset for monolingual data.
+
+ Args:
+ dataset (torch.utils.data.Dataset): dataset to wrap
+ sizes (List[int]): sentence lengths
+ vocab (~fairseq.data.Dictionary): vocabul... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/monolingual_dataset.py |
Write documentation strings for class attributes | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from fairseq.data import Dictionary
class MaskedLMDictionary(Dictionary):
def __init__(
self,
pad="<pad>",
eos=... | --- +++ @@ -7,6 +7,10 @@
class MaskedLMDictionary(Dictionary):
+ """
+ Dictionary for Masked Language Modelling tasks. This extends Dictionary by
+ adding the mask symbol.
+ """
def __init__(
self,
@@ -21,10 +25,15 @@ self.nspecial = len(self.symbols)
def mask(self):
+ ... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/legacy/masked_lm_dictionary.py |
Add well-formatted docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from functools import lru_cache
import numpy as np
import torch
from fairseq.data import Dictionary, data_utils
from . import BaseWrapperDat... | --- +++ @@ -13,9 +13,41 @@
class MaskTokensDataset(BaseWrapperDataset):
+ """
+ A wrapper Dataset for masked language modeling.
+
+ Input items are masked according to the specified masking probability.
+
+ Args:
+ dataset: Dataset to wrap.
+ sizes: Sentence lengths
+ vocab: Diction... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/mask_tokens_dataset.py |
Provide clean and structured docstrings | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
from typing import Dict, List, Tuple
import numpy as np
import torch
from fairseq.data import Dictionary, FairseqDataset, data_ut... | --- +++ @@ -15,6 +15,40 @@
class MaskedLMDataset(FairseqDataset):
+ """
+ A wrapper Dataset for masked language modelling. The dataset
+ wraps around TokenBlockDataset or BlockedPairDataset and creates a batch
+ where the input blocks are masked according to the specified masking
+ probability. Addit... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/legacy/masked_lm_dataset.py |
Add docstrings to my Python code | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import torch
from . import Dictionary, FairseqDataset, data_utils
def collate(
samples,
pad_idx,
eos_idx,
... | --- +++ @@ -92,6 +92,18 @@
class SpanMaskedTokensDataset(FairseqDataset):
+ """
+ A wrapper around TokenBlockDataset for T5 dataset.
+
+ Args:
+ dataset (~torch.utils.data.Dataset): dataset to wrap
+ vocab (~fairseq.data.Dictionary): vocabulary
+ noise_density (float): fraction of the ... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/span_mask_tokens_dataset.py |
Add detailed docstrings explaining each function | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import asyncio
import logging
import time
from collections import OrderedDict
from typing import Dict, List, Optional
import numpy as np
fro... | --- +++ @@ -19,6 +19,28 @@
class MultiCorpusDataset(FairseqDataset):
+ """
+ Stores multiple instances of FairseqDataset together.
+ Unless batch_sample=True, requires each instance
+ to be the same dataset, as the collate method needs to work on batches with
+ samples from each dataset.
+
+ Allow... | https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/data/multi_corpus_dataset.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.