instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Add standardized docstrings across the file | from logging.config import fileConfig
from alembic import context
from ktem.db.models import * # noqa
from sqlalchemy import engine_from_config, pool
from sqlmodel import SQLModel
from theflow.settings import settings
# this is the Alembic Config object, which provides
# access to the values within the .ini file in ... | --- +++ @@ -28,6 +28,17 @@
def run_migrations_offline() -> None:
+ """Run migrations in 'offline' mode.
+
+ This configures the context with just a URL
+ and not an Engine, though an Engine is acceptable
+ here as well. By skipping the Engine creation
+ we don't even need a DBAPI to be available.
+
... | https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/migrations/env.py |
Add concise docstrings to each method |
from __future__ import annotations
def add_binary(first: str, second: str) -> str:
result = ""
carry, index_a, index_b = 0, len(first) - 1, len(second) - 1
zero = ord("0")
while index_a >= 0 or index_b >= 0 or carry == 1:
if index_a >= 0:
carry += ord(first[index_a]) - zero
... | --- +++ @@ -1,8 +1,32 @@+"""
+Add Binary
+
+Given two binary strings, return their sum as a binary string.
+
+Reference: https://leetcode.com/problems/add-binary/
+
+Complexity:
+ Time: O(max(m, n)) where m, n are lengths of the two strings
+ Space: O(max(m, n))
+"""
from __future__ import annotations
de... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/add_binary.py |
Add structured docstrings to improve clarity |
from __future__ import annotations
def search_range(nums: list[int], target: int) -> list[int]:
low = 0
high = len(nums) - 1
while low < high:
mid = low + (high - low) // 2
if target <= nums[mid]:
high = mid
else:
low = mid + 1
for j in range(len(nums... | --- +++ @@ -1,8 +1,37 @@+"""
+Search Range
+
+Given a sorted array of integers and a target value, find the starting and
+ending positions of the target. Returns [-1, -1] if the target is not found.
+
+Reference: https://en.wikipedia.org/wiki/Binary_search_algorithm
+
+Complexity:
+ Time: O(log n + k) where k is t... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/searching/search_range.py |
Generate NumPy-style docstrings |
from __future__ import annotations
def text_justification(words: list[str], max_width: int) -> list[str]:
result: list[str] = []
row_length = 0
row_words: list[str] = []
index = 0
is_first_word = True
while index < len(words):
while row_length <= max_width and index < len(words):
... | --- +++ @@ -1,8 +1,37 @@+"""
+Text Justification
+
+Given an array of words and a max width, format the text such that each line
+has exactly max_width characters and is fully justified. Extra spaces are
+distributed as evenly as possible with left slots getting more.
+
+Reference: https://leetcode.com/problems/text-ju... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/text_justification.py |
Create structured documentation for my script |
from __future__ import annotations
import math
def jump_search(array: list[int], target: int) -> int:
length = len(array)
block_size = int(math.sqrt(length))
block_prev = 0
block = block_size
if array[length - 1] < target:
return -1
while block <= length and array[block - 1] < targe... | --- +++ @@ -1,3 +1,15 @@+"""
+Jump Search
+
+Search for a target value in a sorted array by jumping ahead in fixed-size
+blocks and then performing a linear search within the identified block.
+
+Reference: https://en.wikipedia.org/wiki/Jump_search
+
+Complexity:
+ Time: O(1) best / O(sqrt n) average / O(sqrt n) wo... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/searching/jump_search.py |
Add docstrings for utility scripts |
from __future__ import annotations
def caesar_cipher(text: str, shift: int) -> str:
result = ""
for char in text:
code = ord(char)
if 64 < code < 91:
code = ((code - 65 + shift) % 26) + 65
if 96 < code < 123:
code = ((code - 97 + shift) % 26) + 97
resul... | --- +++ @@ -1,8 +1,33 @@+"""
+Caesar Cipher
+
+Caesar's cipher shifts each letter by a fixed number of positions in the
+alphabet. Letters wrap around when they pass the end of the alphabet.
+
+Reference: https://en.wikipedia.org/wiki/Caesar_cipher
+
+Complexity:
+ Time: O(n) where n is the length of the input stri... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/caesar_cipher.py |
Write proper docstrings for these functions | #!/usr/bin/env python
from __future__ import print_function
import base64
import string
from zlib import compress
import httplib2
import six # type: ignore
if six.PY2:
from string import maketrans
else:
maketrans = bytes.maketrans
plantuml_alphabet = (
string.digits + string.ascii_uppercase + string.... | --- +++ @@ -25,12 +25,21 @@
class PlantUMLError(Exception):
+ """
+ Error in processing.
+ """
class PlantUMLConnectionError(PlantUMLError):
+ """
+ Error connecting or talking to PlantUML Server.
+ """
class PlantUMLHTTPError(PlantUMLConnectionError):
+ """
+ Request to PlantUML s... | https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/utils/plantuml.py |
Add professional docstrings to my codebase |
from __future__ import annotations
def tree_print(tree: dict) -> list[str]:
lines: list[str] = []
for key in tree:
parts = [str(key)]
tree_element = tree[key]
for sub_elem in tree_element:
parts.append(str(sub_elem))
lines.append(" -> ".join(parts))
return line... | --- +++ @@ -1,8 +1,35 @@+"""
+Pretty Print Tree
+
+Prints a dictionary-based tree structure in a human-readable format showing
+keys and their nested elements.
+
+Reference: https://en.wikipedia.org/wiki/Tree_(data_structure)
+
+Complexity:
+ Time: O(n) where n is total number of elements
+ Space: O(1) additiona... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/pretty_print.py |
Add docstrings with type hints explained |
from __future__ import annotations
from collections import deque
from algorithms.common.tree_node import TreeNode
def left_view(root: TreeNode | None) -> list[int]:
if root is None:
return []
result: list[int] = []
queue: deque[TreeNode] = deque([root])
while queue:
level_size = len... | --- +++ @@ -1,3 +1,21 @@+"""
+Binary Tree Views
+
+Compute different "views" of a binary tree — the nodes visible when looking
+at the tree from a particular direction.
+
+- **Left view**: first node at each level (leftmost).
+- **Right view**: last node at each level (rightmost).
+- **Top view**: nodes visible when lo... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/binary_tree_views.py |
Add docstrings with type hints explained | from typing import Optional
from kotaemon.base import DocumentWithEmbedding, Param
from .base import BaseEmbeddings
class LCEmbeddingMixin:
def _get_lc_class(self):
raise NotImplementedError(
"Please return the relevant Langchain class in in _get_lc_class"
)
def __init__(self, *... | --- +++ @@ -87,6 +87,7 @@
class LCOpenAIEmbeddings(LCEmbeddingMixin, BaseEmbeddings):
+ """Wrapper around Langchain's OpenAI embedding, focusing on key parameters"""
def __init__(
self,
@@ -118,6 +119,7 @@
class LCAzureOpenAIEmbeddings(LCEmbeddingMixin, BaseEmbeddings):
+ """Wrapper around... | https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/embeddings/langchain_based.py |
Add docstrings to clarify complex logic | import pickle
import time
from datetime import datetime
from pathlib import Path
from typing import Any, Dict
import gradio as gr
import pandas as pd
from theflow.storage import storage
from kotaemon.contribs.promptui.base import get_component
from kotaemon.contribs.promptui.export import export
from ..logs import R... | --- +++ @@ -41,6 +41,12 @@ def construct_pipeline_ui(
config, func_run, func_save, func_load_params, func_activate_params, func_export
) -> gr.Blocks:
+ """Create UI from config file. Execute the UI from config file
+
+ - Can do now: Log from stdout to UI
+ - In the future, we can provide some hooks and ... | https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/kotaemon/kotaemon/contribs/promptui/ui/pipeline.py |
Document all endpoints with docstrings |
from __future__ import annotations
def alphabet_board_path(target: str) -> str:
moves: list[str] = []
row, col = 0, 0
for ch in target:
idx = ord(ch) - ord("a")
target_row, target_col = divmod(idx, 5)
# Move up/left before down/right to avoid going off-board at 'z'
if targ... | --- +++ @@ -1,8 +1,24 @@+"""Alphabet board path — find moves on a 5x5+1 letter board.
+
+Given a board where 'a'-'z' are laid out in rows of 5:
+ a b c d e
+ f g h i j
+ k l m n o
+ p q r s t
+ u v w x y
+ z
+
+Return the sequence of moves (U/D/L/R/!) to spell a target word
+starting from 'a'.
+
+Insp... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/alphabet_board_path.py |
Add verbose docstrings with examples | import html
import logging
from typing import AnyStr, Optional, Type
from ktem.llms.manager import llms
from ktem.mcp.manager import mcp_manager
from ktem.reasoning.base import BaseReasoning
from ktem.utils.generator import Generator
from ktem.utils.render import Render
from langchain.text_splitter import CharacterTex... | --- +++ @@ -155,6 +155,13 @@
class RewriteQuestionPipeline(BaseComponent):
+ """Rewrite user question
+
+ Args:
+ llm: the language model to rewrite question
+ rewrite_template: the prompt template for llm to paraphrase a text input
+ lang: the language of the answer. Currently support En... | https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/reasoning/react.py |
Generate documentation strings for clarity |
from __future__ import annotations
def can_swap_to_equal(s: str, t: str) -> bool:
if len(s) != len(t):
return False
diffs = [(a, b) for a, b in zip(s, t, strict=False) if a != b]
return len(diffs) == 2 and diffs[0] == diffs[1][::-1] | --- +++ @@ -1,9 +1,17 @@+"""Swap characters — check if two strings can be made equal by one swap.
+
+Given two strings of equal length, determine whether exactly one swap
+of two characters in the first string can make it equal to the second.
+
+Inspired by PR #890 (Thejas-1).
+"""
from __future__ import annotations... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/string/swap_characters.py |
Create docstrings for reusable components | import os
from pathlib import Path
from typing import Optional
import gradio as gr
import pluggy
from ktem import extension_protocol
from ktem.assets import PDFJS_PREBUILT_DIR, KotaemonTheme
from ktem.components import reasonings
from ktem.exceptions import HookAlreadyDeclared, HookNotDeclared
from ktem.index import I... | --- +++ @@ -17,6 +17,23 @@
class BaseApp:
+ """The main app of Kotaemon
+
+ The main application contains app-level information:
+ - setting state
+ - dynamic conversation state
+ - user id
+
+ Also contains registering methods for:
+ - reasoning pipelines
+ - indexing & ... | https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/app.py |
Add docstrings to improve code quality | import asyncio
import glob
import logging
import os
import re
from pathlib import Path
from typing import Generator
import numpy as np
import pandas as pd
from ktem.db.models import engine
from ktem.embeddings.manager import embedding_models_manager as embeddings
from ktem.llms.manager import llms
from sqlalchemy.orm ... | --- +++ @@ -247,6 +247,7 @@
class LightRAGIndexingPipeline(GraphRAGIndexingPipeline):
+ """GraphRAG specific indexing pipeline"""
prompts: dict[str, str] = {}
collection_graph_id: str
@@ -413,6 +414,7 @@
class LightRAGRetrieverPipeline(BaseFileIndexRetriever):
+ """GraphRAG specific retriever ... | https://raw.githubusercontent.com/Cinnamon/kotaemon/HEAD/libs/ktem/ktem/index/file/graph/lightrag_pipelines.py |
Document my Python code with docstrings |
import random
import numpy as np
import torch.utils.data as data
from PIL import Image
import torchvision.transforms as transforms
from abc import ABC, abstractmethod
class BaseDataset(data.Dataset, ABC):
def __init__(self, opt):
self.opt = opt
self.root = opt.dataroot
@staticmethod
def... | --- +++ @@ -1,3 +1,7 @@+"""This module implements an abstract base class (ABC) 'BaseDataset' for datasets.
+
+It also includes common transformation functions (e.g., get_transform, __scale_width), which can be later used in subclasses.
+"""
import random
import numpy as np
@@ -8,21 +12,52 @@
class BaseDataset(d... | https://raw.githubusercontent.com/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/data/base_dataset.py |
Generate helpful docstrings for debugging | import os
from data.base_dataset import BaseDataset, get_transform
from data.image_folder import make_dataset
from skimage import color # require skimage
from PIL import Image
import numpy as np
import torchvision.transforms as transforms
class ColorizationDataset(BaseDataset):
@staticmethod
def modify_comm... | --- +++ @@ -8,13 +8,34 @@
class ColorizationDataset(BaseDataset):
+ """This dataset class can load a set of natural images in RGB, and convert RGB format into (L, ab) pairs in Lab color space.
+
+ This dataset is required by pix2pix-based colorization model ('--model colorization')
+ """
@staticmeth... | https://raw.githubusercontent.com/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/data/colorization_dataset.py |
Add docstrings for utility scripts | import os
from data.base_dataset import BaseDataset, get_params, get_transform
from data.image_folder import make_dataset
from PIL import Image
class AlignedDataset(BaseDataset):
def __init__(self, opt):
BaseDataset.__init__(self, opt)
self.dir_AB = os.path.join(opt.dataroot, opt.phase) # get th... | --- +++ @@ -5,8 +5,18 @@
class AlignedDataset(BaseDataset):
+ """A dataset class for paired image dataset.
+
+ It assumes that the directory '/path/to/data/train' contains image pairs in the form of {A,B}.
+ During test time, you need to prepare a directory '/path/to/data/test'.
+ """
def __init_... | https://raw.githubusercontent.com/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/data/aligned_dataset.py |
Add documentation for all methods |
from data.base_dataset import BaseDataset, get_transform
# from data.image_folder import make_dataset
# from PIL import Image
class TemplateDataset(BaseDataset):
@staticmethod
def modify_commandline_options(parser, is_train):
parser.add_argument("--new_dataset_option", type=float, default=1.0, help... | --- +++ @@ -1,3 +1,16 @@+"""Dataset class template
+
+This module provides a template for users to implement custom datasets.
+You can specify '--dataset_mode template' to use this dataset.
+The class name should be consistent with both the filename and its dataset_mode option.
+The filename should be <dataset_mode>_da... | https://raw.githubusercontent.com/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/data/template_dataset.py |
Improve documentation using docstrings |
from __future__ import annotations
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from jinja2 import TemplateError
class CookiecutterException(Exception):
class NonTemplatedInputDirException(CookiecutterException):
class UnknownTemplateDirException(CookiecutterException):
# unused locally
c... | --- +++ @@ -1,3 +1,4 @@+"""All exceptions used in the Cookiecutter code base are defined here."""
from __future__ import annotations
@@ -8,58 +9,137 @@
class CookiecutterException(Exception):
+ """
+ Base exception class.
+
+ All Cookiecutter-specific exceptions should subclass this class.
+ """
... | https://raw.githubusercontent.com/cookiecutter/cookiecutter/HEAD/cookiecutter/exceptions.py |
Add docstrings that explain inputs and outputs | import dominate
from dominate.tags import meta, h3, table, tr, td, p, a, img, br
from pathlib import Path
class HTML:
def __init__(self, web_dir, title, refresh=0):
self.title = title
self.web_dir = Path(web_dir)
self.img_dir = self.web_dir / "images"
self.web_dir.mkdir(parents=T... | --- +++ @@ -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/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/util/html.py |
Write Python docstrings for this snippet |
import importlib
from models.base_model import BaseModel
def find_model_using_name(model_name: str):
model_filename = "models." + model_name + "_model"
modellib = importlib.import_module(model_filename)
model = None
target_model_name = model_name.replace("_", "") + "model"
for name, cls in modell... | --- +++ @@ -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/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/models/__init__.py |
Generate docstrings for script automation | from __future__ import print_function
from pathlib import Path
import tarfile
import requests
from warnings import warn
from zipfile import ZipFile
from bs4 import BeautifulSoup
class GetData(object):
def __init__(self, technique="cyclegan", verbose=True):
url_dict = {
"pix2pix": "http://efro... | --- +++ @@ -8,6 +8,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/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/util/get_data.py |
Generate helpful docstrings for debugging | 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 0,... | --- +++ @@ -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__(self,... | https://raw.githubusercontent.com/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/util/image_pool.py |
Add detailed documentation for each class | import os
from data.base_dataset import BaseDataset, get_transform
from data.image_folder import make_dataset
from PIL import Image
import random
class UnalignedDataset(BaseDataset):
def __init__(self, opt):
BaseDataset.__init__(self, opt)
self.dir_A = os.path.join(opt.dataroot, opt.phase + "A") ... | --- +++ @@ -6,8 +6,22 @@
class UnalignedDataset(BaseDataset):
+ """
+ This dataset class can load unaligned/unpaired datasets.
+
+ It requires two directories to host training images from domain A '/path/to/data/trainA'
+ and from domain B '/path/to/data/trainB' respectively.
+ You can train the mode... | https://raw.githubusercontent.com/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/data/unaligned_dataset.py |
Please document this code using docstrings |
from __future__ import annotations
import json
import os
import sys
from collections import OrderedDict
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from collections.abc import Iterable
from typing import Literal
from click import Context, Parameter
import click
from cookiecutter import __... | --- +++ @@ -1,3 +1,4 @@+"""Main `cookiecutter` CLI."""
from __future__ import annotations
@@ -35,6 +36,7 @@
def version_msg() -> str:
+ """Return the Cookiecutter version, location and Python powering it."""
python_version = sys.version
location = os.path.dirname(os.path.dirname(os.path.abspath(__... | https://raw.githubusercontent.com/cookiecutter/cookiecutter/HEAD/cookiecutter/cli.py |
Insert docstrings into my code |
from __future__ import annotations
from typing import Any
from jinja2 import Environment, StrictUndefined
from cookiecutter.exceptions import UnknownExtension
class ExtensionLoaderMixin:
def __init__(self, *, context: dict[str, Any] | None = None, **kwargs: Any) -> None:
context = context or {}
... | --- +++ @@ -1,3 +1,4 @@+"""Jinja2 environment and extensions loading."""
from __future__ import annotations
@@ -9,8 +10,21 @@
class ExtensionLoaderMixin:
+ """Mixin providing sane loading of extensions specified in a given context.
+
+ The context is being extracted from the keyword arguments before call... | https://raw.githubusercontent.com/cookiecutter/cookiecutter/HEAD/cookiecutter/environment.py |
Generate docstrings for script automation | import torch
import itertools
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
class CycleGANModel(BaseModel):
@staticmethod
def modify_commandline_options(parser, is_train=True):
parser.set_defaults(no_dropout=True) # default CycleGAN did not use dropou... | --- +++ @@ -6,9 +6,37 @@
class CycleGANModel(BaseModel):
+ """
+ This class implements the CycleGAN model, for learning image-to-image translation without paired data.
+
+ The model training requires '--dataset_mode unaligned' dataset.
+ By default, it uses a '--netG resnet_9blocks' ResNet generator,
+ ... | https://raw.githubusercontent.com/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/models/cycle_gan_model.py |
Generate missing documentation strings | from data.base_dataset import BaseDataset, get_transform
from data.image_folder import make_dataset
from PIL import Image
class SingleDataset(BaseDataset):
def __init__(self, opt):
BaseDataset.__init__(self, opt)
self.A_paths = sorted(make_dataset(opt.dataroot, opt.max_dataset_size))
inpu... | --- +++ @@ -4,18 +4,37 @@
class SingleDataset(BaseDataset):
+ """This dataset class can load a set of images specified by the path --dataroot /path/to/data.
+
+ It can be used for generating CycleGAN results only for one side with the model option '-model test'.
+ """
def __init__(self, opt):
+ ... | https://raw.githubusercontent.com/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/data/single_dataset.py |
Add detailed documentation for each class | import torch
from .base_model import BaseModel
from . import networks
class Pix2PixModel(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(norm="ba... | --- +++ @@ -4,9 +4,31 @@
class Pix2PixModel(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 generator,
+ ... | https://raw.githubusercontent.com/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/models/pix2pix_model.py |
Document all endpoints with docstrings |
from __future__ import annotations
import errno
import logging
import os
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Any
from jinja2.exceptions import UndefinedError
from cookiecutter import utils
from cookiecutter.exceptions import FailedHookException
from cookiecutter.... | --- +++ @@ -1,3 +1,4 @@+"""Functions for discovering and executing various cookiecutter hooks."""
from __future__ import annotations
@@ -32,6 +33,12 @@
def valid_hook(hook_file: str, hook_name: str) -> bool:
+ """Determine if a hook file is valid.
+
+ :param hook_file: The hook file to consider for valid... | https://raw.githubusercontent.com/cookiecutter/cookiecutter/HEAD/cookiecutter/hooks.py |
Generate consistent documentation across files |
import torch
from .base_model import BaseModel
from . import networks
class TemplateModel(BaseModel):
@staticmethod
def modify_commandline_options(parser, is_train=True):
parser.set_defaults(dataset_mode="aligned") # You can rewrite default values for this model. For example, this model usually uses... | --- +++ @@ -1,3 +1,20 @@+"""Model class template
+
+This module provides a template for users to implement custom models.
+You can specify '--model template' to use this model.
+The class name should be consistent with both the filename and its model option.
+The filename should be <model>_dataset.py
+The class name sh... | https://raw.githubusercontent.com/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/models/template_model.py |
Generate helpful docstrings for debugging | from .pix2pix_model import Pix2PixModel
import torch
from skimage import color # used for lab2rgb
import numpy as np
class ColorizationModel(Pix2PixModel):
@staticmethod
def modify_commandline_options(parser, is_train=True):
Pix2PixModel.modify_commandline_options(parser, is_train)
parser.se... | --- +++ @@ -5,20 +5,56 @@
class ColorizationModel(Pix2PixModel):
+ """This is a subclass of Pix2PixModel for image colorization (black & white image -> colorful images).
+
+ The model training requires '-dataset_model colorization' dataset.
+ It trains a pix2pix model, mapping from L channel to ab channels... | https://raw.githubusercontent.com/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/models/colorization_model.py |
Write docstrings that follow conventions |
from __future__ import annotations
import fnmatch
import json
import logging
import os
import shutil
import warnings
from collections import OrderedDict
from pathlib import Path
from typing import Any
from binaryornot.check import is_binary
from jinja2 import Environment, FileSystemLoader
from jinja2.exceptions impo... | --- +++ @@ -1,3 +1,4 @@+"""Functions for generating a project from a project template."""
from __future__ import annotations
@@ -36,6 +37,15 @@
def is_copy_only_path(path: str, context: dict[str, Any]) -> bool:
+ """Check whether the given `path` should only be copied and not rendered.
+
+ Returns True i... | https://raw.githubusercontent.com/cookiecutter/cookiecutter/HEAD/cookiecutter/generate.py |
Write docstrings for this repository | import os
import torch
import torch.distributed as dist
from pathlib import Path
from collections import OrderedDict
from abc import ABC, abstractmethod
from . import networks
class BaseModel(ABC):
def __init__(self, opt):
self.opt = opt
self.isTrain = opt.isTrain
self.save_dir = Path(opt... | --- +++ @@ -8,8 +8,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/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/models/base_model.py |
Add docstrings to improve readability |
from __future__ import annotations
import os
import tempfile
from pathlib import Path
from zipfile import BadZipFile, ZipFile
import requests
from cookiecutter.exceptions import InvalidZipRepository
from cookiecutter.prompt import prompt_and_delete, read_repo_password
from cookiecutter.utils import make_sure_path_e... | --- +++ @@ -1,3 +1,4 @@+"""Utility functions for handling and fetching repo archives in zip format."""
from __future__ import annotations
@@ -20,6 +21,19 @@ no_input: bool = False,
password: str | None = None,
) -> str:
+ """Download and unpack a zipfile at a given URI.
+
+ This will download the z... | https://raw.githubusercontent.com/cookiecutter/cookiecutter/HEAD/cookiecutter/zipfile.py |
Write Python docstrings for this snippet | import argparse
from pathlib import Path
from util import util
import torch
import models
import data
class BaseOptions:
def __init__(self):
self.initialized = False
def initialize(self, parser):
# basic parameters
parser.add_argument("--dataroot", required=True, help="path to images... | --- +++ @@ -7,11 +7,18 @@
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_options> functions in ... | https://raw.githubusercontent.com/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/options/base_options.py |
Generate consistent documentation across files | # The following code is modified from https://github.com/shelhamer/clockwork-fcn
import sys
import os
import glob
import numpy as np
from PIL import Image
class cityscapes:
def __init__(self, data_path):
# data_path something like /data2/cityscapes
self.dir = data_path
self.classes = ['roa... | --- +++ @@ -22,6 +22,12 @@ self.trainId2color = {label.trainId: label.color for label in labels.labels} # dictionary mapping train IDs to colors as 3-tuples
def get_dset(self, split):
+ '''
+ List images as (city, id) for the specified split
+
+ TODO(shelhamer) generate splits from ... | https://raw.githubusercontent.com/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/scripts/eval_cityscapes/cityscapes.py |
Provide docstrings following PEP 257 | 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/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/models/networks.py |
Write docstrings for backend logic |
from __future__ import print_function
import torch
import numpy as np
from PIL import Image
from pathlib import Path
import torch.distributed as dist
import os
def tensor2im(input_image, imtype=np.uint8):
if not isinstance(input_image, np.ndarray):
if isinstance(input_image, torch.Tensor): # get the dat... | --- +++ @@ -1,3 +1,4 @@+"""This module contains simple helper functions"""
from __future__ import print_function
import torch
@@ -9,6 +10,12 @@
def tensor2im(input_image, imtype=np.uint8):
+ """ "Converts a Tensor array into a numpy image array.
+
+ Parameters:
+ input_image (tensor) -- the input ... | https://raw.githubusercontent.com/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/util/util.py |
Write docstrings including parameters and return values | import numpy as np
import sys
import ntpath
import time
from . import util, html
from pathlib import Path
import wandb
import os
import torch.distributed as dist
def save_images(webpage, visuals, image_path, aspect_ratio=1.0, width=256):
image_dir = webpage.get_image_dir()
name = Path(image_path[0]).stem
... | --- +++ @@ -10,6 +10,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/junyanz/pytorch-CycleGAN-and-pix2pix/HEAD/util/visualizer.py |
Add clean documentation to messy code |
from __future__ import annotations
from algorithms.tree.tree import TreeNode
def longest_consecutive(root: TreeNode | None) -> int:
if root is None:
return 0
max_len = 0
_dfs(root, 0, root.val, max_len)
return max_len
def _dfs(root: TreeNode | None, current: int, target: int, max_len: int)... | --- +++ @@ -1,3 +1,15 @@+"""
+Longest Consecutive Sequence in Binary Tree
+
+Given a binary tree, find the length of the longest consecutive sequence path
+from parent to child (values increasing by one).
+
+Reference: https://en.wikipedia.org/wiki/Binary_tree
+
+Complexity:
+ Time: O(n)
+ Space: O(n) due to rec... | https://raw.githubusercontent.com/keon/algorithms/HEAD/algorithms/tree/longest_consecutive.py |
Add docstrings including usage examples |
from __future__ import annotations
import json
import string
import uuid
from collections.abc import Iterable
from secrets import choice
from typing import TYPE_CHECKING, Any
import arrow
from jinja2 import Environment, nodes
from jinja2.ext import Extension
from slugify import slugify as pyslugify
from slugify.slug... | --- +++ @@ -1,3 +1,4 @@+"""Jinja2 extensions."""
from __future__ import annotations
@@ -21,8 +22,10 @@
class JsonifyExtension(Extension):
+ """Jinja2 extension to convert a Python object to JSON."""
def __init__(self, environment: Environment) -> None:
+ """Initialize the extension with the gi... | https://raw.githubusercontent.com/cookiecutter/cookiecutter/HEAD/cookiecutter/extensions.py |
Add missing documentation to my Python functions |
from __future__ import annotations
import json
import os
import re
import sys
from collections import OrderedDict
from collections.abc import Iterator
from itertools import starmap
from pathlib import Path
from typing import TYPE_CHECKING, Any, TypeAlias
from jinja2.exceptions import UndefinedError
from rich.prompt ... | --- +++ @@ -1,3 +1,4 @@+"""Functions for prompting the user for project info."""
from __future__ import annotations
@@ -22,6 +23,11 @@
def read_user_variable(var_name: str, default_value, prompts=None, prefix: str = ""):
+ """Prompt user for variable and return the entered value or given default.
+
+ :pa... | https://raw.githubusercontent.com/cookiecutter/cookiecutter/HEAD/cookiecutter/prompt.py |
Auto-generate documentation strings for this file |
from __future__ import annotations
import os
import re
from typing import TYPE_CHECKING
from cookiecutter.exceptions import RepositoryNotFound
from cookiecutter.vcs import clone
from cookiecutter.zipfile import unzip
if TYPE_CHECKING:
from pathlib import Path
REPO_REGEX = re.compile(
r"""
# something like ... | --- +++ @@ -1,3 +1,4 @@+"""Cookiecutter repository functions."""
from __future__ import annotations
@@ -25,14 +26,21 @@
def is_repo_url(value: str) -> bool:
+ """Return True if value is a repository URL."""
return bool(REPO_REGEX.match(value))
def is_zip_file(value: str) -> bool:
+ """Return Tr... | https://raw.githubusercontent.com/cookiecutter/cookiecutter/HEAD/cookiecutter/repository.py |
Fill in missing docstrings in my code |
from __future__ import annotations
import logging
import os
from pathlib import Path
from typing import TYPE_CHECKING
from cookiecutter.exceptions import NonTemplatedInputDirException
if TYPE_CHECKING:
from jinja2 import Environment
logger = logging.getLogger(__name__)
def find_template(repo_dir: Path | str,... | --- +++ @@ -1,3 +1,4 @@+"""Functions for finding Cookiecutter templates and other components."""
from __future__ import annotations
@@ -15,6 +16,11 @@
def find_template(repo_dir: Path | str, env: Environment) -> Path:
+ """Determine which child directory of ``repo_dir`` is the project template.
+
+ :para... | https://raw.githubusercontent.com/cookiecutter/cookiecutter/HEAD/cookiecutter/find.py |
Provide docstrings following PEP 257 |
from __future__ import annotations
import collections
import copy
import logging
import os
from typing import TYPE_CHECKING, Any
import yaml
from cookiecutter.exceptions import ConfigDoesNotExistException, InvalidConfiguration
if TYPE_CHECKING:
from pathlib import Path
logger = logging.getLogger(__name__)
US... | --- +++ @@ -1,3 +1,4 @@+"""Global configuration handling."""
from __future__ import annotations
@@ -33,11 +34,17 @@
def _expand_path(path: str) -> str:
+ """Expand both environment variables and user home in the given path."""
path = os.path.expandvars(path)
return os.path.expanduser(path)
de... | https://raw.githubusercontent.com/cookiecutter/cookiecutter/HEAD/cookiecutter/config.py |
Add detailed documentation for each class |
from __future__ import annotations
import contextlib
import logging
import os
import shutil
import stat
import tempfile
from collections.abc import Iterator
from pathlib import Path
from typing import TYPE_CHECKING, Any
from jinja2.ext import Extension
from cookiecutter.environment import StrictEnvironment
if TYPE... | --- +++ @@ -1,3 +1,4 @@+"""Helper functions used throughout Cookiecutter."""
from __future__ import annotations
@@ -22,15 +23,28 @@
def force_delete(func, path, _exc_info) -> None: # type: ignore[no-untyped-def]
+ """Error handler for `shutil.rmtree()` equivalent to `rm -rf`.
+
+ Usage: `shutil.rmtree(p... | https://raw.githubusercontent.com/cookiecutter/cookiecutter/HEAD/cookiecutter/utils.py |
Write docstrings describing functionality |
from __future__ import annotations
import logging
import os
import sys
from copy import copy
from pathlib import Path
from typing import Any
from cookiecutter.config import get_user_config
from cookiecutter.exceptions import InvalidModeException
from cookiecutter.generate import generate_context, generate_files
from... | --- +++ @@ -1,3 +1,9 @@+"""
+Main entry point for the `cookiecutter` command.
+
+The code in this module is also a good example of how to use Cookiecutter as a
+library rather than a script.
+"""
from __future__ import annotations
@@ -36,6 +42,33 @@ accept_hooks: bool = True,
keep_project_on_failure: bool... | https://raw.githubusercontent.com/cookiecutter/cookiecutter/HEAD/cookiecutter/main.py |
Generate docstrings for exported functions |
import os
import json
import regex as re
from functools import lru_cache
@lru_cache()
def bytes_to_unicode():
bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
cs = bs[:]
n = 0
for b in range(2**8):
if b not in bs:
bs.append(... | --- +++ @@ -1,3 +1,4 @@+"""Byte pair encoding utilities"""
import os
import json
@@ -6,6 +7,15 @@
@lru_cache()
def bytes_to_unicode():
+ """
+ Returns list of utf-8 byte and a corresponding list of unicode strings.
+ The reversible bpe codes work on unicode strings.
+ This means you need a large # of... | https://raw.githubusercontent.com/openai/gpt-2/HEAD/src/encoder.py |
Provide docstrings following PEP 257 | import numpy as np
import tensorflow as tf
from tensorflow.contrib.training import HParams
def default_hparams():
return HParams(
n_vocab=0,
n_ctx=1024,
n_embd=768,
n_head=12,
n_layer=12,
)
def shape_list(x):
static = x.shape.as_list()
dynamic = tf.shape(x)
... | --- +++ @@ -12,6 +12,7 @@ )
def shape_list(x):
+ """Deal with dynamic shape in tensorflow cleanly."""
static = x.shape.as_list()
dynamic = tf.shape(x)
return [dynamic[i] if s is None else s for i, s in enumerate(static)]
@@ -25,6 +26,7 @@ return 0.5*x*(1+tf.tanh(np.sqrt(2/np.pi)*(x+0.044715... | https://raw.githubusercontent.com/openai/gpt-2/HEAD/src/model.py |
Help me add docstrings to my project |
from __future__ import annotations
import logging
import os
import subprocess
from pathlib import Path
from shutil import which
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Literal
from cookiecutter.exceptions import (
RepositoryCloneFailed,
RepositoryNotFound,
UnknownRepoTy... | --- +++ @@ -1,3 +1,4 @@+"""Helper functions for working with version control systems."""
from __future__ import annotations
@@ -30,6 +31,13 @@
def identify_repo(repo_url: str) -> tuple[Literal["git", "hg"], str]:
+ """Determine if `repo_url` should be treated as a URL to a git or hg repo.
+
+ Repos can b... | https://raw.githubusercontent.com/cookiecutter/cookiecutter/HEAD/cookiecutter/vcs.py |
Create simple docstrings for beginners | # Copyright (c) Facebook, Inc. and its affiliates.
import re
from tqdm import tqdm
class EvalAIAnswerProcessor:
CONTRACTIONS = {
"aint": "ain't",
"arent": "aren't",
"cant": "can't",
"couldve": "could've",
"couldnt": "couldn't",
"couldn'tve": "couldn't've",
... | --- +++ @@ -5,6 +5,11 @@
class EvalAIAnswerProcessor:
+ """
+ Processes an answer similar to Eval AI
+ copied from
+ https://github.com/facebookresearch/mmf/blob/c46b3b3391275b4181567db80943473a89ab98ab/pythia/tasks/processors.py#L897
+ """
CONTRACTIONS = {
"aint": "ain't",
@@... | https://raw.githubusercontent.com/haotian-liu/LLaVA/HEAD/llava/eval/m4c_evaluator.py |
Include argument descriptions in docstrings | from PIL import Image
from io import BytesIO
import base64
import torch
import math
import ast
from transformers import StoppingCriteria
from llava.constants import IMAGE_TOKEN_INDEX
def select_best_resolution(original_size, possible_resolutions):
original_width, original_height = original_size
best_fit = No... | --- +++ @@ -10,6 +10,16 @@
def select_best_resolution(original_size, possible_resolutions):
+ """
+ Selects the best resolution from a list of possible resolutions based on the original size.
+
+ Args:
+ original_size (tuple): The original size of the image in the format (width, height).
+ po... | https://raw.githubusercontent.com/haotian-liu/LLaVA/HEAD/llava/mm_utils.py |
Create documentation for each function signature | # — coding: utf-8 –
import openai
import json
import logging
import sys
import argparse
from langchain.chat_models import ChatOpenAI
from langchain.prompts import (
ChatPromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate
)
from langchain import LLMChain
import nu... | --- +++ @@ -1,716 +1,718 @@-# — coding: utf-8 –
-import openai
-import json
-import logging
-import sys
-import argparse
-from langchain.chat_models import ChatOpenAI
-from langchain.prompts import (
- ChatPromptTemplate,
- MessagesPlaceholder,
- SystemMessagePromptTemplate,
- HumanMessagePromptTemplate
-)
... | https://raw.githubusercontent.com/microsoft/JARVIS/HEAD/easytool/easytool/toolbench.py |
Write beginner-friendly docstrings | # Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright:
# Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright:
# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
#
# Licensed under the Apache License, Version 2.0 (the "License");
#... | --- +++ @@ -184,6 +184,7 @@
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer,
output_dir: str):
+ """Collects the state dict and dump to disk."""
if getattr(trainer.args, "tune_mm_mlp_adapter", False):
# Only save Adapter
@@ -225,6 +226,10 @@ ... | https://raw.githubusercontent.com/haotian-liu/LLaVA/HEAD/llava/train/train.py |
Generate missing documentation strings | import os
import torch
import torch.nn as nn
from torch.utils.data import Sampler
from transformers import Trainer
from transformers.trainer import (
is_sagemaker_mp_enabled,
get_parameter_names,
has_length,
ALL_LAYERNORM_LAYERS,
logger,
)
from typing import List, Optional
def maybe_zero_3(param... | --- +++ @@ -36,6 +36,9 @@
def split_to_even_chunks(indices, lengths, num_chunks):
+ """
+ Split a list of indices into `chunks` chunks of roughly equal lengths.
+ """
if len(indices) % num_chunks != 0:
return [indices[i::num_chunks] for i in range(num_chunks)]
@@ -94,6 +97,10 @@
class L... | https://raw.githubusercontent.com/haotian-liu/LLaVA/HEAD/llava/train/llava_trainer.py |
Add detailed documentation for each class | #!/usr/bin/env python3
import argparse
import os
import shutil
import subprocess
import sys
from urllib.parse import urlparse
from openai import OpenAI
from phone_agent.agent_ios import IOSAgentConfig, IOSPhoneAgent
from phone_agent.config.apps_ios import list_supported_apps
from phone_agent.model import ModelConfig... | --- +++ @@ -1,4 +1,17 @@ #!/usr/bin/env python3
+"""
+Phone Agent iOS CLI - AI-powered iOS phone automation.
+
+Usage:
+ python ios.py [OPTIONS]
+
+Environment Variables:
+ PHONE_AGENT_BASE_URL: Model API base URL (default: http://localhost:8000/v1)
+ PHONE_AGENT_MODEL: Model name (default: autoglm-phone-9b)
+... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/ios.py |
Add docstrings to clarify complex logic |
import ast
import re
import subprocess
import time
from dataclasses import dataclass
from typing import Any, Callable
from phone_agent.config.timing import TIMING_CONFIG
from phone_agent.device_factory import get_device_factory
@dataclass
class ActionResult:
success: bool
should_finish: bool
message: s... | --- +++ @@ -1,3 +1,4 @@+"""Action handler for processing AI model outputs."""
import ast
import re
@@ -12,6 +13,7 @@
@dataclass
class ActionResult:
+ """Result of an action execution."""
success: bool
should_finish: bool
@@ -20,6 +22,15 @@
class ActionHandler:
+ """
+ Handles execution o... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/actions/handler.py |
Create docstrings for API functions |
import os
import subprocess
import time
from typing import List, Optional, Tuple
from phone_agent.config.apps import APP_PACKAGES
from phone_agent.config.timing import TIMING_CONFIG
def get_current_app(device_id: str | None = None) -> str:
adb_prefix = _get_adb_prefix(device_id)
result = subprocess.run(
... | --- +++ @@ -1,3 +1,4 @@+"""Device control utilities for Android automation."""
import os
import subprocess
@@ -9,6 +10,15 @@
def get_current_app(device_id: str | None = None) -> str:
+ """
+ Get the currently focused app name.
+
+ Args:
+ device_id: Optional ADB device ID for multi-device setups... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/adb/device.py |
Create docstrings for API functions |
import time
from dataclasses import dataclass
from typing import Any, Callable
from phone_agent.xctest import (
back,
double_tap,
home,
launch_app,
long_press,
swipe,
tap,
)
from phone_agent.xctest.input import clear_text, hide_keyboard, type_text
@dataclass
class ActionResult:
succ... | --- +++ @@ -1,3 +1,4 @@+"""Action handler for iOS automation using WebDriverAgent."""
import time
from dataclasses import dataclass
@@ -17,6 +18,7 @@
@dataclass
class ActionResult:
+ """Result of an action execution."""
success: bool
should_finish: bool
@@ -25,6 +27,16 @@
class IOSActionHandle... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/actions/handler_ios.py |
Write docstrings for this repository |
import base64
import subprocess
from typing import Optional
def type_text(text: str, device_id: str | None = None) -> None:
adb_prefix = _get_adb_prefix(device_id)
encoded_text = base64.b64encode(text.encode("utf-8")).decode("utf-8")
subprocess.run(
adb_prefix
+ [
"shell",
... | --- +++ @@ -1,3 +1,4 @@+"""Input utilities for Android device text input."""
import base64
import subprocess
@@ -5,6 +6,17 @@
def type_text(text: str, device_id: str | None = None) -> None:
+ """
+ Type text into the currently focused input field using ADB Keyboard.
+
+ Args:
+ text: The text to... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/adb/input.py |
Write docstrings describing each step |
APP_PACKAGES: dict[str, str] = {
# Social & Messaging
"微信": "com.tencent.mm",
"QQ": "com.tencent.mobileqq",
"微博": "com.sina.weibo",
# E-commerce
"淘宝": "com.taobao.taobao",
"京东": "com.jingdong.app.mall",
"拼多多": "com.xunmeng.pinduoduo",
"淘宝闪购": "com.taobao.taobao",
"京东秒送": "com.ji... | --- +++ @@ -1,3 +1,4 @@+"""App name to package name mapping for supported applications."""
APP_PACKAGES: dict[str, str] = {
# Social & Messaging
@@ -188,10 +189,28 @@
def get_package_name(app_name: str) -> str | None:
+ """
+ Get the package name for an app.
+
+ Args:
+ app_name: The display... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/config/apps.py |
Add docstrings to existing functions |
import json
import traceback
from dataclasses import dataclass
from typing import Any, Callable
from phone_agent.actions import ActionHandler
from phone_agent.actions.handler import do, finish, parse_action
from phone_agent.config import get_messages, get_system_prompt
from phone_agent.device_factory import get_devic... | --- +++ @@ -1,3 +1,4 @@+"""Main PhoneAgent class for orchestrating phone automation."""
import json
import traceback
@@ -14,6 +15,7 @@
@dataclass
class AgentConfig:
+ """Configuration for the PhoneAgent."""
max_steps: int = 100
device_id: str | None = None
@@ -28,6 +30,7 @@
@dataclass
class Ste... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/agent.py |
Add docstrings to my Python code |
import json
import traceback
from dataclasses import dataclass
from typing import Any, Callable
from phone_agent.actions.handler import do, finish, parse_action
from phone_agent.actions.handler_ios import IOSActionHandler
from phone_agent.config import get_messages, get_system_prompt
from phone_agent.model import Mod... | --- +++ @@ -1,3 +1,4 @@+"""iOS PhoneAgent class for orchestrating iOS phone automation."""
import json
import traceback
@@ -14,6 +15,7 @@
@dataclass
class IOSAgentConfig:
+ """Configuration for the iOS PhoneAgent."""
max_steps: int = 100
wda_url: str = "http://localhost:8100"
@@ -30,6 +32,7 @@
@... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/agent_ios.py |
Replace inline comments with docstrings |
from phone_agent.config.apps import APP_PACKAGES
from phone_agent.config.apps_ios import APP_PACKAGES_IOS
from phone_agent.config.i18n import get_message, get_messages
from phone_agent.config.prompts_en import SYSTEM_PROMPT as SYSTEM_PROMPT_EN
from phone_agent.config.prompts_zh import SYSTEM_PROMPT as SYSTEM_PROMPT_ZH... | --- +++ @@ -1,3 +1,4 @@+"""Configuration module for Phone Agent."""
from phone_agent.config.apps import APP_PACKAGES
from phone_agent.config.apps_ios import APP_PACKAGES_IOS
@@ -16,6 +17,15 @@
def get_system_prompt(lang: str = "cn") -> str:
+ """
+ Get system prompt by language.
+
+ Args:
+ lang... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/config/__init__.py |
Document functions with clear intent |
APP_PACKAGES_IOS: dict[str, str] = {
# Tencent Apps (腾讯系)
"微信": "com.tencent.xin",
"企业微信": "com.tencent.ww",
"微信读书": "com.tencent.weread",
"微信听书": "com.tencent.wehear",
"QQ": "com.tencent.mqq",
"QQ音乐": "com.tencent.QQMusic",
"QQ阅读": "com.tencent.qqreaderiphone",
"QQ邮箱": "com.tencent... | --- +++ @@ -1,3 +1,8 @@+"""App name to iOS bundle ID mapping for supported applications.
+
+Based on iOS app bundle ID conventions and common iOS applications.
+Bundle IDs are in the format: com.company.appName
+"""
APP_PACKAGES_IOS: dict[str, str] = {
# Tencent Apps (腾讯系)
@@ -197,10 +202,28 @@
def get_bund... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/config/apps_ios.py |
Add well-formatted docstrings |
# Custom ability names for apps that don't use the default "EntryAbility"
# Maps bundle_name -> ability_name
# Generated by: python test/find_abilities.py
APP_ABILITIES: dict[str, str] = {
# Third-party apps
"cn.wps.mobileoffice.hap": "DocumentAbility",
"com.ccb.mobilebank.hm": "CcbMainAbility",
"com.d... | --- +++ @@ -1,3 +1,8 @@+"""HarmonyOS application package name mappings.
+
+Maps user-friendly app names to HarmonyOS bundle names.
+These bundle names are used with the 'hdc shell aa start -b <bundle>' command.
+"""
# Custom ability names for apps that don't use the default "EntryAbility"
# Maps bundle_name -> abil... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/config/apps_harmonyos.py |
Add docstrings including usage examples |
import base64
import os
import subprocess
import tempfile
import uuid
from dataclasses import dataclass
from io import BytesIO
from typing import Tuple
from PIL import Image
@dataclass
class Screenshot:
base64_data: str
width: int
height: int
is_sensitive: bool = False
def get_screenshot(device_i... | --- +++ @@ -1,3 +1,4 @@+"""Screenshot utilities for capturing Android device screen."""
import base64
import os
@@ -13,6 +14,7 @@
@dataclass
class Screenshot:
+ """Represents a captured screenshot."""
base64_data: str
width: int
@@ -21,6 +23,20 @@
def get_screenshot(device_id: str | None = Non... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/adb/screenshot.py |
Create simple docstrings for beginners | import torch
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
from llava.conversation import conv_templates, SeparatorStyle
from llava.model.builder import load_pretrained_model
from llava.utils import disable_torch_init
from llava.mm_utils import tokenizer_image_token
from transformers.generation.st... | --- +++ @@ -77,6 +77,7 @@
class Predictor(BasePredictor):
def setup(self) -> None:
+ """Load the model into memory to make running multiple predictions efficient"""
for weight in weights:
download_weights(weight["src"], weight["dest"], weight["files"])
disable_torch_init()
@... | https://raw.githubusercontent.com/haotian-liu/LLaVA/HEAD/predict.py |
Generate docstrings for exported functions |
import os
from dataclasses import dataclass
@dataclass
class ActionTimingConfig:
# Text input related delays (in seconds)
keyboard_switch_delay: float = 1.0 # Delay after switching to ADB keyboard
text_clear_delay: float = 1.0 # Delay after clearing text
text_input_delay: float = 1.0 # Delay afte... | --- +++ @@ -1,3 +1,8 @@+"""Timing configuration for Phone Agent.
+
+This module defines all configurable waiting times used throughout the application.
+Users can customize these values by modifying this file or by setting environment variables.
+"""
import os
from dataclasses import dataclass
@@ -5,6 +10,7 @@
@d... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/config/timing.py |
Add docstrings explaining edge cases | # — coding: utf-8 –
import json
import re
import os
def read_jsonline(address):
not_mark = []
with open(address, 'r', encoding="utf-8") as f:
for jsonstr in f.readlines():
jsonstr = json.loads(jsonstr)
not_mark.append(jsonstr)
return not_mark
def save_json(ls, address):
... | --- +++ @@ -1,107 +1,109 @@-# — coding: utf-8 –
-import json
-import re
-import os
-
-
-def read_jsonline(address):
- not_mark = []
- with open(address, 'r', encoding="utf-8") as f:
- for jsonstr in f.readlines():
- jsonstr = json.loads(jsonstr)
- not_mark.append(jsonstr)
- return ... | https://raw.githubusercontent.com/microsoft/JARVIS/HEAD/easytool/easytool/util.py |
Add well-formatted docstrings |
import os
import subprocess
import time
from typing import List, Optional, Tuple
from phone_agent.config.apps_harmonyos import APP_ABILITIES, APP_PACKAGES
from phone_agent.config.timing import TIMING_CONFIG
from phone_agent.hdc.connection import _run_hdc_command
import re
def get_current_app(device_id: str | None = ... | --- +++ @@ -1,3 +1,4 @@+"""Device control utilities for HarmonyOS automation."""
import os
import subprocess
@@ -10,6 +11,15 @@ import re
def get_current_app(device_id: str | None = None) -> str:
+ """
+ Get the currently focused app name.
+
+ Args:
+ device_id: Optional HDC device ID for multi-d... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/hdc/device.py |
Help me add docstrings to my project |
# Chinese messages
MESSAGES_ZH = {
"thinking": "思考过程",
"action": "执行动作",
"task_completed": "任务完成",
"done": "完成",
"starting_task": "开始执行任务",
"final_result": "最终结果",
"task_result": "任务结果",
"confirmation_required": "需要确认",
"continue_prompt": "是否继续?(y/n)",
"manual_operation_required... | --- +++ @@ -1,3 +1,4 @@+"""Internationalization (i18n) module for Phone Agent UI messages."""
# Chinese messages
MESSAGES_ZH = {
@@ -51,11 +52,30 @@
def get_messages(lang: str = "cn") -> dict:
+ """
+ Get UI messages dictionary by language.
+
+ Args:
+ lang: Language code, 'cn' for Chinese, 'en'... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/config/i18n.py |
Create simple docstrings for beginners |
import os
import subprocess
import time
from dataclasses import dataclass
from enum import Enum
from typing import Optional
from phone_agent.config.timing import TIMING_CONFIG
# Global flag to control HDC command output
_HDC_VERBOSE = os.getenv("HDC_VERBOSE", "false").lower() in ("true", "1", "yes")
def _run_hdc_... | --- +++ @@ -1,3 +1,4 @@+"""HDC connection management for HarmonyOS devices."""
import os
import subprocess
@@ -14,6 +15,16 @@
def _run_hdc_command(cmd: list, **kwargs) -> subprocess.CompletedProcess:
+ """
+ Run HDC command with optional verbose output.
+
+ Args:
+ cmd: Command list to execute.
... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/hdc/connection.py |
Add docstrings that explain inputs and outputs |
import base64
import subprocess
from typing import Optional
from phone_agent.hdc.connection import _run_hdc_command
def type_text(text: str, device_id: str | None = None) -> None:
hdc_prefix = _get_hdc_prefix(device_id)
# Handle multi-line text by splitting on newlines
if '\n' in text:
lines = ... | --- +++ @@ -1,3 +1,4 @@+"""Input utilities for HarmonyOS device text input."""
import base64
import subprocess
@@ -7,6 +8,20 @@
def type_text(text: str, device_id: str | None = None) -> None:
+ """
+ Type text into the currently focused input field.
+
+ Args:
+ text: The text to type. Supports m... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/hdc/input.py |
Replace inline comments with docstrings | import datetime
import logging
import logging.handlers
import os
import sys
import requests
from llava.constants import LOGDIR
server_error_msg = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**"
moderation_msg = "YOUR INPUT VIOLATES OUR CONTENT MODERATION GUIDELINES. PLEASE TRY AGAIN.... | --- +++ @@ -58,6 +58,9 @@
class StreamToLogger(object):
+ """
+ Fake file-like stream object that redirects writes to a logger instance.
+ """
def __init__(self, logger, log_level=logging.INFO):
self.terminal = sys.stdout
self.logger = logger
@@ -88,12 +91,18 @@
def disable_torch... | https://raw.githubusercontent.com/haotian-liu/LLaVA/HEAD/llava/utils.py |
Add standardized docstrings across the file |
import json
import time
from dataclasses import dataclass, field
from typing import Any
from openai import OpenAI
from phone_agent.config.i18n import get_message
@dataclass
class ModelConfig:
base_url: str = "http://localhost:8000/v1"
api_key: str = "EMPTY"
model_name: str = "autoglm-phone-9b"
max... | --- +++ @@ -1,3 +1,4 @@+"""Model client for AI inference using OpenAI-compatible API."""
import json
import time
@@ -11,6 +12,7 @@
@dataclass
class ModelConfig:
+ """Configuration for the AI model."""
base_url: str = "http://localhost:8000/v1"
api_key: str = "EMPTY"
@@ -25,6 +27,7 @@
@dataclass
... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/model/client.py |
Add docstrings to improve readability |
from enum import Enum
from typing import Any
class DeviceType(Enum):
ADB = "adb"
HDC = "hdc"
IOS = "ios"
class DeviceFactory:
def __init__(self, device_type: DeviceType = DeviceType.ADB):
self.device_type = device_type
self._module = None
@property
def module(self):
... | --- +++ @@ -1,9 +1,11 @@+"""Device factory for selecting ADB or HDC based on device type."""
from enum import Enum
from typing import Any
class DeviceType(Enum):
+ """Type of device connection tool."""
ADB = "adb"
HDC = "hdc"
@@ -11,13 +13,25 @@
class DeviceFactory:
+ """
+ Factory cla... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/device_factory.py |
Add docstrings that explain logic |
import subprocess
import time
from dataclasses import dataclass
from enum import Enum
from typing import Optional
from phone_agent.config.timing import TIMING_CONFIG
class ConnectionType(Enum):
USB = "usb"
WIFI = "wifi"
REMOTE = "remote"
@dataclass
class DeviceInfo:
device_id: str
status: st... | --- +++ @@ -1,3 +1,4 @@+"""ADB connection management for local and remote devices."""
import subprocess
import time
@@ -9,6 +10,7 @@
class ConnectionType(Enum):
+ """Type of ADB connection."""
USB = "usb"
WIFI = "wifi"
@@ -17,6 +19,7 @@
@dataclass
class DeviceInfo:
+ """Information about a ... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/adb/connection.py |
Help me comply with documentation standards | # — coding: utf-8 –
import openai
import json
import logging
import sys
import argparse
from langchain.chat_models import ChatOpenAI
from langchain.prompts import (
ChatPromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate
)
from langchain import LLMChain
import nu... | --- +++ @@ -1,734 +1,736 @@-# — coding: utf-8 –
-import openai
-import json
-import logging
-import sys
-import argparse
-from langchain.chat_models import ChatOpenAI
-from langchain.prompts import (
- ChatPromptTemplate,
- MessagesPlaceholder,
- SystemMessagePromptTemplate,
- HumanMessagePromptTemplate
-)
... | https://raw.githubusercontent.com/microsoft/JARVIS/HEAD/easytool/easytool/toolbench_retrieve.py |
Add professional docstrings to my codebase | # — coding: utf-8 –
import openai
import json
import logging
import sys
import argparse
import ast
from langchain.chat_models import ChatOpenAI
from langchain.prompts import (
ChatPromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate
)
from langchain import LLMChai... | --- +++ @@ -1,109 +1,111 @@-# — coding: utf-8 –
-import openai
-import json
-import logging
-import sys
-import argparse
-import ast
-from langchain.chat_models import ChatOpenAI
-from langchain.prompts import (
- ChatPromptTemplate,
- MessagesPlaceholder,
- SystemMessagePromptTemplate,
- HumanMessagePrompt... | https://raw.githubusercontent.com/microsoft/JARVIS/HEAD/easytool/easytool/restbench.py |
Generate docstrings for each module |
import base64
import os
import subprocess
import tempfile
import uuid
from dataclasses import dataclass
from io import BytesIO
from typing import Tuple
from PIL import Image
from phone_agent.hdc.connection import _run_hdc_command
@dataclass
class Screenshot:
base64_data: str
width: int
height: int
... | --- +++ @@ -1,3 +1,4 @@+"""Screenshot utilities for capturing HarmonyOS device screen."""
import base64
import os
@@ -14,6 +15,7 @@
@dataclass
class Screenshot:
+ """Represents a captured screenshot."""
base64_data: str
width: int
@@ -22,6 +24,20 @@
def get_screenshot(device_id: str | None = N... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/phone_agent/hdc/screenshot.py |
Write docstrings that follow conventions | # — coding: utf-8 –
import openai
import json
import logging
import sys
import argparse
from langchain.chat_models import ChatOpenAI
from langchain.prompts import (
ChatPromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate
)
from langchain import LLMChain
import nu... | --- +++ @@ -1,672 +1,675 @@-# — coding: utf-8 –
-import openai
-import json
-import logging
-import sys
-import argparse
-from langchain.chat_models import ChatOpenAI
-from langchain.prompts import (
- ChatPromptTemplate,
- MessagesPlaceholder,
- SystemMessagePromptTemplate,
- HumanMessagePromptTemplate
-)
... | https://raw.githubusercontent.com/microsoft/JARVIS/HEAD/easytool/easytool/funcQA.py |
Generate docstrings for script automation | #!/usr/bin/env python3
import argparse
import os
import shutil
import subprocess
import sys
from urllib.parse import urlparse
from openai import OpenAI
from phone_agent import PhoneAgent
from phone_agent.agent import AgentConfig
from phone_agent.agent_ios import IOSAgentConfig, IOSPhoneAgent
from phone_agent.config.... | --- +++ @@ -1,4 +1,17 @@ #!/usr/bin/env python3
+"""
+Phone Agent CLI - AI-powered phone automation.
+
+Usage:
+ python main.py [OPTIONS]
+
+Environment Variables:
+ PHONE_AGENT_BASE_URL: Model API base URL (default: http://localhost:8000/v1)
+ PHONE_AGENT_MODEL: Model name (default: autoglm-phone-9b)
+ PHO... | https://raw.githubusercontent.com/zai-org/Open-AutoGLM/HEAD/main.py |
Add detailed documentation for each class |
import os
import sys
import json
import torch
from torch.utils.data import Dataset
from torch.utils.data.dataloader import DataLoader
from mingpt.model import GPT
from mingpt.trainer import Trainer
from mingpt.utils import set_seed, setup_logging, CfgNode as CN
# ----------------------------------------------------... | --- +++ @@ -1,3 +1,6 @@+"""
+Trains a GPT to add n-digit numbers.
+"""
import os
import sys
@@ -38,6 +41,29 @@ # -----------------------------------------------------------------------------
class AdditionDataset(Dataset):
+ """
+ Creates n-digit addition problems. For example, if n=2, then an example
+ ... | https://raw.githubusercontent.com/karpathy/minGPT/HEAD/projects/adder/adder.py |
Add concise docstrings to each method |
import math
import torch
import torch.nn as nn
from torch.nn import functional as F
from mingpt.utils import CfgNode as CN
# -----------------------------------------------------------------------------
class NewGELU(nn.Module):
def forward(self, x):
return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / m... | --- +++ @@ -1,3 +1,12 @@+"""
+Full definition of a GPT Language Model, all of it in this single file.
+
+References:
+1) the official GPT-2 TensorFlow implementation released by OpenAI:
+https://github.com/openai/gpt-2/blob/master/src/model.py
+2) huggingface/transformers PyTorch implementation:
+https://github.com/hug... | https://raw.githubusercontent.com/karpathy/minGPT/HEAD/mingpt/model.py |
Generate descriptive docstrings automatically |
import os
import sys
import json
import random
from ast import literal_eval
import numpy as np
import torch
# -----------------------------------------------------------------------------
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(se... | --- +++ @@ -17,6 +17,7 @@ torch.cuda.manual_seed_all(seed)
def setup_logging(config):
+ """ monotonous bookkeeping """
work_dir = config.system.work_dir
# create the work directory if it doesn't already exist
os.makedirs(work_dir, exist_ok=True)
@@ -28,6 +29,7 @@ f.write(json.dumps(conf... | https://raw.githubusercontent.com/karpathy/minGPT/HEAD/mingpt/utils.py |
Document functions with clear intent |
import os
import json
import regex as re
import requests
import torch
# -----------------------------------------------------------------------------
def bytes_to_unicode():
# the 188 integers that render fine in their original form and need no shifting
bs = list(range(ord("!"), ord("~")+1))+list(range(ord(... | --- +++ @@ -1,3 +1,12 @@+"""
+bpe is short for Byte Pair Encoder. It translates arbitrary utf-8 strings into
+sequences of integers, where each integer represents small chunks of commonly
+occuring characters. This implementation is based on openai's gpt2 encoder.py:
+https://github.com/openai/gpt-2/blob/master/src/enc... | https://raw.githubusercontent.com/karpathy/minGPT/HEAD/mingpt/bpe.py |
Write beginner-friendly docstrings |
import logging
from typing import Any
from graphiti_core.driver.driver import GraphProvider
from graphiti_core.driver.falkordb import STOPWORDS
from graphiti_core.driver.operations.search_ops import SearchOperations
from graphiti_core.driver.query_executor import QueryExecutor
from graphiti_core.driver.record_parsers... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/driver/falkordb/operations/search_ops.py |
Document functions with detailed explanations |
import logging
import re
from typing import TYPE_CHECKING
from ..helpers import semaphore_gather
from ..llm_client import LLMConfig, RateLimitError
from .client import CrossEncoderClient
if TYPE_CHECKING:
from google import genai
from google.genai import types
else:
try:
from google import genai
... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/cross_encoder/gemini_reranker_client.py |
Add documentation for all methods |
from typing import Any
from graphiti_core.edges import EntityEdge
from graphiti_core.helpers import parse_db_date
from graphiti_core.nodes import CommunityNode, EntityNode, EpisodeType, EpisodicNode
def entity_node_from_record(record: Any) -> EntityNode:
attributes = record['attributes']
attributes.pop('uui... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/driver/record_parsers.py |
Help me add docstrings to my project |
import functools
import inspect
from collections.abc import Awaitable, Callable
from typing import Any, TypeVar
from graphiti_core.driver.driver import GraphProvider
from graphiti_core.helpers import semaphore_gather
from graphiti_core.search.search_config import SearchResults
F = TypeVar('F', bound=Callable[..., Aw... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/decorators.py |
Add docstrings for production code |
import logging
from typing import Any
import numpy as np
import openai
from openai import AsyncAzureOpenAI, AsyncOpenAI
from ..helpers import semaphore_gather
from ..llm_client import LLMConfig, OpenAIClient, RateLimitError
from ..prompts import Message
from .client import CrossEncoderClient
logger = logging.getLog... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/cross_encoder/openai_reranker_client.py |
Provide clean and structured docstrings |
from __future__ import annotations
import copy
import logging
import os
from abc import ABC, abstractmethod
from collections.abc import AsyncIterator, Coroutine
from contextlib import asynccontextmanager
from enum import Enum
from typing import TYPE_CHECKING, Any
from dotenv import load_dotenv
from graphiti_core.dr... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/driver/driver.py |
Document this code for team use |
import logging
from collections.abc import AsyncIterator, Coroutine
from contextlib import asynccontextmanager
from typing import Any
from neo4j import AsyncGraphDatabase, EagerResult
from neo4j.exceptions import ClientError
from typing_extensions import LiteralString
from graphiti_core.driver.driver import GraphDri... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/driver/neo4j_driver.py |
Fully document this Python code with docstrings |
import logging
from typing import Any
from graphiti_core.driver.driver import GraphProvider
from graphiti_core.driver.kuzu.operations.record_parsers import (
parse_kuzu_entity_edge,
parse_kuzu_entity_node,
)
from graphiti_core.driver.operations.search_ops import SearchOperations
from graphiti_core.driver.quer... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/driver/kuzu/operations/search_ops.py |
Document all endpoints with docstrings |
import logging
from datetime import datetime
from time import time
from uuid import uuid4
from dotenv import load_dotenv
from pydantic import BaseModel
from typing_extensions import LiteralString
from graphiti_core.cross_encoder.client import CrossEncoderClient
from graphiti_core.cross_encoder.openai_reranker_client... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/graphiti.py |
Insert docstrings into my code |
import json
from typing import Any
from graphiti_core.driver.record_parsers import entity_edge_from_record, entity_node_from_record
from graphiti_core.edges import EntityEdge
from graphiti_core.nodes import EntityNode
def parse_kuzu_entity_node(record: Any) -> EntityNode:
if isinstance(record.get('attributes'),... | --- +++ @@ -1,3 +1,18 @@+"""
+Copyright 2024, Zep Software, Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicabl... | https://raw.githubusercontent.com/getzep/graphiti/HEAD/graphiti_core/driver/kuzu/operations/record_parsers.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.