python_code
stringlengths
0
290k
repo_name
stringclasses
30 values
file_path
stringlengths
6
125
#!/usr/bin/env python # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unles...
accelerate-main
src/accelerate/commands/config/cluster.py
#!/usr/bin/env python # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unles...
accelerate-main
src/accelerate/commands/config/sagemaker.py
#!/usr/bin/env python # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unles...
accelerate-main
src/accelerate/commands/config/config_utils.py
# Copyright 2022 The HuggingFace Team and Brian Chao. 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 requir...
accelerate-main
src/accelerate/commands/menu/selection_menu.py
from .selection_menu import BulletMenu
accelerate-main
src/accelerate/commands/menu/__init__.py
# Copyright 2022 The HuggingFace Team and Brian Chao. 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 requir...
accelerate-main
src/accelerate/commands/menu/keymap.py
# Copyright 2022 The HuggingFace Team and Brian Chao. 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 requir...
accelerate-main
src/accelerate/commands/menu/input.py
# Copyright 2022 The HuggingFace Team and Brian Chao. 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 requir...
accelerate-main
src/accelerate/commands/menu/helpers.py
# Copyright 2022 The HuggingFace Team and Brian Chao. 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 requir...
accelerate-main
src/accelerate/commands/menu/cursor.py
import sys from setuptools import setup, find_packages # PEP0440 compatible formatted version, see: # https://www.python.org/dev/peps/pep-0440/ # # release markers: # X.Y # X.Y.Z # For bugfix releases # # pre-release markers: # X.YaN # Alpha release # X.YbN # Beta release # X.YrcN # Release Candidate ...
adversarialnlp-master
setup.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # AdversarialNLP documentation build configuration file, created by # sphinx-quickstart on Wed Oct 24 11:35:14 2018. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in th...
adversarialnlp-master
docs/conf.py
from adversarialnlp import Adversarial from allennlp.data.dataset_readers.reading_comprehension.squad import SquadReader adversarial = Adversarial(dataset_reader=SquadReader, editor='lstm_lm', num_samples=10) examples = adversarial.generate()
adversarialnlp-master
tutorials/usage.py
#!/usr/bin/env python import logging import os import sys if os.environ.get("ALLENNLP_DEBUG"): LEVEL = logging.DEBUG else: LEVEL = logging.INFO sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__file__, os.pardir)))) logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message...
adversarialnlp-master
adversarialnlp/run.py
_MAJOR = "0" _MINOR = "1" _REVISION = "1-unreleased" VERSION_SHORT = "{0}.{1}".format(_MAJOR, _MINOR) VERSION = "{0}.{1}.{2}".format(_MAJOR, _MINOR, _REVISION)
adversarialnlp-master
adversarialnlp/version.py
from adversarialnlp.version import VERSION as __version__
adversarialnlp-master
adversarialnlp/__init__.py
from .pruner import Pruner
adversarialnlp-master
adversarialnlp/pruners/__init__.py
from allennlp.common import Registrable class Pruner(Registrable): """ ``Pruner`` is used to fil potential adversarial samples Parameters ---------- dataset_reader : ``DatasetReader`` The ``DatasetReader`` object that will be used to sample training examples. """ def __init__(self...
adversarialnlp-master
adversarialnlp/pruners/pruner.py
adversarialnlp-master
adversarialnlp/tests/__init__.py
adversarialnlp-master
adversarialnlp/tests/dataset_readers/__init__.py
# pylint: disable=no-self-use,invalid-name import pytest from allennlp.common.util import ensure_list from adversarialnlp.dataset_readers import ActivityNetCaptionsDatasetReader from adversarialnlp.tests.utils import FIXTURES_ROOT class TestActivityNetCaptionsReader(): @pytest.mark.parametrize("lazy", (True, Fal...
adversarialnlp-master
adversarialnlp/tests/dataset_readers/activitynet_captions_test.py
# pylint: disable=no-self-use,invalid-name from typing import List import pytest from allennlp.data.fields import TextField from allennlp.common.util import ensure_list from allennlp.common.testing import AllenNlpTestCase from allennlp.data import Instance, Token, Vocabulary from allennlp.data.iterators import BasicIt...
adversarialnlp-master
adversarialnlp/tests/generators/swag_generator_test.py
adversarialnlp-master
adversarialnlp/tests/generators/__init__.py
# pylint: disable=no-self-use,invalid-name from typing import List import pytest from adversarialnlp.generators.addsent.addsent_generator import AddSentGenerator from adversarialnlp.generators.addsent.squad_reader import squad_reader from adversarialnlp.common.file_utils import FIXTURES_ROOT # class GeneratorTest(Al...
adversarialnlp-master
adversarialnlp/tests/generators/addsent_generator_test.py
adversarialnlp-master
adversarialnlp/common/__init__.py
# pylint: disable=invalid-name,protected-access #!/usr/bin/env python3 # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found...
adversarialnlp-master
adversarialnlp/common/file_utils.py
from typing import Dict import argparse import logging from allennlp.commands.subcommand import Subcommand from allennlp.common.util import import_submodules from adversarialnlp import __version__ from adversarialnlp.commands.test_install import TestInstall logger = logging.getLogger(__name__) # pylint: disable=inv...
adversarialnlp-master
adversarialnlp/commands/__init__.py
""" The ``test-install`` subcommand verifies an installation by running the unit tests. .. code-block:: bash $ adversarialnlp test-install --help usage: adversarialnlp test-install [-h] [--run-all] [--include-package INCLUDE_PACKAGE] Test that installation works by running t...
adversarialnlp-master
adversarialnlp/commands/test_install.py
from .generator import Generator from .swag import SwagGenerator from .addsent import AddSentGenerator
adversarialnlp-master
adversarialnlp/generators/__init__.py
import logging from typing import Dict, Union, Iterable, List from collections import defaultdict import itertools logger = logging.getLogger(__name__) # pylint: disable=invalid-name class Generator(): r"""An abstract ``Generator`` class. A ``Generator`` takes as inputs an iterable of seeds (for examples ...
adversarialnlp-master
adversarialnlp/generators/generator.py
# Python wrapper for Stanford CoreNLP # Copyright (c) 2017 Lynten Guo, 2018 Thomas Wolf # Extracted and adapted from https://github.com/Lynten/stanford-corenlp from __future__ import print_function import glob import json import logging import os import re import socket import subprocess import sys import time impor...
adversarialnlp-master
adversarialnlp/generators/addsent/corenlp.py
from .addsent_generator import AddSentGenerator from .squad_reader import squad_reader
adversarialnlp-master
adversarialnlp/generators/addsent/__init__.py
"""Utilities for AddSent generator.""" from typing import List, Dict, Tuple, Optional class ConstituencyParse(object): """A CoreNLP constituency parse (or a node in a parse tree). Word-level constituents have |word| and |index| set and no children. Phrase-level constituents have no |word| or |index| and h...
adversarialnlp-master
adversarialnlp/generators/addsent/utils.py
import json import logging from typing import Iterator, List, Tuple from adversarialnlp.common.file_utils import download_files logger = logging.getLogger(__name__) # pylint: disable=invalid-name def squad_reader(file_path: str = None) -> Iterator[List[Tuple[str, str]]]: r""" Reads a JSON-formatted SQuAD file ...
adversarialnlp-master
adversarialnlp/generators/addsent/squad_reader.py
import logging import json import itertools from typing import Iterable, Dict, Tuple from collections import defaultdict from adversarialnlp.common.file_utils import download_files from adversarialnlp.generators import Generator from adversarialnlp.generators.addsent.rules import (ANSWER_RULES, HIGH_CONF_ALTER_RULES, ...
adversarialnlp-master
adversarialnlp/generators/addsent/addsent_generator.py
import math from adversarialnlp.generators.addsent.utils import rejoin MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] def ans_number(a, tokens, q, **kwargs): out_toks = [] seen_num = False for t in to...
adversarialnlp-master
adversarialnlp/generators/addsent/rules/answer_rules.py
from .answer_rules import ANSWER_RULES from .alteration_rules import (HIGH_CONF_ALTER_RULES, ALL_ALTER_RULES, DO_NOT_ALTER, BAD_ALTERATIONS) from .conversion_rules import CONVERSION_RULES
adversarialnlp-master
adversarialnlp/generators/addsent/rules/__init__.py
from pattern import en as patten CONST_PARSE_MACROS = { '$Noun': '$NP/$NN/$NNS/$NNP/$NNPS', '$Verb': '$VB/$VBD/$VBP/$VBZ', '$Part': '$VBN/$VG', '$Be': 'is/are/was/were', '$Do': "do/did/does/don't/didn't/doesn't", '$WHP': '$WHADJP/$WHADVP/$WHNP/$WHPP', } # Map to pattern...
adversarialnlp-master
adversarialnlp/generators/addsent/rules/conversion_rules.py
import collections import nltk nltk.download('wordnet') from nltk.corpus import wordnet as wn from nltk.stem.lancaster import LancasterStemmer STEMMER = LancasterStemmer() POS_TO_WORDNET = { 'NN': wn.NOUN, 'JJ': wn.ADJ, 'JJR': wn.ADJ, 'JJS': wn.ADJ, } def alter_special(token, **kwar...
adversarialnlp-master
adversarialnlp/generators/addsent/rules/alteration_rules.py
from .swag_generator import SwagGenerator from .activitynet_captions_reader import ActivityNetCaptionsDatasetReader
adversarialnlp-master
adversarialnlp/generators/swag/__init__.py
import re from itertools import tee from num2words import num2words def optimistic_restore(network, state_dict): mismatch = False own_state = network.state_dict() for name, param in state_dict.items(): if name not in own_state: print("Unexpected key {} in state_dict with size {}".forma...
adversarialnlp-master
adversarialnlp/generators/swag/utils.py
# pylint: disable=invalid-name,arguments-differ from typing import List, Iterable, Tuple import logging import torch from allennlp.common.util import JsonDict from allennlp.common.file_utils import cached_path from allennlp.data import Instance, Token, Vocabulary from allennlp.data.fields import TextField from allenn...
adversarialnlp-master
adversarialnlp/generators/swag/swag_generator.py
from typing import Dict import json import logging from overrides import overrides from unidecode import unidecode from allennlp.common.file_utils import cached_path from allennlp.data.dataset_readers.dataset_reader import DatasetReader from allennlp.data.fields import TextField, MetadataField from allennlp.data.insta...
adversarialnlp-master
adversarialnlp/generators/swag/activitynet_captions_reader.py
""" A wrapper around ai2s elmo LM to allow for an lm objective... """ from typing import Optional, Tuple from typing import Union, List, Dict import numpy as np import torch from allennlp.common.checks import ConfigurationError from allennlp.data import Token, Vocabulary, Instance from allennlp.data.dataset import Ba...
adversarialnlp-master
adversarialnlp/generators/swag/simple_bilm.py
from typing import Dict, List, Tuple, Union, Optional import torch import numpy as np from allennlp.common.checks import ConfigurationError from allennlp.data.vocabulary import Vocabulary from allennlp.models.model import Model from allennlp.modules.openai_transformer import OpenaiTransformer from allennlp.modules.to...
adversarialnlp-master
adversarialnlp/generators/swag/openai_transformer_model.py
# coding=utf-8 from pytorch_pretrained_bert import BertForMaskedLM,tokenization import torch import sys import csv device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model_name = 'bert-large-uncased' if 'base' in sys.argv: model_name = 'bert-base-uncased' print("using model:",model_name,file=sys.st...
bert-syntax-master
eval_bert.py
import sys from collections import * files=[("base","results/marvin_results_base.txt"),("large","results/marvin_results_large.txt")] if "with_only_prefix" in sys.argv: files += [("base_only_prefix","results/marvin_results_base_only_prefix.txt"),("large_only_prefix","results/marvin_results_large_only_prefix.txt")]...
bert-syntax-master
gen_marvin_tbl_openai_gpt.py
import sys from collections import * files=[("base","results/gulordava_results_base.txt"),("large","results/gulordava_results_large.txt")] by_model={} conditions=set() nskipped=0 for title,fname in files: lines = open(fname) results=defaultdict(Counter) by_model[title]=results skipped = set() for ...
bert-syntax-master
gen_gul_tbl.py
import sys from collections import * files=[("base","results/lgd_results_base.txt"),("large","results/lgd_results_large.txt")] if "with_only_prefix" in sys.argv: files+=[("base_only_prefix","results/lgd_results_base_only_prefix.txt"),("large_only_prefix","results/lgd_results_large_only_prefix.txt")] if "no_split"...
bert-syntax-master
gen_lgd_tbl_openai_gpt.py
''' inflect.py: correctly generate plurals, ordinals, indefinite articles; convert numbers to words Copyright (C) 2010 Paul Dyson Based upon the Perl module Lingua::EN::Inflect by Damian Conway. This program is free software: you can redistribute it and/or modify it under the terms...
bert-syntax-master
inflect.py
import sys from collections import * files=[("base","results/gulordava_results_base.txt"),("large","results/gulordava_results_large.txt")] if "with_only_prefix" in sys.argv: files+=[("base_only_prefix","results/gulordava_results_base_only_prefix.txt"),("large_only_prefix","results/gulordava_results_large_only_pref...
bert-syntax-master
gen_gul_tbl_openai_gpt.py
import csv cases_we_care_about=['1','2','3','4'] from utils import vinfl def inflect(verb): return vinfl[verb] for record in csv.DictReader(open('agr_50_mostcommon_10K.tsv','r'), delimiter='\t'): orig = record['orig_sentence'] n_i = record['n_intervening'] n_di = record['n_diff_intervening'] vind...
bert-syntax-master
make_linzen_goldberg_testset.py
# coding=utf-8 from pytorch_pretrained_bert import OpenAIGPTLMHeadModel, OpenAIGPTTokenizer, BertTokenizer import torch import sys import csv import logging import itertools logging.basicConfig(level=logging.INFO) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model_name = "openai-gpt" print("...
bert-syntax-master
eval_openai_gpt.py
# from Linzen's code repo import inflect infl_eng = inflect.engine() def gen_inflect_from_vocab(vocab_file, freq_threshold=1000): vbp = {} vbz = {} nn = {} nns = {} from_pos = {'NNS': nns, 'NN': nn, 'VBP': vbp, 'VBZ': vbz} for line in file(vocab_file): if line.startswith(' '): # emp...
bert-syntax-master
utils.py
import sys from collections import * files=[("base","results/marvin_results_base.txt"),("large","results/marvin_results_large.txt")] by_model={} conditions=set() for title,fname in files: lines = open(fname) results=defaultdict(Counter) by_model[title]=results skipped = set() for line in lines: ...
bert-syntax-master
gen_marvin_tbl.py
import sys from collections import * files=[("base","results/lgd_results_base.txt"),("large","results/lgd_results_large.txt")] by_model={} conditions=set() nskipped=0 for title,fname in files: lines = open(fname) results=defaultdict(Counter) by_model[title]=results skipped = set() for line in line...
bert-syntax-master
gen_lgd_tbl.py
# Lint as: python3 """ HuggingFace / AutoTrain Advanced """ import os from setuptools import find_packages, setup DOCLINES = __doc__.split("\n") this_directory = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(this_directory, "README.md"), encoding="utf-8") as f: LONG_DESCRIPTION = f.read() #...
autotrain-advanced-main
setup.py
import os from uuid import uuid4 from datasets import load_dataset from autotrain.dataset import AutoTrainDataset from autotrain.project import Project RANDOM_ID = str(uuid4()) DATASET = "amazon_reviews_multi" PROJECT_NAME = f"amazon_reviews_multi_{RANDOM_ID}" TASK = "text_multi_class_classification" MODEL = "bert-...
autotrain-advanced-main
examples/text_classification_multiclass.py
import os from uuid import uuid4 from datasets import load_dataset from autotrain.dataset import AutoTrainDataset from autotrain.project import Project RANDOM_ID = str(uuid4()) DATASET = "imdb" PROJECT_NAME = f"imdb_{RANDOM_ID}" TASK = "text_binary_classification" MODEL = "bert-base-uncased" USERNAME = os.environ[...
autotrain-advanced-main
examples/text_classification_binary.py
import sys from accelerate.state import PartialState from loguru import logger emojis = { "TRACE": "🔍", "DEBUG": "🐛", "INFO": "🚀", "SUCCESS": "✅", "WARNING": "⚠️", "ERROR": "❌", "CRITICAL": "🚨", } def should_log(record): return PartialState().is_main_process def emoji_filter(r...
autotrain-advanced-main
src/autotrain/logging.py
from dataclasses import dataclass from typing import Literal import gradio as gr from pydantic import BaseModel, Field from autotrain.languages import SUPPORTED_LANGUAGES from autotrain.tasks import TASKS class LoraR: TYPE = "int" MIN_VALUE = 1 MAX_VALUE = 100 DEFAULT = 16 STEP = 1 STREAMLIT...
autotrain-advanced-main
src/autotrain/params.py
import io import json import os from dataclasses import dataclass from typing import Union import requests from huggingface_hub import HfApi from autotrain import logger from autotrain.dataset import AutoTrainDataset, AutoTrainDreamboothDataset from autotrain.trainers.clm.params import LLMTrainingParams from autotrai...
autotrain-advanced-main
src/autotrain/backend.py
NLP_TASKS = { "text_binary_classification": 1, "text_multi_class_classification": 2, "text_entity_extraction": 4, "text_extractive_question_answering": 5, "text_summarization": 8, "text_single_column_regression": 10, "speech_recognition": 11, "natural_language_inference": 22, "lm_tra...
autotrain-advanced-main
src/autotrain/tasks.py
import os import sys from autotrain import logger AUTOTRAIN_BACKEND_API = os.getenv("AUTOTRAIN_BACKEND_API", "https://api.autotrain.huggingface.co") HF_API = os.getenv("HF_API", "https://huggingface.co") logger.configure(handlers=[dict(sink=sys.stderr, format="> <level>{level:<7} {message}</level>")])
autotrain-advanced-main
src/autotrain/config.py
TEXT_CLASSIFICATION = [ ".csv", ".jsonl", ]
autotrain-advanced-main
src/autotrain/allowed_file_types.py
# coding=utf-8 # Copyright 2020-2023 The HuggingFace AutoTrain Authors # # 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 b...
autotrain-advanced-main
src/autotrain/__init__.py
import os import uuid import zipfile from dataclasses import dataclass from typing import Any, Dict, List, Optional import pandas as pd from autotrain import logger from autotrain.preprocessor.dreambooth import DreamboothPreprocessor from autotrain.preprocessor.tabular import ( TabularBinaryClassificationPreproce...
autotrain-advanced-main
src/autotrain/dataset.py
import json import os import subprocess import psutil from fastapi import FastAPI from autotrain import logger from autotrain.trainers.clm.params import LLMTrainingParams from autotrain.trainers.dreambooth.params import DreamBoothTrainingParams from autotrain.trainers.generic.params import GenericParams from autotrai...
autotrain-advanced-main
src/autotrain/api.py
import glob import json import os import re import shutil import subprocess import traceback from typing import Dict, Optional import requests from accelerate.state import PartialState from huggingface_hub import HfApi, HfFolder from huggingface_hub.repository import Repository from transformers import AutoConfig fro...
autotrain-advanced-main
src/autotrain/utils.py
import json import os import random import string import zipfile import gradio as gr import pandas as pd from huggingface_hub import list_models from autotrain import logger from autotrain.dataset import AutoTrainDataset, AutoTrainDreamboothDataset, AutoTrainImageClassificationDataset from autotrain.languages import ...
autotrain-advanced-main
src/autotrain/app.py
TRAIN_SPLIT = "train" VALID_SPLIT = "valid" TEST_SPLIT = "test"
autotrain-advanced-main
src/autotrain/splits.py
import os import pty import random import shutil import string import subprocess import gradio as gr from huggingface_hub import HfApi, whoami # ❯ autotrain dreambooth --help # usage: autotrain <command> [<args>] dreambooth [-h] --model MODEL [--revision REVISION] [--tokenizer TOKENIZER] --image-path IMAGE_PATH # ...
autotrain-advanced-main
src/autotrain/dreambooth_app.py
APP_AUTOTRAIN_USERNAME = """Please choose the user or organization who is creating the AutoTrain Project. In case of non-free tier, this user or organization will be billed. """ APP_PROJECT_NAME = """A unique name for the AutoTrain Project. This name will be used to identify the project in the AutoTrain dashboard.""" ...
autotrain-advanced-main
src/autotrain/help.py
SUPPORTED_LANGUAGES = [ "en", "ar", "bn", "de", "es", "fi", "fr", "hi", "it", "ja", "ko", "nl", "pt", "sv", "tr", "zh", "unk", ]
autotrain-advanced-main
src/autotrain/languages.py
""" Copyright 2023 The HuggingFace Team """ import json import os import time from dataclasses import dataclass from typing import Dict, List, Optional, Union import pandas as pd from codecarbon import EmissionsTracker from autotrain import logger from autotrain.backend import SpaceRunner from autotrain.dataset impo...
autotrain-advanced-main
src/autotrain/project.py
def test_dummy(): assert 1 + 1 == 2
autotrain-advanced-main
src/autotrain/tests/test_dummy.py
import os from argparse import ArgumentParser from . import BaseAutoTrainCommand def run_app_command_factory(args): return RunAutoTrainAppCommand( args.port, args.host, args.task, ) class RunAutoTrainAppCommand(BaseAutoTrainCommand): @staticmethod def register_subcommand(par...
autotrain-advanced-main
src/autotrain/cli/run_app.py
from argparse import ArgumentParser from autotrain.backend import SpaceRunner from autotrain.trainers.generic.params import GenericParams from autotrain.trainers.generic.utils import create_dataset_repo from . import BaseAutoTrainCommand BACKEND_CHOICES = [ "spaces-a10gl", "spaces-a10gs", "spaces-a100",...
autotrain-advanced-main
src/autotrain/cli/run_spacerunner.py
from argparse import ArgumentParser from . import BaseAutoTrainCommand def run_api_command_factory(args): return RunAutoTrainAPICommand( args.port, args.host, args.task, ) class RunAutoTrainAPICommand(BaseAutoTrainCommand): @staticmethod def register_subcommand(parser: Argum...
autotrain-advanced-main
src/autotrain/cli/run_api.py
import os import sys from argparse import ArgumentParser import torch from autotrain import logger from autotrain.backend import EndpointsRunner, SpaceRunner from . import BaseAutoTrainCommand def run_tabular_command_factory(args): return RunAutoTrainTabularCommand(args) class RunAutoTrainTabularCommand(Base...
autotrain-advanced-main
src/autotrain/cli/run_tabular.py
from abc import ABC, abstractmethod from argparse import ArgumentParser class BaseAutoTrainCommand(ABC): @staticmethod @abstractmethod def register_subcommand(parser: ArgumentParser): raise NotImplementedError() @abstractmethod def run(self): raise NotImplementedError()
autotrain-advanced-main
src/autotrain/cli/__init__.py
import subprocess from argparse import ArgumentParser from autotrain import logger from . import BaseAutoTrainCommand def run_app_command_factory(args): return RunSetupCommand(args.update_torch) class RunSetupCommand(BaseAutoTrainCommand): @staticmethod def register_subcommand(parser: ArgumentParser):...
autotrain-advanced-main
src/autotrain/cli/run_setup.py
import argparse from .. import __version__ from .run_api import RunAutoTrainAPICommand from .run_app import RunAutoTrainAppCommand from .run_dreambooth import RunAutoTrainDreamboothCommand from .run_image_classification import RunAutoTrainImageClassificationCommand from .run_llm import RunAutoTrainLLMCommand from .run...
autotrain-advanced-main
src/autotrain/cli/autotrain.py
import os import subprocess from argparse import ArgumentParser import torch from autotrain import logger from . import BaseAutoTrainCommand def run_image_classification_command_factory(args): return RunAutoTrainImageClassificationCommand(args) class RunAutoTrainImageClassificationCommand(BaseAutoTrainComman...
autotrain-advanced-main
src/autotrain/cli/run_image_classification.py
import os import subprocess import sys from argparse import ArgumentParser import torch from autotrain import logger from autotrain.backend import EndpointsRunner, SpaceRunner from . import BaseAutoTrainCommand def run_text_classification_command_factory(args): return RunAutoTrainTextClassificationCommand(args...
autotrain-advanced-main
src/autotrain/cli/run_text_classification.py
import os import subprocess import sys from argparse import ArgumentParser import torch from autotrain import logger from . import BaseAutoTrainCommand def run_llm_command_factory(args): return RunAutoTrainLLMCommand(args) class RunAutoTrainLLMCommand(BaseAutoTrainCommand): @staticmethod def register...
autotrain-advanced-main
src/autotrain/cli/run_llm.py
import glob import os from argparse import ArgumentParser from autotrain import logger from autotrain.cli import BaseAutoTrainCommand try: from autotrain.trainers.dreambooth.__main__ import train as train_dreambooth from autotrain.trainers.dreambooth.params import DreamBoothTrainingParams from autotrain....
autotrain-advanced-main
src/autotrain/cli/run_dreambooth.py
import os import albumentations as A import numpy as np import torch from datasets import load_dataset from sklearn import metrics from transformers import ( AutoConfig, AutoImageProcessor, AutoModelForImageClassification, EarlyStoppingCallback, Trainer, TrainingArguments, ) from autotrain imp...
autotrain-advanced-main
src/autotrain/trainers/image_classification.py
autotrain-advanced-main
src/autotrain/trainers/__init__.py
import os import numpy as np import torch from datasets import load_dataset from sklearn import metrics from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, EarlyStoppingCallback, Trainer, TrainingArguments, ) from autotrain import logger, utils from autotr...
autotrain-advanced-main
src/autotrain/trainers/text_classification.py
import os from pydantic import BaseModel from autotrain import logger class AutoTrainParams(BaseModel): def save(self, output_dir): os.makedirs(output_dir, exist_ok=True) path = os.path.join(output_dir, "training_params.json") # save formatted json with open(path, "w") as f: ...
autotrain-advanced-main
src/autotrain/trainers/common.py
import os from itertools import chain import torch from datasets import Dataset, load_dataset from peft import LoraConfig, get_peft_model, prepare_model_for_int8_training from transformers import ( AutoConfig, AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments, default_data_collato...
autotrain-advanced-main
src/autotrain/trainers/lm_trainer.py
from typing import List, Union from pydantic import Field from autotrain.trainers.common import AutoTrainParams class TabularParams(AutoTrainParams): data_path: str = Field(None, title="Data path") model: str = Field("xgboost", title="Model name") username: str = Field(None, title="Hugging Face Username...
autotrain-advanced-main
src/autotrain/trainers/tabular/params.py
autotrain-advanced-main
src/autotrain/trainers/tabular/__init__.py
import copy from collections import defaultdict from dataclasses import dataclass from functools import partial from typing import List, Optional import numpy as np from sklearn import ensemble, impute, linear_model from sklearn import metrics as skmetrics from sklearn import naive_bayes, neighbors, pipeline, preproce...
autotrain-advanced-main
src/autotrain/trainers/tabular/utils.py
import argparse import json import os from functools import partial import joblib import numpy as np import optuna import pandas as pd from datasets import load_dataset from huggingface_hub import HfApi from sklearn import pipeline, preprocessing from sklearn.compose import ColumnTransformer from autotrain import log...
autotrain-advanced-main
src/autotrain/trainers/tabular/__main__.py
from typing import Dict from pydantic import Field from autotrain.trainers.common import AutoTrainParams class GenericParams(AutoTrainParams): username: str = Field(None, title="Hugging Face Username") project_name: str = Field(None, title="Output directory") data_path: str = Field(None, title="Data pat...
autotrain-advanced-main
src/autotrain/trainers/generic/params.py
autotrain-advanced-main
src/autotrain/trainers/generic/__init__.py
import os import subprocess import requests from huggingface_hub import HfApi, snapshot_download from loguru import logger def create_dataset_repo(username, project_name, script_path, token): logger.info("Creating dataset repo...") api = HfApi(token=token) repo_id = f"{username}/autotrain-{project_name}"...
autotrain-advanced-main
src/autotrain/trainers/generic/utils.py
import argparse import json import os from huggingface_hub import HfApi from autotrain import logger from autotrain.trainers.generic import utils from autotrain.trainers.generic.params import GenericParams from autotrain.utils import monitor def parse_args(): # get training_config.json from the end user par...
autotrain-advanced-main
src/autotrain/trainers/generic/__main__.py
from pydantic import Field from autotrain.trainers.common import AutoTrainParams class DreamBoothTrainingParams(AutoTrainParams): model: str = Field(None, title="Model name") revision: str = Field(None, title="Revision") tokenizer: str = Field(None, title="Tokenizer, if different from model") image_p...
autotrain-advanced-main
src/autotrain/trainers/dreambooth/params.py