from flow_elem import FlowElem
from subprocess import Popen
from saper.saperio.readers import cclreader
from saper.saperio import utils
import corpus2


__author__ = 'blaz'


class Liner(FlowElem):
    """
    Liner flow elem is used for named entities recognition.
    """

    def __init__(self, config):
        self.model_path = config.get('liner', 'model')
        self.tagset = corpus2.get_named_tagset(config.get('saper', 'tagset'))

    def feed_flow(self, document):
        """
        It preforms ner process on given document and returns annotated
        document.

        @type document: corpus2.Document
        @rtype: corpus2.Document
        """

        #Creating tempfile.
        new_document = corpus2.Document(path=document.path())
        temp = utils.get_temp_file(document, self.tagset)

        #Running liner.
        liner_cmd = ['liner2', 'pipe', '-i', 'ccl', '-o', 'ccl', '-ini',
                     self.model_path, '-f', temp.name, '-t', temp.name]
        liner = Popen(liner_cmd)
        liner.communicate()

        #Reading liner data.
        ccl_rdr = cclreader.CclReader(None)
        temp_document = ccl_rdr.read_file(temp.name)
        for par in temp_document.paragraphs():
            new_document.add_paragraph(par)
        for rel in document.relations():
            new_document.add_relation(rel)
        temp.close()
        del temp_document

        return new_document