-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgradio.app.py
More file actions
804 lines (699 loc) · 30.5 KB
/
gradio.app.py
File metadata and controls
804 lines (699 loc) · 30.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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
"""
Gradio Interface for Triple-SOS supporting deployment on online platforms.
The current supports gradio >= 5.0.
"""
import datetime
from functools import partial
from itertools import chain
from tokenize import TokenError
from typing import Tuple, List, Dict
import re
import warnings
filter_warnings = [
(DeprecationWarning,
"The 'show_api' parameter in event listeners will be removed in Gradio 6.0.*"),
(DeprecationWarning,
"The 'css' parameter in the Blocks constructor will be removed in Gradio 6.0.*")
]
for warning_type, pattern in filter_warnings:
warnings.filterwarnings(
"ignore",
category=warning_type,
message=pattern
)
from sympy import Poly, Symbol
from sympy import __version__ as SYMPY_VERSION
from sympy.external.importtools import version_tuple
import gradio as gr
from triples.utils.text_process import short_constant_parser
from triples import sum_of_squares
from triples.gui.sos_manager import SOSManager
from triples.gui.linebreak import recursive_latex_auto_linebreak
GRADIO_VERSION = tuple(version_tuple(gr.__version__))
# https://github.com/gradio-app/gradio/pull/8822
GRADIO_LATEX_SUPPORTS_ALIGNED = (GRADIO_VERSION[0] == 4 and GRADIO_VERSION[1] in (39, 40, 41, 43, 44))\
or GRADIO_VERSION[0] > 4
LOCK_MARK = chr(128274)
def has_kwarg(func, name) -> bool:
# inspect the function signature to check if the keyword argument exists
# return name in func.__code__.co_varnames
import inspect
return name in inspect.signature(func).parameters
def gradio_markdown(**kwargs) -> gr.Markdown:
version = GRADIO_VERSION
if version >= (4, 0):
return gr.Markdown(latex_delimiters=[{"left": "$", "right": "$", "display": False}], **kwargs)
return gr.Markdown(**kwargs)
def show_api(show: bool) -> Dict:
if has_kwarg(gr.Button.click, "api_visibility"):
# gradio 6.0
if show:
return {"api_visibility": "public"}
return {"api_visibility": "private"}
# gradio < 6.0
return {"show_api": bool(show)}
def _convert_to_gradio_latex(content):
version = GRADIO_VERSION
replacement = {
'\n': ' \n\n ',
'$$': '$',
# '\\left\\{': '',
# '\\right.': '',
}
if not GRADIO_LATEX_SUPPORTS_ALIGNED:
replacement.update({
'&': ' ',
'\\\\': ' $ \n\n $',
'\\begin{aligned}': '',
'\\end{aligned}': '',
})
if version >= (4, 0):
replacement['\\frac'] = '\\dfrac'
# else:
# replacement['\\begin{aligned}'] = ''
# replacement['\\end{aligned}'] = ''
for k,v in replacement.items():
content = content.replace(k, v)
if version >= (4, 0):
content = re.sub(r'\$(.*?)\$', r'$\ \1$', content, flags=re.DOTALL)
else:
content = re.sub(r'\$(.*?)\$', r'$\displaystyle \1$', content, flags=re.DOTALL)
return content
def flatten_nested_dicts(dicts: List[dict]) -> Dict[tuple, list]:
"""
>>> flatten_nested_dicts([{'a': 1, 'b': {'c': 2, 'd': 3}},
... {'a': 5, 'b': {'d': -1, 'c': 4}}]) # doctest:+SKIP
{('a',): [1, 5], ('b', 'c'): [2, 4], ('b', 'd'): [3, -1]}
"""
result = {}
def traverse(nested_dict: dict, current_path: tuple = ()):
for key, value in nested_dict.items():
new_path = current_path + (key,)
if isinstance(value, dict):
traverse(value, new_path)
else:
if new_path not in result:
result[new_path] = []
result[new_path].append(value)
for d in dicts:
traverse(d)
return result
class GradioInterface():
# Custom CSS for vertical layout styling
css = """
#coefficient_triangle{height: 600px;margin-top:-5px}
#heatmap{
background-color: var(--block-background-fill);
}
.dark .has-scrollbar{
color-scheme: dark;
}
.dark .has-scrollbar::-webkit-scrollbar-thumb {
background-color: var(--neutral-600) !important;
}
.vertical-layout-center {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.vertical-layout-container {
max-width: 800px;
width: 100%;
}
.constraint-row {
margin-bottom: 8px;
}
.constraint-type {
margin: 0 8px;
align-self: center;
}
"""
description = f"""
<hr>
<div>
GitHub Link: <a href="https://github.com/ForeverHaibara/Triple-SOS"
>https://github.com/ForeverHaibara/Triple-SOS</a>
<br><br>
Deployment Date: {datetime.datetime.now().strftime("%Y-%m-%d")}
Gradio Version: {gr.__version__} SymPy Version: {SYMPY_VERSION}
<hr>
<h2>Tutorial</h2>
Inputs are parsed by a special function with convenient syntax for cyclic
sums and cyclic products.
<br><br>
<div style="margin-left: 20px;">
<ol>
<li>Power symbols can be "**", "^", or omitted, e.g., "a2b3"
stands for "a^2*b^3".</li>
<li>Multiplication symbols can be omitted, e.g., "1/2ab" stands for "1/2*a*b".</li>
<li>"s" stands for cyclic sums and "p" for cyclic products. E.g., "s(a)" stands
for "a+b+c" and "p(a)" stands for "a*b*c".
<br><b>NOTE</b>: "s" and "p" are functions. DO NOT use "s" and "p" as symbols.</li>
<li>Configure the the generators and the permutation groups of the cyclic
sums and cyclic products on the right.</li>
<li>Do not use comparison symbols such as ">", "<", "=", "≥", or "≤".</li>
<li>Brackets should be "(" or ")", and other brackets are not allowed.</li>
</ol>
</div>
<br>
<b>More instructions:</b>
<br><br>
<div style="margin-left: 20px;">
<ol>
<li>When there are 3 generators and the input is homogeneous with respect to the
generators, the coefficients and the heatmap are displayed.<br>
If not, "sum-of-squares" still works but there is no visualization.</li>
<li>Set constraints on the right. The right-hand-side should always be zero. E.g.,
"a+b+c<=1" should be written as "1-a-b-c" with type ">=0".</li>
</ol>
</div>
</div>
"""
def __init__(self):
self.layout = {
"horizontal": {},
"vertical": {},
}
use_css = {"css": self.css} if has_kwarg(gr.Blocks.__init__, "css") else {}
with gr.Blocks(**use_css) as self.demo:
# State variables
self.vertical_mode = gr.State(value=False)
# Toggle button for layout mode
with gr.Row():
self.toggle_layout_btn = gr.Button(
"Toggle Vertical Layout",
variant="secondary",
size="sm"
)
gr.Markdown("", visible=False) # Spacer to push toggle button to left
# Main container that will change layout based on vertical_mode state
with gr.Row(equal_height=False, visible=True) as self.horizontal_container:
with gr.Column(scale=5):
self.input_box = gr.Textbox(label="Input", placeholder="Input a polynomial like s(a^2)^2-3s(a^3b)", show_label=False, max_lines=1)
self.coefficient_triangle = gr.HTML('<div id="coeffs" style="width: 100%; height: 600px; position: absolute;"></div>',
elem_id="coefficient_triangle", elem_classes="has-scrollbar")
self._init_shared_outputs("horizontal")
with gr.Column(scale=1) as self.right_column:
# an image display block (note: gr.Image makes low resolution images, use gr.HTML for better quality)
self.image = gr.Image(show_label = False, height=280, width=280, elem_id="heatmap")
# self.image = gr.HTML('<div id="heatmap" style="width=300; height=300; position:absolute;"></div>', elem_id="heatmap")
self.compute_btn = gr.Button("Compute", scale=1, variant="primary")
self._init_shared_components("horizontal")
# Vertical layout container (initially hidden)
with gr.Column("vertical-layout-center", visible=False) as self.vertical_container:
with gr.Column("vertical-layout-container"):
# Input box in vertical layout
self.input_box_vertical = gr.Textbox(
label="Input",
placeholder="Input a polynomial like s(a^2)^2-3s(a^3b)",
show_label=False,
max_lines=20
)
# Right column content in vertical layout
with gr.Column():
self.compute_btn_vertical = gr.Button("Compute", variant="primary")
self._init_shared_components("vertical")
self._init_shared_outputs("vertical")
# add a link to the github repo
self.description_component = gr.HTML(self.description)
# Organize components by layout for better code reuse and maintainability
self.layout['horizontal'].update({
'input': self.input_box,
'compute_btn': self.compute_btn,
})
self.layout['vertical'].update({
'input': self.input_box_vertical,
'compute_btn': self.compute_btn_vertical,
})
Component = gr.components.Component
flatten = flatten_nested_dicts(
[self.layout['horizontal'], self.layout['vertical']]
)
flatten_values = list(chain.from_iterable(flatten.values()))
flatten_values = [_ for _ in flatten_values if isinstance(_, Component)]
# Toggle layout function
self.toggle_layout_btn.click(
fn=self.toggle_layout,
inputs=[self.vertical_mode] + flatten_values,
outputs=[
self.vertical_mode,
self.horizontal_container,
self.vertical_container
] + flatten_values,
**show_api(0)
)
# Setup event handlers for both layouts
self._setup_event_handlers()
self._setup_api()
def _init_shared_components(self, layout: str):
# Generators section
collection = self.layout[layout]
collection['generators_input'] = gr.Textbox(
label="Generators",
placeholder="Enter lowercase letters (a-z), no duplicates",
value="abc",
max_lines=1
)
# Permutation section
collection['perm_group'] = {}
collection['perm_group']['radio'] = gr.Radio(
['Cyc', 'Sym', 'Custom'],
label="Permutation",
value="Cyc"
)
collection['perm_group']['input'] = gr.Textbox(
label="Permutation Group",
value="[[1,2,0]]",
max_lines=1,
interactive=False
)
# Constraints section
collection['constraints'] = {}
with gr.Column():
extra_kwargs = {}
if has_kwarg(gr.Dataframe.__init__, "pinned_columns"):
extra_kwargs["pinned_columns"] = 3
if has_kwarg(gr.Dataframe.__init__, "static_columns"):
extra_kwargs["static_columns"] = [2]
if has_kwarg(gr.Dataframe.__init__, "column_count"): # >= 6.0
extra_kwargs["column_count"] = (3, "fixed")
else:
extra_kwargs["col_count"] = (3, "fixed")
collection['constraints']['df'] = gr.Dataframe(
value = [["a", "", "≥0"], ["b", "", "≥0"], ["c", "", "≥0"]],
headers = ['Constraint', 'Alias', 'Type'],
datatype = "str",
type = "array",
label = "Constraints",
**extra_kwargs
)
with gr.Row():
kwargs = {"size": "sm"}
collection['constraints']['add_inequality'] = gr.Button("+ Inequality", **kwargs)
collection['constraints']['add_equality'] = gr.Button("+ Equality", **kwargs)
collection['constraints']['positive_toggle'] = gr.Button(
f"Positive {LOCK_MARK}", variant="primary", **kwargs
)
collection['constraints']['clear'] = gr.Button("Clear", **kwargs)
collection['methods_btn'] = gr.CheckboxGroup(
['Structural', 'Linear', 'Symmetric', 'SDP'],
value = ['Structural', 'Linear', 'Symmetric', 'SDP'],
label = "Methods"
)
def _init_shared_outputs(self, layout: str):
collection = self.layout[layout]
with gr.Tabs():
collection['outputs'] = {}
kwarg = {"buttons": ["copy"]} if has_kwarg(gr.TextArea.__init__, "buttons") \
else {"show_copy_button": True}
with gr.Tab("Display"):
collection['outputs']['display'] = gradio_markdown(elem_classes="has-scrollbar")
with gr.Tab("LaTeX"):
collection['outputs']['latex'] = gr.TextArea(label="Result", **kwarg)
with gr.Tab("txt"):
collection['outputs']['txt'] = gr.TextArea(label="Result", **kwarg)
with gr.Tab("formatted"):
collection['outputs']['formatted'] = gr.TextArea(label="Result", **kwarg)
# with gr.Tab("expanded"):
# collection['outputs']['expanded'] = gr.TextArea(label="Result", **kwarg)
def _setup_event_handlers(self):
"""Setup event handlers for all new components"""
# Permutation radio toggle event - horizontal layout
for layout_type in self.layout:
layout = self.layout[layout_type]
input_box = layout["input"]
gen_input = layout["generators_input"]
input_box.submit(fn = self.set_poly,
inputs = [input_box, gen_input, layout["perm_group"]["input"]],
outputs = [self.image, self.coefficient_triangle],
**show_api(0)
)
compute_btn = layout["compute_btn"]
compute_btn.click(fn = partial(self.solve, layout_type=layout_type),
inputs = [input_box, gen_input, layout["perm_group"]["input"],
layout["constraints"]["df"], layout["methods_btn"]],
outputs = list(layout['outputs'].values()) + \
[self.image, self.coefficient_triangle], **show_api(0))
perm_group = layout["perm_group"]
perm_group["radio"].change(
fn=self._toggle_perm_group_input,
inputs=[perm_group["radio"], gen_input],
outputs=[perm_group["input"]],
**show_api(0)
)
positive_toggle = layout["constraints"]["positive_toggle"]
for event in (gen_input.blur, gen_input.submit):
# gen_input.change will update too frequently, so we use blur/submit instead
event(
fn=self._configure_generators,
inputs=[gen_input, perm_group["radio"], positive_toggle],
outputs=[gen_input, perm_group["input"], layout["constraints"]["df"]],
**show_api(0)
)
tmp = layout["constraints"]
positive_toggle = tmp["positive_toggle"]
def add_constraint_clicked(df: list, prefix="ineq"):
df = df[:]
tp = "≥0" if prefix == "ineq" else "=0"
df.append(["", "", tp])
return [df, gr.update(value="Positive", variant="secondary")]
for prefix in ('ineq', 'eq'):
add_btn = tmp[f"add_{prefix}uality"]
add_btn.click(
fn=partial(add_constraint_clicked, prefix=prefix),
inputs=tmp["df"],
outputs=[tmp["df"], positive_toggle],
**show_api(0)
)
clear_btn = tmp["clear"]
clear_btn.click(
fn=lambda: [[], gr.update(value="Positive", variant="secondary")],
inputs=[],
outputs=[tmp["df"], positive_toggle],
**show_api(0)
)
positive_toggle.click(
fn=self._toggle_positive,
inputs=[positive_toggle, tmp["df"], layout["generators_input"]],
outputs=[positive_toggle, tmp["df"]],
**show_api(0)
)
def _setup_api(self):
with gr.Row(render=False, equal_height=False):
# Add hidden components for API
self.api_input_expr = gr.Textbox(visible=False, min_width=0, label="Problem")
self.api_input_ineq = gr.Textbox(visible=False, min_width=0, label="Ineqs",
info="Nonnegative expressions separated by ';', e.g., a;b;c for a>=0, b>=0, c>=0.")
self.api_input_eq = gr.Textbox(visible=False, min_width=0, label="Eqs",
info="Zero expressions separated by ';', e.g., a*b*c-1;x^2+y^2-1 for a*b*c-1=0,x^2+y^2-1=0.")
self.api_output = gr.JSON(visible=False, min_width=0, height=0)
# API endpoint
self.api_input_expr.change(
fn=self.api_sum_of_squares,
inputs=[self.api_input_expr, self.api_input_ineq, self.api_input_eq],
outputs=[self.api_output],
api_name="sum_of_squares"
)
def _render_heatmap(self, grid):
if grid is None:
return None
from PIL import Image
from numpy import vstack, hstack, full, uint8
image = grid.save_heatmap(backgroundcolor=255, alpha=True)
image = vstack([full((8, image.shape[1], 4), 0, uint8), image])
side_white = full((image.shape[0], 4, 4), 0, uint8)
image = hstack([side_white, image, side_white])
image = Image.fromarray(image).resize((300,300), Image.LANCZOS)
return image
def _render_coefficient_triangle(self, degree: int, expr: Poly) -> str:
"""
Render the coefficient triangle HTML for the given polynomial.
Args:
degree (int): The degree of the polynomial.
expr (Expr): The polynomial expression.
Returns:
str: The HTML string for the coefficient triangle.
"""
if expr is None or not isinstance(expr, Poly):
return None
html = '<div id="coeffs" style="width: 100%; height: 600px; position: absolute;">'
n = degree
coeffs = expr.coeffs()
monoms = expr.monoms()
monoms.append((-1,-1,0)) # tail flag
l = 100. / (1 + n)
ulx = (50 - l * n / 2)
uly = (29 - 13 * n * l / 45)
fontsize = max(11, int(28-1.5*n))
lengthscale = .28 * fontsize / 20.
t = 0
txts = []
title_parser = lambda chr, deg: '' if chr=='' or deg <= 0 else (chr if deg == 1 else chr + str(deg))
A = expr.gens[0].name if len(expr.gens) > 0 else ''
B = expr.gens[1].name if len(expr.gens) > 1 else ''
C = expr.gens[2].name if len(expr.gens) > 2 else ''
for i in range(n+1):
for j in range(i+1):
if monoms[t][0] == n - i and monoms[t][1] == i - j:
txt = short_constant_parser(coeffs[t])
t += 1
else:
txt = '0'
x = (ulx + l*(2*i-j)/2 - len(txt) * lengthscale - 2*int(len(txt)/4))
y = (uly + l*j*13/15)
title = title_parser(A, n-i) + title_parser(B, i-j) + title_parser(C, j)
txt = '<p style="position: absolute; left: %f%%; top: %f%%; font-size: %dpx; color: %s;" title="%s">%s</p>'%(
x, y, fontsize, 'var(--body-text-color)' if txt != '0' else 'rgb(180,180,180)', title, txt
)
txts.append(txt)
html = html + '\n'.join(txts) + '</div>'
return html
def _toggle_perm_group_input(self, radio_value: str, gen_input: str):
"""Toggle permutation input box editable state based on radio selection"""
updates = {"interactive": radio_value == "Custom"}
n = len(gen_input)
if radio_value == "Cyc" or radio_value == "Sym":
value = [list(range(1, n)) + [0]] if n > 0 else [[]]
if radio_value == "Sym" and n > 2:
value.append([1, 0] + list(range(2, n)))
updates["value"] = value
return gr.update(**updates)
def _configure_generators(self, input_text, perm_group_radio, positive_toggle):
"""Configure generators input"""
# only lowercase a-z, no duplicates
filtered = re.sub(r'[^a-z]', '', input_text)
# Remove duplicates
unique_chars = []
for char in filtered:
if char not in unique_chars:
unique_chars.append(char)
chars = ''.join(unique_chars)
if perm_group_radio == "Cyc" or perm_group_radio == "Sym":
n = len(chars)
perm_group_output = [list(range(1, n)) + [0]] if n > 0 else [[]]
if perm_group_radio == "Sym" and n > 2:
perm_group_output.append([1, 0] + list(range(2, n)))
perm_group_output = gr.update(value=perm_group_output)
else:
perm_group_output = gr.update()
if LOCK_MARK in positive_toggle:
constraints = gr.update(value=[[gen, "", "≥0"] for gen in chars])
else:
constraints = gr.update()
return chars, perm_group_output, constraints
def _toggle_positive(self, button_value, constraints, gens):
"""Handle positive toggle button functionality"""
# Toggle button state
lock = LOCK_MARK
locked = False
if not (lock in button_value):
locked = True
btn = gr.update(
value=f"Positive {lock}" if locked else "Positive",
variant="primary" if locked else "secondary",
)
if locked:
constraints = [[gen, "", "≥0"] for gen in gens]
return btn, constraints
def set_poly(self,
input_text: str,
gens: str,
perm_group: str,
):
if isinstance(gens, str):
gens = tuple([Symbol(g) for g in gens])
if len(gens) != 3:
# do not visualize
return {self.image: None, self.coefficient_triangle: None}
try:
perm_group = SOSManager.parse_perm_group(perm_group)
parser = SOSManager.make_parser(gens, perm_group)
expr = parser(input_text, return_type="expr",
parse_expr_kwargs = {"evaluate": False})
if expr is None:
return {self.image: None, self.coefficient_triangle: None}
except (ValueError, TypeError, SyntaxError, TokenError) as e:
raise gr.Error(f"{e.__class__.__name__}: {e}")
frac = parser(expr, return_type="frac")
if frac[0] is None:
return {self.image: None, self.coefficient_triangle: None}
degree, triangle, heatmap = SOSManager.render_coeff_triangle_and_heatmap(
expr, frac, return_grid=True
)
return {
self.image: self._render_heatmap(heatmap),
self.coefficient_triangle: \
self._render_coefficient_triangle(degree, frac[0])
}
def solve(self,
input_text,
gens,
perm_group,
constraints,
methods,
layout_type = None
):
"""Common solving logic for both horizontal and vertical layouts.
Args:
input_text: Input polynomial string
gens: List of generators
perm_group: Permutation group
constraints: List of constraints
methods: List of methods to use for solving
layout_type: Layout type ('horizontal' or 'vertical') if specific layout output is needed
Returns:
Dictionary with results for the specified layout, or tuple for compatibility with original functions
"""
# Get polynomial and grid from set_poly
if isinstance(gens, str):
gens = tuple([Symbol(g) for g in gens])
try:
perm_group = SOSManager.parse_perm_group(perm_group)
parser = SOSManager.make_parser(gens, perm_group)
expr = parser(input_text, return_type="expr",
parse_expr_kwargs = {"evaluate": False})
except (ValueError, TypeError, SyntaxError, TokenError) as e:
raise gr.Error(f"{e.__class__.__name__}: {e}")
solution = None
render = self.set_poly(input_text, gens, perm_group)
if expr is not None:
ineq_constraints = {}
eq_constraints = {}
for constraint in constraints:
if len(constraint) != 3:
continue
if constraint[2] == "≥0":
ineq_constraints[constraint[0]] = constraint[1]
elif constraint[2] == "=0":
eq_constraints[constraint[0]] = constraint[1]
else:
raise gr.Error('Constraint type must be "≥0" or "=0"')
try:
ineq_constraints = SOSManager.parse_constraints_dict(ineq_constraints, parser)
eq_constraints = SOSManager.parse_constraints_dict(eq_constraints, parser)
except (ValueError, TypeError, SyntaxError, TokenError) as e:
raise gr.Error(f"{e.__class__.__name__}: {e}")
if expr is not None:
try:
# Attempt to find sum of squares
solution = SOSManager.sum_of_squares(
expr,
ineq_constraints,
eq_constraints,
methods=['%sSOS' % method for method in methods] + ['Pivoting', 'Reparametrization'],
)
except Exception as e:
pass
if solution is not None:
solution = solution.rewrite_symmetry(gens, perm_group)
# Prepare LaTeX output
lhs_expr = Symbol('\\text{LHS}')
tex = solution.to_string(mode='latex', lhs_expr=lhs_expr,
together=True, cancel=True, settings={'long_frac_ratio': 2})
if GRADIO_LATEX_SUPPORTS_ALIGNED:
tex = recursive_latex_auto_linebreak(tex)
tex = '$$%s$$' % tex
gradio_latex = _convert_to_gradio_latex(tex)
# Format solution strings
solution_txt = solution.to_string(mode='txt', lhs_expr=lhs_expr)
solution_formatted = solution.to_string(mode='formatted', lhs_expr=lhs_expr)
return (
gradio_latex, tex, solution_txt, solution_formatted,
render[self.image], render[self.coefficient_triangle],
)
else:
# No solution found
no_solution = "No solution found"
return (
no_solution, no_solution, no_solution, no_solution,
render[self.image], render[self.coefficient_triangle],
)
def toggle_layout(self, vertical_mode: bool, *args, **kwargs):
"""Toggle between horizontal and vertical layout"""
# Toggle the mode
new_mode = not vertical_mode
# Sync values between layouts
updates = [None] * len(args)
for i in range(0, len(args), 2):
if new_mode:
updates[i] = gr.update()
updates[i+1] = args[i]
else:
updates[i] = args[i+1]
updates[i+1] = gr.update()
# Return update objects for each output component in the order expected by the outputs list
return [
new_mode, # Update vertical_mode state
gr.update(visible=not new_mode), # Update horizontal container visibility
gr.update(visible=new_mode), # Update vertical container visibility
] + updates
def api_sum_of_squares(self, expr, ineq_constraints, eq_constraints):
# from sympy.parsing.sympy_parser import parse_expr
# from sympy.parsing.sympy_parser import T
from sympy import sympify
# parser = lambda x: parse_expr(x, transformations=T[:7])
def parser(x):
x = sympify(x)
if any(len(s.name) > 1 for s in x.free_symbols):
# prevent a*b miswritten as ab
raise ValueError("Variable names should be single characters.")
return x
parser_t = lambda x: tuple(map(parser, (x.split(':', 1) if ':' in x else (x, x))))
try:
# Parse string inputs to SymPy expressions
parsed_expr = parser(expr)
parsed_ineqs = dict(parser_t(c) for c in (ineq_constraints or '').split(';') if c)
parsed_eqs = dict(parser_t(c) for c in (eq_constraints or '').split(';') if c)
# Call the core function
result = sum_of_squares(
parsed_expr,
parsed_ineqs,
parsed_eqs
)
tex = None
tex_aligned = None
if result is not None:
lhs_expr = Symbol('\\text{LHS}')
tex = result.to_string(mode='latex', lhs_expr=lhs_expr, settings={'long_frac_ratio': 2})
tex_aligned = recursive_latex_auto_linebreak(tex)
return {
'success': bool(result is not None),
'solution': result.solution.doit() if result is not None else None,
'latex': tex,
'latex_aligned': tex_aligned,
'error': None
}
except Exception as e:
return {
'success': False,
'solution': None,
'latex': None,
'latex_aligned': None,
'error': str(e)
}
if __name__ == '__main__':
SOSManager.verbose = False
SOSManager.time_limit = 300.0
interface = GradioInterface()
ALLOW_CORS = True
if ALLOW_CORS:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = interface.demo.app
app.add_middleware(
CORSMiddleware,
allow_origins=[
"https://foreverhaibara.github.io",
# "http://localhost:5173", # Vite
# "http://127.0.0.1:5173" # local
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"]
)
use_css = {"css": interface.css} if has_kwarg(interface.demo.launch, "css") else {}
interface.demo.launch(show_error=True,
**use_css
) #, debug=True)