diff --git a/DO.eval b/DO.eval
new file mode 100755
index 0000000000000000000000000000000000000000..a860322981e1a9439d0a9e0c2837bf1ff07c10a4
--- /dev/null
+++ b/DO.eval
@@ -0,0 +1,39 @@
+#!/bin/bash
+
+ABS_PATH="$(dirname -- "${BASH_SOURCE[0]}")"
+ABS_PATH="$(cd -- "${ABS_PATH}" && pwd)"
+
+mwoz_path=${ABS_PATH}/MultiWOZ_2.1
+trippy_path=${ABS_PATH}/trippy-public
+export PYTHONPATH=${trippy_path}:${PYTHONPATH}
+
+# Convert ChatGPT output into TripPy-style predictions
+python3 convert_to_pred.py --dataset_folder ${mwoz_path} --dataset_config ${trippy_path}/dataset_config/multiwoz21.json --data_folder data --out_file preds.json
+
+# TripPy-style evaluation
+python3 metric_dst.py --dataset_config  ${trippy_path}/dataset_config/multiwoz21.json --file_list preds.json >& eval_chatgpt.log
+
+# Print some statistics
+echo "Missed none:"; cat eval_chatgpt.log | grep "Missed none" | wc -l
+echo "Missed dontcare:"; cat eval_chatgpt.log | grep "Missed dontcare" | wc -l
+echo "Missed copy_value:"; cat eval_chatgpt.log | grep "Missed copy_value" | wc -l
+echo "Missed true:"; cat eval_chatgpt.log | grep "Missed true" | wc -l
+echo "Missed false:"; cat eval_chatgpt.log | grep "Missed false" | wc -l
+echo "Missed refer:"; cat eval_chatgpt.log | grep "Missed refer" | wc -l
+echo "Missed inform:"; cat eval_chatgpt.log | grep "Missed inform" | wc -l
+
+echo "None -> dontcare:"; cat eval_chatgpt.log | grep "Missed none: dontcare" | wc -l
+
+# Evaluate per domain
+for domain in attraction hotel restaurant taxi train; do
+    python3 filter_mwoz_diags.py \
+            --input_file=${mwoz_path}/test_dials.json \
+            --out_list=${domain}_list.txt \
+            --not_domain=${domain}
+    python3 metric_dst.py \
+	    --dataset_config  ${trippy_path}/dataset_config/multiwoz21.json \
+	    --file_list preds.json \
+	    --domain ${domain} \
+	    --filter_list=${domain}_list.txt \
+	    >& eval_chatgpt_${domain}.log
+done
diff --git a/DO.prepare b/DO.prepare
new file mode 100755
index 0000000000000000000000000000000000000000..112ffd838d3d3ab0c0e50a5935083f07c5d9e537
--- /dev/null
+++ b/DO.prepare
@@ -0,0 +1,13 @@
+#!/bin/bash
+
+#git clone https://github.com/budzianowski/multiwoz.git
+#git clone https://gitlab.cs.uni-duesseldorf.de/general/dsml/trippy-public.git
+
+cp -r /gpfs/project/heckmi/tools/trippy-public .
+mkdir -p multiwoz/data
+cp /gpfs/project/heckmi/data/multiwoz/data/MultiWOZ_2.1.zip multiwoz/data
+
+unzip multiwoz/data/MultiWOZ_2.1.zip
+python3 trippy-public/data/split_multiwoz_data.py --data_dir MultiWOZ_2.1
+
+unzip data.zip
diff --git a/README.md b/README.md
index 3952229785d5259c96eace213ee82db2cde01777..a2beab75ee4bc700895d4d025136341fb843ec64 100644
--- a/README.md
+++ b/README.md
@@ -1,92 +1,29 @@
-# ChatGPT-DST - Public
+## Introduction
 
+This is the repository for our paper [ChatGPT for Zero-shot Dialogue State Tracking: A Solution or an Opportunity?](https://aclanthology.org/2023.acl-short.81). We provide our raw log files and the evaluation code used to compute the experimental results that we present in the paper.
 
+## How to run
 
-## Getting started
+`DO.prepare` will clone the [MultiWOZ 2.1](https://github.com/budzianowski/multiwoz.git) dataset and the [TripPy](https://gitlab.cs.uni-duesseldorf.de/general/dsml/trippy-public) code. It will prepare the train/dev/test split of the dataset and unpack the raw log files.
 
-To make it easy for you to get started with GitLab, here's a list of recommended next steps.
+`DO.eval` will convert the raw log files into TripPy-style predictions, run the TripPy-style evaluation and print some statistics. Said evaluation is done across domains. Additionally, this script also runs the evaluation per domain. Detailed results, errors and performance metrics are found in the respective log files.
 
-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)!
+## Citation
 
-## Add your files
+This work is published as [ChatGPT for Zero-shot Dialogue State Tracking: A Solution or an Opportunity?](https://aclanthology.org/2023.acl-short.81)
 
-- [ ] [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:
+If you use our logs or code for your own work, please cite our work as follows:
 
 ```
-cd existing_repo
-git remote add origin https://gitlab.cs.uni-duesseldorf.de/general/dsml/chatgpt-dst-public.git
-git branch -M main
-git push -uf origin main
+@inproceedings{heck-etal-2023-chatgpt,
+    title = "{C}hat{GPT} for Zero-shot Dialogue State Tracking: A Solution or an Opportunity?",
+    author = "Heck, Michael and Lubis, Nurul and Ruppik, Benjamin and Vukovic, Renato and Feng, Shutong and
+              Geishauser, Christian and Lin, Hsien-chin and van Niekerk, Carel and Gasic, Milica",
+    booktitle = "Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 2: Short Papers)",
+    month = jul,
+    year = "2023",
+    address = "Toronto, Canada",
+    publisher = "Association for Computational Linguistics",
+    pages = "936--950",
+}
 ```
-
-## Integrate with your tools
-
-- [ ] [Set up project integrations](https://gitlab.cs.uni-duesseldorf.de/general/dsml/chatgpt-dst-public/-/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/)
-- [ ] [Automatically merge when pipeline succeeds](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!). Thank you 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.
diff --git a/convert_to_pred.py b/convert_to_pred.py
new file mode 100644
index 0000000000000000000000000000000000000000..47ac7e4709c37191b3ec0ccc3990032a72596ccb
--- /dev/null
+++ b/convert_to_pred.py
@@ -0,0 +1,287 @@
+# coding=utf-8
+#
+# Copyright 2022-2023 Heinrich Heine University Duesseldorf
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import argparse
+import os
+import glob
+import re
+import json
+from tqdm import tqdm
+
+import dataset_multiwoz21
+
+
+def prediction_normalization(slot, value):
+    def _normalize_time(text):
+        informed = False
+        if text[:2] == '§§':
+            informed = True
+            text = text[2:]
+        text = re.sub("noon", r"12:00", text) # noon
+        text = re.sub("(\d{1})(a\.?m\.?|p\.?m\.?)", r"\1 \2", text) # am/pm without space
+        text = re.sub("(^| )(\d{1,2}) ?[^0-9]? ?(\d{2})", r"\1\2:\3", text) # Missing/wrong separator
+        text = re.sub("(^| )(\d{1,2})( |$)", r"\1\2:00\3", text) # normalize simple full hour time
+        text = re.sub("(^| )(\d{1}:\d{2})", r"\g<1>0\2", text) # Add missing leading 0
+        # Map 12 hour times to 24 hour times
+        text = re.sub("(\d{2})(:\d{2}) ?p\.?m\.?", lambda x: str(int(x.groups()[0]) + 12 if int(x.groups()[0]) < 12 else int(x.groups()[0])) + x.groups()[1], text)
+        text = re.sub("(^| )24:(\d{2})", r"\g<1>00:\2", text) # Correct times that use 24 as hour
+        final = re.match(".*((before|after) \d{2}:\d{2})", text)
+        result = text
+        if final is not None:
+            result = final[1]
+        final = re.match(".*(\d{2}:\d{2})", text)
+        if final is not None:
+            result = final[1]
+        if informed and result[:2] != '§§':
+            return '§§' + result
+        return result
+
+    def _normalize_value(text):
+        text = re.sub(" ?' ?s", "s", text)
+        return text
+
+    value = value.lower()
+    
+    if "leave" in slot or "arrive" in slot or "time" in slot:
+        if isinstance(value, list):
+            for e_itr in range(len(value)):
+                for ee_itr in range(len(value[e_itr])):
+                    tmp = list(value[e_itr][ee_itr])
+                    tmp[0] = _normalize_time(tmp[0])
+                    value[e_itr][ee_itr] = tuple(tmp)
+        else:
+            value = _normalize_time(value)
+    else:
+        value = _normalize_value(value)
+
+    if slot == "hotel-type":
+        value = "true" if value == "hotel" else value
+        value = "false" if value == "guest house" else value
+                
+    return value
+
+
+def load_dataset(data_dir, dataset_config):
+    # Load dataset config file.
+    with open(dataset_config, "r", encoding='utf-8') as f:
+        raw_config = json.load(f)
+    class_types = raw_config['class_types'] # Required
+    slot_list = raw_config['slots']
+    label_maps = raw_config['label_maps']
+    examples = dataset_multiwoz21.create_examples(os.path.join(data_dir, 'test_dials.json'),
+                                                  'test', class_types, slot_list, label_maps)
+    result = {}
+    for e in examples:
+        guid = e.guid.split('-')[1][:-5]
+        turn = int(e.guid.split('-')[2])
+        if turn == 0:
+            result[guid] = {}
+        values = e.values
+        class_label = e.class_label
+        result[guid][turn] = {"values": values, "class_label": class_label}
+    return result, slot_list
+
+
+def format_output(dataset, predictions, slot_list, with_request=False):
+    prediction_list = []
+    pred_slot_dict = {}
+    for diag_id in predictions:
+        diag_id = re.sub(".txt|.json", "", diag_id)
+        dialog_state = {slot: 'none' for slot in slot_list}
+        for turn in predictions[diag_id]:
+            if turn not in dataset[diag_id]:
+                print("WARNING: turn %s not in dialog %s! Ignoring prediction." % (turn, diag_id))
+                continue
+            prediction = {}
+            prediction['guid'] = ['test', diag_id, int(turn)]
+            prediction['input_ids'] = []
+            for e in predictions[diag_id][turn]:
+                if e not in pred_slot_dict:
+                    pred_slot_dict[e] = 0
+                pred_slot_dict[e] += 1
+            for slot in slot_list:
+                class_type = 0
+                if dataset[diag_id][turn]["class_label"][slot] == 'dontcare':
+                    class_type = 1
+                elif dataset[diag_id][turn]["class_label"][slot] == 'copy_value':
+                    class_type = 2
+                elif dataset[diag_id][turn]["class_label"][slot] == 'true':
+                    class_type = 3
+                elif dataset[diag_id][turn]["class_label"][slot] == 'false':
+                    class_type = 4
+                elif dataset[diag_id][turn]["class_label"][slot] == 'refer':
+                    class_type = 5
+                elif dataset[diag_id][turn]["class_label"][slot] == 'inform':
+                    class_type = 6
+                elif dataset[diag_id][turn]["class_label"][slot] == 'request':
+                    class_type = 7
+
+                pred_class_type = 0
+                pred_hit = False
+                pred_slot = slot
+                for ps in predictions[diag_id][turn]:
+                    if ps == slot:
+                        pred_hit = True
+                        pred_slot = slot
+
+                if pred_hit:
+                    pred_val = predictions[diag_id][turn][pred_slot]
+                    if pred_val == "?":
+                        pred_val = "none"
+                        pred_class_type = 7 if with_request else 0
+                    if pred_val == "dontcare":
+                        pred_val = "dontcare"
+                        pred_class_type = 1
+                    elif pred_val == "yes":
+                        pred_val = "true"
+                        pred_class_type = 3
+                    elif pred_val == "no":
+                        pred_val = "false"
+                        pred_class_type = 4
+                    if pred_val not in ["none", "dontcare", "true", "false"]:
+                        dialog_state[slot] = prediction_normalization(slot, str(pred_val))
+                        pred_class_type = 2 # We can not distinguish refer (5) and inform (6) cases from copy_value (2)
+                    else:
+                        dialog_state[slot] = pred_val
+
+                prediction['class_prediction_%s' % slot] = pred_class_type
+                prediction['class_label_id_%s' % slot] = class_type
+                prediction['start_prediction_%s' % slot] = 0
+                prediction['start_pos_%s' % slot] = 0
+                prediction['end_prediction_%s' % slot] = 0
+                prediction['end_pos_%s' % slot] = 0
+                prediction['refer_prediction_%s' % slot] = 0
+                prediction['refer_id_%s' % slot] = 0
+                prediction['slot_prediction_%s' % slot] = dialog_state[slot]
+                prediction['slot_groundtruth_%s' % slot] = dataset[diag_id][turn]["values"][slot]
+
+            prediction_list.append(prediction)
+        
+    return prediction_list, pred_slot_dict
+
+
+def main():
+    parser = argparse.ArgumentParser()
+
+    # Required parameters
+    parser.add_argument("--dataset_folder", default=None, type=str, required=True,
+                        help="Folder containing dataset.")
+    parser.add_argument("--dataset_config", default=None, type=str, required=True,
+                        help="Dataset config file.")
+    parser.add_argument("--with_request", action='store_true',
+                        help="Whether or not to add request class_type")
+    parser.add_argument("--data_folder", default=None, type=str, required=True,
+                        help="Folder containing raw data.")
+    parser.add_argument("--out_file", default=None, type=str, required=True,
+                        help="Output file.")
+
+    args = parser.parse_args()
+
+    dataset, slot_list = load_dataset(args.dataset_folder, args.dataset_config)
+    
+    data_files = list(sorted(glob.glob(args.data_folder + '/*')))
+
+    predictions = {}
+    for data_file in tqdm(data_files, desc="Formatting predictions"):
+        diag_id = re.search("([^_/]+)(.txt|.json|$)", data_file)
+        diag_id = re.sub(".txt|.json", "", diag_id[1])
+        diag_id = diag_id.strip()
+        with open(data_file, "r", encoding='utf-8') as reader:
+            turn_itr = -1
+            data = reader.readlines()
+            ds = {}
+            sys_seen = False
+            usr_seen = False
+            for line in data:
+                if re.match("^\"system\": ", line):
+                    sys_seen = True
+                    usr_seen = False
+                    continue
+                if re.match("^\"user\": ", line):
+                    if sys_seen:
+                        sys_seen = False
+                        usr_seen = True
+                        turn_itr += 1
+                        ds[turn_itr] = ""
+                        continue
+                    else:
+                        print("ERROR: User utterance seen without preceeding system utterance. Aborting.")
+                        exit(-1)
+                if usr_seen:
+                    ds[turn_itr] += line
+            if turn_itr > -1:
+                for e in ds:
+                    ds[e] = re.sub("} *\n *{", "},{", ds[e])
+                    ds[e] = re.sub("\" *\n *\"", "\",\"", ds[e])
+                    ds[e] = re.sub("\n", "", ds[e])
+                    ds[e] = re.sub("### Turn [0-9]*", "", ds[e])
+            else:
+                print("ERROR: Empty dialog? Aborting.")
+                exit(-1)
+
+            all_empty = True
+            for e_itr, e in enumerate(ds):
+                norm_e = re.search("{.*}", ds[e])
+                if not norm_e:
+                    norm_e = re.search("\[.*\]", ds[e])
+                if norm_e:
+                    xx = re.findall("{\"slot\":.*?\"value\".*?}", norm_e[0])
+                    if xx:
+                        norm_e = [""]
+                        for e in xx:
+                            if len(norm_e[0]) != 0:
+                                norm_e[0] += ","
+                            tmp_dict = dict(eval(e))
+                            norm_e[0] += "\"%s\": \"%s\"" % (tmp_dict["slot"], tmp_dict["value"])
+                    
+                    norm_e = re.sub("[{}]", "", norm_e[0])
+
+                    if re.search(".+\[.+\].+", norm_e):
+                        sublist = re.search("\[.+\]", norm_e)
+                        start, end = sublist.span()
+                        new_span = "\"%s\"" % (eval(sublist[0])[0])
+                        norm_e = norm_e[:start] + new_span + norm_e[end:]
+
+                    norm_e = re.sub("[\[\]]", "", norm_e)
+
+                    if norm_e == '""':
+                        norm_e = ""
+                    if ":" not in norm_e:
+                        norm_e = ""
+
+                    dict_e = dict(eval("{%s}" % norm_e))
+                else:
+                    try:
+                        dict_e = dict(eval("{%s}" % ds[e]))
+                    except:
+                        dict_e = {}
+                if e_itr == 0:
+                    if diag_id in predictions:
+                        print("WARNING: Possible duplicate:", diag_id)
+                    predictions[diag_id] = {}
+                predictions[diag_id][e_itr] = dict_e
+                if len(predictions[diag_id][e_itr]) > 0:
+                    all_empty = False
+            if all_empty:
+                print("WARNING: all predictions for dialog %s are empty!" % (diag_id))
+
+    output, pred_slots = format_output(dataset, predictions, slot_list, args.with_request)
+    with open(args.out_file, "w") as f:
+        json.dump(output, f, indent=2)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/data.zip b/data.zip
new file mode 100644
index 0000000000000000000000000000000000000000..e06581790d19d1a3da78892cfc093cc0f819e9e2
Binary files /dev/null and b/data.zip differ
diff --git a/filter_mwoz_diags.py b/filter_mwoz_diags.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc9685d26ec50e74fca9387eb118b630023cee5b
--- /dev/null
+++ b/filter_mwoz_diags.py
@@ -0,0 +1,64 @@
+# coding=utf-8
+#
+# Copyright 2020-2023 Heinrich Heine University Duesseldorf
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import json
+import argparse
+
+
+DOMAINS = ["taxi", "restaurant", "hotel", "attraction", "train"]
+
+
+def filter_mwoz_diags(input_file, not_domain=None):
+    with open(input_file, "r", encoding='utf-8') as reader:
+        input_data = json.load(reader)
+
+    new_diag_list = []
+    for dialog_id in input_data:
+        entry = input_data[dialog_id]
+        goal = entry['goal']
+
+        # Only keep dialogues that exclusively contain not_domain.
+        skip = False
+        if len(goal[not_domain]) == 0:
+            skip = True
+
+        if skip:
+            continue
+
+        new_diag_list.append(dialog_id.split('.')[0])
+
+    return new_diag_list
+
+
+def main():
+    parser = argparse.ArgumentParser()
+
+    # Required parameters
+    parser.add_argument("--input_file", default=None, type=str, required=True, help="")
+    parser.add_argument("--out_list", default=None, type=str, required=True, help="")
+    parser.add_argument("--not_domain", default=None, type=str, required=False, help="")
+
+    args = parser.parse_args()
+
+    new_diag_list = filter_mwoz_diags(args.input_file, args.not_domain)
+
+    with open(args.out_list, 'w') as f:
+        for l in new_diag_list:
+            f.write("%s\n" % l)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/metric_dst.py b/metric_dst.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bbe53652e3948464146f974eb93eae7523dbbdd
--- /dev/null
+++ b/metric_dst.py
@@ -0,0 +1,307 @@
+# coding=utf-8
+#
+# Copyright 2020-2023 Heinrich Heine University Duesseldorf
+#
+# Part of this code is based on the source code of BERT-DST
+# (arXiv:1907.03040)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import glob
+import json
+import sys
+import numpy as np
+import re
+import argparse
+
+
+def load_dataset_config(dataset_config):
+    with open(dataset_config, "r", encoding='utf-8') as f:
+        raw_config = json.load(f)
+    return raw_config['class_types'], raw_config['slots'], raw_config['label_maps']
+
+
+def tokenize(text):
+    if "\u0120" in text:
+        text = re.sub(" ", "", text)
+        text = re.sub("\u0120", " ", text)
+        text = text.strip()
+    return ' '.join([tok for tok in map(str.strip, re.split("(\W+)", text)) if len(tok) > 0])
+
+
+def is_in_list(tok, value):
+    found = False
+    tok_list = [item for item in map(str.strip, re.split("(\W+)", tok)) if len(item) > 0]
+    value_list = [item for item in map(str.strip, re.split("(\W+)", value)) if len(item) > 0]
+    tok_len = len(tok_list)
+    value_len = len(value_list)
+    for i in range(tok_len + 1 - value_len):
+        if tok_list[i:i + value_len] == value_list:
+            found = True
+            break
+    return found
+
+
+def check_slot_inform(value_label, inform_label, label_maps):
+    value = inform_label
+    if value_label == inform_label:
+        value = value_label
+    elif is_in_list(inform_label, value_label):
+        value = value_label
+    elif is_in_list(value_label, inform_label):
+        value = value_label
+    elif inform_label in label_maps:
+        for inform_label_variant in label_maps[inform_label]:
+            if value_label == inform_label_variant:
+                value = value_label
+                break
+            elif is_in_list(inform_label_variant, value_label):
+                value = value_label
+                break
+            elif is_in_list(value_label, inform_label_variant):
+                value = value_label
+                break
+    elif value_label in label_maps:
+        for value_label_variant in label_maps[value_label]:
+            if value_label_variant == inform_label:
+                value = value_label
+                break
+            elif is_in_list(inform_label, value_label_variant):
+                value = value_label
+                break
+            elif is_in_list(value_label_variant, inform_label):
+                value = value_label
+                break
+    return value
+
+
+def get_joint_slot_correctness(fp, class_types, label_maps,
+                               key_class_label_id='class_label_id',
+                               key_class_prediction='class_prediction',
+                               key_start_pos='start_pos',
+                               key_start_prediction='start_prediction',
+                               key_end_pos='end_pos',
+                               key_end_prediction='end_prediction',
+                               key_refer_id='refer_id',
+                               key_refer_prediction='refer_prediction',
+                               key_slot_groundtruth='slot_groundtruth',
+                               key_slot_prediction='slot_prediction',
+                               filter_list=None):
+    with open(fp) as f:
+        preds = json.load(f)
+        class_correctness = [[] for cl in range(len(class_types) + 1)]
+        pos_correctness = []
+        refer_correctness = []
+        val_correctness = []
+        total_correctness = []
+        per_class_errors = {ct: 0 for ct in range(len(class_types))}
+        per_class_cnt = {ct: 0 for ct in range(len(class_types))}
+
+        for pred in preds:
+            guid = pred['guid']  # List: set_type, dialogue_idx, turn_idx
+
+            if filter_list and guid[1].split('.')[0] not in filter_list:
+                continue
+            
+            turn_gt_class = pred[key_class_label_id]
+            turn_pd_class = pred[key_class_prediction]
+            gt_start_pos = pred[key_start_pos]
+            pd_start_pos = pred[key_start_prediction]
+            gt_end_pos = pred[key_end_pos]
+            pd_end_pos = pred[key_end_prediction]
+            gt_refer = pred[key_refer_id]
+            pd_refer = pred[key_refer_prediction]
+            gt_slot = pred[key_slot_groundtruth]
+            pd_slot = pred[key_slot_prediction]
+
+            gt_slot = tokenize(gt_slot)
+            pd_slot = tokenize(pd_slot)
+
+            # Make sure the true turn labels are contained in the prediction json file!
+            joint_gt_slot = gt_slot
+        
+            if guid[-1] == '0': # First turn, reset the slots
+                joint_pd_slot = 'none'
+
+            if pd_slot[0:3] == "§§ ":
+                if pd_slot[3:] != 'none':
+                    joint_pd_slot = check_slot_inform(joint_gt_slot, pd_slot[3:], label_maps)
+            elif pd_slot[0:2] == "§§":
+                if pd_slot[2:] != 'none':
+                    joint_pd_slot = check_slot_inform(joint_gt_slot, pd_slot[2:], label_maps)
+            else:
+                joint_pd_slot = pd_slot
+            
+            total_correct = True
+
+            per_class_cnt[turn_gt_class] += 1
+            if joint_pd_slot != joint_gt_slot:
+                per_class_errors[turn_gt_class] += 1
+                print("  [%s] Missed %s: %s (should be %s) (turn_gt_class %s vs. turn_pd_class %s)" % (guid, class_types[turn_gt_class], joint_pd_slot, joint_gt_slot, turn_gt_class, turn_pd_class))
+                    
+            # Check the per turn correctness of the class_type prediction
+            if turn_gt_class == turn_pd_class:
+                class_correctness[turn_gt_class].append(1.0)
+                class_correctness[-1].append(1.0)
+                # Only where there is a span, we check its per turn correctness
+                if turn_gt_class == class_types.index('copy_value'):
+                    if gt_start_pos == pd_start_pos and gt_end_pos == pd_end_pos:
+                        pos_correctness.append(1.0)
+                    else:
+                        pos_correctness.append(0.0)
+                # Only where there is a referral, we check its per turn correctness
+                if 'refer' in class_types and turn_gt_class == class_types.index('refer'):
+                    if gt_refer == pd_refer:
+                        refer_correctness.append(1.0)
+                        print("  [%s] Correct referral: %s | %s" % (guid, gt_refer, pd_refer))
+                    else:
+                        refer_correctness.append(0.0)
+                        print("  [%s] Incorrect referral: %s | %s" % (guid, gt_refer, pd_refer))
+            else:
+                if turn_gt_class == class_types.index('copy_value'):
+                    pos_correctness.append(0.0)
+                if 'refer' in class_types and turn_gt_class == class_types.index('refer'):
+                    refer_correctness.append(0.0)
+                class_correctness[turn_gt_class].append(0.0)
+                class_correctness[-1].append(0.0)
+
+            # Check the joint slot correctness.
+            # If the value label is not none, then we need to have a value prediction.
+            # Even if the class_type is 'none', there can still be a value label,
+            # it might just not be pointable in the current turn. It might however
+            # be referrable and thus predicted correctly.
+            if joint_gt_slot == joint_pd_slot:
+                val_correctness.append(1.0)
+            elif joint_gt_slot != 'none' and joint_gt_slot != 'dontcare' and joint_gt_slot != 'true' and joint_gt_slot != 'false' and joint_gt_slot in label_maps:
+                no_match = True
+                for variant in label_maps[joint_gt_slot]:
+                    if variant == joint_pd_slot:
+                        no_match = False
+                        break
+                if no_match:
+                    val_correctness.append(0.0)
+                    total_correct = False
+                    print("  [%s] Incorrect value (variant): %s (turn class: %s) | %s (turn class: %s)" % (guid, joint_gt_slot, turn_gt_class, joint_pd_slot, turn_pd_class))
+                else:
+                    val_correctness.append(1.0)
+            else:
+                val_correctness.append(0.0)
+                total_correct = False
+                print("  [%s] Incorrect value: %s (turn class: %s) | %s (turn class: %s)" % (guid, joint_gt_slot, turn_gt_class, joint_pd_slot, turn_pd_class))
+
+            total_correctness.append(1.0 if total_correct else 0.0)
+
+        # Account for empty lists (due to no instances of spans or referrals being seen)
+        if pos_correctness == []:
+            pos_correctness.append(1.0)
+        if refer_correctness == []:
+            refer_correctness.append(1.0)
+
+        return np.asarray(total_correctness), np.asarray(val_correctness), np.asarray(class_correctness), np.asarray(pos_correctness), np.asarray(refer_correctness), per_class_errors, per_class_cnt
+
+
+if __name__ == "__main__":
+    acc_list = []
+    s_acc_list = []
+    key_class_label_id = 'class_label_id_%s'
+    key_class_prediction = 'class_prediction_%s'
+    key_start_pos = 'start_pos_%s'
+    key_start_prediction = 'start_prediction_%s'
+    key_end_pos = 'end_pos_%s'
+    key_end_prediction = 'end_prediction_%s'
+    key_refer_id = 'refer_id_%s'
+    key_refer_prediction = 'refer_prediction_%s'
+    key_slot_groundtruth = 'slot_groundtruth_%s'
+    key_slot_prediction = 'slot_prediction_%s'
+
+    parser = argparse.ArgumentParser()
+
+    # Required parameters
+    parser.add_argument("--dataset_config", default=None, type=str, required=True,
+                        help="Dataset configuration file.")
+    parser.add_argument("--file_list", default=None, type=str, required=True,
+                        help="List of input files.")
+    parser.add_argument("--domain", default=None, type=str,
+                        help="If specified, only this domain will be evaluated.")
+    parser.add_argument("--filter_list", default=None, type=str,
+                        help="If specified, only dialogues listed in this file will be considered.")
+
+    args = parser.parse_args()
+
+    class_types, slots, label_maps = load_dataset_config(args.dataset_config)
+
+    if args.domain is not None:
+        slots = [s for s in slots if args.domain.lower() in s]
+
+    filter_list = None
+    if args.filter_list is not None:
+        with open(args.filter_list, "r", encoding='utf-8') as f:
+            filter_list = f.read().splitlines()
+
+    # Prepare label_maps
+    label_maps_tmp = {}
+    for v in label_maps:
+        label_maps_tmp[tokenize(v)] = [tokenize(nv) for nv in label_maps[v]]
+    label_maps = label_maps_tmp
+
+    for fp in sorted(glob.glob(args.file_list)):
+        # Infer slot list from data if not provided.
+        if len(slots) == 0:
+            with open(fp) as f:
+                preds = json.load(f)
+                for e in preds[0]:
+                    slot = re.match("^slot_groundtruth_(.*)$", e)
+                    slot = slot[1] if slot else None
+                    if slot and slot not in slots:
+                        slots.append(slot)
+        print(fp)
+        goal_correctness = 1.0
+        slot_correctness = 0.0
+        per_cls_err = {ct: 0 for ct in range(len(class_types))}
+        per_cls_cnt = {ct: 0 for ct in range(len(class_types))}
+        for slot in slots:
+            tot_cor, joint_val_cor, cls_cor, pos_cor, ref_cor, pce, pcc = get_joint_slot_correctness(fp, class_types, label_maps,
+                                                             key_class_label_id=(key_class_label_id % slot),
+                                                             key_class_prediction=(key_class_prediction % slot),
+                                                             key_start_pos=(key_start_pos % slot),
+                                                             key_start_prediction=(key_start_prediction % slot),
+                                                             key_end_pos=(key_end_pos % slot),
+                                                             key_end_prediction=(key_end_prediction % slot),
+                                                             key_refer_id=(key_refer_id % slot),
+                                                             key_refer_prediction=(key_refer_prediction % slot),
+                                                             key_slot_groundtruth=(key_slot_groundtruth % slot),
+                                                             key_slot_prediction=(key_slot_prediction % slot),
+                                                             filter_list=filter_list)
+            print('%s: joint slot acc: %g, joint value acc: %g, turn class acc: %g, turn position acc: %g, turn referral acc: %g' %
+                  (slot, np.mean(tot_cor), np.mean(joint_val_cor), np.mean(cls_cor[-1]), np.mean(pos_cor), np.mean(ref_cor)))
+            goal_correctness *= tot_cor
+            slot_correctness += tot_cor
+            for cl_a in range(len(class_types)):
+                per_cls_err[cl_a] += pce[cl_a]
+                per_cls_cnt[cl_a] += pcc[cl_a]
+
+        print("Errors per groundtruth class:")
+        for cl_itr, cl_a in enumerate(class_types):
+            print("%s: %s of %s" % (cl_a, per_cls_err[cl_itr], per_cls_cnt[cl_itr]))
+            
+        acc = np.mean(goal_correctness)
+        acc_list.append((fp, acc))
+        slot_acc = np.mean(slot_correctness / len(slots))
+        s_acc_list.append((fp, slot_acc))
+
+    s_acc_list_s = sorted(s_acc_list, key=lambda tup: tup[1], reverse=True)
+    for (fp, acc) in s_acc_list_s:
+        print('Joint slot acc: %g, %s' % (acc, fp))
+    acc_list_s = sorted(acc_list, key=lambda tup: tup[1], reverse=True)
+    for (fp, acc) in acc_list_s:
+        print('Joint goal acc: %g, %s' % (acc, fp))