File size: 27,323 Bytes
b3be69b
 
 
 
 
 
 
 
 
aca9376
 
 
 
 
 
 
b3be69b
 
 
 
 
 
6998afd
 
aca9376
 
6998afd
 
 
aca9376
6998afd
aca9376
 
 
 
6998afd
 
 
aca9376
6998afd
 
aca9376
 
6998afd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3be69b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffb5b8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3be69b
ffb5b8d
b3be69b
ffb5b8d
 
 
b3be69b
ffb5b8d
b3be69b
 
ffb5b8d
b3be69b
 
 
ffb5b8d
b3be69b
 
ffb5b8d
b3be69b
ffb5b8d
b3be69b
ffb5b8d
 
b3be69b
 
 
 
 
 
 
 
 
 
 
 
56d3d16
 
 
 
2ff5289
56d3d16
2ff5289
b3be69b
56d3d16
 
 
 
 
 
 
 
b3be69b
2ff5289
b3be69b
 
56d3d16
b3be69b
 
4f03165
 
b3be69b
4f03165
 
aca9376
4f03165
 
 
 
 
 
 
 
 
 
 
aca9376
 
b3be69b
4f03165
 
56d3d16
4f03165
56d3d16
4f03165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56d3d16
4f03165
b3be69b
 
 
 
 
 
 
 
 
 
 
12e6818
b3be69b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56d3d16
b3be69b
 
 
 
 
 
 
 
 
 
 
 
 
56d3d16
b3be69b
 
 
 
 
 
 
 
 
 
 
 
 
56d3d16
 
 
b3be69b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aca9376
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
import gradio as gr
from huggingface_hub import InferenceClient
import os
import pandas as pd
from typing import List, Dict, Tuple
import json
import io
import traceback
import csv
from functools import lru_cache
from concurrent.futures import ThreadPoolExecutor
import math
import nltk
nltk.download('punkt')
from nltk.tokenize import sent_tokenize
from transformers import AutoTokenizer

# μΆ”λ‘  API ν΄λΌμ΄μ–ΈνŠΈ μ„€μ •
hf_client = InferenceClient(
    "CohereForAI/c4ai-command-r-plus-08-2024", token=os.getenv("HF_TOKEN")
)

def chunk_text(text: str, chunk_size: int = 500) -> List[str]:
    """ν…μŠ€νŠΈλ₯Ό 더 μž‘μ€ 청크둜 λΆ„ν• """
    tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-plus-08-2024")
    sentences = sent_tokenize(text)
    chunks = []
    current_chunk = []
    current_length = 0

    for sentence in sentences:
        sentence = sentence.strip()
        tokenized_sentence = tokenizer.encode(sentence, add_special_tokens=False)
        sentence_length = len(tokenized_sentence)
        if current_length + sentence_length > chunk_size:
            if current_chunk:
                chunks.append(' '.join(current_chunk))
            current_chunk = [sentence]
            current_length = sentence_length
        else:
            current_chunk.append(sentence)
            current_length += sentence_length

    if current_chunk:
        chunks.append(' '.join(current_chunk))
    return chunks

@lru_cache(maxsize=100)
def cached_preprocess(text: str) -> str:
    """자주 μ‚¬μš©λ˜λŠ” ν…μŠ€νŠΈμ— λŒ€ν•œ μ „μ²˜λ¦¬ κ²°κ³Όλ₯Ό 캐싱"""
    return preprocess_single_chunk(text)

def preprocess_single_chunk(chunk: str) -> str:
    """단일 청크에 λŒ€ν•œ μ „μ²˜λ¦¬ μˆ˜ν–‰"""
    system_prompt = """당신은 데이터 μ „μ²˜λ¦¬ μ „λ¬Έκ°€μž…λ‹ˆλ‹€. μž…λ ₯된 ν…μŠ€νŠΈλ₯Ό CSV 데이터셋 ν˜•μ‹μœΌλ‘œ λΉ λ₯΄κ²Œ λ³€ν™˜ν•˜μ„Έμš”.
    [κΈ°μ‘΄ κ·œμΉ™ 동일]"""

    full_prompt = f"{system_prompt}\n\nμž…λ ₯ν…μŠ€νŠΈ:\n{chunk}\n\n좜λ ₯:"

    try:
        # 슀트리밍 λΉ„ν™œμ„±ν™” 및 νŒŒλΌλ―Έν„° μ΅œμ ν™”
        response = hf_client.text_generation(
            prompt=full_prompt,
            max_new_tokens=2000,  # 토큰 수 μ œν•œ
            temperature=0.1,      # 더 결정적인 좜λ ₯
            top_p=0.5,           # 더 μ§‘μ€‘λœ 좜λ ₯
            stream=False         # 슀트리밍 λΉ„ν™œμ„±ν™”
        )
        
        return response.strip()
    except Exception as e:
        return f"청크 처리 쀑 였λ₯˜ λ°œμƒ: {str(e)}"

def load_code(filename: str) -> str:
    try:
        with open(filename, 'r', encoding='utf-8') as file:
            return file.read()
    except FileNotFoundError:
        return f"{filename} νŒŒμΌμ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."
    except Exception as e:
        return f"νŒŒμΌμ„ μ½λŠ” 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}"

def load_parquet(filename: str) -> str:
    try:
        df = pd.read_parquet(filename, engine='pyarrow')
        return df.head(10).to_markdown(index=False)
    except FileNotFoundError:
        return f"{filename} νŒŒμΌμ„ 찾을 수 μ—†μŠ΅λ‹ˆλ‹€."
    except Exception as e:
        return f"νŒŒμΌμ„ μ½λŠ” 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}"

def respond(
    message: str,
    history: List[Dict[str, str]],
    system_message: str = "",
    max_tokens: int = 4000,
    temperature: float = 0.5,
    top_p: float = 0.9,
    parquet_data: str = None
) -> str:
    # μ‹œμŠ€ν…œ ν”„λ‘¬ν”„νŠΈ μ„€μ •
    if parquet_data:
        system_prefix = """λ°˜λ“œμ‹œ ν•œκΈ€λ‘œ λ‹΅λ³€ν•  것. λ„ˆλŠ” μ—…λ‘œλ“œλœ 데이터λ₯Ό 기반으둜 μ§ˆλ¬Έμ— λ‹΅λ³€ν•˜λŠ” 역할을 ν•œλ‹€. 데이터λ₯Ό λΆ„μ„ν•˜μ—¬ μ‚¬μš©μžμ—κ²Œ 도움이 λ˜λŠ” 정보λ₯Ό μ œκ³΅ν•˜λΌ. 데이터λ₯Ό ν™œμš©ν•˜μ—¬ μƒμ„Έν•˜κ³  μ •ν™•ν•œ 닡변을 μ œκ³΅ν•˜λ˜, λ―Όκ°ν•œ μ •λ³΄λ‚˜ 개인 정보λ₯Ό λ…ΈμΆœν•˜μ§€ 마라."""
        try:
            df = pd.read_json(io.StringIO(parquet_data))
            # λ°μ΄ν„°μ˜ μš”μ•½ 정보 생성
            data_summary = df.describe(include='all').to_string()
            system_prefix += f"\n\nμ—…λ‘œλ“œλœ λ°μ΄ν„°μ˜ μš”μ•½ 정보:\n{data_summary}"
        except Exception as e:
            print(f"데이터 λ‘œλ“œ 쀑 였λ₯˜ λ°œμƒ: {str(e)}\n{traceback.format_exc()}")
            system_prefix += "\n\n데이터λ₯Ό λ‘œλ“œν•˜λŠ” 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€."
    else:
        system_prefix = system_message or "λ„ˆλŠ” AI μ‘°μ–Έμž 역할이닀."

    # λ©”μ‹œμ§€ 생성
    prompt = system_prefix + "\n\n"
    for chat in history:
        if chat['role'] == 'user':
            prompt += f"μ‚¬μš©μž: {chat['content']}\n"
        else:
            prompt += f"AI: {chat['content']}\n"
    prompt += f"μ‚¬μš©μž: {message}\nAI:"

    try:
        # λͺ¨λΈμ— λ©”μ‹œμ§€ 전솑 및 응닡 λ°›κΈ°
        response = ""
        stream = hf_client.text_generation(
            prompt=prompt,
            max_new_tokens=max_tokens,
            stream=True,
            temperature=temperature,
            top_p=top_p,
        )
        for msg in stream:
            if msg:
                response += msg
                yield response
    except Exception as e:
        error_message = f"μΆ”λ‘  쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}\n{traceback.format_exc()}"
        print(error_message)
        yield error_message

def upload_csv(file_path: str) -> Tuple[str, str]:
    try:
        # CSV 파일 읽기
        df = pd.read_csv(file_path, sep=',')
        # ν•„μˆ˜ 컬럼 확인
        required_columns = {'id', 'text', 'label', 'metadata'}
        available_columns = set(df.columns)
        missing_columns = required_columns - available_columns
        if missing_columns:
            return f"CSV νŒŒμΌμ— λ‹€μŒ ν•„μˆ˜ 컬럼이 λˆ„λ½λ˜μ—ˆμŠ΅λ‹ˆλ‹€: {', '.join(missing_columns)}", ""
        # 데이터 ν΄λ Œμ§•
        df.drop_duplicates(inplace=True)
        df.fillna('', inplace=True)
        # 데이터 μœ ν˜• μ΅œμ ν™”
        df = df.astype({'id': 'int32', 'text': 'string', 'label': 'category', 'metadata': 'string'})
        # Parquet 파일둜 λ³€ν™˜
        parquet_filename = os.path.splitext(os.path.basename(file_path))[0] + '.parquet'
        df.to_parquet(parquet_filename, engine='pyarrow', compression='snappy')
        return f"{parquet_filename} 파일이 μ„±κ³΅μ μœΌλ‘œ μ—…λ‘œλ“œλ˜κ³  λ³€ν™˜λ˜μ—ˆμŠ΅λ‹ˆλ‹€.", parquet_filename
    except Exception as e:
        return f"CSV 파일 μ—…λ‘œλ“œ 및 λ³€ν™˜ 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}", ""

def upload_parquet(file_path: str) -> Tuple[str, str, str]:
    try:
        # Parquet 파일 읽기
        df = pd.read_parquet(file_path, engine='pyarrow')
        # Markdown으둜 λ³€ν™˜ν•˜μ—¬ 미리보기
        parquet_content = df.head(10).to_markdown(index=False)
        # DataFrame을 JSON λ¬Έμžμ—΄λ‘œ λ³€ν™˜
        parquet_json = df.to_json(orient='records', force_ascii=False)
        return "Parquet 파일이 μ„±κ³΅μ μœΌλ‘œ μ—…λ‘œλ“œλ˜μ—ˆμŠ΅λ‹ˆλ‹€.", parquet_content, parquet_json
    except Exception as e:
        return f"Parquet 파일 μ—…λ‘œλ“œ 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}", "", ""

def text_to_parquet(text: str) -> Tuple[str, str, str]:
    try:
        from io import StringIO
        import csv
        
        # μž…λ ₯ ν…μŠ€νŠΈ μ •μ œ
        lines = text.strip().split('\n')
        cleaned_lines = []
        
        for line in lines:
            # 빈 쀄 κ±΄λ„ˆλ›°κΈ°
            if not line.strip():
                continue
            
            # μŒλ”°μ˜΄ν‘œ μ •κ·œν™”
            line = line.replace('""', '"')  # 쀑볡 μŒλ”°μ˜΄ν‘œ 처리
            
            # CSV νŒŒμ‹±μ„ μœ„ν•œ μž„μ‹œ StringIO 객체 생성
            temp_buffer = StringIO(line)
            try:
                # CSV 라인 νŒŒμ‹± μ‹œλ„
                reader = csv.reader(temp_buffer, quoting=csv.QUOTE_ALL)
                parsed_line = next(reader)
                if len(parsed_line) == 4:  # id, text, label, metadata
                    # 각 ν•„λ“œλ₯Ό 적절히 ν¬λ§·νŒ…
                    formatted_line = f'{parsed_line[0]},"{parsed_line[1]}","{parsed_line[2]}","{parsed_line[3]}"'
                    cleaned_lines.append(formatted_line)
            except:
                continue
            finally:
                temp_buffer.close()
        
        # μ •μ œλœ CSV 데이터 생성
        cleaned_csv = '\n'.join(cleaned_lines)
        
        # DataFrame 생성
        df = pd.read_csv(
            StringIO(cleaned_csv),
            sep=',',
            quoting=csv.QUOTE_ALL,
            escapechar='\\',
            names=['id', 'text', 'label', 'metadata']
        )
        
        # 데이터 μœ ν˜• μ΅œμ ν™”
        df = df.astype({'id': 'int32', 'text': 'string', 'label': 'string', 'metadata': 'string'})
        
        # Parquet 파일둜 λ³€ν™˜
        parquet_filename = 'text_to_parquet.parquet'
        df.to_parquet(parquet_filename, engine='pyarrow', compression='snappy')
        
        # Parquet 파일 λ‚΄μš© 미리보기
        parquet_content = load_parquet(parquet_filename)
        
        return f"{parquet_filename} 파일이 μ„±κ³΅μ μœΌλ‘œ λ³€ν™˜λ˜μ—ˆμŠ΅λ‹ˆλ‹€.", parquet_content, parquet_filename
        
    except Exception as e:
        error_message = f"ν…μŠ€νŠΈ λ³€ν™˜ 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}"
        print(f"{error_message}\n{traceback.format_exc()}")
        return error_message, "", ""

def preprocess_text_with_llm(input_text: str) -> str:
    if not input_text.strip():
        return "μž…λ ₯ ν…μŠ€νŠΈκ°€ λΉ„μ–΄μžˆμŠ΅λ‹ˆλ‹€."
        
    system_prompt = """당신은 데이터 μ „μ²˜λ¦¬ μ „λ¬Έκ°€μž…λ‹ˆλ‹€. μž…λ ₯된 ν…μŠ€νŠΈλ₯Ό CSV 데이터셋 ν˜•μ‹μœΌλ‘œ λ³€ν™˜ν•˜μ„Έμš”.

κ·œμΉ™:
1. 좜λ ₯ ν˜•μ‹: id,text,label,metadata
2. id: 1λΆ€ν„° μ‹œμž‘ν•˜λŠ” 순차적 번호
3. text: 의미 μžˆλŠ” λ‹¨μœ„λ‘œ λΆ„λ¦¬λœ ν…μŠ€νŠΈ
4. label: ν…μŠ€νŠΈμ˜ μ£Όμ œλ‚˜ μΉ΄ν…Œκ³ λ¦¬λ₯Ό μ•„λž˜ κΈ°μ€€μœΌλ‘œ μ •ν™•ν•˜κ²Œ ν•œ 개만 선택
   - Historical_Figure (역사적 인물)
   - Military_History (ꡰ사 역사)
   - Technology (기술)
   - Politics (μ •μΉ˜)
   - Culture (λ¬Έν™”)
5. metadata: λ‚ μ§œ, 좜처 λ“± μΆ”κ°€ 정보

μ€‘μš”:
- λ™μΌν•œ ν…μŠ€νŠΈλ₯Ό λ°˜λ³΅ν•΄μ„œ 좜λ ₯ν•˜μ§€ 말 것
- 각 ν…μŠ€νŠΈλŠ” ν•œ 번만 μ²˜λ¦¬ν•˜μ—¬ κ°€μž₯ μ ν•©ν•œ label을 선택할 것
- μž…λ ₯ ν…μŠ€νŠΈλ₯Ό 의미 λ‹¨μœ„λ‘œ 적절히 뢄리할 것

μ˜ˆμ‹œ:
1,"μ΄μˆœμ‹ μ€ μ‘°μ„  μ€‘κΈ°μ˜ 무신이닀.","Historical_Figure","μ‘°μ„ μ‹œλŒ€, μœ„ν‚€λ°±κ³Ό"

μ£Όμ˜μ‚¬ν•­:
- text에 μ‰Όν‘œκ°€ 있으면 ν°λ”°μ˜΄ν‘œλ‘œ 감싸기
- ν°λ”°μ˜΄ν‘œλŠ” λ°±μŠ¬λž˜μ‹œλ‘œ μ΄μŠ€μΌ€μ΄ν”„ 처리
- 각 행은 μƒˆλ‘œμš΄ μ€„λ‘œ ꡬ뢄
- λΆˆν•„μš”ν•œ 반볡 좜λ ₯ κΈˆμ§€"""

    try:
        # ν…μŠ€νŠΈλ₯Ό 청크둜 λΆ„ν• 
        chunks = chunk_text(input_text)
        
        # 병렬 처리둜 청크듀을 처리
        with ThreadPoolExecutor(max_workers=3) as executor:
            futures = []
            for chunk in chunks:
                # 각 청크에 λŒ€ν•œ ν”„λ‘¬ν”„νŠΈ 생성
                chunk_prompt = f"{system_prompt}\n\nμž…λ ₯ν…μŠ€νŠΈ:\n{chunk}\n\n좜λ ₯:"
                future = executor.submit(
                    hf_client.text_generation,
                    prompt=chunk_prompt,
                    max_new_tokens=2000,
                    temperature=0.1,
                    top_p=0.5,
                    stream=False
                )
                futures.append(future)
            processed_chunks = [future.result() for future in futures]
        
        # κ²°κ³Ό 병합 및 쀑볡 제거
        all_lines = []
        seen_texts = set()
        current_id = 1
        
        for chunk_result in processed_chunks:
            # EOS_TOKEN 처리
            if "<EOS_TOKEN>" in chunk_result:
                chunk_result = chunk_result.split("<EOS_TOKEN>")[0]
            
            lines = chunk_result.strip().split('\n')
            for line in lines:
                line = line.strip()
                if line and '좜λ ₯:' not in line and line not in seen_texts:
                    # ID μž¬ν• λ‹Ή
                    parts = line.split(',', 1)
                    if len(parts) > 1:
                        new_line = f"{current_id},{parts[1]}"
                        if new_line not in seen_texts:  # 좔가적인 쀑볡 검사
                            all_lines.append(new_line)
                            seen_texts.add(new_line)
                            current_id += 1
        
        processed_text = '\n'.join(all_lines)
        
        # CSV ν˜•μ‹ 검증
        try:
            from io import StringIO
            import csv
            csv.reader(StringIO(processed_text))
            return processed_text
        except csv.Error:
            return "LLM이 μ˜¬λ°”λ₯Έ CSV ν˜•μ‹μ„ μƒμ„±ν•˜μ§€ λͺ»ν–ˆμŠ΅λ‹ˆλ‹€. λ‹€μ‹œ μ‹œλ„ν•΄μ£Όμ„Έμš”."
            
    except Exception as e:
        error_message = f"μ „μ²˜λ¦¬ 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}"
        print(error_message)
        return error_message

# CSS μ„€μ •
css = """
footer {
    visibility: hidden;
}
#chatbot-container, #chatbot-data-upload {
    height: 700px;
    overflow-y: scroll;
}
#chatbot-container .message, #chatbot-data-upload .message {
    font-size: 14px;
}
/* μž…λ ₯μ°½ 배경색 및 κΈ€μžμƒ‰ λ³€κ²½ */
textarea, input[type="text"] {
    background-color: #ffffff; /* 흰색 λ°°κ²½ */
    color: #000000; /* 검정색 κΈ€μž */
}
/* 파일 μ—…λ‘œλ“œ μ˜μ—­ 높이 쑰절 */
#parquet-upload-area {
    max-height: 150px;
    overflow-y: auto;
}
/* 초기 μ„€λͺ… 글씨 크기 쑰절 */
#initial-description {
    font-size: 14px;
}
"""

# Gradio Blocks μΈν„°νŽ˜μ΄μŠ€ μ„€μ •
with gr.Blocks(css=css) as demo:
    gr.Markdown("# My RAG: LLM이 λ‚˜λ§Œμ˜ λ°μ΄ν„°λ‘œ ν•™μŠ΅ν•œ μ½˜ν…μΈ  생성/λ‹΅λ³€", elem_id="initial-description")
    gr.Markdown(
        "### 1) λ‚˜λ§Œμ˜ 데이터λ₯Ό μž…λ ₯ λ˜λŠ” CSV μ—…λ‘œλ“œλ‘œ Parquet 데이터셋 μžλ™ λ³€ν™˜ 2) Parquet 데이터셋을 μ—…λ‘œλ“œν•˜λ©΄, LLM이 맞좀 ν•™μŠ΅ λ°μ΄ν„°λ‘œ ν™œμš©ν•˜μ—¬ 응닡\n"
        "### Tip) '예제'λ₯Ό 톡해 λ‹€μ–‘ν•œ ν™œμš© 방법을 μ²΄ν—˜ν•˜κ³  μ‘μš©ν•΄ λ³΄μ„Έμš”, 데이터셋 μ—…λ‘œλ“œμ‹œ λ―Έλ¦¬λ³΄κΈ°λŠ” 10건만 좜λ ₯",
        elem_id="initial-description"
    )

    # 첫 번째 νƒ­: 챗봇 데이터 μ—…λ‘œλ“œ (νƒ­ 이름 λ³€κ²½: "My 데이터셋+LLM")
    with gr.Tab("My 데이터셋+LLM"):
        gr.Markdown("### LLMκ³Ό λŒ€ν™”ν•˜κΈ°")
        chatbot_data_upload = gr.Chatbot(label="챗봇", type="messages", elem_id="chatbot-data-upload")
        msg_data_upload = gr.Textbox(label="λ©”μ‹œμ§€ μž…λ ₯", placeholder="여기에 λ©”μ‹œμ§€λ₯Ό μž…λ ₯ν•˜μ„Έμš”...")
        send_data_upload = gr.Button("전솑")

        with gr.Accordion("μ‹œμŠ€ν…œ ν”„λ‘¬ν”„νŠΈ 및 μ˜΅μ…˜ μ„€μ •", open=False):
            system_message = gr.Textbox(label="System Message", value="λ„ˆλŠ” AI μ‘°μ–Έμž 역할이닀.")
            max_tokens = gr.Slider(minimum=1, maximum=8000, value=1000, label="Max Tokens")
            temperature = gr.Slider(minimum=0, maximum=1, value=0.7, label="Temperature")
            top_p = gr.Slider(minimum=0, maximum=1, value=0.9, label="Top P")

        parquet_data_state = gr.State()

        def handle_message_data_upload(
            message: str,
            history: List[Dict[str, str]],
            system_message: str,
            max_tokens: int,
            temperature: float,
            top_p: float,
            parquet_data: str
        ):
            history = history or []
            try:
                # μ‚¬μš©μžμ˜ λ©”μ‹œμ§€λ₯Ό νžˆμŠ€ν† λ¦¬μ— μΆ”κ°€
                history.append({"role": "user", "content": message})
                # 응닡 생성
                response_gen = respond(
                    message, history, system_message, max_tokens, temperature, top_p, parquet_data
                )
                partial_response = ""
                for partial in response_gen:
                    partial_response = partial
                    # λŒ€ν™” λ‚΄μ—­ μ—…λ°μ΄νŠΈ
                    display_history = history + [
                        {"role": "assistant", "content": partial_response}
                    ]
                    yield display_history, ""
                # μ–΄μ‹œμŠ€ν„΄νŠΈμ˜ 응닡을 νžˆμŠ€ν† λ¦¬μ— μΆ”κ°€
                history.append({"role": "assistant", "content": partial_response})
            except Exception as e:
                response = f"μΆ”λ‘  쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}"
                history.append({"role": "assistant", "content": response})
                yield history, ""

        send_data_upload.click(
            handle_message_data_upload,
            inputs=[
                msg_data_upload,
                chatbot_data_upload,
                system_message,
                max_tokens,
                temperature,
                top_p,
                parquet_data_state,  # parquet_data_stateλ₯Ό μ‚¬μš©ν•˜μ—¬ μ—…λ‘œλ“œλœ 데이터λ₯Ό 전달
            ],
            outputs=[chatbot_data_upload, msg_data_upload],
            queue=True
        )

        # 예제 μΆ”κ°€
        with gr.Accordion("예제", open=False):
            gr.Examples(
                examples=[
                    ["μ—…λ‘œλ“œλœ 데이터셋에 λŒ€ν•΄ μš”μ•½ μ„€λͺ…ν•˜λΌ."],
                    ["μ—…λ‘œλ“œλœ 데이터셋 νŒŒμΌμ„ ν•™μŠ΅ λ°μ΄ν„°λ‘œ ν™œμš©ν•˜μ—¬, λ³Έ μ„œλΉ„μŠ€λ₯Ό SEO μ΅œμ ν™”ν•˜μ—¬ λΈ”λ‘œκ·Έ 포슀트(κ°œμš”, λ°°κ²½ 및 ν•„μš”μ„±, κΈ°μ‘΄ μœ μ‚¬ μ œν’ˆ/μ„œλΉ„μŠ€μ™€ λΉ„κ΅ν•˜μ—¬ 특μž₯점, ν™œμš©μ²˜, κ°€μΉ˜, κΈ°λŒ€νš¨κ³Ό, 결둠을 포함)둜 4000 토큰 이상 μž‘μ„±ν•˜λΌ"],
                    ["μ—…λ‘œλ“œλœ 데이터셋 νŒŒμΌμ„ ν•™μŠ΅ λ°μ΄ν„°λ‘œ ν™œμš©ν•˜μ—¬, μ‚¬μš© 방법과 차별점, νŠΉμ§•, 강점을 μ€‘μ‹¬μœΌλ‘œ 4000 토큰 이상 유튜브 μ˜μƒ 슀크립트 ν˜•νƒœλ‘œ μž‘μ„±ν•˜λΌ"],
                    ["μ—…λ‘œλ“œλœ 데이터셋 νŒŒμΌμ„ ν•™μŠ΅ λ°μ΄ν„°λ‘œ ν™œμš©ν•˜μ—¬, μ œν’ˆ 상세 νŽ˜μ΄μ§€ ν˜•μ‹μ˜ λ‚΄μš©μ„ 4000 토큰 이상 μžμ„Ένžˆ μ„€λͺ…ν•˜λΌ"],
                    ["μ—…λ‘œλ“œλœ 데이터셋 νŒŒμΌμ„ ν•™μŠ΅ λ°μ΄ν„°λ‘œ ν™œμš©ν•˜μ—¬, FAQ 20건을 μƒμ„Έν•˜κ²Œ μž‘μ„±ν•˜λΌ. 4000토큰 이상 μ‚¬μš©ν•˜λΌ."],
                    ["μ—…λ‘œλ“œλœ 데이터셋 νŒŒμΌμ„ ν•™μŠ΅ λ°μ΄ν„°λ‘œ ν™œμš©ν•˜μ—¬, νŠΉν—ˆ μΆœμ›μ— ν™œμš©ν•  기술 및 λΉ„μ¦ˆλ‹ˆμŠ€ λͺ¨λΈ 츑면을 ν¬ν•¨ν•˜μ—¬ νŠΉν—ˆ μΆœμ›μ„œ ꡬ성에 맞게 ν˜μ‹ μ μΈ 창의 발λͺ… λ‚΄μš©μ„ μ€‘μ‹¬μœΌλ‘œ 4000 토큰 이상 μž‘μ„±ν•˜λΌ."],
                ],
                inputs=msg_data_upload,
                label="예제 선택",
            )

        # Parquet 파일 μ—…λ‘œλ“œλ₯Ό ν™”λ©΄ ν•˜λ‹¨μœΌλ‘œ 이동
        gr.Markdown("### Parquet 파일 μ—…λ‘œλ“œ")
        with gr.Row():
            with gr.Column():
                parquet_upload = gr.File(
                    label="Parquet 파일 μ—…λ‘œλ“œ", type="filepath", elem_id="parquet-upload-area"
                )
                parquet_upload_button = gr.Button("μ—…λ‘œλ“œ")
                parquet_upload_status = gr.Textbox(label="μ—…λ‘œλ“œ μƒνƒœ", interactive=False)
                parquet_preview_chat = gr.Markdown(label="Parquet 파일 미리보기")

                def handle_parquet_upload(file_path: str):
                    message, parquet_content, parquet_json = upload_parquet(file_path)
                    if parquet_json:
                        return message, parquet_content, parquet_json
                    else:
                        return message, "", ""

                parquet_upload_button.click(
                    handle_parquet_upload,
                    inputs=parquet_upload,
                    outputs=[parquet_upload_status, parquet_preview_chat, parquet_data_state]
                )

    # 두 번째 νƒ­: 데이터 λ³€ν™˜ (νƒ­ 이름 λ³€κ²½: "CSV to My 데이터셋")
    with gr.Tab("CSV to My 데이터셋"):
        gr.Markdown("### CSV 파일 μ—…λ‘œλ“œ 및 Parquet λ³€ν™˜")
        with gr.Row():
            with gr.Column():
                csv_file = gr.File(label="CSV 파일 μ—…λ‘œλ“œ", type="filepath")
                upload_button = gr.Button("μ—…λ‘œλ“œ 및 λ³€ν™˜")
                upload_status = gr.Textbox(label="μ—…λ‘œλ“œ μƒνƒœ", interactive=False)
                parquet_preview = gr.Markdown(label="Parquet 파일 미리보기")
                download_button = gr.File(label="Parquet 파일 λ‹€μš΄λ‘œλ“œ", interactive=False)

                def handle_csv_upload(file_path: str):
                    message, parquet_filename = upload_csv(file_path)
                    if parquet_filename:
                        parquet_content = load_parquet(parquet_filename)
                        return message, parquet_content, parquet_filename
                    else:
                        return message, "", None

                upload_button.click(
                    handle_csv_upload,
                    inputs=csv_file,
                    outputs=[upload_status, parquet_preview, download_button]
                )

    # μ„Έ 번째 νƒ­: ν…μŠ€νŠΈ to csv to parquet λ³€ν™˜ (νƒ­ 이름 λ³€κ²½: "Text to My 데이터셋")
    with gr.Tab("Text to My 데이터셋"):
        gr.Markdown("### ν…μŠ€νŠΈλ₯Ό μž…λ ₯ν•˜λ©΄ CSV둜 λ³€ν™˜ ν›„ Parquet으둜 μžλ™ μ „ν™˜λ©λ‹ˆλ‹€.")
        with gr.Row():
            with gr.Column():
                text_input = gr.Textbox(
                    label="ν…μŠ€νŠΈ μž…λ ₯ (각 행은 `id,text,label,metadata` ν˜•μ‹μœΌλ‘œ μž…λ ₯)",
                    lines=10,
                    placeholder='예: 1,"μ΄μˆœμ‹ ","μž₯κ΅°","거뢁선"\n2,"원균","μž₯κ΅°","λͺ¨ν•¨"\n3,"μ„ μ‘°","μ™•","μ‹œκΈ°"\n4,"λ„μš”ν† λ―Έ νžˆλ°μš”μ‹œ","μ™•","침랡"'
                )
                convert_button = gr.Button("λ³€ν™˜ 및 λ‹€μš΄λ‘œλ“œ")
                convert_status = gr.Textbox(label="λ³€ν™˜ μƒνƒœ", interactive=False)
                parquet_preview_convert = gr.Markdown(label="Parquet 파일 미리보기")
                download_parquet_convert = gr.File(label="Parquet 파일 λ‹€μš΄λ‘œλ“œ", interactive=False)

                def handle_text_to_parquet(text: str):
                    message, parquet_content, parquet_filename = text_to_parquet(text)
                    if parquet_filename:
                        return message, parquet_content, parquet_filename
                    else:
                        return message, "", None

                convert_button.click(
                    handle_text_to_parquet,
                    inputs=text_input,
                    outputs=[convert_status, parquet_preview_convert, download_parquet_convert]
                )

    # λ„€λ²ˆμ§Έ νƒ­μ˜ UI λΆ€λΆ„ μˆ˜μ •
    with gr.Tab("Text Preprocessing with LLM"):
        gr.Markdown("### ν…μŠ€νŠΈλ₯Ό μž…λ ₯ν•˜λ©΄ LLM이 데이터셋 ν˜•μ‹μ— 맞게 μ „μ²˜λ¦¬ν•˜μ—¬ 좜λ ₯ν•©λ‹ˆλ‹€.")
        with gr.Row():
            with gr.Column():
                raw_text_input = gr.Textbox(
                    label="ν…μŠ€νŠΈ μž…λ ₯",
                    lines=15,
                    placeholder="여기에 μ „μ²˜λ¦¬ν•  ν…μŠ€νŠΈλ₯Ό μž…λ ₯ν•˜μ„Έμš”..."
                )
                
                with gr.Row():
                    preprocess_button = gr.Button("μ „μ²˜λ¦¬ μ‹€ν–‰", variant="primary")
                    clear_button = gr.Button("μ΄ˆκΈ°ν™”")
    
                preprocess_status = gr.Textbox(
                    label="μ „μ²˜λ¦¬ μƒνƒœ",
                    interactive=False,
                    value="λŒ€κΈ° 쀑..."
                )
                
                processed_text_output = gr.Textbox(
                    label="μ „μ²˜λ¦¬λœ 데이터셋 좜λ ₯",
                    lines=15,
                    interactive=False
                )
                
                # Parquet λ³€ν™˜ 및 λ‹€μš΄λ‘œλ“œ μ„Ήμ…˜
                convert_to_parquet_button = gr.Button("Parquet으둜 λ³€ν™˜")
                download_parquet = gr.File(label="λ³€ν™˜λœ Parquet 파일 λ‹€μš΄λ‘œλ“œ")

                def handle_text_preprocessing(input_text: str):
                    if not input_text.strip():
                        return "μž…λ ₯ ν…μŠ€νŠΈκ°€ μ—†μŠ΅λ‹ˆλ‹€.", ""
                    
                    try:
                        preprocess_status_msg = "μ „μ²˜λ¦¬λ₯Ό μ‹œμž‘ν•©λ‹ˆλ‹€..."
                        yield preprocess_status_msg, ""
                        
                        processed_text = preprocess_text_with_llm(input_text)
                        
                        if processed_text:
                            preprocess_status_msg = "μ „μ²˜λ¦¬κ°€ μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€."
                            yield preprocess_status_msg, processed_text
                        else:
                            preprocess_status_msg = "μ „μ²˜λ¦¬ κ²°κ³Όκ°€ μ—†μŠ΅λ‹ˆλ‹€."
                            yield preprocess_status_msg, ""
                            
                    except Exception as e:
                        error_msg = f"처리 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {str(e)}"
                        yield error_msg, ""

                def clear_inputs():
                    return "", "λŒ€κΈ° 쀑...", ""

                def convert_to_parquet_file(processed_text: str):
                    if not processed_text.strip():
                        return "λ³€ν™˜ν•  ν…μŠ€νŠΈκ°€ μ—†μŠ΅λ‹ˆλ‹€.", None
                    
                    try:
                        message, parquet_content, parquet_filename = text_to_parquet(processed_text)
                        if parquet_filename:
                            return message, parquet_filename
                        return message, None
                    except Exception as e:
                        return f"Parquet λ³€ν™˜ 쀑 였λ₯˜ λ°œμƒ: {str(e)}", None

                # 이벀트 ν•Έλ“€λŸ¬ μ—°κ²°
                preprocess_button.click(
                    handle_text_preprocessing,
                    inputs=[raw_text_input],
                    outputs=[preprocess_status, processed_text_output],
                    queue=True
                )

                clear_button.click(
                    clear_inputs,
                    outputs=[raw_text_input, preprocess_status, processed_text_output]
                )

                convert_to_parquet_button.click(
                    convert_to_parquet_file,
                    inputs=[processed_text_output],
                    outputs=[preprocess_status, download_parquet]
                )

                # 예제 ν…μŠ€νŠΈ μΆ”κ°€
                with gr.Accordion("예제 ν…μŠ€νŠΈ", open=False):
                    gr.Examples(
                        examples=[
                            ["μ΄μˆœμ‹ μ€ μ‘°μ„  μ€‘κΈ°μ˜ 무신이닀. κ·ΈλŠ” μž„μ§„μ™œλž€ λ‹Ήμ‹œ 해ꡰ을 μ΄λŒμ—ˆλ‹€. 거뢁선을 λ§Œλ“€μ–΄ μ™œκ΅°κ³Ό μ‹Έμ› λ‹€."],
                            ["인곡지λŠ₯은 컴퓨터 κ³Όν•™μ˜ ν•œ 뢄야이닀. κΈ°κ³„ν•™μŠ΅μ€ 인곡지λŠ₯의 ν•˜μœ„ 뢄야이닀. λ”₯λŸ¬λ‹μ€ κΈ°κ³„ν•™μŠ΅μ˜ ν•œ 방법이닀."]
                        ],
                        inputs=raw_text_input,
                        label="예제 선택"
                    )

    gr.Markdown("### [email protected]", elem_id="initial-description")

if __name__ == "__main__":
    demo.launch(share=True)  # μ½”λ“œμƒμ˜ 였λ₯˜λ‚˜ κ°œμ„ μ΄ ν•„μš”ν•œ 사항을 μΆ”λ‘ ν•˜μ—¬ λ³΄κ³ ν•˜λΌ