Search in sources :

Example 1 with STextualDS

use of org.corpus_tools.salt.common.STextualDS in project ANNIS by korpling.

the class CorefVisualizer method writeOutput.

/**
 * writes Output for the CorefVisualizer
 * @param writer writer to write with
 */
@Override
public void writeOutput(VisualizerInput input, Writer w) {
    // root html element
    Html html = new Html();
    Head head = new Head();
    Body body = new Body();
    html.removeXmlns();
    html.appendChild(head);
    html.appendChild(body);
    try {
        LinkedList<String> fonts = new LinkedList<String>();
        if (input.getFont() != null) {
            Link linkFont = new Link();
            linkFont.setHref(input.getFont().getUrl());
            head.appendChild(linkFont);
            fonts.add(input.getFont().getName());
        }
        fonts.add("serif");
        Link linkJQueryUI = new Link();
        linkJQueryUI.setHref(input.getResourcePath("coref/jquery-ui-1.11.4.custom/jquery-ui.min.css"));
        linkJQueryUI.setRel("stylesheet");
        linkJQueryUI.setType("text/css");
        head.appendChild(linkJQueryUI);
        Link linkJQueryUIStructure = new Link();
        linkJQueryUIStructure.setHref(input.getResourcePath("coref/jquery-ui-1.11.4.custom/jquery-ui.structure.min.css"));
        linkJQueryUIStructure.setRel("stylesheet");
        linkJQueryUIStructure.setType("text/css");
        head.appendChild(linkJQueryUIStructure);
        Script scriptJquery = new Script("text/javascript");
        scriptJquery.setSrc(input.getResourcePath("coref/jquery.js"));
        head.appendChild(scriptJquery);
        Script scriptUI = new Script("text/javascript");
        scriptUI.setSrc(input.getResourcePath("coref/jquery-ui-1.11.4.custom/jquery-ui.min.js"));
        head.appendChild(scriptUI);
        Link linkCoref = new Link();
        linkCoref.setHref(input.getResourcePath("coref/coref.css"));
        linkCoref.setRel("stylesheet");
        linkCoref.setType("text/css");
        head.appendChild(linkCoref);
        Script scriptCoref = new Script("text/javascript");
        scriptCoref.setSrc(input.getResourcePath("coref/CorefVisualizer.js"));
        head.appendChild(scriptCoref);
        body.setStyle("font-family: '" + StringUtils.join(fonts, "', '") + "';");
        // get Info
        globalIndex = 0;
        tokensOfNode = new HashMap<String, List<String>>();
        referentList = new LinkedList<TReferent>();
        komponent = new LinkedList<TComponent>();
        referentOfToken = new HashMap<String, HashMap<Long, Integer>>();
        componentOfToken = new HashMap<String, List<Long>>();
        componenttype = new LinkedList<TComponenttype>();
        SDocument saltDoc = input.getDocument();
        SDocumentGraph saltGraph = saltDoc.getDocumentGraph();
        if (saltGraph == null) {
            body.setText("An Error occured: Could not get Graph of Result (Graph == null).");
            return;
        }
        List<SRelation<SNode, SNode>> edgeList = saltGraph.getRelations();
        if (edgeList == null) {
            return;
        }
        for (SRelation rawRel : edgeList) {
            if (includeEdge(rawRel, input.getNamespace())) {
                SPointingRelation rel = (SPointingRelation) rawRel;
                String relType = componentNameForRelation(rel);
                visitedNodes = new LinkedList<String>();
                // got type for this?
                boolean gotIt = false;
                int componentnr;
                for (componentnr = 0; componentnr < componenttype.size(); componentnr++) {
                    if (componenttype.get(componentnr) != null && componenttype.get(componentnr).type != null && componenttype.get(componentnr).nodeList != null && componenttype.get(componentnr).type.equals(relType) && componenttype.get(componentnr).nodeList.contains(rel.getSource().getId())) {
                        gotIt = true;
                        break;
                    }
                }
                TComponent currentComponent;
                TComponenttype currentComponenttype;
                if (gotIt) {
                    currentComponent = komponent.get(componentnr);
                    currentComponenttype = componenttype.get(componentnr);
                } else {
                    currentComponenttype = new TComponenttype();
                    currentComponenttype.type = relType;
                    componenttype.add(currentComponenttype);
                    componentnr = komponent.size();
                    currentComponent = new TComponent();
                    currentComponent.type = relType;
                    currentComponent.tokenList = new LinkedList<String>();
                    komponent.add(currentComponent);
                    currentComponenttype.nodeList.add(rel.getSource().getId());
                }
                TReferent ref = new TReferent();
                ref.annotations = new HashSet<SerializableAnnotation>();
                for (SAnnotation anno : rel.getAnnotations()) {
                    ref.annotations.add(new SerializableAnnotation(anno));
                }
                ref.component = componentnr;
                referentList.add(ref);
                List<String> currentTokens = getAllTokens(rel.getSource(), componentNameForRelation(rel), currentComponenttype, componentnr, input.getNamespace());
                // neu
                setReferent(rel.getTarget(), globalIndex, 0);
                // neu
                setReferent(rel.getSource(), globalIndex, 1);
                for (String s : currentTokens) {
                    if (!currentComponent.tokenList.contains(s)) {
                        currentComponent.tokenList.add(s);
                    }
                }
                globalIndex++;
            }
        }
        colorlist = new HashMap<Integer, Integer>();
        // A list containing all the generated HTML elements, one list entry
        // for each text.
        List<List<Node>> nodesPerText = new LinkedList<List<Node>>();
        // write output for each text separatly
        List<STextualDS> texts = saltGraph.getTextualDSs();
        if (texts != null && !texts.isEmpty()) {
            for (STextualDS t : texts) {
                DataSourceSequence<Integer> sequence = new DataSourceSequence<>(t, 0, (t.getText() != null) ? t.getText().length() : 0);
                List<SToken> token = saltGraph.getSortedTokenByText(saltGraph.getTokensBySequence(sequence));
                if (token != null) {
                    boolean validText = true;
                    if (Boolean.parseBoolean(input.getMappings().getProperty("hide_empty", "false"))) {
                        validText = false;
                        // check if the text contains any matching annotations
                        for (SToken tok : token) {
                            /* 
                 * The token is only added to this map if an valid edge
                 * (according to the resolver trigger) conntected to 
                 * this token was found.
                 */
                            if (referentOfToken.get(tok.getId()) != null && !referentOfToken.get(tok.getId()).isEmpty()) {
                                validText = true;
                                break;
                            }
                        }
                    }
                    if (validText) {
                        List<Node> nodes = outputSingleText(token, input);
                        nodesPerText.add(nodes);
                    }
                }
            }
            // end for each STexutalDS
            /* 
         * Append the generated output to the body, wrap in table if necessary. 
         */
            // present all texts as columns side by side if using multiple texts
            Table tableTexts = new Table();
            Tr trTextRow = new Tr();
            trTextRow.setCSSClass("textRow");
            // only append wrapper table if we have multiple texts
            if (nodesPerText.size() > 1) {
                body.appendChild(tableTexts);
                tableTexts.appendChild(trTextRow);
            }
            for (List<Node> nodes : nodesPerText) {
                // multi-text mode?
                if (nodesPerText.size() > 1) {
                    Td tdSingleText = new Td();
                    trTextRow.appendChild(tdSingleText);
                    tdSingleText.setCSSClass("text");
                    tdSingleText.appendChild(nodes);
                } else {
                    body.appendChild(nodes);
                }
            }
        } else {
            Text errorTxt = new Text("Could not find any texts for the " + input.getNamespace() + " node namespace (layer).");
            body.appendChild(errorTxt);
        }
        // write HTML4 transitional doctype
        w.append(new Doctype(DocumentType.HTMLTransitional).write());
        // append the html tree
        w.append(html.write());
    } catch (IOException ex) {
        log.error(null, ex);
    }
}
Also used : HashMap(java.util.HashMap) SNode(org.corpus_tools.salt.core.SNode) SStructuredNode(org.corpus_tools.salt.common.SStructuredNode) Node(com.hp.gagawa.java.Node) SToken(org.corpus_tools.salt.common.SToken) Td(com.hp.gagawa.java.elements.Td) SRelation(org.corpus_tools.salt.core.SRelation) SDocumentGraph(org.corpus_tools.salt.common.SDocumentGraph) STextualDS(org.corpus_tools.salt.common.STextualDS) LinkedList(java.util.LinkedList) List(java.util.List) Body(com.hp.gagawa.java.elements.Body) Tr(com.hp.gagawa.java.elements.Tr) SPointingRelation(org.corpus_tools.salt.common.SPointingRelation) Script(com.hp.gagawa.java.elements.Script) Head(com.hp.gagawa.java.elements.Head) Table(com.hp.gagawa.java.elements.Table) SAnnotation(org.corpus_tools.salt.core.SAnnotation) Html(com.hp.gagawa.java.elements.Html) SDocument(org.corpus_tools.salt.common.SDocument) Doctype(com.hp.gagawa.java.elements.Doctype) Text(com.hp.gagawa.java.elements.Text) IOException(java.io.IOException) DataSourceSequence(org.corpus_tools.salt.util.DataSourceSequence) LinkedList(java.util.LinkedList) Link(com.hp.gagawa.java.elements.Link)

Example 2 with STextualDS

use of org.corpus_tools.salt.common.STextualDS in project ANNIS by korpling.

the class SaltAnnotateExtractor method createSinglePrimaryText.

private void createSinglePrimaryText(SDocumentGraph graph, long textID, TreeMap<Long, String> tokenTexts, TreeMap<Long, SToken> tokenByIndex) {
    STextualDS textDataSource = SaltFactory.createSTextualDS();
    textDataSource.setName("sText" + textID);
    graph.addNode(textDataSource);
    StringBuilder sbText = new StringBuilder();
    Iterator<Map.Entry<Long, String>> itToken = tokenTexts.entrySet().iterator();
    long index = 0;
    while (itToken.hasNext()) {
        Map.Entry<Long, String> e = itToken.next();
        SToken tok = tokenByIndex.get(e.getKey());
        SFeature rawFeature = tok.getFeature(SaltUtil.createQName(ANNIS_NS, FEAT_RELANNIS_NODE));
        if (rawFeature != null) {
            RelannisNodeFeature feat = (RelannisNodeFeature) rawFeature.getValue();
            if (feat.getTextRef() == textID) {
                STextualRelation textRel = SaltFactory.createSTextualRelation();
                textRel.setSource(tok);
                textRel.setTarget(textDataSource);
                textRel.setStart(sbText.length());
                textRel.setEnd(sbText.length() + e.getValue().length());
                textRel.setName("sTextRel" + textID + "_" + (index++));
                textRel.setTarget(textDataSource);
                graph.addRelation(textRel);
                sbText.append(e.getValue());
                if (itToken.hasNext()) {
                    sbText.append(" ");
                }
            }
        }
    }
    textDataSource.setText(sbText.toString());
}
Also used : RelannisNodeFeature(annis.model.RelannisNodeFeature) STextualRelation(org.corpus_tools.salt.common.STextualRelation) SToken(org.corpus_tools.salt.common.SToken) STextualDS(org.corpus_tools.salt.common.STextualDS) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) SFeature(org.corpus_tools.salt.core.SFeature)

Example 3 with STextualDS

use of org.corpus_tools.salt.common.STextualDS in project ANNIS by korpling.

the class TimelineReconstructor method convertSpanToToken.

private void convertSpanToToken(SStructuredNode span, String orderName) {
    final Set<String> validSpanAnnos = new HashSet<>(order2spanAnnos.get(orderName));
    if (!nodesToDelete.contains(span)) {
        nodesToDelete.add(span);
        if (textsByName.get(orderName) == null) {
            STextualDS newText = graph.createTextualDS("");
            newText.setName(orderName);
            textsByName.put(orderName, newText);
            textDataByName.put(orderName, new StringBuilder());
        }
        STextualDS textDS = textsByName.get(orderName);
        StringBuilder textData = textDataByName.get(orderName);
        TreeSet<Integer> coveredIdx = new TreeSet<>(spans2TimelinePos.get(span));
        if (!coveredIdx.isEmpty()) {
            SAnnotation textValueAnno = getTextValueAnno(orderName, span);
            if (textValueAnno != null) {
                String textValue = textValueAnno.getValue_STEXT();
                int startTextIdx = textData.length();
                textData.append(textValue);
                int endTextIdx = textData.length();
                SToken newToken = graph.createToken(textDS, startTextIdx, endTextIdx);
                // keep track of changed ids for matches
                if (this.matchIDs.contains(span.getId()))
                    this.oldID2newID.put(span.getId(), newToken.getId());
                // move all features to the new token
                if (span.getFeatures() != null) {
                    for (SFeature feat : span.getFeatures()) {
                        if (!"salt".equals(feat.getNamespace())) {
                            newToken.addFeature(feat);
                        }
                    }
                }
                // move all annotations to the new token
                if (span.getAnnotations() != null) {
                    for (SAnnotation annot : span.getAnnotations()) {
                        if (!"salt".equals(annot.getNamespace()) && !orderName.equals(annot.getName())) {
                            newToken.addAnnotation(annot);
                        }
                    }
                }
                STimelineRelation timeRel = SaltFactory.createSTimelineRelation();
                timeRel.setSource(newToken);
                timeRel.setTarget(graph.getTimeline());
                timeRel.setStart(coveredIdx.first());
                timeRel.setEnd(coveredIdx.last());
                graph.addRelation(timeRel);
                moveRelations(span, newToken, validSpanAnnos, orderName);
            }
        }
    }
}
Also used : SAnnotation(org.corpus_tools.salt.core.SAnnotation) SToken(org.corpus_tools.salt.common.SToken) TreeSet(java.util.TreeSet) STextualDS(org.corpus_tools.salt.common.STextualDS) STimelineRelation(org.corpus_tools.salt.common.STimelineRelation) HashSet(java.util.HashSet) SFeature(org.corpus_tools.salt.core.SFeature)

Example 4 with STextualDS

use of org.corpus_tools.salt.common.STextualDS in project ANNIS by korpling.

the class RSTImpl method getText.

/**
 * Gets the overlapping token as string from a node, which are direct
 * dominated by this node.
 *
 * @param currNode
 * @return is null, if there is no relation to a token, or there is more then
 * one STEXT is overlapped by this node
 */
private String getText(SToken currNode) {
    List<DataSourceSequence> sSequences = ((SDocumentGraph) currNode.getGraph()).getOverlappedDataSourceSequence(currNode, SALT_TYPE.STEXT_OVERLAPPING_RELATION);
    // only support one text for spanns
    if (sSequences == null || sSequences.size() != 1) {
        log.error("rst supports only one text and only text level");
        return null;
    }
    log.debug("sSequences {}", sSequences.toString());
    /**
     * Check if it is a text data structure. As described in the salt manual in
     * chapter "5.8 More specific nodes and relations" the start and end point
     * of a range of token is stored in superordinate node of type SSequentialDS
     */
    if (sSequences.get(0).getDataSource() instanceof STextualDS) {
        STextualDS text = ((STextualDS) sSequences.get(0).getDataSource());
        int start = sSequences.get(0).getStart().intValue();
        int end = sSequences.get(0).getEnd().intValue();
        return text.getText().substring(start, end);
    }
    // something fundamentally goes wrong
    log.error("{} instead of {}", sSequences.get(0).getDataSource().getClass().getName(), STextualDS.class.getName());
    return null;
}
Also used : SDocumentGraph(org.corpus_tools.salt.common.SDocumentGraph) STextualDS(org.corpus_tools.salt.common.STextualDS) DataSourceSequence(org.corpus_tools.salt.util.DataSourceSequence)

Example 5 with STextualDS

use of org.corpus_tools.salt.common.STextualDS in project ANNIS by korpling.

the class TimelineReconstructorTest method testBematacDialog.

/**
 * Tests a sample dialog reconstruction.
 * The dialog is this one: https://korpling.org/annis3/?id=44b60a56-31da-4469-b438-62fdb67f28f1
 *
 * The Salt which was generated by ANNIS is loaded and the virtual tokenization is removed.
 * It is checked if
 * <ul>
 * <li>the newly created tokenization is correct</li>
 * <li>spans cover the correct token</li>
 * </ul>
 */
@Test
public void testBematacDialog() {
    SDocumentGraph docGraph = SaltUtil.loadDocumentGraph(URI.createURI(getClass().getResource("SampleDialog.salt").toString()));
    Map<String, String> anno2order = new HashMap<>();
    anno2order.put("default_ns::instructee_utt", "instructee_dipl");
    anno2order.put("default_ns::instructor_utt", "instructor_dipl");
    TimelineReconstructor.removeVirtualTokenization(docGraph, anno2order);
    // instructor_dipl, instructor_norm, instructee_dipl, instructee_norm, instructee_extra, break
    List<STextualDS> texts = docGraph.getTextualDSs();
    assertEquals(6, texts.size());
    STextualDS instructorDipl = findTextualDSByName("instructor_dipl", texts);
    assertNotNull(instructorDipl);
    assertEquals("in Richtung des Toasters gehst ja gehst", instructorDipl.getText());
    DataSourceSequence<Integer> seq = new DataSourceSequence<>();
    seq.setDataSource(instructorDipl);
    seq.setStart(instructorDipl.getStart());
    seq.setEnd(instructorDipl.getEnd());
    List<SToken> instructorDiplToken = docGraph.getTokensBySequence(seq);
    assertEquals(7, instructorDiplToken.size());
    assertEquals("in", docGraph.getText(instructorDiplToken.get(0)));
    assertEquals("Richtung", docGraph.getText(instructorDiplToken.get(1)));
    assertEquals("des", docGraph.getText(instructorDiplToken.get(2)));
    assertEquals("Toasters", docGraph.getText(instructorDiplToken.get(3)));
    assertEquals("gehst", docGraph.getText(instructorDiplToken.get(4)));
    assertEquals("ja", docGraph.getText(instructorDiplToken.get(5)));
    assertEquals("gehst", docGraph.getText(instructorDiplToken.get(6)));
    // check that the other real spans are now connected with the token
    List<SNode> uttNode = docGraph.getNodesByName("sSpan1294");
    assertNotNull(uttNode);
    assertEquals(1, uttNode.size());
    SAnnotation uttAnno = uttNode.get(0).getAnnotation("default_ns::instructor_utt");
    assertNotNull(uttAnno);
    assertEquals("utt", uttAnno.getValue_STEXT());
    List<SRelation> uttOutRelations = uttNode.get(0).getOutRelations();
    assertNotNull(uttOutRelations);
    assertEquals(5, uttOutRelations.size());
    for (SRelation rel : uttOutRelations) {
        assertTrue(rel instanceof SSpanningRelation);
        assertEquals(instructorDipl, CommonHelper.getTextualDSForNode((SNode) rel.getTarget(), docGraph));
    }
    STextualDS instructorNorm = findTextualDSByName("instructor_norm", texts);
    assertNotNull(instructorNorm);
    assertEquals("in Richtung des Toasters gehst ja gehst", instructorNorm.getText());
    STextualDS instructeeDipl = findTextualDSByName("instructee_dipl", texts);
    assertNotNull(instructeeDipl);
    assertEquals("mhm ich geh in Richtung des Toasters okay", instructeeDipl.getText());
    STextualDS instructeeNorm = findTextualDSByName("instructee_norm", texts);
    assertNotNull(instructeeNorm);
    assertEquals("ich gehe in Richtung des Toasters okay", instructeeNorm.getText());
    STextualDS instructeeExtra = findTextualDSByName("instructee_extra", texts);
    assertNotNull(instructeeExtra);
    assertEquals("zeichnet", instructeeExtra.getText());
    STextualDS breakText = findTextualDSByName("break", texts);
    assertNotNull(breakText);
    assertEquals("0,7 0,5", breakText.getText());
}
Also used : SNode(org.corpus_tools.salt.core.SNode) HashMap(java.util.HashMap) SAnnotation(org.corpus_tools.salt.core.SAnnotation) DataSourceSequence(org.corpus_tools.salt.util.DataSourceSequence) SToken(org.corpus_tools.salt.common.SToken) SRelation(org.corpus_tools.salt.core.SRelation) SDocumentGraph(org.corpus_tools.salt.common.SDocumentGraph) SSpanningRelation(org.corpus_tools.salt.common.SSpanningRelation) STextualDS(org.corpus_tools.salt.common.STextualDS) Test(org.junit.Test)

Aggregations

STextualDS (org.corpus_tools.salt.common.STextualDS)8 HashMap (java.util.HashMap)4 SToken (org.corpus_tools.salt.common.SToken)4 SNode (org.corpus_tools.salt.core.SNode)4 SDocumentGraph (org.corpus_tools.salt.common.SDocumentGraph)3 SAnnotation (org.corpus_tools.salt.core.SAnnotation)3 SFeature (org.corpus_tools.salt.core.SFeature)3 SRelation (org.corpus_tools.salt.core.SRelation)3 DataSourceSequence (org.corpus_tools.salt.util.DataSourceSequence)3 RelannisNodeFeature (annis.model.RelannisNodeFeature)2 HashSet (java.util.HashSet)2 Map (java.util.Map)2 GridEvent (annis.gui.widgets.grid.GridEvent)1 Row (annis.gui.widgets.grid.Row)1 MediaController (annis.libgui.media.MediaController)1 PDFController (annis.libgui.media.PDFController)1 Node (com.hp.gagawa.java.Node)1 Body (com.hp.gagawa.java.elements.Body)1 Doctype (com.hp.gagawa.java.elements.Doctype)1 Head (com.hp.gagawa.java.elements.Head)1