instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Can you add docstrings to this Python file?
import argparse import glob import json import os from pathlib import Path from typing import Sequence import matplotlib.pyplot as plt def load_jsonl_log(path): all_examples = [] with open(path, "r") as f: for line in f: line = json.loads(line) if "spec" in line.keys() or "fin...
--- +++ @@ -9,6 +9,10 @@ def load_jsonl_log(path): + """ + Given jsonl log, returns list containing tuples + of (question, was_answer_to_questopm_correct) + """ all_examples = [] with open(path, "r") as f: for line in f: @@ -27,6 +31,10 @@ def get_questions(files: Sequence[Path]) ...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/sandbagging/scripts/consistency_plots.py
Add detailed documentation for each class
import os from abc import abstractmethod from typing import Any, Dict, Sequence from evals.completion_fns.openai import OpenAIChatCompletionFn from evals.elsuite.sandbagging.defaults import ( SANDBAGGING_IMPROVED_GPT_4, SANDBAGGING_IMPROVED_GPT_35, SANDBAGGING_SIMPLE, SANDBAGGING_SUBSET_SIMPLE, SCR...
--- +++ @@ -24,6 +24,10 @@ class StrategySolver(Solver): + """ + Solver for MMLU, adapts its strategy based off the parameters + passed at initialization. Generalized for both LMs and humans + """ def __init__( self, @@ -50,11 +54,24 @@ @abstractmethod def _produce_scratchpad(...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/sandbagging/solvers.py
Please document this code using docstrings
from typing import Any, Sequence import evals from evals.record import Event def get_violation_events(events: Sequence[Event], valid_samples: Sequence[str]) -> Sequence[Event]: sampled = [e.data["sampled"] for e in events] violations = [e[0] not in valid_samples for e in sampled] violation_events = [i f...
--- +++ @@ -5,6 +5,10 @@ def get_violation_events(events: Sequence[Event], valid_samples: Sequence[str]) -> Sequence[Event]: + """ + Return all events, where the first character of the events sample + isn't in valid_samples + """ sampled = [e.data["sampled"] for e in events] violations = [e[0]...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/sandbagging/utils.py
Add docstrings including usage examples
from evals.solvers.solver import Solver, SolverResult from evals.task_state import TaskState class BaselineNoPromptSolver(Solver): def __init__( self, **kwargs, ): def _solve( self, task_state: TaskState, **kwargs, ) -> SolverResult: return SolverResul...
--- +++ @@ -7,6 +7,9 @@ self, **kwargs, ): + """ + This solver simply returns an empty string as the prompt. + """ def _solve( self, @@ -25,6 +28,9 @@ self, **kwargs, ): + """ + This solver simply returns the original instruc...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/self_prompting/solvers/baselines.py
Create Google-style docstrings for my code
import json import logging import os import random from collections import defaultdict from typing import Any, Dict, List, Optional, Union import evals import evals.metrics from evals.api import CompletionFn from evals.elsuite.skill_acquisition.task_description import TASK_DESCRIPTION from evals.elsuite.skill_acquisit...
--- +++ @@ -67,6 +67,16 @@ self.max_replies = max_replies # Used as timeout. def eval_sample(self, solver: Solver, sample: Dict, rng: random.Random) -> Dict[str, Any]: + """Runs the appropriate private evaluation function depending on the eval phase: retrieval or non-retrieval. + + Args: +...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/skill_acquisition/eval.py
Add clean documentation to messy code
import copy import logging import re from dataclasses import dataclass from typing import Any, Optional from evals.elsuite.bugged_tools.tools import Tool, ToolTaskState from evals.solvers.solver import Solver, SolverResult from evals.task_state import Message, TaskState logger = logging.getLogger(__name__) @datacla...
--- +++ @@ -100,6 +100,10 @@ return self._finish_run(task_state, solver_result, None, turn) def _get_tool_names_and_descriptions(self, tools: list[Tool]): + """ + Given sequence of tools, creates a string of each tools name + and description, each tool's info separated by a newline +...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/solver_tools_convo.py
Provide docstrings following PEP 257
import json import logging import random import re from math import sqrt from typing import Callable, Dict, List, Set, Union import numpy as np from nltk.translate.bleu_score import SmoothingFunction, sentence_bleu ANSWER_PATTERN = r"\[ANSWER:? .+?\]" VIEW_PATTERN = r"\[VIEW:? .+?\]" PROMPTS = { "retrieval_instru...
--- +++ @@ -45,6 +45,15 @@ def process_answer(output: str) -> str: + """Extracts the answer from model output. + The answer looks like [ANSWER X], where X is the answer. + + Args: + output (str): model output + + Returns: + str: answer provided by the model + """ maybe_multiple_ans...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/skill_acquisition/utils.py
Generate docstrings with parameter types
import random from typing import Any from evals.elsuite.track_the_stat import utils from evals.solvers.solver import NestedSolver, Solver, SolverResult, SolverSpec from evals.task_state import Message, TaskState class ExplicitStateSolver(NestedSolver): def __init__( self, underlying_solver: Solve...
--- +++ @@ -56,11 +56,18 @@ return self._median_solve(task_state) def _mode_solve(self, task_state: TaskState) -> str: + """ + Picks a random number from the numbers seen so far + """ numbers = list(task_state.current_state["state_data"].keys()) random_mode = ra...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/track_the_stat/solvers.py
Add docstrings for production code
from typing import Literal, List, Optional from evals.task_state import Message, TaskState PROMPTS = { "guesser": "You are about to play the game '20 questions'. The other player has thought of a noun which you should try to guess. You can ask 20 yes/no questions, to which they will answer 'yes', 'no', or 'skip' (...
--- +++ @@ -10,6 +10,7 @@ } def generate_task_state_for(role: Literal["guesser", "gamemaster"], conversation: list[Message], word: Optional[str] = None, max_questions: int = 20, shortlist: Optional[List[str]] = None) -> TaskState: + """Generates a TaskState for the given role and conversation.""" if role == ...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/twenty_questions/utils.py
Add return value explanations in docstrings
import re from collections import Counter from typing import Union import numpy as np def yellow_string(str: str) -> str: return f"\033[1;33m{str}\033[0m" def median(numbers: list[int]) -> int: return np.median(numbers) def mode(numbers: list[int]) -> int: frequency = {} for number in numbers: ...
--- +++ @@ -10,10 +10,19 @@ def median(numbers: list[int]) -> int: + """ + Returns the median of the given list of numbers. If the list has an even + number of elements, the arithmetic mean of the two middle elements of the + sorted list is returned. + """ return np.median(numbers) def mode...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/track_the_stat/utils.py
Generate docstrings for script automation
from typing import Optional, Tuple, Union, List import json import random import networkx as nx import numpy as np import pandas as pd from evals.elsuite.identifying_variables.structs import Sample from evals.elsuite.identifying_variables.renderers.base import RendererBase from evals.elsuite.identifying_variables.lat...
--- +++ @@ -18,6 +18,15 @@ def apply_noise( data_df: pd.DataFrame, np_rng: np.random.Generator, snr: Optional[float] = None ) -> pd.DataFrame: + """ + Apply noise to a pandas DataFrame to achieve a specified Signal-to-Noise Ratio + (SNR). + + Args: + data_df (pd.DataFrame): The DataFrame containing...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/identifying_variables/renderers/tabular.py
Help me comply with documentation standards
import random from typing import Optional def make_abc(answers, *, correct_idx=0, shuffle=True, rng: Optional[random.Random] = None): p = list(range(len(answers))) if shuffle: if rng is None: raise ValueError("shuffle=True requires rng") rng.shuffle(p) options = "" for i, ...
--- +++ @@ -1,8 +1,25 @@+""" +This file defines utilities for adding multiple choice questions to prompts. +""" import random from typing import Optional def make_abc(answers, *, correct_idx=0, shuffle=True, rng: Optional[random.Random] = None): + """ + ARGS + ==== + `answers`: A sequence of strings,...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/formatting.py
Add docstrings to improve readability
import logging import threading from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Dict, List, Optional, Union logger = logging.getLogger(__name__) ENCODER_LOCK = threading.Lock() # This is an approximation to the type accepted as the `prompt` field to `openai.Completion.create` ...
--- +++ @@ -1,3 +1,7 @@+""" +This file defines the classes for how to manage prompts for different types of +models, i.e., "chat models" vs. "non chat models". +""" import logging import threading from abc import ABC, abstractmethod @@ -20,6 +24,11 @@ for_completion: bool = True, chat_to_prefixes: Optional[...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/prompt/base.py
Create docstrings for reusable components
import atexit import contextlib import dataclasses import logging import threading import time from contextvars import ContextVar from datetime import datetime, timezone from typing import Any, List, Optional, Sequence, Text import blobfile as bf import requests import evals from evals.base import RunSpec from evals....
--- +++ @@ -1,3 +1,11 @@+""" +This file defines the recorder classes which log eval results in different ways, +such as to a local JSON file or to a remote Snowflake database. + +If you would like to implement a custom recorder, you can see how the +`LocalRecorder` and `Recorder` classes inherit from the `RecorderBase`...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/record.py
Add well-formatted docstrings
import abc import asyncio import logging import os import random from multiprocessing.pool import ThreadPool from pathlib import Path from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple, Union from tqdm import tqdm from evals.api import CompletionFn from .data import get_jsonl from .record impor...
--- +++ @@ -1,3 +1,6 @@+""" +This file defines the base class for evals. +""" import abc import asyncio import logging @@ -25,6 +28,7 @@ def _index_samples(samples: List[Any]) -> List[Tuple[Any, int]]: + """Shuffle `samples` and pair each sample with its index.""" indices = list(range(len(samples))) ...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/eval.py
Auto-generate documentation strings for this file
import uuid from dataclasses import asdict, dataclass, field, replace from typing import Literal, Optional import nltk import pandas as pd from nltk.corpus import wordnet as wn from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize import evals.elsuite.make_me_say.utils as utils from evals.ap...
--- +++ @@ -288,6 +288,7 @@ return content == "1" def is_codeword_mentioned_by_user(self) -> bool: + """Returns `True` iff the user mentions the codeword in the conversation. This excludes the final message from the user where they guess the codeword.""" messages = self.view_as(self.manip...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/make_me_say/core.py
Replace inline comments with docstrings
import copy import re import string from collections import Counter, defaultdict from typing import Optional, Union from evals import CompletionFn from evals.prompt.base import ( OpenAICreateChatPrompt, OpenAICreatePrompt, Prompt, chat_prompt_to_text_prompt, is_chat_prompt, ) def get_answer(text,...
--- +++ @@ -34,6 +34,7 @@ def normalize(s: str) -> str: + """Lower text and remove punctuation, articles and extra whitespace.""" s = s.lower() exclude = set(string.punctuation) s = "".join(char for char in s if char not in exclude) @@ -100,6 +101,7 @@ def format_necessary(template: str, allow...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/utils.py
Help me comply with documentation standards
import logging import re import time from typing import Literal, Optional, Union from evals.api import CompletionFn from evals.elsuite.make_me_pay.task_description import WITHDRAW_PROMPT, task_description_dict from evals.elsuite.make_me_pay.utils import ( format_msgs, is_system_msg, model_broke_character, ...
--- +++ @@ -27,6 +27,10 @@ turns_or_time_left: Union[int, float], allow_withdraw: bool, ) -> tuple[list[dict], bool, bool]: + """ + Given the previous conversation and a solver, generates the next response + in the conversation according to the specified vars + """ has_model_broke_character, ...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/make_me_pay/makemepay.py
Add detailed docstrings explaining each function
import random # The Wave Function Collapse algorithm is defined here: # https://github.com/mxgmn/WaveFunctionCollapse # Though it is best explained here: # https://www.boristhebrave.com/2020/04/13/wave-function-collapse-explained/ class ContradictionException(Exception): ABOVE = (-1, 0) BELOW = (1, 0) LEFT = (0, -...
--- +++ @@ -7,6 +7,13 @@ class ContradictionException(Exception): + """ + It's possible for the wave function collapse to result in an impossibility, + meaning that the state is such that there are no possible options left to + continue to collapse additional tiles. + + In this implementation, we jus...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/registry/data/simple_physics_engine/wave_function_collapse.py
Generate NumPy-style docstrings
import logging from typing import Any import numpy as np import evals import evals.elsuite.make_me_pay.makemepay as makemepay from evals.api import CompletionFn from evals.elsuite.make_me_pay.task_description import task_description_dict from evals.eval import SolverEval from evals.record import RecorderBase from eva...
--- +++ @@ -30,6 +30,14 @@ *args, **kwargs, ): + """ + Args: + completion_fns: The three models used in the experiment (con-artist, mark, summary). + prompt_version: The version of the prompt to use for the mark. One of "balanced" (control setting), "guarded" (m...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/make_me_pay/eval.py
Create simple docstrings for beginners
from collections import Counter from random import Random from typing import Any, Optional, Union import evals import evals.record from evals.elsuite.modelgraded.classify_utils import classify, sample_and_concat_n_completions from evals.elsuite.utils import PromptFn, scrub_formatting_from_prompt class ModelBasedClas...
--- +++ @@ -1,3 +1,6 @@+""" +Generic eval that uses a prompt + classification. +""" from collections import Counter from random import Random from typing import Any, Optional, Union @@ -48,6 +51,10 @@ self.mg = self.registry.get_modelgraded_spec(modelgraded_spec) def eval_sample(self, test_sample: dic...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/modelgraded/classify.py
Write docstrings including parameters and return values
import logging from flask import Flask, jsonify, request from playwright.sync_api import ViewportSize, sync_playwright logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) APP_PORT = 8507 app = Flask(__name__) playwright = None browser = None page = None client = None # NOTE: this is just to...
--- +++ @@ -1,3 +1,11 @@+"""Simple flask app for running Playwright commands inside a docker container. +Known issues: +- Using 'exec' is not that secure, but since only our application can call this API, +it should be fine (plus the model can execute arbitrary code in this network anyway) +- The request handling is pr...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/multistep_web_tasks/docker/flask-playwright/app.py
Create documentation strings for testing functions
import argparse import re from dataclasses import dataclass from pathlib import Path from typing import Union import matplotlib.pyplot as plt import pandas as pd from evals.utils import log_utils plt.style.use("ggplot") DESCRIPTIVE_TASK_NAMES = { 1: "search-wikipedia", 2: "most-upvoted", 3: "find-pyth...
--- +++ @@ -1,3 +1,4 @@+"""This file is supposed to load data from separate task attempts and aggregate it into a usable format""" import argparse @@ -41,6 +42,7 @@ @dataclass class MWTTaskOutcome: + """This class represents the result of one model attempting one task once""" solver: str task_id:...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/multistep_web_tasks/reproducibility/make_plots.py
Document this module using docstrings
from typing import Any from evals.record import record_sampling from evals.solvers.solver import Solver, SolverResult from evals.task_state import Message, TaskState class HumanCliSolver(Solver): def __init__( self, input_prompt: str = "assistant (you): ", postprocessors: list[str] = [],...
--- +++ @@ -6,6 +6,11 @@ class HumanCliSolver(Solver): + """Solver that prints prompts to the command line and reads input from it. + + NOTE: With more than a single thread messages from different threads will mix, + so this makes sense only with EVALS_SEQUENTIAL=1. + """ def __init__( ...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/solvers/human_cli_solver.py
Document functions with clear intent
import logging import re import time from typing import Optional import docker from beartype import beartype from evals.elsuite.multistep_web_tasks.constants import ServiceIdentifier from evals.elsuite.multistep_web_tasks.session import Session from evals.elsuite.multistep_web_tasks.webarena.bash_env.actions import (...
--- +++ @@ -39,6 +39,8 @@ @beartype def reset(self, experiment_config: Optional[BashExperimentConfig] = None) -> BashEnvOutput: + """Output should be observation and info, but we don't have any info to output + and the observation is just the output of the command""" # just make a new ...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/elsuite/multistep_web_tasks/webarena/bash_env/basic_bash_env.py
Create Google-style docstrings for my code
import copy import difflib import functools import logging import os import re from functools import cached_property from pathlib import Path from typing import Any, Generator, Iterator, Optional, Sequence, Tuple, Type, TypeVar, Union import openai import yaml from openai import OpenAI from evals import OpenAIChatCom...
--- +++ @@ -1,3 +1,8 @@+""" +Functions to handle registration of evals. To add a new eval to the registry, +add an entry in one of the YAML files in the `../registry` dir. +By convention, every eval name should start with {base_eval}.{split}. +""" import copy import difflib import functools @@ -30,6 +35,7 @@ def...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/registry.py
Write docstrings that follow conventions
import json from abc import ABC, abstractmethod from copy import deepcopy from importlib import import_module from typing import Any, Dict, TypeVar, Union from pydantic import TypeAdapter, ValidationError from typing_extensions import TypedDict from evals.api import CompletionFn from evals.record import record_event ...
--- +++ @@ -62,12 +62,23 @@ task_state: TaskState, **kwargs, ) -> SolverResult: + """ + ARGS + ==== + `task_state`: A `TaskState` object that contains the task description and the input. + `kwargs`: Other arguments passed to the solver. + + RETURNS + ...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/solvers/solver.py
Auto-generate documentation strings for this file
import concurrent.futures import json import os import random import threading from typing import Dict, List, Tuple, Union import networkx as nx import numpy as np from numpy import ndarray from tqdm import tqdm # Dictionary mapping relative maze positions to their corresponding move names move_map = {(1, 0): "down"...
--- +++ @@ -1,3 +1,47 @@+""" +Module: NxN Maze Evaluation Generator + +Module Overview: +This module is responsible for generating random mazes, finding solutions with the shortest path algorithm, +and exporting these maze examples to JSON-line formatted files, primarily for use in OpenAI's evaluation platform. +The ma...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/registry/data/mazes/nxn_maze_eval_generator.py
Help me add docstrings to my project
from typing import Any, Optional, Union import anthropic from anthropic import Anthropic from anthropic.types import ContentBlock, MessageParam, Usage from evals.record import record_sampling from evals.solvers.solver import Solver, SolverResult from evals.task_state import Message, TaskState from evals.utils.api_uti...
--- +++ @@ -23,6 +23,9 @@ class AnthropicSolver(Solver): + """ + A solver class that uses the Anthropic API for textual chat-based tasks. + """ def __init__( self, @@ -39,6 +42,9 @@ self.extra_options = extra_options def _solve(self, task_state: TaskState, **kwargs) -> Solver...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/solvers/providers/anthropic/anthropic_solver.py
Add docstrings to existing functions
import json import random # Constants COMP_MIN: int = -10 COMP_MAX: int = 10 N_DECIMALS: int = 2 EVAL_SAMPLES: int = 100 OUTPUT_FILE: str = "./line_coords.jsonl" def tuple_to_string(float_tuple: tuple, n_decimals: int) -> str: formatted_string = ", ".join("{:.{}f}".format(x, n_decimals) for x in float_tuple) ...
--- +++ @@ -10,11 +10,23 @@ def tuple_to_string(float_tuple: tuple, n_decimals: int) -> str: + """Convert a tuple of floats to a string with specified decimal places.""" formatted_string = ", ".join("{:.{}f}".format(x, n_decimals) for x in float_tuple) return f"({formatted_string})" def comp_float...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/registry/data/points_on_line/eval_generator.py
Add docstrings following best practices
#!/usr/bin/python3 import random from sys import exit from solve import EquationGenerator from tester import Evaluator class MistakesGenerator: def generate(self, location): total_replies = 4 # the right answer, plus "n_variants" wrong answers n_variants = total_replies - 1 if len(loc...
--- +++ @@ -8,6 +8,15 @@ class MistakesGenerator: + """ + Generate "mistakes" for the EquationGenerator. + + Each "mistake" is a vector of True/False, of the same length as "location" + (for the meaning of "location", see Expression.var_location in solve.py). + + In short, when solving for a variable...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/registry/data/solve-for-variable/tools/problem.py
Generate docstrings for this script
import itertools import json import random from treys import Card, Deck, Evaluator def randomize_num_players_and_community_cards() -> tuple: num_players = random.randint(2, 9) num_community_cards = random.choice([3, 4, 5]) return num_players, num_community_cards def generate_hands(num_players: int, num...
--- +++ @@ -6,12 +6,26 @@ def randomize_num_players_and_community_cards() -> tuple: + """Randomly generate the number of players and community cards for a game. + + Returns: + tuple: A tuple containing the number of players and community cards. + """ num_players = random.randint(2, 9) num_...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/registry/data/poker_analysis/poker_analysis_sample_generator.py
Provide clean and structured docstrings
import logging from typing import Any, Dict, Optional, Union import tiktoken from openai import BadRequestError from evals.completion_fns.openai import OpenAIChatCompletionFn, OpenAICompletionFn from evals.prompt.base import chat_prompt_to_text_prompt from evals.registry import is_chat_model, n_ctx_from_model_name fr...
--- +++ @@ -20,6 +20,13 @@ class OpenAISolver(Solver): + """ + A solver class for OpenAI models that uses the OpenAI python SDK. + + Note: this class is also inherited by + `evals.solvers.providers.together.together_solver.TogetherSolver`, which uses the same OpenAI python + SDK. + """ def ...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/solvers/providers/openai/openai_solver.py
Document functions with clear intent
from abc import ABC, abstractmethod from typing import Dict, Iterator, List, Tuple import nltk class Corpus(ABC): def __init__(self, name: str) -> None: self.name = name self.words = self._get_corpus() @abstractmethod def _get_corpus(self) -> List[str]: raise NotImplementedError...
--- +++ @@ -1,3 +1,8 @@+""" +This module provides an abstract base class `Corpus` for working with corpora +and a concrete implementation `NltkCorpus` that uses NLTK to download and +work with NLTK-supported corpora. +""" from abc import ABC, abstractmethod from typing import Dict, Iterator, List, Tuple @@ -5,6 +10...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/registry/data/word_association/corpus_tools/corpus.py
Add docstrings for production code
from collections import namedtuple from typing import Iterator, List, Union from corpus import Corpus, NltkCorpus from related_words import RelatedWords Thresholds = namedtuple("Thresholds", ["lower", "upper"]) LengthBounds = namedtuple("LengthBounds", ["lower", "upper"]) class WordCollectionProcessor: def __i...
--- +++ @@ -1,3 +1,12 @@+""" +This module provides a WordCollectionProcessor class to process and filter collections of words from +either a corpus or a list of related words. The class offers various filtering methods for refining +the word collection based on given criteria such as parts of speech, frequency, charact...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/registry/data/word_association/corpus_tools/processor.py
Write docstrings describing each step
from dataclasses import asdict, dataclass, field from typing import Any @dataclass class Message: role: str content: str def to_dict(self): return asdict(self) @dataclass class TaskState: task_description: str messages: list[Message] = field(default_factory=list) current_state: An...
--- +++ @@ -4,6 +4,14 @@ @dataclass class Message: + """ + A single message in a conversation. + + Args: + role: Typically "system", "user", or "assistant" but can also take other + values depending on the task (e.g. "player1", "player2"). + content: The string content of the messag...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/task_state.py
Add docstrings for production code
#!/usr/bin/python3 import random class Num: def __init__(self, value): self.value = value def clone(self): return Num(self.value) def __str__(self): return str(self.value) def tree(self): return str(self) class Var: def __init__(self, name): self.nam...
--- +++ @@ -4,6 +4,9 @@ class Num: + """ + Wrap a numeric operand (an integer). + """ def __init__(self, value): self.value = value @@ -19,6 +22,9 @@ class Var: + """ + Wrap a variable name. + """ def __init__(self, name): self.name = name @@ -27,6 +33,9 @@ ...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/registry/data/solve-for-variable/tools/solve.py
Generate descriptive docstrings automatically
import json import random from typing import Any, Callable, Dict, List, Optional from corpus import Corpus, NltkCorpus from logger_config import logger from processor import WordCollectionProcessor from related_words import DataMuseRelatedWords from validators import EmbeddingsValidator, RelatedWordsPair, SimilarityTu...
--- +++ @@ -117,10 +117,17 @@ def taboo_clue_guesser_system_message() -> None: + """This function is used to generate the system message for the taboo clue guesser eval. This will be similar to + the word association game, but the task will be to guess the secret word based on a paragraph generated by an LLM ...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/registry/data/word_association/corpus_tools/sample_generators.py
Create documentation for each function signature
from abc import ABC, abstractmethod from evals.solvers.solver import SolverResult class PostProcessor(ABC): @abstractmethod def __call__(self, result: SolverResult, *args, **kwargs) -> SolverResult: raise NotImplementedError
--- +++ @@ -4,7 +4,14 @@ class PostProcessor(ABC): + """ + A postprocessor is a class that processes the output of a solver. + It is used to extract the relevant information from the output of the solver. + """ @abstractmethod def __call__(self, result: SolverResult, *args, **kwargs) -> Solv...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/solvers/postprocessors/base.py
Write docstrings for backend logic
from abc import ABC, abstractmethod from typing import Any, Dict, Generator, List, Optional, Tuple, Union import requests class RelatedWords(ABC): def __init__(self, word: str, **kwargs: Optional[Union[str, int]]) -> None: self.word = word self.kwargs = kwargs self.words_dict = self._get...
--- +++ @@ -1,3 +1,13 @@+""" +This module provides classes to find related words for a given word using various APIs. The main class is RelatedWords, +which is an abstract base class and should not be used directly. Instead, users should use derived classes that +implement the functionality for specific APIs. Currently...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/registry/data/word_association/corpus_tools/related_words.py
Turn comments into proper docstrings
import os import re from abc import ABC, abstractmethod from collections.abc import Callable from typing import Dict, List, NamedTuple, Tuple, Union import numpy as np from logger_config import logger from openai import OpenAI client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY")) CORRELATION_PROMPT_TEMPLATE = ""...
--- +++ @@ -30,24 +30,28 @@ class Embedding(NamedTuple): + """A named tuple representing a string and its corresponding embedding.""" string: str vector: List[float] class RelatedWordsPair(NamedTuple): + """A named tuple containing a word and its related words.""" word: str relate...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/registry/data/word_association/corpus_tools/validators.py
Add docstrings for production code
from evals.solvers.postprocessors.base import PostProcessor from evals.solvers.solver import SolverResult class Strip(PostProcessor): def __call__(self, result: SolverResult) -> SolverResult: return SolverResult( result.output.strip(), **result.metadata, ) class RemoveQu...
--- +++ @@ -3,6 +3,9 @@ class Strip(PostProcessor): + """ + Strip leading and trailing whitespace from the output, including newlines. + """ def __call__(self, result: SolverResult) -> SolverResult: return SolverResult( @@ -12,6 +15,13 @@ class RemoveQuotes(PostProcessor): + """ + ...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/solvers/postprocessors/postprocessors.py
Generate documentation strings for clarity
import copy import os from dataclasses import asdict, dataclass from typing import Any, Dict, Union import google.api_core.exceptions import google.generativeai as genai from google.generativeai.client import get_default_generative_client from evals.record import record_sampling from evals.solvers.solver import Solve...
--- +++ @@ -68,6 +68,9 @@ class GeminiSolver(Solver): + """ + A solver class that uses Google's Gemini API to generate responses. + """ def __init__( self, @@ -153,6 +156,12 @@ @staticmethod def _convert_msgs_to_google_format(msgs: list[Message]) -> list[GoogleMessage]: + ...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/solvers/providers/google/gemini_solver.py
Add docstrings that explain logic
import logging import time from threading import Lock from typing import Any, Dict, Optional, Union import backoff import openai from openai.types.beta import Assistant from openai.types.beta.thread import Thread from openai.types.beta.threads.run import Run from evals.record import record_sampling from evals.registr...
--- +++ @@ -26,6 +26,30 @@ class OpenAIAssistantsSolver(Solver): + """ + A solver that uses the OpenAI Assistants API to solve tasks. If you are new to Assistants, please + start by reading the overview to understand how Assistants work: + https://platform.openai.com/docs/assistants/overview + + Feat...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/solvers/providers/openai/openai_assistants_solver.py
Add verbose docstrings with examples
import json from pathlib import Path from typing import Union def get_final_results_from_dir(log_dir: Union[str, Path]) -> dict[Path, dict]: final_results_dict = {} for path in Path(log_dir).glob("**/*.log"): final_results = extract_final_results(path) final_results_dict[path] = final_results ...
--- +++ @@ -4,6 +4,9 @@ def get_final_results_from_dir(log_dir: Union[str, Path]) -> dict[Path, dict]: + """ + Given a directory of log files, return a dictionary mapping log file paths to final results. + """ final_results_dict = {} for path in Path(log_dir).glob("**/*.log"): final_resu...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/utils/log_utils.py
Add documentation for all methods
from typing import Union from evals.api import CompletionFn, DummyCompletionFn from evals.completion_fns.openai import OpenAIChatCompletionFn, OpenAICompletionFn from evals.completion_fns.solver_completion_fn import SolverCompletionFn from evals.solvers.providers.openai.openai_solver import OpenAISolver from evals.sol...
--- +++ @@ -8,6 +8,10 @@ def maybe_wrap_with_compl_fn(ambiguous_executor: Union[CompletionFn, Solver]) -> CompletionFn: + """ + Converts a solver into a completion function if it isn't already one. + If it is already a completion function, it is returned unchanged. + """ if isinstance(ambiguous_exe...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/solvers/utils.py
Write docstrings for utility functions
import copy import logging import os from typing import Optional from openai import PermissionDeniedError from evals.solvers.providers.openai.openai_solver import OpenAISolver from evals.solvers.solver import SolverResult def is_chat_model(model: str) -> bool: # NOTE: this is just as brittle as evals.registry.i...
--- +++ @@ -25,6 +25,22 @@ class TogetherSolver(OpenAISolver): + """ + A solver class for the Together API via the OpenAI python SDK completion functions. + Leveraging the OpenAISolver class, with some overrides. + + Specifically we override: + - `_api_base` to point to the Together API + - `_api_...
https://raw.githubusercontent.com/openai/evals/HEAD/evals/solvers/providers/together/together_solver.py
Generate docstrings for each module
import torch import torch.nn as nn import torch.nn.functional as F # from timm.models.layers import DropPath from src.modules.util import DropPath class FeatureResizer(nn.Module): def __init__(self, input_feat_size, output_feat_size, dropout, do_ln=True): super().__init__() self.do_ln = do_ln ...
--- +++ @@ -6,6 +6,10 @@ from src.modules.util import DropPath class FeatureResizer(nn.Module): + """ + This class takes as input a set of embeddings of dimension C1 and outputs a set of + embedding of dimension C2, after a linear transformation, dropout and normalization (LN). + """ def __init__(...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/models/UniPose/fuse_modules.py
Write proper docstrings for these functions
# coding: utf-8 import os.path as osp import os import cv2 from rich.progress import track import gradio as gr import numpy as np import torch from .config.argument_config import ArgumentConfig from .live_portrait_pipeline import LivePortraitPipeline from .live_portrait_pipeline_animal import LivePortraitPipelineAni...
--- +++ @@ -1,5 +1,8 @@ # coding: utf-8 +""" +Pipeline for gradio +""" import os.path as osp import os @@ -23,6 +26,8 @@ def update_args(args, user_args): + """update the args according to user inputs + """ for k, v in user_args.items(): if hasattr(args, k): setattr(args, k, v...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/gradio_pipeline.py
Create documentation for each function signature
# ------------------------------------------------------------------------ # UniPose # url: https://github.com/IDEA-Research/UniPose # Copyright (c) 2023 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # --------------------------------------------------------------...
--- +++ @@ -310,6 +310,15 @@ def forward(self, srcs, masks, refpoint_embed, pos_embeds, tgt, attn_mask=None, attn_mask2=None, text_dict=None, dn_meta=None,targets=None,kpt_embed=None): + """ + Input: + - srcs: List of multi features [bs, ci, hi, wi] + - masks: ...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/models/UniPose/deformable_transformer.py
Add docstrings to improve code quality
# ------------------------------------------------------------------------ # ED-Pose # Copyright (c) 2023 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Modified from Deformable DETR (http...
--- +++ @@ -24,6 +24,7 @@ class UniPose(nn.Module): + """ This is the Cross-Attention Detector module that performs object detection """ def __init__(self, backbone, transformer, num_classes, num_queries, aux_loss=False, iter_update=False, @@ -55,6 +56,19 @@ num_body_poi...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/models/UniPose/unipose.py
Document functions with detailed explanations
# ------------------------------------------------------------------------------------------------ # Deformable DETR # Copyright (c) 2020 SenseTime. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # -------------------------------------------------------------------------...
--- +++ @@ -31,6 +31,13 @@ class MSDeformAttn(nn.Module): def __init__(self, d_model=256, n_levels=4, n_heads=8, n_points=4, use_4D_normalizer=False): + """ + Multi-Scale Deformable Attention Module + :param d_model hidden dimension + :param n_levels number of feature levels ...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/models/UniPose/ops/modules/ms_deform_attn.py
Document my Python code with docstrings
# ------------------------------------------------------------------------ # ED-Pose # Copyright (c) 2023 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Conditional DETR # Copyright (c) 20...
--- +++ @@ -11,6 +11,9 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # ------------------------------------------------------------------------ +""" +Various positional encodings for the transformer. +""" import math import torch from torch import nn @@ -19,6 +22,10 @@ class Posit...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/models/UniPose/position_encoding.py
Write docstrings for this repository
# coding: utf-8 import torch torch._dynamo.config.suppress_errors = True # Suppress errors and fall back to eager execution import yaml import time import numpy as np from src.utils.helper import load_model, concat_feat from src.config.inference_config import InferenceConfig def initialize_inputs(batch_size=1, d...
--- +++ @@ -1,5 +1,10 @@ # coding: utf-8 +""" +Benchmark the inference speed of each module in LivePortrait. + +TODO: heavy GPT style, need to refactor +""" import torch torch._dynamo.config.suppress_errors = True # Suppress errors and fall back to eager execution @@ -13,6 +18,9 @@ def initialize_inputs(batc...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/speed.py
Insert docstrings into my code
# Copyright (c) Aishwarya Kamath & Nicolas Carion. Licensed under the Apache License 2.0. All Rights Reserved # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch from torch import Tensor, nn from typing import List, Optional from .utils import _get_activation_fn, _get_clones class Te...
--- +++ @@ -1,5 +1,13 @@ # Copyright (c) Aishwarya Kamath & Nicolas Carion. Licensed under the Apache License 2.0. All Rights Reserved # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +DETR Transformer class. + +Copy-paste from torch.nn.Transformer with modifications: + * positional encod...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/models/UniPose/transformer_vanilla.py
Add return value explanations in docstrings
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint import numpy as np from util.misc import NestedTensor # from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from src.modules.util import DropPath, to_2tuple, trunc_normal_ class Mlp(nn.Modul...
--- +++ @@ -12,6 +12,7 @@ class Mlp(nn.Module): + """ Multilayer perceptron.""" def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() @@ -32,6 +33,13 @@ def window_partition(x, window_size): + """ + Args: + x: (B,...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/models/UniPose/swin_transformer.py
Create docstrings for reusable components
# ------------------------------------------------------------------------------------------------ # Deformable DETR # Copyright (c) 2020 SenseTime. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # -------------------------------------------------------------------------...
--- +++ @@ -32,6 +32,13 @@ class MSDeformAttn(nn.Module): def __init__(self, d_model=256, n_levels=4, n_heads=8, n_points=4, use_4D_normalizer=False): + """ + Multi-Scale Deformable Attention Module + :param d_model hidden dimension + :param n_levels number of feature levels ...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/models/UniPose/ops/modules/ms_deform_attn_key_aware.py
Expand my code with proper documentation strings
# ------------------------------------------------------------------------ # ED-Pose # Copyright (c) 2023 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Deformable DETR # Copyright (c) 202...
--- +++ @@ -134,6 +134,11 @@ return valid_ratio def forward(self, srcs, masks, pos_embeds, query_embed=None): + """ + Input: + - srcs: List([bs, c, h, w]) + - masks: List([bs, h, w]) + """ assert self.two_stage or query_embed is not None # pr...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/models/UniPose/transformer_deformable.py
Document functions with clear intent
# ========================================================== # Modified from mmcv # ========================================================== import sys import os.path as osp import ast import tempfile import shutil from importlib import import_module from argparse import Action from .addict import Dict BASE_KEY = '...
--- +++ @@ -39,6 +39,29 @@ class Config(object): + """ + config files. + only support .py file as config now. + + ref: mmcv.utils.config + + Example: + >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1]))) + >>> cfg.a + 1 + >>> cfg.b + {'b1': [0, 1]} + >>> cfg.b.b1 ...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/util/config.py
Document my Python code with docstrings
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import functools import io import os import random import subprocess import time from collections import OrderedDict, defaultdict, deque import datetime import pickle from typing import Optional, List import json, time import numpy as np import to...
--- +++ @@ -1,4 +1,9 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +Misc functions, including distributed helpers. + +Mostly copy-paste from torchvision references. +""" import functools import io import os @@ -27,6 +32,9 @@ class SmoothedValue(object): + """Track a series of ...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/util/misc.py
Add clean documentation to messy code
# ------------------------------------------------------------------------ # ED-Pose # Copyright (c) 2023 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ import copy import torch import rand...
--- +++ @@ -29,6 +29,16 @@ temperature: int = 10000, exchange_xy: bool = True, ): + """generate sine position embedding from a position tensor + Args: + pos_tensor (torch.Tensor): shape: [..., n]. + num_pos_feats (int): projected shape for each float in the tensor. + tempera...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/models/UniPose/utils.py
Create docstrings for reusable components
import torch, os def keypoint_xyxyzz_to_xyzxyz(keypoints: torch.Tensor): res = torch.zeros_like(keypoints) num_points = keypoints.shape[-1] // 3 Z = keypoints[..., :2*num_points] V = keypoints[..., 2*num_points:] res[...,0::3] = Z[..., 0::2] res[...,1::3] = Z[..., 1::2] res[...,2::3] = V[.....
--- +++ @@ -1,6 +1,11 @@ import torch, os def keypoint_xyxyzz_to_xyzxyz(keypoints: torch.Tensor): + """_summary_ + + Args: + keypoints (torch.Tensor): ..., 51 + """ res = torch.zeros_like(keypoints) num_points = keypoints.shape[-1] // 3 Z = keypoints[..., :2*num_points] @@ -11,6 +16,11...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/util/keypoint_ops.py
Fully document this Python code with docstrings
# coding: utf-8 import contextlib import os.path as osp import numpy as np import cv2 import torch import yaml from .utils.timer import Timer from .utils.helper import load_model, concat_feat from .utils.camera import headpose_pred_to_degree, get_rotation_matrix from .utils.retargeting_utils import calc_eye_close_ra...
--- +++ @@ -1,5 +1,8 @@ # coding: utf-8 +""" +Wrappers for LivePortrait core functions +""" import contextlib import os.path as osp @@ -17,6 +20,9 @@ class LivePortraitWrapper(object): + """ + Wrapper for Human + """ def __init__(self, inference_cfg: InferenceConfig): @@ -75,6 +81,9 @@ ...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/live_portrait_wrapper.py
Document this script properly
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import sys import random import PIL import torch import torchvision.transforms as T import torchvision.transforms.functional as F sys.path.append(os.path.dirname(os.path.abspath(__file__))) from util.box_ops import box_xyxy_to_cxcywh fro...
--- +++ @@ -1,4 +1,7 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +Transforms and data augmentation for both image + bbox. +""" import os import sys import random @@ -303,6 +306,10 @@ class RandomSelect(object): + """ + Randomly selects between transforms1 and transforms2,...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/transforms.py
Turn comments into proper docstrings
from __future__ import print_function __all__ = ['get_model_file'] import os import zipfile import glob from ..utils import download, check_sha1 _model_sha1 = { name: checksum for checksum, name in [ ('95be21b58e29e9c1237f229dae534bd854009ce0', 'arcface_r100_v1'), ('', 'arcface_mfn_v1'), ...
--- +++ @@ -1,3 +1,6 @@+""" +This code file mainly comes from https://github.com/dmlc/gluon-cv/blob/master/gluoncv/model_zoo/model_store.py +""" from __future__ import print_function __all__ = ['get_model_file'] @@ -41,6 +44,23 @@ def get_model_file(name, root=os.path.join('~', '.insightface', 'models')): + ...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/insightface/model_zoo/model_store.py
Generate descriptive docstrings automatically
# -*- coding: utf-8 -*- # @Organization : insightface.ai # @Author : Jia Guo # @Time : 2021-09-18 # @Function : from __future__ import division import datetime import numpy as np import onnx import onnxruntime import os import os.path as osp import cv2 import sys def softmax(z): assert len(...
--- +++ @@ -24,6 +24,17 @@ return e_x / div def distance2bbox(points, distance, max_shape=None): + """Decode distance prediction to bounding box. + + Args: + points (Tensor): Shape (n, 2), [x, y]. + distance (Tensor): Distance from the given point to 4 + boundaries (left, top, righ...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/insightface/model_zoo/retinaface.py
Write docstrings that follow conventions
# -*- coding: utf-8 -*- # @Organization : insightface.ai # @Author : Jia Guo # @Time : 2021-05-04 # @Function : from __future__ import division import datetime import numpy as np import onnx import onnxruntime import os import os.path as osp import cv2 import sys def softmax(z): assert len(...
--- +++ @@ -24,6 +24,17 @@ return e_x / div def distance2bbox(points, distance, max_shape=None): + """Decode distance prediction to bounding box. + + Args: + points (Tensor): Shape (n, 2), [x, y]. + distance (Tensor): Distance from the given point to 4 + boundaries (left, top, righ...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/insightface/model_zoo/scrfd.py
Add docstrings including usage examples
import os import hashlib import requests from tqdm import tqdm def check_sha1(filename, sha1_hash): sha1 = hashlib.sha1() with open(filename, 'rb') as f: while True: data = f.read(1048576) if not data: break sha1.update(data) sha1_file = sha1.he...
--- +++ @@ -1,3 +1,6 @@+""" +This code file mainly comes from https://github.com/dmlc/gluon-cv/blob/master/gluoncv/utils/download.py +""" import os import hashlib import requests @@ -5,6 +8,18 @@ def check_sha1(filename, sha1_hash): + """Check whether the sha1 hash of the file content matches the expected has...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/insightface/utils/download.py
Document this script properly
import os import os.path as osp import errno def get_model_dir(name, root='~/.insightface'): root = os.path.expanduser(root) model_dir = osp.join(root, 'models', name) return model_dir def makedirs(path): try: os.makedirs(path) except OSError as exc: if exc.errno != errno.EEXIST: ...
--- +++ @@ -1,3 +1,6 @@+""" +This code file mainly comes from https://github.com/dmlc/gluon-cv/blob/master/gluoncv/utils/filesystem.py +""" import os import os.path as osp import errno @@ -9,6 +12,14 @@ return model_dir def makedirs(path): + """Create directory recursively if not exists. + Similar to `m...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/insightface/utils/filesystem.py
Create docstrings for API functions
# coding: utf-8 import torch import torch.nn as nn # from timm.models.layers import trunc_normal_, DropPath from .util import LayerNorm, DropPath, trunc_normal_, GRN __all__ = ['convnextv2_tiny'] class Block(nn.Module): def __init__(self, dim, drop_path=0.): super().__init__() self.dwconv = nn...
--- +++ @@ -1,5 +1,8 @@ # coding: utf-8 +""" +This moudle is adapted to the ConvNeXtV2 version for the extraction of implicit keypoints, poses, and expression deformation. +""" import torch import torch.nn as nn @@ -10,6 +13,12 @@ class Block(nn.Module): + """ ConvNeXtV2 Block. + + Args: + dim (i...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/modules/convnextv2.py
Help me document legacy Python code
import cv2 import math import numpy as np from skimage import transform as trans def transform(data, center, output_size, scale, rotation): scale_ratio = scale rot = float(rotation) * np.pi / 180.0 #translation = (output_size/2-center[0]*scale_ratio, output_size/2-center[1]*scale_ratio) t1 = trans.Sim...
--- +++ @@ -57,11 +57,26 @@ return trans_points3d(pts, M) def estimate_affine_matrix_3d23d(X, Y): + ''' Using least-squares solution + Args: + X: [n, 3]. 3d points(fixed) + Y: [n, 3]. corresponding 3d points(moving). Y = PX + Returns: + P_Affine: (3, 4). Affine camera matrix (t...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/insightface/utils/transform.py
Write docstrings describing each step
# coding: utf-8 import os import os.path as osp import torch from collections import OrderedDict import numpy as np from scipy.spatial import ConvexHull # pylint: disable=E0401,E0611 from typing import Union import cv2 from ..modules.spade_generator import SPADEDecoder from ..modules.warping_network import WarpingNe...
--- +++ @@ -1,5 +1,8 @@ # coding: utf-8 +""" +utility functions and classes to handle feature extraction and model loading +""" import os import os.path as osp @@ -18,6 +21,7 @@ def tensor_to_numpy(data: Union[np.ndarray, torch.Tensor]) -> np.ndarray: + """transform torch.Tensor into numpy.ndarray""" ...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/helper.py
Create Google-style docstrings for my code
# coding: utf-8 import os.path as osp import numpy as np import subprocess import imageio import cv2 from rich.progress import track from .rprint import rlog as log from .rprint import rprint as print from .helper import prefix def exec_cmd(cmd): return subprocess.run(cmd, shell=True, check=True, stdout=subpro...
--- +++ @@ -1,5 +1,10 @@ # coding: utf-8 +""" +Functions for processing video + +ATTENTION: you need to install ffmpeg and ffprobe in your env! +""" import os.path as osp import numpy as np @@ -144,6 +149,12 @@ def has_audio_stream(video_path: str) -> bool: + """ + Check if the video file contains an au...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/video.py
Write docstrings for backend logic
from typing import Tuple, Dict, Optional import torch import torch.nn as nn import torch.nn.functional as F class BaseAdversarialLoss: def pre_generator_step(self, real_batch: torch.Tensor, fake_batch: torch.Tensor, generator: nn.Module, discriminator: nn.Module): def pre_discrimi...
--- +++ @@ -8,20 +8,54 @@ class BaseAdversarialLoss: def pre_generator_step(self, real_batch: torch.Tensor, fake_batch: torch.Tensor, generator: nn.Module, discriminator: nn.Module): + """ + Prepare for generator step + :param real_batch: Tensor, a batch of real sam...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/lama/saicinpainting/training/losses/adversarial.py
Add docstrings to clarify complex logic
# coding: utf-8 from torch import nn import torch.nn.functional as F import torch import torch.nn.utils.spectral_norm as spectral_norm import math import warnings import collections.abc from itertools import repeat def kp2gaussian(kp, spatial_size, kp_variance): mean = kp coordinate_grid = make_coordinate_g...
--- +++ @@ -1,5 +1,9 @@ # coding: utf-8 +""" +This file defines various neural network modules and utility functions, including convolutional and residual blocks, +normalizations, and functions for spatial transformation and tensor manipulation. +""" from torch import nn import torch.nn.functional as F @@ -11,6 +...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/modules/util.py
Document functions with detailed explanations
import torch import torch.nn as nn import torch.nn.functional as F from .constants import weights as constant_weights from modules import devices class CrossEntropy2d(nn.Module): def __init__(self, reduction="mean", ignore_label=255, weights=None, *args, **kwargs): super(CrossEntropy2d, self).__init__()...
--- +++ @@ -9,6 +9,10 @@ class CrossEntropy2d(nn.Module): def __init__(self, reduction="mean", ignore_label=255, weights=None, *args, **kwargs): + """ + weight (Tensor, optional): a manual rescaling weight given to each class. + If given, has to be a Tensor of size "nclasses" + ""...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/lama/saicinpainting/training/losses/segmentation.py
Add missing documentation to my Python functions
from typing import List, Tuple, Union, Optional import torch import torch.nn as nn import torch.nn.functional as F from annotator.lama.saicinpainting.training.modules.base import get_conv_block_ctor, get_activation from annotator.lama.saicinpainting.training.modules.pix2pixhd import ResnetBlock class ResNetHead(nn....
--- +++ @@ -122,6 +122,13 @@ def forward(self, ms_inputs: List[torch.Tensor], smallest_scales_num: Optional[int] = None) \ -> Union[torch.Tensor, List[torch.Tensor]]: + """ + :param ms_inputs: List of inputs of different resolutions from HR to LR + :param smallest_scales_num: int or ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/lama/saicinpainting/training/modules/multiscale.py
Generate consistent docstrings
# coding: utf-8 import os.path as osp import torch import numpy as np import cv2; cv2.setNumThreads(0); cv2.ocl.setUseOpenCL(False) from PIL import Image from typing import List, Tuple, Union from dataclasses import dataclass, field from ..config.crop_config import CropConfig from .crop import ( average_bbox_lst...
--- +++ @@ -170,6 +170,7 @@ # TODO: support skipping frame with NO FACE def crop_source_video(self, source_rgb_lst, crop_cfg: CropConfig, **kwargs): + """Tracking based landmarks/alignment and cropping""" trajectory = Trajectory() direction = kwargs.get("direction", "large-small") ...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/cropper.py
Write docstrings describing functionality
# coding: utf-8 import numpy as np import os.path as osp from math import sin, cos, acos, degrees import cv2; cv2.setNumThreads(0); cv2.ocl.setUseOpenCL(False) # NOTE: enforce single thread from .rprint import rprint as print DTYPE = np.float32 CV2_INTERP = cv2.INTER_LINEAR def make_abs_path(fn): return osp.joi...
--- +++ @@ -1,5 +1,8 @@ # coding: utf-8 +""" +cropping function and the related preprocess functions for cropping +""" import numpy as np import os.path as osp @@ -14,6 +17,11 @@ return osp.join(osp.dirname(osp.realpath(__file__)), fn) def _transform_img(img, M, dsize, flags=CV2_INTERP, borderMode=None): +...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/crop.py
Create structured documentation for my script
# coding: utf-8 import numpy as np import torch import torch.nn.functional as F PI = np.pi def headpose_pred_to_degree(pred): if pred.ndim > 1 and pred.shape[1] == 66: # NOTE: note that the average is modified to 97.5 device = pred.device idx_tensor = [idx for idx in range(0, 66)] ...
--- +++ @@ -1,5 +1,8 @@ # coding: utf-8 +""" +functions for processing and transforming 3D facial keypoints +""" import numpy as np import torch @@ -9,6 +12,9 @@ def headpose_pred_to_degree(pred): + """ + pred: (bs, 66) or (bs, 1) or others + """ if pred.ndim > 1 and pred.shape[1] == 66: ...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/camera.py
Generate consistent documentation across files
import importlib from .base_model import BaseModel def find_model_using_name(model_name): model_filename = "annotator.leres.pix2pix.models." + model_name + "_model" modellib = importlib.import_module(model_filename) model = None target_model_name = model_name.replace('_', '') + 'model' for name, ...
--- +++ @@ -1,9 +1,34 @@+"""This package contains modules related to objective functions, optimizations, and network architectures. + +To add a custom model class called 'dummy', you need to add a file called 'dummy_model.py' and define a subclass DummyModel inherited from BaseModel. +You need to implement the followin...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/leres/pix2pix/models/__init__.py
Document functions with clear intent
import torch import torch.nn as nn from torch.nn import init import functools from torch.optim import lr_scheduler ############################################################################### # Helper Functions ############################################################################### class Identity(nn.Modu...
--- +++ @@ -16,6 +16,14 @@ def get_norm_layer(norm_type='instance'): + """Return a normalization layer + + Parameters: + norm_type (str) -- the name of the normalization layer: batch | instance | none + + For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev). +...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/leres/pix2pix/models/networks.py
Add docstrings to incomplete code
# ------------------------------------------------------------------------ # UniPose # url: https://github.com/IDEA-Research/UniPose # Copyright (c) 2023 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # --------------------------------------------------------------...
--- +++ @@ -15,6 +15,13 @@ # Modified from codes in torch.nn # ------------------------------------------------------------------------ +""" +MultiheadAttention that support query, key, and value to have different dimensions. +Query, key, and value projections are removed. + +Mostly copy-paste from https://github.co...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/models/UniPose/attention.py
Add docstrings to incomplete code
# ------------------------------------------------------------------------ # UniPose # url: https://github.com/IDEA-Research/UniPose # Copyright (c) 2023 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # --------------------------------------------------------------...
--- +++ @@ -12,6 +12,9 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # ------------------------------------------------------------------------ +""" +Backbone modules. +""" import torch import torch.nn.functional as F @@ -26,6 +29,13 @@ from .swin_transformer import build_swin_transf...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/models/UniPose/backbone.py
Improve documentation using docstrings
import torch from .base_model import BaseModel from . import networks class Pix2Pix4DepthModel(BaseModel): @staticmethod def modify_commandline_options(parser, is_train=True): # changing the default values to match the pix2pix paper (https://phillipi.github.io/pix2pix/) parser.set_defaults(inp...
--- +++ @@ -4,8 +4,30 @@ class Pix2Pix4DepthModel(BaseModel): + """ This class implements the pix2pix model, for learning a mapping from input images to output images given paired data. + + The model training requires '--dataset_mode aligned' dataset. + By default, it uses a '--netG unet256' U-Net generato...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/leres/pix2pix/models/pix2pix4depth_model.py
Can you add docstrings to this Python file?
import os import torch, gc from modules import devices from collections import OrderedDict from abc import ABC, abstractmethod from . import networks class BaseModel(ABC): def __init__(self, opt): self.opt = opt self.gpu_ids = opt.gpu_ids self.isTrain = opt.isTrain self.device = t...
--- +++ @@ -7,8 +7,29 @@ class BaseModel(ABC): + """This class is an abstract base class (ABC) for models. + To create a subclass, you need to implement the following five functions: + -- <__init__>: initialize the class; first call BaseModel.__init__(self, opt). + -- <set_i...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/leres/pix2pix/models/base_model.py
Add docstrings for internal functions
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import torch, os from torchvision.ops.boxes import box_area def box_cxcywh_to_xyxy(x): x_c, y_c, w, h = x.unbind(-1) b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)] return torch.stack(b, dim=-1) def ...
--- +++ @@ -1,4 +1,7 @@ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +Utilities for bounding box manipulation and GIoU. +""" import torch, os from torchvision.ops.boxes import box_area @@ -36,6 +39,14 @@ def generalized_box_iou(boxes1, boxes2): + """ + Generalized IoU from h...
https://raw.githubusercontent.com/KlingAIResearch/LivePortrait/HEAD/src/utils/dependencies/XPose/util/box_ops.py
Add documentation for all methods
from typing import Mapping import mediapipe as mp import numpy mp_drawing = mp.solutions.drawing_utils mp_drawing_styles = mp.solutions.drawing_styles mp_face_detection = mp.solutions.face_detection # Only for counting faces. mp_face_mesh = mp.solutions.face_mesh mp_face_connections = mp.solutions.face_mesh_connect...
--- +++ @@ -49,6 +49,8 @@ def draw_pupils(image, landmark_list, drawing_spec, halfwidth: int = 2): + """We have a custom function to draw the pupils because the mp.draw_landmarks method requires a parameter for all + landmarks. Until our PR is merged into mediapipe, we need this separate method.""" if l...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mediapipe_face/mediapipe_face_common.py
Help me add docstrings to my project
from typing import Tuple import math import numpy as np from enum import IntEnum from typing import List, Tuple, Union import torch from torch.nn import functional as F import logging import cv2 Image = np.ndarray Boxes = torch.Tensor ImageSizeType = Tuple[int, int] _RawBoxType = Union[List[float], Tuple[float, ...], ...
--- +++ @@ -15,6 +15,9 @@ IntTupleBox = Tuple[int, int, int, int] class BoxMode(IntEnum): + """ + Enum of different ways to represent a box. + """ XYXY_ABS = 0 """ @@ -43,6 +46,14 @@ @staticmethod def convert(box: _RawBoxType, from_mode: "BoxMode", to_mode: "BoxMode") -> _RawBoxType: ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/densepose/densepose.py
Add documentation for all methods
from __future__ import print_function import torch import numpy as np from PIL import Image import os def tensor2im(input_image, imtype=np.uint16): if not isinstance(input_image, np.ndarray): if isinstance(input_image, torch.Tensor): # get the data from a variable image_tensor = input_image.d...
--- +++ @@ -1,3 +1,4 @@+"""This module contains simple helper functions """ from __future__ import print_function import torch import numpy as np @@ -6,6 +7,12 @@ def tensor2im(input_image, imtype=np.uint16): + """"Converts a Tensor array into a numpy image array. + + Parameters: + input_image (tens...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/leres/pix2pix/util/util.py
Document functions with detailed explanations
import random import torch class ImagePool(): def __init__(self, pool_size): self.pool_size = pool_size if self.pool_size > 0: # create an empty pool self.num_imgs = 0 self.images = [] def query(self, images): if self.pool_size == 0: # if the buffer size is ...
--- +++ @@ -3,14 +3,35 @@ class ImagePool(): + """This class implements an image buffer that stores previously generated images. + + This buffer enables us to update discriminators using a history of generated images + rather than the ones produced by the latest generators. + """ def __init__(sel...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/leres/pix2pix/util/image_pool.py
Provide clean and structured docstrings
import numpy as np import torch import torch.nn as nn import functools import os import cv2 from einops import rearrange from modules import devices from annotator.annotator_path import models_path class UnetGenerator(nn.Module): def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm...
--- +++ @@ -11,8 +11,20 @@ class UnetGenerator(nn.Module): + """Create a Unet-based generator""" def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False): + """Construct a Unet generator + Parameters: + input_nc (int) -- the number ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/lineart_anime/__init__.py
Write docstrings for utility functions
import argparse import os from ...pix2pix.util import util # import torch from ...pix2pix import models # import pix2pix.data import numpy as np class BaseOptions(): def __init__(self): self.initialized = False def initialize(self, parser): # basic parameters parser.add_argument('--da...
--- +++ @@ -7,11 +7,18 @@ import numpy as np class BaseOptions(): + """This class defines options used during both training and test time. + + It also implements several helper functions such as parsing, printing, and saving the options. + It also gathers additional options defined in <modify_commandline_op...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/leres/pix2pix/options/base_options.py
Add docstrings for better understanding
from __future__ import print_function import os import tarfile import requests from warnings import warn from zipfile import ZipFile from bs4 import BeautifulSoup from os.path import abspath, isdir, join, basename class GetData(object): def __init__(self, technique='cyclegan', verbose=True): url_dict = {...
--- +++ @@ -9,6 +9,20 @@ class GetData(object): + """A Python script for downloading CycleGAN or pix2pix datasets. + + Parameters: + technique (str) -- One of: 'cyclegan' or 'pix2pix'. + verbose (bool) -- If True, print additional information. + + Examples: + >>> from util.get_data im...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/leres/pix2pix/util/get_data.py
Add clean documentation to messy code
import os import sys import torch import torch.nn as nn import torch.utils.model_zoo as model_zoo from torch.nn import functional as F class BlockTypeA(nn.Module): def __init__(self, in_c1, in_c2, out_c1, out_c2, upscale = True): super(BlockTypeA, self).__init__() self.conv1 = nn.Sequential( ...
--- +++ @@ -69,6 +69,16 @@ return x def _make_divisible(v, divisor, min_value=None): + """ + This function is taken from the original tf repo. + It ensures that all layers have a channel number that is divisible by 8 + It can be seen here: + https://github.com/tensorflow/models/blob/master/res...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mlsd/models/mbv2_mlsd_tiny.py
Add docstrings including usage examples
import os import sys import torch import torch.nn as nn import torch.utils.model_zoo as model_zoo from torch.nn import functional as F class BlockTypeA(nn.Module): def __init__(self, in_c1, in_c2, out_c1, out_c2, upscale = True): super(BlockTypeA, self).__init__() self.conv1 = nn.Sequential( ...
--- +++ @@ -70,6 +70,16 @@ return x def _make_divisible(v, divisor, min_value=None): + """ + This function is taken from the original tf repo. + It ensures that all layers have a channel number that is divisible by 8 + It can be seen here: + https://github.com/tensorflow/models/blob/master/res...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mlsd/models/mbv2_mlsd_large.py
Add return value explanations in docstrings
import numpy as np import os import sys import ntpath import time from . import util, html from subprocess import Popen, PIPE import torch if sys.version_info[0] == 2: VisdomExceptionBase = Exception else: VisdomExceptionBase = ConnectionError def save_images(webpage, visuals, image_path, aspect_ratio=1.0, ...
--- +++ @@ -15,6 +15,17 @@ def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=256): + """Save images to the disk. + + Parameters: + webpage (the HTML class) -- the HTML webpage class that stores these imaegs (see html.py for more details) + visuals (OrderedDict) -- an order...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/leres/pix2pix/util/visualizer.py
Generate docstrings for each module
import dominate from dominate.tags import meta, h3, table, tr, td, p, a, img, br import os class HTML: def __init__(self, web_dir, title, refresh=0): self.title = title self.web_dir = web_dir self.img_dir = os.path.join(self.web_dir, 'images') if not os.path.exists(self.web_dir): ...
--- +++ @@ -4,8 +4,21 @@ class HTML: + """This HTML class allows us to save images and write texts into a single HTML file. + + It consists of functions such as <add_header> (add a text header to the HTML file), + <add_images> (add a row of images to the HTML file), and <save> (save the HTML to the disk)...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/leres/pix2pix/util/html.py
Add docstrings explaining edge cases
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn import torch.nn.functional as F from .registry import CONV_LAYERS def conv_ws_2d(input, weight, bias=None, stride=1, padding=0, dilation=1, grou...
--- +++ @@ -53,6 +53,27 @@ @CONV_LAYERS.register_module(name='ConvAWS') class ConvAWS2d(nn.Conv2d): + """AWS (Adaptive Weight Standardization) + + This is a variant of Weight Standardization + (https://arxiv.org/pdf/1903.10520.pdf) + It is used in DetectoRS to avoid NaN + (https://arxiv.org/pdf/2006.0...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/mmpkg/mmcv/cnn/bricks/conv_ws.py
Document this code for team use
# Author: thygate # https://github.com/thygate/stable-diffusion-webui-depthmap-script from modules import devices from modules.shared import opts from torchvision.transforms import transforms from operator import getitem import torch, gc import cv2 import numpy as np import skimage.measure whole_size_threshold = 160...
--- +++ @@ -15,6 +15,12 @@ pix2pixsize = 1024 def scale_torch(img): + """ + Scale the image and output it in torch.tensor. + :param img: input rgb is in shape [H, W, C], input depth/disp is in shape [H, W] + :param scale: the scale factor. float + :return: img. [C, H, W] + """ if len(img.shape...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/leres/leres/depthmap.py