Skip to content
Snippets Groups Projects
Commit 05a8d6cf authored by Coskun, Ertan's avatar Coskun, Ertan
Browse files

Merge branch '31-directly-assign-and-visualize-the-prefix-of-a-qnode' into 'main'

directly added the qname to the QNodes

Closes #31

See merge request !40
parents 48bd1418 ce694068
No related branches found
No related tags found
1 merge request!40directly added the qname to the QNodes
Pipeline #1751898 passed
...@@ -13,24 +13,26 @@ class Action: ...@@ -13,24 +13,26 @@ class Action:
file_path (str): the location of the file in the local machine, which should be read from. file_path (str): the location of the file in the local machine, which should be read from.
Returns: Returns:
A Tuple consisting of the triples (boolean, statements, prefixes). A Tuple consisting of the triples (boolean, statements, prefixes, graph).
The boolean tells if the process was correctly executed or an error occurred. The boolean tells if the process was correctly executed or an error occurred.
Statements are a list of triples of (subject, predicate, object). Statements are a list of triples of (subject, predicate, object).
Prefixes are a dictionary of str with their shortened replacement. Prefixes are a dictionary of str with their shortened replacement.
Graph (rdflib.Graph) : Data structure of the loaded graph.
""" """
g = rdflib.Graph() g: rdflib.Graph = rdflib.Graph()
print("[info] parsing file: {}".format(file_path)) print("[info] parsing file: {}".format(file_path))
try: try:
g.parse(file_path) g.parse(file_path)
except Exception: except Exception:
print("[error] could not parse file: {}".format(file_path)) print("[error] could not parse file: {}".format(file_path))
return False, None, None return False, None, None, None
print("[info] parsing finished.") print("[info] parsing finished.")
print("[info] getting prefixes...") print("[info] getting prefixes...")
prefixes: dict[str, rdflib.URIRef] = dict(g.namespaces()) prefixes: dict[str, rdflib.URIRef] = dict(g.namespaces())
print("[info] done.") print("[info] done.")
triples = g.triples((None, None, None)) triples = g.triples((None, None, None))
return True, triples, prefixes return True, triples, prefixes, g
@staticmethod @staticmethod
def _writeFile(graph: rdflib.Graph, filePath: str, format: str): def _writeFile(graph: rdflib.Graph, filePath: str, format: str):
......
...@@ -42,7 +42,7 @@ class QRDFGraph(QWidget): ...@@ -42,7 +42,7 @@ class QRDFGraph(QWidget):
# init Graph # init Graph
self.nodes: Dict[Tuple[str, Optional[QNode.Parent]], QNode] = {} self.nodes: Dict[Tuple[str, Optional[QNode.Parent]], QNode] = {}
self.edges: Dict[Tuple[str, QNode, QNode], QEdge] = {} self.edges: Dict[Tuple[str, QNode, QNode], QEdge] = {}
self.graph: rdflib.Graph | None = None
self.prefixes: Dict[str, str] = {} self.prefixes: Dict[str, str] = {}
self._lastOpenedFile = "" self._lastOpenedFile = ""
...@@ -136,7 +136,7 @@ class QRDFGraph(QWidget): ...@@ -136,7 +136,7 @@ class QRDFGraph(QWidget):
"""Creates a new data node and add it to the graph. """Creates a new data node and add it to the graph.
It creates a new data node with a standard template It creates a new data node with a standard template
and add it to graph with the szene location of the contextmenu. and add it to graph with the scene location of the context menu.
""" """
print("add a node at:", self.contextMenuPos) print("add a node at:", self.contextMenuPos)
if self.contextMenuPos: if self.contextMenuPos:
...@@ -236,10 +236,10 @@ class QRDFGraph(QWidget): ...@@ -236,10 +236,10 @@ class QRDFGraph(QWidget):
self._lastOpenedFile = file_path self._lastOpenedFile = file_path
self._openedFiles.append(file_path) self._openedFiles.append(file_path)
successful, statements, prefixes = Action._readFile(file_path) successful, statements, prefixes, graph = Action._readFile(file_path)
if not successful: if not successful:
return False return False
self.graph = graph
self.prefixes = prefixes self.prefixes = prefixes
print("Extracted prefixes:", self.prefixes) print("Extracted prefixes:", self.prefixes)
statements = list(statements) statements = list(statements)
...@@ -317,7 +317,30 @@ class QRDFGraph(QWidget): ...@@ -317,7 +317,30 @@ class QRDFGraph(QWidget):
""" """
node = self.nodes.get((value, parent)) node = self.nodes.get((value, parent))
if node is None: if node is None:
node = QNode(value, parent, graph=self, label=label, size=size, pos=pos)
q_name = None
if self.graph:
all_nodes: list[rdflib.Node] = list(self.graph.all_nodes())
for node in all_nodes:
if (
isinstance(node, rdflib.URIRef)
and str(node) == value
and value.startswith("http")
and not self.graph.qname(value).startswith("ns")
):
q_name = self.graph.qname(value)
break
node = QNode(
value=value,
parent=parent,
graph=self,
label=label,
pos=pos,
size=size,
is_prefix_shown=q_name,
q_name=q_name
)
self.view.changed_zoom_factor.connect(node.update_font_size) self.view.changed_zoom_factor.connect(node.update_font_size)
self.view.reached_text_visibility_factor.connect(node.set_label_visible) self.view.reached_text_visibility_factor.connect(node.set_label_visible)
self.nodes[(value, parent)] = node self.nodes[(value, parent)] = node
...@@ -339,7 +362,7 @@ class QRDFGraph(QWidget): ...@@ -339,7 +362,7 @@ class QRDFGraph(QWidget):
startNode (QNode): The subject of this statement. startNode (QNode): The subject of this statement.
endNode (QNode): The object of this statement. endNode (QNode): The object of this statement.
edgeType (QEdge.EdgeType): Information of this statement, edgeType (QEdge.EdgeType): Information of this statement,
if it refering to itself or is a simplex or duplex. if it's referring to itself or is a simplex or duplex.
Returns: Returns:
QEdge: The edge data entry. QEdge: The edge data entry.
......
...@@ -65,6 +65,8 @@ class QNode(QGraphicsItem): ...@@ -65,6 +65,8 @@ class QNode(QGraphicsItem):
label: Optional[str] = None, label: Optional[str] = None,
pos: Optional[QPointF] = None, pos: Optional[QPointF] = None,
size: float = 40.0, size: float = 40.0,
is_prefix_shown: bool = False,
q_name: str | None = None
) -> None: ) -> None:
"""Initializes a QNode instance. """Initializes a QNode instance.
...@@ -75,6 +77,8 @@ class QNode(QGraphicsItem): ...@@ -75,6 +77,8 @@ class QNode(QGraphicsItem):
label (Optional[str], optional): The label of the node. Defaults to None. label (Optional[str], optional): The label of the node. Defaults to None.
pos (Optional[QPointF], optional): The position of the node. Defaults to None. pos (Optional[QPointF], optional): The position of the node. Defaults to None.
size (float, optional): The size of the node. Defaults to 40 and is also set at QRDFGraph addNode. size (float, optional): The size of the node. Defaults to 40 and is also set at QRDFGraph addNode.
is_prefix_shown (bool): Describes if the prefix should be visible inside the node. Defaults to False.
q_name (str|None): the combination of the prefix and the rest of the URI. Defaults to None.
""" """
super().__init__(None) super().__init__(None)
...@@ -89,6 +93,9 @@ class QNode(QGraphicsItem): ...@@ -89,6 +93,9 @@ class QNode(QGraphicsItem):
self.types: Set[QNode] = set() self.types: Set[QNode] = set()
self.kind: QNode.Kind = QNode.Kind.URI if parent is None else QNode.Kind.STRING self.kind: QNode.Kind = QNode.Kind.URI if parent is None else QNode.Kind.STRING
self.is_prefix_shown = is_prefix_shown
self.q_name = q_name
self.marked: bool = False self.marked: bool = False
self.bounding_text_rect: QRectF = QRectF(0.0, 0.0, self.size, self.size).normalized() self.bounding_text_rect: QRectF = QRectF(0.0, 0.0, self.size, self.size).normalized()
...@@ -261,13 +268,18 @@ class QNode(QGraphicsItem): ...@@ -261,13 +268,18 @@ class QNode(QGraphicsItem):
self.kind = QNode.Kind.URI if self.parent is None else QNode.Kind.STRING self.kind = QNode.Kind.URI if self.parent is None else QNode.Kind.STRING
def inferLabel(self) -> None: def inferLabel(self) -> None:
"""Sets the label of the node based on the prefixes in the graph.""" """Determines the label of the visual node.
for prefixUri, prefixLabel in self.graph.prefixes.items():
if self.value.startswith(prefixUri.rstrip("/")): If the is_prefix_shown boolean equals true,
remaining_uri = self.value[len(prefixUri) :] then the label will be the q_name.
self.label = prefixLabel + "+" + remaining_uri
self.marked = True Else the label will be the last string part after the last "/" symbol.
If there is no symbol after the last "/" symbol the string after the next-to-last "/" symbol.
"""
if self.is_prefix_shown:
self.label = self.q_name
return return
if self.value.split("/")[-1] == "": if self.value.split("/")[-1] == "":
self.label = self.value self.label = self.value
else: else:
......
...@@ -4,7 +4,7 @@ from rdfviewer.controller.actions import Action ...@@ -4,7 +4,7 @@ from rdfviewer.controller.actions import Action
def testActionReadFromJsonLd(): def testActionReadFromJsonLd():
"""Tests if the software can read from Json Files with prefixes.""" """Tests if the software can read from Json Files with prefixes."""
status, triples, prefixes = Action._readFile("tests/data/ro-test.json") status, triples, prefixes, graph = Action._readFile("tests/data/ro-test.json")
triples = tuple(triples) triples = tuple(triples)
print("[test] triples:") print("[test] triples:")
for triple in triples: for triple in triples:
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment