-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDetailerMaskParser.cs
More file actions
522 lines (444 loc) · 15.5 KB
/
Copy pathDetailerMaskParser.cs
File metadata and controls
522 lines (444 loc) · 15.5 KB
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
namespace Spoomples.Extensions.WildcardImporter;
using System.Globalization;
using System.Text.RegularExpressions;
public class DetailerMaskParser
{
private readonly string _input;
private int _position;
public DetailerMaskParser(string input)
{
_input = input;
_position = 0;
}
public MaskSpecifier ParseExpression(char? expected = null)
{
var left = ParseInvertExpression();
SkipWhitespace();
while (!IsAtEnd())
{
var op = ConsumeChar();
switch (op)
{
case '+':
left = ParsePostfixExpression(left);
break;
case '|':
left = new UnionMask(left, ParseInvertExpression());
break;
case '&':
left = new IntersectMask(left, ParseInvertExpression());
break;
default:
if (expected == op)
return left;
throw new InvalidOperationException($"Unexpected character '{op}' at position {_position} in input '{_input}'.");
}
SkipWhitespace();
}
if (expected != null)
throw new InvalidOperationException($"Expected character '{expected}' at position {_position} in input '{_input}'.");
return left;
}
// Precedence level 2: ! (invert)
private MaskSpecifier ParseInvertExpression()
{
SkipWhitespace();
if (!IsAtEnd() && PeekChar() == '!')
{
ConsumeChar();
SkipWhitespace();
var mask = ParseInvertExpression();
if (mask is InvertMask)
return ((InvertMask)mask).Mask;
return new InvertMask(mask);
}
return ParseIndexExpression();
}
// Precedence level 1.5: [N] (index operator - postfix)
private MaskSpecifier ParseIndexExpression()
{
var expr = ParsePrimaryExpression();
// Handle postfix index operator
while (!IsAtEnd() && PeekChar() == '[')
{
ConsumeChar(); // consume '['
SkipWhitespace();
if (!TryParseInteger(out int index))
throw new InvalidOperationException($"Expected integer index at position {_position}");
SkipWhitespace();
if (IsAtEnd() || PeekChar() != ']')
throw new InvalidOperationException($"Expected ']' after index at position {_position}");
ConsumeChar(); // consume ']'
expr = new IndexedMask(expr, index);
SkipWhitespace();
}
return expr;
}
// Handle postfix + operator (grow)
private MaskSpecifier ParsePostfixExpression(MaskSpecifier expr)
{
SkipWhitespace();
if (!TryParseInteger(out int pixels))
throw new InvalidOperationException($"Expected integer after '+' at position {_position}");
expr = new GrowMask(expr, pixels);
SkipWhitespace();
return expr;
}
// Precedence level 1: Parentheses and primary expressions
private MaskSpecifier ParsePrimaryExpression()
{
SkipWhitespace();
if (IsAtEnd())
throw new InvalidOperationException("Unexpected end of input");
char ch = PeekChar();
// Parentheses
if (ch == '(')
{
ConsumeChar(); // consume '('
SkipWhitespace();
// Check if this might be a box() function
if (_position > 1 && _input.Substring(Math.Max(0, _position - 4), Math.Min(4, _position)).EndsWith("box("))
{
// This is actually a box function, backtrack
_position--;
return ParseFunction();
}
var expr = ParseExpression(')');
SkipWhitespace();
return expr;
}
// Functions (box, bbox)
if (char.IsLetter(ch))
{
return ParseFunction();
}
throw new InvalidOperationException($"Unexpected character '{ch}' at position {_position}");
}
private MaskSpecifier ParseFunction()
{
var functionName = ParseIdentifier();
if (functionName == "box")
{
return ParseFunctionCall(functionName);
}
else if (functionName.StartsWith("yolo-"))
{
// For YOLO masks, we need to capture the class filter part
var modelName = functionName.Substring(5); // Remove "yolo-" prefix
var classFilter = "";
// Check for optional (classes) part
if (!IsAtEnd() && PeekChar() == '(')
{
ConsumeChar(); // consume '('
var classContent = new StringBuilder();
while (!IsAtEnd() && PeekChar() != ')')
{
classContent.Append(ConsumeChar());
}
if (!IsAtEnd() && PeekChar() == ')')
{
ConsumeChar(); // consume ')'
classFilter = classContent.ToString();
}
else
{
throw new InvalidOperationException($"Expected ')' after class list at position {_position}");
}
}
var baseMask = new YoloMask(modelName, classFilter);
return ParseThresholdSuffix(baseMask);
}
else if (functionName == "circle")
{
return ParseFunctionCall(functionName);
}
else if (functionName == "oval")
{
return ParseFunctionCall(functionName);
}
else if (functionName == "hull")
{
return ParseFunctionCall(functionName);
}
else
{
// Treat as CLIPSEG mask
return ParseClipSegMask(functionName);
}
}
// Helper types and methods for clean argument parsing
private struct Maybe<T>
{
public readonly bool HasValue;
public readonly T Value;
private Maybe(bool hasValue, T value)
{
HasValue = hasValue;
Value = value;
}
public static Maybe<T> Some(T value) => new(true, value);
public static Maybe<T> None() => new(false, default(T));
public TResult Fold<TResult>(Func<T, TResult> onSome, Func<TResult> onNone)
{
return HasValue ? onSome(Value) : onNone();
}
}
private Maybe<T1> TryParseArgs<T1>(Func<T1> tryParse1)
{
var savedPosition = _position;
try
{
var arg1 = tryParse1();
SkipWhitespace();
if (!IsAtEnd() && PeekChar() == ')')
{
ConsumeChar(); // consume ')'
return Maybe<T1>.Some(arg1);
}
}
catch
{
// Parsing failed
}
_position = savedPosition;
return Maybe<T1>.None();
}
private Maybe<(T1, T2, T3)> TryParseArgs<T1, T2, T3>(
Func<T1> tryParse1,
Func<T2> tryParse2,
Func<T3> tryParse3)
{
var savedPosition = _position;
try
{
var arg1 = tryParse1();
SkipWhitespace();
if (!IsAtEnd() && PeekChar() == ',')
{
ConsumeChar(); // consume ','
SkipWhitespace();
var arg2 = tryParse2();
SkipWhitespace();
if (!IsAtEnd() && PeekChar() == ',')
{
ConsumeChar(); // consume ','
SkipWhitespace();
var arg3 = tryParse3();
SkipWhitespace();
if (!IsAtEnd() && PeekChar() == ')')
{
ConsumeChar(); // consume ')'
return Maybe<(T1, T2, T3)>.Some((arg1, arg2, arg3));
}
}
}
}
catch
{
// Parsing failed
}
_position = savedPosition;
return Maybe<(T1, T2, T3)>.None();
}
private Maybe<(T1, T2, T3, T4)> TryParseArgs<T1, T2, T3, T4>(
Func<T1> tryParse1,
Func<T2> tryParse2,
Func<T3> tryParse3,
Func<T4> tryParse4)
{
var savedPosition = _position;
try
{
var arg1 = tryParse1();
SkipWhitespace();
if (!IsAtEnd() && PeekChar() == ',')
{
ConsumeChar(); // consume ','
SkipWhitespace();
var arg2 = tryParse2();
SkipWhitespace();
if (!IsAtEnd() && PeekChar() == ',')
{
ConsumeChar(); // consume ','
SkipWhitespace();
var arg3 = tryParse3();
SkipWhitespace();
if (!IsAtEnd() && PeekChar() == ',')
{
ConsumeChar(); // consume ','
SkipWhitespace();
var arg4 = tryParse4();
SkipWhitespace();
if (!IsAtEnd() && PeekChar() == ')')
{
ConsumeChar(); // consume ')'
return Maybe<(T1, T2, T3, T4)>.Some((arg1, arg2, arg3, arg4));
}
}
}
}
}
catch
{
// Parsing failed
}
_position = savedPosition;
return Maybe<(T1, T2, T3, T4)>.None();
}
private double ParseDoubleArg()
{
if (!TryParseDouble(out double value))
throw new InvalidOperationException($"Expected numeric value at position {_position}");
return value;
}
private MaskSpecifier ParseFunctionCall(string functionName)
{
SkipWhitespace();
if (IsAtEnd() || PeekChar() != '(')
throw new InvalidOperationException($"Expected '(' after '{functionName}' at position {_position}");
ConsumeChar(); // consume '('
SkipWhitespace();
// Try to parse as specific function arguments first
if (functionName == "box")
{
// Try to parse box(x,y,width,height) format
return TryParseArgs(ParseDoubleArg, ParseDoubleArg, ParseDoubleArg, ParseDoubleArg)
.Fold<MaskSpecifier>(
args => new BoxMask(args.Item1, args.Item2, args.Item3, args.Item4),
() => new BoundingBoxMask(ParseExpression(')'))
);
}
else if (functionName == "circle")
{
// Try to parse circle(x,y,radius) format
return TryParseArgs(ParseDoubleArg, ParseDoubleArg, ParseDoubleArg)
.Fold<MaskSpecifier>(
args => new CircleMask(args.Item1, args.Item2, args.Item3),
() => new BoundingCircleMask(ParseExpression(')'))
);
}
else if (functionName == "oval")
{
// Try to parse oval(x,y,width,height) format
return TryParseArgs(ParseDoubleArg, ParseDoubleArg, ParseDoubleArg, ParseDoubleArg)
.Fold<MaskSpecifier>(
args => new OvalMask(args.Item1, args.Item2, args.Item3, args.Item4),
() => new BoundingOvalMask(ParseExpression(')'))
);
}
else if (functionName == "hull")
{
return new HullMask(ParseExpression(')'));
}
// For other functions that don't have coordinate overloads, only support mask expression
throw new InvalidOperationException($"Unknown function '{functionName}' at position {_position}");
}
private MaskSpecifier ParseClipSegMask(string text)
{
// Continue reading until we hit an operator or end
var sb = new StringBuilder(text);
while (!IsAtEnd())
{
SkipWhitespace();
if (IsAtEnd())
break;
char ch = PeekChar();
if (ch == ':' || ch == '|' || ch == '&' || ch == '+' || ch == ')' || ch == '[')
break;
if (char.IsLetter(ch))
{
sb.Append(' ');
sb.Append(ParseIdentifier());
}
else
{
break;
}
}
var baseMask = new ClipSegMask(sb.ToString().Trim());
return ParseThresholdSuffix(baseMask);
}
private MaskSpecifier ParseThresholdSuffix(MaskSpecifier baseMask)
{
SkipWhitespace();
if (!IsAtEnd() && PeekChar() == ':')
{
ConsumeChar(); // consume ':'
SkipWhitespace();
if (!TryParseDouble(out double threshold))
throw new InvalidOperationException($"Expected threshold value after ':' at position {_position}");
if (baseMask is YoloMask yoloMask)
{
baseMask = yoloMask with { Threshold = threshold };
}
if (baseMask is ClipSegMask clipSegMask)
{
baseMask = clipSegMask with { Threshold = threshold };
}
SkipWhitespace();
if (!IsAtEnd() && PeekChar() == ':')
{
ConsumeChar(); // consume second ':'
SkipWhitespace();
if (!TryParseDouble(out double maxVal))
throw new InvalidOperationException($"Expected threshold max value after second ':' at position {_position}");
baseMask = new ThresholdMask(baseMask, maxVal);
}
}
return baseMask;
}
private string ParseIdentifier()
{
var sb = new StringBuilder();
while (!IsAtEnd() && (char.IsLetterOrDigit(PeekChar()) || PeekChar() == '-' || PeekChar() == '_' || PeekChar() == '.'))
{
sb.Append(ConsumeChar());
}
return sb.ToString();
}
private bool TryParseInteger(out int value)
{
var sb = new StringBuilder();
while (!IsAtEnd() && char.IsDigit(PeekChar()))
{
sb.Append(ConsumeChar());
}
return int.TryParse(sb.ToString(), out value);
}
private bool TryParseDouble(out double value)
{
var sb = new StringBuilder();
while (!IsAtEnd())
{
char ch = PeekChar();
if (char.IsDigit(ch) || ch == '.')
{
sb.Append(ConsumeChar());
}
else
{
break;
}
}
return double.TryParse(sb.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out value);
}
private void SkipWhitespace()
{
while (!IsAtEnd() && char.IsWhiteSpace(PeekChar()))
{
_position++;
}
}
private char PeekChar()
{
return IsAtEnd() ? '\0' : _input[_position];
}
private char ConsumeChar()
{
return IsAtEnd() ? '\0' : _input[_position++];
}
private bool IsAtEnd()
{
return _position >= _input.Length;
}
}