instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings including usage examples
def response_groundedness_judge1_prompt(response: str, context: str) -> str: return f"""### Instruction You are a world class expert designed to evaluate the groundedness of an assertion. You will be provided with an assertion and a context. Your task is to determine if the assertion is supported by the context....
--- +++ @@ -1,6 +1,17 @@+"""Response groundedness prompts - V1-identical converted to functions.""" def response_groundedness_judge1_prompt(response: str, context: str) -> str: + """ + V1-identical response groundedness judge 1 prompt - matches template_groundedness1 exactly. + + Args: + response: ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/metrics/response_groundedness.py
Generate docstrings for script automation
from __future__ import annotations __all__ = ["Prompt"] import gzip import json import typing as t import warnings from pathlib import Path from ragas._analytics import PromptUsageEvent, track if t.TYPE_CHECKING: from pydantic import BaseModel class Prompt: def __init__( self, instruction:...
--- +++ @@ -21,6 +21,71 @@ examples: t.Optional[t.List[t.Tuple[t.Dict, t.Dict]]] = None, response_model: t.Optional[BaseModel] = None, ): + """ + Create a simple prompt object. + + Parameters: + ----------- + instruction : str + The prompt instruction ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/simple_prompt.py
Write clean docstrings for readability
from __future__ import annotations import base64 import binascii import ipaddress import logging import os import re import socket import typing as t from io import BytesIO from urllib.parse import urlparse import requests from langchain_core.language_models import BaseLanguageModel from langchain_core.messages impor...
--- +++ @@ -129,6 +129,34 @@ callbacks: t.Optional[Callbacks] = None, retries_left: int = 3, ) -> t.List[OutputModel]: + """ + Generate multiple outputs using the provided language model and input data. + + Parameters + ---------- + llm : BaseRagasLLM + ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/multi_modal_prompt.py
Add docstrings to my Python code
from __future__ import annotations import copy import hashlib import json import logging import os import typing as t from langchain_core.exceptions import OutputParserException from langchain_core.language_models import BaseLanguageModel from langchain_core.output_parsers import PydanticOutputParser from langchain_c...
--- +++ @@ -30,6 +30,22 @@ def is_langchain_llm( llm: t.Union[BaseRagasLLM, InstructorBaseRagasLLM, BaseLanguageModel], ) -> bool: + """ + Detect if an LLM is a LangChain LLM or a Ragas LLM. + + Args: + llm: The LLM instance to check + + Returns: + True if it's a LangChain LLM, False if ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/pydantic_prompt.py
Write docstrings that follow conventions
from __future__ import annotations import logging import typing as t from datasets import Dataset from ragas.dataset_schema import EvaluationDataset, MultiTurnSample, SingleTurnSample from ragas.metrics.base import Metric, MetricType, MultiTurnMetric, SingleTurnMetric logger = logging.getLogger(__name__) def rema...
--- +++ @@ -12,12 +12,18 @@ def remap_column_names(dataset: Dataset, column_map: dict[str, str]) -> Dataset: + """ + Remap the column names in case dataset uses different column names + """ inverse_column_map = {v: k for k, v in column_map.items()} return dataset.rename_columns(inverse_column_m...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/validation.py
Write docstrings for algorithm functions
from __future__ import annotations import itertools import logging import os import random import re import string import typing as t import uuid import warnings from datetime import datetime from functools import lru_cache from pathlib import Path import numpy as np import tiktoken from datasets import Dataset from ...
--- +++ @@ -28,6 +28,7 @@ @lru_cache(maxsize=1) def get_cache_dir() -> str: + "get cache location" DEFAULT_XDG_CACHE_HOME = "~/.cache" xdg_cache = os.getenv("XDG_CACHE_HOME", DEFAULT_XDG_CACHE_HOME) default_ragas_cache = os.path.join(xdg_cache, "ragas") @@ -98,6 +99,7 @@ class DeprecationHelper...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/utils.py
Write docstrings for data processing functions
from __future__ import annotations import typing as t from abc import ABC, abstractmethod import tiktoken class BaseTokenizer(ABC): @abstractmethod def encode(self, text: str) -> t.List[int]: pass @abstractmethod def decode(self, tokens: t.List[int]) -> str: pass def count_to...
--- +++ @@ -1,3 +1,9 @@+""" +Tokenizer abstractions for Ragas. + +This module provides a unified interface for different tokenizer implementations, +supporting both tiktoken (OpenAI) and HuggingFace tokenizers. +""" from __future__ import annotations @@ -8,20 +14,25 @@ class BaseTokenizer(ABC): + """Abstrac...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/tokenizers.py
Document functions with detailed explanations
import copy import typing as t from pydantic import BaseModel def get_all_strings(obj: t.Any) -> list[str]: strings = [] if isinstance(obj, str): strings.append(obj) elif isinstance(obj, BaseModel): for field_value in obj.model_dump().values(): strings.extend(get_all_strings(...
--- +++ @@ -5,6 +5,9 @@ def get_all_strings(obj: t.Any) -> list[str]: + """ + Get all strings in the objects. + """ strings = [] if isinstance(obj, str): @@ -23,6 +26,16 @@ def update_strings(obj: t.Any, old_strings: list[str], new_strings: list[str]) -> t.Any: + """ + Replace strings...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/utils.py
Write reusable docstrings
import logging import typing as t from dataclasses import dataclass import numpy as np from tenacity import ( AsyncRetrying, Retrying, WrappedFn, after_log, retry_if_exception_type, stop_after_attempt, wait_random_exponential, ) from tenacity.after import after_nothing @dataclass class Ru...
--- +++ @@ -17,6 +17,36 @@ @dataclass class RunConfig: + """ + Configuration for a timeouts, retries and seed for Ragas operations. + + Parameters + ---------- + timeout : int, optional + Maximum time (in seconds) to wait for a single operation, by default 180. + max_retries : int, optional ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/run_config.py
Write docstrings for this repository
import typing as t from pydantic import BaseModel, Field from ragas.prompt.metrics.base_prompt import BasePrompt class TopicExtractionInput(BaseModel): user_input: str = Field( ..., description="The conversation between Human, AI and Tools" ) class TopicExtractionOutput(BaseModel): topics: t....
--- +++ @@ -1,3 +1,4 @@+"""TopicAdherence prompt classes and models.""" import typing as t @@ -19,6 +20,7 @@ class TopicExtractionPrompt(BasePrompt[TopicExtractionInput, TopicExtractionOutput]): + """Prompt for extracting topics from a conversation.""" input_model = TopicExtractionInput output_m...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/topic_adherence/util.py
Document this module using docstrings
import json import os import glob #import sys from PyQt6.QtCore import QObject from opensnitch.utils.xdg import xdg_config_home from opensnitch.utils import logger from opensnitch.actions.default_configs import ( commonDelegateConfig, rulesDelegateConfig, fwDelegateConfig, netstatDelegateConfig ) fro...
--- +++ @@ -18,6 +18,77 @@ from opensnitch.plugins import PluginsManager class Actions(QObject): + """List of actions to perform on the data that is displayed on the GUI, + defined in JSON files. + + Whenever an item (popup, cell, etc) matches a condition, an action + (config/plugin) is applied. For exam...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/actions/__init__.py
Add professional docstrings to my codebase
from PyQt6.QtSql import QSqlDatabase, QSqlQueryModel, QSqlQuery import threading import sys import os from datetime import datetime, timedelta from opensnitch.utils import logger class Database: db = None __instance = None DB_IN_MEMORY = "file::memory:" DB_TYPE_MEMORY = 0 DB_TYPE_FILE = 1 ...
--- +++ @@ -342,6 +342,8 @@ self.logger.info("db upgrade OK") def optimize(self): + """https://www.sqlite.org/pragma.html#pragma_optimize + """ q = QSqlQuery("PRAGMA optimize;", self.db) q.exec() @@ -619,6 +621,8 @@ return True def get_connecti...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/database/__init__.py
Add docstrings to my Python code
import datetime import os import json from PyQt6 import QtCore, QtGui, QtWidgets from PyQt6.QtCore import QCoreApplication as QC from opensnitch.config import Config from opensnitch.version import version from opensnitch.nodes import Nodes from opensnitch.firewall import Firewall from opensnitch.database.enums import...
--- +++ @@ -933,6 +933,8 @@ pass def _cb_rules_tree_item_clicked(self, item, col): + """Event fired when the user clicks on the left panel of the rules tab + """ item_model = self.rulesTreePanel.indexFromItem(item, col) item_row = item_model.row() parent = item.pa...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/dialogs/events/dialog.py
Write clean docstrings for readability
import re from PyQt6 import QtCore from . import ( constants ) from opensnitch.config import Config from opensnitch.customwidgets.completer import Completer from opensnitch.proto.enums import ( ConnFields, NodeFields, RuleFields ) OP_NOT_EQUAL = "!=" OP_NOT_EQUAL2 = "<>" OP_EQUAL = "=" # LIKE OP_CONT...
--- +++ @@ -126,6 +126,7 @@ return f"SELECT {fields} FROM {table}" def get_view_query(self, model, idx, where_clause=None): + """builds the query of a view""" qstr = self.get_query( self.win.TABLES[idx]['name'], self.win.TABLES[idx]['display_fields'] @@ -142,6 +1...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/dialogs/events/queries.py
Document this module using docstrings
from PyQt6 import QtWidgets from PyQt6.QtCore import QCoreApplication as QC import opensnitch.firewall as Fw from opensnitch.utils import ( NetworkServices, NetworkInterfaces ) from . import ( utils ) net_srv = NetworkServices() # list of widgets representing a rule. statem_list = {} st_num = 0 DPORT = 0 ...
--- +++ @@ -292,6 +292,11 @@ } def add_new(win, title="", topWidget=None): + """Creates dynamically the widgets to define firewall rules: + statement (dst port, dst ip, log), protocol, operator (==, !=,...) + and value (443, 1.1.1.1, etc) + Some expressions may have different options (protoco...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/dialogs/firewall_rule/statements.py
Annotate my code with docstrings
__all__ = ["discrete_metric", "DiscreteMetric"] import typing as t from dataclasses import dataclass, field from pydantic import Field if t.TYPE_CHECKING: from ragas.metrics.base import EmbeddingModelType from .base import SimpleLLMMetric from .decorator import DiscreteMetricProtocol, create_metric_decorator f...
--- +++ @@ -1,3 +1,4 @@+"""Base class from which all discrete metrics should inherit.""" __all__ = ["discrete_metric", "DiscreteMetric"] @@ -16,6 +17,46 @@ @dataclass(repr=False) class DiscreteMetric(SimpleLLMMetric, DiscreteValidator): + """ + Metric for categorical/discrete evaluations with predefined a...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/discrete.py
Create docstrings for all classes and functions
import typing as t from typing import List, Literal, Union import numpy as np from ragas.messages import AIMessage, HumanMessage, ToolMessage from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import ( TopicClassificationInput, TopicClassificationO...
--- +++ @@ -1,3 +1,4 @@+"""TopicAdherence metric - Modern collections implementation.""" import typing as t from typing import List, Literal, Union @@ -25,6 +26,49 @@ class TopicAdherence(BaseMetric): + """ + Measures how well an AI system adheres to predefined topics during conversations. + + AI syste...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/topic_adherence/metric.py
Generate docstrings with parameter types
import sys import time import os import os.path import json from PyQt6 import QtCore, QtGui, uic, QtWidgets from PyQt6.QtCore import QCoreApplication as QC from opensnitch.utils import Icons, Message from opensnitch.config import Config from opensnitch.nodes import Nodes from opensnitch.dialogs.firewall_rule import F...
--- +++ @@ -340,6 +340,9 @@ def fw_is_incompatible(self, addr, node): + """Check if the fw is compatible with this GUI. + If it's incompatible, disable the option to enable it. + """ incompatible = False # firewall iptables is not supported from the GUI. # display...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/dialogs/firewall.py
Provide docstrings following PEP 257
import typing as t from ragas.messages import ToolCall def make_hashable(obj: t.Any) -> t.Any: if isinstance(obj, dict): # Convert dict to frozenset of (key, hashable_value) tuples return frozenset((k, make_hashable(v)) for k, v in obj.items()) elif isinstance(obj, (list, tuple)): # ...
--- +++ @@ -1,3 +1,4 @@+"""Tool Call F1 utility functions.""" import typing as t @@ -5,6 +6,17 @@ def make_hashable(obj: t.Any) -> t.Any: + """ + Recursively convert an object to a hashable representation. + + Converts nested dicts, lists, and sets to hashable types (frozensets, tuples). + + Args: ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/tool_call_f1/util.py
Add docstrings to existing functions
__all__ = ["numeric_metric", "NumericMetric"] import typing as t from dataclasses import dataclass if t.TYPE_CHECKING: from ragas.metrics.base import EmbeddingModelType from .base import SimpleLLMMetric from .decorator import NumericMetricProtocol, create_metric_decorator from .validators import NumericValidato...
--- +++ @@ -1,3 +1,4 @@+"""Base class for all numeric metrics""" __all__ = ["numeric_metric", "NumericMetric"] @@ -14,6 +15,49 @@ @dataclass(repr=False) class NumericMetric(SimpleLLMMetric, NumericValidator): + """ + Metric for continuous numeric evaluations within a specified range. + + This class is ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/numeric.py
Include argument descriptions in docstrings
import typing as t from abc import ABC, abstractmethod from dataclasses import dataclass from langchain_core.callbacks import Callbacks from ragas.dataset_schema import SingleMetricAnnotation from ragas.llms.base import BaseRagasLLM from ragas.losses import Loss from ragas.metrics.base import MetricWithLLM from ragas...
--- +++ @@ -13,6 +13,9 @@ @dataclass class Optimizer(ABC): + """ + Abstract base class for all optimizers. + """ metric: t.Optional[MetricWithLLM] = None llm: t.Optional[BaseRagasLLM] = None @@ -29,4 +32,21 @@ with_debugging_logs=False, raise_exceptions: bool = True, ) -> t...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/optimizers/base.py
Add structured docstrings to improve clarity
from PyQt6.QtCore import QObject, QCoreApplication as QC from google.protobuf import json_format import opensnitch.proto as proto ui_pb2, ui_pb2_grpc = proto.import_() from opensnitch.nodes import Nodes from .enums import * from .rules import * from .chains import * from .exprs import * from .profiles import ( Pr...
--- +++ @@ -69,6 +69,8 @@ return self.update_rule(addr, uuid, chain) def filter_rules(self, nail): + """ + """ chains = [] for addr in self._nodes.get_nodes(): node = self._nodes.get_node(addr) @@ -105,6 +107,7 @@ return chains def filter_by_tab...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/firewall/__init__.py
Create docstrings for API functions
import json def answer_accuracy_judge1_prompt( query: str, user_answer: str, reference_answer: str ) -> str: safe_query = json.dumps(query) safe_user_answer = json.dumps(user_answer) safe_reference_answer = json.dumps(reference_answer) return f"""Instruction: You are a world class state of the a...
--- +++ @@ -1,3 +1,4 @@+"""Answer Accuracy prompts - Convert NVIDIA dual-judge templates to function format.""" import json @@ -5,6 +6,19 @@ def answer_accuracy_judge1_prompt( query: str, user_answer: str, reference_answer: str ) -> str: + """ + First judge template for answer accuracy evaluation. + + ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/metrics/answer_accuracy.py
Create docstrings for all classes and functions
import threading import sys import time import os import os.path import pwd import json from datetime import datetime from PyQt6 import QtCore, QtGui, uic, QtWidgets from PyQt6.QtCore import QCoreApplication as QC, QEvent from slugify import slugify from opensnitch.utils import Icons, logger from opensnitch.desktop_...
--- +++ @@ -161,6 +161,10 @@ self.checkSum.toggle() def _configure_plugins(self): + """configure the plugins that apply to this dialog. + When configuring the plugins on a particular view, they'll add, + change or extend the existing functionality. + """ for conf ...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/dialogs/prompt/dialog.py
Add return value explanations in docstrings
import copy import json import typing as t from abc import ABC from pydantic import BaseModel, Field from ragas.prompt.utils import get_all_strings, update_strings if t.TYPE_CHECKING: from ragas.llms.base import InstructorBaseRagasLLM # Type variables for generics InputModel = t.TypeVar("InputModel", bound=Bas...
--- +++ @@ -1,3 +1,4 @@+"""Base prompt class for metrics with structured input/output models.""" import copy import json @@ -30,6 +31,7 @@ class _TranslatedStrings(BaseModel): + """Response model for translation - preserves order and count.""" statements: t.List[str] = Field( ..., description...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/metrics/base_prompt.py
Document this script properly
import os import os.path import logging import requests import threading from queue import Queue from opensnitch.version import version from opensnitch.dialogs.stats import StatsDialog from opensnitch.notifications import DesktopNotifications from opensnitch.plugins import PluginBase, PluginSignal from opensnitch.util...
--- +++ @@ -21,6 +21,11 @@ logger.setLevel(logging.WARNING) class Downloader(PluginBase): + """A plugin that schedules downloads from remote urls. + + This plugin may require to create a rule to allow connections to the + configured urls, to avoid popups. + """ # fields overriden from parent class ...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/plugins/downloader/downloader.py
Add docstrings to incomplete code
import json import typing as t def statement_generator_prompt(question: str, answer: str) -> str: # Format inputs exactly like V1's model_dump_json(indent=4, exclude_none=True) safe_question = json.dumps(question) safe_answer = json.dumps(answer) return f"""Given a question and an answer, analyze th...
--- +++ @@ -1,9 +1,20 @@+"""Common prompts shared across multiple metrics.""" import json import typing as t def statement_generator_prompt(question: str, answer: str) -> str: + """ + V1-identical statement generator - matches PydanticPrompt.to_string() exactly. + + Args: + question: The questi...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/metrics/common.py
Help me add docstrings to my project
from PyQt6 import QtWidgets from PyQt6.QtCore import QCoreApplication as QC from . import constants def load_nodes(win): win.comboNodes.blockSignals(True) win.comboNodes.clear() win._node_list = win.nodes.get() win.comboNodes.addItem(QC.translate("firewall", "All"), "all") for addr in win._node_l...
--- +++ @@ -94,9 +94,15 @@ win.addr = "" def enable_save(win, enable=True): + """Enable Save buton whenever some detail of a rule changes. + The button may or not be hidden. If we're editing a rule it'll be shown + but disabled/enabled. + """ win.cmdSave.setEnabled(enable) def enable_buttons(...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/dialogs/firewall_rule/utils.py
Document this code for team use
from __future__ import annotations import re from typing import Dict, Sequence # Regular expression to extract both straight and curly quoted spans. Matches # pairs of quotes and captures the inner text. _QUOTE_RE = re.compile(r"[\"" "''`´](.*?)[\"" "''`´]") def _normalize(text: str) -> str: return re.sub(r"\...
--- +++ @@ -1,3 +1,18 @@+""" +Quoted Spans Alignment Metric +================================ + +This module provides a simple metric to measure citation alignment for quoted spans +in model-generated answers. The idea is to compute the fraction of quoted spans +appearing verbatim in any of the provided source passages...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/quoted_spans.py
Can you add docstrings to this Python file?
import typing as t from ragas.llms.base import BaseRagasLLM class RagasDSPyLM: def __init__(self, ragas_llm: BaseRagasLLM): self.ragas_llm = ragas_llm self.history: t.List[t.Dict[str, t.Any]] = [] def __call__( self, prompt: t.Optional[str] = None, messages: t.Option...
--- +++ @@ -4,6 +4,17 @@ class RagasDSPyLM: + """ + Wrapper to make Ragas LLM compatible with DSPy. + + DSPy expects LM objects to have specific methods for inference. + This wrapper adapts Ragas LLM to work with DSPy's optimization framework. + + Parameters + ---------- + ragas_llm : BaseRagas...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/optimizers/dspy_llm_wrapper.py
Add docstrings to meet PEP guidelines
import re import os.path from PyQt6.QtCore import QCoreApplication as QC from opensnitch.utils.network_aliases import NetworkAliases from opensnitch.utils import ( qvalidator, Icons ) from . import nodes, constants # XXX: remove? def bool(s): return s == 'True' def load_aliases_into_menu(win): aliase...
--- +++ @@ -123,6 +123,9 @@ win.nodeApplyAllCheck.setChecked(False) def comma_to_regexp(win, text, expected_type): + """translates items separated by comma, to regular expression + returns True|False, regexp|error + """ s_parts = text.replace(" ", "").split(",") sp_regex = r'^(' for p in ...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/dialogs/ruleseditor/utils.py
Write reusable docstrings
from PyQt6.QtCore import QCoreApplication as QC from opensnitch.config import Config from opensnitch.rules import Rule def verify(checksums, rule): # when verifying checksums, we'll always have a rule type List, with at # least: path of the process + checksum if rule.operator.type != Config.RULE_TYPE_LIST:...
--- +++ @@ -3,6 +3,9 @@ from opensnitch.rules import Rule def verify(checksums, rule): + """return true if the checksum of a rule matches the one of the process + opening a connection. + """ # when verifying checksums, we'll always have a rule type List, with at # least: path of the process + chec...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/dialogs/prompt/checksums.py
Write documentation strings for class attributes
import math import threading from PyQt6.QtGui import QStandardItemModel from PyQt6.QtSql import QSqlQuery, QSql from PyQt6.QtWidgets import QTableView from PyQt6.QtCore import ( QItemSelectionRange, QItemSelectionModel, QItemSelection, QModelIndex, pyqtSignal, QEvent, Qt) class GenericTabl...
--- +++ @@ -93,6 +93,7 @@ #self._update_col_count() def rowCount(self, index=None): + """ensures that only the needed rows is created""" return len(self.items) def total(self): @@ -105,6 +106,8 @@ return num def data(self, index, role=Qt.ItemDataRole.DisplayRole): + ...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/customwidgets/generictableview.py
Document helper functions with docstrings
import glob import json import os.path class Profiles(): @staticmethod def load_predefined_profiles(): profiles = glob.glob("/etc/opensnitchd/system-fw.d/profiles/*.profile") p = [] for pr_path in profiles: with open(pr_path) as f: p.append({os.path.basena...
--- +++ @@ -73,6 +73,10 @@ class ProfileDropInput(): + """ + Set input filter table policy to DROP and add the needed rules to allow + outbound connections. + """ # TODO: delete dropInput profile's rules value = { @@ -138,6 +142,10 @@ } class ProfileDropOutput(): + """ + Set out...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/firewall/profiles.py
Write clean docstrings for readability
import json import typing as t def correctness_classifier_prompt( question: str, answer_statements: t.List[str], ground_truth_statements: t.List[str] ) -> str: # Format inputs exactly like V1's model_dump_json(indent=4, exclude_none=True) safe_question = json.dumps(question) safe_answer_statements = ...
--- +++ @@ -1,3 +1,7 @@+"""Answer Correctness prompts for classification. + +Note: statement_generator_prompt has been moved to ragas.prompt.metrics.common +""" import json import typing as t @@ -6,6 +10,17 @@ def correctness_classifier_prompt( question: str, answer_statements: t.List[str], ground_truth_statem...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/metrics/answer_correctness.py
Add detailed docstrings explaining each function
__all__ = [ "create_metric_decorator", "BaseMetricProtocol", "DiscreteMetricProtocol", "NumericMetricProtocol", "RankingMetricProtocol", ] import asyncio import inspect import typing as t import warnings from dataclasses import dataclass, field from typing import get_args, get_origin, get_type_hin...
--- +++ @@ -1,3 +1,4 @@+"""decorator factory for creating custom metrics""" __all__ = [ "create_metric_decorator", @@ -34,48 +35,74 @@ # Protocol classes for type hints class BaseMetricProtocol(Protocol): + """Protocol defining the base metric interface.""" name: str def score(self, **kwargs...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/decorator.py
Expand my code with proper documentation strings
import typing as t from ragas.dataset_schema import SingleMetricAnnotation from ragas.llms.base import BaseRagasLLM from ragas.losses import Loss from ragas.prompt.pydantic_prompt import PydanticPrompt def setup_dspy_llm(dspy: t.Any, ragas_llm: BaseRagasLLM) -> None: from ragas.optimizers.dspy_llm_wrapper import...
--- +++ @@ -7,6 +7,16 @@ def setup_dspy_llm(dspy: t.Any, ragas_llm: BaseRagasLLM) -> None: + """ + Configure DSPy to use Ragas LLM. + + Parameters + ---------- + dspy : Any + The DSPy module. + ragas_llm : BaseRagasLLM + Ragas LLM instance to use for DSPy operations. + """ fr...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/optimizers/dspy_adapter.py
Add verbose docstrings with examples
from PyQt6 import QtCore from PyQt6.QtGui import QColor, QPalette from PyQt6.QtWidgets import QStyle from opensnitch.plugins import PluginBase, PluginSignal class Highlight(PluginBase): name = "Highlight" version = "0.1" author = "opensnitch" created = "" modified = "" #enabled = True #...
--- +++ @@ -7,6 +7,79 @@ class Highlight(PluginBase): + """Customizes QTablewView cells via QItemDelegates. + Format: + "highlight": { + "cells": [ + { + "text": ["allow", "True"], + "cols": [3, 4], + "color": "green", + "bgcolor": "", + "alignment":...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/plugins/highlight/highlight.py
Add docstrings that explain logic
from google.protobuf import __version__ as protobuf_version from .enums import * class Utils(): @staticmethod def isExprPort(value): return value == Statements.TCP.value or \ value == Statements.UDP.value or \ value == Statements.UDPLITE.value or \ valu...
--- +++ @@ -6,6 +6,9 @@ @staticmethod def isExprPort(value): + """Return true if the value is valid for a port based rule: + nft add rule ... tcp dport 22 accept + """ return value == Statements.TCP.value or \ value == Statements.UDP.value or \ ...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/firewall/utils.py
Generate docstrings for script automation
import typing as t from ragas.messages import AIMessage from ragas.metrics.collections.base import BaseMetric from ragas.metrics.result import MetricResult from .util import calculate_f1_score, tool_call_to_hashable if t.TYPE_CHECKING: from ragas.messages import HumanMessage, ToolCall, ToolMessage class ToolC...
--- +++ @@ -1,3 +1,4 @@+"""Tool Call F1 metric - Modern collections implementation.""" import typing as t @@ -12,8 +13,57 @@ class ToolCallF1(BaseMetric): + """ + Modern implementation of Tool Call F1 metric. + + Measures the F1 score between predicted and reference tool calls. This metric + treats...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/collections/tool_call_f1/metric.py
Create structured documentation for my script
from PyQt6.QtCore import QObject, pyqtSignal from PyQt6.QtCore import QCoreApplication as QC from google.protobuf.json_format import MessageToJson import uuid from .enums import Operator from .exprs import ExprLog import opensnitch.proto as proto ui_pb2, ui_pb2_grpc = proto.import_() class Rules(QObject): rulesU...
--- +++ @@ -26,6 +26,8 @@ pass def add(self, addr, rule): + """Add a new rule to the corresponding table on the given node + """ node = self._nodes.get_node(addr) if node is None or not 'firewall' in node: return False, QC.translate("firewall", "rule not found...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/firewall/rules.py
Document functions with clear intent
import os import os.path import logging import requests import json import threading from queue import Queue from PyQt6.QtCore import QCoreApplication as QC from opensnitch.version import version from opensnitch.dialogs.stats import StatsDialog from opensnitch.notifications import DesktopNotifications from opensnitch....
--- +++ @@ -22,6 +22,11 @@ logger.setLevel(logging.ERROR) class Versionchecker(PluginBase): + """A plugin that checks periodically OpenSnitch available release. + + This plugin may require to create a rule to allow connections to the + configured urls, to avoid popups. + """ # fields overriden from ...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/plugins/versionchecker/versionchecker.py
Generate consistent docstrings
import json import re import logging import requests from PyQt6 import QtCore from opensnitch.actions import Actions from opensnitch.version import version from opensnitch.config import Config from opensnitch.plugins import PluginBase, PluginSignal from opensnitch.dialogs.events import StatsDialog, constants as evt_c...
--- +++ @@ -45,6 +45,9 @@ self.analyze(self.parent, self.config, self.what, self.url, self.timeout, self.api_key, self.conn) def analyze(self, parent, conf, what, url, timeout, api_key, conn): + """Returns analyze results on success. + None on error. + """ logger.debug("vt_a...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/plugins/virustotal/virustotal.py
Create docstrings for each class method
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from . import ui_pb2 as ui__pb2 class UIStub(object): def __init__(self, channel): self.Ping = channel.unary_unary( '/protocol.UI/Ping', request_serializer=ui__pb2.PingRequest.SerializeToStr...
--- +++ @@ -1,12 +1,19 @@ # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +"""Client and server classes corresponding to protobuf-defined services.""" import grpc from . import ui_pb2 as ui__pb2 class UIStub(object): + """Missing associated documentation comment in .proto file.""" ...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/proto/ui_pb2_grpc.py
Document all public functions with docstrings
from PyQt6 import QtWidgets, QtGui, QtCore from PyQt6.QtCore import QCoreApplication as QC from datetime import datetime, timedelta from threading import Thread, Lock, Event import grpc import os import sys import json import copy path = os.path.abspath(os.path.dirname(__file__)) sys.path.append(path) import opensni...
--- +++ @@ -268,6 +268,9 @@ self._menu_autostart.setChecked(self._autostart.isEnabled()) def _show_gui_if_tray_not_available(self): + """If the system tray is not available or ready, show the GUI after + 10s. This delay helps to skip showing up the GUI when DEs' autologin is on. + ""...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/service.py
Add docstrings to improve readability
import json def answer_relevancy_prompt(response: str) -> str: # Use json.dumps() to safely escape the response string safe_response = json.dumps(response) return f"""Generate a question for the given answer and Identify if answer is noncommittal. Give noncommittal as 1 if the answer is noncommittal and...
--- +++ @@ -1,8 +1,18 @@+"""Answer Relevance prompt for generating questions and detecting noncommittal responses.""" import json def answer_relevancy_prompt(response: str) -> str: + """ + Generate the prompt for answer relevance evaluation. + + Args: + response: The response text to evaluate + ...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/prompt/metrics/answer_relevance.py
Please document this code using docstrings
from PyQt6 import QtCore, QtWidgets, QtGui from opensnitch.version import version as gui_version from opensnitch.database import Database from opensnitch.config import Config from opensnitch.utils.themes import Themes from opensnitch.desktop_parser import LinuxDesktopParser from threading import Thread, Event import p...
--- +++ @@ -33,6 +33,13 @@ return self.ASN_AVAILABLE def load(self): + """Load the ASN DB from disk. + + It'll try to load it from user's opensnitch directory if these file exist: + - ~/.config/opensnitch/ipasn_db.dat.gz + - ~/.config/opensnitch/asnames.json + O...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/utils/__init__.py
Document this code for team use
import sys import os import logging from PyQt6 import QtCore, QtGui, uic, QtWidgets from PyQt6.QtCore import QCoreApplication as QC from opensnitch.config import Config from opensnitch.nodes import Nodes from opensnitch.database import Database from opensnitch.customwidgets.itemwidgetcentered import IconTextItem from...
--- +++ @@ -211,27 +211,35 @@ self.init() def add_section(self, widget, icon, lbl): + """adds a new tab to the Preferences, and returns the new index""" return self.stackedWidget.addTab(widget, icon, lbl) def insert_section(self, idx, widget, lbl): + """inserts a new tab at ...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/dialogs/preferences/dialog.py
Generate consistent docstrings
import json import logging import time from PyQt6.QtCore import QCoreApplication as QC import opensnitch.proto as proto ui_pb2, ui_pb2_grpc = proto.import_() from opensnitch.config import Config from opensnitch.utils import languages from opensnitch.database import Database from opensnitch.dialogs.preferences import ...
--- +++ @@ -32,6 +32,7 @@ utils.needs_restart(win) def load(win): + """load the settings from the configuration file""" ## general win.default_action = win.cfgMgr.getInt(win.cfgMgr.DEFAULT_ACTION_KEY) win.default_target = win.cfgMgr.getInt(win.cfgMgr.DEFAULT_TARGET_KEY, 0) @@ -384,6 +385,7 @@ ...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/dialogs/preferences/settings.py
Add docstrings for production code
from slugify import slugify import os import ipaddress from PyQt6.QtCore import QCoreApplication as QC from opensnitch.config import Config from opensnitch.dialogs.prompt import constants from opensnitch.utils.network_aliases import NetworkAliases def truncate_text(text, max_size=64): if len(text) > max_size: ...
--- +++ @@ -28,6 +28,11 @@ return rule_temp_name[:128] def get_popup_message(is_local, node, hostname, app_name, con): + """ + _get_popup_message helps constructing the message that is displayed on + the pop-up dialog. Example: + curl is connecting to www.opensnitch.io on TCP port 443 + """ ...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/dialogs/prompt/utils.py
Add detailed documentation for each class
__all__ = ["ranking_metric", "RankingMetric"] import typing as t from dataclasses import dataclass from pydantic import Field if t.TYPE_CHECKING: from ragas.metrics.base import EmbeddingModelType from .base import SimpleLLMMetric from .decorator import RankingMetricProtocol, create_metric_decorator from .valid...
--- +++ @@ -1,3 +1,4 @@+"""Base class for ranking metrics""" __all__ = ["ranking_metric", "RankingMetric"] @@ -16,6 +17,48 @@ @dataclass(repr=False) class RankingMetric(SimpleLLMMetric, RankingValidator): + """ + Metric for evaluations that produce ranked lists of items. + + This class is used for metr...
https://raw.githubusercontent.com/vibrantlabsai/ragas/HEAD/src/ragas/metrics/ranking.py
Add docstrings explaining edge cases
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -50,6 +50,23 @@ def logger_merge_config(merge_config, lora_merge): + """ + Logs the merge configuration details to debug output, with different formatting + for LoRA merges versus standard model merges. + + Args: + merge_config (object): Configuration object containing merge parameters...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/export/export.py
Write Python docstrings for this snippet
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -26,6 +26,7 @@ @dataclass class PreTrainingArguments(TrainingArguments): + """pretraining arguments""" eval_iters: int = field( default=-1, @@ -99,6 +100,10 @@ @property def need_data(self): + """ + whether need load data + return True + """ ...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/hparams/finetuning_args.py
Please document this code using docstrings
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -92,6 +92,7 @@ def read_args(args: Optional[Union[dict[str, Any], list[str]]] = None) -> Union[dict[str, Any], list[str]]: + r"""Get arguments from the command line or a config file.""" if args is not None: return args @@ -116,6 +117,19 @@ args: Optional[Union[dict[str, Any], list[...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/hparams/parser.py
Create docstrings for each class method
# !/usr/bin/env python3 # Copyright (c) 2025 PaddlePaddle Authors. 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 # #...
--- +++ @@ -14,6 +14,10 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +End2EndProcessorArgumentsHelper + +""" from dataclasses import dataclass, field @@ -25,6 +29,9 @@ @dataclass class UtteranceProcessorArguments(BasePreprocessArguments): + ...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/hparams/preprocess_args.py
Write docstrings that follow conventions
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) 2023 DeepSeek. 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.o...
--- +++ @@ -28,6 +28,16 @@ @triton.jit def act_quant_kernel(x_ptr, y_ptr, s_ptr, BLOCK_SIZE: tl.constexpr): + """ + Quantizes the input tensor `x_ptr` and stores the result in `y_ptr` and the scaling factor in `s_ptr`. + Args: + x_ptr (triton.Pointer): Pointer to the input tensor. + y_ptr (tri...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/deepseek_v3_pretrain/kernel.py
Add return value explanations in docstrings
from PyQt6 import QtCore, QtGui, uic, QtWidgets from PyQt6.QtCore import QCoreApplication as QC from slugify import slugify from datetime import datetime import sys import os import pwd import time import ipaddress import opensnitch.proto as proto ui_pb2, ui_pb2_grpc = proto.import_() from opensnitch.config import Co...
--- +++ @@ -102,24 +102,31 @@ self.uidCombo.setCurrentText(oldUid) def add_section(self, widget, icon, lbl): + """adds a new tab to the Preferences, and returns the new index""" return self.tabWidget.addTab(widget, icon, lbl) def insert_section(self, idx, widget, lbl): + """...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/dialogs/ruleseditor/dialog.py
Create docstrings for each class method
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) 2023 DeepSeek. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differ...
--- +++ @@ -17,6 +17,7 @@ # 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. +"""Paddle DeepSeek model.""" from __future__ import annotations @@ -131,6 +132,7 @@ def get_use_casual_m...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/deepseek_v3_pretrain/modeling.py
Add docstrings to clarify complex logic
from .enums import * import opensnitch.proto as proto ui_pb2, ui_pb2_grpc = proto.import_() class Chains(): def __init__(self, nodes): self._nodes = nodes def get(self): chains = {} for node in self._nodes.get_nodes(): chains[node] = self.get_node_chains(node) ret...
--- +++ @@ -102,6 +102,12 @@ # class ChainFilter(Chains): + """ + ChainFilter returns a new chain of type filter. + + The name of the chain is the one listed with: nft list table inet filter. + It corresponds with the hook name, but can be a random name. + """ @staticmethod def input(famil...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/firewall/chains.py
Document this module using docstrings
from opensnitch.plugins import PluginBase, PluginSignal class Sample(PluginBase): # fields overriden from parent class name = "Sample" version = 0 author = "opensnitch" created = "" modified = "" enabled = False description = "OpenSnitch sample plugin" # where this plugin be execu...
--- +++ @@ -24,9 +24,13 @@ pass def compile(self): + """Transform a json object to python objects. + """ print("Sample.compile()") def run(self, args): + """Run the action on the given arguments. + """ print("Sample.run() args:", args) def cb_si...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/plugins/sample/sample.py
Add structured docstrings to improve clarity
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) Microsoft Corporation. # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # Copyright (C) 2024 THL A29 Limited, a Tencent company. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License")...
--- +++ @@ -215,6 +215,17 @@ l_aux=None, l_zloss=None, ): + """MoE Layer forward function + 1. Gate Forward. + 2. Dispatch export. + 3. Experts Forward. + + Args: + hidden_state: MoE Layer input + + Returns: + final_out: M...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/deepseek_v3_pretrain/moe_layer.py
Generate docstrings for exported functions
from PyQt6.QtCore import QObject, pyqtSignal from queue import Queue from datetime import datetime import time import json from opensnitch.database import Database from opensnitch.config import Config from opensnitch.utils import NetworkInterfaces, logger from opensnitch.rules import Rules import opensnitch.proto as ...
--- +++ @@ -40,6 +40,28 @@ return len(self._nodes) def add(self, _peer, client_config=None): + """registers a new node. + When connecting for the first time, the node is configured with the + default settings: + - a bidirectional notifications queue. + - the sta...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/nodes.py
Add docstrings explaining edge cases
from PyQt6.QtCore import QCoreApplication as QC from opensnitch.config import Config class DesktopNotifications(): _cfg = Config.init() # list of hints: # https://people.gnome.org/~mccann/docs/notification-spec/notification-spec-latest.html#hints HINT_DESKTOP_ENTRY = "desktop-entry" CATEGORY_NETW...
--- +++ @@ -2,6 +2,20 @@ from opensnitch.config import Config class DesktopNotifications(): + """DesktopNotifications display informative pop-ups using the system D-Bus. + The notifications are handled and configured by the system. + + The notification daemon also decides where to show the notifications, as...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/notifications.py
Add docstrings that explain inputs and outputs
# Copyright (c) 2024 PaddlePaddle Authors. 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 appli...
--- +++ @@ -42,12 +42,16 @@ def disable_dropout_in_model(model: paddle.nn.Layer) -> None: + """ "disable dropout""" for module in model.children(): if isinstance(module, paddle.nn.Dropout): module.p = 0 class DPOTrainer(Trainer): + """ + Initialize DPOTrainer. + """ ...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/dpo/dpo_trainer.py
Create docstrings for all classes and functions
from PyQt6 import QtCore from abc import ABC, abstractmethod from importlib import util import os import gc import weakref from opensnitch.config import Config from opensnitch.utils import logger class PluginSignal(QtCore.QObject): signal = QtCore.pyqtSignal(dict) # actions to send to the plugins DISABLE...
--- +++ @@ -35,6 +35,9 @@ self.signal.disconnect(callback) class PluginsList(): + """plugins store. Whenever a plugin is instantiated, it's added to the + plugin list automatically + """ actions = [] names = {} @@ -45,6 +48,35 @@ cls.names[cls.name] = cls class PluginBase(...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/plugins/__init__.py
Add detailed docstrings explaining each function
from PyQt6.QtCore import QObject, pyqtSignal from opensnitch.database import Database from opensnitch.utils import logger from opensnitch.database.enums import RuleFields from opensnitch.config import Config import opensnitch.proto as proto ui_pb2, ui_pb2_grpc = proto.import_() import os import json from slugify imp...
--- +++ @@ -35,6 +35,9 @@ @staticmethod def new_from_records(records): + """Creates a new protobuf Rule from DB records. + Fields of the record are in the order defined on the DB. + """ rule = ui_pb2.Rule(name=records.value(RuleFields.Name)) rule.enabled = Rule.to_bool(...
https://raw.githubusercontent.com/evilsocket/opensnitch/HEAD/ui/opensnitch/rules.py
Generate docstrings for exported functions
# Copyright (c) 2026 PaddlePaddle Authors. 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 appli...
--- +++ @@ -109,6 +109,11 @@ @dataclass class DataArguments: + """ + Arguments pertaining to what data we are going to input our model for training and evaluating. + Using `PdArgumentParser` we can turn this class into argparse arguments to be able to + specify them on the command line. + """ i...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/deepseek_v3_pretrain/workflow.py
Write docstrings for algorithm functions
# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2025 DeepSeek # # 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 t...
--- +++ @@ -14,6 +14,19 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +FP8 Utilities for Mixture of Experts (MoE) Token Dispatcher + +This module provides optimized operations for FP8 (8-bit floating point) computations +in Mixture of Experts architect...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/ernie_pretrain/models/moe/token_dispatcher/fp8_utils.py
Create Google-style docstrings for my code
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2025 DeepSeek # # 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 t...
--- +++ @@ -27,6 +27,9 @@ if not hasattr(paddle.Tensor, "_clear_to_zero_allocation"): def _clear_to_zero_allocation(self): + """ + _clear_to_zero_allocation + """ old_shape = self.shape dst = paddle.empty([0], dtype=self.dtype) dst_t = dst.value().get_tensor() @@ -...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/deepseek_v3_pretrain/moe_utils.py
Annotate my code with docstrings
# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2025 DeepSeek # # 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 t...
--- +++ @@ -22,6 +22,14 @@ def inplace_offload(x): + """Offload tensor to CPU in-place to save GPU memory. + + Args: + x (paddle.Tensor): The tensor to be offloaded to CPU. + + Note: + This operation modifies the tensor in-place by sharing data with a CPU copy. + """ if not x.place._e...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/ernie_pretrain/models/moe/token_dispatcher/moe_utils.py
Help me comply with documentation standards
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2025 DeepSeek # # 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 t...
--- +++ @@ -29,6 +29,26 @@ class _DeepepManager(_DispatchManager): + """ + A manager class to handle fused all-to-all communication processes for MoE models using + DeepEP backend. See https://github.com/deepseek-ai/deepep for more details. + + The workflow of the DeepEP dispatcher is: + (1) setup_me...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/deepseek_v3_pretrain/token_dispatcher.py
Add docstrings to incomplete code
# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. # Copyright (c) Microsoft Corporation. # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # Copyright (C) 2024 THL A29 Limited, a Tencent company. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License")...
--- +++ @@ -67,6 +67,16 @@ self.using_flex_token = kwargs.pop("using_flex_token", False) def _priority(self, topk_idx: paddle.Tensor, capacity: int) -> paddle.Tensor: + """_summary_ + The priority is the cumulative sum of the expert indices. + + This method is used in hunyuan...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/deepseek_v3_pretrain/moe_gate.py
Replace inline comments with docstrings
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -178,8 +178,28 @@ class Top2Gate(nn.Layer): + """Gating network for Top-2 Mixture of Experts (MoE) routing. + + This gate computes routing weights for each token and selects the top-2 experts + for each input token. Supports both standard and balanced routing strategies. + + Attributes: + ...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/ernie_pretrain/models/moe/top2_gate.py
Add standardized docstrings across the file
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -12,20 +12,41 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""SFT utils""" class DataGenerator: + """Generates an infinite stream of examples""" def __init__(self, data_source): + """ + Initializes the iterator ...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/sft/make_data_utils.py
Add docstrings explaining edge cases
# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved. # Copyright 2022 EleutherAI and the HuggingFace Inc. 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...
--- +++ @@ -13,6 +13,19 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +FP8 Linear Layer Implementation for PaddlePaddle + +This module implements FP8 (8-bit floating point) linear layers using PaddlePaddle's +incubate APIs for low-precision training. K...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/ernie_pretrain/models/fp8_linear.py
Add documentation for all methods
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" Estimate DPO """ import json import os @@ -28,6 +29,19 @@ def calculate_acc_steps(num_samples, train_batch, dataset_world_size, per_device_train_batch_size): + """calculate...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/dpo/dpo_estimate_training.py
Generate docstrings with parameter types
# Copyright 2024 The HuggingFace Inc. 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 appl...
--- +++ @@ -29,6 +29,10 @@ def conversations_formatting_function(tokenizer: AutoTokenizer, messages_field: Literal["messages", "conversations"]): + r""" + return a callable function that takes in a "messages" dataset and returns a formatted dataset, based on the tokenizer + apply chat template to the datas...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/sft/dataset_formatting.py
Write docstrings including parameters and return values
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -71,11 +71,13 @@ def set_grad_in_dtype_non_consistent(ctx): + """Allow grad dtype not consistent with forward dtype""" if hasattr(ctx, "set_grad_in_dtype_consistent"): ctx.set_grad_in_dtype_consistent(False) class Fp8MoeGateDispatchAndQuant(paddle.autograd.PyLayer): + """Fp8MoeGa...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/ernie_pretrain/models/moe/moe_layer.py
Add docstrings for better understanding
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # Copyright 2018 The Google AI Language Team Authors and 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...
--- +++ @@ -24,17 +24,73 @@ class Stack(object): + """ + Stacks the input data samples to construct the batch. The N input samples + must have the same shape/length and will be stacked to construct a batch. + + Args: + axis (int, optional): The axis in the result data along which the input + ...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/data/collate.py
Document my Python code with docstrings
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -35,6 +35,7 @@ @dataclass class Sequence: + """Sequence.""" token_ids: Optional[List[int]] position_ids: Optional[List[int]] @@ -157,6 +158,10 @@ yield pack def __iter__(self): + """ + Rewrite the __iter__ method to implement dataset iteration. +...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/datasets/DPODataset.py
Include argument descriptions in docstrings
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -19,6 +19,16 @@ def create_dataset(**dataset_config: Dict[str, Any]): + """Create dataset based on configuration parameters. + + Args: + dataset_config (dict): Configuration dictionary, required keys: + - stage: 'dpo', 'sft', 'pt' (case-insensitive). + - Other keys pass...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/datasets/loader.py
Help me write clear docstrings
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -24,6 +24,15 @@ def terminate_process_tree(pid: int) -> None: + """ + Terminate the process tree of the given process ID + + Args: + pid (int): The process ID that needs to be terminated + + Returns: + None + """ try: parent = psutil.Process(pid) except psu...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/utils/process.py
Generate helpful docstrings for debugging
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -37,6 +37,7 @@ @dataclass class TextSequence: + """Encapsulated text sequence class.""" token_ids: List[int] position_ids: List[int] @@ -46,6 +47,7 @@ @dataclass class Sequence: + """Encapsulated sequence class.""" token_ids: List[int] position_ids: List[int] @@ -174,6 +17...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/datasets/SFTDataset.py
Document functions with detailed explanations
# Copyright (c) 2020 PaddlePaddle Authors. 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 appli...
--- +++ @@ -94,6 +94,10 @@ def import_main_class(module_path): + """ + Import a module at module_path and return its DatasetBuilder class. + + """ module_path = DATASETS_MODULE_PATH + module_path module = importlib.import_module(module_path) main_cls_type = DatasetBuilder @@ -152,6 +156,31 @...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/datasets/dataset.py
Add docstrings for utility scripts
# Copyright (c) 2023 PaddlePaddle Authors. 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 appli...
--- +++ @@ -475,6 +475,7 @@ def pad_batch_data(insts, masks=None, pad_id=0, return_seq_len=False, pad_style="right"): + """Pad sequences to the max sequence length in batch.""" max_len = max(map(len, insts)) if pad_style == "left": inst_data = np.array([[pad_id] * (max_len - len(inst)) + list(...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/utils/llm_utils.py
Create docstrings for each class method
# Copyright (c) 2026 PaddlePaddle Authors. 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 appli...
--- +++ @@ -153,6 +153,7 @@ class TensorMeta: + """Recording the meta info of forward inputs, to avoid 0-size problems""" def __init__(self, tensor): self.shape = tensor.shape @@ -1475,6 +1476,14 @@ return get_attr(self.embed_tokens, "weight") def forward(self, args): + """_...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/deepseek_v3_pretrain/modeling_pp.py
Add docstrings to improve readability
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -22,12 +22,23 @@ class BaseMixDataset(IterableDataset): + """ + Base class for mixed datasets that combine multiple data sources with configurable sampling strategies. + """ def __init__( self, multi_source_dataset, **dataset_config, ): + """ + ...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/datasets/reader/mix_datasets.py
Add docstrings including usage examples
# Copyright (c) 2020 PaddlePaddle Authors. 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 appli...
--- +++ @@ -22,6 +22,37 @@ class Vocab(object): + """ + The class used to convert between tokens and ids. It also includes some + store/load functions. + + Args: + counter (collections.Counter, optional): A Counter instance describes + the tokens and their frequencies. Its keys will be...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/data/vocab.py
Write reusable docstrings
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -26,8 +26,19 @@ class InfiniteDataset(IterableDataset): + """Infinite iterable dataset with shuffle support. + + This dataset supports continuous iteration and optional random shuffling. + """ def __init__(self, dataset, rng=None, random_shuffle=True): + """Initialize InfiniteDatas...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/datasets/reader/multi_source_datasets.py
Generate docstrings for exported functions
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -12,6 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Implement base data transfer protocol between any two functions, modules. +We can subclass Protocol to define more detailed batch info with specific keys +""" import copy from dat...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/datasets/rlhf_datasets/protocol.py
Add inline docstrings for readability
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. import hashlib import math import os import time import numpy as np import paddle from .blendable_dataset import BlendableDataset from .indexed_dataset import make_dataset as make_indexed_dataset local_rank = int(os.getenv("PADDLE_RANK_IN_NODE", 0)) INF...
--- +++ @@ -1,5 +1,6 @@ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +"""GPT style dataset.""" import hashlib import math import os @@ -32,6 +33,21 @@ def get_logits(batch_ids, max_retries=1, timeout=1200, retry_delay=1, prob_nums=10): + """ + Retrieve logits with retry mechanism if no ...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/data/causal_dataset.py
Fill in missing docstrings in my code
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -81,6 +81,7 @@ system: Optional[str] = None, tools: Optional[str] = None, ) -> tuple[list[int], list[int]]: + r"""Return a single pair of token ids representing prompt and response respectively.""" encoded_messages = self._encode(tokenizer, messages, system, tools) ...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/datasets/template/template.py
Create simple docstrings for beginners
# copyright (c) 2023 paddlepaddle authors. 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 appli...
--- +++ @@ -11,6 +11,7 @@ # 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. +""" Generation configuration class and utilities.""" import copy import json @@ -33,6 +34,16 @@ def resol...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/generation/configuration_utils.py
Add docstrings that explain purpose and usage
# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the HuggingFace's Transformers library. # https://github.com/huggingface/transformers/blob/v4.40.0/src/transformers/models/llava/processing_llava.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not...
--- +++ @@ -56,6 +56,7 @@ def _make_batched_images(images, imglens: list[int]): + r"""Make nested list of images.""" batch_images = [] for imglen in imglens: batch_images.append(images[:imglen]) @@ -65,6 +66,7 @@ def _check_video_is_nested_images(video) -> bool: + r"""Check if the video...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/datasets/template/mm_plugin.py
Write docstrings for algorithm functions
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -36,9 +36,14 @@ @abstractmethod def apply(self, **kwargs) -> SLOTS: + r"""Forms a list of slots according to the inputs to encode.""" ... def extract(self, content: str) -> Union[str, list["FunctionCall"]]: + r"""Extract a list of tuples from the response message if u...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/datasets/template/formatter.py
Write docstrings for utility functions
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -80,19 +80,23 @@ @dataclass class ToolUtils(ABC): + """Base class for tool utilities.""" @staticmethod @abstractmethod def tool_formatter(tools: list[dict[str, Any]]) -> str: + r"""Generate the system message describing all the available tools.""" ... @staticmeth...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/datasets/template/tool_utils.py
Write docstrings including parameters and return values
# Copyright (c) 2025 PaddlePaddle Authors. 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 appli...
--- +++ @@ -23,6 +23,7 @@ def check_path(path): + """_summary_""" if path is None: raise ValueError("Dataset Path is None. Please set dataset path firstly.") else: @@ -30,6 +31,14 @@ def _training_function(config: dict[str, Any]) -> None: + """_summary_ + + Args: + config (dic...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/cli/train/tuner.py
Add docstrings to existing functions
# Copyright (c) 2023 PaddlePaddle Authors. 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 appli...
--- +++ @@ -163,6 +163,7 @@ class IndexedDataset(paddle.io.Dataset): + """Loader for IndexedDataset""" _HDR_MAGIC = b"TNTIDX\x00\x00" @@ -226,6 +227,11 @@ return sents def get(self, idx, offset=0, length=None): + """Retrieves a single item from the dataset with the option to on...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/data/indexed_dataset.py
Add professional docstrings to my codebase
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # Copyright 2018 The Google AI Language Team Authors and 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...
--- +++ @@ -71,6 +71,16 @@ def default_data_collator(features: List[InputDataClass], return_tensors="pd") -> Dict[str, Any]: + """ + Very simple data collator that simply collates batches of dict-like objects and performs special handling for + potential keys named: + + - `label`: handles a single v...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/data/data_collator.py
Help me add docstrings to my project
# Copyright (c) 2020 PaddlePaddle Authors. 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 appli...
--- +++ @@ -20,6 +20,27 @@ class SamplerHelper(object): + """ + The class is to help construct iterable sampler used for + :class:`paddle.io.DataLoader`. It wraps a dataset and uses its + :meth:`__getitem__` method. Every subclass of :class:`SamplerHelper` has + to provide an :meth:`__iter__` method,...
https://raw.githubusercontent.com/PaddlePaddle/PaddleFormers/HEAD/paddleformers/data/sampler.py