Skip to content

Commit

Permalink
Extended QanaryComponent and changed usage of component names in the …
Browse files Browse the repository at this point in the history
…corresponding methods
  • Loading branch information
dschiese committed May 27, 2024
1 parent 2ddc309 commit c939d5e
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.wse.qanaryexplanationservice.helper.dtos.ComposedExplanationDTO;
import com.wse.qanaryexplanationservice.helper.pojos.ComposedExplanation;
import com.wse.qanaryexplanationservice.helper.pojos.QanaryComponent;
import com.wse.qanaryexplanationservice.services.ExplanationService;
import io.swagger.v3.oas.annotations.Operation;
import org.slf4j.Logger;
Expand All @@ -24,12 +25,12 @@ public class ExplanationController {
/**
* Computes the explanations for (currently) the output data for a specific graph and/or component
*
* @param componentURI ComponentURI with its prefixes
* @param component @see QanaryComponent
* @param acceptHeader The answer is formatted as RDF, possibly in RDF/XML, TTL or JSON-LD.
* @return Explanation for system or component as RDF
*/
@CrossOrigin
@GetMapping(value = {"/explanations/{graphURI}", "/explanations/{graphURI}/{componentURI}"}, produces = {
@GetMapping(value = {"/explanations/{graphURI}", "/explanations/{graphURI}/{component}"}, produces = {
"application/rdf+xml",
"text/turtle",
"application/ld+json",
Expand All @@ -46,16 +47,16 @@ public class ExplanationController {
)
public ResponseEntity<?> getExplanations(
@PathVariable String graphURI,
@PathVariable(required = false) String componentURI,
@PathVariable(required = false) QanaryComponent component,
@RequestHeader(value = "accept", required = false) String acceptHeader) throws Exception {
if (componentURI == null) {
if (component == null) {
String result = explanationService.getQaSystemExplanation(graphURI, acceptHeader);
if (result != null)
return new ResponseEntity<>(result, HttpStatus.OK);
else
return new ResponseEntity<>(null, HttpStatus.NOT_ACCEPTABLE);
} else {
String result = this.explanationService.getTemplateComponentExplanation(graphURI, componentURI, acceptHeader);
String result = this.explanationService.getTemplateComponentExplanation(graphURI, component, acceptHeader);
if (result != null)
return new ResponseEntity<>(result, HttpStatus.OK);
else
Expand Down Expand Up @@ -98,10 +99,10 @@ public ResponseEntity<?> getInputExplanation(
)
public ResponseEntity<?> getOutputExplanation(
@PathVariable String graphURI,
@PathVariable String componentURI,
@PathVariable QanaryComponent component,
@RequestHeader(value = "accept", required = false) String acceptHeader) {
try {
String explanationInFormattedString = explanationService.getTemplateComponentExplanation(graphURI, componentURI, acceptHeader);
String explanationInFormattedString = explanationService.getTemplateComponentExplanation(graphURI, component, acceptHeader);
return new ResponseEntity<>(explanationInFormattedString, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,28 +1,37 @@
package com.wse.qanaryexplanationservice.helper.pojos;

import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;

public class QanaryComponent {

@NotNull
private String componentName;
@NotNull
private String prefixedComponentName;
private String componentMainType;

public QanaryComponent() {

}

public QanaryComponent(String componentName) {
this.componentName = componentName;
setComponentNames(componentName);
}

public QanaryComponent(String componentName, String componentMainType) {
this.componentMainType = componentMainType;
this.componentName = componentName;
}

private void setComponentNames(String componentName) {
if (componentName.contains("urn:qanary:")) {
this.componentName = componentName.replace("urn:qanary:", "");
this.prefixedComponentName = componentName;
} else {
this.componentName = componentName;
this.prefixedComponentName = "urn:qanary:" + componentName;
}
}

public String getComponentMainType() {
return componentMainType;
}
Expand All @@ -38,4 +47,8 @@ public String getComponentName() {
public void setComponentName(String componentName) {
this.componentName = componentName;
}

public String getPrefixedComponentName() {
return prefixedComponentName;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ public String getQaSystemExplanation(String header, String graphUri) throws Exce
return tmplExpService.explainQaSystem(header, graphUri);
}

public String getTemplateComponentExplanation(String graphUri, String componentUri, String header) throws Exception {
return tmplExpService.explainComponentAsRdf(graphUri, componentUri, header);
public String getTemplateComponentExplanation(String graphUri, QanaryComponent component, String header) throws Exception {
return tmplExpService.explainComponentAsRdf(graphUri, component, header);
}

public String getTemplateComponentInputExplanation(String graphUri, String componentUri) throws IOException {
Expand Down Expand Up @@ -82,29 +82,29 @@ public ComposedExplanation composedExplanationsForOutputData(ComposedExplanation
}

public ComposedExplanation composedExplanationForInputData(ComposedExplanationDTO composedExplanationDTO) throws Exception {
List<String> components = composedExplanationDTO.getGenerativeExplanationRequest().getQanaryComponents().stream().map(QanaryComponent::getComponentName).toList();
List<QanaryComponent> components = composedExplanationDTO.getGenerativeExplanationRequest().getQanaryComponents();
String graph = composedExplanationDTO.getGraphUri();
ComposedExplanation composedExplanation = new ComposedExplanation();
for (String component : components) {
for (QanaryComponent component : components) {

QuerySolutionMap bindings = new QuerySolutionMap();
bindings.add("graph", ResourceFactory.createResource(graph));
bindings.add("component", ResourceFactory.createResource("urn:qanary:" + component));
bindings.add("component", ResourceFactory.createResource(component.getPrefixedComponentName()));
String query = QanaryTripleStoreConnector.readFileFromResourcesWithMap(TemplateExplanationsService.INPUT_DATA_SELECT_QUERY, bindings);
ResultSet results = qanaryRepository.selectWithResultSet(query);

QuerySolution querySolution = results.next(); // TODO: Add component to composedExplanation
String resultQuery = querySolution.get("body").toString();

String templatebasedExplanation = tmplExpService.createExplanationForQuery(querySolution, graph, component);
String templatebasedExplanation = tmplExpService.createExplanationForQuery(querySolution, graph, component.getComponentName());

String prompt = genExpService.getInputDataExplanationPrompt(
component,
component.getComponentName(),
resultQuery,
composedExplanationDTO.getGenerativeExplanationRequest().getShots()
);
String gptExplanation = genExpService.sendPrompt(prompt, composedExplanationDTO.getGenerativeExplanationRequest().getGptModel());
composedExplanation.addExplanationItem(component, templatebasedExplanation, prompt, gptExplanation, resultQuery);
composedExplanation.addExplanationItem(component.getComponentName(), templatebasedExplanation, prompt, gptExplanation, resultQuery);
}
return composedExplanation;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,12 +210,10 @@ public ResultSet fetchTriples(String graphURI, String componentURI, String annot
if (annotationType != null)
query = query.replace("?annotationType", "qa:" + annotationType);
ResultSet resultSet = qanaryRepository.selectWithResultSet(query);
if (resultSet.hasNext())
return resultSet;
else {
if (!resultSet.hasNext()) {
logger.warn("The resultSet for the component {} is null, empty dataset is returned.", componentURI);
return resultSet;
}
return resultSet;
} catch (IOException e) {
logger.error("Exception while passing values to plain query: {}", e.getLocalizedMessage());
throw new Exception(e);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.wse.qanaryexplanationservice.services;

import com.wse.qanaryexplanationservice.helper.pojos.QanaryComponent;
import com.wse.qanaryexplanationservice.repositories.QanaryRepository;
import eu.wdaqua.qanary.commons.triplestoreconnectors.QanaryTripleStoreConnector;
import org.apache.commons.lang3.StringUtils;
Expand All @@ -24,7 +25,6 @@
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -70,7 +70,6 @@ public class TemplateExplanationsService {
}};
private static final String EXPLANATION_NAMESPACE = "urn:qanary:explanations#";
Logger logger = LoggerFactory.getLogger(TemplateExplanationsService.class);
private Map<String, ResultSet> stringResultSetMap = new HashMap<>();
@Autowired
private QanaryRepository qanaryRepository;
@Value("${explanations.dataset.limit}")
Expand All @@ -84,24 +83,23 @@ public TemplateExplanationsService() {
/**
* Computes a textual explanation for a specific component on a specific graphURI
*
* @param graphUri specific graphURI
* @param componentUri specific componentURI
* @param graphUri specific graphURI
* @param component @see QanaryComponent
* @return Explanation in accepted format, default: Turtle
*/
public String explainComponentAsRdf(String graphUri, String componentUri, String header) throws IOException {
public String explainComponentAsRdf(String graphUri, QanaryComponent component, String header) throws IOException {
logger.info("Passed header: {}", header);
Model model = createModelForSpecificComponent(
explainComponentAsText(graphUri, componentUri, "de"),
explainComponentAsText(graphUri, componentUri, "en"),
"urn:qanary:" + componentUri
explainComponentAsText(graphUri, component.getPrefixedComponentName(), "de"),
explainComponentAsText(graphUri, component.getPrefixedComponentName(), "en"),
component.getPrefixedComponentName()
);
return convertToDesiredFormat(header, model);
}

public String explainComponentAsText(String graphUri, String componentUri, String lang) throws IOException {
String component = "urn:qanary:" + componentUri;
List<String> types = fetchAllAnnotations(graphUri, component);
return createTextualExplanation(graphUri, component, lang, types);
List<String> types = fetchAllAnnotations(graphUri, componentUri);
return createTextualExplanation(graphUri, componentUri, lang, types);
}

/**
Expand Down Expand Up @@ -132,10 +130,7 @@ private String composeExplanations(String componentURI, String lang, List<String
*/
public Model createModel(String graphUri, String componentUri) throws IOException {

List<String> types = new ArrayList<>();
if (stringResultSetMap.isEmpty()) {
types = fetchAllAnnotations(graphUri, componentUri);
}
List<String> types = fetchAllAnnotations(graphUri, componentUri); // Can be cached
String contentDE = createTextualExplanation(graphUri, componentUri, "de", types);
String contentEN = createTextualExplanation(graphUri, componentUri, "en", types);

Expand Down Expand Up @@ -489,10 +484,6 @@ public String createTextualExplanation(String graphURI, String componentURI, Str

Map<String, List<String>> createdExplanations = createSpecificExplanations(types, graphURI, lang, componentURI);

AtomicInteger i = new AtomicInteger();

// createdExplanations.forEach((component, list) -> createdExplanations.put(component, list.stream().skip(1).map((explanation) -> i.incrementAndGet() + ". " + explanation).toList()));

StringBuilder result = new StringBuilder();
createdExplanations.forEach((component, list) -> {
result.append(composeExplanations(componentURI, lang, list, list.get(0)));
Expand Down
29 changes: 29 additions & 0 deletions src/test/java/com/wse/qanaryexplanationservice/PojoTests.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.wse.qanaryexplanationservice;

import com.wse.qanaryexplanationservice.helper.pojos.QanaryComponent;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.TestComponent;

@TestComponent
public class PojoTests {

@Test
public void testCorrectPrefixingWithPlainName() {
String componentName = "test";
QanaryComponent qanaryComponent = new QanaryComponent(componentName);

Assertions.assertEquals(componentName, qanaryComponent.getComponentName());
Assertions.assertEquals("urn:qanary:" + componentName, qanaryComponent.getPrefixedComponentName());
}

@Test
public void testCorrectPrefixingWithPrefixedName() {
String componentName = "urn:qanary:test";
QanaryComponent qanaryComponent = new QanaryComponent(componentName);

Assertions.assertEquals(componentName, qanaryComponent.getPrefixedComponentName());
Assertions.assertEquals("test", qanaryComponent.getComponentName());
}

}

0 comments on commit c939d5e

Please sign in to comment.