Line data Source code
1 : import { resolveSubgraphInputTarget } from '@/core/graph/subgraph/resolveSubgraphInputTarget'
2 : import type { LGraph } from '@/lib/litegraph/src/LGraph'
3 : import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
4 : import {
5 : collectAllNodes,
6 : getExecutionIdByNode,
7 : isExecutionPathActive
8 : } from '@/utils/graphTraversalUtil'
9 : import { filterOutputNodes } from '@/utils/nodeFilterUtil'
10 :
11 : import { MEDIA_KIND_BY_SINK_TYPE } from './tourRolePins'
12 : import type { TourMediaKind } from './tourRolePins'
13 :
14 : /** Roles read off a graph nobody pinned. Host-mapping stays the caller's job. */
15 : interface HeuristicRoles {
16 : source: LGraphNode | null
17 : prompt: LGraphNode | null
18 : sink: LGraphNode | null
19 : mediaKind: TourMediaKind
20 : }
21 :
22 2355 : const MEDIA_KIND_BY_SLOT_TYPE: Partial<Record<string, TourMediaKind>> = {
23 : IMAGE: 'image',
24 : VIDEO: 'video'
25 : }
26 :
27 : /** `neg` alone is the abbreviation; anything longer must be `negative*`, or
28 : * `negate`, `negligible` and Spanish `negro` disqualify a real prompt. */
29 2355 : const DISQUALIFYING = ['negative', 'neg', 'system', 'undesired', 'avoid']
30 :
31 : /** `anti` names the negative box only next to the noun — `Anti-prompt`,
32 : * `AntiPrompt`, `ANTIPROMPT` — since `anti_aliasing` and `antique` are ordinary
33 : * words a real prompt carries. Read off the normalised label, not its words, so
34 : * the pair survives the separator and camelCase spellings alike. */
35 2355 : const ANTI_PROMPT = /\banti ?prompts?\b/
36 :
37 0 : function disqualified(word: string): boolean {
38 0 : return DISQUALIFYING.includes(word) || word.startsWith('negative')
39 : }
40 :
41 0 : function readsAsAntiPrompt(label: string | undefined): boolean {
42 0 : return ANTI_PROMPT.test(labelWords(label).join(' '))
43 : }
44 :
45 : /** Real templates ship nodes with no title and widgets with no name. */
46 0 : function labelWords(label: string | undefined): string[] {
47 0 : return (label ?? '')
48 : .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
49 : .toLowerCase()
50 : .replace(/[^a-z0-9]+/g, ' ')
51 : .split(' ')
52 : .filter(Boolean)
53 : }
54 :
55 0 : function slotType(slot: { type?: unknown }): string {
56 0 : return String(slot.type ?? '').toUpperCase()
57 : }
58 :
59 : /** Multiline is what separates a prompt box from a seed or a filename. */
60 0 : function promptWidgets(node: LGraphNode) {
61 0 : return (node.widgets ?? []).filter(
62 : (widget) => widget.type === 'customtext' || widget.options.multiline
63 : )
64 : }
65 :
66 0 : function consumerInputNames(nodes: LGraphNode[]): Map<LGraphNode, string[]> {
67 0 : const names = new Map<LGraphNode, string[]>()
68 :
69 0 : for (const consumer of nodes) {
70 0 : if (consumer.isVirtualNode) continue
71 : const inputs = consumer.inputs
72 0 : inputs.forEach((input, slot) => {
73 0 : const producer = consumer.getInputNode(slot)
74 0 : if (producer)
75 0 : names.set(producer, [...(names.get(producer) ?? []), input.name])
76 : })
77 : }
78 :
79 0 : return names
80 : }
81 :
82 : /** A text node inside a subgraph is titled nothing useful; its port is not. */
83 0 : function exposedInputNames(nodes: LGraphNode[]): Map<LGraphNode, string[]> {
84 0 : const names = new Map<LGraphNode, string[]>()
85 :
86 0 : for (const host of nodes) {
87 0 : if (!host.isSubgraphNode()) continue
88 :
89 0 : for (const input of host.inputs) {
90 0 : const target = resolveSubgraphInputTarget(host, input.name)
91 0 : const inner = target && host.subgraph.getNodeById(target.nodeId)
92 0 : if (inner) names.set(inner, [...(names.get(inner) ?? []), input.name])
93 : }
94 : }
95 :
96 0 : return names
97 : }
98 :
99 : /**
100 : * Ranks a text node on its title, its widget's name, any subgraph port wired to
101 : * it, and the input name it feeds one hop on, normalised for case and
102 : * separators. Anything reading as a negative prompt disqualifies.
103 : */
104 0 : function promptScore(labels: string[], fedInputNames: string[]): number {
105 0 : const words = labels.flatMap(labelWords)
106 0 : const fed = fedInputNames.flatMap(labelWords)
107 :
108 0 : if ([...words, ...fed].some(disqualified)) return -1
109 0 : if ([...labels, ...fedInputNames].some(readsAsAntiPrompt)) return -1
110 0 : if (fed.includes('positive')) return 3
111 0 : if (words.includes('positive')) return 2
112 0 : if (words.includes('prompt')) return 1
113 0 : return 0
114 : }
115 :
116 : /**
117 : * Each node scores on its best prompt widget, so one carrying both a positive
118 : * and a negative box is not disqualified by widget order. A tie at the top
119 : * resolves to nothing; a lone text box wins by being alone. Virtual nodes are
120 : * skipped: a note never runs, and a subgraph host's promoted widgets mirror an
121 : * interior node that host-maps back to it, tying a prompt against itself.
122 : */
123 0 : function findPrompt(nodes: LGraphNode[]): LGraphNode | null {
124 0 : const consumers = consumerInputNames(nodes)
125 0 : const exposed = exposedInputNames(nodes)
126 :
127 0 : const ranked = nodes
128 : .flatMap((node) => {
129 0 : if (node.isVirtualNode) return []
130 0 : const widgets = promptWidgets(node)
131 0 : if (!widgets.length) return []
132 0 : const fed = consumers.get(node) ?? []
133 0 : const shared = [node.title, ...(exposed.get(node) ?? [])]
134 0 : const scores = widgets.map((w) => promptScore([...shared, w.name], fed))
135 0 : return [{ node, score: Math.max(...scores) }]
136 : })
137 : .sort((a, b) => b.score - a.score)
138 :
139 0 : const best = ranked.at(0)
140 0 : const runnerUp = ranked.at(1)
141 0 : if (!best || best.score < 0) return null
142 0 : return !runnerUp || best.score > runnerUp.score ? best.node : null
143 : }
144 :
145 : /** Produces an image and consumes nothing. Two of them is a coin flip. */
146 0 : function findSource(nodes: LGraphNode[]): LGraphNode | null {
147 0 : const sources = nodes.filter(
148 : (node) =>
149 : !node.isVirtualNode &&
150 : !node.inputs.some((input) => input.link != null) &&
151 : node.outputs.some((output) => slotType(output) === 'IMAGE')
152 : )
153 :
154 0 : return sources.length === 1 ? sources[0] : null
155 : }
156 :
157 : /** Any output node fed media can show the result; disagreeing kinds cannot. */
158 0 : function findSink(
159 : nodes: LGraphNode[]
160 : ): { node: LGraphNode; mediaKind: TourMediaKind } | null {
161 0 : const sinks = filterOutputNodes(nodes).flatMap((node) => {
162 0 : for (const input of node.inputs) {
163 0 : const slotKind = MEDIA_KIND_BY_SLOT_TYPE[slotType(input)]
164 0 : if (input.link == null || !slotKind) continue
165 : const mediaKind = MEDIA_KIND_BY_SINK_TYPE[node.type] ?? slotKind
166 0 : return [{ node, slotKind, mediaKind }]
167 : }
168 0 : return []
169 : })
170 :
171 0 : const first = sinks.at(0)
172 0 : if (!first) return null
173 : // Sinks must agree on the data they are fed; a video combine and a still
174 : // preview of the same frames do not disagree, they rank — the video is the
175 : // result and the preview is scaffolding.
176 0 : if (!sinks.every(({ slotKind }) => slotKind === first.slotKind)) return null
177 0 : return sinks.find(({ mediaKind }) => mediaKind === 'video') ?? first
178 : }
179 :
180 : /** Roles for a shared workflow or an unpinned template. No sink, no tour. */
181 0 : export function heuristicRoles(graph: LGraph): HeuristicRoles | null {
182 0 : const active = collectAllNodes(graph).filter((node) => {
183 0 : const executionId = getExecutionIdByNode(graph, node)
184 0 : return executionId ? isExecutionPathActive(graph, executionId) : false
185 : })
186 :
187 0 : const sink = findSink(active)
188 0 : if (!sink) return null
189 :
190 0 : return {
191 : source: findSource(active),
192 : prompt: findPrompt(active),
193 : sink: sink.node,
194 : mediaKind: sink.mediaKind
195 : }
196 : }
|