Spaces:
Sleeping
Sleeping
Update modules/knowledge_graph.py
Browse files- modules/knowledge_graph.py +54 -0
modules/knowledge_graph.py
CHANGED
|
@@ -290,6 +290,60 @@ class KnowledgeGraph:
|
|
| 290 |
return related_concepts
|
| 291 |
|
| 292 |
def search_with_depth(self, query: str, max_depth: int = 3, limit: int = 5) -> List[Tuple[str, float]]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
"""
|
| 294 |
Enhanced search with depth control and path weights
|
| 295 |
|
|
|
|
| 290 |
return related_concepts
|
| 291 |
|
| 292 |
def search_with_depth(self, query: str, max_depth: int = 3, limit: int = 5) -> List[Tuple[str, float]]:
|
| 293 |
+
"""Enhanced search with depth control and path weights"""
|
| 294 |
+
temp_query_node = f"_query_{query}"
|
| 295 |
+
|
| 296 |
+
try:
|
| 297 |
+
# First add the query node and its relationships
|
| 298 |
+
query_relationships = self.expand_concept(query)
|
| 299 |
+
if not query_relationships:
|
| 300 |
+
print(f"No relationships found for query: {query}")
|
| 301 |
+
return []
|
| 302 |
+
|
| 303 |
+
# Ensure query node is added before adding relationships
|
| 304 |
+
self.graph.add_node(temp_query_node, node_type='query')
|
| 305 |
+
self.add_weighted_relationships(temp_query_node, query_relationships)
|
| 306 |
+
|
| 307 |
+
# Rest of the search logic...
|
| 308 |
+
image_scores = {}
|
| 309 |
+
image_nodes = [n for n, attr in self.graph.nodes(data=True)
|
| 310 |
+
if attr.get('node_type') == 'image']
|
| 311 |
+
|
| 312 |
+
for image_id in image_nodes:
|
| 313 |
+
try:
|
| 314 |
+
paths = nx.all_simple_paths(
|
| 315 |
+
self.graph,
|
| 316 |
+
source=temp_query_node,
|
| 317 |
+
target=image_id,
|
| 318 |
+
cutoff=max_depth
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
path_scores = []
|
| 322 |
+
for path in paths:
|
| 323 |
+
score = self._calculate_path_score(path)
|
| 324 |
+
path_scores.append(score)
|
| 325 |
+
|
| 326 |
+
if path_scores:
|
| 327 |
+
image_scores[image_id] = max(path_scores)
|
| 328 |
+
|
| 329 |
+
except nx.NetworkXNoPath:
|
| 330 |
+
continue
|
| 331 |
+
|
| 332 |
+
# Sort and return results
|
| 333 |
+
sorted_results = sorted(
|
| 334 |
+
image_scores.items(),
|
| 335 |
+
key=lambda x: x[1],
|
| 336 |
+
reverse=True
|
| 337 |
+
)
|
| 338 |
+
return sorted_results[:limit]
|
| 339 |
+
|
| 340 |
+
finally:
|
| 341 |
+
# Clean up: remove temporary query node
|
| 342 |
+
if self.graph.has_node(temp_query_node):
|
| 343 |
+
self.graph.remove_node(temp_query_node)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def search_with_depth1(self, query: str, max_depth: int = 3, limit: int = 5) -> List[Tuple[str, float]]:
|
| 347 |
"""
|
| 348 |
Enhanced search with depth control and path weights
|
| 349 |
|