Search in sources :

Example 36 with Representation

use of org.apache.stanbol.entityhub.servicesapi.model.Representation in project stanbol by apache.

the class SesameContextTest method testStoreToContextEnabledYard.

/**
     * Test visibility of Entities added to specific contexts
     * @throws YardException
     */
@Test
public void testStoreToContextEnabledYard() throws YardException {
    //add a new entity to yard 2
    String context2added = "http://www.test.org/addedEntity";
    Representation rep = RdfValueFactory.getInstance().createRepresentation(context2added);
    rep.addReference(rdfType.stringValue(), skosConcept.stringValue());
    rep.addNaturalText(skosPrefLabel.stringValue(), "added Entity", "en");
    rep.addNaturalText(skosPrefLabel.stringValue(), "hinzugefüte Entity", "de");
    yard2.store(rep);
    //test visibility to other yards
    Assert.assertFalse(yard1.isRepresentation(context2added));
    Assert.assertTrue(yard2.isRepresentation(context2added));
    Assert.assertTrue(unionYard.isRepresentation(context2added));
    //remove it and test again
    yard2.remove(context2added);
    Assert.assertFalse(yard1.isRepresentation(context2added));
    Assert.assertFalse(yard2.isRepresentation(context2added));
    Assert.assertFalse(unionYard.isRepresentation(context2added));
}
Also used : RdfRepresentation(org.apache.stanbol.entityhub.model.sesame.RdfRepresentation) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation) Test(org.junit.Test)

Example 37 with Representation

use of org.apache.stanbol.entityhub.servicesapi.model.Representation in project stanbol by apache.

the class SolrYardTest method testFieldQuery.

@Test
public void testFieldQuery() throws YardException {
    // NOTE: this does not test if the updated view of the representation is
    // stored, but only that the update method works correctly
    Yard yard = getYard();
    String id1 = "urn:yard.test.testFieldQuery:representation.id1";
    String id2 = "urn:yard.test.testFieldQuery:representation.id2";
    String field = "urn:the.field:used.for.testFieldQuery";
    Representation test1 = create(id1, true);
    Representation test2 = create(id2, true);
    // change the representations to be sure to force an update even if the
    // implementation checks for changes before updating a representation
    test1.add(field, "This is the text content of a field with value1.");
    test2.add(field, "This is the text content of a field with value2.");
    Iterable<Representation> updatedIterable = yard.update(Arrays.asList(test1, test2));
    assertNotNull(updatedIterable);
    FieldQuery query = yard.getQueryFactory().createFieldQuery();
    query.setConstraint(field, new TextConstraint(Arrays.asList("text content")));
    QueryResultList<Representation> results = yard.find(query);
    assertEquals(2, results.size());
    // fetch the light / minimal representation
    query = yard.getQueryFactory().createFieldQuery();
    query.setConstraint(field, new TextConstraint(Arrays.asList("value2")));
    results = yard.find(query);
    assertEquals(1, results.size());
    Representation result = results.iterator().next();
    assertEquals("urn:yard.test.testFieldQuery:representation.id2", result.getId());
    assertEquals(null, result.getFirst(field));
    // fetch the full representation
    results = yard.findRepresentation(query);
    assertEquals(1, results.size());
    result = results.iterator().next();
    assertEquals("urn:yard.test.testFieldQuery:representation.id2", result.getId());
    assertEquals("This is the text content of a field with value2.", result.getFirst(field));
}
Also used : FieldQuery(org.apache.stanbol.entityhub.servicesapi.query.FieldQuery) SolrYard(org.apache.stanbol.entityhub.yard.solr.impl.SolrYard) Yard(org.apache.stanbol.entityhub.servicesapi.yard.Yard) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation) TextConstraint(org.apache.stanbol.entityhub.servicesapi.query.TextConstraint) YardTest(org.apache.stanbol.entityhub.test.yard.YardTest) Test(org.junit.Test)

Example 38 with Representation

use of org.apache.stanbol.entityhub.servicesapi.model.Representation in project stanbol by apache.

the class EntityhubSearcher method lookup.

@Override
public Collection<? extends Entity> lookup(IRI field, Set<IRI> includeFields, List<String> search, String[] languages, Integer limit, Integer offset) throws EntitySearcherException {
    Entityhub entityhub = getSearchService();
    if (entityhub == null) {
        throw new EntitySearcherException("The Entityhub is currently not active");
    }
    FieldQuery query = EntitySearcherUtils.createFieldQuery(entityhub.getQueryFactory(), field, includeFields, search, languages);
    if (limit != null && limit > 0) {
        query.setLimit(limit);
    } else if (this.limit != null) {
        query.setLimit(this.limit);
    }
    if (offset != null && offset.intValue() > 0) {
        query.setOffset(offset.intValue());
    }
    QueryResultList<Representation> results;
    try {
        results = entityhub.find(query);
    } catch (EntityhubException e) {
        throw new EntitySearcherException("Exception while searchign for " + search + '@' + Arrays.toString(languages) + "in the Entityhub", e);
    }
    if (!results.isEmpty()) {
        Set<String> languagesSet = new HashSet<String>(Arrays.asList(languages));
        Collection<Entity> entities = new ArrayList<Entity>(results.size());
        for (Representation result : results) {
            entities.add(new EntityhubEntity(result, null, languagesSet));
        }
        return entities;
    } else {
        return Collections.emptyList();
    }
}
Also used : FieldQuery(org.apache.stanbol.entityhub.servicesapi.query.FieldQuery) Entity(org.apache.stanbol.enhancer.engines.entitylinking.Entity) ArrayList(java.util.ArrayList) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation) EntitySearcherException(org.apache.stanbol.enhancer.engines.entitylinking.EntitySearcherException) EntityhubException(org.apache.stanbol.entityhub.servicesapi.EntityhubException) Entityhub(org.apache.stanbol.entityhub.servicesapi.Entityhub) HashSet(java.util.HashSet)

Example 39 with Representation

use of org.apache.stanbol.entityhub.servicesapi.model.Representation in project stanbol by apache.

the class EnhancementRDFUtils method writeEntityAnnotation.

/**
     * @param literalFactory
     *            the LiteralFactory to use
     * @param graph
     *            the Graph to use
     * @param contentItemId
     *            the contentItemId the enhancement is extracted from
     * @param relatedEnhancements
     *            enhancements this textAnnotation is related to
     * @param suggestion
     *            the entity suggestion
     * @param nameField the field used to extract the name
     * @param lang the preferred language to include or <code>null</code> if none
     */
public static IRI writeEntityAnnotation(EnhancementEngine engine, LiteralFactory literalFactory, Graph graph, IRI contentItemId, Collection<BlankNodeOrIRI> relatedEnhancements, Suggestion suggestion, String nameField, String lang) {
    Representation rep = suggestion.getEntity().getRepresentation();
    // 1. extract the "best label"
    //Start with the matched one
    Text label = suggestion.getMatchedLabel();
    //if the matched label is not in the requested language
    boolean langMatch = (lang == null && label.getLanguage() == null) || (label.getLanguage() != null && label.getLanguage().startsWith(lang));
    //search if a better label is available for this Entity
    if (!langMatch) {
        Iterator<Text> labels = rep.getText(nameField);
        while (labels.hasNext() && !langMatch) {
            Text actLabel = labels.next();
            langMatch = (lang == null && actLabel.getLanguage() == null) || (actLabel.getLanguage() != null && actLabel.getLanguage().startsWith(lang));
            if (langMatch) {
                //if the language matches ->
                //override the matched label
                label = actLabel;
            }
        }
    }
    //else the matched label will be the best to use
    Literal literal;
    if (label.getLanguage() == null) {
        literal = new PlainLiteralImpl(label.getText());
    } else {
        literal = new PlainLiteralImpl(label.getText(), new Language(label.getLanguage()));
    }
    // Now create the entityAnnotation
    IRI entityAnnotation = EnhancementEngineHelper.createEntityEnhancement(graph, engine, contentItemId);
    // first relate this entity annotation to the text annotation(s)
    for (BlankNodeOrIRI enhancement : relatedEnhancements) {
        graph.add(new TripleImpl(entityAnnotation, DC_RELATION, enhancement));
    }
    IRI entityUri = new IRI(rep.getId());
    // add the link to the referred entity
    graph.add(new TripleImpl(entityAnnotation, ENHANCER_ENTITY_REFERENCE, entityUri));
    // add the label parsed above
    graph.add(new TripleImpl(entityAnnotation, ENHANCER_ENTITY_LABEL, literal));
    if (suggestion.getScore() != null) {
        graph.add(new TripleImpl(entityAnnotation, ENHANCER_CONFIDENCE, literalFactory.createTypedLiteral(suggestion.getScore())));
    }
    Iterator<Reference> types = rep.getReferences(RDF_TYPE.getUnicodeString());
    while (types.hasNext()) {
        graph.add(new TripleImpl(entityAnnotation, ENHANCER_ENTITY_TYPE, new IRI(types.next().getReference())));
    }
    //add the name of the ReferencedSite that manages the Entity
    if (suggestion.getEntity().getSite() != null) {
        graph.add(new TripleImpl(entityAnnotation, new IRI(RdfResourceEnum.site.getUri()), new PlainLiteralImpl(suggestion.getEntity().getSite())));
    }
    return entityAnnotation;
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) Language(org.apache.clerezza.commons.rdf.Language) PlainLiteralImpl(org.apache.clerezza.commons.rdf.impl.utils.PlainLiteralImpl) Reference(org.apache.stanbol.entityhub.servicesapi.model.Reference) Literal(org.apache.clerezza.commons.rdf.Literal) BlankNodeOrIRI(org.apache.clerezza.commons.rdf.BlankNodeOrIRI) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation) Text(org.apache.stanbol.entityhub.servicesapi.model.Text) TripleImpl(org.apache.clerezza.commons.rdf.impl.utils.TripleImpl)

Example 40 with Representation

use of org.apache.stanbol.entityhub.servicesapi.model.Representation in project stanbol by apache.

the class NamedEntityTaggingEngine method computeEntityRecommentations.

/**
     * Computes the Enhancements
     * 
     * @param site
     *            The {@link SiteException} id or <code>null</code> to use the {@link Entityhub}
     * @param literalFactory
     *            the {@link LiteralFactory} used to create RDF Literals
     * @param contentItemId
     *            the id of the contentItem
     * @param textAnnotation
     *            the text annotation to enhance
     * @param subsumedAnnotations
     *            other text annotations for the same entity
     * @param language
     *            the language of the analysed text or <code>null</code> if not available.
     * @return the suggestions for the parsed {@link NamedEntity}
     * @throws EntityhubException
     *             On any Error while looking up Entities via the Entityhub
     */
protected final List<Suggestion> computeEntityRecommentations(Site site, NamedEntity namedEntity, List<IRI> subsumedAnnotations, String language) throws EntityhubException {
    // First get the required properties for the parsed textAnnotation
    // ... and check the values
    log.debug("Process {}", namedEntity);
    // if site is NULL use
    // the Entityhub
    FieldQueryFactory queryFactory = site == null ? entityhub.getQueryFactory() : site.getQueryFactory();
    log.trace("Will use a query-factory of type [{}].", queryFactory.getClass().toString());
    FieldQuery query = queryFactory.createFieldQuery();
    // replace spaces with plus to create an AND search for all words in the
    // name!
    Constraint labelConstraint;
    // TODO: make case sensitivity configurable
    boolean casesensitive = false;
    String namedEntityLabel = casesensitive ? namedEntity.getName() : namedEntity.getName().toLowerCase();
    if (language != null) {
        // search labels in the language and without language
        labelConstraint = new TextConstraint(namedEntityLabel, casesensitive, language, null);
    } else {
        labelConstraint = new TextConstraint(namedEntityLabel, casesensitive);
    }
    query.setConstraint(nameField, labelConstraint);
    if (OntologicalClasses.DBPEDIA_PERSON.equals(namedEntity.getType())) {
        if (personState) {
            if (personType != null) {
                query.setConstraint(RDF_TYPE.getUnicodeString(), new ReferenceConstraint(personType));
            }
        // else no type constraint
        } else {
            // ignore people
            return Collections.emptyList();
        }
    } else if (DBPEDIA_ORGANISATION.equals(namedEntity.getType())) {
        if (orgState) {
            if (orgType != null) {
                query.setConstraint(RDF_TYPE.getUnicodeString(), new ReferenceConstraint(orgType));
            }
        // else no type constraint
        } else {
            // ignore people
            return Collections.emptyList();
        }
    } else if (OntologicalClasses.DBPEDIA_PLACE.equals(namedEntity.getType())) {
        if (this.placeState) {
            if (this.placeType != null) {
                query.setConstraint(RDF_TYPE.getUnicodeString(), new ReferenceConstraint(placeType));
            }
        // else no type constraint
        } else {
            // ignore people
            return Collections.emptyList();
        }
    }
    query.setLimit(Math.max(20, this.numSuggestions * 3));
    log.trace("A query has been created of type [{}] and the following settings:\n{}", query.getClass().toString(), query.toString());
    if (null == site)
        log.trace("A query will be sent to the entity-hub of type [{}].", entityhub.getClass());
    else
        log.trace("A query will be sent to a site [id :: {}][type :: {}].", site.getId(), site.getClass());
    QueryResultList<Entity> results = // if site is NULL
    site == null ? entityhub.findEntities(query) : // use the Entityhub
    site.findEntities(// else the referenced site
    query);
    log.debug(" - {} results returned by query {}", results.size(), results.getQuery());
    if (results.isEmpty()) {
        // no results nothing to do
        return Collections.emptyList();
    }
    // we need to normalise the confidence values from [0..1]
    // * levenshtein distance as absolute (1.0 for exact match)
    // * Solr scores * levenshtein to rank entities relative to each other
    Float maxScore = null;
    Float maxExactScore = null;
    List<Suggestion> matches = new ArrayList<Suggestion>(numSuggestions);
    // assumes entities are sorted by score
    for (Iterator<Entity> guesses = results.iterator(); guesses.hasNext(); ) {
        Suggestion match = new Suggestion(guesses.next());
        Representation rep = match.getEntity().getRepresentation();
        Float score = rep.getFirst(RdfResourceEnum.resultScore.getUri(), Float.class);
        if (maxScore == null) {
            maxScore = score;
        }
        Iterator<Text> labels = rep.getText(nameField);
        while (labels.hasNext() && match.getLevenshtein() < 1.0) {
            Text label = labels.next();
            if (// if the content language is unknown ->
            language == null || // accept all labels
            label.getLanguage() == // accept labels with no
            null || // and labels in the same language as the content
            (language != null && label.getLanguage().startsWith(language))) {
                double actMatch = levenshtein(casesensitive ? label.getText() : label.getText().toLowerCase(), namedEntityLabel);
                if (actMatch > match.getLevenshtein()) {
                    match.setLevenshtein(actMatch);
                    match.setMatchedLabel(label);
                }
            }
        }
        if (match.getMatchedLabel() != null) {
            if (match.getLevenshtein() == 1.0) {
                if (maxExactScore == null) {
                    maxExactScore = score;
                }
                // normalise exact matches against the best exact score
                match.setScore(score.doubleValue() / maxExactScore.doubleValue());
            } else {
                // normalise partial matches against the best match and the
                // Levenshtein similarity with the label
                match.setScore(score.doubleValue() * match.getLevenshtein() / maxScore.doubleValue());
            }
            matches.add(match);
        } else {
            log.debug("No value of {} for Entity {}!", nameField, match.getEntity().getId());
        }
    }
    // now sort the results
    Collections.sort(matches);
    return matches.subList(0, Math.min(matches.size(), numSuggestions));
}
Also used : FieldQuery(org.apache.stanbol.entityhub.servicesapi.query.FieldQuery) Entity(org.apache.stanbol.entityhub.servicesapi.model.Entity) ReferenceConstraint(org.apache.stanbol.entityhub.servicesapi.query.ReferenceConstraint) Constraint(org.apache.stanbol.entityhub.servicesapi.query.Constraint) TextConstraint(org.apache.stanbol.entityhub.servicesapi.query.TextConstraint) ArrayList(java.util.ArrayList) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation) Text(org.apache.stanbol.entityhub.servicesapi.model.Text) FieldQueryFactory(org.apache.stanbol.entityhub.servicesapi.query.FieldQueryFactory) ReferenceConstraint(org.apache.stanbol.entityhub.servicesapi.query.ReferenceConstraint) TextConstraint(org.apache.stanbol.entityhub.servicesapi.query.TextConstraint)

Aggregations

Representation (org.apache.stanbol.entityhub.servicesapi.model.Representation)198 Test (org.junit.Test)117 Text (org.apache.stanbol.entityhub.servicesapi.model.Text)32 HashSet (java.util.HashSet)31 Yard (org.apache.stanbol.entityhub.servicesapi.yard.Yard)25 Entity (org.apache.stanbol.entityhub.servicesapi.model.Entity)16 YardException (org.apache.stanbol.entityhub.servicesapi.yard.YardException)15 ValueFactory (org.apache.stanbol.entityhub.servicesapi.model.ValueFactory)14 Reference (org.apache.stanbol.entityhub.servicesapi.model.Reference)12 FieldQuery (org.apache.stanbol.entityhub.servicesapi.query.FieldQuery)12 ArrayList (java.util.ArrayList)11 RdfRepresentation (org.apache.stanbol.entityhub.model.sesame.RdfRepresentation)10 IOException (java.io.IOException)9 IRI (org.apache.clerezza.commons.rdf.IRI)9 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)8 Graph (org.apache.clerezza.commons.rdf.Graph)8 IndexedGraph (org.apache.stanbol.commons.indexedgraph.IndexedGraph)8 RdfRepresentation (org.apache.stanbol.entityhub.model.clerezza.RdfRepresentation)8 RdfValueFactory (org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory)8 EntityhubException (org.apache.stanbol.entityhub.servicesapi.EntityhubException)8