[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# Label Studio for Hugging Face's Transformers\n\n[Website](https://labelstud.io/) • [Docs](https://labelstud.io/guide) • [Twitter](https://twitter.com/heartexlabs) • [Join Slack Community <img src=\"https://app.heartex.ai/docs/images/slack-mini.png\" width=\"18px\"/>](https://slack.labelstud.io/?source=github-1)\n\n<br/>\n\n**Transfer learning for NLP models by annotating your textual data without any additional coding.**\n\nThis package provides a ready-to-use container that links together:\n\n- [Label Studio](https://github.com/heartexlabs/label-studio) as annotation frontend\n- [Hugging Face's transformers](https://github.com/huggingface/transformers) as machine learning backend for NLP\n\n<br/>\n\n[<img src=\"https://raw.githubusercontent.com/heartexlabs/label-studio-transformers/master/images/codeless.png\" height=\"500\">](https://github.com/heartexlabs/label-studio-transformers)\n\n### Quick Usage\n\n#### Install Label Studio and other dependencies\n\n```bash\npip install -r requirements.txt\n```\n\n##### Create ML backend with BERT classifier\n```bash\nlabel-studio-ml init my-ml-backend --script models/bert_classifier.py\ncp models/utils.py my-ml-backend/utils.py\n\n# Start ML backend at http://localhost:9090\nlabel-studio-ml start my-ml-backend\n\n# Start Label Studio in the new terminal with the same python environment\nlabel-studio start\n```\n\n1. Create a project with `Choices` and `Text` tags in the labeling config.\n2. Connect the ML backend in the Project settings with `http://localhost:9090`\n\n##### Create ML backend with BERT named entity recognizer\n```bash\nlabel-studio-ml init my-ml-backend --script models/ner.py\ncp models/utils.py my-ml-backend/utils.py\n\n# Start ML backend at http://localhost:9090\nlabel-studio-ml start my-ml-backend\n\n# Start Label Studio in the new terminal with the same python environment\nlabel-studio start\n```\n\n1. Create a project with `Labels` and `Text` tags in the labeling config.\n2. Connect the ML backend in the Project settings with `http://localhost:9090`\n\n#### Training and inference\n\nThe browser opens at `http://localhost:8080`. Upload your data on **Import** page then annotate by selecting **Labeling** page.\nOnce you've annotate sufficient amount of data, go to **Model** page and press **Start Training** button. Once training is finished, model automatically starts serving for inference from Label Studio, and you'll find all model checkpoints inside `my-ml-backend/<ml-backend-id>/` directory.\n\n[Click here](https://labelstud.io/guide/ml.html) to read more about how to use Machine Learning backend and build Human-in-the-Loop pipelines with Label Studio\n\n## License\n\nThis software is licensed under the [Apache 2.0 LICENSE](/LICENSE) © [Heartex](https://www.heartex.com/). 2020\n\n<img src=\"https://github.com/heartexlabs/label-studio/blob/master/images/opossum_looking.png?raw=true\" title=\"Hey everyone!\" height=\"140\" width=\"140\" />\n"
  },
  {
    "path": "models/__init__.py",
    "content": ""
  },
  {
    "path": "models/bert_classifier.py",
    "content": "import torch\nimport numpy as np\nimport os\n\nfrom torch.utils.data import SequentialSampler\nfrom tqdm import tqdm, trange\nfrom collections import deque\nfrom tensorboardX import SummaryWriter\nfrom transformers import BertTokenizer, BertForSequenceClassification\nfrom transformers import AdamW, get_linear_schedule_with_warmup\nfrom torch.utils.data import TensorDataset, DataLoader, RandomSampler\n\nfrom label_studio_ml.model import LabelStudioMLBase\n\nfrom utils import prepare_texts, calc_slope\n\n\nif torch.cuda.is_available():\n    device = torch.device(\"cuda\")\n    print('There are %d GPU(s) available.' % torch.cuda.device_count())\n    print('We will use the GPU:', torch.cuda.get_device_name(0))\nelse:\n    print('No GPU available, using the CPU instead.')\n    device = torch.device(\"cpu\")\n\n\nclass BertClassifier(LabelStudioMLBase):\n\n    def __init__(\n        self, pretrained_model='bert-base-multilingual-cased', maxlen=64,\n        batch_size=32, num_epochs=100, logging_steps=1, train_logs=None, **kwargs\n    ):\n        super(BertClassifier, self).__init__(**kwargs)\n        self.pretrained_model = pretrained_model\n        self.maxlen = maxlen\n        self.batch_size = batch_size\n        self.num_epochs = num_epochs\n        self.logging_steps = logging_steps\n        self.train_logs = train_logs\n\n        # then collect all keys from config which will be used to extract data from task and to form prediction\n        # Parsed label config contains only one output of <Choices> type\n        assert len(self.parsed_label_config) == 1\n        self.from_name, self.info = list(self.parsed_label_config.items())[0]\n        assert self.info['type'] == 'Choices'\n\n        # the model has only one textual input\n        assert len(self.info['to_name']) == 1\n        assert len(self.info['inputs']) == 1\n        assert self.info['inputs'][0]['type'] == 'Text'\n        self.to_name = self.info['to_name'][0]\n        self.value = self.info['inputs'][0]['value']\n\n        if not self.train_output:\n            self.labels = self.info['labels']\n            self.reset_model('bert-base-multilingual-cased', cache_dir=None, device='cpu')\n            print('Initialized with from_name={from_name}, to_name={to_name}, labels={labels}'.format(\n                from_name=self.from_name, to_name=self.to_name, labels=str(self.labels)\n            ))\n        else:\n            self.load(self.train_output)\n            print('Loaded from train output with from_name={from_name}, to_name={to_name}, labels={labels}'.format(\n                from_name=self.from_name, to_name=self.to_name, labels=str(self.labels)\n            ))\n\n    def reset_model(self, pretrained_model, cache_dir, device):\n        model = BertForSequenceClassification.from_pretrained(\n            pretrained_model,\n            num_labels=len(self.labels),\n            output_attentions=False,\n            output_hidden_states=False,\n            cache_dir=cache_dir\n        )\n        model.to(device)\n        return model\n\n    def load(self, train_output):\n        pretrained_model = train_output['model_path']\n        self.tokenizer = BertTokenizer.from_pretrained(pretrained_model)\n        self.model = BertForSequenceClassification.from_pretrained(pretrained_model)\n        self.model.to(device)\n        self.model.eval()\n        self.batch_size = train_output['batch_size']\n        self.labels = train_output['labels']\n        self.maxlen = train_output['maxlen']\n\n    @property\n    def not_trained(self):\n        return not hasattr(self, 'tokenizer')\n\n    def predict(self, tasks, **kwargs):\n        if self.not_trained:\n            print('Can\\'t get prediction because model is not trained yet.')\n            return []\n\n        texts = [task['data'][self.value] for task in tasks]\n        predict_dataloader = prepare_texts(texts, self.tokenizer, self.maxlen, SequentialSampler, self.batch_size)\n\n        pred_labels, pred_scores = [], []\n        for batch in predict_dataloader:\n            batch = tuple(t.to(device) for t in batch)\n            inputs = {\n                'input_ids': batch[0],\n                'attention_mask': batch[1]\n            }\n            with torch.no_grad():\n                outputs = self.model(**inputs)\n                logits = outputs[0]\n\n            batch_preds = logits.detach().cpu().numpy()\n\n            argmax_batch_preds = np.argmax(batch_preds, axis=-1)\n            pred_labels.extend(str(self.labels[i]) for i in argmax_batch_preds)\n\n            max_batch_preds = np.max(batch_preds, axis=-1)\n            pred_scores.extend(float(s) for s in max_batch_preds)\n\n        predictions = []\n        for predicted_label, score in zip(pred_labels, pred_scores):\n            result = [{\n                'from_name': self.from_name,\n                'to_name': self.to_name,\n                'type': 'choices',\n                'value': {'choices': [predicted_label]}\n            }]\n\n            predictions.append({'result': result, 'score': score})\n        return predictions\n\n    def fit(self, completions, workdir=None, cache_dir=None, **kwargs):\n        input_texts = []\n        output_labels, output_labels_idx = [], []\n        label2idx = {l: i for i, l in enumerate(self.labels)}\n        for completion in completions:\n            # get input text from task data\n\n            if completion['annotations'][0].get('skipped'):\n                continue\n\n            input_text = completion['data'][self.value]\n            input_texts.append(input_text)\n\n            # get an annotation\n            output_label = completion['annotations'][0]['result'][0]['value']['choices'][0]\n            output_labels.append(output_label)\n            output_label_idx = label2idx[output_label]\n            output_labels_idx.append(output_label_idx)\n\n        new_labels = set(output_labels)\n        added_labels = new_labels - set(self.labels)\n        if len(added_labels) > 0:\n            print('Label set has been changed. Added ones: ' + str(list(added_labels)))\n            self.labels = list(sorted(new_labels))\n            label2idx = {l: i for i, l in enumerate(self.labels)}\n            output_labels_idx = [label2idx[label] for label in output_labels]\n\n        tokenizer = BertTokenizer.from_pretrained(self.pretrained_model, cache_dir=cache_dir)\n\n        train_dataloader = prepare_texts(input_texts, tokenizer, self.maxlen, RandomSampler, self.batch_size, output_labels_idx)\n        model = self.reset_model(self.pretrained_model, cache_dir, device)\n\n        total_steps = len(train_dataloader) * self.num_epochs\n        optimizer = AdamW(model.parameters(), lr=2e-5, eps=1e-8)\n        scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, num_training_steps=total_steps)\n        global_step = 0\n        total_loss, logging_loss = 0.0, 0.0\n        model.zero_grad()\n        train_iterator = trange(self.num_epochs, desc='Epoch')\n        if self.train_logs:\n            tb_writer = SummaryWriter(logdir=os.path.join(self.train_logs, os.path.basename(self.output_dir)))\n        else:\n            tb_writer = None\n        loss_queue = deque(maxlen=10)\n        for epoch in train_iterator:\n            epoch_iterator = tqdm(train_dataloader, desc='Iteration')\n            for step, batch in enumerate(epoch_iterator):\n                model.train()\n                batch = tuple(t.to(device) for t in batch)\n                inputs = {'input_ids': batch[0],\n                          'attention_mask': batch[1],\n                          'labels': batch[2]}\n                outputs = model(**inputs)\n                loss = outputs[0]\n                loss.backward()\n                total_loss += loss.item()\n\n                torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n                optimizer.step()\n                scheduler.step()\n                model.zero_grad()\n                global_step += 1\n                if global_step % self.logging_steps == 0:\n                    last_loss = (total_loss - logging_loss) / self.logging_steps\n                    loss_queue.append(last_loss)\n                    if tb_writer:\n                        tb_writer.add_scalar('lr', scheduler.get_lr()[0], global_step)\n                        tb_writer.add_scalar('loss', last_loss, global_step)\n                    logging_loss = total_loss\n\n            # slope-based early stopping\n            if len(loss_queue) == loss_queue.maxlen:\n                slope = calc_slope(loss_queue)\n                if tb_writer:\n                    tb_writer.add_scalar('slope', slope, global_step)\n                if abs(slope) < 1e-2:\n                    break\n\n        if tb_writer:\n            tb_writer.close()\n\n        model_to_save = model.module if hasattr(model, 'module') else model  # Take care of distributed/parallel training  # noqa\n        model_to_save.save_pretrained(workdir)\n        tokenizer.save_pretrained(workdir)\n\n        return {\n            'model_path': workdir,\n            'batch_size': self.batch_size,\n            'maxlen': self.maxlen,\n            'pretrained_model': self.pretrained_model,\n            'labels': self.labels\n        }\n"
  },
  {
    "path": "models/ner.py",
    "content": "import torch\nimport numpy as np\nimport re\nimport os\nimport io\nimport logging\n\nfrom functools import partial\nfrom itertools import groupby\nfrom operator import itemgetter\nfrom torch.nn import CrossEntropyLoss\nfrom torch.utils.data import Dataset, DataLoader\nfrom tqdm import tqdm, trange\nfrom tensorboardX import SummaryWriter\nfrom collections import deque\n\nfrom transformers import (\n    BertTokenizer, BertForTokenClassification, BertConfig,\n    RobertaConfig, RobertaForTokenClassification, RobertaTokenizer,\n    DistilBertConfig, DistilBertForTokenClassification, DistilBertTokenizer,\n    CamembertConfig, CamembertForTokenClassification, CamembertTokenizer,\n    AutoConfig, AutoModelForTokenClassification, AutoTokenizer\n)\nfrom transformers import AdamW, get_linear_schedule_with_warmup\n\nfrom label_studio_ml.model import LabelStudioMLBase\nfrom utils import calc_slope\n\n\nlogger = logging.getLogger(__name__)\n\n\nALL_MODELS = sum(\n    [list(conf.pretrained_config_archive_map.keys()) for conf in (BertConfig, RobertaConfig, DistilBertConfig)],\n    [])\n\nMODEL_CLASSES = {\n    'bert': (BertConfig, BertForTokenClassification, BertTokenizer),\n    'roberta': (RobertaConfig, RobertaForTokenClassification, RobertaTokenizer),\n    'distilbert': (DistilBertConfig, DistilBertForTokenClassification, DistilBertTokenizer),\n    'camembert': (CamembertConfig, CamembertForTokenClassification, CamembertTokenizer),\n}\n\n\nclass SpanLabeledTextDataset(Dataset):\n\n    def __init__(\n        self, list_of_strings, list_of_spans=None, tokenizer=None, tag_idx_map=None,\n        cls_token='[CLS]', sep_token='[SEP]', pad_token_label_id=-1, max_seq_length=128, sep_token_extra=False,\n        cls_token_at_end=False, sequence_a_segment_id=0, cls_token_segment_id=1, mask_padding_with_zero=True\n    ):\n        self.list_of_strings = list_of_strings\n        self.list_of_spans = list_of_spans or [[] * len(list_of_strings)]\n        self.tokenizer = tokenizer\n        self.cls_token = cls_token\n        self.sep_token = sep_token\n        self.pad_token_label_id = pad_token_label_id\n        self.max_seq_length = max_seq_length\n        self.sep_token_extra = sep_token_extra\n        self.cls_token_at_end = cls_token_at_end\n        self.sequence_a_segment_id = sequence_a_segment_id\n        self.cls_token_segment_id = cls_token_segment_id\n        self.mask_padding_with_zero = mask_padding_with_zero\n\n        (self.original_list_of_tokens, self.original_list_of_tags, tag_idx_map_,\n         original_list_of_tokens_start_map) = self._prepare_data()\n\n        if tag_idx_map is None:\n            self.tag_idx_map = tag_idx_map_\n        else:\n            self.tag_idx_map = tag_idx_map\n\n        (self.list_of_tokens, self.list_of_token_ids, self.list_of_labels, self.list_of_label_ids,\n         self.list_of_segment_ids, self.list_of_token_start_map) = [], [], [], [], [], []\n\n        for original_tokens, original_tags, original_token_start_map in zip(\n            self.original_list_of_tokens,\n            self.original_list_of_tags,\n            original_list_of_tokens_start_map\n        ):\n            tokens, token_ids, labels, label_ids, segment_ids, token_start_map = self._convert_to_features(\n                original_tokens, original_tags, self.tag_idx_map, original_token_start_map)\n            self.list_of_token_ids.append(token_ids)\n            self.list_of_tokens.append(tokens)\n            self.list_of_labels.append(labels)\n            self.list_of_segment_ids.append(segment_ids)\n            self.list_of_label_ids.append(label_ids)\n            self.list_of_token_start_map.append(token_start_map)\n\n    def get_params_dict(self):\n        return {\n            'cls_token': self.cls_token,\n            'sep_token': self.sep_token,\n            'pad_token_label_id': self.pad_token_label_id,\n            'max_seq_length': self.max_seq_length,\n            'sep_token_extra': self.sep_token_extra,\n            'cls_token_at_end': self.cls_token_at_end,\n            'sequence_a_segment_id': self.sequence_a_segment_id,\n            'cls_token_segment_id': self.cls_token_segment_id,\n            'mask_padding_with_zero': self.mask_padding_with_zero\n        }\n\n    def dump(self, output_file):\n        with io.open(output_file, mode='w') as f:\n            for tokens, labels in zip(self.list_of_tokens, self.list_of_labels):\n                for token, label in zip(tokens, labels):\n                    f.write(f'{token} {label}\\n')\n                f.write('\\n')\n\n    def _convert_to_features(self, words, labels, label_map, list_token_start_map):\n        tokens, out_labels, label_ids, tokens_idx_map = [], [], [], []\n        for i, (word, label, token_start) in enumerate(zip(words, labels, list_token_start_map)):\n            word_tokens = self.tokenizer.tokenize(word)\n            tokens.extend(word_tokens)\n            tokens_idx_map.extend([token_start] * len(word_tokens))\n            # Use the real label id for the first token of the word, and padding ids for the remaining tokens\n            label_ids.extend([label_map[label]] + [self.pad_token_label_id] * (len(word_tokens) - 1))\n            out_labels.extend([label] + ['X'] * (len(word_tokens) - 1))\n\n        # Account for [CLS] and [SEP] with \"- 2\" and with \"- 3\" for RoBERTa.\n        special_tokens_count = 3 if self.sep_token_extra else 2\n        if len(tokens) > self.max_seq_length - special_tokens_count:\n            tokens = tokens[:(self.max_seq_length - special_tokens_count)]\n            label_ids = label_ids[:(self.max_seq_length - special_tokens_count)]\n            out_labels = out_labels[:(self.max_seq_length - special_tokens_count)]\n            tokens_idx_map = tokens_idx_map[:(self.max_seq_length - special_tokens_count)]\n\n        # The convention in BERT is:\n        # (a) For sequence pairs:\n        #  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n        #  type_ids:   0   0  0    0    0     0       0   0   1  1  1  1   1   1\n        # (b) For single sequences:\n        #  tokens:   [CLS] the dog is hairy . [SEP]\n        #  type_ids:   0   0   0   0  0     0   0\n        #\n        # Where \"type_ids\" are used to indicate whether this is the first\n        # sequence or the second sequence. The embedding vectors for `type=0` and\n        # `type=1` were learned during pre-training and are added to the wordpiece\n        # embedding vector (and position vector). This is not *strictly* necessary\n        # since the [SEP] token unambiguously separates the sequences, but it makes\n        # it easier for the model to learn the concept of sequences.\n        #\n        # For classification tasks, the first vector (corresponding to [CLS]) is\n        # used as as the \"sentence vector\". Note that this only makes sense because\n        # the entire model is fine-tuned.\n        tokens += [self.sep_token]\n        label_ids += [self.pad_token_label_id]\n        out_labels += ['X']\n        tokens_idx_map += [-1]\n        if self.sep_token_extra:\n            # roberta uses an extra separator b/w pairs of sentences\n            tokens += [self.sep_token]\n            label_ids += [self.pad_token_label_id]\n            out_labels += ['X']\n            tokens_idx_map += [-1]\n        segment_ids = [self.sequence_a_segment_id] * len(tokens)\n        if self.cls_token_at_end:\n            tokens += [self.cls_token]\n            label_ids += [self.pad_token_label_id]\n            out_labels += ['X']\n            segment_ids += [self.cls_token_segment_id]\n            tokens_idx_map += [-1]\n        else:\n            tokens = [self.cls_token] + tokens\n            label_ids = [self.pad_token_label_id] + label_ids\n            out_labels = ['X'] + out_labels\n            segment_ids = [self.cls_token_segment_id] + segment_ids\n            tokens_idx_map = [-1] + tokens_idx_map\n\n        token_ids = self.tokenizer.convert_tokens_to_ids(tokens)\n\n        return tokens, token_ids, out_labels, label_ids, segment_ids, tokens_idx_map\n\n    def _apply_tokenizer(self, original_tokens, original_tags):\n        out_tokens, out_tags, out_maps = [], [], []\n        for i, (original_token, original_tag) in enumerate(zip(original_tokens, original_tags)):\n            tokens = self.tokenizer.tokenize(original_token)\n            out_tokens.extend(tokens)\n            out_maps.extend([i] * len(tokens))\n            start_tag = original_tag.startswith('B-')\n            for j in range(len(tokens)):\n                if (j == 0 and start_tag) or original_tag == 'O':\n                    out_tags.append(original_tag)\n                else:\n                    out_tags.append(f'I-{original_tag[2:]}')\n        return out_tokens, out_tags, out_maps\n\n    def _prepare_data(self):\n        list_of_tokens, list_of_tags, list_of_token_idx_maps = [], [], []\n        tag_idx_map = {'O': 0}\n        for text, spans in zip(self.list_of_strings, self.list_of_spans):\n            if not text:\n                continue\n\n            tokens = []\n            start = 0\n            for t in text.split():\n                tokens.append((t, start))\n                start += len(t) + 1\n\n            if spans:\n                spans = list(sorted(spans, key=itemgetter('start')))\n                span = spans.pop(0)\n                prefix = 'B-'\n                tags = []\n                for token, token_start in tokens:\n                    token_end = token_start + len(token) - 1\n\n                    # token precedes current span\n                    if not span or token_end < span['start']:\n                        tags.append('O')\n                        continue\n\n                    # token jumps over the span (it could happens\n                    # when prev label ends with whitespaces, e.g. \"cat \" \"too\" or span created for whitespace)\n                    if token_start > span['end']:\n\n                        prefix = 'B-'\n                        no_more_spans = False\n                        while token_start > span['end']:\n                            if not len(spans):\n                                no_more_spans = True\n                                break\n                            span = spans.pop(0)\n\n                        if no_more_spans:\n                            tags.append('O')\n                            span = None\n                            continue\n\n                        if token_end < span['start']:\n                            tags.append('O')\n                            continue\n\n                    label = span['label']\n                    if label.startswith(prefix):\n                        tag = label\n                    else:\n                        tag = f'{prefix}{label}'\n                    tags.append(tag)\n                    if tag not in tag_idx_map:\n                        tag_idx_map[tag] = len(tag_idx_map)\n                    if span['end'] > token_end:\n                        prefix = 'I-'\n                    elif len(spans):\n                        span = spans.pop(0)\n                        prefix = 'B-'\n                    else:\n                        span = None\n            else:\n                tags = ['O'] * len(tokens)\n\n            list_of_tokens.append([t[0] for t in tokens])\n            list_of_token_idx_maps.append([t[1] for t in tokens])\n            list_of_tags.append(tags)\n\n        return list_of_tokens, list_of_tags, tag_idx_map, list_of_token_idx_maps\n\n    def __len__(self):\n        return len(self.list_of_token_ids)\n\n    def __getitem__(self, idx):\n        return {\n            'tokens': self.list_of_token_ids[idx],\n            'labels': self.list_of_label_ids[idx],\n            'segments': self.list_of_segment_ids[idx],\n            'token_start_map': self.list_of_token_start_map[idx],\n            'string': self.list_of_strings[idx]\n        }\n\n    @property\n    def num_labels(self):\n        return len(self.tag_idx_map)\n\n    @classmethod\n    def pad_sequences(cls, batch, mask_padding_with_zero, pad_on_left, pad_token, pad_token_segment_id, pad_token_label_id):\n        # The mask has 1 for real tokens and 0 for padding tokens. Only real\n        # tokens are attended to.\n        max_seq_length = max(map(len, (sample['tokens'] for sample in batch)))\n        batch_input_ids, batch_label_ids, batch_segment_ids, batch_input_mask, batch_token_start_map = [], [], [], [], []\n        batch_strings = []\n        for sample in batch:\n            input_ids = sample['tokens']\n            label_ids = sample['labels']\n            segment_ids = sample['segments']\n            # The mask has 1 for real tokens and 0 for padding tokens. Only real\n            # tokens are attended to.\n            input_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)\n            padding_length = max_seq_length - len(input_ids)\n            if pad_on_left:\n                input_ids = ([pad_token] * padding_length) + input_ids\n                input_mask = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask\n                segment_ids = ([pad_token_segment_id] * padding_length) + segment_ids\n                label_ids = ([pad_token_label_id] * padding_length) + label_ids\n            else:\n                input_ids += ([pad_token] * padding_length)\n                input_mask += ([0 if mask_padding_with_zero else 1] * padding_length)\n                segment_ids += ([pad_token_segment_id] * padding_length)\n                label_ids += ([pad_token_label_id] * padding_length)\n            batch_input_ids.append(input_ids)\n            batch_label_ids.append(label_ids)\n            batch_segment_ids.append(segment_ids)\n            batch_input_mask.append(input_mask)\n            batch_token_start_map.append(sample['token_start_map'])\n            batch_strings.append(sample['string'])\n\n        return {\n            'input_ids': torch.tensor(batch_input_ids, dtype=torch.long),\n            'label_ids': torch.tensor(batch_label_ids, dtype=torch.long),\n            'segment_ids': torch.tensor(batch_segment_ids, dtype=torch.long),\n            'input_mask': torch.tensor(batch_input_mask, dtype=torch.long),\n            'token_start_map': batch_token_start_map,\n            'strings': batch_strings\n        }\n\n    @classmethod\n    def get_padding_function(cls, model_type, tokenizer, pad_token_label_id):\n        return partial(\n            cls.pad_sequences,\n            mask_padding_with_zero=True,\n            pad_on_left=model_type in ['xlnet'],\n            pad_token=tokenizer.convert_tokens_to_ids([tokenizer.pad_token])[0],\n            pad_token_segment_id=4 if model_type in ['xlnet'] else 0,\n            pad_token_label_id=pad_token_label_id\n        )\n\n\nclass TransformersBasedTagger(LabelStudioMLBase):\n\n    def __init__(self, **kwargs):\n        super(TransformersBasedTagger, self).__init__(**kwargs)\n\n        assert len(self.parsed_label_config) == 1\n        self.from_name, self.info = list(self.parsed_label_config.items())[0]\n        assert self.info['type'] == 'Labels'\n\n        # the model has only one textual input\n        assert len(self.info['to_name']) == 1\n        assert len(self.info['inputs']) == 1\n        assert self.info['inputs'][0]['type'] == 'Text'\n        self.to_name = self.info['to_name'][0]\n        self.value = self.info['inputs'][0]['value']\n\n        if not self.train_output:\n            self.labels = self.info['labels']\n        else:\n            self.load(self.train_output)\n\n    def load(self, train_output):\n        pretrained_model = train_output['model_path']\n        self._model_type = train_output['model_type']\n        _, model_class, tokenizer_class = MODEL_CLASSES[train_output['model_type']]\n\n        self._tokenizer = AutoTokenizer.from_pretrained(pretrained_model)\n        self._model = AutoModelForTokenClassification.from_pretrained(pretrained_model)\n        self._batch_size = train_output['batch_size']\n        self._pad_token = self._tokenizer.convert_tokens_to_ids([self._tokenizer.pad_token])[0]\n        self._pad_token_label_id = train_output['pad_token_label_id']\n        self._label_map = train_output['label_map']\n        self._mask_padding_with_zero = True\n        self._dataset_params_dict = train_output['dataset_params_dict']\n\n        self._batch_padding = SpanLabeledTextDataset.get_padding_function(\n            self._model_type, self._tokenizer, self._pad_token_label_id)\n\n    def predict(self, tasks, **kwargs):\n        texts = [task['data'][self.value] for task in tasks]\n        predict_set = SpanLabeledTextDataset(texts, tokenizer=self._tokenizer, **self._dataset_params_dict)\n        from_name = self.from_name\n        to_name = self.to_name\n        predict_loader = DataLoader(\n            dataset=predict_set,\n            batch_size=self._batch_size,\n            collate_fn=self._batch_padding\n        )\n\n        results = []\n        for batch in tqdm(predict_loader, desc='Prediction'):\n            inputs = {\n                'input_ids': batch['input_ids'],\n                'attention_mask': batch['input_mask'],\n                'token_type_ids': batch['segment_ids']\n            }\n            if self._model_type == 'distilbert':\n                inputs.pop('token_type_ids')\n            with torch.no_grad():\n                model_output = self._model(**inputs)\n                logits = model_output[0]\n\n            batch_preds = logits.detach().cpu().numpy()\n            argmax_batch_preds = np.argmax(batch_preds, axis=-1)\n            max_batch_preds = np.max(batch_preds, axis=-1)\n            input_mask = batch['input_mask'].detach().cpu().numpy()\n            batch_token_start_map = batch['token_start_map']\n            batch_strings = batch['strings']\n\n            for max_preds, argmax_preds, mask_tokens, token_start_map, string in zip(\n                max_batch_preds, argmax_batch_preds, input_mask, batch_token_start_map, batch_strings\n            ):\n                preds, scores, starts = [], [], []\n                for max_pred, argmax_pred, mask_token, token_start in zip(max_preds, argmax_preds, mask_tokens, token_start_map):\n                    if token_start != -1:\n                        preds.append(self._label_map[str(argmax_pred)])\n                        scores.append(max_pred)\n                        starts.append(token_start)\n                mean_score = np.mean(scores) if len(scores) > 0 else 0\n\n                result = []\n\n                for label, group in groupby(zip(preds, starts, scores), key=lambda i: re.sub('^(B-|I-)', '', i[0])):\n                    _, group_start, _ = list(group)[0]\n                    if len(result) > 0:\n                        if group_start == 0:\n                            result.pop(-1)\n                        else:\n                            result[-1]['value']['end'] = group_start - 1\n                    if label != 'O':\n                        result.append({\n                            'from_name': from_name,\n                            'to_name': to_name,\n                            'type': 'labels',\n                            'value': {\n                                'labels': [label],\n                                'start': group_start,\n                                'end': None, \n                                'text': '...'\n                            }\n                        })\n                if result and result[-1]['value']['end'] is None:\n                    result[-1]['value']['end'] = len(string)\n                results.append({\n                    'result': result,\n                    'score': float(mean_score),\n                    'cluster': None\n                })\n        return results\n\n    def get_spans(self, completion):\n        spans = []\n        for r in completion['result']:\n            if r['from_name'] == self.from_name and r['to_name'] == self.to_name:\n                labels = r['value'].get('labels')\n                if not isinstance(labels, list) or len(labels) == 0:\n                    logger.warning(f'Error while parsing {r}: list type expected for \"labels\"')\n                    continue\n                label = labels[0]\n                start, end = r['value'].get('start'), r['value'].get('end')\n                if start is None or end is None:\n                    logger.warning(f'Error while parsing {r}: \"labels\" should contain \"start\" and \"end\" fields')\n                spans.append({\n                    'label': label,\n                    'start': start,\n                    'end': end\n                })\n        return spans\n\n    def fit(\n        self, completions, workdir=None, model_type='bert', pretrained_model='bert-base-uncased',\n        batch_size=32, learning_rate=5e-5, adam_epsilon=1e-8, num_train_epochs=100, weight_decay=0.0, logging_steps=1,\n        warmup_steps=0, save_steps=50, dump_dataset=True, cache_dir='~/.heartex/cache', train_logs=None,\n        **kwargs\n    ):\n        train_logs = train_logs or os.path.join(workdir, 'train_logs')\n        os.makedirs(train_logs, exist_ok=True)\n        logger.debug('Prepare models')\n        cache_dir = os.path.expanduser(cache_dir)\n        os.makedirs(cache_dir, exist_ok=True)\n\n        model_type = model_type.lower()\n        # assert model_type in MODEL_CLASSES.keys(), f'Input model type {model_type} not in {MODEL_CLASSES.keys()}'\n        # assert pretrained_model in ALL_MODELS, f'Pretrained model {pretrained_model} not in {ALL_MODELS}'\n\n        tokenizer = AutoTokenizer.from_pretrained(pretrained_model, cache_dir=cache_dir)\n\n        logger.debug('Read data')\n        # read input data stream\n        texts, list_of_spans = [], []\n        for item in completions:\n            texts.append(item['data'][self.value])\n            list_of_spans.append(self.get_spans(item['annotations'][0]))\n\n        logger.debug('Prepare dataset')\n        pad_token_label_id = CrossEntropyLoss().ignore_index\n        train_set = SpanLabeledTextDataset(\n            texts, list_of_spans, tokenizer,\n            cls_token_at_end=model_type in ['xlnet'],\n            cls_token_segment_id=2 if model_type in ['xlnet'] else 0,\n            sep_token_extra=model_type in ['roberta'],\n            pad_token_label_id=pad_token_label_id\n        )\n\n        if dump_dataset:\n            dataset_file = os.path.join(workdir, 'train_set.txt')\n            train_set.dump(dataset_file)\n\n        # config = config_class.from_pretrained(pretrained_model, num_labels=train_set.num_labels, cache_dir=cache_dir)\n        config = AutoConfig.from_pretrained(pretrained_model, num_labels=train_set.num_labels, cache_dir=cache_dir)\n        # model = model_class.from_pretrained(pretrained_model, config=config, cache_dir=cache_dir)\n        model = AutoModelForTokenClassification.from_pretrained(pretrained_model, config=config, cache_dir=cache_dir)\n\n        batch_padding = SpanLabeledTextDataset.get_padding_function(model_type, tokenizer, pad_token_label_id)\n\n        train_loader = DataLoader(\n            dataset=train_set,\n            batch_size=batch_size,\n            shuffle=True,\n            collate_fn=batch_padding\n        )\n\n        no_decay = ['bias', 'LayerNorm.weight']\n        optimizer_grouped_parameters = [\n            {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],\n             'weight_decay': weight_decay},\n            {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n        ]\n\n        num_training_steps = len(train_loader) * num_train_epochs\n        optimizer = AdamW(optimizer_grouped_parameters, lr=learning_rate, eps=adam_epsilon)\n        scheduler = get_linear_schedule_with_warmup(\n            optimizer, num_warmup_steps=warmup_steps, num_training_steps=num_training_steps)\n\n        tr_loss, logging_loss = 0, 0\n        global_step = 0\n        if train_logs:\n            tb_writer = SummaryWriter(logdir=os.path.join(train_logs, os.path.basename(workdir)))\n        epoch_iterator = trange(num_train_epochs, desc='Epoch')\n        loss_queue = deque(maxlen=10)\n        for _ in epoch_iterator:\n            batch_iterator = tqdm(train_loader, desc='Batch')\n            for step, batch in enumerate(batch_iterator):\n\n                model.train()\n                inputs = {\n                    'input_ids': batch['input_ids'],\n                    'attention_mask': batch['input_mask'],\n                    'labels': batch['label_ids'],\n                    'token_type_ids': batch['segment_ids']\n                }\n                if model_type == 'distilbert':\n                    inputs.pop('token_type_ids')\n\n                model_output = model(**inputs)\n                loss = model_output[0]\n                loss.backward()\n                tr_loss += loss.item()\n                optimizer.step()\n                scheduler.step()\n                model.zero_grad()\n                global_step += 1\n                if global_step % logging_steps == 0:\n                    last_loss = (tr_loss - logging_loss) / logging_steps\n                    loss_queue.append(last_loss)\n                    if train_logs:\n                        tb_writer.add_scalar('lr', scheduler.get_lr()[0], global_step)\n                        tb_writer.add_scalar('loss', last_loss, global_step)\n                    logging_loss = tr_loss\n\n            # slope-based early stopping\n            if len(loss_queue) == loss_queue.maxlen:\n                slope = calc_slope(loss_queue)\n                if train_logs:\n                    tb_writer.add_scalar('slope', slope, global_step)\n                if abs(slope) < 1e-2:\n                    break\n\n        if train_logs:\n            tb_writer.close()\n\n        model_to_save = model.module if hasattr(model, \"module\") else model  # Take care of distributed/parallel training\n        model_to_save.save_pretrained(workdir)\n        tokenizer.save_pretrained(workdir)\n        label_map = {i: t for t, i in train_set.tag_idx_map.items()}\n\n        return {\n            'model_path': workdir,\n            'batch_size': batch_size,\n            'pad_token_label_id': pad_token_label_id,\n            'dataset_params_dict': train_set.get_params_dict(),\n            'model_type': model_type,\n            'pretrained_model': pretrained_model,\n            'label_map': label_map\n        }\n"
  },
  {
    "path": "models/utils.py",
    "content": "import torch\nimport numpy as np\n\nfrom torch.utils.data import TensorDataset, DataLoader\n\n\ndef pad_sequences(input_ids, maxlen):\n    padded_ids = []\n    for ids in input_ids:\n        nonpad = min(len(ids), maxlen)\n        pids = [ids[i] for i in range(nonpad)]\n        for i in range(nonpad, maxlen):\n            pids.append(0)\n        padded_ids.append(pids)\n    return padded_ids\n\n\ndef prepare_texts(texts, tokenizer, maxlen, sampler_class, batch_size, choices_ids=None):\n    # create input token indices\n    input_ids = []\n    for text in texts:\n        input_ids.append(tokenizer.encode(text, add_special_tokens=True))\n    # input_ids = pad_sequences(input_ids, maxlen=maxlen, dtype='long', value=0, truncating='post', padding='post')\n    input_ids = pad_sequences(input_ids, maxlen)\n    # Create attention masks\n    attention_masks = []\n    for sent in input_ids:\n        attention_masks.append([int(token_id > 0) for token_id in sent])\n\n    if choices_ids is not None:\n        dataset = TensorDataset(torch.tensor(input_ids, dtype=torch.long), torch.tensor(attention_masks, dtype=torch.long), torch.tensor(choices_ids, dtype=torch.long))\n    else:\n        dataset = TensorDataset(torch.tensor(input_ids, dtype=torch.long), torch.tensor(attention_masks, dtype=torch.long))\n    sampler = sampler_class(dataset)\n    dataloader = DataLoader(dataset, sampler=sampler, batch_size=batch_size)\n    return dataloader\n\n\ndef calc_slope(y):\n    n = len(y)\n    if n == 1:\n        raise ValueError('Can\\'t compute slope for array of length=1')\n    x_mean = (n + 1) / 2\n    x2_mean = (n + 1) * (2 * n + 1) / 6\n    xy_mean = np.average(y, weights=np.arange(1, n + 1))\n    y_mean = np.mean(y)\n    slope = (xy_mean - x_mean * y_mean) / (x2_mean - x_mean * x_mean)\n    return slope"
  },
  {
    "path": "requirements.txt",
    "content": "torch==1.13.1\ntransformers==4.4.2\ntensorboardX==1.9\nlabel-studio>=1.0.0\ngit+git://github.com/heartexlabs/label-studio-ml-backend@master#egg=label-studio-ml\n"
  }
]