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
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
"""
MOUSE Workflow - Visual Workflow Builder with UI Execution
@Powered by VIDraft
โœ“ Visual workflow designer with drag-and-drop
โœ“ Import/Export JSON with copy-paste support
โœ“ Auto-generate UI from workflow for end-user execution
"""

import os, json, typing, tempfile, traceback
import gradio as gr
from gradio_workflowbuilder import WorkflowBuilder

# Optional imports for LLM APIs
try:
    from openai import OpenAI
    OPENAI_AVAILABLE = True
except ImportError:
    OPENAI_AVAILABLE = False
    print("OpenAI library not available. Install with: pip install openai")

# Anthropic ๊ด€๋ จ ์ฝ”๋“œ ์ฃผ์„ ์ฒ˜๋ฆฌ
# try:
#     import anthropic
#     ANTHROPIC_AVAILABLE = True
# except ImportError:
#     ANTHROPIC_AVAILABLE = False
#     print("Anthropic library not available. Install with: pip install anthropic")
ANTHROPIC_AVAILABLE = False

try:
    import requests
    REQUESTS_AVAILABLE = True
except ImportError:
    REQUESTS_AVAILABLE = False
    print("Requests library not available. Install with: pip install requests")

try:
    from huggingface_hub import HfApi, create_repo, upload_file
    HF_HUB_AVAILABLE = True
except ImportError:
    HF_HUB_AVAILABLE = False
    print("Huggingface Hub not available. Install with: pip install huggingface-hub")

# -------------------------------------------------------------------
# ๐Ÿ› ๏ธ  ํ—ฌํผ ํ•จ์ˆ˜๋“ค
# -------------------------------------------------------------------
def export_pretty(data: typing.Dict[str, typing.Any]) -> str:
    return json.dumps(data, indent=2, ensure_ascii=False) if data else "No workflow to export"

def export_file(data: typing.Dict[str, typing.Any]) -> typing.Optional[str]:
    """์›Œํฌํ”Œ๋กœ์šฐ๋ฅผ JSON ํŒŒ์ผ๋กœ ๋‚ด๋ณด๋‚ด๊ธฐ"""
    if not data:
        return None
    
    try:
        # ์ž„์‹œ ํŒŒ์ผ ์ƒ์„ฑ
        fd, path = tempfile.mkstemp(suffix=".json", prefix="workflow_", text=True)
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        return path
    except Exception as e:
        print(f"Error exporting file: {e}")
        return None

def load_json_from_text_or_file(json_text: str, file_obj) -> typing.Tuple[typing.Dict[str, typing.Any], str]:
    """ํ…์ŠคํŠธ ๋˜๋Š” ํŒŒ์ผ์—์„œ JSON ๋กœ๋“œ"""
    # ํŒŒ์ผ์ด ์žˆ์œผ๋ฉด ํŒŒ์ผ ์šฐ์„ 
    if file_obj is not None:
        try:
            with open(file_obj.name, "r", encoding="utf-8") as f:
                json_text = f.read()
        except Exception as e:
            return None, f"โŒ Error reading file: {str(e)}"
    
    # JSON ํ…์ŠคํŠธ๊ฐ€ ์—†๊ฑฐ๋‚˜ ๋น„์–ด์žˆ์œผ๋ฉด
    if not json_text or json_text.strip() == "":
        return None, "No JSON data provided"
    
    try:
        # JSON ํŒŒ์‹ฑ
        data = json.loads(json_text.strip())
        
        # ๋ฐ์ดํ„ฐ ๊ฒ€์ฆ
        if not isinstance(data, dict):
            return None, "Invalid format: not a dictionary"
        
        # ํ•„์ˆ˜ ํ•„๋“œ ํ™•์ธ
        if 'nodes' not in data:
            data['nodes'] = []
        if 'edges' not in data:
            data['edges'] = []
            
        nodes_count = len(data.get('nodes', []))
        edges_count = len(data.get('edges', []))
        
        return data, f"โœ… Loaded: {nodes_count} nodes, {edges_count} edges"
        
    except json.JSONDecodeError as e:
        return None, f"โŒ JSON parsing error: {str(e)}"
    except Exception as e:
        return None, f"โŒ Error: {str(e)}"

def create_sample_workflow(example_type="basic"):
    """์ƒ˜ํ”Œ ์›Œํฌํ”Œ๋กœ์šฐ ์ƒ์„ฑ"""
    
    if example_type == "basic":
        # ๊ธฐ๋ณธ ์˜ˆ์ œ: ๊ฐ„๋‹จํ•œ Q&A
        return {
            "nodes": [
                {
                    "id": "input_1",
                    "type": "ChatInput",
                    "position": {"x": 100, "y": 200},
                    "data": {
                        "label": "User Question",
                        "template": {
                            "input_value": {"value": "What is the capital of Korea?"}
                        }
                    }
                },
                {
                    "id": "llm_1",
                    "type": "llmNode",
                    "position": {"x": 400, "y": 200},
                    "data": {
                        "label": "AI Processing",
                        "template": {
                            "provider": {"value": "OpenAI"},
                            "model": {"value": "gpt-4.1-mini"},
                            "temperature": {"value": 0.7},
                            "system_prompt": {"value": "You are a helpful assistant."}
                        }
                    }
                },
                {
                    "id": "output_1",
                    "type": "ChatOutput",
                    "position": {"x": 700, "y": 200},
                    "data": {"label": "Answer"}
                }
            ],
            "edges": [
                {"id": "e1", "source": "input_1", "target": "llm_1"},
                {"id": "e2", "source": "llm_1", "target": "output_1"}
            ]
        }
    
    elif example_type == "vidraft":
        # VIDraft ์˜ˆ์ œ
        return {
            "nodes": [
                {
                    "id": "input_1",
                    "type": "ChatInput",
                    "position": {"x": 100, "y": 200},
                    "data": {
                        "label": "User Input",
                        "template": {
                            "input_value": {"value": "AI์™€ ๋จธ์‹ ๋Ÿฌ๋‹์˜ ์ฐจ์ด์ ์„ ์„ค๋ช…ํ•ด์ฃผ์„ธ์š”."}
                        }
                    }
                },
                {
                    "id": "llm_1",
                    "type": "llmNode",
                    "position": {"x": 400, "y": 200},
                    "data": {
                        "label": "VIDraft AI (Gemma)",
                        "template": {
                            "provider": {"value": "VIDraft"},
                            "model": {"value": "Gemma-3-r1984-27B"},
                            "temperature": {"value": 0.8},
                            "system_prompt": {"value": "๋‹น์‹ ์€ ์ „๋ฌธ์ ์ด๊ณ  ์นœ์ ˆํ•œ AI ๊ต์œก์ž์ž…๋‹ˆ๋‹ค. ๋ณต์žกํ•œ ๊ฐœ๋…์„ ์‰ฝ๊ฒŒ ์„ค๋ช…ํ•ด์ฃผ์„ธ์š”."}
                        }
                    }
                },
                {
                    "id": "output_1",
                    "type": "ChatOutput",
                    "position": {"x": 700, "y": 200},
                    "data": {"label": "AI Explanation"}
                }
            ],
            "edges": [
                {"id": "e1", "source": "input_1", "target": "llm_1"},
                {"id": "e2", "source": "llm_1", "target": "output_1"}
            ]
        }
    
    elif example_type == "multi_input":
        # ๋‹ค์ค‘ ์ž…๋ ฅ ์˜ˆ์ œ
        return {
            "nodes": [
                {
                    "id": "name_input",
                    "type": "textInput",
                    "position": {"x": 100, "y": 100},
                    "data": {
                        "label": "Your Name",
                        "template": {
                            "input_value": {"value": "John"}
                        }
                    }
                },
                {
                    "id": "topic_input",
                    "type": "textInput",
                    "position": {"x": 100, "y": 250},
                    "data": {
                        "label": "Topic",
                        "template": {
                            "input_value": {"value": "Python programming"}
                        }
                    }
                },
                {
                    "id": "level_input",
                    "type": "textInput",
                    "position": {"x": 100, "y": 400},
                    "data": {
                        "label": "Skill Level",
                        "template": {
                            "input_value": {"value": "beginner"}
                        }
                    }
                },
                {
                    "id": "combiner",
                    "type": "textNode",
                    "position": {"x": 350, "y": 250},
                    "data": {
                        "label": "Combine Inputs",
                        "template": {
                            "text": {"value": "Create a personalized learning plan"}
                        }
                    }
                },
                {
                    "id": "llm_1",
                    "type": "llmNode",
                    "position": {"x": 600, "y": 250},
                    "data": {
                        "label": "Generate Learning Plan",
                        "template": {
                            "provider": {"value": "OpenAI"},
                            "model": {"value": "gpt-4.1-mini"},
                            "temperature": {"value": 0.7},
                            "system_prompt": {"value": "You are an expert educational consultant. Create personalized learning plans based on the user's name, topic of interest, and skill level."}
                        }
                    }
                },
                {
                    "id": "output_1",
                    "type": "ChatOutput",
                    "position": {"x": 900, "y": 250},
                    "data": {"label": "Your Learning Plan"}
                }
            ],
            "edges": [
                {"id": "e1", "source": "name_input", "target": "combiner"},
                {"id": "e2", "source": "topic_input", "target": "combiner"},
                {"id": "e3", "source": "level_input", "target": "combiner"},
                {"id": "e4", "source": "combiner", "target": "llm_1"},
                {"id": "e5", "source": "llm_1", "target": "output_1"}
            ]
        }
    
    elif example_type == "chain":
        # ์ฒด์ธ ์ฒ˜๋ฆฌ ์˜ˆ์ œ
        return {
            "nodes": [
                {
                    "id": "input_1",
                    "type": "ChatInput",
                    "position": {"x": 50, "y": 200},
                    "data": {
                        "label": "Original Text",
                        "template": {
                            "input_value": {"value": "The quick brown fox jumps over the lazy dog."}
                        }
                    }
                },
                {
                    "id": "translator",
                    "type": "llmNode",
                    "position": {"x": 300, "y": 200},
                    "data": {
                        "label": "Translate to Korean",
                        "template": {
                            "provider": {"value": "VIDraft"},
                            "model": {"value": "Gemma-3-r1984-27B"},
                            "temperature": {"value": 0.3},
                            "system_prompt": {"value": "You are a professional translator. Translate the given English text to Korean accurately."}
                        }
                    }
                },
                {
                    "id": "analyzer",
                    "type": "llmNode",
                    "position": {"x": 600, "y": 200},
                    "data": {
                        "label": "Analyze Translation",
                        "template": {
                            "provider": {"value": "OpenAI"},
                            "model": {"value": "gpt-4.1-mini"},
                            "temperature": {"value": 0.5},
                            "system_prompt": {"value": "You are a linguistic expert. Analyze the Korean translation and explain its nuances and cultural context."}
                        }
                    }
                },
                {
                    "id": "output_translation",
                    "type": "ChatOutput",
                    "position": {"x": 450, "y": 350},
                    "data": {"label": "Korean Translation"}
                },
                {
                    "id": "output_analysis",
                    "type": "ChatOutput",
                    "position": {"x": 900, "y": 200},
                    "data": {"label": "Translation Analysis"}
                }
            ],
            "edges": [
                {"id": "e1", "source": "input_1", "target": "translator"},
                {"id": "e2", "source": "translator", "target": "analyzer"},
                {"id": "e3", "source": "translator", "target": "output_translation"},
                {"id": "e4", "source": "analyzer", "target": "output_analysis"}
            ]
        }
    
    # ๊ธฐ๋ณธ๊ฐ’์€ basic
    return create_sample_workflow("basic")

# ๋ฐฐํฌ๋ฅผ ์œ„ํ•œ ๋…๋ฆฝ ์•ฑ ์ƒ์„ฑ ํ•จ์ˆ˜
def generate_standalone_app(workflow_data: dict, app_name: str, app_description: str) -> str:
    """์›Œํฌํ”Œ๋กœ์šฐ๋ฅผ ๋…๋ฆฝ์ ์ธ Gradio ์•ฑ์œผ๋กœ ๋ณ€ํ™˜"""
    
    # JSON ๋ฐ์ดํ„ฐ๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜
    workflow_json = json.dumps(workflow_data, indent=2)
    
    app_code = f'''"""
{app_name}
{app_description}
Generated by MOUSE Workflow
"""

import os
import json
import gradio as gr
import requests

# Workflow configuration
WORKFLOW_DATA = {workflow_json}

def execute_workflow(*input_values):
    """Execute the workflow with given inputs"""
    
    # API keys from environment
    vidraft_token = os.getenv("FRIENDLI_TOKEN")
    openai_key = os.getenv("OPENAI_API_KEY")
    
    nodes = WORKFLOW_DATA.get("nodes", [])
    edges = WORKFLOW_DATA.get("edges", [])
    
    results = {{}}
    
    # Get input nodes
    input_nodes = [n for n in nodes if n.get("type") in ["ChatInput", "textInput", "Input", "numberInput"]]
    
    # Map inputs to node IDs
    for i, node in enumerate(input_nodes):
        if i < len(input_values):
            results[node["id"]] = input_values[i]
    
    # Process nodes
    for node in nodes:
        node_id = node.get("id")
        node_type = node.get("type", "")
        node_data = node.get("data", {{}})
        template = node_data.get("template", {{}})
        
        if node_type == "textNode":
            # Combine connected inputs
            base_text = template.get("text", {{}}).get("value", "")
            connected_inputs = []
            
            for edge in edges:
                if edge.get("target") == node_id:
                    source_id = edge.get("source")
                    if source_id in results:
                        connected_inputs.append(f"{{source_id}}: {{results[source_id]}}")
            
            if connected_inputs:
                results[node_id] = f"{{base_text}}\\n\\nInputs:\\n" + "\\n".join(connected_inputs)
            else:
                results[node_id] = base_text
                
        elif node_type in ["llmNode", "OpenAIModel", "ChatModel"]:
            # Get provider and model
            provider = template.get("provider", {{}}).get("value", "OpenAI")
            temperature = template.get("temperature", {{}}).get("value", 0.7)
            system_prompt = template.get("system_prompt", {{}}).get("value", "")
            
            # Get input text
            input_text = ""
            for edge in edges:
                if edge.get("target") == node_id:
                    source_id = edge.get("source")
                    if source_id in results:
                        input_text = results[source_id]
                        break
            
            # Call API
            if provider == "OpenAI" and openai_key:
                try:
                    from openai import OpenAI
                    client = OpenAI(api_key=openai_key)
                    
                    messages = []
                    if system_prompt:
                        messages.append({{"role": "system", "content": system_prompt}})
                    messages.append({{"role": "user", "content": input_text}})
                    
                    response = client.chat.completions.create(
                        model="gpt-4.1-mini",
                        messages=messages,
                        temperature=temperature,
                        max_tokens=1000
                    )
                    
                    results[node_id] = response.choices[0].message.content
                except Exception as e:
                    results[node_id] = f"[OpenAI Error: {{str(e)}}]"
                    
            elif provider == "VIDraft" and vidraft_token:
                try:
                    headers = {{
                        "Authorization": f"Bearer {{vidraft_token}}",
                        "Content-Type": "application/json"
                    }}
                    
                    messages = []
                    if system_prompt:
                        messages.append({{"role": "system", "content": system_prompt}})
                    messages.append({{"role": "user", "content": input_text}})
                    
                    payload = {{
                        "model": "dep89a2fld32mcm",
                        "messages": messages,
                        "max_tokens": 16384,
                        "temperature": temperature,
                        "top_p": 0.8,
                        "stream": False
                    }}
                    
                    response = requests.post(
                        "https://api.friendli.ai/dedicated/v1/chat/completions",
                        headers=headers,
                        json=payload,
                        timeout=30
                    )
                    
                    if response.status_code == 200:
                        results[node_id] = response.json()["choices"][0]["message"]["content"]
                    else:
                        results[node_id] = f"[VIDraft Error: {{response.status_code}}]"
                except Exception as e:
                    results[node_id] = f"[VIDraft Error: {{str(e)}}]"
            else:
                results[node_id] = f"[Simulated Response: {{input_text[:50]}}...]"
                
        elif node_type in ["ChatOutput", "textOutput", "Output"]:
            # Get connected result
            for edge in edges:
                if edge.get("target") == node_id:
                    source_id = edge.get("source")
                    if source_id in results:
                        results[node_id] = results[source_id]
                        break
    
    # Return outputs
    output_nodes = [n for n in nodes if n.get("type") in ["ChatOutput", "textOutput", "Output"]]
    return [results.get(n["id"], "") for n in output_nodes]

# Build UI
with gr.Blocks(title="{app_name}", theme=gr.themes.Soft()) as demo:
    gr.Markdown("# {app_name}")
    gr.Markdown("{app_description}")
    
    # Extract nodes
    nodes = WORKFLOW_DATA.get("nodes", [])
    input_nodes = [n for n in nodes if n.get("type") in ["ChatInput", "textInput", "Input", "numberInput"]]
    output_nodes = [n for n in nodes if n.get("type") in ["ChatOutput", "textOutput", "Output"]]
    
    # Create inputs
    inputs = []
    if input_nodes:
        gr.Markdown("### ๐Ÿ“ฅ Inputs")
        for node in input_nodes:
            label = node.get("data", {{}}).get("label", node.get("id"))
            template = node.get("data", {{}}).get("template", {{}})
            default_value = template.get("input_value", {{}}).get("value", "")
            
            if node.get("type") == "numberInput":
                inp = gr.Number(label=label, value=float(default_value) if default_value else 0)
            else:
                inp = gr.Textbox(label=label, value=default_value, lines=2)
            inputs.append(inp)
    
    # Execute button
    btn = gr.Button("๐Ÿš€ Execute Workflow", variant="primary")
    
    # Create outputs
    outputs = []
    if output_nodes:
        gr.Markdown("### ๐Ÿ“ค Outputs")
        for node in output_nodes:
            label = node.get("data", {{}}).get("label", node.get("id"))
            out = gr.Textbox(label=label, interactive=False, lines=3)
            outputs.append(out)
    
    # Connect
    btn.click(fn=execute_workflow, inputs=inputs, outputs=outputs)
    
    gr.Markdown("---")
    gr.Markdown("*Powered by MOUSE Workflow*")

if __name__ == "__main__":
    demo.launch()
'''
    
    return app_code

def generate_requirements_txt() -> str:
    """Generate requirements.txt for the standalone app"""
    return """gradio==5.34.2
openai
requests
"""

def deploy_to_huggingface(workflow_data: dict, app_name: str, app_description: str, 
                         hf_token: str, space_name: str, is_private: bool = False) -> dict:
    """Deploy workflow to Hugging Face Space"""
    
    if not HF_HUB_AVAILABLE:
        return {"success": False, "error": "huggingface-hub library not installed"}
    
    try:
        # Initialize HF API
        api = HfApi(token=hf_token)
        
        # Create repository
        repo_id = api.create_repo(
            repo_id=space_name,
            repo_type="space",
            space_sdk="gradio",
            private=is_private,
            exist_ok=True
        )
        
        # Generate files
        app_code = generate_standalone_app(workflow_data, app_name, app_description)
        requirements = generate_requirements_txt()
        readme = f"""---
title: {app_name}
emoji: ๐Ÿญ
colorFrom: blue
colorTo: green
sdk: gradio
sdk_version: 5.34.2
app_file: app.py
pinned: false
---

# {app_name}

{app_description}

Generated by MOUSE Workflow
"""
        
        # Upload files
        api.upload_file(
            path_or_fileobj=app_code.encode(),
            path_in_repo="app.py",
            repo_id=repo_id.repo_id,
            repo_type="space"
        )
        
        api.upload_file(
            path_or_fileobj=requirements.encode(),
            path_in_repo="requirements.txt",
            repo_id=repo_id.repo_id,
            repo_type="space"
        )
        
        api.upload_file(
            path_or_fileobj=readme.encode(),
            path_in_repo="README.md",
            repo_id=repo_id.repo_id,
            repo_type="space"
        )
        
        space_url = f"https://huggingface.co/spaces/{repo_id.repo_id}"
        
        return {
            "success": True,
            "space_url": space_url,
            "message": f"Successfully deployed to {space_url}"
        }
        
    except Exception as e:
        return {
            "success": False,
            "error": str(e)
        }

# UI ์‹คํ–‰์„ ์œ„ํ•œ ์‹ค์ œ ์›Œํฌํ”Œ๋กœ์šฐ ์‹คํ–‰ ํ•จ์ˆ˜
def execute_workflow_simple(workflow_data: dict, input_values: dict) -> dict:
    """์›Œํฌํ”Œ๋กœ์šฐ ์‹ค์ œ ์‹คํ–‰"""
    import traceback
    
    # API ํ‚ค ํ™•์ธ
    vidraft_token = os.getenv("FRIENDLI_TOKEN")  # VIDraft/Friendli token
    openai_key = os.getenv("OPENAI_API_KEY")
    # anthropic_key = os.getenv("ANTHROPIC_API_KEY")  # ์ฃผ์„ ์ฒ˜๋ฆฌ
    
    # OpenAI ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ํ™•์ธ
    try:
        from openai import OpenAI
        openai_available = True
    except ImportError:
        openai_available = False
        print("OpenAI library not available")
    
    # Anthropic ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ํ™•์ธ - ์ฃผ์„ ์ฒ˜๋ฆฌ
    # try:
    #     import anthropic
    #     anthropic_available = True
    # except ImportError:
    #     anthropic_available = False
    #     print("Anthropic library not available")
    anthropic_available = False
    
    results = {}
    nodes = workflow_data.get("nodes", [])
    edges = workflow_data.get("edges", [])
    
    # ๋…ธ๋“œ๋ฅผ ์ˆœ์„œ๋Œ€๋กœ ์ฒ˜๋ฆฌ
    for node in nodes:
        node_id = node.get("id")
        node_type = node.get("type", "")
        node_data = node.get("data", {})
        
        try:
            if node_type in ["ChatInput", "textInput", "Input"]:
                # UI์—์„œ ์ œ๊ณต๋œ ์ž…๋ ฅ๊ฐ’ ์‚ฌ์šฉ
                if node_id in input_values:
                    results[node_id] = input_values[node_id]
                else:
                    # ๊ธฐ๋ณธ๊ฐ’ ์‚ฌ์šฉ
                    template = node_data.get("template", {})
                    default_value = template.get("input_value", {}).get("value", "")
                    results[node_id] = default_value
            
            elif node_type == "textNode":
                # ํ…์ŠคํŠธ ๋…ธ๋“œ๋Š” ์—ฐ๊ฒฐ๋œ ๋ชจ๋“  ์ž…๋ ฅ์„ ๊ฒฐํ•ฉ
                template = node_data.get("template", {})
                base_text = template.get("text", {}).get("value", "")
                
                # ์—ฐ๊ฒฐ๋œ ์ž…๋ ฅ๋“ค ์ˆ˜์ง‘
                connected_inputs = []
                for edge in edges:
                    if edge.get("target") == node_id:
                        source_id = edge.get("source")
                        if source_id in results:
                            connected_inputs.append(f"{source_id}: {results[source_id]}")
                
                # ๊ฒฐํ•ฉ๋œ ํ…์ŠคํŠธ ์ƒ์„ฑ
                if connected_inputs:
                    combined_text = f"{base_text}\n\nInputs:\n" + "\n".join(connected_inputs)
                    results[node_id] = combined_text
                else:
                    results[node_id] = base_text
            
            elif node_type in ["llmNode", "OpenAIModel", "ChatModel"]:
                # LLM ๋…ธ๋“œ ์ฒ˜๋ฆฌ
                template = node_data.get("template", {})
                
                # ํ”„๋กœ๋ฐ”์ด๋” ์ •๋ณด ์ถ”์ถœ - VIDraft ๋˜๋Š” OpenAI๋งŒ ํ—ˆ์šฉ
                provider_info = template.get("provider", {})
                provider = provider_info.get("value", "OpenAI") if isinstance(provider_info, dict) else "OpenAI"
                
                # provider๊ฐ€ VIDraft ๋˜๋Š” OpenAI๊ฐ€ ์•„๋‹Œ ๊ฒฝ์šฐ OpenAI๋กœ ๊ธฐ๋ณธ ์„ค์ •
                if provider not in ["VIDraft", "OpenAI"]:
                    provider = "OpenAI"
                
                # ๋ชจ๋ธ ์ •๋ณด ์ถ”์ถœ
                if provider == "OpenAI":
                    # OpenAI๋Š” gpt-4.1-mini๋กœ ๊ณ ์ •
                    model = "gpt-4.1-mini"
                elif provider == "VIDraft":
                    # VIDraft๋Š” Gemma-3-r1984-27B๋กœ ๊ณ ์ •
                    model = "Gemma-3-r1984-27B"
                else:
                    model = "gpt-4.1-mini"  # ๊ธฐ๋ณธ๊ฐ’
                
                # ์˜จ๋„ ์ •๋ณด ์ถ”์ถœ
                temp_info = template.get("temperature", {})
                temperature = temp_info.get("value", 0.7) if isinstance(temp_info, dict) else 0.7
                
                # ์‹œ์Šคํ…œ ํ”„๋กฌํ”„ํŠธ ์ถ”์ถœ
                prompt_info = template.get("system_prompt", {})
                system_prompt = prompt_info.get("value", "") if isinstance(prompt_info, dict) else ""
                
                # ์ž…๋ ฅ ํ…์ŠคํŠธ ์ฐพ๊ธฐ
                input_text = ""
                for edge in edges:
                    if edge.get("target") == node_id:
                        source_id = edge.get("source")
                        if source_id in results:
                            input_text = results[source_id]
                            break
                
                # ์‹ค์ œ API ํ˜ธ์ถœ
                if provider == "OpenAI" and openai_key and openai_available:
                    try:
                        client = OpenAI(api_key=openai_key)
                        
                        messages = []
                        if system_prompt:
                            messages.append({"role": "system", "content": system_prompt})
                        messages.append({"role": "user", "content": input_text})
                        
                        response = client.chat.completions.create(
                            model="gpt-4.1-mini",  # ๊ณ ์ •๋œ ๋ชจ๋ธ๋ช…
                            messages=messages,
                            temperature=temperature,
                            max_tokens=1000
                        )
                        
                        results[node_id] = response.choices[0].message.content
                        
                    except Exception as e:
                        results[node_id] = f"[OpenAI Error: {str(e)}]"
                
                # Anthropic ๊ด€๋ จ ์ฝ”๋“œ ์ฃผ์„ ์ฒ˜๋ฆฌ
                # elif provider == "Anthropic" and anthropic_key and anthropic_available:
                #     try:
                #         client = anthropic.Anthropic(api_key=anthropic_key)
                #         
                #         message = client.messages.create(
                #             model="claude-3-haiku-20240307",
                #             max_tokens=1000,
                #             temperature=temperature,
                #             system=system_prompt if system_prompt else None,
                #             messages=[{"role": "user", "content": input_text}]
                #         )
                #         
                #         results[node_id] = message.content[0].text
                #         
                #     except Exception as e:
                #         results[node_id] = f"[Anthropic Error: {str(e)}]"
                
                elif provider == "VIDraft" and vidraft_token:
                    try:
                        import requests
                        
                        headers = {
                            "Authorization": f"Bearer {vidraft_token}",
                            "Content-Type": "application/json"
                        }
                        
                        # ๋ฉ”์‹œ์ง€ ๊ตฌ์„ฑ
                        messages = []
                        if system_prompt:
                            messages.append({"role": "system", "content": system_prompt})
                        messages.append({"role": "user", "content": input_text})
                        
                        payload = {
                            "model": "dep89a2fld32mcm",  # VIDraft ๋ชจ๋ธ ID
                            "messages": messages,
                            "max_tokens": 16384,
                            "temperature": temperature,
                            "top_p": 0.8,
                            "stream": False  # ๋™๊ธฐ ์‹คํ–‰์„ ์œ„ํ•ด False๋กœ ์„ค์ •
                        }
                        
                        # VIDraft API endpoint
                        response = requests.post(
                            "https://api.friendli.ai/dedicated/v1/chat/completions",
                            headers=headers,
                            json=payload,
                            timeout=30
                        )
                        
                        if response.status_code == 200:
                            response_json = response.json()
                            results[node_id] = response_json["choices"][0]["message"]["content"]
                        else:
                            results[node_id] = f"[VIDraft API Error: {response.status_code} - {response.text}]"
                            
                    except Exception as e:
                        results[node_id] = f"[VIDraft Error: {str(e)}]"
                
                else:
                    # API ํ‚ค๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ ์‹œ๋ฎฌ๋ ˆ์ด์…˜
                    results[node_id] = f"[Simulated {provider} Response to: {input_text[:50]}...]"
            
            elif node_type in ["ChatOutput", "textOutput", "Output"]:
                # ์ถœ๋ ฅ ๋…ธ๋“œ๋Š” ์—ฐ๊ฒฐ๋œ ๋…ธ๋“œ์˜ ๊ฒฐ๊ณผ๋ฅผ ๊ฐ€์ ธ์˜ด
                for edge in edges:
                    if edge.get("target") == node_id:
                        source_id = edge.get("source")
                        if source_id in results:
                            results[node_id] = results[source_id]
                            break
                        
        except Exception as e:
            results[node_id] = f"[Node Error: {str(e)}]"
            print(f"Error processing node {node_id}: {traceback.format_exc()}")
    
    return results

# -------------------------------------------------------------------
# ๐ŸŽจ CSS
# -------------------------------------------------------------------
CSS = """
.main-container{max-width:1600px;margin:0 auto;}
.workflow-section{margin-bottom:2rem;min-height:500px;}
.button-row{display:flex;gap:1rem;justify-content:center;margin:1rem 0;}
.status-box{
    padding:10px;border-radius:5px;margin-top:10px;
    background:#f0f9ff;border:1px solid #3b82f6;color:#1e40af;
}
.component-description{
  padding:24px;background:linear-gradient(135deg,#f8fafc 0%,#e2e8f0 100%);
  border-left:4px solid #3b82f6;border-radius:12px;
  box-shadow:0 2px 8px rgba(0,0,0,.05);margin:16px 0;
}
.workflow-container{position:relative;}
.ui-execution-section{
    background:linear-gradient(135deg,#f0fdf4 0%,#dcfce7 100%);
    padding:24px;border-radius:12px;margin:24px 0;
    border:1px solid #86efac;
}
.powered-by{
    text-align:center;color:#64748b;font-size:14px;
    margin-top:8px;font-style:italic;
}
.sample-buttons{
    display:grid;grid-template-columns:1fr 1fr;gap:0.5rem;
    margin-top:0.5rem;
}
.deploy-section{
    background:linear-gradient(135deg,#fef3c7 0%,#fde68a 100%);
    padding:24px;border-radius:12px;margin:24px 0;
    border:1px solid #fbbf24;
}
"""

# -------------------------------------------------------------------
# ๐Ÿ–ฅ๏ธ  Gradio ์•ฑ
# -------------------------------------------------------------------
with gr.Blocks(title="๐Ÿญ MOUSE Workflow", theme=gr.themes.Soft(), css=CSS) as demo:
    
    with gr.Column(elem_classes=["main-container"]):
        gr.Markdown("# ๐Ÿญ MOUSE Workflow")
        gr.Markdown("**Visual Workflow Builder with Interactive UI Execution**")
        gr.HTML('<p class="powered-by">@Powered by VIDraft & Huggingface gradio</p>')
        
        gr.HTML(
            """
            <div class="component-description">
              <p style="font-size:16px;margin:0;">Build sophisticated workflows visually โ€ข Import/Export JSON โ€ข Generate interactive UI for end-users</p>
            </div>
            """
        )
        
        # API Status Display
        with gr.Accordion("๐Ÿ”Œ API Status", open=False):
            gr.Markdown(f"""
            **Available APIs:**
            - FRIENDLI_TOKEN (VIDraft): {'โœ… Connected' if os.getenv("FRIENDLI_TOKEN") else 'โŒ Not found'}
            - OPENAI_API_KEY: {'โœ… Connected' if os.getenv("OPENAI_API_KEY") else 'โŒ Not found'}
            
            **Libraries:**
            - OpenAI: {'โœ… Installed' if OPENAI_AVAILABLE else 'โŒ Not installed'}
            - Requests: {'โœ… Installed' if REQUESTS_AVAILABLE else 'โŒ Not installed'}
            - Hugging Face Hub: {'โœ… Installed' if HF_HUB_AVAILABLE else 'โŒ Not installed (needed for deployment)'}
            
            **Available Models:**
            - OpenAI: gpt-4.1-mini (fixed)
            - VIDraft: Gemma-3-r1984-27B (model ID: dep89a2fld32mcm)
            
            **Sample Workflows:**
            - Basic Q&A: Simple question-answer flow
            - VIDraft: Korean language example with Gemma model
            - Multi-Input: Combine multiple inputs for personalized output
            - Chain: Sequential processing with multiple outputs
            
            *Note: Without API keys, the UI will simulate AI responses.*
            """)
        
        # State for storing workflow data
        loaded_data = gr.State(None)
        trigger_update = gr.State(False)
        
        # โ”€โ”€โ”€ Dynamic Workflow Container โ”€โ”€โ”€
        with gr.Column(elem_classes=["workflow-container"]):
            @gr.render(inputs=[loaded_data, trigger_update])
            def render_workflow(data, trigger):
                """๋™์ ์œผ๋กœ WorkflowBuilder ๋ Œ๋”๋ง"""
                workflow_value = data if data else {"nodes": [], "edges": []}
                
                return WorkflowBuilder(
                    label="๐ŸŽจ Visual Workflow Designer",
                    info="Drag from sidebar โ†’ Connect nodes โ†’ Edit properties",
                    value=workflow_value,
                    elem_id="main_workflow"
                )
        
        # โ”€โ”€โ”€ Import Section โ”€โ”€โ”€
        with gr.Accordion("๐Ÿ“ฅ Import Workflow", open=True):
            with gr.Row():
                with gr.Column(scale=2):
                    import_json_text = gr.Code(
                        language="json",
                        label="Paste JSON here",
                        lines=8,
                        value='{\n  "nodes": [],\n  "edges": []\n}'
                    )
                with gr.Column(scale=1):
                    file_upload = gr.File(
                        label="Or upload JSON file",
                        file_types=[".json"],
                        type="filepath"
                    )
                    btn_load = gr.Button("๐Ÿ“ฅ Load Workflow", variant="primary", size="lg")
                    
                    # Sample buttons
                    gr.Markdown("**Sample Workflows:**")
                    with gr.Row():
                        btn_sample_basic = gr.Button("๐ŸŽฏ Basic Q&A", variant="secondary", scale=1)
                        btn_sample_vidraft = gr.Button("๐Ÿค– VIDraft", variant="secondary", scale=1)
                    with gr.Row():
                        btn_sample_multi = gr.Button("๐Ÿ“ Multi-Input", variant="secondary", scale=1)
                        btn_sample_chain = gr.Button("๐Ÿ”— Chain", variant="secondary", scale=1)
                    
                    # Status
                    status_text = gr.Textbox(
                        label="Status", 
                        value="Ready", 
                        elem_classes=["status-box"],
                        interactive=False
                    )
        
        # โ”€โ”€โ”€ Export Section โ”€โ”€โ”€
        gr.Markdown("## ๐Ÿ’พ Export")
        
        with gr.Row():
            with gr.Column(scale=3):
                export_preview = gr.Code(
                    language="json", 
                    label="Current Workflow JSON", 
                    lines=8
                )
            with gr.Column(scale=1):
                btn_preview = gr.Button("๐Ÿ‘๏ธ Preview JSON", size="lg")
                btn_download = gr.DownloadButton(
                    "๐Ÿ’พ Download JSON", 
                    size="lg",
                    visible=True
                )
        
        # โ”€โ”€โ”€ Deploy Section โ”€โ”€โ”€
        with gr.Accordion("๐Ÿš€ Deploy to Hugging Face Space", open=False, elem_classes=["deploy-section"]):
            gr.Markdown("""
            Deploy your workflow as an independent Hugging Face Space app. 
            This will create a standalone application that anyone can use without the workflow builder.
            """)
            
            with gr.Row():
                with gr.Column(scale=2):
                    deploy_name = gr.Textbox(
                        label="App Name",
                        placeholder="My Awesome Workflow App",
                        value="My Workflow App"
                    )
                    deploy_description = gr.Textbox(
                        label="App Description",
                        placeholder="Describe what your workflow does...",
                        lines=3,
                        value="A workflow application created with MOUSE Workflow builder."
                    )
                    deploy_space_name = gr.Textbox(
                        label="Space Name (your-username/space-name)",
                        placeholder="username/my-workflow-app",
                        info="This will be the URL of your Space"
                    )
                    
                with gr.Column(scale=1):
                    deploy_token = gr.Textbox(
                        label="Hugging Face Token",
                        type="password",
                        placeholder="hf_...",
                        info="Get your token from huggingface.co/settings/tokens"
                    )
                    deploy_private = gr.Checkbox(
                        label="Make Space Private",
                        value=False
                    )
                    
                    btn_deploy = gr.Button("๐Ÿš€ Deploy to HF Space", variant="primary", size="lg")
                    
                    # Deploy status
                    deploy_status = gr.Markdown("")
            
            # Preview generated code
            with gr.Accordion("๐Ÿ“„ Preview Generated Code", open=False):
                generated_code_preview = gr.Code(
                    language="python",
                    label="app.py (This will be deployed)",
                    lines=20
                )
        
        # โ”€โ”€โ”€ UI Execution Section โ”€โ”€โ”€
        with gr.Column(elem_classes=["ui-execution-section"]):
            gr.Markdown("## ๐Ÿš€ UI Execution")
            gr.Markdown("Generate an interactive UI from your workflow for end-users")
            
            btn_execute_ui = gr.Button("โ–ถ๏ธ Generate & Run UI", variant="primary", size="lg")
            
            # UI execution state
            ui_workflow_data = gr.State(None)
            
            # Dynamic UI container
            @gr.render(inputs=[ui_workflow_data])
            def render_execution_ui(workflow_data):
                if not workflow_data or not workflow_data.get("nodes"):
                    gr.Markdown("*Load a workflow first, then click 'Generate & Run UI'*")
                    return
                
                gr.Markdown("### ๐Ÿ“‹ Generated UI")
                
                # Extract input and output nodes
                input_nodes = []
                output_nodes = []
                
                for node in workflow_data.get("nodes", []):
                    node_type = node.get("type", "")
                    if node_type in ["ChatInput", "textInput", "Input", "numberInput"]:
                        input_nodes.append(node)
                    elif node_type in ["ChatOutput", "textOutput", "Output"]:
                        output_nodes.append(node)
                    elif node_type == "textNode":
                        # textNode๋Š” ์ค‘๊ฐ„ ์ฒ˜๋ฆฌ ๋…ธ๋“œ๋กœ, UI์—๋Š” ํ‘œ์‹œํ•˜์ง€ ์•Š์Œ
                        pass
                
                # Create input components
                input_components = {}
                
                if input_nodes:
                    gr.Markdown("#### ๐Ÿ“ฅ Inputs")
                    for node in input_nodes:
                        node_id = node.get("id")
                        label = node.get("data", {}).get("label", node_id)
                        node_type = node.get("type")
                        
                        # Get default value
                        template = node.get("data", {}).get("template", {})
                        default_value = template.get("input_value", {}).get("value", "")
                        
                        if node_type == "numberInput":
                            input_components[node_id] = gr.Number(
                                label=label,
                                value=float(default_value) if default_value else 0
                            )
                        else:
                            input_components[node_id] = gr.Textbox(
                                label=label,
                                value=default_value,
                                lines=2,
                                placeholder="Enter your input..."
                            )
                
                # Execute button
                execute_btn = gr.Button("๐ŸŽฏ Execute", variant="primary")
                
                # Create output components
                output_components = {}
                
                if output_nodes:
                    gr.Markdown("#### ๐Ÿ“ค Outputs")
                    for node in output_nodes:
                        node_id = node.get("id")
                        label = node.get("data", {}).get("label", node_id)
                        
                        output_components[node_id] = gr.Textbox(
                            label=label,
                            interactive=False,
                            lines=3
                        )
                
                # Execution log
                gr.Markdown("#### ๐Ÿ“Š Execution Log")
                log_output = gr.Textbox(
                    label="Log",
                    interactive=False,
                    lines=5
                )
                
                # Define execution handler
                def execute_ui_workflow(*input_values):
                    # Create input dictionary
                    inputs_dict = {}
                    input_keys = list(input_components.keys())
                    for i, key in enumerate(input_keys):
                        if i < len(input_values):
                            inputs_dict[key] = input_values[i]
                    
                    # Check API status
                    log = "=== Workflow Execution Started ===\n"
                    log += f"Inputs provided: {len(inputs_dict)}\n"
                    
                    # API ์ƒํƒœ ํ™•์ธ
                    vidraft_token = os.getenv("FRIENDLI_TOKEN")
                    openai_key = os.getenv("OPENAI_API_KEY")
                    
                    log += "\nAPI Status:\n"
                    log += f"- FRIENDLI_TOKEN (VIDraft): {'โœ… Found' if vidraft_token else 'โŒ Not found'}\n"
                    log += f"- OPENAI_API_KEY: {'โœ… Found' if openai_key else 'โŒ Not found'}\n"
                    
                    if not vidraft_token and not openai_key:
                        log += "\nโš ๏ธ No API keys found. Results will be simulated.\n"
                        log += "To get real AI responses, set API keys in environment variables.\n"
                    
                    log += "\n--- Processing Nodes ---\n"
                    
                    try:
                        results = execute_workflow_simple(workflow_data, inputs_dict)
                        
                        # Prepare outputs
                        output_values = []
                        for node_id in output_components.keys():
                            value = results.get(node_id, "No output")
                            output_values.append(value)
                            
                            # Log ๊ธธ์ด ์ œํ•œ
                            display_value = value[:100] + "..." if len(str(value)) > 100 else value
                            log += f"\nOutput [{node_id}]: {display_value}\n"
                        
                        log += "\n=== Execution Completed Successfully! ===\n"
                        output_values.append(log)
                        
                        return output_values
                        
                    except Exception as e:
                        error_msg = f"โŒ Error: {str(e)}"
                        log += f"\n{error_msg}\n"
                        log += "=== Execution Failed ===\n"
                        return [error_msg] * len(output_components) + [log]
                
                # Connect execution
                all_inputs = list(input_components.values())
                all_outputs = list(output_components.values()) + [log_output]
                
                execute_btn.click(
                    fn=execute_ui_workflow,
                    inputs=all_inputs,
                    outputs=all_outputs
                )
        
        # โ”€โ”€โ”€ Event Handlers โ”€โ”€โ”€
        
        # Load workflow (from text or file)
        def load_workflow(json_text, file_obj):
            data, status = load_json_from_text_or_file(json_text, file_obj)
            if data:
                return data, status, json_text if not file_obj else export_pretty(data)
            else:
                return None, status, gr.update()
        
        btn_load.click(
            fn=load_workflow,
            inputs=[import_json_text, file_upload],
            outputs=[loaded_data, status_text, import_json_text]
        ).then(
            fn=lambda current_trigger: not current_trigger,
            inputs=trigger_update,
            outputs=trigger_update
        )
        
        # Auto-load when file is uploaded
        file_upload.change(
            fn=load_workflow,
            inputs=[import_json_text, file_upload],
            outputs=[loaded_data, status_text, import_json_text]
        ).then(
            fn=lambda current_trigger: not current_trigger,
            inputs=trigger_update,
            outputs=trigger_update
        )
        
        # Load samples
        btn_sample_basic.click(
            fn=lambda: (create_sample_workflow("basic"), "โœ… Basic Q&A sample loaded", export_pretty(create_sample_workflow("basic"))),
            outputs=[loaded_data, status_text, import_json_text]
        ).then(
            fn=lambda current_trigger: not current_trigger,
            inputs=trigger_update,
            outputs=trigger_update
        )
        
        btn_sample_vidraft.click(
            fn=lambda: (create_sample_workflow("vidraft"), "โœ… VIDraft sample loaded", export_pretty(create_sample_workflow("vidraft"))),
            outputs=[loaded_data, status_text, import_json_text]
        ).then(
            fn=lambda current_trigger: not current_trigger,
            inputs=trigger_update,
            outputs=trigger_update
        )
        
        btn_sample_multi.click(
            fn=lambda: (create_sample_workflow("multi_input"), "โœ… Multi-input sample loaded", export_pretty(create_sample_workflow("multi_input"))),
            outputs=[loaded_data, status_text, import_json_text]
        ).then(
            fn=lambda current_trigger: not current_trigger,
            inputs=trigger_update,
            outputs=trigger_update
        )
        
        btn_sample_chain.click(
            fn=lambda: (create_sample_workflow("chain"), "โœ… Chain processing sample loaded", export_pretty(create_sample_workflow("chain"))),
            outputs=[loaded_data, status_text, import_json_text]
        ).then(
            fn=lambda current_trigger: not current_trigger,
            inputs=trigger_update,
            outputs=trigger_update
        )
        
        # Preview current workflow
        btn_preview.click(
            fn=export_pretty,
            inputs=loaded_data,
            outputs=export_preview
        )
        
        # Download workflow
        def prepare_download(data):
            """๋‹ค์šด๋กœ๋“œ๋ฅผ ์œ„ํ•œ ํŒŒ์ผ ์ค€๋น„"""
            if not data:
                return None
            return export_file(data)
        
        # Download ๋ฒ„ํŠผ์— ํŒŒ์ผ ์—ฐ๊ฒฐ
        loaded_data.change(
            fn=prepare_download,
            inputs=loaded_data,
            outputs=btn_download
        )
        
        # Generate UI execution
        btn_execute_ui.click(
            fn=lambda data: data,
            inputs=loaded_data,
            outputs=ui_workflow_data
        )
        
        # Auto-update export preview when workflow changes
        loaded_data.change(
            fn=export_pretty,
            inputs=loaded_data,
            outputs=export_preview
        )
        
        # โ”€โ”€โ”€ Deploy Event Handlers โ”€โ”€โ”€
        
        # Preview generated code
        def preview_generated_code(workflow_data, app_name, app_description):
            if not workflow_data:
                return "No workflow loaded"
            
            try:
                code = generate_standalone_app(workflow_data, app_name, app_description)
                return code
            except Exception as e:
                return f"Error generating code: {str(e)}"
        
        # Update preview when inputs change
        deploy_name.change(
            fn=preview_generated_code,
            inputs=[loaded_data, deploy_name, deploy_description],
            outputs=generated_code_preview
        )
        
        deploy_description.change(
            fn=preview_generated_code,
            inputs=[loaded_data, deploy_name, deploy_description],
            outputs=generated_code_preview
        )
        
        loaded_data.change(
            fn=preview_generated_code,
            inputs=[loaded_data, deploy_name, deploy_description],
            outputs=generated_code_preview
        )
        
        # Deploy handler
        def handle_deploy(workflow_data, app_name, app_description, hf_token, space_name, is_private):
            if not workflow_data:
                return "โŒ No workflow loaded. Please load a workflow first."
            
            if not hf_token:
                return "โŒ Hugging Face token is required. Get yours at huggingface.co/settings/tokens"
            
            if not space_name:
                return "โŒ Space name is required. Format: username/space-name"
            
            # Validate space name format
            if "/" not in space_name:
                return "โŒ Invalid space name format. Use: username/space-name"
            
            # Check if huggingface-hub is available
            if not HF_HUB_AVAILABLE:
                return "โŒ huggingface-hub library not installed. Install with: pip install huggingface-hub"
            
            # Show deploying status
            yield "๐Ÿ”„ Deploying to Hugging Face Space..."
            
            # Deploy
            result = deploy_to_huggingface(
                workflow_data=workflow_data,
                app_name=app_name,
                app_description=app_description,
                hf_token=hf_token,
                space_name=space_name,
                is_private=is_private
            )
            
            if result["success"]:
                yield f"""โœ… **Deployment Successful!**
                
๐ŸŽ‰ Your workflow has been deployed to:
[{result['space_url']}]({result['space_url']})

โฑ๏ธ The Space will be ready in a few minutes. Building usually takes 2-5 minutes.

๐Ÿ“ **Next Steps:**
1. Visit your Space URL
2. Wait for the build to complete
3. Share the URL with others
4. You can edit the code directly on Hugging Face if needed

๐Ÿ’ก **Tip:** Set your API keys as secrets in the Space settings:
- FRIENDLI_TOKEN (for VIDraft)
- OPENAI_API_KEY (for OpenAI)
"""
            else:
                yield f"โŒ **Deployment Failed**\n\nError: {result['error']}"
        
        btn_deploy.click(
            fn=handle_deploy,
            inputs=[loaded_data, deploy_name, deploy_description, deploy_token, deploy_space_name, deploy_private],
            outputs=deploy_status
        )
        

# -------------------------------------------------------------------
# ๐Ÿš€ ์‹คํ–‰
# -------------------------------------------------------------------
if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", show_error=True)