diff --git a/.gitignore b/.gitignore index b38a2b8179b5de21e9f22378bce61e56cdbf6085..fc11d864c4ecd7b3c23d92f535468acd398420fe 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,7 @@ datasets/* -lab* \ No newline at end of file +lab* +__pycache__ +token_vocab.pth +label_vocab.pth +lstm.pth +app.log diff --git a/README.md b/README.md index eccc982fde1ec5037c2c425dba5d3515d9120258..96143dbd9a18cc78993fb6f3798d19b753336c2b 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,3 @@ # COM3029 CW - - -## Getting started - -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin https://gitlab.surrey.ac.uk/fw00355/com3029-cw.git -git branch -M main -git push -uf origin main -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](https://gitlab.surrey.ac.uk/fw00355/com3029-cw/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. +Open app/app.ipynb to use the group work application. diff --git a/app/app.ipynb b/app/app.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..26043403de8f7b8461233a6b3d629c0af7485ab8 --- /dev/null +++ b/app/app.ipynb @@ -0,0 +1,174 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# COM3029 NLP Group 3 Group CW Notebook\n", + "\n", + "* Requires python and pip to run the training code\n", + "* Requires docker to run the web server" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Model Training\n", + "* First cell installs dependencies for training \n", + "* Second cell trains the model, outputting the model and vocabs into the server directory\n", + "\n", + "---\n", + "---\n", + "---" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Install training requirements\n", + "%pip install -r train/requirements.txt -q" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Train the model\n", + "%run train/train.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Running Server\n", + "\n", + "* First cell runs the server via docker \n", + "* Second cell closes the server via docker \n", + "\n", + "* Note: can also be ran manually without docker if dependencies are correct\n", + "\n", + "---\n", + "---\n", + "---" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Run the server\n", + "# Note: May take a while...\n", + "!docker compose --progress quiet up -d" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Close the server\n", + "!docker compose down" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Testing server\n", + "\n", + "* First cell clears the log \n", + "* Second cell does a test call to the server \n", + "* Third cell allows you to view the server log\n", + "\n", + "---\n", + "---\n", + "---" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Clear the log\n", + "with open('logs/app.log', 'w') as file:\n", + " file.write('')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Test the server\n", + "%run test/test.py" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# View the log\n", + "import json\n", + "\n", + "with open('logs/app.log', 'r') as file:\n", + " log = [json.loads(line) for line in file]\n", + "\n", + " for entry in log:\n", + " message = json.loads(entry['message'])\n", + " print(f\"Timestamp: {entry['timestamp']}, Input: {message['input']}, Predictions: {message['predictions']}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Stress testing\n", + "\n", + "* TODO: Stress Testing\n", + "* locust testing (https://locust.io/)?\n", + "* 1 long api call test?\n", + "* Maybe both as 2 scripts stored in /test which can be ran here?\n", + "\n", + "---\n", + "---\n", + "---" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.12.3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/app/docker-compose.yml b/app/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1c2e000e920772f5b9b051d3c0b2eaad92095d0b --- /dev/null +++ b/app/docker-compose.yml @@ -0,0 +1,10 @@ +version: '3.8' +services: + server: + build: + context: ./server + image: webserver + ports: + - "5734:5734" + volumes: + - ./logs:/app/logs diff --git a/app/server/Dockerfile b/app/server/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9bef51700a4aa235879e457121cb64564614c67a --- /dev/null +++ b/app/server/Dockerfile @@ -0,0 +1,15 @@ +FROM python:3.9 + +WORKDIR /app + +COPY requirements.txt /app + +RUN pip install -r requirements.txt + +COPY . /app + +RUN python -m spacy download en_core_web_sm + +EXPOSE 5734 + +CMD ["python", "main.py"] diff --git a/app/server/logger.py b/app/server/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..105ae338e77355aaf8b865d876dbf36548878826 --- /dev/null +++ b/app/server/logger.py @@ -0,0 +1,26 @@ +import logging +import json + +# Create logger formatter +class JSONFormatter(logging.Formatter): + def format(self, record): + log_data = { + 'timestamp': self.formatTime(record), + 'level': record.levelname, + 'message': record.getMessage(), + } + return json.dumps(log_data) + +# Create logger +logger = logging.getLogger('json_logger') +logger.setLevel(logging.INFO) + +# Create and link file handler +file_handler = logging.FileHandler('/app/logs/app.log') +file_handler.setLevel(logging.INFO) +file_handler.setFormatter(JSONFormatter()) +logger.addHandler(file_handler) + +# Create log function +def log(message): + logger.info(json.dumps(message)) diff --git a/app/server/main.py b/app/server/main.py new file mode 100644 index 0000000000000000000000000000000000000000..3af662a0e4c681f13b6ee9c6e1f5dac8b92a5aed --- /dev/null +++ b/app/server/main.py @@ -0,0 +1,25 @@ +from pydantic import BaseModel +from fastapi import FastAPI +import uvicorn +from model import predict + +# Create request class +class RequestBody(BaseModel): + text: str + +# Create api app entrypoint +app = FastAPI() + +# Root get request +@app.get("/") +def root(): + return {"/classify": "/classify is a POST endpoint which takes in a text string and returns the classified tokens"} + +# Classify post request +@app.post("/classify") +def classify(args: RequestBody): + return predict(args.text) + +# Run server +if __name__ == "__main__": + uvicorn.run(app, host="0.0.0.0", port=5734) diff --git a/app/server/model.py b/app/server/model.py new file mode 100644 index 0000000000000000000000000000000000000000..328b7766add7c2c7c42be888d8cf8b06f35bce5e --- /dev/null +++ b/app/server/model.py @@ -0,0 +1,51 @@ +import torchtext; torchtext.disable_torchtext_deprecation_warning() +import torch.nn as nn +import torch +import spacy +from logger import log + +# Create LSTM +class LSTM(nn.Module): + def __init__(self, input_dim, embedding_dim, hidden_dim, output_dim): + super().__init__() + self.embedding = nn.Embedding(input_dim, embedding_dim) + self.lstm = nn.LSTM(embedding_dim, hidden_dim, batch_first=True) + self.fc = nn.Linear(hidden_dim, output_dim) + + def forward(self, tokens): + embedded = self.embedding(tokens) + output, _ = self.lstm(embedded) + return self.fc(output) + +# Load vocabs +label_vocab = torch.load("label_vocab.pth") +token_vocab = torch.load("token_vocab.pth") + +# Load model +model = LSTM(len(token_vocab), 100, 256, len(label_vocab)) +model.load_state_dict(torch.load("lstm.pth")) +model.eval() + +# Load tokenizer +tokenizer = spacy.load("en_core_web_sm") + +# Predicts labels via LSTM +# Inputs a string sentence +# Outputs an array of labels +def predict(sentence): + # Preprocess + tokenized = tokenizer(sentence) + tokens = [token.text for token in tokenized] + tokens = [token_vocab[token] for token in tokens] + tokens = torch.tensor(tokens).unsqueeze(0) + + # Predict + with torch.no_grad(): + output = model(tokens) + _, predictions_list = torch.max(output, 2) + predicted = [label_vocab.get_itos()[label.item()] for label in predictions_list.squeeze()] + + # Log values + log({ "input": sentence, "predictions": predicted}) + + return predicted diff --git a/app/server/requirements.txt b/app/server/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..31cb751130569e9fed2609df381cfbd749a7fcb0 --- /dev/null +++ b/app/server/requirements.txt @@ -0,0 +1,5 @@ +fastapi==0.110.3 +uvicorn==0.29.0 +torch==2.3.0 +torchtext==0.18.0 +spacy==3.7.4 diff --git a/app/test/test.py b/app/test/test.py new file mode 100644 index 0000000000000000000000000000000000000000..bd7bee51f43c02a05fa6a38e4c5c075a7970633f --- /dev/null +++ b/app/test/test.py @@ -0,0 +1,17 @@ +import requests + +try: + sentence = "This is a test sentence." + print("Sentence:", sentence) + + response = requests.post( + "http://localhost:5734/classify", + json = { "text": sentence } + ) + + if response.status_code == 200: + print("Predicted:", response.json()) + else: + print("Error:", response.text) +except: + print("An unexpected error has occurred, is the server online?") diff --git a/app/train/requirements.txt b/app/train/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..e3b9fd491c7b2e36622de0ed37cc5cca7f016ec2 --- /dev/null +++ b/app/train/requirements.txt @@ -0,0 +1,5 @@ +datasets==2.19.0 +scikit-learn==1.4.2 +torch==2.3.0 +torchtext==0.18.0 +pandas==2.2.2 diff --git a/app/train/train.py b/app/train/train.py new file mode 100644 index 0000000000000000000000000000000000000000..eca6ff23b7ffcc3d8df6321628b7b61c5f949321 --- /dev/null +++ b/app/train/train.py @@ -0,0 +1,170 @@ +import torchtext; torchtext.disable_torchtext_deprecation_warning() +import torch +from datasets import load_dataset +from torchtext.data.functional import to_map_style_dataset +from torchtext.vocab import build_vocab_from_iterator, vocab +from collections import OrderedDict +from torch.utils.data import Dataset, DataLoader +from torch.nn.utils.rnn import pad_sequence +from pandas import DataFrame +from sklearn.metrics import confusion_matrix, f1_score +import torch.optim as optim +import torch.nn as nn + +# Inits +DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") +torch.manual_seed(1234) +torch.backends.cudnn.deterministic = True + +# Load dataset +raw_dataset = load_dataset("surrey-nlp/PLOD-CW") + +# Convert raw dataset into maps +train_dataset = to_map_style_dataset(raw_dataset['train']) +validation_dataset = to_map_style_dataset(raw_dataset['validation']) +test_dataset = to_map_style_dataset(raw_dataset['test']) + +# Create vocabs +def token_vocab_iterator(data): + for item in data: + yield item['tokens'] + +token_vocab = build_vocab_from_iterator(token_vocab_iterator(train_dataset), specials=("<unk>", "<pad>"), max_tokens=50_000) +token_vocab.set_default_index(token_vocab["<unk>"]) + +label_vocab = vocab(OrderedDict([("<pad>", 1), ("B-O", 1), ("B-AC", 1), ("B-LF", 1), ("I-LF", 1)])) + +# Create LSTM +class LSTM(nn.Module): + def __init__(self, input_dim, embedding_dim, hidden_dim, output_dim): + super().__init__() + self.embedding = nn.Embedding(input_dim, embedding_dim) + self.lstm = nn.LSTM(embedding_dim, hidden_dim, batch_first=True) + self.fc = nn.Linear(hidden_dim, output_dim) + + def forward(self, tokens): + embedded = self.embedding(tokens) + output, _ = self.lstm(embedded) + return self.fc(output) + +# Create dataloader functions +class SeqClassDataset(Dataset): + def __init__(self, data, token_vocab, label_vocab): + self.data = data + self.token_vocab = token_vocab + self.label_vocab = label_vocab + + def __len__(self): + return len(self.data) + + def __getitem__(self, idx): + tokens = self.data[idx]['tokens'] + ner_tags = self.data[idx]['ner_tags'] + token_numerical = [self.token_vocab[token] for token in tokens] + label_numerical = [self.label_vocab[label] for label in ner_tags] + + return torch.tensor(token_numerical, dtype=torch.long), torch.tensor(label_numerical, dtype=torch.long) + +def collate_batch(batch): + labels, tokens = zip(*batch) + + tokens_padded = pad_sequence(tokens, batch_first=True, padding_value=token_vocab['<pad>']) + labels_padded = pad_sequence(labels, batch_first=True, padding_value=label_vocab['<pad>']) + + return tokens_padded, labels_padded + +def create_dataloader(data): + return DataLoader(data, batch_size=64, shuffle=True, collate_fn=collate_batch) + +# Create training helper functions +def train(model, iterator, optimizer, criterion): + epoch_loss = 0 + model.train() + + for batch in iterator: + labels, tokens = batch + optimizer.zero_grad() + + predictions = model(tokens) + predictions = predictions.view(-1, predictions.shape[-1]) + labels = labels.view(-1) + + loss = criterion(predictions, labels) + loss.backward() + optimizer.step() + epoch_loss += loss.item() + + return epoch_loss / len(iterator) + +def evaluate(model, iterator, criterion): + epoch_loss = 0 + model.eval() + + with torch.no_grad(): + for batch in iterator: + labels, tokens = batch + + predictions = model(tokens) + predictions = predictions.view(-1, predictions.shape[-1]) + labels = labels.view(-1) + labels = labels - 1 + + loss = criterion(predictions, labels) + epoch_loss += loss.item() + + return epoch_loss / len(iterator) + +# Create predict and metrics functions +def predict(model, iterator): + model.eval() + + with torch.no_grad(): + for batch in iterator: + labels, tokens = batch + + predictions_list = model(tokens).argmax(dim=2).tolist() + labels_list = labels.tolist() + + predicted = [[label_vocab.get_itos()[index] for index in sentence] for sentence in predictions_list] + actual = [[label_vocab.get_itos()[index] for index in sentence] for sentence in labels_list] + + return predicted, actual + +def calculate_metrics(predicted, actual): + predicted_flat = [tag for sublist in predicted for tag in sublist] + actual_flat = [tag for sublist in actual for tag in sublist] + + labels = ['B-O', 'B-AC', 'B-LF', 'I-LF'] + cm = DataFrame(confusion_matrix(actual_flat, predicted_flat, labels=labels), index=labels, columns=labels) + f1 = f1_score(actual_flat, predicted_flat, average='weighted', labels=labels) + + return cm, f1 + +# Train LSTM model +train_dataloader = create_dataloader(SeqClassDataset(train_dataset, token_vocab, label_vocab)) +validation_dataloader = create_dataloader(SeqClassDataset(validation_dataset, token_vocab, label_vocab)) +test_dataloader = create_dataloader(SeqClassDataset(test_dataset, token_vocab, label_vocab)) + +model = LSTM(len(token_vocab), 100, 256, len(label_vocab)) +optimizer = optim.Adam(model.parameters()) +criterion = nn.CrossEntropyLoss() + +for epoch in range(25): + train_loss = train(model, train_dataloader, optimizer, criterion) + validation_loss = evaluate(model, validation_dataloader, criterion) + print("epoch {:<2d} train_loss {:.3f} validation_loss {:.3f}".format(epoch, train_loss, validation_loss)) + +torch.save(model.state_dict(), 'server/lstm.pth') +torch.save(token_vocab, 'server/token_vocab.pth') +torch.save(label_vocab, 'server/label_vocab.pth') +print() + +# Predictions for LSTM model +predicted, actual = predict(model, test_dataloader) + +cm, f1 = calculate_metrics(predicted, actual) + +print("f1", f1) +print() +print(cm) +print()