File size: 24,332 Bytes
747ccea
 
fe67895
90e9b67
0fbbd89
749529a
071b7e9
9f4a039
46b5d6c
79997b0
54a4802
3c698c1
 
 
0e5afe0
0fbbd89
6da265e
c36dc6b
6da265e
d59bb1e
 
 
 
6da265e
0fbbd89
90e9b67
 
c3ae439
90e9b67
 
 
 
 
747ccea
0fbbd89
8f71308
0fbbd89
5fd7b47
 
0fbbd89
9f4a039
0fbbd89
ca69132
d8a457b
749529a
9f4a039
 
 
 
 
 
 
 
749529a
 
071b7e9
2d978fc
9f4a039
f6e3821
9f4a039
 
 
 
 
747ccea
90e9b67
0fbbd89
d8a457b
9f4a039
 
 
90e9b67
 
 
9f4a039
 
2d978fc
 
90e9b67
 
9f4a039
 
 
 
0fbbd89
4f42976
0fbbd89
f6e3821
0fbbd89
884361c
 
 
 
0fbbd89
4f42976
 
 
 
 
 
f6e3821
4f42976
c8b6371
ca69132
0fbbd89
ca69132
d8a457b
ca69132
 
f6e3821
0fbbd89
c8b6371
749529a
 
d8a457b
4f42976
d8a457b
4f42976
c8b6371
f6e3821
b058138
06ef6db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46b5d6c
06ef6db
46b5d6c
06ef6db
 
 
46b5d6c
06ef6db
2bb387f
749529a
06ef6db
f6e3821
 
 
06ef6db
0fbbd89
f6e3821
06ef6db
c8b6371
06ef6db
f6e3821
06ef6db
 
46b5d6c
f6e3821
79997b0
b50c10b
 
 
 
 
 
 
 
 
06ef6db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b50c10b
 
06ef6db
b50c10b
 
06ef6db
b25fdc4
06ef6db
b9810ca
79997b0
b25fdc4
 
 
06ef6db
 
79997b0
b25fdc4
79997b0
b50c10b
b25fdc4
 
 
 
06ef6db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b50c10b
 
 
 
 
 
 
 
 
 
79997b0
06ef6db
79997b0
 
 
0fbbd89
66fa514
 
 
 
8f71308
3c698c1
2bb387f
f6e3821
8f71308
f6e3821
 
dea516f
 
 
 
 
3c698c1
 
 
 
 
 
 
 
 
66fa514
 
4f42976
79997b0
3c698c1
 
2442eca
1071ed2
3c698c1
 
 
b50c10b
 
6fd59f1
 
884361c
d8a457b
 
 
884361c
71edfae
95a32d4
dea516f
71edfae
 
 
749529a
 
3c698c1
 
 
 
 
 
 
 
 
2013128
 
1071ed2
 
0fbbd89
3c698c1
 
 
d8a457b
0fbbd89
d8a457b
3c698c1
 
 
 
 
1071ed2
3c698c1
2013128
0fbbd89
 
d8a457b
2013128
d8a457b
 
5d1bacd
 
 
 
 
 
 
 
 
d8a457b
 
2013128
 
3c698c1
 
 
 
707bf52
1071ed2
707bf52
 
 
1071ed2
3c698c1
 
 
 
 
1071ed2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6fd59f1
 
884361c
 
 
95a32d4
884361c
 
 
c8b6371
ca69132
c8b6371
f6e3821
ca69132
c8b6371
 
ca69132
 
 
884361c
ca69132
884361c
ca69132
884361c
 
6fd59f1
 
dea516f
 
 
 
 
 
46b5d6c
dea516f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06ef6db
79997b0
 
 
 
 
 
 
 
 
b50c10b
 
 
 
06ef6db
b50c10b
 
 
 
 
 
79997b0
 
 
 
 
b50c10b
 
06ef6db
 
 
 
 
79997b0
 
b50c10b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79997b0
 
5d1bacd
b50c10b
 
79997b0
 
b50c10b
 
 
 
b9810ca
b50c10b
 
 
 
 
b9810ca
b50c10b
 
 
 
 
 
 
 
 
 
5d1bacd
b50c10b
6311e3f
b50c10b
b3bb461
 
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
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

# 추론 API 클라이언트 설정
hf_client = InferenceClient(
    "CohereForAI/c4ai-command-r-plus-08-2024", token=os.getenv("HF_TOKEN")
)

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에 쉼표가 있으면 큰따옴표로 감싸기
- 큰따옴표는 백슬래시로 이스케이프 처리
- 각 행은 새로운 줄로 구분
- 불필요한 반복 출력 금지"""

    full_prompt = f"{system_prompt}\n\n입력텍스트:\n{input_text}\n\n출력:"

    try:
        response = ""
        stream = hf_client.text_generation(
            prompt=full_prompt,
            max_new_tokens=4000,
            temperature=0.1,  # 더 결정적인 출력을 위해 낮춤
            top_p=0.9,
            stream=True,
        )
        
        for msg in stream:
            if msg:
                response += msg
        
        # <EOS_TOKEN> 이전까지만 추출하고 정제
        if "<EOS_TOKEN>" in response:
            processed_text = response.split("<EOS_TOKEN>")[0].strip()
        else:
            processed_text = response.strip()
            
        # 중복 출력 제거
        lines = processed_text.split('\n')
        unique_lines = []
        seen_texts = set()
        
        for line in lines:
            line = line.strip()
            if line and '출력:' not in line and line not in seen_texts:
                unique_lines.append(line)
                seen_texts.add(line)
        
        processed_text = '\n'.join(unique_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)