instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Create docstrings for API functions
# Added by C: # JsException (from jsproxy.c) import ast import builtins import linecache import tokenize from collections.abc import Generator from copy import deepcopy from importlib import import_module from io import StringIO from textwrap import dedent from types import CodeType from typing import Any, Literal ...
--- +++ @@ -1,3 +1,6 @@+""" +A library of helper utilities for connecting Python to the browser environment. +""" # Added by C: # JsException (from jsproxy.c) @@ -16,6 +19,22 @@ def should_quiet(source: str, /) -> bool: + """ + Should we suppress output? + + Returns + ------- + ``True`` if th...
https://raw.githubusercontent.com/pyodide/pyodide/HEAD/src/py/_pyodide/_base.py
Please document this code using docstrings
from collections.abc import Callable from typing import Any, Protocol, cast from . import ( IN_PYODIDE, JsCallableDoubleProxy, JsDomElement, JsProxy, JsWeakRef, create_once_callable, create_proxy, ) if IN_PYODIDE: from js import clearInterval, clearTimeout, setInterval, setTimeout cl...
--- +++ @@ -16,6 +16,7 @@ class Destroyable(Protocol): + """:meta private:""" def destroy(self): pass @@ -43,6 +44,10 @@ def add_event_listener( elt: JsDomElement, event: str, listener: Callable[[Any], None] ) -> None: + """Wrapper for JavaScript's + :js:meth:`~EventTarget.addEventLis...
https://raw.githubusercontent.com/pyodide/pyodide/HEAD/src/py/pyodide/ffi/wrappers.py
Include argument descriptions in docstrings
# Copyright (c) Microsoft Corporation. # # 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 applicable law or agreed to in wri...
--- +++ @@ -12,6 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Python package `playwright` is a Python library to automate Chromium, +Firefox and WebKit with a single API. Playwright is built to enable cross-browser +web automation that is ever...
https://raw.githubusercontent.com/microsoft/playwright-python/HEAD/playwright/async_api/__init__.py
Add structured docstrings to improve clarity
# Copyright (c) Microsoft Corporation. # # 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 applicable law or agreed to in wri...
--- +++ @@ -12,6 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Python package `playwright` is a Python library to automate Chromium, +Firefox and WebKit with a single API. Playwright is built to enable cross-browser +web automation that is ever...
https://raw.githubusercontent.com/microsoft/playwright-python/HEAD/playwright/sync_api/__init__.py
Create structured documentation for my script
# Copyright (c) Microsoft Corporation. # # 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 applicable law or agreed to in wri...
--- +++ @@ -122,12 +122,17 @@ return handler def on(self, event: Any, f: Any) -> None: + """Registers the function ``f`` to the event name ``event``.""" self._impl_obj.on(event, self._wrap_handler(f)) def once(self, event: Any, f: Any) -> None: + """The same as ``self.on``, ...
https://raw.githubusercontent.com/microsoft/playwright-python/HEAD/playwright/_impl/_sync_base.py
Generate docstrings for script automation
# Copyright (c) Microsoft Corporation. # # 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 applicable law or agreed to in wri...
--- +++ @@ -76,12 +76,17 @@ return handler def on(self, event: Any, f: Any) -> None: + """Registers the function ``f`` to the event name ``event``.""" self._impl_obj.on(event, self._wrap_handler(f)) def once(self, event: Any, f: Any) -> None: + """The same as ``self.on``, ex...
https://raw.githubusercontent.com/microsoft/playwright-python/HEAD/playwright/_impl/_async_base.py
Add docstrings for utility scripts
from dataclasses import dataclass, field from typing import List from lightrag.utils import get_env_value @dataclass class RAGAnythingConfig: # Directory Configuration # --- working_dir: str = field(default=get_env_value("WORKING_DIR", "./rag_storage", str)) """Directory where RAG storage and cache ...
--- +++ @@ -1,3 +1,8 @@+""" +Configuration classes for RAGAnything + +Contains configuration dataclasses with environment variable support +""" from dataclasses import dataclass, field from typing import List @@ -6,6 +11,7 @@ @dataclass class RAGAnythingConfig: + """Configuration class for RAGAnything with en...
https://raw.githubusercontent.com/HKUDS/RAG-Anything/HEAD/raganything/config.py
Add docstrings to my Python code
import os from typing import Dict, Any, Optional, Callable import sys import asyncio import atexit from dataclasses import dataclass, field from pathlib import Path from dotenv import load_dotenv # Add project root directory to Python path sys.path.insert(0, str(Path(__file__).parent.parent)) # Load environment vari...
--- +++ @@ -1,3 +1,11 @@+""" +Complete document parsing + multimodal content insertion Pipeline + +This script integrates: +1. Document parsing (using configurable parsers) +2. Pure text content LightRAG insertion +3. Specialized processing for multimodal content (using different processors) +""" import os from typ...
https://raw.githubusercontent.com/HKUDS/RAG-Anything/HEAD/raganything/raganything.py
Fully document this Python code with docstrings
# type: ignore from __future__ import annotations import os import hashlib import json import argparse import base64 import subprocess import tempfile import logging from pathlib import Path from typing import ( Dict, List, Optional, Union, Tuple, Any, Iterator, TypeVar, ) T = TypeVa...
--- +++ @@ -1,4 +1,25 @@ # type: ignore +""" +Generic Document Parser Utility + +This module provides functionality for parsing documents using the built-in +MinerU, Docling, and PaddleOCR parsers, and exposes a small registry for +**in-process** custom parsers (see :func:`register_parser`). + +Important notes: + +- Th...
https://raw.githubusercontent.com/HKUDS/RAG-Anything/HEAD/raganything/parser.py
Document my Python code with docstrings
import os import time import hashlib import json from typing import Dict, List, Any, Tuple, Optional from pathlib import Path from raganything.base import DocStatus from raganything.parser import MineruParser, MineruExecutionError, get_parser from raganything.utils import ( separate_content, insert_text_conte...
--- +++ @@ -1,3 +1,8 @@+""" +Document processing functionality for RAGAnything + +Contains methods for parsing documents and processing multimodal content +""" import os import time @@ -19,8 +24,18 @@ class ProcessorMixin: + """ProcessorMixin class containing document processing functionality for RAGAnything...
https://raw.githubusercontent.com/HKUDS/RAG-Anything/HEAD/raganything/processor.py
Generate consistent documentation across files
from __future__ import annotations import logging import time from dataclasses import dataclass, field from typing import Any, Dict, List, Optional import threading logger = logging.getLogger(__name__) @dataclass class ProcessingEvent: event_type: str timestamp: float = field(default_factory=time.time) ...
--- +++ @@ -1,3 +1,24 @@+""" +Processing callbacks and event system for RAGAnything. + +Provides a lightweight publish-subscribe mechanism that lets users hook +into every stage of the document processing pipeline — parsing, text +insertion, multimodal processing, and querying. + +Usage:: + + from raganything.callba...
https://raw.githubusercontent.com/HKUDS/RAG-Anything/HEAD/raganything/callbacks.py
Improve my code by adding docstrings
import base64 from typing import Dict, List, Any, Tuple from pathlib import Path from lightrag.utils import logger def separate_content( content_list: List[Dict[str, Any]], ) -> Tuple[str, List[Dict[str, Any]]]: text_parts = [] multimodal_items = [] for item in content_list: content_type = i...
--- +++ @@ -1,3 +1,8 @@+""" +Utility functions for RAGAnything + +Contains helper functions for content separation, text insertion, and other utilities +""" import base64 from typing import Dict, List, Any, Tuple @@ -8,6 +13,15 @@ def separate_content( content_list: List[Dict[str, Any]], ) -> Tuple[str, List[...
https://raw.githubusercontent.com/HKUDS/RAG-Anything/HEAD/raganything/utils.py
Annotate my code with docstrings
import json import hashlib import re import time from typing import Dict, List, Any from pathlib import Path from lightrag import QueryParam from lightrag.utils import always_get_an_event_loop from raganything.prompt import PROMPTS from raganything.utils import ( get_processor_for_type, encode_image_to_base64,...
--- +++ @@ -1,3 +1,8 @@+""" +Query functionality for RAGAnything + +Contains all query-related methods for both text and multimodal queries +""" import json import hashlib @@ -16,10 +21,23 @@ class QueryMixin: + """QueryMixin class containing query functionality for RAGAnything""" def _generate_multim...
https://raw.githubusercontent.com/HKUDS/RAG-Anything/HEAD/raganything/query.py
Help me comply with documentation standards
import asyncio import logging from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path from typing import Dict, List, Optional, Tuple from dataclasses import dataclass import time from tqdm import tqdm from .parser import get_parser @dataclass class BatchProcessingResult: succe...
--- +++ @@ -1,3 +1,9 @@+""" +Batch and Parallel Document Parsing + +This module provides functionality for processing multiple documents in parallel, +with progress reporting and error handling. +""" import asyncio import logging @@ -14,6 +20,7 @@ @dataclass class BatchProcessingResult: + """Result of batch p...
https://raw.githubusercontent.com/HKUDS/RAG-Anything/HEAD/raganything/batch_parser.py
Create documentation for each function signature
import re import json import time import base64 from typing import Dict, Any, Tuple, List from pathlib import Path from dataclasses import dataclass from lightrag.utils import ( logger, compute_mdhash_id, ) from lightrag.lightrag import LightRAG from dataclasses import asdict from lightrag.kg.shared_storage i...
--- +++ @@ -1,3 +1,13 @@+""" +Specialized processors for different modalities + +Includes: +- ContextExtractor: Universal context extraction for multimodal content +- ImageModalProcessor: Specialized processor for image content +- TableModalProcessor: Specialized processor for table content +- EquationModalProcessor: S...
https://raw.githubusercontent.com/HKUDS/RAG-Anything/HEAD/raganything/modalprocessors.py
Improve documentation using docstrings
import os import logging from pathlib import Path from typing import Dict, Any, Optional from dataclasses import dataclass import tempfile import subprocess try: import markdown MARKDOWN_AVAILABLE = True except ImportError: MARKDOWN_AVAILABLE = False try: from weasyprint import HTML WEASYPRINT_...
--- +++ @@ -1,3 +1,14 @@+""" +Enhanced Markdown to PDF Conversion + +This module provides improved Markdown to PDF conversion with: +- Better formatting and styling +- Image support +- Table support +- Code syntax highlighting +- Custom templates +- Multiple output formats +""" import os import logging @@ -33,6 +44...
https://raw.githubusercontent.com/HKUDS/RAG-Anything/HEAD/raganything/enhanced_markdown.py
Insert docstrings into my code
import asyncio import logging from pathlib import Path from typing import List, Dict, Any, Optional, TYPE_CHECKING import time from .batch_parser import BatchParser, BatchProcessingResult if TYPE_CHECKING: from .config import RAGAnythingConfig class BatchMixin: # Type hints for mixin attributes (will be a...
--- +++ @@ -1,3 +1,8 @@+""" +Batch processing functionality for RAGAnything + +Contains methods for processing multiple documents in batch mode +""" import asyncio import logging @@ -12,6 +17,7 @@ class BatchMixin: + """BatchMixin class containing batch processing functionality for RAGAnything""" # Ty...
https://raw.githubusercontent.com/HKUDS/RAG-Anything/HEAD/raganything/batch.py
Create documentation for each function signature
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,24 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Transformations for 3D coordinates. + +This Module contains objects for representing Vectors (Vecs), Rotation Matrices +(Rots) and proper Rigid transformation (Rigids). These are repr...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/r3.py
Generate docstrings for exported functions
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Utilities for extracting identifiers from MSA sequence descriptions.""" import dataclasses import re @@ -52,6 +53,19 @@ def _parse_sequence_identifier(msa_sequence_identifier: ...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/data/msa_identifiers.py
Insert docstrings into my code
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Helper methods for the AlphaFold Colab notebook.""" from typing import AbstractSet, Any, Mapping, Optional, Sequence from alphafold.common import residue_constants @@ -23,6 +24,7 @...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/notebooks/notebook_utils.py
Add inline docstrings for readability
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,26 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Ops for all atom representations. + +Generally we employ two different representations for all atom coordinates, +one is atom37 where each heavy atom corresponds to a given position i...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/all_atom.py
Fill in missing docstrings in my code
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Code for constructing the model.""" from typing import Any, Mapping, Optional @@ -30,6 +31,7 @@ def get_confidence_metrics( prediction_result: Mapping[str, Any], multimer_mod...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/model.py
Write docstrings for algorithm functions
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Code to generate processed features.""" import copy from typing import List, Mapping, Tuple @@ -28,6 +29,7 @@ config: ml_collections.ConfigDict, num_res: int, ) -> Tuple[...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/features.py
Add structured docstrings to improve clarity
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Datasets consisting of proteins.""" from typing import Dict, Mapping, Optional, Sequence from alphafold.model.tf import protein_features import numpy as np @@ -21,6 +22,7 @@ def...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/tf/proteins_dataset.py
Add docstrings explaining edge cases
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""A collection of common Haiku modules for use in protein folding.""" import numbers from typing import Sequence, Union @@ -28,6 +29,7 @@ def get_initializer_scale(initializer_na...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/common_modules.py
Add professional docstrings to my codebase
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""A Python wrapper for hmmsearch - search profile against a sequence db.""" import os import subprocess @@ -26,6 +27,7 @@ class Hmmsearch(object): + """Python wrapper of the hmm...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/data/tools/hmmsearch.py
Document functions with detailed explanations
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -11,6 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Common utilities for data pipeline tools.""" import contextlib import shutil import tempfile @@ -22,6 +23,7...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/data/tools/utils.py
Expand my code with proper documentation strings
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Feature pre-processing input pipeline for AlphaFold.""" from alphafold.model.tf import data_transforms from alphafold.model.tf import shape_placeholders @@ -31,6 +32,7 @@ def n...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/tf/input_pipeline.py
Write proper docstrings for these functions
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -11,6 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Model config.""" import copy import functools @@ -855,6 +856,7 @@ class EmbeddingsAndEvoformer(base_co...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/config.py
Document my Python code with docstrings
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Functions for getting templates and calculating template features.""" import abc import dataclasses import datetime @@ -32,43 +33,56 @@ class Error(Exception): + """Base class ...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/data/templates.py
Write docstrings including parameters and return values
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -11,6 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Vec3Array Class.""" from __future__ import annotations @@ -30,6 +31,16 @@ @struct_of_array.StructOfArra...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/geometry/vector.py
Replace inline comments with docstrings
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Functions for building the features for the AlphaFold multimer model.""" import collections import contextlib @@ -46,6 +47,7 @@ sequences: Sequence[str], descriptions: Seq...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/data/pipeline_multimer.py
Document all endpoints with docstrings
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Full AlphaFold protein structure prediction script.""" import enum import json import os @@ -275,6 +276,7 @@ def _jnp_to_np(output: Dict[str, Any]) -> Dict[str, Any]: + """Recu...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/run_alphafold.py
Add docstrings including usage examples
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Functions for building the input features for the AlphaFold model.""" import os from typing import Any, Mapping, MutableMapping, Optional, Sequence, Union @@ -36,6 +37,7 @@ def mak...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/data/pipeline.py
Add standardized docstrings across the file
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Library to run Jackhmmer from Python.""" from concurrent import futures import glob @@ -28,6 +29,7 @@ class Jackhmmer: + """Python wrapper of the Jackhmmer binary.""" def...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/data/tools/jackhmmer.py
Document all public functions with docstrings
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Pairing logic for multimer data pipeline.""" import collections import dataclasses @@ -68,6 +69,15 @@ @dataclasses.dataclass(frozen=True, kw_only=True, slots=True) class MSAStat...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/data/msa_pairing.py
Include argument descriptions in docstrings
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""A Python wrapper for hmmbuild - construct HMM profiles from MSA.""" import os import re @@ -24,15 +25,50 @@ class Hmmbuild(object): + """Python wrapper of the hmmbuild binary....
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/data/tools/hmmbuild.py
Help me comply with documentation standards
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Convenience functions for reading data.""" import io import os @@ -22,10 +23,11 @@ def get_model_haiku_params(model_name: str, data_dir: str) -> hk.Params: + """Get the Haiku ...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/data.py
Generate descriptive docstrings automatically
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Function to stack repeats of a layer function without shared parameters.""" import collections import contextlib @@ -67,8 +68,10 @@ class _LayerStack(hk.Module): + """Module t...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/layer_stack.py
Add docstrings to improve readability
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Functions for processing confidence metrics.""" import json from typing import Dict, Optional, Tuple @@ -27,6 +28,14 @@ def compute_plddt(logits: np.ndarray) -> np.ndarray: + ...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/common/confidence.py
Add docstrings explaining edge cases
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Specialized mapping functions.""" import functools import inspect @@ -33,6 +34,7 @@ def _set_docstring(docstr: str) -> Callable[[T], T]: + """Decorator for setting the docstri...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/mapping.py
Add inline docstrings for readability
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Modules and utilities for the structure module in the multimer system.""" import functools import numbers @@ -37,6 +38,7 @@ def squared_difference(x: jnp.ndarray, y: jnp.ndarra...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/folding_multimer.py
Write docstrings for utility functions
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Cleans up a PDB file using pdbfixer in preparation for OpenMM simulations. + +fix_pdb uses a third-party tool. We also support fixing some additional edge +cases like removing chains ...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/relax/cleanup.py
Add inline docstrings for readability
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Library to run HHblits from Python.""" import glob import os @@ -29,6 +30,7 @@ class HHBlits: + """Python wrapper of the HHblits binary.""" def __init__( self, @@ ...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/data/tools/hhblits.py
Write docstrings for backend logic
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Library to run HHsearch from Python.""" import glob import os @@ -26,6 +27,7 @@ class HHSearch: + """Python wrapper of the HHsearch binary.""" def __init__( self, ...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/data/tools/hhsearch.py
Add docstrings that explain purpose and usage
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""A collection of JAX utility functions for use in protein folding.""" import collections import contextlib @@ -27,6 +28,7 @@ def stable_softmax(logits: jax.Array) -> jax.Array: ...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/utils.py
Add docstrings to improve collaboration
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Constants used in AlphaFold.""" import collections import functools @@ -414,6 +415,17 @@ Mapping[str, List[Bond]], Mapping[str, List[BondAngle]], ]: + """Load stereo_che...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/common/residue_constants.py
Create structured documentation for my script
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Parses the mmCIF file format.""" import collections import dataclasses import functools @@ -68,6 +69,21 @@ @dataclasses.dataclass(frozen=True) class MmcifObject: + """Representa...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/data/mmcif_parsing.py
Write docstrings that follow conventions
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Data for AlphaFold.""" from alphafold.common import residue_constants from alphafold.model.tf import shape_helpers @@ -65,6 +66,7 @@ def curry1(f): + """Supply all arguments b...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/tf/data_transforms.py
Document all public functions with docstrings
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Docker launch script for Alphafold docker image.""" import os import pathlib @@ -130,6 +131,7 @@ def _create_mount(mount_name: str, path: str) -> Tuple[types.Mount, str]: + ""...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/docker/run_docker.py
Generate docstrings for script automation
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -11,6 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Rot3Array Matrix Class.""" from __future__ import annotations @@ -30,6 +31,7 @@ @struct_of_array.Struct...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/geometry/rotation_matrix.py
Add docstrings to existing functions
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,10 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Modules and code used in the core part of AlphaFold. + +The structure generation code is in 'folding.py'. +""" import functools from alphafold.common import residue_constants from ...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/modules.py
Add docstrings including usage examples
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Modules and utilities for the structure module.""" import functools from typing import Dict @@ -34,6 +35,17 @@ class InvariantPointAttention(hk.Module): + """Invariant Point a...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/folding.py
Write docstrings for this repository
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Functions for parsing various file formats.""" import collections import dataclasses import itertools @@ -27,6 +28,7 @@ @dataclasses.dataclass(frozen=True) class Msa: + """Class...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/data/parsers.py
Improve my code by adding docstrings
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Contains descriptions of various protein features.""" import enum from typing import Dict, Optional, Sequence, Tuple, Union from alphafold.common import residue_constants @@ -74,6 +...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/tf/protein_features.py
Document functions with clear intent
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -11,6 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Rigid3Array Transformations represented by a Matrix and a Vector.""" from __future__ import annotations @...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/geometry/rigid_matrix_vector.py
Auto-generate documentation strings for this file
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""A Python wrapper for Kalign.""" import os import subprocess from typing import Sequence @@ -23,6 +24,7 @@ def _to_a3m(sequences: Sequence[str]) -> str: + """Converts sequences ...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/data/tools/kalign.py
Add docstrings for utility scripts
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,10 +12,23 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Utilities for dealing with shapes of TensorFlow tensors.""" import tensorflow.compat.v1 as tf def shape_list(x): + """Return list of dimensions of a tensor, statically where p...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/tf/shape_helpers.py
Write docstrings including parameters and return values
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -11,6 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Ops for all atom representations.""" from typing import Dict, Optional @@ -27,6 +28,14 @@ def _make_c...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/all_atom_multimer.py
Add professional docstrings to my codebase
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -11,6 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Class decorator to represent (nested) struct of arrays.""" import dataclasses @@ -30,6 +31,7 @@ @proper...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/geometry/struct_of_array.py
Write clean docstrings for readability
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Restrained Amber Minimization of a structure.""" import io import time @@ -37,6 +38,7 @@ def will_restrain(atom: openmm_app.Atom, rset: str) -> bool: + """Returns True if the ...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/relax/amber_minimize.py
Document my Python code with docstrings
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Utils for minimization.""" import io from alphafold.common import residue_constants from Bio import PDB @@ -19,6 +20,17 @@ def overwrite_b_factors(pdb_str: str, bfactors: np.nda...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/relax/utils.py
Generate docstrings for exported functions
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Feature processing logic for multimer data pipeline.""" from typing import Iterable, List, MutableMapping @@ -57,6 +58,7 @@ def _is_homomer_or_monomer(chains: Iterable[pipelin...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/data/feature_processing.py
Write docstrings for utility functions
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,24 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Quaternion geometry modules. + +This introduces a representation of coordinate frames that is based around a +‘QuatAffine’ object. This object describes an array of coordinate frames....
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/quat_affine.py
Document functions with detailed explanations
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Amber relaxation.""" from typing import Any, Dict, Sequence, Tuple from alphafold.common import protein from alphafold.relax import amber_minimize @@ -20,6 +21,7 @@ class AmberR...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/relax/relax.py
Create documentation for each function signature
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Config for the protein folding model and experiment.""" from collections.abc import Mapping import contextlib @@ -27,6 +28,7 @@ def _strip_optional(t: type[Any]) -> type[Any]: ...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/base_config.py
Add docstrings with type hints explained
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Protein data type.""" import collections import dataclasses @@ -62,6 +63,7 @@ @dataclasses.dataclass(frozen=True) class Protein: + """Protein structure representation.""" ...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/common/protein.py
Create docstrings for each class method
# Copyright 2021 DeepMind Technologies Limited # # 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 applicable law or agr...
--- +++ @@ -12,6 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Core modules, which have been refactored in AlphaFold-Multimer. + +The main difference is that MSA sampling pipeline is moved inside the JAX model +for easier implementation of recycl...
https://raw.githubusercontent.com/google-deepmind/alphafold/HEAD/alphafold/model/modules_multimer.py
Insert docstrings into my code
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -13,6 +13,11 @@ # limitations under the License. # ============================================================================== +"""Simple, end-to-end, LeNet-5-like convolutional MNIST model example. +This should achieve a test error of 0.7%. Please keep this model as simple and +linear as possible, it ...
https://raw.githubusercontent.com/davidsandberg/facenet/HEAD/tmp/mnist_center_loss.py
Add docstrings that explain logic
# MIT License # # Copyright (c) 2016 David Sandberg # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, me...
--- +++ @@ -1,3 +1,5 @@+"""Functions for building the face recognition network. +""" # MIT License # # Copyright (c) 2016 David Sandberg @@ -58,6 +60,14 @@ return affine1 def l2_loss(tensor, weight=1.0, scope=None): + """Define a L2Loss, useful for regularize, i.e. weight decay. + Args: + tensor: ...
https://raw.githubusercontent.com/davidsandberg/facenet/HEAD/tmp/network.py
Add docstrings explaining edge cases
# MIT License # # Copyright (c) 2016 David Sandberg # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, me...
--- +++ @@ -1,3 +1,6 @@+"""Training a face recognizer with TensorFlow based on the FaceNet paper +FaceNet: A Unified Embedding for Face Recognition and Clustering: http://arxiv.org/abs/1503.03832 +""" # MIT License # # Copyright (c) 2016 David Sandberg @@ -266,6 +269,8 @@ return step def select_triplets(em...
https://raw.githubusercontent.com/davidsandberg/facenet/HEAD/src/train_tripletloss.py
Include argument descriptions in docstrings
# MIT License # # Copyright (c) 2016 David Sandberg # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, me...
--- +++ @@ -1,3 +1,6 @@+"""Visualize individual feature channels and their combinations to explore the space of patterns learned by the neural network +Based on http://nbviewer.jupyter.org/github/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb +""" # MIT License # # Copyrig...
https://raw.githubusercontent.com/davidsandberg/facenet/HEAD/tmp/visualize.py
Create documentation strings for testing functions
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
--- +++ @@ -13,6 +13,12 @@ # limitations under the License. # ============================================================================== +"""Contains the definition of the Inception Resnet V1 architecture. +As described in http://arxiv.org/abs/1602.07261. + Inception-v4, Inception-ResNet and the Impact of Resid...
https://raw.githubusercontent.com/davidsandberg/facenet/HEAD/src/models/inception_resnet_v1.py
Generate descriptive docstrings automatically
# MIT License # # Copyright (c) 2016 David Sandberg # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, me...
--- +++ @@ -1,3 +1,6 @@+""" Tensorflow implementation of the face detection / alignment algorithm found at +https://github.com/kpzhang93/MTCNN_face_detection_alignment +""" # MIT License # # Copyright (c) 2016 David Sandberg @@ -32,6 +35,7 @@ import os def layer(op): + """Decorator for composable network laye...
https://raw.githubusercontent.com/davidsandberg/facenet/HEAD/src/align/detect_face.py
Add docstrings to incomplete code
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -13,6 +13,11 @@ # limitations under the License. # ============================================================================== +"""Simple, end-to-end, LeNet-5-like convolutional MNIST model example. +This should achieve a test error of 0.7%. Please keep this model as simple and +linear as possible, it ...
https://raw.githubusercontent.com/davidsandberg/facenet/HEAD/tmp/mnist_noise_labels.py
Create docstrings for each class method
# Copyright 2015-2016 Carnegie Mellon University # # 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 applicable law or ag...
--- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Module for dlib-based alignment.""" # NOTE: This file has been copied from the openface project. # https://github.com/cmusatyalab/openface/blob/master/openface/align_dlib.py @@ -6...
https://raw.githubusercontent.com/davidsandberg/facenet/HEAD/tmp/align_dlib.py
Add docstrings for better understanding
import tensorflow as tf import numpy as np import importlib import argparse import facenet import os import math def face_distance(face_encodings, face_to_compare): import numpy as np if len(face_encodings) == 0: return np.empty((0)) #return 1/np.linalg.norm(face_encodings - face_to_compare, axis=1...
--- +++ @@ -1,3 +1,4 @@+""" Face Cluster """ import tensorflow as tf import numpy as np import importlib @@ -6,6 +7,13 @@ import os import math def face_distance(face_encodings, face_to_compare): + """ + Given a list of face encodings, compare them to a known face encoding and get a euclidean distance + f...
https://raw.githubusercontent.com/davidsandberg/facenet/HEAD/contributed/clustering.py
Add docstrings for internal functions
# MIT License # # Copyright (c) 2016 David Sandberg # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, me...
--- +++ @@ -1,3 +1,5 @@+"""Functions for building the face recognition network. +""" # MIT License # # Copyright (c) 2016 David Sandberg @@ -40,6 +42,16 @@ from six import iteritems def triplet_loss(anchor, positive, negative, alpha): + """Calculate the triplet loss according to the FaceNet paper + + A...
https://raw.githubusercontent.com/davidsandberg/facenet/HEAD/src/facenet.py
Add docstrings to clarify complex logic
# boilerplate code import numpy as np from functools import partial import PIL.Image import tensorflow as tf import matplotlib.pyplot as plt import urllib2 import os import zipfile def main(): # download pre-trained model by running the command below in a shell # wget https://storage.googleapis.com/download....
--- +++ @@ -51,6 +51,7 @@ # Helper functions for TF Graph visualization #pylint: disable=unused-variable def strip_consts(graph_def, max_const_size=32): + """Strip large constant values from graph_def.""" strip_def = tf.GraphDef() for n0 in graph_def.node: n = strip_d...
https://raw.githubusercontent.com/davidsandberg/facenet/HEAD/tmp/deepdream.py
Generate documentation strings for clarity
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
--- +++ @@ -13,6 +13,12 @@ # limitations under the License. # ============================================================================== +"""Contains the definition of the Inception Resnet V2 architecture. +As described in http://arxiv.org/abs/1602.07261. + Inception-v4, Inception-ResNet and the Impact of Resid...
https://raw.githubusercontent.com/davidsandberg/facenet/HEAD/src/models/inception_resnet_v2.py
Write docstrings for data processing functions
#from __future__ import print_function, division import torch import numpy as np from sklearn.preprocessing import StandardScaler import random from PIL import Image import torch.utils.data as data import os import os.path def make_dataset(image_list, labels): if labels: len_ = len(image_list) images...
--- +++ @@ -47,6 +47,25 @@ class ImageList(object): + """A generic data loader where the images are arranged in this way: :: + root/dog/xxx.png + root/dog/xxy.png + root/dog/xxz.png + root/cat/123.png + root/cat/nsdf3.png + root/cat/asd932_.png + Args: + root (...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/CSG/utils/preprocess/data_list.py
Generate missing documentation strings
#!/usr/bin/env python3.6 __author__ = "Chang Liu" __email__ = "changliu@microsoft.com" import sys, os from warnings import warn import torch as tc import torch.nn as nn import torchvision as tv from . import backbone from . import mlp sys.path.append('..') from distr import tensorify, is_same_tensor, wrap4_multi_batch...
--- +++ @@ -1,4 +1,11 @@ #!/usr/bin/env python3.6 +''' CNN Architecture + +Based on the architecture in MDD <https://github.com/thuml/MDD>, +and leverage the repositories of `domainbed` <https://github.com/facebookresearch/DomainBed> +and `pytorch_GAN_zoo` <https://github.com/facebookresearch/pytorch_GAN_zoo>. +Archite...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/CSG/arch/cnn.py
Generate docstrings with examples
import torch import logging from espnet.asr.asr_utils import add_results_to_json import argparse import numpy as np import collections import json def str2bool(str): return True if str.lower() == 'true' else False def setup_logging(verbose=1): if verbose > 0: logging.basicConfig( level=lo...
--- +++ @@ -35,6 +35,10 @@ # Load and save def load_pretrained_model(model, model_path, modules_to_load=None, exclude_modules=None): + ''' + load_pretrained_model(model=model, model_path="", + modules_to_load=None, exclude_modules="") + ''' model_dict = torch.load(model_...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/ASR/CMatch/utils.py
Add detailed documentation for each class
#!/usr/bin/env python3.6 import math import torch as tc from .utils import edic from .base import Distr __author__ = "Chang Liu" __version__ = "1.0.1" __email__ = "changliu@microsoft.com" def elbo(p_joint: Distr, q_cond: Distr, obs: edic, n_mc: int=10, repar: bool=True) -> tc.Tensor: # [shape_bat] -> [shape_bat] ...
--- +++ @@ -1,4 +1,11 @@ #!/usr/bin/env python3.6 +'''Probabilistic Programming Package. + +The prototype is distributions, which can be a conditional one with +functions for parameters to define the dependency. Distribution +multiplication is implemented, as well as the mean, expectation, +sampling with backprop capab...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/CSG/distr/tools.py
Create structured documentation for my script
import collections from espnet.nets.pytorch_backend.e2e_asr_transformer import * from espnet.nets.pytorch_backend.e2e_asr_transformer import E2E as SpeechTransformer from espnet.nets.pytorch_backend.transformer.encoder import * from espnet.nets.pytorch_backend.transformer.decoder import * from espnet.nets.pytorch_backe...
--- +++ @@ -150,6 +150,14 @@ ), ) def forward(self, xs, masks, return_repr=False): + """Encode input sequence. + Args: + xs (torch.Tensor): Input tensor (#batch, time, idim). + masks (torch.Tensor): Mask tensor (#batch, time). + Returns: + ...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/ASR/CMatch/e2e_asr_udatransformer.py
Fully document this Python code with docstrings
#!/usr/bin/env python3.6 import math import torch as tc from .utils import edic, edicify, expand_front, fargnames, fedic, swap_dim_ranges, tcsizeify, tcsize_broadcast, tcsize_div, tensorify __author__ = "Chang Liu" __version__ = "1.0.1" __email__ = "changliu@microsoft.com" class Distr: default_device = None ...
--- +++ @@ -1,4 +1,11 @@ #!/usr/bin/env python3.6 +'''Probabilistic Programming Package. + +The prototype is distributions, which can be a conditional one with +functions for parameters to define the dependency. Distribution +multiplication is implemented, as well as the mean, expectation, +sampling with backprop capab...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/CSG/distr/base.py
Generate missing documentation strings
import torch import numpy as np ''' Borrowed and modified from neural_sp: https://github.com/hirofumi0810/neural_sp/blob/154d9248b54e3888797fd81f93adc4700a75509a/neural_sp/models/seq2seq/decoders/ctc.py#L625 ''' LOG_0 = -1e10 LOG_1 = 0 def np2tensor(array, device=None): tensor = torch.from_numpy(array).to(devi...
--- +++ @@ -10,9 +10,23 @@ LOG_1 = 0 def np2tensor(array, device=None): + """Convert form np.ndarray to torch.Tensor. + Args: + array (np.ndarray): A tensor of any sizes + Returns: + tensor (torch.Tensor): + """ tensor = torch.from_numpy(array).to(device) return tensor def pad_li...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/ASR/CMatch/ctc_aligner.py
Document this script properly
# Copyright 2019 Shigeki Karita # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) from argparse import Namespace from distutils.util import strtobool import logging import math import numpy import torch from espnet.nets.pytorch_backend.e2e_asr_transformer import * from espnet.nets.pytorch_backend.transfo...
--- +++ @@ -1,6 +1,7 @@ # Copyright 2019 Shigeki Karita # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) +"""Transformer speech recognition model (pytorch).""" from argparse import Namespace from distutils.util import strtobool @@ -36,6 +37,7 @@ class SimAdapter(MultiHeadedAttention): def __ini...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/ASR/Adapter/e2e_asr_adaptertransformer.py
Add docstrings to my Python code
#!/usr/bin/env python3.6 import sys import math import torch as tc sys.path.append('..') from distr import Distr, edic __author__ = "Chang Liu" __email__ = "changliu@microsoft.com" def elbo_z2xy(p_zx: Distr, p_y1z: Distr, q_z1x: Distr, obs_xy: edic, n_mc: int=0, wlogpi: float=1., repar: bool=True) -> tc.Tensor: i...
--- +++ @@ -1,4 +1,7 @@ #!/usr/bin/env python3.6 +""" Modification to the `distr` package for the structure of the + Causal Semantic Generative model. +""" import sys import math import torch as tc @@ -9,6 +12,9 @@ __email__ = "changliu@microsoft.com" def elbo_z2xy(p_zx: Distr, p_y1z: Distr, q_z1x: Distr, obs_...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/CSG/methods/xdistr.py
Add missing documentation to my Python functions
import torch import logging from espnet.asr.asr_utils import add_results_to_json import argparse import numpy as np import collections import json def load_head_from_pretrained_model(model, model_path): model_dict = torch.load(model_path, map_location=lambda storage, loc: storage) if "model" in model_dict.key...
--- +++ @@ -20,6 +20,9 @@ model.load_state_dict(dst_state) def load_adapter_from_pretrained_model(model, model_path, src_adapter, tgt_adapter): + ''' + src_adapter, tgt_adapter: str, names of the source and target adapters to load parameters + ''' model_dict = torch.load(model_path, map_location=la...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/ASR/Adapter/utils.py
Write docstrings for backend logic
#!/usr/bin/env python3.6 import torch as tc from functools import partial, wraps from inspect import signature __author__ = "Chang Liu" __version__ = "1.0.1" __email__ = "changliu@microsoft.com" # enhanced dictionary class edic(dict): def __and__(self, other): return edic({k:other[k] for k in set(self) & set(oth...
--- +++ @@ -1,4 +1,11 @@ #!/usr/bin/env python3.6 +'''Probabilistic Programming Package. + +The prototype is distributions, which can be a conditional one with +functions for parameters to define the dependency. Distribution +multiplication is implemented, as well as the mean, expectation, +sampling with backprop capab...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/CSG/distr/utils.py
Write docstrings describing each step
#!/usr/bin/env python3.6 import sys, os import json import torch as tc import torch.nn as nn sys.path.append('..') from distr import tensorify, is_same_tensor, wrap4_multi_batchdims __author__ = "Chang Liu" __email__ = "changliu@microsoft.com" def init_linear(nnseq, wmean, wstd, bval): for mod in nnseq: i...
--- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3.6 +'''Multi-Layer Perceptron Architecture. + +For causal discriminative model and the corresponding generative model. +''' import sys, os import json import torch as tc @@ -45,6 +49,11 @@ class MLPsvy1x(MLPBase): def __init__(self, dim_x, dims_postx2prev, dim_v, di...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/CSG/arch/mlp.py
Add documentation for all methods
import numpy as np from sklearn import svm def proxy_a_distance(source_X, target_X, verbose=False): nb_source = np.shape(source_X)[0] nb_target = np.shape(target_X)[0] if verbose: print('PAD on', (nb_source, nb_target), 'examples') C_list = np.logspace(-5, 4, 10) half_source, half_target...
--- +++ @@ -2,6 +2,9 @@ from sklearn import svm def proxy_a_distance(source_X, target_X, verbose=False): + """ + Compute the Proxy-A-Distance of a source/target representation + """ nb_source = np.shape(source_X)[0] nb_target = np.shape(target_X)[0] @@ -37,6 +40,9 @@ def estimate_mu(_X1, _Y1...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/DeepMEDA/dynamic_factor.py
Generate docstrings for exported functions
from __future__ import absolute_import import random import cv2 import keras import numpy as np from evaldnn.utils import common class ImageNetValData(): class ImageNetValDataX(): def __init__(self, dir, filenames, fashion, size, transform): self._dir = dir self._filenames = ...
--- +++ @@ -1,3 +1,6 @@+""" +Provides some useful utils for keras model evaluation. +""" from __future__ import absolute_import @@ -11,6 +14,31 @@ class ImageNetValData(): + """ Class for loading and preprocessing imagenet validation set. + + One can download the imagenet validation set at http://image-n...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/ReMoS/CV_adv/nc_prune/coverage/utils/keras.py
Create documentation strings for testing functions
from __future__ import absolute_import import random import warnings import numpy as np import tensorflow as tf from tensorflow.contrib.slim.nets import inception from tensorflow.contrib.slim.nets import nasnet from tensorflow.contrib.slim.nets import pnasnet from tensorflow.contrib.slim.nets import resnet_v1 from t...
--- +++ @@ -1,3 +1,6 @@+""" +Provides some useful utils for tensorflow model evaluation. +""" from __future__ import absolute_import @@ -17,6 +20,36 @@ class ImageNetValData(): + """ Class for loading and preprocessing imagenet validation set. + + One can download the imagenet validation set at http://im...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/ReMoS/CV_adv/nc_prune/coverage/utils/tensorflow.py
Write docstrings for backend logic
from __future__ import absolute_import import random import PIL import numpy as np import torch import torchvision from evaldnn.utils import common class ImageNetValDataset(torch.utils.data.Dataset): mean = (0.485, 0.456, 0.406) std = (0.229, 0.224, 0.225) def __init__(self, resize_size, center_crop...
--- +++ @@ -1,3 +1,6 @@+""" +Provides some useful utils for torch model evaluation. +""" from __future__ import absolute_import @@ -12,6 +15,30 @@ class ImageNetValDataset(torch.utils.data.Dataset): + """ Class for loading and preprocessing imagenet validation set. + + One can download the imagenet valid...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/ReMoS/CV_adv/nc_prune/coverage/utils/pytorch.py
Add docstrings with type hints explained
import torch import torch.nn as nn from torch.utils.model_zoo import load_url as load_state_dict_from_url from pdb import set_trace as st __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d', 'wide_resnet50_2', 'wide_resnet101_2'...
--- +++ @@ -22,11 +22,13 @@ def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): + """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation) def conv1x1(in...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/ReMoS/CV_adv/model/fe_resnet.py
Add return value explanations in docstrings
from __future__ import absolute_import import numpy as np from numba import njit, prange import copy from .utils import common from pdb import set_trace as st class MyNeuronCoverage: def __init__(self, threshold=0.5): self._threshold = threshold self._layer_neuron_id_to_global_neuron_id = {} ...
--- +++ @@ -1,3 +1,6 @@+""" +Provides a class for model neuron coverage evaluation. +""" from __future__ import absolute_import @@ -9,6 +12,18 @@ from pdb import set_trace as st class MyNeuronCoverage: + """ Class for model neuron coverage evaluation. + + Based on the outputs of the intermediate layers, u...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/ReMoS/CV_backdoor/remos/coverage/my_neuron_coverage.py
Improve documentation using docstrings
from __future__ import absolute_import import numpy as np from numba import njit, prange from .utils import common from .my_neuron_coverage import MyNeuronCoverage from pdb import set_trace as st class TopKNeuronCoverage(MyNeuronCoverage): def __init__(self, k=5): super(TopKNeuronCoverage, self).__init_...
--- +++ @@ -1,3 +1,6 @@+""" +Provides a class for model neuron coverage evaluation. +""" from __future__ import absolute_import @@ -19,6 +22,29 @@ @staticmethod @njit(parallel=True) def _calc_1(intermediate_layer_output, features_index, threshold): + """Calculate the mean of each output from e...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/ReMoS/CV_adv/nc_prune/coverage/top_k_coverage.py
Provide docstrings following PEP 257
from __future__ import absolute_import import numpy as np from numba import njit, prange import copy from .utils import common from pdb import set_trace as st class MyNeuronCoverage: def __init__(self, threshold=0.5): self._threshold = threshold self._layer_neuron_id_to_global_neuron_id = {} ...
--- +++ @@ -1,3 +1,6 @@+""" +Provides a class for model neuron coverage evaluation. +""" from __future__ import absolute_import @@ -9,6 +12,18 @@ from pdb import set_trace as st class MyNeuronCoverage: + """ Class for model neuron coverage evaluation. + + Based on the outputs of the intermediate layers, u...
https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/ReMoS/CV_adv/nc_prune/coverage/my_neuron_coverage.py