instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Write docstrings that follow conventions | import torch
import math
import tqdm
class NoiseScheduleVP:
def __init__(
self,
schedule='discrete',
betas=None,
alphas_cumprod=None,
continuous_beta_0=0.1,
continuous_beta_1=20.,
):
if schedule not in ['discrete', 'linear', ... | --- +++ @@ -12,6 +12,85 @@ continuous_beta_0=0.1,
continuous_beta_1=20.,
):
+ """Create a wrapper class for the forward SDE (VP type).
+
+ ***
+ Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t.
+ ... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/models/diffusion/uni_pc/uni_pc.py |
Create documentation strings for testing functions | from __future__ import annotations
import dataclasses
import inspect
import os
from typing import Optional, Any
from fastapi import FastAPI
from gradio import Blocks
from modules import errors, timer, extensions, shared, util
def report_exception(c, job):
errors.report(f"Error executing callback {job} for {c.s... | --- +++ @@ -1,542 +1,613 @@-from __future__ import annotations
-
-import dataclasses
-import inspect
-import os
-from typing import Optional, Any
-
-from fastapi import FastAPI
-from gradio import Blocks
-
-from modules import errors, timer, extensions, shared, util
-
-
-def report_exception(c, job):
- errors.report... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/script_callbacks.py |
Help me write clear docstrings | from __future__ import annotations
import json
import logging
import math
import os
import sys
import hashlib
from dataclasses import dataclass, field
import torch
import numpy as np
from PIL import Image, ImageOps
import random
import cv2
from skimage import exposure
from typing import Any
import modules.sd_hijack
f... | --- +++ @@ -1,1733 +1,1792 @@-from __future__ import annotations
-import json
-import logging
-import math
-import os
-import sys
-import hashlib
-from dataclasses import dataclass, field
-
-import torch
-import numpy as np
-from PIL import Image, ImageOps
-import random
-import cv2
-from skimage import exposure
-from ... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/processing.py |
Document classes and their methods | import math
from collections import namedtuple
import torch
from modules import prompt_parser, devices, sd_hijack, sd_emphasis
from modules.shared import opts
class PromptChunk:
def __init__(self):
self.tokens = []
self.multipliers = []
self.fixes = []
PromptChunkFix = namedtuple('Pro... | --- +++ @@ -1,336 +1,384 @@-import math
-from collections import namedtuple
-
-import torch
-
-from modules import prompt_parser, devices, sd_hijack, sd_emphasis
-from modules.shared import opts
-
-
-class PromptChunk:
-
- def __init__(self):
- self.tokens = []
- self.multipliers = []
- self.fix... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_hijack_clip.py |
Add docstrings that explain purpose and usage | import ldm.modules.encoders.modules
import open_clip
import torch
import transformers.utils.hub
from modules import shared
class ReplaceHelper:
def __init__(self):
self.replaced = []
def replace(self, obj, field, func):
original = getattr(obj, field, None)
if original is None:
... | --- +++ @@ -1,186 +1,232 @@-import ldm.modules.encoders.modules
-import open_clip
-import torch
-import transformers.utils.hub
-
-from modules import shared
-
-
-class ReplaceHelper:
- def __init__(self):
- self.replaced = []
-
- def replace(self, obj, field, func):
- original = getattr(obj, field, ... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_disable_initialization.py |
Create Google-style docstrings for my code | import os
import json
import sys
from dataclasses import dataclass
import gradio as gr
from modules import errors
from modules.shared_cmd_options import cmd_opts
from modules.paths_internal import script_path
class OptionInfo:
def __init__(self, default=None, label="", component=None, component_args=None, oncha... | --- +++ @@ -1,321 +1,336 @@-import os
-import json
-import sys
-from dataclasses import dataclass
-
-import gradio as gr
-
-from modules import errors
-from modules.shared_cmd_options import cmd_opts
-from modules.paths_internal import script_path
-
-
-class OptionInfo:
- def __init__(self, default=None, label="", c... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/options.py |
Generate docstrings for each module | import torch
from torch.nn.functional import silu
from types import MethodType
from modules import devices, sd_hijack_optimizations, shared, script_callbacks, errors, sd_unet, patches
from modules.hypernetworks import hypernetwork
from modules.shared import cmd_opts
from modules import sd_hijack_clip, sd_hijack_open_c... | --- +++ @@ -1,403 +1,409 @@-import torch
-from torch.nn.functional import silu
-from types import MethodType
-
-from modules import devices, sd_hijack_optimizations, shared, script_callbacks, errors, sd_unet, patches
-from modules.hypernetworks import hypernetwork
-from modules.shared import cmd_opts
-from modules impo... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_hijack.py |
Add docstrings to improve readability | import torch
from packaging import version
from einops import repeat
import math
from modules import devices
from modules.sd_hijack_utils import CondFunc
class TorchHijackForUnet:
def __getattr__(self, item):
if item == 'cat':
return self.cat
if hasattr(torch, item):
ret... | --- +++ @@ -1,141 +1,154 @@-import torch
-from packaging import version
-from einops import repeat
-import math
-
-from modules import devices
-from modules.sd_hijack_utils import CondFunc
-
-
-class TorchHijackForUnet:
-
- def __getattr__(self, item):
- if item == 'cat':
- return self.cat
-
- ... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_hijack_unet.py |
Write docstrings for this repository | import collections
import importlib
import os
import sys
import threading
import enum
import torch
import re
import safetensors.torch
from omegaconf import OmegaConf, ListConfig
from urllib import request
import ldm.modules.midas as midas
from modules import paths, shared, modelloader, devices, script_callbacks, sd_v... | --- +++ @@ -1,1006 +1,1034 @@-import collections
-import importlib
-import os
-import sys
-import threading
-import enum
-
-import torch
-import re
-import safetensors.torch
-from omegaconf import OmegaConf, ListConfig
-from urllib import request
-import ldm.modules.midas as midas
-
-from modules import paths, shared, ... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_models.py |
Generate docstrings with parameter types | import dataclasses
import os
import gradio as gr
from modules import errors, shared
@dataclasses.dataclass
class PostprocessedImageSharedInfo:
target_width: int = None
target_height: int = None
class PostprocessedImage:
def __init__(self, image):
self.image = image
self.info = {}
... | --- +++ @@ -1,215 +1,230 @@-import dataclasses
-import os
-import gradio as gr
-
-from modules import errors, shared
-
-
-@dataclasses.dataclass
-class PostprocessedImageSharedInfo:
- target_width: int = None
- target_height: int = None
-
-
-class PostprocessedImage:
- def __init__(self, image):
- self.... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/scripts_postprocessing.py |
Add docstrings following best practices | from collections import defaultdict
def patch(key, obj, field, replacement):
patch_key = (obj, field)
if patch_key in originals[key]:
raise RuntimeError(f"patch for {field} is already applied")
original_func = getattr(obj, field)
originals[key][patch_key] = original_func
setattr(obj, fi... | --- +++ @@ -1,37 +1,64 @@-from collections import defaultdict
-
-
-def patch(key, obj, field, replacement):
-
- patch_key = (obj, field)
- if patch_key in originals[key]:
- raise RuntimeError(f"patch for {field} is already applied")
-
- original_func = getattr(obj, field)
- originals[key][patch_key] ... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/patches.py |
Generate docstrings for each module | from __future__ import annotations
import torch
class Emphasis:
name: str = "Base"
description: str = ""
tokens: list[list[int]]
"""tokens from the chunk of the prompt"""
multipliers: torch.Tensor
"""tensor with multipliers, once for each token"""
z: torch.Tensor
"""output of cond ... | --- +++ @@ -1,68 +1,70 @@-from __future__ import annotations
-import torch
-
-
-class Emphasis:
-
- name: str = "Base"
- description: str = ""
-
- tokens: list[list[int]]
- """tokens from the chunk of the prompt"""
-
- multipliers: torch.Tensor
- """tensor with multipliers, once for each token"""
-
- ... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_emphasis.py |
Create docstrings for all classes and functions | from __future__ import annotations
import re
from collections import namedtuple
import lark
# a prompt like this: "fantasy landscape with a [mountain:lake:0.25] and [an oak:a christmas tree:0.75][ in foreground::0.6][: in background:0.25] [shoddy:masterful:0.5]"
# will be represented with prompt_schedule like this (a... | --- +++ @@ -1,368 +1,464 @@-from __future__ import annotations
-
-import re
-from collections import namedtuple
-import lark
-
-# a prompt like this: "fantasy landscape with a [mountain:lake:0.25] and [an oak:a christmas tree:0.75][ in foreground::0.6][: in background:0.25] [shoddy:masterful:0.5]"
-# will be represente... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/prompt_parser.py |
Add docstrings for utility scripts |
import numpy as np
philox_m = [0xD2511F53, 0xCD9E8D57]
philox_w = [0x9E3779B9, 0xBB67AE85]
two_pow32_inv = np.array([2.3283064e-10], dtype=np.float32)
two_pow32_inv_2pi = np.array([2.3283064e-10 * 6.2831855], dtype=np.float32)
def uint32(x):
return x.view(np.uint32).reshape(-1, 2).transpose(1, 0)
def philox4... | --- +++ @@ -1,71 +1,102 @@-
-import numpy as np
-
-philox_m = [0xD2511F53, 0xCD9E8D57]
-philox_w = [0x9E3779B9, 0xBB67AE85]
-
-two_pow32_inv = np.array([2.3283064e-10], dtype=np.float32)
-two_pow32_inv_2pi = np.array([2.3283064e-10 * 6.2831855], dtype=np.float32)
-
-
-def uint32(x):
- return x.view(np.uint32).reshap... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/rng_philox.py |
Write docstrings for utility functions | from __future__ import annotations
import torch
import sgm.models.diffusion
import sgm.modules.diffusionmodules.denoiser_scaling
import sgm.modules.diffusionmodules.discretizer
from modules import devices, shared, prompt_parser
from modules import torch_utils
def get_learned_conditioning(self: sgm.models.diffusion.... | --- +++ @@ -1,111 +1,114 @@-from __future__ import annotations
-
-import torch
-
-import sgm.models.diffusion
-import sgm.modules.diffusionmodules.denoiser_scaling
-import sgm.modules.diffusionmodules.discretizer
-from modules import devices, shared, prompt_parser
-from modules import torch_utils
-
-
-def get_learned_c... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_models_xl.py |
Add docstrings to improve readability | import torch
from modules import prompt_parser, sd_samplers_common
from modules.shared import opts, state
import modules.shared as shared
from modules.script_callbacks import CFGDenoiserParams, cfg_denoiser_callback
from modules.script_callbacks import CFGDenoisedParams, cfg_denoised_callback
from modules.script_callb... | --- +++ @@ -1,283 +1,312 @@-import torch
-from modules import prompt_parser, sd_samplers_common
-
-from modules.shared import opts, state
-import modules.shared as shared
-from modules.script_callbacks import CFGDenoiserParams, cfg_denoiser_callback
-from modules.script_callbacks import CFGDenoisedParams, cfg_denoised_... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_samplers_cfg_denoiser.py |
Auto-generate documentation strings for this file | from __future__ import annotations
from pathlib import Path
from modules import errors
import csv
import os
import typing
import shutil
class PromptStyle(typing.NamedTuple):
name: str
prompt: str | None
negative_prompt: str | None
path: str | None = None
def merge_prompts(style_prompt: str, prompt: ... | --- +++ @@ -1,218 +1,234 @@-from __future__ import annotations
-from pathlib import Path
-from modules import errors
-import csv
-import os
-import typing
-import shutil
-
-
-class PromptStyle(typing.NamedTuple):
- name: str
- prompt: str | None
- negative_prompt: str | None
- path: str | None = None
-
-
-d... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/styles.py |
Add detailed documentation for each class | import datetime
import logging
import threading
import time
from modules import errors, shared, devices
from typing import Optional
log = logging.getLogger(__name__)
class State:
skipped = False
interrupted = False
stopping_generation = False
job = ""
job_no = 0
job_count = 0
processing_... | --- +++ @@ -1,161 +1,168 @@-import datetime
-import logging
-import threading
-import time
-
-from modules import errors, shared, devices
-from typing import Optional
-
-log = logging.getLogger(__name__)
-
-
-class State:
- skipped = False
- interrupted = False
- stopping_generation = False
- job = ""
- ... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/shared_state.py |
Add docstrings explaining edge cases | import os
import re
import sys
import inspect
from collections import namedtuple
from dataclasses import dataclass
import gradio as gr
from modules import shared, paths, script_callbacks, extensions, script_loading, scripts_postprocessing, errors, timer, util
topological_sort = util.topological_sort
AlwaysVisible =... | --- +++ @@ -1,880 +1,1040 @@-import os
-import re
-import sys
-import inspect
-from collections import namedtuple
-from dataclasses import dataclass
-
-import gradio as gr
-
-from modules import shared, paths, script_callbacks, extensions, script_loading, scripts_postprocessing, errors, timer, util
-
-topological_sort ... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/scripts.py |
Add return value explanations in docstrings | # this code is adapted from the script contributed by anon from /h/
import pickle
import collections
import torch
import numpy
import _codecs
import zipfile
import re
# PyTorch 1.13 and later have _TypedStorage renamed to TypedStorage
from modules import errors
TypedStorage = torch.storage.TypedStorage if hasattr(... | --- +++ @@ -1,158 +1,196 @@-# this code is adapted from the script contributed by anon from /h/
-
-import pickle
-import collections
-
-import torch
-import numpy
-import _codecs
-import zipfile
-import re
-
-
-# PyTorch 1.13 and later have _TypedStorage renamed to TypedStorage
-from modules import errors
-
-TypedStora... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/safe.py |
Add verbose docstrings with examples | from __future__ import annotations
import torch.nn
import torch
def get_param(model) -> torch.nn.Parameter:
if hasattr(model, "model") and hasattr(model.model, "parameters"):
# Unpeel a model descriptor to get at the actual Torch module.
model = model.model
for param in model.parameters():
... | --- +++ @@ -5,6 +5,9 @@
def get_param(model) -> torch.nn.Parameter:
+ """
+ Find the first parameter in a model or module.
+ """
if hasattr(model, "model") and hasattr(model.model, "parameters"):
# Unpeel a model descriptor to get at the actual Torch module.
model = model.model
@@ -1... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/torch_utils.py |
Add docstrings that explain logic | import dataclasses
import torch
import k_diffusion
import numpy as np
from scipy import stats
from modules import shared
def to_d(x, sigma, denoised):
return (x - denoised) / sigma
k_diffusion.sampling.to_d = to_d
@dataclasses.dataclass
class Scheduler:
name: str
label: str
function: any
def... | --- +++ @@ -8,6 +8,7 @@
def to_d(x, sigma, denoised):
+ """Converts a denoiser output to a Karras ODE derivative."""
return (x - denoised) / sigma
@@ -43,6 +44,9 @@ def get_align_your_steps_sigmas(n, sigma_min, sigma_max, device):
# https://research.nvidia.com/labs/toronto-ai/AlignYourSteps/howto.h... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_schedulers.py |
Create Google-style docstrings for my code | import os
from pathlib import Path
from modules.paths_internal import script_path
def is_restartable() -> bool:
return bool(os.environ.get('SD_WEBUI_RESTART'))
def restart_program() -> None:
tmpdir = Path(script_path) / "tmp"
tmpdir.mkdir(parents=True, exist_ok=True)
(tmpdir / "restart").touch()
... | --- +++ @@ -5,10 +5,14 @@
def is_restartable() -> bool:
+ """
+ Return True if the webui is restartable (i.e. there is something watching to restart it with)
+ """
return bool(os.environ.get('SD_WEBUI_RESTART'))
def restart_program() -> None:
+ """creates file tmp/restart and immediately stops... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/restart.py |
Can you add docstrings to this Python file? | import functools
import os.path
import urllib.parse
from base64 import b64decode
from io import BytesIO
from pathlib import Path
from typing import Optional, Union
from dataclasses import dataclass
from modules import shared, ui_extra_networks_user_metadata, errors, extra_networks, util
from modules.images import read... | --- +++ @@ -1,721 +1,838 @@-import functools
-import os.path
-import urllib.parse
-from base64 import b64decode
-from io import BytesIO
-from pathlib import Path
-from typing import Optional, Union
-from dataclasses import dataclass
-
-from modules import shared, ui_extra_networks_user_metadata, errors, extra_networks,... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/ui_extra_networks.py |
Generate docstrings with parameter types | import gradio as gr
class FormComponent:
def get_expected_parent(self):
return gr.components.Form
gr.Dropdown.get_expected_parent = FormComponent.get_expected_parent
class ToolButton(FormComponent, gr.Button):
def __init__(self, *args, **kwargs):
classes = kwargs.pop("elem_classes", [])
... | --- +++ @@ -1,119 +1,145 @@-import gradio as gr
-
-
-class FormComponent:
- def get_expected_parent(self):
- return gr.components.Form
-
-
-gr.Dropdown.get_expected_parent = FormComponent.get_expected_parent
-
-
-class ToolButton(FormComponent, gr.Button):
-
- def __init__(self, *args, **kwargs):
- ... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/ui_components.py |
Generate consistent docstrings | import inspect
from collections import namedtuple
import numpy as np
import torch
from PIL import Image
from modules import devices, images, sd_vae_approx, sd_samplers, sd_vae_taesd, shared, sd_models
from modules.shared import opts, state
import k_diffusion.sampling
SamplerDataTuple = namedtuple('SamplerData', ['nam... | --- +++ @@ -1,345 +1,355 @@-import inspect
-from collections import namedtuple
-import numpy as np
-import torch
-from PIL import Image
-from modules import devices, images, sd_vae_approx, sd_samplers, sd_vae_taesd, shared, sd_models
-from modules.shared import opts, state
-import k_diffusion.sampling
-
-
-SamplerDataT... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_samplers_common.py |
Add docstrings that explain logic | import csv
import dataclasses
import json
import html
import os
from contextlib import nullcontext
import gradio as gr
from modules import call_queue, shared, ui_tempdir, util
from modules.infotext_utils import image_from_url_text
import modules.images
from modules.ui_components import ToolButton
import modules.infot... | --- +++ @@ -1,322 +1,325 @@-import csv
-import dataclasses
-import json
-import html
-import os
-from contextlib import nullcontext
-
-import gradio as gr
-
-from modules import call_queue, shared, ui_tempdir, util
-from modules.infotext_utils import image_from_url_text
-import modules.images
-from modules.ui_component... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/ui_common.py |
Turn comments into proper docstrings | import json
import os
import gradio as gr
from modules import errors
from modules.ui_components import ToolButton, InputAccordion
def radio_choices(comp): # gradio 3.41 changes choices from list of values to list of pairs
return [x[0] if isinstance(x, tuple) else x for x in getattr(comp, 'choices', [])]
clas... | --- +++ @@ -1,227 +1,238 @@-import json
-import os
-
-import gradio as gr
-
-from modules import errors
-from modules.ui_components import ToolButton, InputAccordion
-
-
-def radio_choices(comp): # gradio 3.41 changes choices from list of values to list of pairs
- return [x[0] if isinstance(x, tuple) else x for x i... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/ui_loadsave.py |
Generate docstrings for each module | import os
import tempfile
from collections import namedtuple
from pathlib import Path
import gradio.components
from PIL import PngImagePlugin
from modules import shared
Savedfile = namedtuple("Savedfile", ["name"])
def register_tmp_file(gradio, filename):
if hasattr(gradio, 'temp_file_sets'): # gradio 3.15
... | --- +++ @@ -1,96 +1,100 @@-import os
-import tempfile
-from collections import namedtuple
-from pathlib import Path
-
-import gradio.components
-
-from PIL import PngImagePlugin
-
-from modules import shared
-
-
-Savedfile = namedtuple("Savedfile", ["name"])
-
-
-def register_tmp_file(gradio, filename):
- if hasattr... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/ui_tempdir.py |
Add docstrings that explain inputs and outputs | import os
import re
from modules import shared
from modules.paths_internal import script_path, cwd
def natural_sort_key(s, regex=re.compile('([0-9]+)')):
return [int(text) if text.isdigit() else text.lower() for text in regex.split(s)]
def listfiles(dirname):
filenames = [os.path.join(dirname, x) for x in ... | --- +++ @@ -1,191 +1,213 @@-import os
-import re
-
-from modules import shared
-from modules.paths_internal import script_path, cwd
-
-
-def natural_sort_key(s, regex=re.compile('([0-9]+)')):
- return [int(text) if text.isdigit() else text.lower() for text in regex.split(s)]
-
-
-def listfiles(dirname):
- filenam... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/util.py |
Write documentation strings for class attributes | import logging
from typing import Callable
import numpy as np
import torch
import tqdm
from PIL import Image
from modules import devices, images, shared, torch_utils
logger = logging.getLogger(__name__)
def pil_image_to_torch_bgr(img: Image.Image) -> torch.Tensor:
img = np.array(img.convert("RGB"))
img = i... | --- +++ @@ -36,6 +36,9 @@
def upscale_pil_patch(model, img: Image.Image) -> Image.Image:
+ """
+ Upscale a given PIL image using the given model.
+ """
param = torch_utils.get_param(model)
with torch.inference_mode():
@@ -168,6 +171,9 @@ scale: int,
desc: str,
):
+ """
+ Conveni... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/upscaler_utils.py |
Write docstrings for backend logic |
from abc import ABC, abstractmethod
from contextlib import AsyncExitStack
from typing import Any
from mcp import ClientSession, StdioServerParameters
from mcp.client.sse import sse_client
from mcp.client.stdio import stdio_client
from mcp.client.streamable_http import streamablehttp_client
class MCPConnection(ABC):... | --- +++ @@ -1,3 +1,4 @@+"""Lightweight connection handling for MCP servers."""
from abc import ABC, abstractmethod
from contextlib import AsyncExitStack
@@ -10,6 +11,7 @@
class MCPConnection(ABC):
+ """Base class for MCP server connections."""
def __init__(self):
self.session = None
@@ -17,8 ... | https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/mcp-builder/scripts/connections.py |
Create structured documentation for my script | import math
from dataclasses import dataclass
from typing import Tuple, Optional, Literal
import torch
from torch import nn
import torch.nn.functional as F
import torch.distributed as dist
from kernel import act_quant, weight_dequant, fp8_gemm
world_size = 1
rank = 0
block_size = 128
gemm_impl: Literal["bf16", "fp8... | --- +++ @@ -18,6 +18,40 @@
@dataclass
class ModelArgs:
+ """
+ Data class for defining model arguments and hyperparameters.
+
+ Attributes:
+ max_batch_size (int): Maximum batch size.
+ max_seq_len (int): Maximum sequence length.
+ dtype (Literal["bf16", "fp8"]): Data type for computati... | https://raw.githubusercontent.com/deepseek-ai/DeepSeek-V3/HEAD/inference/model.py |
Annotate my code with docstrings | from collections import namedtuple
from copy import copy
from itertools import permutations, chain
import random
import csv
import os.path
from io import StringIO
from PIL import Image
import numpy as np
import modules.scripts as scripts
import gradio as gr
from modules import images, sd_samplers, processing, sd_mode... | --- +++ @@ -1,815 +1,817 @@-from collections import namedtuple
-from copy import copy
-from itertools import permutations, chain
-import random
-import csv
-import os.path
-from io import StringIO
-from PIL import Image
-import numpy as np
-
-import modules.scripts as scripts
-import gradio as gr
-
-from modules import... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/scripts/xyz_grid.py |
Add docstrings that explain inputs and outputs |
import argparse
import asyncio
import json
import re
import sys
import time
import traceback
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any
from anthropic import Anthropic
from connections import create_connection
EVALUATION_PROMPT = """You are an AI assistant with access to tool... | --- +++ @@ -1,3 +1,7 @@+"""MCP Server Evaluation Harness
+
+This script evaluates MCP servers by running test questions against them using Claude.
+"""
import argparse
import asyncio
@@ -50,6 +54,7 @@
def parse_evaluation_file(file_path: Path) -> list[dict[str, Any]]:
+ """Parse XML evaluation file with qa_p... | https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/mcp-builder/scripts/evaluation.py |
Add docstrings to clarify complex logic | #!/usr/bin/env python3
import argparse
import json
import math
import sys
from datetime import datetime, timezone
from pathlib import Path
def calculate_stats(values: list[float]) -> dict:
if not values:
return {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0}
n = len(values)
mean = sum(value... | --- +++ @@ -1,4 +1,38 @@ #!/usr/bin/env python3
+"""
+Aggregate individual run results into benchmark summary statistics.
+
+Reads grading.json files from run directories and produces:
+- run_summary with mean, stddev, min, max for each metric
+- delta between with_skill and without_skill configurations
+
+Usage:
+ ... | https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/scripts/aggregate_benchmark.py |
Create docstrings for all classes and functions |
from pathlib import Path
def parse_skill_md(skill_path: Path) -> tuple[str, str, str]:
content = (skill_path / "SKILL.md").read_text()
lines = content.split("\n")
if lines[0].strip() != "---":
raise ValueError("SKILL.md missing frontmatter (no opening ---)")
end_idx = None
for i, line ... | --- +++ @@ -1,9 +1,11 @@+"""Shared utilities for skill-creator scripts."""
from pathlib import Path
def parse_skill_md(skill_path: Path) -> tuple[str, str, str]:
+ """Parse a SKILL.md file, returning (name, description, full_content)."""
content = (skill_path / "SKILL.md").read_text()
lines = con... | https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/scripts/utils.py |
Generate docstrings with parameter types | #!/usr/bin/env python3
import argparse
import json
import os
import re
import subprocess
import sys
from pathlib import Path
from scripts.utils import parse_skill_md
def _call_claude(prompt: str, model: str | None, timeout: int = 300) -> str:
cmd = ["claude", "-p", "--output-format", "text"]
if model:
... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""Improve a skill description based on eval results.
+
+Takes eval results (from run_eval.py) and generates an improved description
+by calling `claude -p` as a subprocess (same auth pattern as run_eval.py —
+uses the session's Claude Code auth, no separate ANTHROPIC_AP... | https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/scripts/improve_description.py |
Add professional docstrings to my codebase | #!/usr/bin/env python3
import argparse
import base64
import json
import mimetypes
import os
import re
import signal
import subprocess
import sys
import time
import webbrowser
from functools import partial
from http.server import HTTPServer, BaseHTTPRequestHandler
from pathlib import Path
# Files to exclude from outpu... | --- +++ @@ -1,4 +1,16 @@ #!/usr/bin/env python3
+"""Generate and serve a review page for eval results.
+
+Reads the workspace directory, discovers runs (directories with outputs/),
+embeds all output data into a self-contained HTML page, and serves it via
+a tiny HTTP server. Feedback auto-saves to feedback.json in the... | https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/eval-viewer/generate_review.py |
Add docstrings with type hints explained | #!/usr/bin/env python3
import argparse
import json
import random
import sys
import tempfile
import time
import webbrowser
from pathlib import Path
from scripts.generate_report import generate_html
from scripts.improve_description import improve_description
from scripts.run_eval import find_project_root, run_eval
from... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""Run the eval + improve loop until all pass or max iterations reached.
+
+Combines run_eval.py and improve_description.py in a loop, tracking history
+and returning the best description found. Supports train/test split to prevent
+overfitting.
+"""
import argparse
... | https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/scripts/run_loop.py |
Document helper functions with docstrings | import os
import json
from argparse import ArgumentParser
from glob import glob
from tqdm import tqdm
import torch
from safetensors.torch import load_file, save_file
from kernel import weight_dequant
def main(fp8_path, bf16_path):
torch.set_default_dtype(torch.bfloat16)
os.makedirs(bf16_path, exist_ok=True)
... | --- +++ @@ -10,6 +10,25 @@ from kernel import weight_dequant
def main(fp8_path, bf16_path):
+ """
+ Converts FP8 weights to BF16 and saves the converted weights.
+
+ This function reads FP8 weights from the specified directory, converts them to BF16,
+ and saves the converted weights to another specified... | https://raw.githubusercontent.com/deepseek-ai/DeepSeek-V3/HEAD/inference/fp8_cast_bf16.py |
Create docstrings for API functions | #!/usr/bin/env python3
import fnmatch
import sys
import zipfile
from pathlib import Path
from scripts.quick_validate import validate_skill
# Patterns to exclude when packaging skills.
EXCLUDE_DIRS = {"__pycache__", "node_modules"}
EXCLUDE_GLOBS = {"*.pyc"}
EXCLUDE_FILES = {".DS_Store"}
# Directories excluded only at ... | --- +++ @@ -1,4 +1,14 @@ #!/usr/bin/env python3
+"""
+Skill Packager - Creates a distributable .skill file of a skill folder
+
+Usage:
+ python utils/package_skill.py <path/to/skill-folder> [output-directory]
+
+Example:
+ python utils/package_skill.py skills/public/my-skill
+ python utils/package_skill.py ski... | https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/scripts/package_skill.py |
Add docstrings to my Python code | #!/usr/bin/env python3
import argparse
import json
import os
import select
import subprocess
import sys
import time
import uuid
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
from scripts.utils import parse_skill_md
def find_project_root() -> Path:
current = Path.cwd()... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""Run trigger evaluation for a skill description.
+
+Tests whether a skill's description causes Claude to trigger (read the skill)
+for a set of queries. Outputs results as JSON.
+"""
import argparse
import json
@@ -15,6 +20,11 @@
def find_project_root() -> Path:... | https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/scripts/run_eval.py |
Write docstrings describing functionality | import os
import json
from argparse import ArgumentParser
from typing import List
import torch
import torch.distributed as dist
from transformers import AutoTokenizer
from safetensors.torch import load_model
from model import Transformer, ModelArgs
def sample(logits, temperature: float = 1.0):
logits = logits /... | --- +++ @@ -12,6 +12,16 @@
def sample(logits, temperature: float = 1.0):
+ """
+ Samples a token from the logits using temperature scaling.
+
+ Args:
+ logits (torch.Tensor): The logits tensor for token predictions.
+ temperature (float, optional): Temperature for scaling logits. Defaults to ... | https://raw.githubusercontent.com/deepseek-ai/DeepSeek-V3/HEAD/inference/generate.py |
Create Google-style docstrings for my code | from typing import Tuple, Optional
import torch
import triton
import triton.language as tl
from triton import Config
@triton.jit
def act_quant_kernel(x_ptr, y_ptr, s_ptr, BLOCK_SIZE: tl.constexpr, scale_fmt: tl.constexpr):
pid = tl.program_id(axis=0)
offs = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
x =... | --- +++ @@ -8,6 +8,18 @@
@triton.jit
def act_quant_kernel(x_ptr, y_ptr, s_ptr, BLOCK_SIZE: tl.constexpr, scale_fmt: tl.constexpr):
+ """
+ Quantizes the input tensor `x_ptr` and stores the result in `y_ptr` and the scaling factor in `s_ptr`.
+
+ Args:
+ x_ptr (triton.Pointer): Pointer to the input te... | https://raw.githubusercontent.com/deepseek-ai/DeepSeek-V3/HEAD/inference/kernel.py |
Add docstrings following best practices | import os
import torch
import torch.nn as nn
from modules import devices, paths_internal, shared
sd_vae_taesd_models = {}
def conv(n_in, n_out, **kwargs):
return nn.Conv2d(n_in, n_out, 3, padding=1, **kwargs)
class Clamp(nn.Module):
@staticmethod
def forward(x):
return torch.tanh(x / 3) * 3
... | --- +++ @@ -1,3 +1,9 @@+"""
+Tiny AutoEncoder for Stable Diffusion
+(DNN for encoding / decoding SD's latent space)
+
+https://github.com/madebyollin/taesd
+"""
import os
import torch
import torch.nn as nn
@@ -53,6 +59,7 @@ latent_shift = 0.5
def __init__(self, decoder_path="taesd_decoder.pth", latent_cha... | https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui/HEAD/modules/sd_vae_taesd.py |
Add docstrings including usage examples | #!/usr/bin/env python3
import argparse
import html
import json
import sys
from pathlib import Path
def generate_html(data: dict, auto_refresh: bool = False, skill_name: str = "") -> str:
history = data.get("history", [])
holdout = data.get("holdout", 0)
title_prefix = html.escape(skill_name + " \u2014 ")... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""Generate an HTML report from run_loop.py output.
+
+Takes the JSON output from run_loop.py and generates a visual HTML report
+showing each description attempt with check/x for each test case.
+Distinguishes between train and test queries.
+"""
import argparse
imp... | https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/skill-creator/scripts/generate_report.py |
Add docstrings including usage examples | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Author : XueWeiHan
# E-mail : 595666367@qq.com
# Date : 16/8/30 下午10:43
# Desc : Github Bot
import os
import logging
import smtplib
import datetime
from operator import itemgetter
from email.mime.text import MIMEText
from email.header import Heade... | --- +++ @@ -68,6 +68,11 @@
def get_data(page=1):
+ """
+ 从目标源获取数据
+ https://developer.github.com/v3/activity/events/
+ GitHub 规定:默认每页 30 条,最多 300 条目
+ """
args = '?page={page}'.format(page=page)
@@ -83,6 +88,11 @@
def get_all_data():
+ """
+ 获取全部 300 条的数据
+ https://developer.git... | https://raw.githubusercontent.com/521xueweihan/HelloGitHub/HEAD/script/github_bot/github_bot.py |
Add inline docstrings for readability | #!/usr/bin/env python3
from typing import Optional
import numpy as np
from PIL import Image, ImageDraw, ImageFont
def create_blank_frame(
width: int, height: int, color: tuple[int, int, int] = (255, 255, 255)
) -> Image.Image:
return Image.new("RGB", (width, height), color)
def draw_circle(
frame: Ima... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+Frame Composer - Utilities for composing visual elements into frames.
+
+Provides functions for drawing shapes, text, emojis, and compositing elements
+together to create animation frames.
+"""
from typing import Optional
@@ -9,6 +15,17 @@ def create_blank_fram... | https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/slack-gif-creator/core/frame_composer.py |
Expand my code with proper documentation strings | #!/usr/bin/env python3
from pathlib import Path
def validate_gif(
gif_path: str | Path, is_emoji: bool = True, verbose: bool = True
) -> tuple[bool, dict]:
from PIL import Image
gif_path = Path(gif_path)
if not gif_path.exists():
return False, {"error": f"File not found: {gif_path}"}
#... | --- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3
+"""
+Validators - Check if GIFs meet Slack's requirements.
+
+These validators help ensure your GIFs meet Slack's size and dimension constraints.
+"""
from pathlib import Path
@@ -6,6 +11,17 @@ def validate_gif(
gif_path: str | Path, is_emoji: bool = True, verbo... | https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/slack-gif-creator/core/validators.py |
Add docstrings to improve collaboration | #!/usr/bin/env python3
import math
def linear(t: float) -> float:
return t
def ease_in_quad(t: float) -> float:
return t * t
def ease_out_quad(t: float) -> float:
return t * (2 - t)
def ease_in_out_quad(t: float) -> float:
if t < 0.5:
return 2 * t * t
return -1 + (4 - 2 * t) * t
d... | --- +++ @@ -1,45 +1,60 @@ #!/usr/bin/env python3
+"""
+Easing Functions - Timing functions for smooth animations.
+
+Provides various easing functions for natural motion and timing.
+All functions take a value t (0.0 to 1.0) and return eased value (0.0 to 1.0).
+"""
import math
def linear(t: float) -> float:
+ ... | https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/slack-gif-creator/core/easing.py |
Add docstrings to make code maintainable | #!/usr/bin/env python3
from pathlib import Path
from typing import Optional
import imageio.v3 as imageio
import numpy as np
from PIL import Image
class GIFBuilder:
def __init__(self, width: int = 480, height: int = 480, fps: int = 15):
self.width = width
self.height = height
self.fps = ... | --- +++ @@ -1,4 +1,10 @@ #!/usr/bin/env python3
+"""
+GIF Builder - Core module for assembling frames into GIFs optimized for Slack.
+
+This module provides the main interface for creating GIFs from programmatically
+generated frames, with automatic optimization for Slack's requirements.
+"""
from pathlib import Pat... | https://raw.githubusercontent.com/anthropics/skills/HEAD/skills/slack-gif-creator/core/gif_builder.py |
Add docstrings that explain logic | from collections.abc import Callable
from typing import Annotated, Any
from annotated_doc import Doc
from starlette.background import BackgroundTasks as StarletteBackgroundTasks
from typing_extensions import ParamSpec
P = ParamSpec("P")
class BackgroundTasks(StarletteBackgroundTasks):
def add_task(
sel... | --- +++ @@ -9,6 +9,33 @@
class BackgroundTasks(StarletteBackgroundTasks):
+ """
+ A collection of background tasks that will be called after a response has been
+ sent to the client.
+
+ Read more about it in the
+ [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-t... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/background.py |
Add missing documentation to my Python functions | from collections.abc import Mapping, Sequence
from typing import Annotated, Any, TypedDict
from annotated_doc import Doc
from pydantic import BaseModel, create_model
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.exceptions import WebSocketException as StarletteWebSocketExcepti... | --- +++ @@ -15,6 +15,32 @@
class HTTPException(StarletteHTTPException):
+ """
+ An HTTP exception you can raise in your own code to show errors to the client.
+
+ This is for client errors, invalid authentication, invalid data, etc. Not for server
+ errors in your code.
+
+ Read more about it in the
... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/exceptions.py |
Auto-generate documentation strings for this file | from collections.abc import Callable, Mapping
from typing import (
Annotated,
Any,
BinaryIO,
TypeVar,
cast,
)
from annotated_doc import Doc
from pydantic import GetJsonSchemaHandler
from starlette.datastructures import URL as URL # noqa: F401
from starlette.datastructures import Address as Address... | --- +++ @@ -19,6 +19,38 @@
class UploadFile(StarletteUploadFile):
+ """
+ A file uploaded in a request.
+
+ Define it as a *path operation function* (or dependency) parameter.
+
+ If you are using a regular `def` function, you can use the `upload_file.file`
+ attribute to access the raw standard Pyth... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/datastructures.py |
Expand my code with proper documentation strings | from collections.abc import Awaitable, Callable, Coroutine, Sequence
from enum import Enum
from typing import Annotated, Any, TypeVar
from annotated_doc import Doc
from fastapi import routing
from fastapi.datastructures import Default, DefaultPlaceholder
from fastapi.exception_handlers import (
http_exception_hand... | --- +++ @@ -39,6 +39,20 @@
class FastAPI(Starlette):
+ """
+ `FastAPI` app class, the main entrypoint to use FastAPI.
+
+ Read more in the
+ [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/).
+
+ ## Example
+
+ ```python
+ from fastapi import FastAPI
+
+ app ... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/applications.py |
Add documentation for all methods | import dataclasses
import inspect
import sys
from collections.abc import (
AsyncGenerator,
AsyncIterable,
AsyncIterator,
Callable,
Generator,
Iterable,
Iterator,
Mapping,
Sequence,
)
from contextlib import AsyncExitStack, contextmanager
from copy import copy, deepcopy
from dataclasse... | --- +++ @@ -867,6 +867,7 @@
def is_union_of_base_models(field_type: Any) -> bool:
+ """Check if field type is a Union where all members are BaseModel subclasses."""
from fastapi.types import UnionType
origin = get_origin(field_type)
@@ -1000,6 +1001,16 @@ def get_body_field(
*, flat_dependant: D... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/dependencies/utils.py |
Generate descriptive docstrings automatically | import dataclasses
import datetime
from collections import defaultdict, deque
from collections.abc import Callable
from decimal import Decimal
from enum import Enum
from ipaddress import (
IPv4Address,
IPv4Interface,
IPv4Network,
IPv6Address,
IPv6Interface,
IPv6Network,
)
from pathlib import Pat... | --- +++ @@ -41,6 +41,23 @@ # Adapted from Pydantic v1
# TODO: pv2 should this return strings instead?
def decimal_encoder(dec_value: Decimal) -> int | float:
+ """
+ Encodes a Decimal as int if there's no exponent, otherwise float
+
+ This is useful when we use ConstrainedDecimal to represent Numeric(x,0)
+ ... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/encoders.py |
Add well-formatted docstrings | import json
from typing import Annotated, Any
from annotated_doc import Doc
from fastapi.encoders import jsonable_encoder
from starlette.responses import HTMLResponse
def _html_safe_json(value: Any) -> str:
return (
json.dumps(value)
.replace("<", "\\u003c")
.replace(">", "\\u003e")
... | --- +++ @@ -7,6 +7,10 @@
def _html_safe_json(value: Any) -> str:
+ """Serialize a value to JSON with HTML special characters escaped.
+
+ This prevents injection when the JSON is embedded inside a <script> tag.
+ """
return (
json.dumps(value)
.replace("<", "\\u003c")
@@ -130,6 +134,... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/openapi/docs.py |
Generate docstrings for each module | from collections.abc import Callable, Sequence
from typing import Annotated, Any, Literal
from annotated_doc import Doc
from fastapi import params
from fastapi._compat import Undefined
from fastapi.datastructures import _Unset
from fastapi.openapi.models import Example
from pydantic import AliasChoices, AliasPath
from... | --- +++ @@ -300,6 +300,27 @@ ),
],
) -> Any:
+ """
+ Declare a path parameter for a *path operation*.
+
+ Read more about it in the
+ [FastAPI docs for Path Parameters and Numeric Validations](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/).
+
+ ```python
+ from t... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/param_functions.py |
Generate descriptive docstrings automatically | from typing import Any
from fastapi.exceptions import FastAPIDeprecationWarning
from fastapi.sse import EventSourceResponse as EventSourceResponse # noqa
from starlette.responses import FileResponse as FileResponse # noqa
from starlette.responses import HTMLResponse as HTMLResponse # noqa
from starlette.responses i... | --- +++ @@ -33,6 +33,20 @@ stacklevel=2,
)
class UJSONResponse(JSONResponse):
+ """JSON response using the ujson library to serialize data to JSON.
+
+ **Deprecated**: `UJSONResponse` is deprecated. FastAPI now serializes data
+ directly to JSON bytes via Pydantic when a return type or response model is
... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/responses.py |
Generate consistent docstrings | import contextlib
import email.message
import functools
import inspect
import json
import types
from collections.abc import (
AsyncIterator,
Awaitable,
Callable,
Collection,
Coroutine,
Generator,
Iterator,
Mapping,
Sequence,
)
from contextlib import (
AbstractAsyncContextManager,... | --- +++ @@ -97,6 +97,10 @@ def request_response(
func: Callable[[Request], Awaitable[Response] | Response],
) -> ASGIApp:
+ """
+ Takes a function or coroutine `func(request) -> response`,
+ and returns an ASGI application.
+ """
f: Callable[[Request], Awaitable[Response]] = (
func # ty... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/routing.py |
Add detailed documentation for each class | from typing import Annotated
from annotated_doc import Doc
from fastapi.openapi.models import APIKey, APIKeyIn
from fastapi.security.base import SecurityBase
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.status import HTTP_401_UNAUTHORIZED
class APIKeyBase(Secur... | --- +++ @@ -29,6 +29,15 @@ self.scheme_name = scheme_name or self.__class__.__name__
def make_not_authenticated_error(self) -> HTTPException:
+ """
+ The WWW-Authenticate header is not standardized for API Key authentication but
+ the HTTP specification requires that an error of 401 ... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/security/api_key.py |
Add inline docstrings for readability | from typing import Annotated, Any, cast
from annotated_doc import Doc
from fastapi.exceptions import HTTPException
from fastapi.openapi.models import OAuth2 as OAuth2Model
from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel
from fastapi.param_functions import Form
from fastapi.security.base import Securit... | --- +++ @@ -12,6 +12,49 @@
class OAuth2PasswordRequestForm:
+ """
+ This is a dependency class to collect the `username` and `password` as form data
+ for an OAuth2 password flow.
+
+ The OAuth2 specification dictates that for a password flow the data should be
+ collected using form data (instead of... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/security/oauth2.py |
Write docstrings for this repository | import json
import logging
import os
import re
import shutil
import subprocess
from html.parser import HTMLParser
from http.server import HTTPServer, SimpleHTTPRequestHandler
from multiprocessing import Pool
from pathlib import Path
from typing import Any
import mkdocs.utils
import typer
import yaml
from jinja2 import... | --- +++ @@ -71,10 +71,12 @@
def strip_markdown_links(text: str) -> str:
+ """Replace markdown links with just their visible text."""
return md_link_pattern.sub(r"\1", text)
class VisibleTextExtractor(HTMLParser):
+ """Extract visible text from a string with HTML tags."""
def __init__(self):
... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/scripts/docs.py |
Generate docstrings with parameter types | import re
from typing import TypedDict
CODE_INCLUDE_RE = re.compile(r"^\{\*\s*(\S+)\s*(.*)\*\}$")
CODE_INCLUDE_PLACEHOLDER = "<CODE_INCLUDE>"
HEADER_WITH_PERMALINK_RE = re.compile(r"^(#{1,6}) (.+?)(\s*\{\s*#.*\s*\})?\s*$")
HEADER_LINE_RE = re.compile(r"^(#{1,6}) (.+?)(?:\s*\{\s*(#.*)\s*\})?\s*$")
TIANGOLO_COM = "htt... | --- +++ @@ -79,6 +79,13 @@
def extract_code_includes(lines: list[str]) -> list[CodeIncludeInfo]:
+ """
+ Extract lines that contain code includes.
+
+ Return list of CodeIncludeInfo, where each dict contains:
+ - `line_no` - line number (1-based)
+ - `line` - text of the line
+ """
includes... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/scripts/doc_parsing_utils.py |
Add verbose docstrings with examples | import binascii
from base64 import b64decode
from typing import Annotated
from annotated_doc import Doc
from fastapi.exceptions import HTTPException
from fastapi.openapi.models import HTTPBase as HTTPBaseModel
from fastapi.openapi.models import HTTPBearer as HTTPBearerModel
from fastapi.security.base import SecurityBa... | --- +++ @@ -14,12 +14,39 @@
class HTTPBasicCredentials(BaseModel):
+ """
+ The HTTP Basic credentials given as the result of using `HTTPBasic` in a
+ dependency.
+
+ Read more about it in the
+ [FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/).
+ "... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/security/http.py |
Document all public functions with docstrings | from typing import Annotated, Any
from annotated_doc import Doc
from pydantic import AfterValidator, BaseModel, Field, model_validator
from starlette.responses import StreamingResponse
# Canonical SSE event schema matching the OpenAPI 3.2 spec
# (Section 4.14.4 "Special Considerations for Server-Sent Events")
_SSE_EV... | --- +++ @@ -18,6 +18,17 @@
class EventSourceResponse(StreamingResponse):
+ """Streaming response with `text/event-stream` media type.
+
+ Use as `response_class=EventSourceResponse` on a *path operation* that uses `yield`
+ to enable Server Sent Events (SSE) responses.
+
+ Works with **any HTTP method**... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/fastapi/sse.py |
Document all endpoints with docstrings | import os
from collections.abc import Iterable
from pathlib import Path
from typing import Annotated
import typer
from scripts.doc_parsing_utils import check_translation
non_translated_sections = (
f"reference{os.sep}",
"release-notes.md",
"fastapi-people.md",
"external-links.md",
"newsletter.md"... | --- +++ @@ -28,6 +28,9 @@
def iter_all_lang_paths(lang_path_root: Path) -> Iterable[Path]:
+ """
+ Iterate on the markdown files to translate in order of priority.
+ """
first_dirs = [
lang_path_root / "learn",
@@ -60,6 +63,11 @@
def process_one_page(path: Path) -> bool:
+ """
+ F... | https://raw.githubusercontent.com/fastapi/fastapi/HEAD/scripts/translation_fixer.py |
Help me add docstrings to my project | import os
from functools import lru_cache
from subprocess import CalledProcessError, run
from typing import Optional, Union
import numpy as np
import torch
import torch.nn.functional as F
from .utils import exact_div
# hard-coded audio hyperparameters
SAMPLE_RATE = 16000
N_FFT = 400
HOP_LENGTH = 160
CHUNK_LENGTH = 3... | --- +++ @@ -23,6 +23,21 @@
def load_audio(file: str, sr: int = SAMPLE_RATE):
+ """
+ Open an audio file and read as mono waveform, resampling as necessary
+
+ Parameters
+ ----------
+ file: str
+ The audio file to open
+
+ sr: int
+ The sample rate to resample the audio if necessary... | https://raw.githubusercontent.com/openai/whisper/HEAD/whisper/audio.py |
Add docstrings that explain logic | import base64
import os
import string
from dataclasses import dataclass, field
from functools import cached_property, lru_cache
from typing import Dict, List, Optional, Tuple
import tiktoken
LANGUAGES = {
"en": "english",
"zh": "chinese",
"de": "german",
"es": "spanish",
"ru": "russian",
"ko":... | --- +++ @@ -130,6 +130,7 @@
@dataclass
class Tokenizer:
+ """A thin wrapper around `tiktoken` providing quick access to special tokens"""
encoding: tiktoken.Encoding
num_languages: int
@@ -165,6 +166,10 @@ return self.encoding.decode(token_ids, **kwargs)
def decode_with_timestamps(self,... | https://raw.githubusercontent.com/openai/whisper/HEAD/whisper/tokenizer.py |
Add documentation for all methods | import hashlib
import io
import os
import urllib
import warnings
from typing import List, Optional, Union
import torch
from tqdm import tqdm
from .audio import load_audio, log_mel_spectrogram, pad_or_trim
from .decoding import DecodingOptions, DecodingResult, decode, detect_language
from .model import ModelDimensions... | --- +++ @@ -96,6 +96,7 @@
def available_models() -> List[str]:
+ """Returns the names of available models"""
return list(_MODELS.keys())
@@ -105,6 +106,26 @@ download_root: str = None,
in_memory: bool = False,
) -> Whisper:
+ """
+ Load a Whisper ASR model
+
+ Parameters
+ --------... | https://raw.githubusercontent.com/openai/whisper/HEAD/whisper/__init__.py |
Add minimal docstrings for each function | import base64
import gzip
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Dict, Iterable, Optional, Tuple
import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from .decoding import decode as decode_function
from .decoding import detect... | --- +++ @@ -60,6 +60,7 @@
def sinusoids(length, channels, max_timescale=10000):
+ """Returns sinusoids for positional embedding"""
assert channels % 2 == 0
log_timescale_increment = np.log(max_timescale) / (channels // 2 - 1)
inv_timescales = torch.exp(-log_timescale_increment * torch.arange(chann... | https://raw.githubusercontent.com/openai/whisper/HEAD/whisper/model.py |
Improve documentation using docstrings | from dataclasses import dataclass, field, replace
from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Sequence, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor
from torch.distributions import Categorical
from .audio import CHUNK_LENGTH
from .tokenize... | --- +++ @@ -19,6 +19,18 @@ def detect_language(
model: "Whisper", mel: Tensor, tokenizer: Tokenizer = None
) -> Tuple[Tensor, List[dict]]:
+ """
+ Detect the spoken language in the audio, and return them as list of strings, along with the ids
+ of the most probable language tokens and the probability dis... | https://raw.githubusercontent.com/openai/whisper/HEAD/whisper/decoding.py |
Document all public functions with docstrings | import json
import os
import re
from fractions import Fraction
from typing import Iterator, List, Match, Optional, Union
from more_itertools import windowed
from .basic import remove_symbols_and_diacritics
class EnglishNumberNormalizer:
def __init__(self):
super().__init__()
self.zeros = {"o",... | --- +++ @@ -10,6 +10,15 @@
class EnglishNumberNormalizer:
+ """
+ Convert any spelled-out numbers into arabic numbers, while handling:
+
+ - remove any commas
+ - keep the suffixes such as: `1960s`, `274th`, `32nd`, etc.
+ - spell out currency symbols after the number. e.g. `$20 million` -> `20000000... | https://raw.githubusercontent.com/openai/whisper/HEAD/whisper/normalizers/english.py |
Add structured docstrings to improve clarity | import re
import unicodedata
import regex
# non-ASCII letters that are not separated by "NFKD" normalization
ADDITIONAL_DIACRITICS = {
"œ": "oe",
"Œ": "OE",
"ø": "o",
"Ø": "O",
"æ": "ae",
"Æ": "AE",
"ß": "ss",
"ẞ": "SS",
"đ": "d",
"Đ": "D",
"ð": "d",
"Ð": "D",
"þ": ... | --- +++ @@ -25,6 +25,10 @@
def remove_symbols_and_diacritics(s: str, keep=""):
+ """
+ Replace any other markers, symbols, and punctuations with a space,
+ and drop any diacritics (category 'Mn' and some manual mappings)
+ """
return "".join(
(
c
@@ -44,6 +48,9 @@
def remo... | https://raw.githubusercontent.com/openai/whisper/HEAD/whisper/normalizers/basic.py |
Fully document this Python code with docstrings | # Copyright (c) 2016, Aaron Christianson
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of condition... | --- +++ @@ -23,6 +23,18 @@ # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+'''
+Monkey patch setuptools to write faster console_scripts with this format:
+
+ i... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/fastentrypoints.py |
Insert docstrings into my code | import json
import os
import socket
try:
from shutil import get_terminal_size
except ImportError:
from backports.shutil_get_terminal_size import get_terminal_size
import pyte
from .. import const, logs
def _get_socket_path():
return os.environ.get(const.SHELL_LOGGER_SOCKET_ENV)
def is_available():
p... | --- +++ @@ -14,6 +14,11 @@
def is_available():
+ """Returns `True` if shell logger socket available.
+
+ :rtype: book
+
+ """
path = _get_socket_path()
if not path:
return False
@@ -42,6 +47,7 @@
def get_output(script):
+ """Gets command output from shell logger."""
with logs... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/output_readers/shell_logger.py |
Document this code for team use | import os
import sys
from warnings import warn
from six import text_type
from . import const
from .system import Path
try:
import importlib.util
def load_source(name, pathname, _file=None):
module_spec = importlib.util.spec_from_file_location(name, pathname)
module = importlib.util.module_from... | --- +++ @@ -25,6 +25,7 @@ self[key] = value
def init(self, args=None):
+ """Fills `settings` with values from `settings.py` and env."""
from .logs import exception
self._setup_user_dir()
@@ -51,6 +52,7 @@ settings_file.write(u'# {} = {}\n'.format(*setting))
... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/conf.py |
Document my Python code with docstrings | import array
import fcntl
from functools import partial
import mmap
import os
import pty
import signal
import sys
import termios
import tty
from .. import logs, const
def _read(f, fd):
data = os.read(fd, 1024)
try:
f.write(data)
except ValueError:
position = const.LOG_SIZE_IN_BYTES - const... | --- +++ @@ -31,6 +31,11 @@
def _spawn(shell, master_read):
+ """Create a spawned process.
+
+ Modified version of pty.spawn with terminal size support.
+
+ """
pid, master_fd = pty.fork()
if pid == pty.CHILD:
@@ -57,6 +62,11 @@
def shell_logger(output):
+ """Logs shell output to the `out... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/entrypoints/shell_logger.py |
Generate docstrings for each module | # Initialize output before importing any module, that can use colorama.
from ..system import init_output
init_output()
import getpass # noqa: E402
import os # noqa: E402
import json # noqa: E402
from tempfile import gettempdir # noqa: E402
import time # noqa: E402
import six # noqa: E402
from psutil import Proc... | --- +++ @@ -17,6 +17,7 @@
def _get_shell_pid():
+ """Returns parent process pid."""
proc = Process(os.getpid())
try:
@@ -26,12 +27,14 @@
def _get_not_configured_usage_tracker_path():
+ """Returns path of special file where we store latest shell pid."""
return Path(gettempdir()).joinpath(u... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/entrypoints/not_configured.py |
Add docstrings that explain purpose and usage | import sys
from .conf import settings
from .types import Rule
from .system import Path
from . import logs
def get_loaded_rules(rules_paths):
for path in rules_paths:
if path.name != '__init__.py':
rule = Rule.from_path(path)
if rule and rule.is_enabled:
yield rule
... | --- +++ @@ -6,6 +6,12 @@
def get_loaded_rules(rules_paths):
+ """Yields all available rules.
+
+ :type rules_paths: [Path]
+ :rtype: Iterable[Rule]
+
+ """
for path in rules_paths:
if path.name != '__init__.py':
rule = Rule.from_path(path)
@@ -14,6 +20,11 @@
def get_rules_... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/corrector.py |
Generate missing documentation strings | from thefuck.utils import for_app
from thefuck.shells import shell
@for_app('docker')
def match(command):
return 'image is being used by running container' in command.output
def get_new_command(command):
container_id = command.output.strip().split(' ')
return shell.and_('docker container rm -f {}', '{}'... | --- +++ @@ -4,9 +4,17 @@
@for_app('docker')
def match(command):
+ '''
+ Matches a command's output with docker's output
+ warning you that you need to remove a container before removing an image.
+ '''
return 'image is being used by running container' in command.output
def get_new_command(comma... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/rules/docker_image_being_used_by_container.py |
Write docstrings for algorithm functions | class EmptyCommand(Exception):
class NoRuleMatched(Exception):
class ScriptNotInLog(Exception): | --- +++ @@ -1,7 +1,10 @@ class EmptyCommand(Exception):
+ """Raised when empty command passed to `thefuck`."""
class NoRuleMatched(Exception):
+ """Raised when no rule matched for some command."""
-class ScriptNotInLog(Exception):+class ScriptNotInLog(Exception):
+ """Script not found in log."""
| https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/exceptions.py |
Help me document legacy Python code | import sys
from argparse import ArgumentParser, SUPPRESS
from .const import ARGUMENT_PLACEHOLDER
from .utils import get_alias
class Parser(object):
def __init__(self):
self._parser = ArgumentParser(prog='thefuck', add_help=False)
self._add_arguments()
def _add_arguments(self):
self._... | --- +++ @@ -5,12 +5,17 @@
class Parser(object):
+ """Argument parser that can handle arguments with our special
+ placeholder.
+
+ """
def __init__(self):
self._parser = ArgumentParser(prog='thefuck', add_help=False)
self._add_arguments()
def _add_arguments(self):
+ "... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/argument_parser.py |
Improve documentation using docstrings | import os
import re
from thefuck.utils import get_closest, replace_command
from thefuck.specific.brew import get_brew_path_prefix, brew_available
BREW_CMD_PATH = '/Homebrew/Library/Homebrew/cmd'
TAP_PATH = '/Homebrew/Library/Taps'
TAP_CMD_PATH = '/%s/%s/cmd'
enabled_by_default = brew_available
def _get_brew_command... | --- +++ @@ -11,6 +11,7 @@
def _get_brew_commands(brew_path_prefix):
+ """To get brew default commands on local environment"""
brew_cmd_path = brew_path_prefix + BREW_CMD_PATH
return [name[:-3] for name in os.listdir(brew_cmd_path)
@@ -18,6 +19,8 @@
def _get_brew_tap_specific_commands(brew_path_pr... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/rules/brew_unknown_command.py |
Add docstrings to existing functions | import os
import shlex
import six
from subprocess import Popen, PIPE, STDOUT
from psutil import AccessDenied, Process, TimeoutExpired
from .. import logs
from ..conf import settings
def _kill_process(proc):
try:
proc.kill()
except AccessDenied:
logs.debug(u'Rerun: process PID {} ({}) could not... | --- +++ @@ -8,6 +8,12 @@
def _kill_process(proc):
+ """Tries to kill the process otherwise just logs a debug message, the
+ process will be killed when thefuck terminates.
+
+ :type proc: Process
+
+ """
try:
proc.kill()
except AccessDenied:
@@ -16,6 +22,15 @@
def _wait_output(pop... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/output_readers/rerun.py |
Write docstrings for data processing functions |
import os
import six
from thefuck.specific.sudo import sudo_support
from thefuck.rules import cd_mkdir
from thefuck.utils import for_app, get_close_matches
__author__ = "mmussomele"
MAX_ALLOWED_DIFF = 0.6
def _get_sub_dirs(parent):
return [child for child in os.listdir(parent) if os.path.isdir(os.path.join(par... | --- +++ @@ -1,3 +1,4 @@+"""Attempts to spellcheck and correct failed cd commands"""
import os
import six
@@ -11,12 +12,14 @@
def _get_sub_dirs(parent):
+ """Returns a list of the child directories of the given parent directory"""
return [child for child in os.listdir(parent) if os.path.isdir(os.path.joi... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/rules/cd_correction.py |
Create docstrings for all classes and functions | from subprocess import Popen, PIPE
from time import time
import os
import sys
import six
from .. import logs
from ..conf import settings
from ..const import ARGUMENT_PLACEHOLDER
from ..utils import DEVNULL, cache
from .generic import Generic
@cache('~/.config/fish/config.fish', '~/.config/fish/functions')
def _get_fu... | --- +++ @@ -107,6 +107,7 @@ reload='fish')
def _get_version(self):
+ """Returns the version of the current shell"""
proc = Popen(['fish', '--version'], stdout=PIPE, stderr=DEVNULL)
return proc.stdout.read().decode('utf-8').split()[-1]
@@ -117,6 +118,7 @@ logs.ex... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/shells/fish.py |
Create documentation strings for testing functions | import io
import os
import shlex
import six
from collections import namedtuple
from ..logs import warn
from ..utils import memoize
from ..conf import settings
from ..system import Path
ShellConfiguration = namedtuple('ShellConfiguration', (
'content', 'path', 'reload', 'can_configure_automatically'))
class Gene... | --- +++ @@ -28,9 +28,11 @@ return command_script
def from_shell(self, command_script):
+ """Prepares command before running in app."""
return self._expand_aliases(command_script)
def to_shell(self, command_script):
+ """Prepares command for running in shell."""
... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/shells/generic.py |
Document all endpoints with docstrings | import subprocess
from .. import utils
@utils.memoize
def get_pkgfile(command):
try:
command = command.strip()
if command.startswith('sudo '):
command = command[5:]
command = command.split(" ")[0]
packages = subprocess.check_output(
['pkgfile', '-b', '-v'... | --- +++ @@ -1,9 +1,15 @@+""" This file provide some utility functions for Arch Linux specific rules."""
import subprocess
from .. import utils
@utils.memoize
def get_pkgfile(command):
+ """ Gets the packages that provide the given command using `pkgfile`.
+
+ If the command is of the form `sudo foo`, sear... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/specific/archlinux.py |
Help me write clear docstrings |
from typing import Any
from markitdown import MarkItDown
from ._ocr_service import LLMVisionOCRService
from ._pdf_converter_with_ocr import PdfConverterWithOCR
from ._docx_converter_with_ocr import DocxConverterWithOCR
from ._pptx_converter_with_ocr import PptxConverterWithOCR
from ._xlsx_converter_with_ocr import Xl... | --- +++ @@ -1,3 +1,7 @@+"""
+Plugin registration for markitdown-ocr.
+Registers OCR-enhanced converters with priority-based replacement strategy.
+"""
from typing import Any
from markitdown import MarkItDown
@@ -13,6 +17,21 @@
def register_converters(markitdown: MarkItDown, **kwargs: Any) -> None:
+ """
+ ... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown-ocr/src/markitdown_ocr/_plugin.py |
Generate NumPy-style docstrings | import os
import sys
from . import logs
from .shells import shell
from .conf import settings, load_source
from .const import DEFAULT_PRIORITY, ALL_ENABLED
from .exceptions import EmptyCommand
from .utils import get_alias, format_raw_script
from .output_readers import get_output
class Command(object):
def __init_... | --- +++ @@ -10,8 +10,15 @@
class Command(object):
+ """Command that should be fixed."""
def __init__(self, script, output):
+ """Initializes command with given values.
+
+ :type script: basestring
+ :type output: basestring
+
+ """
self.script = script
self.ou... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/types.py |
Document functions with clear intent |
import io
import re
import sys
from typing import Any, BinaryIO, Optional
from markitdown.converters import HtmlConverter
from markitdown.converter_utils.docx.pre_process import pre_process_docx
from markitdown import DocumentConverterResult, StreamInfo
from markitdown._exceptions import (
MissingDependencyExcept... | --- +++ @@ -1,3 +1,7 @@+"""
+Enhanced DOCX Converter with OCR support for embedded images.
+Extracts images from Word documents and performs OCR while maintaining context.
+"""
import io
import re
@@ -27,6 +31,10 @@
class DocxConverterWithOCR(HtmlConverter):
+ """
+ Enhanced DOCX Converter with OCR suppor... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown-ocr/src/markitdown_ocr/_docx_converter_with_ocr.py |
Add docstrings including usage examples | import atexit
import os
import pickle
import re
import shelve
import sys
import six
from decorator import decorator
from difflib import get_close_matches as difflib_get_close_matches
from functools import wraps
from .logs import warn, exception
from .conf import settings
from .system import Path
DEVNULL = open(os.devn... | --- +++ @@ -23,6 +23,7 @@
def memoize(fn):
+ """Caches previous calls to the function."""
memo = {}
@wraps(fn)
@@ -46,6 +47,7 @@
@memoize
def which(program):
+ """Returns `program` path or `None`."""
try:
from shutil import which
@@ -69,6 +71,15 @@
def default_settings(param... | https://raw.githubusercontent.com/nvbn/thefuck/HEAD/thefuck/utils.py |
Add structured docstrings to improve clarity | import locale
from typing import BinaryIO, Any
from striprtf.striprtf import rtf_to_text
from markitdown import (
MarkItDown,
DocumentConverter,
DocumentConverterResult,
StreamInfo,
)
__plugin_interface_version__ = (
1 # The version of the plugin interface that this plugin uses
)
ACCEPTED_MIME_... | --- +++ @@ -23,12 +23,18 @@
def register_converters(markitdown: MarkItDown, **kwargs):
+ """
+ Called during construction of MarkItDown instances to register converters provided by plugins.
+ """
# Simply create and attach an RtfConverter instance
markitdown.register_converter(RtfConverter())
... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown-sample-plugin/src/markitdown_sample_plugin/_plugin.py |
Write docstrings including parameters and return values | import sys
import io
import re
from typing import BinaryIO, Any
from .._base_converter import DocumentConverter, DocumentConverterResult
from .._stream_info import StreamInfo
from .._exceptions import MissingDependencyException, MISSING_DEPENDENCY_MESSAGE
# Pattern for MasterFormat-style partial numbering (e.g., ".1"... | --- +++ @@ -12,6 +12,20 @@
def _merge_partial_numbering_lines(text: str) -> str:
+ """
+ Post-process extracted text to merge MasterFormat-style partial numbering
+ with the following text line.
+
+ MasterFormat documents use partial numbering like:
+ .1 The intent of this Request for Proposal..... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown/src/markitdown/converters/_pdf_converter.py |
Add well-formatted docstrings |
import io
import sys
from typing import Any, BinaryIO, Optional
from markitdown import DocumentConverter, DocumentConverterResult, StreamInfo
from markitdown._exceptions import (
MissingDependencyException,
MISSING_DEPENDENCY_MESSAGE,
)
from ._ocr_service import LLMVisionOCRService
# Import dependencies
_dep... | --- +++ @@ -1,3 +1,7 @@+"""
+Enhanced PDF Converter with OCR support for embedded images.
+Extracts images from PDFs and performs OCR while maintaining document context.
+"""
import io
import sys
@@ -22,6 +26,12 @@
def _extract_images_from_page(page: Any) -> list[dict]:
+ """
+ Extract images from a PDF p... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown-ocr/src/markitdown_ocr/_pdf_converter_with_ocr.py |
Add docstrings that explain inputs and outputs |
import io
import sys
from typing import Any, BinaryIO, Optional
from typing import BinaryIO, Any, Optional
from markitdown.converters import HtmlConverter
from markitdown import DocumentConverter, DocumentConverterResult, StreamInfo
from markitdown._exceptions import (
MissingDependencyException,
MISSING_DEP... | --- +++ @@ -1,3 +1,7 @@+"""
+Enhanced PPTX Converter with improved OCR support.
+Already has LLM-based image description, this enhances it with traditional OCR fallback.
+"""
import io
import sys
@@ -21,6 +25,7 @@
class PptxConverterWithOCR(DocumentConverter):
+ """Enhanced PPTX Converter with OCR fallback."... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown-ocr/src/markitdown_ocr/_pptx_converter_with_ocr.py |
Add docstrings that explain inputs and outputs | import contextlib
import sys
import os
from collections.abc import AsyncIterator
from mcp.server.fastmcp import FastMCP
from starlette.applications import Starlette
from mcp.server.sse import SseServerTransport
from starlette.requests import Request
from starlette.routing import Mount, Route
from starlette.types import... | --- +++ @@ -19,6 +19,7 @@
@mcp.tool()
async def convert_to_markdown(uri: str) -> str:
+ """Convert a resource described by an http:, https:, file: or data: URI to markdown"""
return MarkItDown(enable_plugins=check_plugins_enabled()).convert_uri(uri).markdown
@@ -58,6 +59,7 @@
@contextlib.asyncconte... | https://raw.githubusercontent.com/microsoft/markitdown/HEAD/packages/markitdown-mcp/src/markitdown_mcp/__main__.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.