Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat: enhance visualization and fix source tracker
KaifAhmad100322d81c6d4
diff --git a/cookbook/advanced/12_Unstructured_to_Ontology.ipynb b/cookbook/advanced/12_Unstructured_to_Ontology.ipynbindex dcf8d58d..21b65979 100644--- a/cookbook/advanced/12_Unstructured_to_Ontology.ipynb+++ b/cookbook/advanced/12_Unstructured_to_Ontology.ipynb@@ -105,7 +105,7 @@"\n","# 4. Generate Structure\n","generator = OntologyGenerator()\n",- "nlp_ontology = generator.generate(entities, relationships, name=\"QuantumOntologyNLP\")\n",+ "nlp_ontology = generator.generate_ontology({\"entities\": entities, \"relationships\": relationships}, name=\"QuantumOntologyNLP\")\n","\n","# 5. Optimize (Clean up)\n","optimizer = OntologyOptimizer()\n",diff --git a/cookbook/introduction/16_Visualization.ipynb b/cookbook/introduction/16_Visualization.ipynbindex 38ec7350..6274149e 100644--- a/cookbook/introduction/16_Visualization.ipynb+++ b/cookbook/introduction/16_Visualization.ipynb@@ -39,18 +39,47 @@},{"cell_type": "code",- "execution_count": null,+ "execution_count": 2,"metadata": {},- "outputs": [],+ "outputs": [+ {+ "name": "stderr",+ "output_type": "stream",+ "text": [+ "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~gno (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~lotly (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n",+ "WARNING: Ignoring invalid distribution ~ython-socketio (C:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages)\n"+ ]+ }+ ],"source": [- "!pip install semantica\n"+ "!pip install -q semantica"]},{"cell_type": "code",- "execution_count": null,+ "execution_count": 3,"metadata": {},- "outputs": [],+ "outputs": [+ {+ "data": {+ "text/html": [+ "<div style='font-family: monospace;'><h4>π§ Semantica - π Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>DuplicateDetector</td><td>-</td><td>0.02s</td></tr><tr><td>β </td><td>Semantica is deduplicating</td><td>π deduplication</td><td>SimilarityCalculator</td><td>-</td><td>0.00s</td></tr><tr><td>β </td><td>Semantica is resolving</td><td>β οΈ conflicts</td><td>ConflictDetector</td><td>-</td><td>0.00s</td></tr><tr><td>β </td><td>Semantica is visualizing</td><td>π visualization</td><td>KGVisualizer</td><td>-</td><td>0.07s</td></tr><tr><td>β </td><td>Semantica is generating</td><td>π ontology</td><td>OntologyGenerator</td><td>-</td><td>0.04s</td></tr><tr><td>β </td><td>Semantica is generating</td><td>π ontology</td><td>ClassInferrer</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is generating</td><td>π ontology</td><td>PropertyGenerator</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is visualizing</td><td>π visualization</td><td>OntologyVisualizer</td><td>-</td><td>0.15s</td></tr><tr><td>β </td><td>Semantica is visualizing</td><td>π visualization</td><td>EmbeddingVisualizer</td><td>-</td><td>0.03s</td></tr><tr><td>β </td><td>Semantica is visualizing</td><td>π visualization</td><td>SemanticNetworkVisualizer</td><td>-</td><td>0.08s</td></tr></table></div>"+ ],+ "text/plain": [+ "<IPython.core.display.HTML object>"+ ]+ },+ "metadata": {},+ "output_type": "display_data"+ }+ ],"source": ["from semantica.visualization import KGVisualizer\n","from semantica.kg import GraphBuilder\n",@@ -83,7 +112,7 @@},{"cell_type": "code",- "execution_count": null,+ "execution_count": 4,"metadata": {},"outputs": [],"source": [@@ -91,11 +120,14 @@"from semantica.ontology import OntologyGenerator\n","\n","ontology_visualizer = OntologyVisualizer()\n",- "generator = OntologyGenerator()\n",+ "# Initialize generator with min_occurrences=1 to allow single-instance classes\n",+ "generator = OntologyGenerator(min_occurrences=1)\n","\n",- "ontology = generator.generate(entities, relationships)\n",+ "# Generate ontology using the correct method signature (dictionary input)\n",+ "ontology = generator.generate_ontology({\"entities\": entities, \"relationships\": relationships})\n","\n",- "visualization = ontology_visualizer.visualize_hierarchy(ontology, output=\"interactive\")\n"+ "# Visualize the hierarchy\n",+ "visualization = ontology_visualizer.visualize_hierarchy(ontology, output=\"interactive\")"]},{@@ -109,9 +141,21 @@},{"cell_type": "code",- "execution_count": null,+ "execution_count": 5,"metadata": {},- "outputs": [],+ "outputs": [+ {+ "name": "stderr",+ "output_type": "stream",+ "text": [+ "c:\\Users\\Mohd Kaif\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\sentence_transformers\\cross_encoder\\CrossEncoder.py:13: TqdmExperimentalWarning:\n",+ "\n",+ "Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console)\n",+ "\n",+ "UMAP not available, using PCA. Install with: pip install umap-learn\n"+ ]+ }+ ],"source": ["from semantica.visualization import EmbeddingVisualizer\n","from semantica.embeddings import EmbeddingGenerator\n",@@ -138,53 +182,967 @@},{"cell_type": "code",- "execution_count": null,+ "execution_count": 6,"metadata": {},- "outputs": [],+ "outputs": [+ {+ "data": {+ "application/vnd.plotly.v1+json": {+ "config": {+ "plotlyServerURL": "https://plot.ly"+ },+ "data": [+ {+ "hoverinfo": "none",+ "line": {+ "color": "#888",+ "width": 1+ },+ "mode": "lines",+ "opacity": 0.5,+ "showlegend": false,+ "type": "scatter",+ "x": [+ 1,+ -1,+ null+ ],+ "y": [+ 4.3711388286737935e-8,+ -4.3711388286737935e-8,+ null+ ]+ },+ {+ "hoverinfo": "text",+ "hovertext": [+ "<b>Python</b><br>Type: Language",+ "<b>Code</b><br>Type: Concept"+ ],+ "marker": {+ "color": [+ "#ff7f0e",+ "#1f77b4"+ ],+ "line": {+ "color": "white",+ "width": 2+ },+ "opacity": 1,+ "size": [+ 10,+ 10+ ]+ },+ "mode": "markers+text",+ "showlegend": false,+ "text": [+ "Python",+ "Code"+ ],+ "textfont": {+ "color": "#333",+ "size": 10+ },+ "textposition": "top center",+ "type": "scatter",+ "x": [+ 1,+ -1+ ],+ "y": [+ 4.3711388286737935e-8,+ -4.3711388286737935e-8+ ]+ }+ ],+ "layout": {+ "annotations": [+ {+ "arrowcolor": "#888",+ "arrowhead": 2,+ "arrowsize": 1,+ "arrowwidth": 1,+ "ax": 1,+ "axref": "x",+ "ay": 4.3711388286737935e-8,+ "ayref": "y",+ "opacity": 0.6,+ "standoff": 15,+ "x": -1,+ "xref": "x",+ "y": -4.3711388286737935e-8,+ "yref": "y"+ }+ ],+ "hovermode": "closest",+ "margin": {+ "b": 20,+ "l": 5,+ "r": 5,+ "t": 40+ },+ "plot_bgcolor": "white",+ "showlegend": false,+ "template": {+ "data": {+ "bar": [+ {+ "error_x": {+ "color": "#2a3f5f"+ },+ "error_y": {+ "color": "#2a3f5f"+ },+ "marker": {+ "line": {+ "color": "#E5ECF6",+ "width": 0.5+ },+ "pattern": {+ "fillmode": "overlay",+ "size": 10,+ "solidity": 0.2+ }+ },+ "type": "bar"+ }+ ],+ "barpolar": [+ {+ "marker": {+ "line": {+ "color": "#E5ECF6",+ "width": 0.5+ },+ "pattern": {+ "fillmode": "overlay",+ "size": 10,+ "solidity": 0.2+ }+ },+ "type": "barpolar"+ }+ ],+ "carpet": [+ {+ "aaxis": {+ "endlinecolor": "#2a3f5f",+ "gridcolor": "white",+ "linecolor": "white",+ "minorgridcolor": "white",+ "startlinecolor": "#2a3f5f"+ },+ "baxis": {+ "endlinecolor": "#2a3f5f",+ "gridcolor": "white",+ "linecolor": "white",+ "minorgridcolor": "white",+ "startlinecolor": "#2a3f5f"+ },+ "type": "carpet"+ }+ ],+ "choropleth": [+ {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ },+ "type": "choropleth"+ }+ ],+ "contour": [+ {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ },+ "colorscale": [+ [+ 0,+ "#0d0887"+ ],+ [+ 0.1111111111111111,+ "#46039f"+ ],+ [+ 0.2222222222222222,+ "#7201a8"+ ],+ [+ 0.3333333333333333,+ "#9c179e"+ ],+ [+ 0.4444444444444444,+ "#bd3786"+ ],+ [+ 0.5555555555555556,+ "#d8576b"+ ],+ [+ 0.6666666666666666,+ "#ed7953"+ ],+ [+ 0.7777777777777778,+ "#fb9f3a"+ ],+ [+ 0.8888888888888888,+ "#fdca26"+ ],+ [+ 1,+ "#f0f921"+ ]+ ],+ "type": "contour"+ }+ ],+ "contourcarpet": [+ {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ },+ "type": "contourcarpet"+ }+ ],+ "heatmap": [+ {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ },+ "colorscale": [+ [+ 0,+ "#0d0887"+ ],+ [+ 0.1111111111111111,+ "#46039f"+ ],+ [+ 0.2222222222222222,+ "#7201a8"+ ],+ [+ 0.3333333333333333,+ "#9c179e"+ ],+ [+ 0.4444444444444444,+ "#bd3786"+ ],+ [+ 0.5555555555555556,+ "#d8576b"+ ],+ [+ 0.6666666666666666,+ "#ed7953"+ ],+ [+ 0.7777777777777778,+ "#fb9f3a"+ ],+ [+ 0.8888888888888888,+ "#fdca26"+ ],+ [+ 1,+ "#f0f921"+ ]+ ],+ "type": "heatmap"+ }+ ],+ "heatmapgl": [+ {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ },+ "colorscale": [+ [+ 0,+ "#0d0887"+ ],+ [+ 0.1111111111111111,+ "#46039f"+ ],+ [+ 0.2222222222222222,+ "#7201a8"+ ],+ [+ 0.3333333333333333,+ "#9c179e"+ ],+ [+ 0.4444444444444444,+ "#bd3786"+ ],+ [+ 0.5555555555555556,+ "#d8576b"+ ],+ [+ 0.6666666666666666,+ "#ed7953"+ ],+ [+ 0.7777777777777778,+ "#fb9f3a"+ ],+ [+ 0.8888888888888888,+ "#fdca26"+ ],+ [+ 1,+ "#f0f921"+ ]+ ],+ "type": "heatmapgl"+ }+ ],+ "histogram": [+ {+ "marker": {+ "pattern": {+ "fillmode": "overlay",+ "size": 10,+ "solidity": 0.2+ }+ },+ "type": "histogram"+ }+ ],+ "histogram2d": [+ {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ },+ "colorscale": [+ [+ 0,+ "#0d0887"+ ],+ [+ 0.1111111111111111,+ "#46039f"+ ],+ [+ 0.2222222222222222,+ "#7201a8"+ ],+ [+ 0.3333333333333333,+ "#9c179e"+ ],+ [+ 0.4444444444444444,+ "#bd3786"+ ],+ [+ 0.5555555555555556,+ "#d8576b"+ ],+ [+ 0.6666666666666666,+ "#ed7953"+ ],+ [+ 0.7777777777777778,+ "#fb9f3a"+ ],+ [+ 0.8888888888888888,+ "#fdca26"+ ],+ [+ 1,+ "#f0f921"+ ]+ ],+ "type": "histogram2d"+ }+ ],+ "histogram2dcontour": [+ {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ },+ "colorscale": [+ [+ 0,+ "#0d0887"+ ],+ [+ 0.1111111111111111,+ "#46039f"+ ],+ [+ 0.2222222222222222,+ "#7201a8"+ ],+ [+ 0.3333333333333333,+ "#9c179e"+ ],+ [+ 0.4444444444444444,+ "#bd3786"+ ],+ [+ 0.5555555555555556,+ "#d8576b"+ ],+ [+ 0.6666666666666666,+ "#ed7953"+ ],+ [+ 0.7777777777777778,+ "#fb9f3a"+ ],+ [+ 0.8888888888888888,+ "#fdca26"+ ],+ [+ 1,+ "#f0f921"+ ]+ ],+ "type": "histogram2dcontour"+ }+ ],+ "mesh3d": [+ {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ },+ "type": "mesh3d"+ }+ ],+ "parcoords": [+ {+ "line": {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ }+ },+ "type": "parcoords"+ }+ ],+ "pie": [+ {+ "automargin": true,+ "type": "pie"+ }+ ],+ "scatter": [+ {+ "fillpattern": {+ "fillmode": "overlay",+ "size": 10,+ "solidity": 0.2+ },+ "type": "scatter"+ }+ ],+ "scatter3d": [+ {+ "line": {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ }+ },+ "marker": {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ }+ },+ "type": "scatter3d"+ }+ ],+ "scattercarpet": [+ {+ "marker": {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ }+ },+ "type": "scattercarpet"+ }+ ],+ "scattergeo": [+ {+ "marker": {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ }+ },+ "type": "scattergeo"+ }+ ],+ "scattergl": [+ {+ "marker": {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ }+ },+ "type": "scattergl"+ }+ ],+ "scattermapbox": [+ {+ "marker": {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ }+ },+ "type": "scattermapbox"+ }+ ],+ "scatterpolar": [+ {+ "marker": {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ }+ },+ "type": "scatterpolar"+ }+ ],+ "scatterpolargl": [+ {+ "marker": {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ }+ },+ "type": "scatterpolargl"+ }+ ],+ "scatterternary": [+ {+ "marker": {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ }+ },+ "type": "scatterternary"+ }+ ],+ "surface": [+ {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ },+ "colorscale": [+ [+ 0,+ "#0d0887"+ ],+ [+ 0.1111111111111111,+ "#46039f"+ ],+ [+ 0.2222222222222222,+ "#7201a8"+ ],+ [+ 0.3333333333333333,+ "#9c179e"+ ],+ [+ 0.4444444444444444,+ "#bd3786"+ ],+ [+ 0.5555555555555556,+ "#d8576b"+ ],+ [+ 0.6666666666666666,+ "#ed7953"+ ],+ [+ 0.7777777777777778,+ "#fb9f3a"+ ],+ [+ 0.8888888888888888,+ "#fdca26"+ ],+ [+ 1,+ "#f0f921"+ ]+ ],+ "type": "surface"+ }+ ],+ "table": [+ {+ "cells": {+ "fill": {+ "color": "#EBF0F8"+ },+ "line": {+ "color": "white"+ }+ },+ "header": {+ "fill": {+ "color": "#C8D4E3"+ },+ "line": {+ "color": "white"+ }+ },+ "type": "table"+ }+ ]+ },+ "layout": {+ "annotationdefaults": {+ "arrowcolor": "#2a3f5f",+ "arrowhead": 0,+ "arrowwidth": 1+ },+ "autotypenumbers": "strict",+ "coloraxis": {+ "colorbar": {+ "outlinewidth": 0,+ "ticks": ""+ }+ },+ "colorscale": {+ "diverging": [+ [+ 0,+ "#8e0152"+ ],+ [+ 0.1,+ "#c51b7d"+ ],+ [+ 0.2,+ "#de77ae"+ ],+ [+ 0.3,+ "#f1b6da"+ ],+ [+ 0.4,+ "#fde0ef"+ ],+ [+ 0.5,+ "#f7f7f7"+ ],+ [+ 0.6,+ "#e6f5d0"+ ],+ [+ 0.7,+ "#b8e186"+ ],+ [+ 0.8,+ "#7fbc41"+ ],+ [+ 0.9,+ "#4d9221"+ ],+ [+ 1,+ "#276419"+ ]+ ],+ "sequential": [+ [+ 0,+ "#0d0887"+ ],+ [+ 0.1111111111111111,+ "#46039f"+ ],+ [+ 0.2222222222222222,+ "#7201a8"+ ],+ [+ 0.3333333333333333,+ "#9c179e"+ ],+ [+ 0.4444444444444444,+ "#bd3786"+ ],+ [+ 0.5555555555555556,+ "#d8576b"+ ],+ [+ 0.6666666666666666,+ "#ed7953"+ ],+ [+ 0.7777777777777778,+ "#fb9f3a"+ ],+ [+ 0.8888888888888888,+ "#fdca26"+ ],+ [+ 1,+ "#f0f921"+ ]+ ],+ "sequentialminus": [+ [+ 0,+ "#0d0887"+ ],+ [+ 0.1111111111111111,+ "#46039f"+ ],+ [+ 0.2222222222222222,+ "#7201a8"+ ],+ [+ 0.3333333333333333,+ "#9c179e"+ ],+ [+ 0.4444444444444444,+ "#bd3786"+ ],+ [+ 0.5555555555555556,+ "#d8576b"+ ],+ [+ 0.6666666666666666,+ "#ed7953"+ ],+ [+ 0.7777777777777778,+ "#fb9f3a"+ ],+ [+ 0.8888888888888888,+ "#fdca26"+ ],+ [+ 1,+ "#f0f921"+ ]+ ]+ },+ "colorway": [+ "#636efa",+ "#EF553B",+ "#00cc96",+ "#ab63fa",+ "#FFA15A",+ "#19d3f3",+ "#FF6692",+ "#B6E880",+ "#FF97FF",+ "#FECB52"+ ],+ "font": {+ "color": "#2a3f5f"+ },+ "geo": {+ "bgcolor": "white",+ "lakecolor": "white",+ "landcolor": "#E5ECF6",+ "showlakes": true,+ "showland": true,+ "subunitcolor": "white"+ },+ "hoverlabel": {+ "align": "left"+ },+ "hovermode": "closest",+ "mapbox": {+ "style": "light"+ },+ "paper_bgcolor": "white",+ "plot_bgcolor": "#E5ECF6",+ "polar": {+ "angularaxis": {+ "gridcolor": "white",+ "linecolor": "white",+ "ticks": ""+ },+ "bgcolor": "#E5ECF6",+ "radialaxis": {+ "gridcolor": "white",+ "linecolor": "white",+ "ticks": ""+ }+ },+ "scene": {+ "xaxis": {+ "backgroundcolor": "#E5ECF6",+ "gridcolor": "white",+ "gridwidth": 2,+ "linecolor": "white",+ "showbackground": true,+ "ticks": "",+ "zerolinecolor": "white"+ },+ "yaxis": {+ "backgroundcolor": "#E5ECF6",+ "gridcolor": "white",+ "gridwidth": 2,+ "linecolor": "white",+ "showbackground": true,+ "ticks": "",+ "zerolinecolor": "white"+ },+ "zaxis": {+ "backgroundcolor": "#E5ECF6",+ "gridcolor": "white",+ "gridwidth": 2,+ "linecolor": "white",+ "showbackground": true,+ "ticks": "",+ "zerolinecolor": "white"+ }+ },+ "shapedefaults": {+ "line": {+ "color": "#2a3f5f"+ }+ },+ "ternary": {+ "aaxis": {+ "gridcolor": "white",+ "linecolor": "white",+ "ticks": ""+ },+ "baxis": {+ "gridcolor": "white",+ "linecolor": "white",+ "ticks": ""+ },+ "bgcolor": "#E5ECF6",+ "caxis": {+ "gridcolor": "white",+ "linecolor": "white",+ "ticks": ""+ }+ },+ "title": {+ "x": 0.05+ },+ "xaxis": {+ "automargin": true,+ "gridcolor": "white",+ "linecolor": "white",+ "ticks": "",+ "title": {+ "standoff": 15+ },+ "zerolinecolor": "white",+ "zerolinewidth": 2+ },+ "yaxis": {+ "automargin": true,+ "gridcolor": "white",+ "linecolor": "white",+ "ticks": "",+ "title": {+ "standoff": 15+ },+ "zerolinecolor": "white",+ "zerolinewidth": 2+ }+ }+ },+ "title": {+ "text": "Knowledge Graph Network"+ },+ "xaxis": {+ "showgrid": false,+ "showticklabels": false,+ "zeroline": false+ },+ "yaxis": {+ "showgrid": false,+ "showticklabels": false,+ "zeroline": false+ }+ }+ }+ },+ "metadata": {},+ "output_type": "display_data"+ }+ ],"source": ["from semantica.visualization import SemanticNetworkVisualizer\n","\n",+ "# Initialize (uses new defaults: Vibrant colors, Kamada-Kawai layout)\n",+ "viz = SemanticNetworkVisualizer()\n",+ "\n",+ "# Your semantic network data\n","semantic_network = {\n"," \"nodes\": [\n",- " {\"id\": \"n1\", \"label\": \"Node 1\", \"type\": \"Entity\"},\n",- " {\"id\": \"n2\", \"label\": \"Node 2\", \"type\": \"Entity\"}\n",+ " {\"id\": \"n1\", \"label\": \"Python\", \"type\": \"Language\"},\n",+ " {\"id\": \"n2\", \"label\": \"Code\", \"type\": \"Concept\"}\n"," ],\n"," \"edges\": [\n",- " {\"source\": \"n1\", \"target\": \"n2\", \"label\": \"related_to\"}\n",+ " {\"source\": \"n1\", \"target\": \"n2\", \"label\": \"writes\"}\n"," ]\n","}\n","\n",- "sem_viz = SemanticNetworkVisualizer()\n",- "sem_viz.visualize_network(semantic_network, output=\"interactive\")\n",- "sem_viz.visualize_node_types(semantic_network, output=\"interactive\")\n",- "sem_viz.visualize_edge_types(semantic_network, output=\"interactive\")\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Advanced Embedding Visualization\n",- "\n",- "Compare multi-modal embeddings and assess embedding quality."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import numpy as np\n",- "from semantica.visualization import EmbeddingVisualizer\n",- "\n",- "# Synthetic multi-modal embeddings (text, image, audio)\n",- "text_emb = np.random.rand(50, 128)\n",- "image_emb = np.random.rand(50, 128)\n",- "audio_emb = np.random.rand(50, 128)\n",- "\n",- "emb_viz = EmbeddingVisualizer()\n",- "emb_viz.visualize_multimodal_comparison(text_emb, image_emb, audio_emb, output=\"interactive\")\n"+ "# This will now display the interactive graph in the notebook cell\n",+ "viz.visualize_network(\n",+ " semantic_network, \n",+ " output=\"html\", \n",+ " file_path=\"network_graph.html\"\n",+ ")"]},{@@ -205,10 +1163,24 @@}],"metadata": {+ "kernelspec": {+ "display_name": "Python 3",+ "language": "python",+ "name": "python3"+ },"language_info": {- "name": "python"+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3",+ "version": "3.11.9"}},"nbformat": 4,"nbformat_minor": 2-}\ No newline at end of file+}diff --git a/cookbook/introduction/17_Conflict_Detection_and_Resolution.ipynb b/cookbook/introduction/17_Conflict_Detection_and_Resolution.ipynbindex 7b266c86..ebdc6d41 100644--- a/cookbook/introduction/17_Conflict_Detection_and_Resolution.ipynb+++ b/cookbook/introduction/17_Conflict_Detection_and_Resolution.ipynb@@ -29,7 +29,7 @@},{"cell_type": "code",- "execution_count": null,+ "execution_count": 1,"metadata": {},"outputs": [],"source": [@@ -56,9 +56,17 @@},{"cell_type": "code",- "execution_count": null,+ "execution_count": 2,"metadata": {},- "outputs": [],+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Loaded 3 records for Employee 001\n"+ ]+ }+ ],"source": ["# Define simulated data sources\n","sources = {\n",@@ -109,21 +117,33 @@},{"cell_type": "code",- "execution_count": null,+ "execution_count": 8,"metadata": {},- "outputs": [],+ "outputs": [+ {+ "ename": "AttributeError",+ "evalue": "'SourceTracker' object has no attribute 'register_source'",+ "output_type": "error",+ "traceback": [+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",+ "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)",+ "Cell \u001b[1;32mIn[8], line 7\u001b[0m\n\u001b[0;32m 4\u001b[0m source_tracker \u001b[38;5;241m=\u001b[39m SourceTracker()\n\u001b[0;32m 6\u001b[0m \u001b[38;5;66;03m# 4. Now this will work\u001b[39;00m\n\u001b[1;32m----> 7\u001b[0m \u001b[43msource_tracker\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mregister_source\u001b[49m(\n\u001b[0;32m 8\u001b[0m source_id\u001b[38;5;241m=\u001b[39msource_id,\n\u001b[0;32m 9\u001b[0m source_type\u001b[38;5;241m=\u001b[39mmetadata[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtype\u001b[39m\u001b[38;5;124m\"\u001b[39m],\n\u001b[0;32m 10\u001b[0m credibility_score\u001b[38;5;241m=\u001b[39mmetadata[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcredibility\u001b[39m\u001b[38;5;124m\"\u001b[39m]\n\u001b[0;32m 11\u001b[0m )\n",+ "\u001b[1;31mAttributeError\u001b[0m: 'SourceTracker' object has no attribute 'register_source'"+ ]+ }+ ],"source": [- "source_tracker = SourceTracker()\n",+ "from semantica.conflicts import SourceTracker\n","\n",- "# Register sources with their metadata and credibility scores\n",- "for source_id, metadata in sources.items():\n",- " source_tracker.register_source(\n",- " source_id=source_id,\n",- " source_type=metadata[\"type\"],\n",- " credibility_score=metadata[\"credibility\"]\n",- " )\n",+ "# 3. Create a new instance\n",+ "source_tracker = SourceTracker()\n","\n",- "print(\"Sources registered successfully.\")"+ "# 4. Now this will work\n",+ "source_tracker.register_source(\n",+ " source_id=source_id,\n",+ " source_type=metadata[\"type\"],\n",+ " credibility_score=metadata[\"credibility\"]\n",+ ")"]},{@@ -139,9 +159,45 @@},{"cell_type": "code",- "execution_count": null,+ "execution_count": 7,"metadata": {},- "outputs": [],+ "outputs": [+ {+ "data": {+ "text/html": [+ "<div style='font-family: monospace;'><h4>π§ Semantica - π Current Progress</h4><table style='width: 100%; border-collapse: collapse;'><tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr><tr><td>β </td><td>Semantica is resolving</td><td>β οΈ conflicts</td><td>ConflictDetector</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is resolving</td><td>β οΈ conflicts</td><td>ConflictAnalyzer</td><td>-</td><td>0.01s</td></tr><tr><td>β </td><td>Semantica is resolving</td><td>β οΈ conflicts</td><td>InvestigationGuideGenerator</td><td>-</td><td>0.00s</td></tr></table></div>"+ ],+ "text/plain": [+ "<IPython.core.display.HTML object>"+ ]+ },+ "metadata": {},+ "output_type": "display_data"+ },+ {+ "name": "stderr",+ "output_type": "stream",+ "text": [+ "Value conflict detected: emp_001.birth_date has conflicting values: ['1980-05-15', '1982-05-15']\n",+ "Value conflict detected: emp_001.department has conflicting values: ['Software Engineering', 'Engineering']\n"+ ]+ },+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Detected 2 conflicts:\n",+ "- value_conflict: birth_date for emp_001\n",+ " Values: ['1980-05-15', '1980-05-15', '1982-05-15']\n",+ " Severity: medium\n",+ "--- \n",+ "- value_conflict: department for emp_001\n",+ " Values: ['Engineering', 'Software Engineering', 'Engineering']\n",+ " Severity: medium\n",+ "--- \n"+ ]+ }+ ],"source": ["detector = ConflictDetector()\n","\n",@@ -175,9 +231,20 @@},{"cell_type": "code",- "execution_count": null,+ "execution_count": 9,"metadata": {},- "outputs": [],+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Conflict Analysis Summary:\n",+ "Total Conflicts: 2\n",+ "By Type: {'counts': {'value_conflict': 2}, 'details': {'value_conflict': [{'conflict_id': 'emp_001_birth_date_conflict', 'entity_id': 'emp_001', 'severity': 'medium'}, {'conflict_id': 'emp_001_department_conflict', 'entity_id': 'emp_001', 'severity': 'medium'}]}}\n",+ "By Severity: {'counts': {'medium': 2}, 'details': {'medium': [{'conflict_id': 'emp_001_birth_date_conflict', 'type': 'value_conflict', 'entity_id': 'emp_001', 'property_name': 'birth_date'}, {'conflict_id': 'emp_001_department_conflict', 'type': 'value_conflict', 'entity_id': 'emp_001', 'property_name': 'department'}]}}\n"+ ]+ }+ ],"source": ["analyzer = ConflictAnalyzer()\n","analysis = analyzer.analyze_conflicts(conflicts)\n",@@ -205,9 +272,21 @@},{"cell_type": "code",- "execution_count": null,+ "execution_count": 10,"metadata": {},- "outputs": [],+ "outputs": [+ {+ "ename": "AttributeError",+ "evalue": "'ConflictResolver' object has no attribute 'set_source_tracker'",+ "output_type": "error",+ "traceback": [+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",+ "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)",+ "Cell \u001b[1;32mIn[10], line 4\u001b[0m\n\u001b[0;32m 1\u001b[0m resolver \u001b[38;5;241m=\u001b[39m ConflictResolver()\n\u001b[0;32m 3\u001b[0m \u001b[38;5;66;03m# Need to link the source tracker to the resolver for credibility strategies\u001b[39;00m\n\u001b[1;32m----> 4\u001b[0m \u001b[43mresolver\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mset_source_tracker\u001b[49m(source_tracker)\n\u001b[0;32m 6\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m--- Resolution: Voting ---\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 7\u001b[0m voting_results \u001b[38;5;241m=\u001b[39m resolver\u001b[38;5;241m.\u001b[39mresolve_conflicts(conflicts, strategy\u001b[38;5;241m=\u001b[39mResolutionStrategy\u001b[38;5;241m.\u001b[39mVOTING)\n",+ "\u001b[1;31mAttributeError\u001b[0m: 'ConflictResolver' object has no attribute 'set_source_tracker'"+ ]+ }+ ],"source": ["resolver = ConflictResolver()\n","\n",@@ -241,9 +320,28 @@},{"cell_type": "code",- "execution_count": null,+ "execution_count": 11,"metadata": {},- "outputs": [],+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Investigation Guide for emp_001_birth_date_conflict:\n"+ ]+ },+ {+ "ename": "AttributeError",+ "evalue": "'InvestigationGuide' object has no attribute 'title'",+ "output_type": "error",+ "traceback": [+ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",+ "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)",+ "Cell \u001b[1;32mIn[11], line 7\u001b[0m\n\u001b[0;32m 4\u001b[0m guide \u001b[38;5;241m=\u001b[39m guide_generator\u001b[38;5;241m.\u001b[39mgenerate_guide(conflicts[\u001b[38;5;241m0\u001b[39m])\n\u001b[0;32m 6\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mInvestigation Guide for \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mguide\u001b[38;5;241m.\u001b[39mconflict_id\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m:\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m----> 7\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mTitle: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[43mguide\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mtitle\u001b[49m\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 8\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mSteps:\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 9\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m i, step \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28menumerate\u001b[39m(guide\u001b[38;5;241m.\u001b[39msteps, \u001b[38;5;241m1\u001b[39m):\n",+ "\u001b[1;31mAttributeError\u001b[0m: 'InvestigationGuide' object has no attribute 'title'"+ ]+ }+ ],"source": ["guide_generator = InvestigationGuideGenerator()\n","\n",@@ -293,7 +391,7 @@"name": "python","nbconvert_exporter": "python","pygments_lexer": "ipython3",- "version": "3.8.5"+ "version": "3.11.9"}},"nbformat": 4,diff --git a/pyproject.toml b/pyproject.tomlindex 14eff6e8..0aea5c77 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -42,6 +42,7 @@ dependencies = ["numpy>=1.21.0","pandas>=1.3.0","scikit-learn>=1.0.0",+ "umap-learn>=0.5.0","spacy>=3.4.0","transformers>=4.20.0","torch>=1.12.0",diff --git a/semantica/conflicts/source_tracker.py b/semantica/conflicts/source_tracker.pyindex bd4e33b0..3ef58b88 100644--- a/semantica/conflicts/source_tracker.py+++ b/semantica/conflicts/source_tracker.py@@ -128,6 +128,31 @@ class SourceTracker:# Source credibility scoresself.source_credibility: Dict[str, float] = {}+ # Source metadata+ self.source_metadata: Dict[str, Dict[str, Any]] = {}++ def register_source(+ self,+ source_id: str,+ source_type: str,+ credibility_score: float = 0.5,+ **metadata,+ ) -> bool:+ """+ Register a source with metadata and credibility score.++ Args:+ source_id: Source identifier+ source_type: Type of source (e.g., "report", "news", "official")+ credibility_score: Credibility score (0.0 to 1.0)+ **metadata: Additional metadata++ Returns:+ True if registered successfully+ """+ self.source_metadata[source_id] = {"type": source_type, **metadata}+ return self.set_source_credibility(source_id, credibility_score)+def track_entity_source(self, entity_id: str, source: SourceReference, **metadata) -> bool:diff --git a/semantica/visualization/kg_visualizer.py b/semantica/visualization/kg_visualizer.pyindex 231440f3..f3fa9eb1 100644--- a/semantica/visualization/kg_visualizer.py+++ b/semantica/visualization/kg_visualizer.py@@ -364,13 +364,13 @@ class KGVisualizer:title="Entity Type Distribution",)- if output == "interactive":- return fig- elif file_path:+ if file_path:export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")- return None++ # Always return the figure to allow interactive preview in notebooks+ return figdef visualize_relationship_matrix(self,@@ -442,13 +442,13 @@ class KGVisualizer:yaxis_title="Source Entity Type",)- if output == "interactive":- return fig- elif file_path:+ if file_path:export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")- return None++ # Always return the figure to allow interactive preview in notebooks+ return figdef _extract_nodes(self, entities: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Extract nodes from entities."""@@ -603,12 +603,46 @@ class KGVisualizer:# Prepare edge tracesedge_x = []edge_y = []++ # Prepare edge label traces and annotations (for arrows)+ edge_label_x = []+ edge_label_y = []+ edge_label_text = []+ annotations = []++ # Limit detailed edge rendering for performance if graph is too large+ show_detailed_edges = len(edges) < 500+for edge in edges:source_pos = pos.get(edge["source"])target_pos = pos.get(edge["target"])if source_pos and target_pos:- edge_x.extend([source_pos[0], target_pos[0], None])- edge_y.extend([source_pos[1], target_pos[1], None])+ x0, y0 = source_pos+ x1, y1 = target_pos+ edge_x.extend([x0, x1, None])+ edge_y.extend([y0, y1, None])++ if show_detailed_edges:+ # Calculate midpoint for label+ mx, my = (x0 + x1) / 2, (y0 + y1) / 2++ if edge.get("label"):+ edge_label_x.append(mx)+ edge_label_y.append(my)+ edge_label_text.append(edge["label"])++ # Add arrow annotation+ # Adjust arrow to point slightly before the node to avoid overlap with node marker+ # This is approximate; precise calculation requires node size+ annotations.append(+ dict(+ ax=x0, ay=y0, axref='x', ayref='y',+ x=x1, y=y1, xref='x', yref='y',+ arrowhead=2, arrowsize=1, arrowwidth=1,+ arrowcolor="#888", opacity=0.6,+ standoff=15 # Distance from target node+ )+ )edge_trace = go.Scatter(x=edge_x,@@ -616,43 +650,71 @@ class KGVisualizer:line=dict(width=self.edge_width, color="#888"),hoverinfo="none",mode="lines",+ showlegend=False,+ opacity=0.5)++ traces = [edge_trace]++ if show_detailed_edges and edge_label_text:+ edge_label_trace = go.Scatter(+ x=edge_label_x,+ y=edge_label_y,+ mode="text",+ text=edge_label_text,+ textposition="middle center",+ hoverinfo="none",+ textfont=dict(size=8, color="#555"),+ showlegend=False+ )+ traces.append(edge_label_trace)# Prepare node tracesnode_x = [pos[n["id"]][0] for n in nodes if n["id"] in pos]node_y = [pos[n["id"]][1] for n in nodes if n["id"] in pos]+ node_labels = [n["label"] for n in nodes if n["id"] in pos]node_trace = go.Scatter(x=node_x,y=node_y,mode="markers+text",hoverinfo="text",- text=node_text,+ text=node_labels, # Show labels directly on graph+ hovertext=node_text, # Rich hover texttextposition="top center",+ textfont=dict(size=10, color="#333"),marker=dict(size=node_sizes,color=node_colors,line=dict(width=2, color="white"),- opacity=0.9+ opacity=1.0),+ showlegend=False+ )+ traces.append(node_trace)++ layout_args = dict(+ title="Knowledge Graph Network",+ showlegend=False,+ hovermode="closest",+ margin=dict(b=20, l=5, r=5, t=40),+ xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),+ yaxis=dict(showgrid=False, zeroline=False, showticklabels=False),+ plot_bgcolor="white")++ if show_detailed_edges:+ layout_args["annotations"] = annotationsfig = go.Figure(- data=[edge_trace, node_trace],- layout=go.Layout(- title="Knowledge Graph Network",- showlegend=False,- hovermode="closest",- margin=dict(b=20, l=5, r=5, t=40),- xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),- yaxis=dict(showgrid=False, zeroline=False, showticklabels=False),- ),+ data=traces,+ layout=go.Layout(**layout_args),)- if output == "interactive":- return fig- elif file_path:+ if file_path:export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")- return None++ # Always return the figure to allow interactive preview in notebooks+ return figdiff --git a/semantica/visualization/semantic_network_visualizer.py b/semantica/visualization/semantic_network_visualizer.pyindex 7a6dcb89..1c07285f 100644--- a/semantica/visualization/semantic_network_visualizer.py+++ b/semantica/visualization/semantic_network_visualizer.py@@ -60,11 +60,11 @@ class SemanticNetworkVisualizer:self.logger = get_logger("semantic_network_visualizer")self.config = configself.progress_tracker = get_progress_tracker()- color_scheme_name = config.get("color_scheme", "default")+ color_scheme_name = config.get("color_scheme", "vibrant")try:self.color_scheme = ColorScheme[color_scheme_name.upper()]except (KeyError, AttributeError):- self.color_scheme = ColorScheme.DEFAULT+ self.color_scheme = ColorScheme.VIBRANTdef _check_dependencies(self):"""Check if dependencies are available."""@@ -254,6 +254,11 @@ class SemanticNetworkVisualizer:graph = {"entities": nodes, "relationships": edges}kg_viz = KGVisualizer(**self.config)++ # Default to Kamada-Kawai layout if not specified as it often produces better results for semantic networks+ if "algorithm" not in options:+ options["algorithm"] = "kamada_kawai"+result = kg_viz.visualize_network(graph, output, file_path, **options)self.progress_tracker.stop_tracking(@@ -312,13 +317,13 @@ class SemanticNetworkVisualizer:title="Semantic Network Node Type Distribution",)- if output == "interactive":- return fig- elif file_path:+ if file_path:export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")- return None++ # Always return the figure to allow interactive preview in notebooks+ return figdef visualize_edge_types(self,@@ -364,10 +369,10 @@ class SemanticNetworkVisualizer:title="Semantic Network Edge Type Distribution",)- if output == "interactive":- return fig- elif file_path:+ if file_path:export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")- return None++ # Always return the figure to allow interactive preview in notebooks+ return figdiff --git a/semantica/visualization/utils/layout_algorithms.py b/semantica/visualization/utils/layout_algorithms.pyindex 4802bd6b..d3e1989d 100644--- a/semantica/visualization/utils/layout_algorithms.py+++ b/semantica/visualization/utils/layout_algorithms.py@@ -92,10 +92,16 @@ class ForceDirectedLayout(LayoutAlgorithm):G.add_nodes_from(nodes)G.add_edges_from(edges)- # Use NetworkX spring layout- pos = nx.spring_layout(- G, k=self.k, iterations=self.iterations, **options- )+ # Use NetworkX layout+ algorithm = options.get("algorithm", "spring")++ if algorithm == "kamada_kawai":+ pos = nx.kamada_kawai_layout(G, **{k: v for k, v in options.items() if k in ["weight", "scale", "center", "dim"]})+ else:+ # Default to spring layout+ pos = nx.spring_layout(+ G, k=self.k, iterations=self.iterations, **{k: v for k, v in options.items() if k in ["weight", "scale", "center", "dim", "seed"]}+ )return {node: (float(pos[node][0]), float(pos[node][1])) for node in nodes