import os
import trees
import tempfile
from PYEVALB import scorer
from evaluate import seg_fscore_from_file

frag = 'DUMMY'
#frag = 'FRAG'

outdir = '../output/turn_pipeline_no_voicing_redux/'

split='test'

filenames = ['nonsp_seg_26229_dev=87.61.pt.silver.parsed.DUMMY.test.silver.turns',
             'nonsp_seg_38976_dev=87.36.pt.silver.parsed.DUMMY.test.silver.turns',
             'nonsp_seg_5154_dev=87.24.pt.silver.parsed.DUMMY.test.silver.turns',
             'nonsp_seg_72240_dev=87.60.pt.silver.parsed.DUMMY.test.silver.turns',
             'nonsp_seg_73784_dev=87.61.pt.silver.parsed.DUMMY.test.silver.turns',
             'sp_seg_26229_dev=89.54.pt.silver.parsed.DUMMY.test.silver.turns',
             'sp_seg_38976_dev=89.46.pt.silver.parsed.DUMMY.test.silver.turns',
             'sp_seg_5154_dev=89.62.pt.silver.parsed.DUMMY.test.silver.turns',
             'sp_seg_72240_dev=89.59.pt.silver.parsed.DUMMY.test.silver.turns',
             'sp_seg_73784_dev=89.99.pt.silver.parsed.DUMMY.test.silver.turns']

#predf = f'../output/turn_pipeline_voicing/sp_seg_pitch_dev=89.44.pt.silver.parsed.{frag}.silver.turns'
#predf = os.path.join(outdir,'sp_seg_26229_dev=88.96.pt.silver.parsed.FRAG.silver.turns')
#predf = os.path.join(outdir,'sp_seg_72240_dev=89.16.pt.silver.parsed.FRAG.silver.turns')
#predf = os.path.join(outdir,'sp_seg_38976_dev=88.83.pt.silver.parsed.FRAG.silver.turns')
#predf = os.path.join(outdir,'sp_seg_73784_dev=88.94.pt.silver.parsed.FRAG.silver.turns')
predf = os.path.join(outdir,filenames[9])
#predf = os.path.join(outdir,'nonsp_seg_26229_dev=87.61.pt.silver.parsed.FRAG.silver.turns')
#predf = os.path.join(outdir,'nonsp_seg_5154_dev=87.24.pt.silver.parsed.FRAG.silver.turns')
#predf = os.path.join(outdir,'nonsp_seg_38976_dev=87.36.pt.silver.parsed.FRAG.silver.turns')
#predf = os.path.join(outdir,'nonsp_seg_73784_dev=87.61.pt.silver.parsed.FRAG.silver.turns')
#predf = os.path.join(outdir,'nonsp_seg_dev=87.60.pt.silver.parsed.FRAG.silver.turns')

print(predf)

idf = f'../../../data/input_features/turn_opensmile/turn_{split}.ids'

treebank,ids = trees.load_trees_with_idx(predf,idf,strip_top=True)


for tt in treebank:
    children = tt.children
    new_children = []
    for i,child in enumerate(children):
        if child.label == frag:
            new_children.extend(child.children)
        else:
            new_children.append(child)
    tt.children = new_children

            

outf = predf+'.defrag'

with open(outf,'w') as f:
    for tt in treebank:
        f.write(tt.linearize())
        f.write('\n')

gold_path = f'../../../data/input_features/turn_opensmile/turn_{split}.trees'

temp_dir = tempfile.TemporaryDirectory(prefix="evalb-")
output_path = os.path.join(temp_dir.name, "output.txt")

scr = scorer.Scorer()
scr.evalb(gold_path,outf,output_path)
print(f'output at {output_path}')

import pdb;pdb.set_trace()


