File size: 38,250 Bytes
2a02b1f
 
 
 
 
8f54e55
 
2a02b1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f54e55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a02b1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f54e55
 
 
 
 
 
 
2a02b1f
 
8f54e55
2a02b1f
 
 
 
 
 
 
 
 
8f54e55
 
2a02b1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f54e55
2a02b1f
 
8f54e55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a02b1f
8f54e55
 
2a02b1f
 
 
 
 
 
 
 
 
8f54e55
2a02b1f
 
8f54e55
2a02b1f
 
8f54e55
2a02b1f
 
 
 
 
 
 
 
 
 
 
 
 
 
8f54e55
2a02b1f
 
 
8f54e55
2a02b1f
8f54e55
2a02b1f
 
8f54e55
2a02b1f
 
8f54e55
2a02b1f
8f54e55
2a02b1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f54e55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a02b1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2bc4f5
 
2a02b1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f54e55
 
 
 
 
 
2a02b1f
 
8f54e55
 
 
 
 
 
 
 
2a02b1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f54e55
 
 
 
 
 
 
 
 
 
2a02b1f
 
8f54e55
 
2a02b1f
 
 
 
 
3238c20
 
 
 
 
 
 
 
 
 
2a02b1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
import gradio as gr
import os
import sys
import json
import requests
import re
from typing import List, Tuple

# ํ˜„์žฌ ๋””๋ ‰ํ† ๋ฆฌ์™€ ํฐํŠธ ํŒŒ์ผ ๊ฒฝ๋กœ ์„ค์ •
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
FONT_PATH = os.path.join(CURRENT_DIR, 'NanumGothic-Regular.ttf')
FONTS_CONF_PATH = os.path.join(CURRENT_DIR, 'fonts.conf')

# fonts.conf ํŒŒ์ผ ์ƒ์„ฑ ํ•จ์ˆ˜
def create_fonts_conf():
    """Graphviz๊ฐ€ ๋กœ์ปฌ ํฐํŠธ๋ฅผ ์ธ์‹ํ•  ์ˆ˜ ์žˆ๋„๋ก fonts.conf ํŒŒ์ผ ์ƒ์„ฑ"""
    fonts_conf_content = f"""<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
    <!-- ๋กœ์ปฌ ํฐํŠธ ๋””๋ ‰ํ† ๋ฆฌ ์ถ”๊ฐ€ -->
    <dir>{CURRENT_DIR}</dir>
    
    <!-- NanumGothic ํฐํŠธ ๋ณ„์นญ ์„ค์ • -->
    <alias>
        <family>NanumGothic</family>
        <prefer>
            <family>NanumGothic-Regular</family>
        </prefer>
    </alias>
    
    <alias>
        <family>NanumGothic-Regular</family>
        <default>
            <family>NanumGothic-Regular</family>
        </default>
    </alias>
    
    <!-- ํ•œ๊ธ€ ํฐํŠธ ๋งคํ•‘ -->
    <match target="pattern">
        <test name="family">
            <string>NanumGothic</string>
        </test>
        <edit name="family" mode="assign">
            <string>NanumGothic-Regular</string>
        </edit>
    </match>
</fontconfig>
"""
    
    with open(FONTS_CONF_PATH, 'w', encoding='utf-8') as f:
        f.write(fonts_conf_content)
    print(f"fonts.conf ํŒŒ์ผ ์ƒ์„ฑ๋จ: {FONTS_CONF_PATH}")

# ํฐํŠธ ์„ค์ •
if os.path.exists(FONT_PATH):
    print(f"ํ•œ๊ธ€ ํฐํŠธ ํŒŒ์ผ ๋ฐœ๊ฒฌ: {FONT_PATH}")
    
    # fonts.conf ํŒŒ์ผ ์ƒ์„ฑ
    create_fonts_conf()
    
    # Graphviz๊ฐ€ ํฐํŠธ๋ฅผ ์ฐพ์„ ์ˆ˜ ์žˆ๋„๋ก ํ™˜๊ฒฝ ๋ณ€์ˆ˜ ์„ค์ •
    os.environ['GDFONTPATH'] = CURRENT_DIR
    os.environ['FONTCONFIG_PATH'] = CURRENT_DIR
    os.environ['FONTCONFIG_FILE'] = FONTS_CONF_PATH
    
    print(f"GDFONTPATH ์„ค์ •: {CURRENT_DIR}")
    print(f"FONTCONFIG_FILE ์„ค์ •: {FONTS_CONF_PATH}")
else:
    print(f"๊ฒฝ๊ณ : ํ•œ๊ธ€ ํฐํŠธ ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค: {FONT_PATH}")

# ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋กœ ํฐํŠธ ๊ฒฝ๋กœ ์ €์žฅ (generator๋“ค์ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก)
os.environ['KOREAN_FONT_PATH'] = FONT_PATH

from concept_map_generator import generate_concept_map
from synoptic_chart_generator import generate_synoptic_chart
from radial_diagram_generator import generate_radial_diagram
from process_flow_generator import generate_process_flow_diagram
from wbs_diagram_generator import generate_wbs_diagram

from sample_data import CONCEPT_MAP_JSON, SYNOPTIC_CHART_JSON, RADIAL_DIAGRAM_JSON, PROCESS_FLOW_JSON, WBS_DIAGRAM_JSON

# ๋ธŒ๋ ˆ์ด๋ธŒ ์„œ์น˜ API ํ•จ์ˆ˜
def brave_search(query: str) -> List[dict]:
    """๋ธŒ๋ ˆ์ด๋ธŒ ์„œ์น˜ API๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ฒ€์ƒ‰ ์ˆ˜ํ–‰"""
    api_key = os.getenv("BSEARCH_API")
    if not api_key:
        print("Warning: BSEARCH_API environment variable not set")
        return []
    
    url = "https://api.search.brave.com/res/v1/web/search"
    headers = {
        "Accept": "application/json",
        "X-Subscription-Token": api_key
    }
    params = {
        "q": query,
        "count": 5  # ์ƒ์œ„ 5๊ฐœ ๊ฒฐ๊ณผ๋งŒ ๊ฐ€์ ธ์˜ค๊ธฐ
    }
    
    try:
        response = requests.get(url, headers=headers, params=params, timeout=10)
        if response.status_code == 200:
            data = response.json()
            results = []
            if "web" in data and "results" in data["web"]:
                for result in data["web"]["results"][:5]:
                    results.append({
                        "title": result.get("title", ""),
                        "description": result.get("description", ""),
                        "url": result.get("url", "")
                    })
            return results
        else:
            print(f"Brave Search API error: {response.status_code}")
            return []
    except Exception as e:
        print(f"Brave Search error: {str(e)}")
        return []

def extract_keywords(prompt: str, diagram_type: str) -> str:
    """ํ”„๋กฌํ”„ํŠธ์—์„œ ํ•ต์‹ฌ ํ‚ค์›Œ๋“œ ์ถ”์ถœ"""
    # ๋‹ค์ด์–ด๊ทธ๋žจ ํƒ€์ž… ์ œ๊ฑฐ
    prompt_clean = prompt.lower()
    
    # ์ผ๋ฐ˜์ ์ธ ์š”์ฒญ ํ‘œํ˜„ ์ œ๊ฑฐ
    remove_patterns = [
        r"create\s+a?\s*", r"make\s+a?\s*", r"generate\s+a?\s*", r"build\s+a?\s*",
        r"design\s+a?\s*", r"develop\s+a?\s*", r"show\s+me\s*", r"i\s+need\s+a?\s*",
        r"diagram\s*", r"chart\s*", r"map\s*", r"flow\s*", r"๋ฅผ\s*๋งŒ๋“ค์–ด\s*",
        r"์ƒ์„ฑํ•ด\s*", r"๊ทธ๋ ค\s*", r"๋ณด์—ฌ\s*", r"์„ค๊ณ„\s*", r"๊ตฌ์ถ•\s*"
    ]
    
    for pattern in remove_patterns:
        prompt_clean = re.sub(pattern, "", prompt_clean)
    
    # ์ฃผ์š” ๋ช…์‚ฌ์™€ ํ•ต์‹ฌ ์šฉ์–ด๋งŒ ์ถ”์ถœ
    # ๊ฐ„๋‹จํ•œ ๋ฐฉ๋ฒ•: ๊ธธ์ด๊ฐ€ 3์ž ์ด์ƒ์ธ ๋‹จ์–ด๋“ค์„ ์ถ”์ถœ
    words = prompt_clean.split()
    keywords = []
    
    for word in words:
        # ๋ถˆํ•„์š”ํ•œ ๋‹จ์–ด ์ œ์™ธ
        if len(word) > 2 and word not in ["the", "and", "for", "with", "that", "this", "from", "about"]:
            keywords.append(word)
    
    # ์ตœ๋Œ€ 5๊ฐœ ํ‚ค์›Œ๋“œ๋งŒ ์‚ฌ์šฉ
    return " ".join(keywords[:5])

def enrich_prompt_with_search(prompt: str, diagram_type: str, search_results: List[dict]) -> str:
    """๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ํ”„๋กฌํ”„ํŠธ๋ฅผ ๋ณด๊ฐ•"""
    if not search_results:
        return prompt
    
    # ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ์—์„œ ์œ ์šฉํ•œ ์ •๋ณด ์ถ”์ถœ
    enrichment = "\n\nAdditional context from web search:\n"
    for i, result in enumerate(search_results[:3]):  # ์ƒ์œ„ 3๊ฐœ๋งŒ ์‚ฌ์šฉ
        enrichment += f"- {result['title']}: {result['description']}\n"
    
    enriched_prompt = f"{prompt}{enrichment}"
    return enriched_prompt

# LLM API ํ•จ์ˆ˜ ์ˆ˜์ •
def call_llm_api(prompt, diagram_type, use_search=False, search_results=None):
    """Friendli AI API๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ JSON ์ƒ์„ฑ"""
    token = os.environ.get("FRIENDLI_TOKEN") or "YOUR_FRIENDLI_TOKEN"
    url = "https://api.friendli.ai/dedicated/v1/chat/completions"
    headers = {
        "Authorization": "Bearer " + token,
        "Content-Type": "application/json"
    }
    
    # ๋‹ค์ด์–ด๊ทธ๋žจ ํƒ€์ž…๋ณ„ JSON ๊ตฌ์กฐ ๊ฐ€์ด๋“œ - ์‹ค์ œ ์ƒ์„ฑ๊ธฐ๊ฐ€ ์š”๊ตฌํ•˜๋Š” ์ •ํ™•ํ•œ ํ˜•์‹
    json_guides = {
        "Concept Map": """Generate a JSON for a concept map with the EXACT following structure:
{
  "central_node": "Main Topic",
  "nodes": [
    {
      "id": "node1",
      "label": "First Concept",
      "relationship": "is part of",
      "subnodes": [
        {
          "id": "node1_1",
          "label": "Sub Concept 1",
          "relationship": "includes",
          "subnodes": []
        }
      ]
    },
    {
      "id": "node2",
      "label": "Second Concept",
      "relationship": "relates to",
      "subnodes": []
    }
  ]
}""",
        "Synoptic Chart": """Generate a JSON for a synoptic chart with the EXACT following structure:
{
  "central_node": "Chart Title",
  "nodes": [
    {
      "id": "phase1",
      "label": "Phase 1 Name",
      "relationship": "starts with",
      "subnodes": [
        {
          "id": "sub1_1",
          "label": "Sub Item 1",
          "relationship": "includes",
          "subnodes": []
        }
      ]
    }
  ]
}""",
        "Radial Diagram": """Generate a JSON for a radial diagram with the EXACT following structure:
{
  "central_node": "Central Concept",
  "nodes": [
    {
      "id": "branch1",
      "label": "Branch 1",
      "relationship": "connected to",
      "subnodes": [
        {
          "id": "item1",
          "label": "Item 1",
          "relationship": "example",
          "subnodes": []
        }
      ]
    }
  ]
}""",
        "Process Flow": """Generate a JSON for a process flow diagram with the EXACT following structure:
{
  "start_node": "Start Process",
  "nodes": [
    {"id": "step1", "label": "First Step", "type": "process"},
    {"id": "step2", "label": "Decision Point", "type": "decision"},
    {"id": "step3", "label": "Another Step", "type": "process"},
    {"id": "end", "label": "End Process", "type": "end"}
  ],
  "connections": [
    {"from": "start_node", "to": "step1", "label": "Begin"},
    {"from": "step1", "to": "step2", "label": "Next"},
    {"from": "step2", "to": "step3", "label": "Yes"},
    {"from": "step3", "to": "end", "label": "Complete"}
  ]
}""",
        "WBS Diagram": """Generate a JSON for a WBS diagram with the EXACT following structure:
{
  "project_title": "Project Name",
  "phases": [
    {
      "id": "phase1",
      "label": "Phase 1",
      "tasks": [
        {
          "id": "task1_1",
          "label": "Task 1.1",
          "subtasks": [
            {
              "id": "subtask1_1_1",
              "label": "Subtask 1.1.1",
              "sub_subtasks": []
            }
          ]
        }
      ]
    }
  ]
}"""
    }
    
    # ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ๊ฐ€ ์žˆ์œผ๋ฉด ์‹œ์Šคํ…œ ํ”„๋กฌํ”„ํŠธ์— ์ถ”๊ฐ€
    search_context = ""
    if use_search and search_results:
        search_context = "\n\nUse the following search results to enrich the diagram content:\n"
        for result in search_results[:3]:
            search_context += f"- {result['title']}: {result['description']}\n"
    
    system_prompt = f"""You are a helpful assistant that generates JSON structures for diagrams.
{json_guides.get(diagram_type, '')}
{search_context}
Important rules:
1. Generate ONLY valid JSON without any explanation or markdown formatting
2. The JSON must follow the EXACT structure shown above - do not change field names
3. Make the content relevant to the user's prompt
4. Use the user's language (Korean or English) for the content values
5. For IDs, use simple alphanumeric strings without spaces (e.g., "node1", "task1_1")
6. Ensure all connections reference existing node IDs
7. For Process Flow: 'type' can be: "process", "decision", "start", "end", "io"
8. For nested structures (Concept Map, Synoptic Chart, Radial, WBS), include empty 'subnodes' or 'subtasks' arrays when there are no children
9. Do not add any additional fields not shown in the example structure
10. If search results are provided, incorporate relevant information into the diagram content"""

    payload = {
        "model": "dep89a2fld32mcm",
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": f"Create a {diagram_type} JSON for: {prompt}"}
        ],
        "max_tokens": 16384,
        "top_p": 0.8,
        "stream": False  # ๊ฐ„๋‹จํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด stream์„ False๋กœ ์„ค์ •
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=30)
        
        # API ์‘๋‹ต ์ƒํƒœ ํ™•์ธ
        if response.status_code != 200:
            return json.dumps({"error": f"API returned status code {response.status_code}: {response.text}"})
        
        response_data = response.json()
        
        if 'choices' in response_data and len(response_data['choices']) > 0:
            content = response_data['choices'][0]['message']['content']
            # JSON ๋ถ€๋ถ„๋งŒ ์ถ”์ถœ (๋งˆํฌ๋‹ค์šด ์ฝ”๋“œ ๋ธ”๋ก ์ œ๊ฑฐ)
            content = content.strip()
            if content.startswith("```json"):
                content = content[7:]
            if content.startswith("```"):
                content = content[3:]
            if content.endswith("```"):
                content = content[:-3]
            
            # ์ถ”๊ฐ€์ ์ธ ํ…์ŠคํŠธ ์ œ๊ฑฐ (JSON ์™ธ์˜ ์„ค๋ช…์ด ์žˆ์„ ๊ฒฝ์šฐ)
            content = content.strip()
            # JSON ์‹œ์ž‘ ์œ„์น˜ ์ฐพ๊ธฐ
            json_start = content.find('{')
            if json_start != -1:
                content = content[json_start:]
                # JSON ๋ ์œ„์น˜ ์ฐพ๊ธฐ
                bracket_count = 0
                json_end = -1
                for i, char in enumerate(content):
                    if char == '{':
                        bracket_count += 1
                    elif char == '}':
                        bracket_count -= 1
                        if bracket_count == 0:
                            json_end = i
                            break
                if json_end != -1:
                    content = content[:json_end + 1]
            
            return content.strip()
        else:
            return json.dumps({"error": "No response from LLM"})
    except requests.exceptions.Timeout:
        return json.dumps({"error": "Request timed out"})
    except requests.exceptions.RequestException as e:
        print(f"LLM API Request Error: {str(e)}")
        return json.dumps({"error": f"Request failed: {str(e)}"})
    except Exception as e:
        print(f"LLM API Error: {str(e)}")
        return json.dumps({"error": str(e)})

def generate_with_llm(prompt, diagram_type, output_format, use_search):
    """LLM์œผ๋กœ JSON์„ ์ƒ์„ฑํ•˜๊ณ  ๋‹ค์ด์–ด๊ทธ๋žจ์„ ์ƒ์„ฑ"""
    if not prompt:
        return None, "Please enter a prompt", ""
    
    search_results = []
    search_info = ""
    
    # ๋ธŒ๋ ˆ์ด๋ธŒ ์„œ์น˜ ์‚ฌ์šฉ ์‹œ
    if use_search:
        keywords = extract_keywords(prompt, diagram_type)
        if keywords:
            search_info = f"๐Ÿ” Searching for: {keywords}\n"
            search_results = brave_search(keywords)
            if search_results:
                search_info += f"โœ… Found {len(search_results)} relevant results\n\n"
                for i, result in enumerate(search_results[:3]):
                    search_info += f"{i+1}. {result['title']}\n   {result['description'][:100]}...\n\n"
            else:
                search_info += "โŒ No search results found\n\n"
    
    # LLM์œผ๋กœ JSON ์ƒ์„ฑ (๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ํฌํ•จ)
    generated_json = call_llm_api(prompt, diagram_type, use_search, search_results)
    
    try:
        # JSON ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ
        json_data = json.loads(generated_json)
        json_str = json.dumps(json_data, indent=2, ensure_ascii=False)
        
        # JSON ๊ตฌ์กฐ ๊ฒ€์ฆ
        if diagram_type in ["Concept Map", "Synoptic Chart", "Radial Diagram"]:
            if "central_node" not in json_data or "nodes" not in json_data:
                return None, f"Invalid JSON structure for {diagram_type}. Missing 'central_node' or 'nodes'. Generated JSON:\n{json_str}", search_info
        elif diagram_type == "Process Flow":
            if "start_node" not in json_data or "nodes" not in json_data or "connections" not in json_data:
                return None, f"Invalid JSON structure for Process Flow. Missing 'start_node', 'nodes', or 'connections'. Generated JSON:\n{json_str}", search_info
        elif diagram_type == "WBS Diagram":
            if "project_title" not in json_data or "phases" not in json_data:
                return None, f"Invalid JSON structure for WBS. Missing 'project_title' or 'phases'. Generated JSON:\n{json_str}", search_info
        
        # ๋‹ค์ด์–ด๊ทธ๋žจ ์ƒ์„ฑ
        try:
            if diagram_type == "Concept Map":
                diagram = generate_concept_map(json_str, output_format)
            elif diagram_type == "Synoptic Chart":
                diagram = generate_synoptic_chart(json_str, output_format)
            elif diagram_type == "Radial Diagram":
                diagram = generate_radial_diagram(json_str, output_format)
            elif diagram_type == "Process Flow":
                diagram = generate_process_flow_diagram(json_str, output_format)
            elif diagram_type == "WBS Diagram":
                diagram = generate_wbs_diagram(json_str, output_format)
            else:
                return None, "Invalid diagram type", search_info
            
            # ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๊ฐ€ ๋ฐ˜ํ™˜๋œ ๊ฒฝ์šฐ
            if isinstance(diagram, str) and diagram.startswith("Error:"):
                return None, f"Diagram generation error: {diagram}\n\nGenerated JSON:\n{json_str}", search_info
            
            return diagram, json_str, search_info
            
        except Exception as e:
            return None, f"Error generating diagram: {str(e)}\n\nGenerated JSON:\n{json_str}", search_info
        
    except json.JSONDecodeError as e:
        return None, f"Invalid JSON generated: {str(e)}\n\nGenerated content:\n{generated_json}", search_info
    except Exception as e:
        return None, f"Unexpected error: {str(e)}\n\nGenerated content:\n{generated_json}", search_info

if __name__ == "__main__":
    DEFAULT_BASE_COLOR = '#19191a' 

    with gr.Blocks(
        title="Advanced Graph Generator",
        theme=gr.themes.Soft(
            primary_hue="violet",
            secondary_hue="purple",
        ),
        css="""
        /* ๊ทธ๋ผ๋””์–ธํŠธ ๋ฐฐ๊ฒฝ */
        .gradio-container {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        
        /* ๋ฉ”์ธ ์ปจํ…Œ์ด๋„ˆ ์Šคํƒ€์ผ */
        .main-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 30px;
            margin: 20px auto;
            max-width: 1400px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
        }
        
        /* ํ—ค๋” ์Šคํƒ€์ผ */
        .header-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px;
            border-radius: 15px;
            margin-bottom: 30px;
            text-align: center;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
        }
        
        .header-section h1 {
            font-size: 2.5em;
            font-weight: 700;
            margin-bottom: 10px;
        }
        
        .header-section p {
            font-size: 1.2em;
            opacity: 0.9;
        }
        
        /* ํƒญ ์Šคํƒ€์ผ */
        .gr-tab-item {
            padding: 15px 30px;
            font-size: 1.1em;
            font-weight: 600;
            background: white;
            border-radius: 10px 10px 0 0;
            transition: all 0.3s ease;
            margin-right: 5px;
        }
        
        .gr-tab-item:hover {
            background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
        }
        
        .gr-tab-item.selected {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white !important;
        }
        
        /* ๋ฒ„ํŠผ ์Šคํƒ€์ผ */
        .gr-button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            font-size: 1.1em;
            font-weight: 600;
            border-radius: 10px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }
        
        .gr-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
        }
        
        .gr-button.primary {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        
        /* ์ž…๋ ฅ ํ•„๋“œ ์Šคํƒ€์ผ */
        .gr-textbox, .gr-dropdown {
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 12px;
            font-size: 1em;
            transition: all 0.3s ease;
            background: white;
        }
        
        .gr-textbox:focus, .gr-dropdown:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        /* ํŒจ๋„ ์Šคํƒ€์ผ */
        .panel-section {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
        }
        
        /* ์ด๋ฏธ์ง€ ์ปจํ…Œ์ด๋„ˆ ์Šคํƒ€์ผ */
        .gr-image {
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }
        
        /* ์˜ˆ์ œ ์ด๋ฏธ์ง€ ์Šคํƒ€์ผ */
        .example-images {
            gap: 20px;
        }
        
        .example-images .gr-image {
            transition: transform 0.3s ease;
        }
        
        .example-images .gr-image:hover {
            transform: scale(1.02);
        }
        
        /* ๋ผ๋””์˜ค ๋ฒ„ํŠผ ์Šคํƒ€์ผ */
        .gr-radio {
            background: white;
            padding: 15px;
            border-radius: 10px;
            border: 2px solid #e9ecef;
        }
        
        /* LLM ํƒญ ํŠน๋ณ„ ์Šคํƒ€์ผ */
        .llm-tab {
            background: linear-gradient(135deg, #f5f7fa 0%, #ffffff 100%);
            padding: 30px;
            border-radius: 15px;
        }
        
        .llm-input-section {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
        }
        
        /* ๊ฒ€์ƒ‰ ์ •๋ณด ์Šคํƒ€์ผ */
        .search-info {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            margin-top: 10px;
            border-left: 4px solid #667eea;
        }
        
        /* ์ฒดํฌ๋ฐ•์Šค ์Šคํƒ€์ผ */
        .gr-checkbox {
            margin-top: 15px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 8px;
        }
        
        /* ๋ฐ˜์‘ํ˜• ๋””์ž์ธ */
        @media (max-width: 768px) {
            .main-container {
                padding: 15px;
                margin: 10px;
            }
            
            .header-section h1 {
                font-size: 2em;
            }
            
            .gr-tab-item {
                padding: 10px 15px;
                font-size: 1em;
            }
        }
        """
    ) as demo:
        with gr.Column(elem_classes=["main-container"]):
            with gr.Column(elem_classes=["header-section"]):
                gr.Markdown(
                    """
                    # ๐ŸŽจ ChartGPT : AI-Powered Multi Diagram Generator
                    ### based LLM 'Gemma-3-R1984-27B' Model. Powered by VIDraftโšก
                    """
                )

            with gr.Row(variant="panel", elem_classes=["panel-section"]):
                output_format_radio = gr.Radio(
                    choices=["png", "svg"],
                    value="png",
                    label="๐Ÿ“ Output Format",
                    interactive=True
                )

            with gr.Tabs():
                # AI ์–ด์‹œ์Šคํ„ดํŠธ ํƒญ (์ฒซ ๋ฒˆ์งธ)
                with gr.TabItem("๐Ÿค– AI Assistant", elem_classes=["llm-tab"]):
                    gr.Markdown(
                        """
                        ### ๐Ÿ’ก Describe your diagram in Korean or English, and AI will create it for you!
                        """
                    )
                    
                    with gr.Row():
                        with gr.Column(scale=1, elem_classes=["llm-input-section"]):
                            prompt_input = gr.Textbox(
                                placeholder="์˜ˆ: '๋จธ์‹ ๋Ÿฌ๋‹ ํ”„๋กœ์„ธ์Šค๋ฅผ ๋ณด์—ฌ์ฃผ๋Š” ํ”Œ๋กœ์šฐ์ฐจํŠธ๋ฅผ ๋งŒ๋“ค์–ด์ค˜' or 'Create a concept map about climate change'",
                                label="๐Ÿ“ Enter your prompt",
                                lines=3
                            )
                            
                            diagram_type_select = gr.Dropdown(
                                choices=["Concept Map", "Synoptic Chart", "Radial Diagram", "Process Flow", "WBS Diagram"],
                                value="Concept Map",
                                label="๐Ÿ“Š Select Diagram Type",
                                interactive=True
                            )
                            
                            use_search_checkbox = gr.Checkbox(
                                label="๐Ÿ” Use Brave Search to enhance content",
                                value=False,
                                info="Search the web for relevant information to enrich your diagram"
                            )
                            
                            generate_btn = gr.Button("โœจ Generate with AI", variant="primary", size="lg")
                            
                            search_info_output = gr.Textbox(
                                label="๐Ÿ” Search Information",
                                lines=8,
                                interactive=False,
                                visible=False,
                                elem_classes=["search-info"]
                            )
                            
                            generated_json_output = gr.Textbox(
                                label="๐Ÿ“„ Generated JSON",
                                lines=15,
                                interactive=True,
                                visible=True
                            )
                        
                        with gr.Column(scale=2):
                            ai_output_image = gr.Image(
                                label="๐ŸŽจ Generated Diagram",
                                type="filepath",
                                show_download_button=True,
                                height=600
                            )
                    
                    # ๊ฒ€์ƒ‰ ์ฒดํฌ๋ฐ•์Šค ๋ณ€๊ฒฝ ์‹œ ๊ฒ€์ƒ‰ ์ •๋ณด ์ถœ๋ ฅ ํ‘œ์‹œ/์ˆจ๊น€
                    def toggle_search_info(use_search):
                        return gr.update(visible=use_search)
                    
                    use_search_checkbox.change(
                        fn=toggle_search_info,
                        inputs=[use_search_checkbox],
                        outputs=[search_info_output]
                    )
                    
                    generate_btn.click(
                        fn=generate_with_llm,
                        inputs=[prompt_input, diagram_type_select, output_format_radio, use_search_checkbox],
                        outputs=[ai_output_image, generated_json_output, search_info_output]
                    )
                    
                    with gr.Row(elem_classes=["panel-section"]):
                        gr.Examples(
                            examples=[
                                ["Design a process flow diagram that maps every phase of the software development life cycle SDLC from requirements to maintenance and shows handoffs and feedback loops to reduce risk and speed delivery", "Process Flow"],
                                ["Develop a concept map that classifies key types of artificial intelligence symbolic, statistical, neural, hybrid and links each to real world application areas such as healthcare diagnostics, autonomous vehicles, predictive maintenance and generative media to highlight unique capabilities", "Concept Map"],
                                ["Build a work breakdown structure WBS diagram for an online shopping mall project that decomposes scope into clear deliverables and work packages including UX research, responsive front end, secure payment integration, logistics APIs and post launch analytics to align resources and schedules", "WBS Diagram"],
                                ["Create a radial diagram with Renewable Energy at the center and spokes for solar, wind, hydro, geothermal and biomass each annotated with core technologies capacity trends and sustainability impact to underline the diversified portfolio needed for a net zero future", "Radial Diagram"],
                                ["Present a synoptic chart of the machine learning pipeline showing data ingestion, cleansing, feature engineering, model training, validation and deployment with parallel swimlanes for tools compute resources and compliance checkpoints to optimize accuracy and governance", "Synoptic Chart"],
                                ["DevSecOps ๊ฒŒ์ดํŠธ, ์‹ค์‹œ๊ฐ„ KPI ๋Œ€์‹œ๋ณด๋“œ, ์ž๋™ ๋กค๋ฐฑ ๊ฒฝ๋กœ, AI ๊ธฐ๋ฐ˜ ์˜์‚ฌ ๊ฒฐ์ • ๋…ธ๋“œ๋ฅผ ๊ต์ฐจ ๋ฐฐ์น˜ํ•˜์—ฌ ์ง€์†์  ๋”œ๋ฆฌ๋ฒ„๋ฆฌ ์šฐ์ˆ˜์„ฑ์„ ๋ณด์—ฌ์ฃผ๋Š” ์—”ํ„ฐํ”„๋ผ์ด์ฆˆ๊ธ‰ SDLC ํ”„๋กœ์„ธ์Šค ํ”Œ๋กœ์šฐ ์‹œ๊ฐํ™”๋ฅผ ์„ค๊ณ„ํ•˜๋ผ", "Process Flow"],
                                ["๋‰ด๋กœ์‹ฌ๋ณผ๋ฆญ ์ถ”๋ก , ํŒŒ์šด๋ฐ์ด์…˜ ๋ชจ๋ธ, ์—ฃ์ง€ AI, ์ž๊ธฐ ์ง€๋„ ํ•™์Šต๊ณผ ๊ฐ™์€ ์ตœ์ฒจ๋‹จ ํŒจ๋Ÿฌ๋‹ค์ž„์„ ํ•œ๋ฐ ์—ฎ๊ณ  ์ด๋ฅผ ๋ฐ”์ด์˜คํ…Œํฌ, ์Šค๋งˆํŠธ ์‹œํ‹ฐ, ๊ธฐํ›„ ๋ชจ๋ธ๋ง, ๋ชฐ์ž…ํ˜• XR ๋“ฑ ํŒŒ๊ดด์  ํ™œ์šฉ ์‚ฌ๋ก€์™€ ๋™์ ์œผ๋กœ ์—ฐ๊ฒฐํ•˜์—ฌ ์ตœ์ „์„  ํ˜์‹ ์„ ์กฐ๋ช…ํ•˜๋Š” ๋ฐฉ๋Œ€ํ•œ AI ๋ถ„๋ฅ˜ ์ฒด๊ณ„ ์ปจ์…‰๋งต์„ ๊ตฌ์ถ•ํ•˜๋ผ", "Concept Map"],
                                ["๋งˆ์ดํฌ๋กœ์„œ๋น„์Šค, CI/CD ํŒŒ์ดํ”„๋ผ์ธ, ํ—ค๋“œ๋ฆฌ์Šค CMS ํ†ตํ•ฉ, ์ดˆ๊ฐœ์ธํ™” ์ถ”์ฒœ ์—”์ง„ ํŠœ๋‹, ๋ฉ€ํ‹ฐ ํด๋ผ์šฐ๋“œ ํšŒ๋ณตํƒ„๋ ฅ์„ฑ๊นŒ์ง€ ์„ธ๋ถ„ํ™”ํ•˜์—ฌ ์ž‘์—…๋Ÿ‰ ์ถ”์ •๊ณผ ํฌ๋ฆฌํ‹ฐ์ปฌ ํŒจ์Šค ์ƒํ˜ธ ์—ฐ๊ณ„๋ฅผ ์ฃผ์„์œผ๋กœ ๋‹ด์€ ์ฐจ์„ธ๋Œ€ ์˜ด๋‹ˆ์ฑ„๋„ e-์ปค๋จธ์Šค ์ƒํƒœ๊ณ„๋ฅผ ์œ„ํ•œ ์ดˆ์ •๋ฐ€ WBS๋ฅผ ์„ค๊ณ„ํ•˜๋ผ", "WBS Diagram"],
                                ["์žฌ์ƒ์—๋„ˆ์ง€๋ฅผ ์ค‘์‹ฌ์œผ๋กœ ๋‹ค์ธต ๋ฐฉ์‚ฌํ˜• ๋‹ค์ด์–ด๊ทธ๋žจ์„ ๊ทธ๋ฆฌ๋˜, ๋ฐœ์ „ยท์ €์žฅยท์†ก๋ฐฐ์ „ยท์ •์ฑ… ์ˆ˜๋‹จ์„ ๋™์‹ฌ์›์œผ๋กœ ๋ฐฐ์น˜ํ•˜๊ณ , ํƒœ์–‘๊ด‘ PV, CSP, ํ•ด์ƒ ๋ฐ ์œก์ƒํ’๋ ฅ, ์กฐ๋ ฅ, ๊ทธ๋ฆฐ ์ˆ˜์†Œ, ์ฐจ์„ธ๋Œ€ ๋ฐฐํ„ฐ๋ฆฌ ํ™”ํ•™, ์Šค๋งˆํŠธ ๊ทธ๋ฆฌ๋“œ AI๋ฅผ ์Šคํฌํฌ๋กœ ์—ฐ๊ฒฐํ•˜๋ฉฐ, LCOE ์ถ”์„ธ์™€ ํƒ„์†Œ ์ƒ์‡„ ์‹œ๋‚˜๋ฆฌ์˜ค๋ฅผ ์ฃผ์„์œผ๋กœ ํ‘œ๊ธฐํ•˜๋ผ", "Radial Diagram"],
                                ["๋ฐ์ดํ„ฐ ์ถœ์ฒ˜, ์ž๋™ํ™”๋œ ํ”ผ์ฒ˜ ์Šคํ† ์–ด, ์—ฐํ•ฉ ํ•™์Šต ์˜ค์ผ€์ŠคํŠธ๋ ˆ์ด์…˜, ๋ชจ๋ธ ์„ฑ๋Šฅ ๋“œ๋ฆฌํ”„ํŠธ ๊ฐ์ง€, ์„€๋„ ๋ฐฐํฌ ์บ๋„ˆ๋ฆฌ, ์œค๋ฆฌ ์ค€์ˆ˜ ๊ฐ์‚ฌ์˜ ์‹œ๊ฐ„ ์ถ• ๋ ˆ์ธ์„ ๋ณ‘์น˜ํ•˜๊ณ , ๊ฒŒ์ดํŠธ ๊ธฐ์ค€๊ณผ ๋กค๋ฐฑ ํŠธ๋ฆฌ๊ฑฐ๊นŒ์ง€ ๊ฐ–์ถ˜ ํ”„๋กœ๋•์…˜๊ธ‰ ๋จธ์‹ ๋Ÿฌ๋‹ ํŒŒ์ดํ”„๋ผ์ธ์„ ์˜ํ™”์  ์‹œ์•ผ๋กœ ๋ฌ˜์‚ฌํ•œ ์‹œ๋†‰ํ‹ฑ ์ฐจํŠธ๋ฅผ ์ œ์ž‘ํ•˜๋ผ", "Synoptic Chart"]
                            ],
                            inputs=[prompt_input, diagram_type_select],
                            label="๐Ÿ’ญ Example Prompts"
                        )

                # ๊ธฐ์กด ํƒญ๋“ค
                with gr.TabItem("๐Ÿ—บ๏ธ Concept Map"):
                    with gr.Row():
                        with gr.Column(scale=1, elem_classes=["panel-section"]):
                            json_input_cm = gr.Textbox(
                                value=CONCEPT_MAP_JSON,
                                placeholder="Paste JSON following the documented format",
                                label="JSON Input",
                                lines=20
                            )
                            submit_btn_cm = gr.Button("Generate Concept Map", variant="primary")
                        
                        with gr.Column(scale=2):
                            output_cm = gr.Image(
                                label="Generated Diagram",
                                type="filepath",
                                show_download_button=True,
                                height=500
                            )
                    
                    submit_btn_cm.click(
                        fn=generate_concept_map, 
                        inputs=[json_input_cm, output_format_radio], 
                        outputs=output_cm
                    )
                    
                    gr.Markdown("## ๐Ÿ“ธ Examples")
                    with gr.Row(elem_classes=["example-images"]):
                        gr.Image(value="./images/cm1.svg", label="Sample 1", show_label=True, interactive=False)
                        gr.Image(value="./images/cm2.svg", label="Sample 2", show_label=True, interactive=False)

                with gr.TabItem("๐Ÿ“Š Synoptic Chart"):
                    with gr.Row():
                        with gr.Column(scale=1, elem_classes=["panel-section"]):
                            json_input_sc = gr.Textbox(
                                value=SYNOPTIC_CHART_JSON,
                                placeholder="Paste JSON following the documented format",
                                label="JSON Input",
                                lines=20
                            )
                            submit_btn_sc = gr.Button("Generate Synoptic Chart", variant="primary")
                        
                        with gr.Column(scale=2):
                            output_sc = gr.Image(
                                label="Generated Diagram",
                                type="filepath",
                                show_download_button=True,
                                height=500
                            )
                    
                    submit_btn_sc.click(
                        fn=generate_synoptic_chart, 
                        inputs=[json_input_sc, output_format_radio], 
                        outputs=output_sc
                    )
                    
                    gr.Markdown("## ๐Ÿ“ธ Examples")
                    with gr.Row(elem_classes=["example-images"]):
                        gr.Image(value="./images/sc1.svg", label="Sample 1", show_label=True, interactive=False)
                        gr.Image(value="./images/sc2.svg", label="Sample 2", show_label=True, interactive=False)

                with gr.TabItem("โ˜€๏ธ Radial Diagram"):
                    with gr.Row():
                        with gr.Column(scale=1, elem_classes=["panel-section"]):
                            json_input_rd = gr.Textbox(
                                value=RADIAL_DIAGRAM_JSON,
                                placeholder="Paste JSON following the documented format",
                                label="JSON Input",
                                lines=20
                            )
                            submit_btn_rd = gr.Button("Generate Radial Diagram", variant="primary")
                        
                        with gr.Column(scale=2):
                            output_rd = gr.Image(
                                label="Generated Diagram",
                                type="filepath",
                                show_download_button=True,
                                height=500
                            )
                    
                    submit_btn_rd.click(
                        fn=generate_radial_diagram, 
                        inputs=[json_input_rd, output_format_radio], 
                        outputs=output_rd
                    )
                    
                    gr.Markdown("## ๐Ÿ“ธ Examples")
                    with gr.Row(elem_classes=["example-images"]):
                        gr.Image(value="./images/rd1.svg", label="Sample 1", show_label=True, interactive=False)
                        gr.Image(value="./images/rd2.svg", label="Sample 2", show_label=True, interactive=False)
                        gr.Image(value="./images/rd3.svg", label="Sample 3", show_label=True, interactive=False)
                        gr.Image(value="./images/rd4.svg", label="Sample 4", show_label=True, interactive=False)

                with gr.TabItem("๐Ÿ”„ Process Flow"):
                    with gr.Row():
                        with gr.Column(scale=1, elem_classes=["panel-section"]):
                            json_input_pf = gr.Textbox(
                                value=PROCESS_FLOW_JSON,
                                placeholder="Paste JSON following the documented format",
                                label="JSON Input",
                                lines=20
                            )
                            submit_btn_pf = gr.Button("Generate Process Flow", variant="primary")
                        
                        with gr.Column(scale=2):
                            output_pf = gr.Image(
                                label="Generated Diagram",
                                type="filepath",
                                show_download_button=True,
                                height=500
                            )
                    
                    submit_btn_pf.click(
                        fn=generate_process_flow_diagram, 
                        inputs=[json_input_pf, output_format_radio], 
                        outputs=output_pf
                    )
                    
                    gr.Markdown("## ๐Ÿ“ธ Examples")
                    with gr.Row(elem_classes=["example-images"]):
                        gr.Image(value="./images/pf1.svg", label="Sample 1", show_label=True, interactive=False)
                        gr.Image(value="./images/pf2.svg", label="Sample 2", show_label=True, interactive=False)

                with gr.TabItem("๐Ÿ“‹ WBS Diagram"):
                    with gr.Row():
                        with gr.Column(scale=1, elem_classes=["panel-section"]):
                            json_input_wbs = gr.Textbox(
                                value=WBS_DIAGRAM_JSON,
                                placeholder="Paste JSON following the documented format",
                                label="JSON Input",
                                lines=20
                            )
                            submit_btn_wbs = gr.Button("Generate WBS Diagram", variant="primary")
                        
                        with gr.Column(scale=2):
                            output_wbs = gr.Image(
                                label="Generated Diagram",
                                type="filepath",
                                show_download_button=True,
                                height=500
                            )
                    
                    submit_btn_wbs.click(
                        fn=generate_wbs_diagram, 
                        inputs=[json_input_wbs, output_format_radio], 
                        outputs=output_wbs
                    )
                    
                    gr.Markdown("## ๐Ÿ“ธ Examples")
                    with gr.Row(elem_classes=["example-images"]):
                        gr.Image(value="./images/wd1.svg", label="Sample 1", show_label=True, interactive=False)
                        gr.Image(value="./images/wd2.svg", label="Sample 2", show_label=True, interactive=False)
    
    demo.launch(
        mcp_server=True,
        share=False,
        server_port=7860,
        server_name="0.0.0.0"
    )