File size: 35,702 Bytes
40cb993
 
 
 
 
52f088b
4632401
c904043
40cb993
0f6dead
 
 
40cb993
2441c57
 
40cb993
99c97cb
 
0f6dead
2755a97
 
52f088b
2755a97
 
447034b
 
b1eedcd
2d3dbef
447034b
 
 
 
2755a97
9724b7e
ef73841
94459ae
0f6dead
c5aa224
 
 
 
 
0f6dead
52f088b
 
cf417b8
0f6dead
 
 
ea04e61
 
 
0f6dead
ea04e61
 
 
cf417b8
ea04e61
99c97cb
40cb993
0f6dead
 
 
e15465f
0f6dead
 
 
 
8ee600c
 
0f6dead
8ee600c
 
e15465f
eb924c7
110a358
e15465f
110a358
 
e15465f
 
bc975f4
e15465f
 
110a358
 
bc975f4
 
 
ed0e29b
 
5422ee0
ed0e29b
 
5422ee0
 
e15465f
 
 
 
 
 
 
 
 
 
5422ee0
 
 
 
 
 
 
 
 
 
 
 
e15465f
 
 
 
 
 
 
 
 
 
2755a97
5422ee0
 
 
 
e15465f
0f6dead
 
 
f8e9052
0f6dead
 
 
f304ca1
08bf22a
0f6dead
 
f8e9052
 
0f6dead
f8e9052
0f6dead
 
f8e9052
0f6dead
 
 
 
f304ca1
08bf22a
0f6dead
 
f8e9052
 
0f6dead
 
0dbb7a7
e15465f
eb924c7
 
e15465f
eb924c7
ed0e29b
e15465f
eb924c7
 
e15465f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb924c7
f304ca1
 
 
 
 
 
 
 
 
eb924c7
 
 
5422ee0
 
e15465f
5422ee0
 
 
 
 
e15465f
5422ee0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed0e29b
5422ee0
e15465f
5422ee0
 
 
 
e15465f
eb924c7
0f6dead
e15465f
 
c4886db
0f6dead
e15465f
 
c4886db
2755a97
0f6dead
 
 
 
 
 
2755a97
0f6dead
 
2755a97
0f6dead
 
2755a97
 
0f6dead
 
 
2755a97
 
0f6dead
 
 
 
 
 
2755a97
 
0f6dead
2755a97
0f6dead
2755a97
 
 
0f6dead
0dbb7a7
a9835a6
cf417b8
7db1459
cf417b8
9ac6adf
fffddf5
 
7db1459
fffddf5
 
0f6dead
2441c57
0f6dead
ed0e29b
 
0f6dead
ed0e29b
 
2441c57
0f6dead
903eee1
2755a97
ed0e29b
7db1459
0f6dead
903eee1
 
0f6dead
 
72cded0
ed0e29b
 
 
d0879fb
 
a9835a6
d0879fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58b3f67
d0879fb
0f6dead
93269d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7db1459
 
 
 
a9835a6
342f4f1
 
a9835a6
 
7db1459
 
 
a9835a6
 
 
c4ca859
2755a97
0f6dead
e3453d8
314d1bf
9ac6adf
 
d0879fb
fe0bdf5
7db1459
a9835a6
e1c51a9
fe0bdf5
1de5296
ed0e29b
 
 
1de5296
 
 
 
7db1459
 
 
 
 
 
1de5296
7db1459
1de5296
7db1459
 
bfd3483
 
 
 
 
 
 
 
 
 
 
1de5296
 
 
bfd3483
 
 
1de5296
 
bfd3483
1de5296
 
bfd3483
 
fe0bdf5
1de5296
 
7db1459
a9835a6
0f6dead
1de5296
 
a37dc2c
1928550
 
a9835a6
ed0e29b
 
 
 
 
 
 
32fae78
 
f7b9851
 
32fae78
 
 
 
a9835a6
 
7fb424b
1e0ab64
 
 
 
 
 
 
 
 
 
 
 
32fae78
1e0ab64
 
 
7fb424b
1e0ab64
 
 
 
 
 
 
 
 
 
 
7fb424b
1e0ab64
a9835a6
 
1e0ab64
a9835a6
1de5296
 
a9835a6
32fae78
 
 
1de5296
a9835a6
 
a6e231f
1e0ab64
140bea6
 
 
 
b4cc81b
 
a9835a6
 
6237bd0
a9835a6
 
 
1de5296
a9835a6
 
ed0e29b
 
 
a9835a6
 
 
 
 
ed0e29b
 
e1c51a9
 
 
ed0e29b
1de5296
 
 
314d1bf
 
327f103
1de5296
 
 
a9835a6
 
1de5296
255579c
 
 
 
ed0e29b
 
 
 
 
 
 
 
1928550
1de5296
1928550
ed0e29b
1928550
ed0e29b
cf417b8
859ac8f
ba2b3e2
 
 
cf417b8
52f088b
40cb993
65e5e12
23058b1
 
 
 
e15465f
1e38aeb
83cd553
a895315
ba2b3e2
 
1e38aeb
23058b1
 
f8e9052
 
e15465f
1e38aeb
83cd553
1e38aeb
ba2b3e2
 
4164d80
a895315
 
e1c51a9
 
a895315
 
447034b
d2dfd57
f8e9052
 
ed0e29b
e15465f
f8e9052
ed0e29b
 
1928550
a5b5de7
e15465f
 
 
a5b5de7
1928550
f8e9052
e1c51a9
 
 
 
 
 
 
255579c
 
 
 
 
e1c51a9
f8e9052
4a57354
1928550
e15465f
 
d2dfd57
0f6dead
 
 
 
84051ff
83cd553
 
 
11cdd15
ba2b3e2
c0dcd8b
ba2b3e2
83cd553
36eb37f
4a57354
 
 
 
 
 
 
 
 
 
5edde8f
4a57354
 
 
 
d3b3ec9
fe0bdf5
2755a97
4a57354
 
 
58d2771
a10f44a
58d2771
5edde8f
4a57354
 
 
 
 
 
f357a71
 
 
 
4a57354
 
 
 
 
 
 
 
9724b7e
 
 
 
 
 
 
4a57354
 
 
 
 
 
 
 
 
 
 
9724b7e
4a57354
 
9724b7e
 
9c229ce
f1ddbf7
9724b7e
003bf04
 
 
 
4164d80
08730ad
a895315
08730ad
ce9eaa9
 
e1c51a9
08730ad
a895315
08730ad
 
 
ce9eaa9
719dcc1
0f6dead
84051ff
 
 
52f2903
84051ff
50b914a
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
import gradio as gr
import sqlite3
import pandas as pd
import os
import re
import base64
import difflib
import traceback

# ==========================================
# 1. Environment Setup & Data Helpers
# ==========================================
UPLOAD_DIR = "uploaded_dbs"
if not os.path.exists(UPLOAD_DIR):
    os.makedirs(UPLOAD_DIR)

db_registry = []

def convert_blob_to_html_img(blob_data):
    if blob_data is None or pd.isna(blob_data):
        return ""
    try:
        if isinstance(blob_data, (bytes, bytearray)):
            encoded = base64.b64encode(blob_data).decode('utf-8')
            return f'''
            <img src="data:image/png;base64,{encoded}"
                 style="width: 40%; 
                        max-height: 300px; 
                        object-fit: contain;
                        display: block;
                        margin: 10px 0;">
            '''
        return str(blob_data)
    except Exception:
        return str(blob_data)

def decode_sqlite_text(x):
    try:
        return x.decode('utf-8')
    except UnicodeDecodeError:
        return x

def fetch_available_standards():
    global db_registry
    db_registry = []

    for file_name in os.listdir(UPLOAD_DIR):
        if file_name.endswith(".db"):
            name = file_name.replace(".db", "")
            parts = name.split("_")
            if len(parts) >= 2:
                db_registry.append({
                    "path": os.path.join(UPLOAD_DIR, file_name),
                    "standard": parts[0],
                    "version": parts[1]
                })

    return sorted(list(set([d["standard"] for d in db_registry])))


# ==========================================
# 2. UI Component Handlers
# ==========================================

def load_initial_standards():
    return gr.Dropdown(choices=fetch_available_standards())

def update_version_dropdown(standard):
    if not standard:
        return gr.Dropdown(choices=[])
    versions = sorted(set(d["version"] for d in db_registry if d["standard"] == standard))
    return gr.Dropdown(choices=versions)

# โฌ‡๏ธ [์ˆ˜์ •] Version์ด ์„ ํƒ๋˜๋ฉด Category์™€ ํ•จ๊ป˜ Status ๊ฐ’๋„ ๊ฐ™์ด ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.
def update_base_category_dropdown(standard, version):
    if not standard or not version:
        return gr.update(choices=[], value=None, interactive=False), gr.update(value="")

    choices = ["ALL"]
    status_value = "" # Status ๊ธฐ๋ณธ๊ฐ’
    
    db_path = os.path.join(UPLOAD_DIR, f"{standard}_{version}.db")
    if not os.path.exists(db_path): 
        return gr.update(choices=choices), gr.update(value="")

    try:
        conn = sqlite3.connect(db_path)
        tables = pd.read_sql("SELECT name FROM sqlite_master WHERE type='table';", conn)['name'].tolist()
        
        valid_tables = [t for t in tables if t.lower() not in ['mapping_registry', 'mapping_table', 'table_config', 'sqlite_sequence']]
        
        main_table = f"{standard}_{version}"
        if main_table not in valid_tables:
            main_table = valid_tables[0] if valid_tables else None

        if main_table:
            # ๐Ÿ’ก [ํ•ต์‹ฌ ์ถ”๊ฐ€] DB์—์„œ Status ๊ฐ’์„ ์ฝ์–ด์˜ต๋‹ˆ๋‹ค.
            try:
                cols_check = pd.read_sql(f"PRAGMA table_info([{main_table}])", conn)['name'].tolist()
                if "Status" in cols_check or "status" in cols_check:
                    status_df = pd.read_sql(f"SELECT Status FROM [{main_table}] WHERE Status IS NOT NULL AND Status != '' LIMIT 1", conn)
                    if not status_df.empty:
                        status_value = str(status_df.iloc[0]['Status'])
            except Exception:
                pass

            cols = pd.read_sql(f"PRAGMA table_info([{main_table}])", conn)['name'].tolist()
            lower_cols = [c.lower() for c in cols]
            if 'chapter' in lower_cols and 'category' in lower_cols:
                ch_col = cols[lower_cols.index('chapter')]
                ca_col = cols[lower_cols.index('category')]
                
                df = pd.read_sql(f"SELECT DISTINCT [{ch_col}], [{ca_col}] FROM [{main_table}]", conn)
                for _, row in df.iterrows():
                    ch = str(row[ch_col]).strip()
                    ca = str(row[ca_col]).strip()
                    if ch and ca and ch.lower() not in ['none', 'nan'] and ca.lower() not in ['none', 'nan']:
                        choices.append(f"{ch}.{ca}")

        pattern = re.compile(f"^{standard}[_\\s-]*{version}[_\\s-]*", re.IGNORECASE)
        for t in valid_tables:
            if t == main_table: continue
            short_name = pattern.sub("", t).strip(" _")
            if short_name and short_name not in choices:
                choices.append(short_name)
            elif t not in choices:
                choices.append(t)

        conn.close()
    except Exception: 
        import traceback
        traceback.print_exc()
        
    return gr.update(choices=choices, value=None, interactive=True), gr.update(value=status_value)

def update_comp_standard_dropdown(base_std, base_ver):
    if not base_std or not base_ver:
        return gr.Dropdown(choices=[], value=None, interactive=False)

    try:
        conn = sqlite3.connect(os.path.join(UPLOAD_DIR, "mapping.db"))
        query = "SELECT DISTINCT TRIM(Comp_std) AS Comp_std FROM Mapping_registry WHERE TRIM(Base_std)=TRIM(?) AND TRIM(Base_ver)=TRIM(?)"
        df = pd.read_sql(query, conn, params=[base_std, base_ver])
        conn.close()

        mapped_stds = sorted(df['Comp_std'].dropna().unique().tolist()) if not df.empty else []
        return gr.update(choices=mapped_stds, value=None, interactive=bool(mapped_stds))
    except Exception:
        return gr.update(choices=[], value=None, interactive=False)

def update_comp_version_dropdown(base_std, base_ver, comp_std):
    if not all([base_std, base_ver, comp_std]):
        return gr.update(choices=[], value=None, interactive=False)

    try:
        conn = sqlite3.connect(os.path.join(UPLOAD_DIR, "mapping.db"))
        query = "SELECT DISTINCT TRIM(Comp_ver) AS Comp_ver FROM Mapping_registry WHERE TRIM(Base_std)=TRIM(?) AND TRIM(Base_ver)=TRIM(?) AND TRIM(Comp_std)=TRIM(?)"
        df = pd.read_sql(query, conn, params=[base_std, base_ver, comp_std])
        conn.close()

        mapped_vers = sorted(df['Comp_ver'].dropna().unique().tolist()) if not df.empty else []
        return gr.update(choices=mapped_vers, value=None, interactive=bool(mapped_vers))
    except Exception:
        return gr.update(choices=[], value=None, interactive=False)

# โฌ‡๏ธ [์ˆ˜์ •] ๋น„๊ต ๋ฒ•๊ทœ์—์„œ๋„ Category ๊ฐฑ์‹  ์‹œ Status๋ฅผ ์ฝ์–ด์˜ต๋‹ˆ๋‹ค.
def update_comp_category_dropdown(base_std, base_ver, base_cat, comp_std, comp_ver):
    if not all([base_std, base_ver, base_cat, comp_std, comp_ver]):
        return gr.update(choices=[], value=None, interactive=False), gr.update(value="")

    base_type = "Main" if not base_cat or base_cat == "ALL" or "." in base_cat else base_cat
    status_value = ""

    try:
        # Status ์ฝ๊ธฐ
        comp_db_path = os.path.join(UPLOAD_DIR, f"{comp_std}_{comp_ver}.db")
        if os.path.exists(comp_db_path):
            c_conn = sqlite3.connect(comp_db_path)
            c_tables = pd.read_sql("SELECT name FROM sqlite_master WHERE type='table';", c_conn)['name'].tolist()
            c_valid_tables = [t for t in c_tables if t.lower() not in ['mapping_registry', 'mapping_table', 'table_config', 'sqlite_sequence']]
            c_main_table = f"{comp_std}_{comp_ver}"
            if c_main_table not in c_valid_tables:
                c_main_table = c_valid_tables[0] if c_valid_tables else None
            
            if c_main_table:
                try:
                    cols_check = pd.read_sql(f"PRAGMA table_info([{c_main_table}])", c_conn)['name'].tolist()
                    if "Status" in cols_check or "status" in cols_check:
                        status_df = pd.read_sql(f"SELECT Status FROM [{c_main_table}] WHERE Status IS NOT NULL AND Status != '' LIMIT 1", c_conn)
                        if not status_df.empty:
                            status_value = str(status_df.iloc[0]['Status'])
                except Exception:
                    pass

        conn = sqlite3.connect(os.path.join(UPLOAD_DIR, "mapping.db"))
        query = """
        SELECT DISTINCT TRIM(Comp_Type) AS Comp_Type 
        FROM Mapping_registry 
        WHERE TRIM(Base_std)=TRIM(?) 
          AND TRIM(Base_ver)=TRIM(?) 
          AND TRIM(Base_Type)=TRIM(?) 
          AND TRIM(Comp_std)=TRIM(?) 
          AND TRIM(Comp_ver)=TRIM(?)
        """
        df = pd.read_sql(query, conn, params=[base_std, base_ver, base_type, comp_std, comp_ver])
        conn.close()

        allowed_types = df['Comp_Type'].dropna().tolist()
        if not allowed_types:
            return gr.update(choices=[], value=None), gr.update(value=status_value)

        final_choices = []
        if "Main" in allowed_types:
            final_choices.append("ALL")
            if os.path.exists(comp_db_path):
                # c_conn is already closed above, reopen if needed
                c_conn = sqlite3.connect(comp_db_path)
                if c_main_table:
                    cols = pd.read_sql(f"PRAGMA table_info([{c_main_table}])", c_conn)['name'].tolist()
                    lower_cols = [c.lower() for c in cols]
                    if 'chapter' in lower_cols and 'category' in lower_cols:
                        ch_col = cols[lower_cols.index('chapter')]
                        ca_col = cols[lower_cols.index('category')]
                        
                        c_df = pd.read_sql(f"SELECT DISTINCT [{ch_col}], [{ca_col}] FROM [{c_main_table}]", c_conn)
                        for _, row in c_df.iterrows():
                            ch = str(row[ch_col]).strip()
                            ca = str(row[ca_col]).strip()
                            if ch and ca and ch.lower() not in ['none', 'nan'] and ca.lower() not in ['none', 'nan']:
                                final_choices.append(f"{ch}.{ca}")
                c_conn.close()
        
        for t in allowed_types:
            if t != "Main": final_choices.append(t)

        return gr.update(choices=final_choices, value=final_choices[0] if final_choices else None, interactive=True), gr.update(value=status_value)
        
    except Exception as e:
        import traceback
        traceback.print_exc()
        return gr.update(choices=[], value=None), gr.update(value="")

def reset_base_selections():
    # Status๊นŒ์ง€ 4๊ฐœ๋ฅผ ๋ฆฌ์…‹
    return gr.update(value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(value="")

def reset_comp_selections():
    # Status๊นŒ์ง€ 4๊ฐœ๋ฅผ ๋ฆฌ์…‹
    return gr.update(value=None), gr.update(choices=[], value=None), gr.update(choices=[], value=None), gr.update(value="")


# ==========================================
# 3. Core Logic & Data Processing
# ==========================================
def generate_html_diff(base_text, comp_text):
    base_text = "" if pd.isna(base_text) else str(base_text)
    comp_text = "" if pd.isna(comp_text) else str(comp_text)

    b_words = base_text.split()
    c_words = comp_text.split()

    diff_generator = list(difflib.ndiff(b_words, c_words))
    b_result, c_result = [], []
    i = 0

    while i < len(diff_generator):
        code = diff_generator[i][0]
        word = diff_generator[i][2:]

        if code == ' ':
            b_result.append(word)
            c_result.append(word)
        elif code == '-' and i+1 < len(diff_generator) and diff_generator[i+1][0] == '+':
            new_word = diff_generator[i+1][2:]
            b_result.append(f"<span style='color:#ff4d4f;font-weight:600'>{word}</span>")
            c_result.append(f"<span style='color:#ff4d4f;font-weight:600'>{new_word}</span>")
            i += 1
        elif code == '-':
            b_result.append(f"<span style='color:#ff4d4f;font-weight:600'>{word}</span>")
        elif code == '+':
            c_result.append(f"<span style='color:#2ecc71;font-weight:600'>{word}</span>")

        i += 1

    return " ".join(b_result), " ".join(c_result)

def fetch_database_records(standard, version, selection, table_type):
    if not all([standard, version, selection]):
        return pd.DataFrame({"Info": ["์„ ํƒ ํ•„์š”"]}), []

    try:
        db_path = os.path.join(UPLOAD_DIR, f"{standard}_{version}.db")
        if not os.path.exists(db_path):
            return pd.DataFrame({"Error": [f"ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค: {db_path}"]}), []
            
        conn = sqlite3.connect(db_path)
        conn.text_factory = decode_sqlite_text 

        tables = pd.read_sql("SELECT name FROM sqlite_master WHERE type='table';", conn)['name'].tolist()
        valid_tables = [t for t in tables if t.lower() not in ['mapping_registry', 'mapping_table', 'table_config', 'sqlite_sequence']]
        
        main_table = f"{standard}_{version}"
        if main_table not in valid_tables:
            main_table = valid_tables[0] if valid_tables else None

        target_table = None
        pattern = re.compile(f"^{standard}[_\\s-]*{version}[_\\s-]*", re.IGNORECASE)

        for t in valid_tables:
            if t == selection or pattern.sub("", t).strip(" _") == selection:
                target_table = t
                break

        if target_table and target_table != main_table:
            df = pd.read_sql(f"SELECT * FROM [{target_table}]", conn)
        else:
            if not main_table:
                return pd.DataFrame({"Error": ["๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋‚ด์—์„œ ๋ฉ”์ธ ํ…Œ์ด๋ธ”์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."]}), []
                
            cursor = conn.cursor()
            cursor.execute(f"PRAGMA table_info([{main_table}])")
            cols = [c[1] for c in cursor.fetchall()]
            lower_cols = [c.lower().strip() for c in cols]

            real_ch, real_cat = None, None
            for c, lc in zip(cols, lower_cols):
                if lc == "chapter": real_ch = c
                elif lc == "category": real_cat = c

            if selection == "ALL":
                cursor.execute(f"SELECT * FROM [{main_table}]")
            elif "." in selection and real_ch and real_cat:
                ch, ca = selection.split(".", 1)
                query = f"SELECT * FROM [{main_table}] WHERE REPLACE(TRIM(CAST([{real_ch}] AS TEXT)), ' ', '') = ? AND REPLACE(TRIM(CAST([{real_cat}] AS TEXT)), ' ', '') = ?"
                cursor.execute(query, (ch.replace(" ", ""), ca.replace(" ", "")))
            else:
                cursor.execute(f"SELECT * FROM [{main_table}]")
            
            df = pd.DataFrame(cursor.fetchall(), columns=cols)

        df = df.drop(columns=[c for c in df.columns if c.lower() == "version"], errors="ignore")
        
        # =========================================================
        # ๐Ÿ’ก [์Šค๋งˆํŠธ ์Šค์บ” ๋กœ์ง] DB ์ปฌ๋Ÿผ์„ ๋ณด๊ณ  ๋งž๋Š” Main ์„ค์ •์„ ์•Œ์•„์„œ ์ฐพ์Šต๋‹ˆ๋‹ค.
        # =========================================================
        conn_map = sqlite3.connect(os.path.join(UPLOAD_DIR, "mapping.db"))
        config_df = pd.read_sql("SELECT Anchor_Column, Display_Columns FROM Table_Config WHERE Table_Type=?", conn_map, params=[table_type])
        conn_map.close()

        anchor_col_config = "Section"
        display_setting = "Description"

        if not config_df.empty:
            df_cols_lower = [c.lower() for c in df.columns]
            for _, row in config_df.iterrows():
                # DB์— ์ ํžŒ Anchor ์—ด์ด ์‹ค์ œ ๋ฐ์ดํ„ฐํ”„๋ ˆ์ž„์— ์กด์žฌํ•˜๋Š”์ง€ ํ™•์ธ
                first_anchor = str(row['Anchor_Column']).split(',')[0].strip().lower()
                if first_anchor in df_cols_lower:
                    anchor_col_config = str(row['Anchor_Column'])
                    raw_disp = row['Display_Columns']
                    display_setting = str(raw_disp) if pd.notna(raw_disp) and str(raw_disp).strip() != "" else None
                    break
        # =========================================================

        anchor_cols_config = [x.strip() for x in anchor_col_config.split(',')]

        real_anchors = []
        for ac in anchor_cols_config:
            real_ac = next((c for c in df.columns if c.lower() == ac.lower()), ac)
            real_anchors.append(real_ac)

        if display_setting:
            cols_to_show = [c.strip() for c in display_setting.split(',')]
            actual_cols_to_show = [c for c in df.columns if next((True for req in cols_to_show if c.lower() == req.lower()), False)]
            
            for ra in reversed(real_anchors):
                if ra in df.columns and ra not in actual_cols_to_show:
                    actual_cols_to_show.insert(0, ra)
            
            if actual_cols_to_show:
                df = df[actual_cols_to_show]

        for col in df.columns:
            df[col] = df[col].apply(convert_blob_to_html_img)

        return df, real_anchors 

    except Exception as e:
        import traceback
        traceback.print_exc()
        return pd.DataFrame({"Error": [str(e)]}), []

def execute_unified_search(base_std, base_ver, base_cat, comp_std, comp_ver, comp_cat, mapped_only, diff_only):
    try:
        def get_type_by_cat(cat):
            if not cat or cat == "ALL": return "Main"
            if "." in cat: return "Main"
            return cat

        type_b = get_type_by_cat(base_cat)
        type_c = get_type_by_cat(comp_cat)
        
        def apply_visual_merge(df, cols):
            if not df.empty and len(cols) > 1:
                is_dup = pd.Series([True] * len(df), index=df.index)
                for col in cols:
                    if col in df.columns:
                        curr = df[col].astype(str).str.strip()
                        match = (curr == curr.shift(1)) & (~curr.isin(["", "nan", "None", "&nbsp;"]))
                        is_dup = is_dup & match
                        df.loc[is_dup, col] = "&nbsp;"
            return df

        def combine_code_desc(df):
            cols = list(df.columns)
            new_cols = []
            processed = set()
            for col in cols:
                if col in processed: continue
                if "_Code" in col:
                    desc_col = col.replace("_Code", "_Description")
                    if desc_col in cols:
                        new_col_name = col.replace("_Code", "")
                        def combine_cells(row):
                            c, d = str(row[col]).strip(), str(row[desc_col]).strip()
                            if c in ["nan", "None", "", "&nbsp;"]: return d
                            if d in ["nan", "None", "", "&nbsp;"]: return f"<span style='font-weight:bold; color:#1a73e8;'>{c}</span>"
                            return f"<span style='font-weight:bold; color:#1a73e8; display:block; margin-bottom:4px;'>{c}</span>{d}"
                        df[new_col_name] = df.apply(combine_cells, axis=1)
                        new_cols.append(new_col_name)
                        processed.update([col, desc_col])
                    else: new_cols.append(col)
                elif "_Description" in col:
                    if col.replace("_Description", "_Code") not in cols: new_cols.append(col)
                else: new_cols.append(col)
            return df[new_cols]

        if base_std and base_ver and base_cat and (not comp_std or not comp_ver or not comp_cat):
            df, _ = fetch_database_records(base_std, base_ver, base_cat, type_b)
            if "Error" in df.columns: return df
            return apply_visual_merge(df, df.columns)

        if all([base_std, base_ver, base_cat, comp_std, comp_ver, comp_cat]):
            df_base, real_anchors_b = fetch_database_records(base_std, base_ver, base_cat, type_b)
            df_comp, real_anchors_c = fetch_database_records(comp_std, comp_ver, comp_cat, type_c)

            if "Error" in df_base.columns: return df_base
            if "Error" in df_comp.columns: return df_comp

            for ra in real_anchors_b:
                if ra not in df_base.columns: 
                    return pd.DataFrame({"Error": [f"๊ธฐ์ค€ ์—ด(Anchor) '{ra}'์ด(๊ฐ€) ๊ธฐ์ค€ ๋ฐ์ดํ„ฐ์— ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. Table_Config๋ฅผ ํ™•์ธํ•˜์„ธ์š”."]})
            for ra in real_anchors_c:
                if ra not in df_comp.columns: 
                    return pd.DataFrame({"Error": [f"๋น„๊ต ์—ด(Anchor) '{ra}'์ด(๊ฐ€) ๋น„๊ต ๋ฐ์ดํ„ฐ์— ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. Table_Config๋ฅผ ํ™•์ธํ•˜์„ธ์š”."]})

            def clean_key_val(v):
                s = str(v).strip()
                if s.endswith('.0') and s[:-2].isdigit(): 
                    s = s[:-2]
                return s.replace(" ", "")

            df_base['merge_key'] = df_base[real_anchors_b].apply(lambda row: '-'.join([clean_key_val(x) for x in row]), axis=1)
            df_comp['merge_key'] = df_comp[real_anchors_c].apply(lambda row: '-'.join([clean_key_val(x) for x in row]), axis=1)

            conn_map = sqlite3.connect(os.path.join(UPLOAD_DIR, "mapping.db"))
            
            q_fw = "SELECT * FROM Mapping_table WHERE TRIM(Base_std)=? AND TRIM(Base_ver)=? AND TRIM(Comp_std)=? AND TRIM(Comp_ver)=?"
            df_fw = pd.read_sql(q_fw, conn_map, params=[base_std.strip(), base_ver.strip(), comp_std.strip(), comp_ver.strip()])
            
            q_rv = "SELECT * FROM Mapping_table WHERE TRIM(Comp_std)=? AND TRIM(Comp_ver)=? AND TRIM(Base_std)=? AND TRIM(Base_ver)=?"
            df_rv = pd.read_sql(q_rv, conn_map, params=[base_std.strip(), base_ver.strip(), comp_std.strip(), comp_ver.strip()])
            conn_map.close()

            cols_fw_lower = {c.lower(): c for c in df_fw.columns}
            
            if 'base_type' in cols_fw_lower and 'comp_type' in cols_fw_lower:
                b_col = cols_fw_lower['base_type']
                c_col = cols_fw_lower['comp_type']
                
                df_fw[b_col] = df_fw[b_col].fillna('Main').astype(str).str.strip().str.upper()
                df_fw[c_col] = df_fw[c_col].fillna('Main').astype(str).str.strip().str.upper()
                df_fw = df_fw[(df_fw[b_col] == type_b.strip().upper()) & (df_fw[c_col] == type_c.strip().upper())]
                
                if not df_rv.empty:
                    df_rv[b_col] = df_rv[b_col].fillna('Main').astype(str).str.strip().str.upper()
                    df_rv[c_col] = df_rv[c_col].fillna('Main').astype(str).str.strip().str.upper()
                    df_rv = df_rv[(df_rv[c_col] == type_b.strip().upper()) & (df_rv[b_col] == type_c.strip().upper())]

            b_sec = cols_fw_lower.get('base_section', 'Base_section')
            c_sec = cols_fw_lower.get('comp_section', 'Comp_section')
            
            df_fw = df_fw[[b_sec, c_sec]].rename(columns={b_sec: 'Base_section', c_sec: 'Comp_section'})
            if not df_rv.empty:
                df_rv = df_rv[[b_sec, c_sec]].rename(columns={b_sec: 'Comp_section', c_sec: 'Base_section'})
            else:
                df_rv = pd.DataFrame(columns=['Base_section', 'Comp_section'])

            df_mapping = pd.concat([df_fw, df_rv], ignore_index=True)

            if not df_mapping.empty:
                df_mapping['Base_section'] = df_mapping['Base_section'].astype(str).str.replace('\n', ',').str.split(',')
                df_mapping['Comp_section'] = df_mapping['Comp_section'].astype(str).str.replace('\n', ',').str.split(',')
                df_mapping = df_mapping.explode('Base_section').explode('Comp_section')
                
                df_mapping['Base_section'] = df_mapping['Base_section'].apply(clean_key_val)
                df_mapping['Comp_section'] = df_mapping['Comp_section'].apply(clean_key_val)
                df_mapping = df_mapping.dropna().drop_duplicates()
            else:
                df_mapping = pd.DataFrame(columns=['Base_section', 'Comp_section'])

            if base_std.strip().upper() == comp_std.strip().upper() and type_b.strip().upper() == type_c.strip().upper():
                implicit = pd.DataFrame({'Base_section': list(set(df_base['merge_key']) & set(df_comp['merge_key'])), 
                                         'Comp_section': list(set(df_base['merge_key']) & set(df_comp['merge_key']))})
                bridge = pd.concat([df_mapping, implicit], ignore_index=True).drop_duplicates()
            else:
                bridge = df_mapping.copy()

            rename_b = {c: f"{c}_{base_ver}" for c in df_base.columns if c != 'merge_key'}
            df_base = df_base.rename(columns=rename_b)
            
            rename_c = {c: f"{c}_{comp_ver}" for c in df_comp.columns if c != 'merge_key'}
            df_comp = df_comp.rename(columns=rename_c)

            df_base['base_idx'], df_comp['comp_idx'] = range(len(df_base)), range(len(df_comp))
            merged = pd.merge(bridge, df_base, left_on='Base_section', right_on='merge_key', how='outer')
            merged = pd.merge(merged, df_comp, left_on='Comp_section', right_on='merge_key', how='outer')
            
            merged['base_idx'] = merged['base_idx'].fillna(float('inf'))
            merged['comp_idx'] = merged['comp_idx'].fillna(float('inf'))
            merged = merged.sort_values(['base_idx', 'comp_idx'])

            result_rows = []
            for _, row in merged.iterrows():
                row_dict = {}
                has_b = not pd.isna(row.get('base_idx')) and row.get('base_idx') != float('inf')
                has_c = not pd.isna(row.get('comp_idx')) and row.get('comp_idx') != float('inf')

                if mapped_only and not (has_b and has_c):
                    continue
                
                for c in rename_b.values(): row_dict[c] = str(row[c]) if has_b and not pd.isna(row[c]) else ""
                for c in rename_c.values(): row_dict[c] = str(row[c]) if has_c and not pd.isna(row[c]) else ""
                
                if has_b and has_c:
                    for orig_col in rename_b.keys():
                        if 'description' in orig_col.lower() and rename_c.get(orig_col) in row_dict:
                            b_v, c_v = row_dict[rename_b[orig_col]], row_dict[rename_c[orig_col]]
                            if b_v and c_v and "<img" not in b_v and "<img" not in c_v and b_v != c_v:
                                row_dict[rename_b[orig_col]], row_dict[rename_c[orig_col]] = generate_html_diff(b_v, c_v)
                result_rows.append(row_dict)

            final_df = combine_code_desc(pd.DataFrame(result_rows))

            if diff_only:
                mask = final_df.astype(str).apply(lambda col: col.str.contains('color:#ff4d4f|color:#2ecc71', case=False, regex=True)).any(axis=1)
                final_df = final_df[mask]
            
            b_cols_final = [c for c in final_df.columns if c.endswith(f"_{base_ver}")]
            c_cols_final = [c for c in final_df.columns if c.endswith(f"_{comp_ver}")]

            final_df = apply_visual_merge(final_df, b_cols_final)
            final_df = apply_visual_merge(final_df, c_cols_final)

            return final_df

        return pd.DataFrame({"Info": ["์กฐ๊ฑด์„ ์„ ํƒํ•˜์„ธ์š”."]})
    except Exception as e:
        import traceback
        traceback.print_exc()
        return pd.DataFrame({"Error": [f"์‹œ์Šคํ…œ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}"]})


# ==========================================
# 4. UI Layout & Event Binding
# ==========================================
with gr.Blocks() as demo:
    gr.Markdown("# ๐Ÿ“œ Regulation Viewer")

    with gr.Row():
        with gr.Accordion("๐Ÿ“Œ ๊ธฐ์ค€ ๋ฒ•๊ทœ", open=True):
            with gr.Column():
                base_standard = gr.Dropdown(label="Standard")
                base_version = gr.Dropdown(label="Version")
                base_status = gr.Textbox(label="Status", interactive=False, lines=1)
                
                with gr.Row(elem_classes="reset-row"):
                    base_category = gr.Dropdown(label="Category", scale=4)
                    # โฌ‡๏ธ elem_classes="reset-btn" ์ถ”๊ฐ€!
                    base_reset_btn = gr.Button("โ†บ ์ดˆ๊ธฐํ™”", scale=1, elem_classes="reset-btn")
    
        with gr.Accordion("๐Ÿ”„ ๋น„๊ต ๋ฒ•๊ทœ", open=False):
            with gr.Column():
                comp_standard = gr.Dropdown(label="Standard", choices=[])
                comp_version = gr.Dropdown(label="Version", choices=[])
                comp_status = gr.Textbox(label="Status", interactive=False, lines=1)
                
                with gr.Row(elem_classes="reset-row"):
                    comp_category = gr.Dropdown(label="Category", choices=[], scale=4)
                    # โฌ‡๏ธ elem_classes="reset-btn" ์ถ”๊ฐ€!
                    comp_reset_btn = gr.Button("โ†บ ์ดˆ๊ธฐํ™”", scale=1, elem_classes="reset-btn")

    with gr.Row(elem_id="search_row"):
        search_btn = gr.Button("๐Ÿ” ์กฐํšŒ", variant="primary", scale=10)
        # โฌ‡๏ธ [์ถ”๊ฐ€] ๋งคํ•‘ ์ฒดํฌ๋ฐ•์Šค ์ถ”๊ฐ€!
        mapped_only_cb = gr.Checkbox(label="๐Ÿ”— ๋งคํ•‘๋œ ํ•ญ๋ชฉ๋งŒ ๋ณด๊ธฐ", value=False, elem_id="mapped_cb_item", container=False, scale=1)
        diff_filter_cb = gr.Checkbox(label="๐Ÿ’ก ๋ณ€๊ฒฝ๋œ ๋‚ด์šฉ๋งŒ ๋ณด๊ธฐ", value=False, elem_id="diff_cb_item", container=False, scale=1)

    output_df = gr.Dataframe(wrap=True, interactive=False, datatype="html", max_height=800)

    demo.load(fn=load_initial_standards, inputs=None, outputs=base_standard)

    base_standard.change(fn=update_version_dropdown, inputs=[base_standard], outputs=[base_version])
    base_version.change(fn=update_base_category_dropdown, inputs=[base_standard, base_version], outputs=[base_category, base_status])

    base_version.change(fn=update_comp_standard_dropdown, inputs=[base_standard, base_version], outputs=[comp_standard])
    comp_standard.change(fn=update_comp_version_dropdown, inputs=[base_standard, base_version, comp_standard], outputs=[comp_version])

    comp_change_triggers = [base_standard, base_version, base_category, comp_standard, comp_version]
    
    base_category.change(fn=update_comp_category_dropdown, inputs=comp_change_triggers, outputs=[comp_category, comp_status])
    comp_version.change(fn=update_comp_category_dropdown, inputs=comp_change_triggers, outputs=[comp_category, comp_status])

    search_btn.click(
        fn=execute_unified_search,
        inputs=[base_standard, base_version, base_category, comp_standard, comp_version, comp_category, mapped_only_cb, diff_filter_cb],
        outputs=[output_df]
    )
  
    mapped_only_cb.change(
        fn=execute_unified_search,
        inputs=[base_standard, base_version, base_category, comp_standard, comp_version, comp_category, mapped_only_cb, diff_filter_cb],
        outputs=[output_df]
    )

    diff_filter_cb.change(
        fn=execute_unified_search,
        inputs=[base_standard, base_version, base_category, comp_standard, comp_version, comp_category, mapped_only_cb, diff_filter_cb],
        outputs=[output_df]
    )

    base_reset_btn.click(fn=reset_base_selections, inputs=None, outputs=[base_standard, base_version, base_category, base_status])
    comp_reset_btn.click(fn=reset_comp_selections, inputs=None, outputs=[comp_standard, comp_version, comp_category, comp_status])


# ==========================================
# 5. Application Styling (CSS)
# ==========================================
css = """
.reset-row {
    align-items: flex-end !important; 
    margin-bottom: 5px !important; 
}
.reset-btn {
    margin-bottom: 10px !important; 
}

table { 
    table-layout: auto !important; 
    width: max-content !important; 
    min-width: 100% !important;
}

th, td {
    min-width: 150px; 
}

table:has(th:nth-last-child(2):first-child),
table:has(th:nth-last-child(3):first-child),
table:has(th:nth-last-child(4):first-child),
table:has(th:nth-last-child(5):first-child),
table:has(th:nth-last-child(6):first-child) {
    table-layout: fixed !important;
    width: 100% !important;
}

table th:nth-last-child(2):first-child, table td:nth-last-child(2):first-child { width: 15% !important; min-width: 0 !important; } 
table th:nth-last-child(1), table td:nth-last-child(1) { width: 85% !important; min-width: 0 !important; }

table th:nth-child(1):nth-last-child(3), table td:nth-child(1):nth-last-child(3) { width: 20% !important; min-width: 0 !important; } 
table th:nth-child(2):nth-last-child(2), table td:nth-child(2):nth-last-child(2) { width: 30% !important; min-width: 0 !important; } 
table th:nth-child(3):nth-last-child(1), table td:nth-child(3):nth-last-child(1) { width: 50% !important; min-width: 0 !important; }

table th:nth-child(1):nth-last-child(4), table td:nth-child(1):nth-last-child(4) { width: 10% !important; min-width: 0 !important; } 
table th:nth-child(2):nth-last-child(3), table td:nth-child(2):nth-last-child(3) { width: 40% !important; min-width: 0 !important; } 
table th:nth-child(3):nth-last-child(2), table td:nth-child(3):nth-last-child(2) { width: 10% !important; min-width: 0 !important; } 
table th:nth-child(4):nth-last-child(1), table td:nth-child(4):nth-last-child(1) { width: 40% !important; min-width: 0 !important; }

table th:nth-child(1):nth-last-child(5), table td:nth-child(1):nth-last-child(5) { width: 15% !important; min-width: 0 !important; } 
table th:nth-child(2):nth-last-child(4), table td:nth-child(2):nth-last-child(4) { width: 15% !important; min-width: 0 !important; } 
table th:nth-child(3):nth-last-child(3), table td:nth-child(3):nth-last-child(3) { width: 15% !important; min-width: 0 !important; } 
table th:nth-child(4):nth-last-child(2), table td:nth-child(4):nth-last-child(2) { width: 15% !important; min-width: 0 !important; } 
table th:nth-child(5):nth-last-child(1), table td:nth-child(5):nth-last-child(1) { width: 40% !important; min-width: 0 !important; }

table th:nth-child(1):nth-last-child(6), table td:nth-child(1):nth-last-child(6) { width: 8% !important; min-width: 0 !important; } 
table th:nth-child(2):nth-last-child(5), table td:nth-child(2):nth-last-child(5) { width: 15% !important; min-width: 0 !important; } 
table th:nth-child(3):nth-last-child(4), table td:nth-child(3):nth-last-child(4) { width: 27% !important; min-width: 0 !important; } 
table th:nth-child(4):nth-last-child(3), table td:nth-child(4):nth-last-child(3) { width: 8% !important; min-width: 0 !important; } 
table th:nth-child(5):nth-last-child(2), table td:nth-child(5):nth-last-child(2) { width: 15% !important; min-width: 0 !important; } 
table th:nth-child(6):nth-last-child(1), table td:nth-child(6):nth-last-child(1) { width: 27% !important; min-width: 0 !important; }

thead th { 
    font-size: 18px !important;
    position: sticky;
    top: 0; 
    background: white; 
    z-index: 10;
} 
.dataframe { 
    max-height: none !important; 
    overflow-y: visible !important; 
    overflow-x: auto !important; 
    display: block;
} 
.dataframe > div { 
    max-height: none !important; 
    overflow: visible !important; 
} 
td { 
    font-size: 18px !important;
    white-space: pre-wrap !important;
    word-break: keep-all !important; 
    line-height: 1.6; 
    padding: 10px; 
    vertical-align: top !important;
    text-align: left !important;
} 
td img {
    display: block;
    max-width: none !important;
}

#search_row {
    align-items: center !important; 
    margin-bottom: 5px !important;
}

#diff_cb_item, #mapped_cb_item {
    margin-top: 0 !important;
    padding-left: 15px !important; 
    width: max-content !important;
    min-width: max-content !important;
    flex-grow: 0 !important;
}
"""

if __name__ == "__main__":
    demo.launch(
        theme=gr.themes.Soft(),
        share=True,
        css=css
    )