#!/usr/bin/env python3

# This program takes a series of XML-formatted files and creates an
# RTTM v1.3 (https://catalog.ldc.upenn.edu/docs/LDC2004T12/RTTM-format-v13.pdf)
# output file.

# Typical invocation:
#
#   nite_xml_to_rttm.py ~/Downloads/ami_public_manual_1.6.2/words/ES2008a.*.words.xml | sort -n -k 4 > /tmp/ES2008a.rttm
#
import math
import sys
import xml.etree.ElementTree as ET

xml_trees = []


def print_rttm_line(start_time, end_time, speaker_num):
    print("SPEAKER meeting\t1\t{}\t{}\t<NA>\t<NA>\tSpeaker_{}\t<NA>".format(start_time, end_time - start_time,
                                                                            speaker_num))


def convert_xml_to_rttm():
    xml_file = xml_files[xml_file_index]
    tree = ET.parse(xml_file)
    root = tree.getroot()
    xml_trees.append(root)
    start_time = end_time = None
    for element in root:
        if element.tag == 'w' and 'starttime' in element.attrib and 'endtime' in element.attrib:
            if start_time is None:
                start_time = float(element.attrib['starttime'])
            if end_time is None:
                end_time = float(element.attrib['starttime'])  # yes, 'starttime'
            if math.isclose(end_time, float(element.attrib['starttime']), abs_tol=0.01):
                # collapse the two
                end_time = float(element.attrib['endtime'])
            else:
                print_rttm_line(start_time, end_time, speaker_num=xml_file_index)
                start_time = float(element.attrib['starttime'])
                end_time = float(element.attrib['endtime'])
    if not ((start_time is None) or (end_time is None)):
        print_rttm_line(start_time, end_time, speaker_num=xml_file_index)


xml_files = sys.argv[1:]
for xml_file_index in range(len(xml_files)):
    convert_xml_to_rttm()

@@ -404,16 +404,116 @@
  = %5B%5D%0A%0A%0A
+# 'meeting' label is given to the generated rttm file. Can be changed according to sys arg filename%0A
 def prin
@@ -590,33 +590,35 @@
 ting
-%5Ct1%5Ct%7B%7D%5Ct%7B%7D%5Ct
+ 1 %7B:.3f%7D %7B:.3f%7D 
 %3CNA%3E
-%5Ct
+ 
 %3CNA%3E
-%5Ct
+ 
 Spea
@@ -627,10 +627,9 @@
 r_%7B%7D
-%5Ct
+ 
 %3CNA%3E
@@ -763,17 +763,16 @@
 _num))%0A%0A
-%0A
 def conv
@@ -1824,16 +1824,368 @@
 ndex)%0A%0A%0A
+# check for file input%0Aif len(sys.argv) %3C 2:%0A    print()%0A    print(%22Please give AMI xml file as input. Download from http://groups.inf.ed.ac.uk/ami/AMICorpusAnnotations/ami_public_manual_1.6.2.zip%22)%0A    print(%22USAGE: %5Cn nite_xml_to_rttm.py ~/Downloads/ami_public_manual_1.6.2/words/ES2008a.*.words.xml %7C sort -n -k 4 %3E /tmp/ES2008a.rttm%22)%0A    print()%0A%0A
 xml_file

add file input checks