Spaces:
Running
Running
File size: 13,176 Bytes
c2ea5ed |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 |
import {
UniversalGraphData,
UniversalNode,
UniversalLink,
GraphDataAdapter,
GraphVisualizationConfig,
GraphVisualizationType,
} from "@/types/graph-visualization";
import { TemporalNode, TemporalLink, GraphFrame } from "@/types/temporal";
import { Entity, Relation } from "@/types";
import {
detectSchemaType,
getSchemaCapabilities,
} from "@/lib/schema-detection";
// Temporal Data Adapter
export class TemporalDataAdapter implements GraphDataAdapter<GraphFrame> {
adapt(data: GraphFrame): UniversalGraphData {
const nodes: UniversalNode[] = data.nodes.map((node: TemporalNode) => ({
id: node.id,
name: node.name || node.id,
label: node.name || node.id,
type: node.type || "entity",
raw_prompt: node.raw_prompt,
importance: (node as any).importance,
x: node.x,
y: node.y,
fx: node.fx,
fy: node.fy,
properties: { ...node },
}));
const links: UniversalLink[] = data.links.map((link: TemporalLink) => ({
id: link.id,
source: typeof link.source === "string" ? link.source : link.source.id,
target: typeof link.target === "string" ? link.target : link.target.id,
type: link.type || "relation",
label: link.type || "relation",
relationship: link.type,
interaction_prompt: link.interaction_prompt,
importance: (link as any).importance,
value: link.value || 1,
weight: link.value || 1,
properties: { ...link },
}));
return {
nodes,
links,
metadata: data.metadata,
};
}
validate(data: GraphFrame): boolean {
return (
data &&
Array.isArray(data.nodes) &&
Array.isArray(data.links) &&
data.nodes.every((node) => node.id) &&
data.links.every((link) => link.id && link.source && link.target)
);
}
getDefaultConfig(): Partial<GraphVisualizationConfig> {
return {
type: GraphVisualizationType.TEMPORAL_GRAPH,
nodeRadius: 8,
linkDistance: 100,
chargeStrength: -300,
showNodeLabels: true,
showLinkLabels: true,
showDirectionalArrows: true,
useCurvedLinks: true,
enableZoom: true,
enablePan: true,
enableDrag: true,
enableSelection: true,
layoutType: "force",
animationDuration: 500,
};
}
}
// Knowledge Graph Data Adapter
export class KnowledgeGraphDataAdapter
implements
GraphDataAdapter<{
entities: Entity[];
relations: Relation[];
metadata?: Record<string, any>;
}>
{
adapt(data: {
entities: Entity[];
relations: Relation[];
metadata?: Record<string, any>;
}): UniversalGraphData {
console.log("🔧 KnowledgeGraphDataAdapter.adapt() called with:", {
entities: data.entities?.length || 0,
relations: data.relations?.length || 0,
hasMetadata: !!data.metadata,
});
const nodes: UniversalNode[] = data.entities.map(
(entity: Entity, index) => {
// Debug logging to check entity data
console.log(`Entity ${index}:`, {
id: entity.id,
name: entity.name,
type: entity.type,
hasName: !!entity.name,
nameLength: entity.name?.length || 0,
});
// Ensure we have a proper label - fallback to ID if name is missing
const label = entity.name || entity.id || `Node ${index}`;
return {
id: entity.id,
name: entity.name,
label: label,
type: entity.type,
raw_prompt: (entity as any).raw_prompt,
raw_prompt_ref: (entity as any).raw_prompt_ref,
raw_text_ref: (entity as any).raw_text_ref,
importance: (entity as any).importance,
group: this.getTypeGroup(entity.type),
properties: entity.properties,
// Simple grid layout for initial positioning
x: 100 + (index % 6) * 120,
y: 100 + Math.floor(index / 6) * 100,
};
}
);
// Create set of valid node IDs for relation validation
const validNodeIds = new Set(nodes.map((node) => node.id));
// Filter relations to only include those with valid source and target nodes
const validRelations = data.relations.filter((relation: Relation) => {
const hasValidSource = validNodeIds.has(relation.source);
const hasValidTarget = validNodeIds.has(relation.target);
if (!hasValidSource || !hasValidTarget) {
console.warn(
`Skipping relation ${relation.id}: ` +
`source '${relation.source}' ${
hasValidSource ? "exists" : "missing"
}, ` +
`target '${relation.target}' ${
hasValidTarget ? "exists" : "missing"
}`
);
return false;
}
return true;
});
// Log filtering stats
const filteredCount = data.relations.length - validRelations.length;
if (filteredCount > 0) {
console.warn(
`Filtered out ${filteredCount} invalid relations out of ${data.relations.length} total`
);
}
const links: UniversalLink[] = validRelations.map((relation: Relation) => ({
id: relation.id,
source: relation.source,
target: relation.target,
type: relation.type,
label: relation.type,
relationship: relation.type,
interaction_prompt: relation.interaction_prompt,
interaction_prompt_ref: (relation as any).interaction_prompt_ref,
importance: (relation as any).importance,
value: 1,
weight: 1,
properties: relation.properties,
}));
// Detect schema type and add capabilities
const schemaType = detectSchemaType(data);
const schemaCapabilities = getSchemaCapabilities(schemaType);
return {
nodes,
links,
failures: (data as any).failures || [],
metadata: {
...data.metadata,
schema_type: schemaType,
schema_capabilities: schemaCapabilities,
},
};
}
validate(data: {
entities: Entity[];
relations: Relation[];
metadata?: Record<string, any>;
}): boolean {
return (
data &&
Array.isArray(data.entities) &&
Array.isArray(data.relations) &&
data.entities.every((entity) => entity.id && entity.name) &&
data.relations.every(
(relation) =>
relation.id && relation.source && relation.target && relation.type
)
);
}
getDefaultConfig(): Partial<GraphVisualizationConfig> {
return {
type: GraphVisualizationType.KNOWLEDGE_GRAPH,
nodeRadius: 15,
linkDistance: 100,
chargeStrength: -300,
showNodeLabels: true,
showLinkLabels: true,
showDirectionalArrows: false,
useCurvedLinks: false,
enableZoom: true,
enablePan: true,
enableDrag: true,
enableSelection: true,
layoutType: "force",
animationDuration: 500,
nodeColorScheme: [
"#ff6b6b",
"#4ecdc4",
"#45b7d1",
"#96ceb4",
"#feca57",
"#ff9ff3",
],
};
}
private getTypeGroup(type: string): number {
const typeGroups: Record<string, number> = {
Person: 1,
Organization: 2,
Location: 3,
Event: 4,
Concept: 5,
Product: 6,
};
return typeGroups[type] || 0;
}
}
// Reference-Based Data Adapter (extends KnowledgeGraphDataAdapter)
export class ReferenceBasedDataAdapter extends KnowledgeGraphDataAdapter {
adapt(data: {
entities: Entity[];
relations: Relation[];
failures?: Array<any>;
metadata?: Record<string, any>;
}): UniversalGraphData {
console.log(
"🎯 ReferenceBasedDataAdapter.adapt() called - will delegate to parent"
);
// Use parent adapter for basic conversion
const result = super.adapt(data);
// Enhance with reference-based specific features
result.failures = data.failures || [];
// Ensure schema type is set to reference_based
if (result.metadata) {
result.metadata.schema_type = "reference_based";
result.metadata.schema_capabilities =
getSchemaCapabilities("reference_based");
}
return result;
}
validate(data: any): boolean {
// Use parent validation plus check for reference-based features
const basicValid = super.validate(data);
if (!basicValid) return false;
// Additional validation for reference-based features
const hasReferenceFeatures = detectSchemaType(data) === "reference_based";
return hasReferenceFeatures;
}
}
// Simple Graph Data Adapter (for backward compatibility)
export class SimpleGraphDataAdapter
implements
GraphDataAdapter<{
nodes: Array<{
id: string;
name: string;
type: string;
[key: string]: any;
}>;
links: Array<{
source: string;
target: string;
type: string;
[key: string]: any;
}>;
}>
{
adapt(data: {
nodes: Array<{
id: string;
name: string;
type: string;
[key: string]: any;
}>;
links: Array<{
source: string;
target: string;
type: string;
[key: string]: any;
}>;
}): UniversalGraphData {
const nodes: UniversalNode[] = data.nodes.map((node, index) => ({
id: node.id,
name: node.name,
label: node.name,
type: node.type,
importance: node.importance,
properties: { ...node },
// Simple grid layout
x: 100 + (index % 4) * 120,
y: 100 + Math.floor(index / 4) * 100,
}));
const links: UniversalLink[] = data.links.map((link, index) => ({
id: `link-${index}`,
source: link.source,
target: link.target,
type: link.type,
label: link.type,
relationship: link.type,
importance: link.importance,
value: 1,
weight: 1,
properties: { ...link },
}));
return {
nodes,
links,
metadata: {
entity_count: nodes.length,
relation_count: links.length,
},
};
}
validate(data: {
nodes: Array<{
id: string;
name: string;
type: string;
[key: string]: any;
}>;
links: Array<{
source: string;
target: string;
type: string;
[key: string]: any;
}>;
}): boolean {
return (
data &&
Array.isArray(data.nodes) &&
Array.isArray(data.links) &&
data.nodes.every((node) => node.id && node.name && node.type) &&
data.links.every((link) => link.source && link.target && link.type)
);
}
getDefaultConfig(): Partial<GraphVisualizationConfig> {
return {
type: GraphVisualizationType.SIMPLE_GRAPH,
nodeRadius: 20,
linkDistance: 80,
chargeStrength: -200,
showNodeLabels: true,
showLinkLabels: true,
showDirectionalArrows: false,
useCurvedLinks: false,
enableZoom: false,
enablePan: false,
enableDrag: false,
enableSelection: false,
layoutType: "grid",
animationDuration: 0,
};
}
}
// Factory function to get appropriate adapter
export function getGraphDataAdapter(
type?: GraphVisualizationType,
data?: any
): GraphDataAdapter {
console.log("🏭 getGraphDataAdapter called with:", { type, hasData: !!data });
// Auto-detect schema if data provided but no type specified
if (!type && data) {
try {
const schemaType = detectSchemaType(data);
console.log(
"🔍 Auto-detecting adapter type based on schema:",
schemaType
);
if (schemaType === "reference_based") {
type = GraphVisualizationType.KNOWLEDGE_GRAPH;
} else {
type = GraphVisualizationType.SIMPLE_GRAPH;
}
} catch (error) {
console.warn(
"Schema detection failed in adapter factory, using default KNOWLEDGE_GRAPH:",
error
);
type = GraphVisualizationType.KNOWLEDGE_GRAPH;
}
}
// Default to KNOWLEDGE_GRAPH if no type provided
if (!type) {
type = GraphVisualizationType.KNOWLEDGE_GRAPH;
}
switch (type) {
case GraphVisualizationType.TEMPORAL_GRAPH:
return new TemporalDataAdapter();
case GraphVisualizationType.KNOWLEDGE_GRAPH:
// Use ReferenceBasedDataAdapter for reference-based data, otherwise KnowledgeGraphDataAdapter
if (data) {
try {
if (detectSchemaType(data) === "reference_based") {
console.log(
"✅ Using ReferenceBasedDataAdapter for reference-based schema"
);
return new ReferenceBasedDataAdapter();
}
} catch (error) {
console.warn(
"Schema detection failed during adapter selection, using KnowledgeGraphDataAdapter:",
error
);
}
}
console.log(
"✅ Using KnowledgeGraphDataAdapter for direct-based or unknown schema"
);
return new KnowledgeGraphDataAdapter();
case GraphVisualizationType.SIMPLE_GRAPH:
console.log("✅ Using SimpleGraphDataAdapter");
return new SimpleGraphDataAdapter();
default:
console.log("✅ Using KnowledgeGraphDataAdapter (default fallback)");
return new KnowledgeGraphDataAdapter(); // Default fallback
}
}
|