Update app.py
Browse files
app.py
CHANGED
@@ -145,49 +145,56 @@ def text_to_parquet(text: str) -> Tuple[str, str, str]:
|
|
145 |
return error_message, "", ""
|
146 |
|
147 |
def preprocess_text_with_llm(input_text: str) -> str:
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
|
|
|
|
|
|
|
|
161 |
|
162 |
입력 텍스트:
|
|
|
163 |
|
164 |
-
|
165 |
-
|
166 |
-
전처리된 데이터셋:
|
167 |
-
1,"오늘은 날씨가 좋다.","날씨","2023-10-05"
|
168 |
-
2,"내일은 비가 올 예정이다.","날씨","2023-10-05"
|
169 |
-
|
170 |
-
**이제 아래의 입력 텍스트를 처리하세요:**
|
171 |
-
|
172 |
-
""" + input_text
|
173 |
|
174 |
-
# LLM 호출 및 응답 처리
|
175 |
try:
|
176 |
response = ""
|
177 |
stream = hf_client.text_generation(
|
178 |
-
prompt=
|
179 |
-
max_new_tokens=
|
180 |
-
temperature=0.
|
181 |
top_p=0.9,
|
182 |
stream=True,
|
183 |
)
|
|
|
184 |
for msg in stream:
|
185 |
if msg:
|
186 |
response += msg
|
187 |
-
|
188 |
-
|
189 |
processed_text = response.strip()
|
190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
191 |
except Exception as e:
|
192 |
error_message = f"전처리 중 오류가 발생했습니다: {str(e)}\n{traceback.format_exc()}"
|
193 |
print(error_message)
|
@@ -221,8 +228,6 @@ textarea, input[type="text"] {
|
|
221 |
}
|
222 |
"""
|
223 |
|
224 |
-
|
225 |
-
|
226 |
# Gradio Blocks 인터페이스 설정
|
227 |
with gr.Blocks(css=css) as demo:
|
228 |
gr.Markdown("# My RAG: LLM이 나만의 데이터로 학습한 콘텐츠 생성/답변", elem_id="initial-description")
|
@@ -232,6 +237,8 @@ with gr.Blocks(css=css) as demo:
|
|
232 |
elem_id="initial-description"
|
233 |
)
|
234 |
|
|
|
|
|
235 |
# 첫 번째 탭: 챗봇 데이터 업로드 (탭 이름 변경: "My 데이터셋+LLM")
|
236 |
with gr.Tab("My 데이터셋+LLM"):
|
237 |
gr.Markdown("### LLM과 대화하기")
|
@@ -386,7 +393,7 @@ with gr.Blocks(css=css) as demo:
|
|
386 |
outputs=[convert_status, parquet_preview_convert, download_parquet_convert]
|
387 |
)
|
388 |
|
389 |
-
# 네 번째 탭: 텍스트를 데이터셋 형식으로 전처리 (
|
390 |
with gr.Tab("Text Preprocessing with LLM"):
|
391 |
gr.Markdown("### 텍스트를 입력하면 LLM이 데이터셋 형식에 맞게 전처리하여 출력합니다.")
|
392 |
with gr.Row():
|
@@ -396,37 +403,98 @@ with gr.Blocks(css=css) as demo:
|
|
396 |
lines=15,
|
397 |
placeholder="여기에 전처리할 텍스트를 입력하세요..."
|
398 |
)
|
399 |
-
|
400 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
401 |
processed_text_output = gr.Textbox(
|
402 |
label="전처리된 데이터셋 출력",
|
403 |
lines=15,
|
404 |
interactive=False
|
405 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
406 |
|
407 |
def handle_text_preprocessing(input_text: str):
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
413 |
preprocess_button.click(
|
414 |
handle_text_preprocessing,
|
415 |
inputs=[raw_text_input],
|
416 |
-
outputs=[preprocess_status, processed_text_output]
|
|
|
417 |
)
|
418 |
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
|
|
|
|
|
|
|
|
|
|
|
430 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
431 |
|
|
|
432 |
|
|
|
|
|
|
145 |
return error_message, "", ""
|
146 |
|
147 |
def preprocess_text_with_llm(input_text: str) -> str:
|
148 |
+
if not input_text.strip():
|
149 |
+
return "입력 텍스트가 비어있습니다."
|
150 |
+
|
151 |
+
system_prompt = """당신은 데이터 전처리 전문가입니다. 입력된 텍스트를 CSV 데이터셋 형식으로 변환하세요.
|
152 |
+
|
153 |
+
규칙:
|
154 |
+
1. 출력 형식: id,text,label,metadata
|
155 |
+
2. id: 1부터 시작하는 순차적 번호
|
156 |
+
3. text: 의미 있는 단위로 분리된 텍스트
|
157 |
+
4. label: 텍스트의 주제나 카테고리
|
158 |
+
5. metadata: 추가 정보(날짜, 출처 등)
|
159 |
+
|
160 |
+
주의사항:
|
161 |
+
- 텍스트에 쉼표가 있으면 큰따옴표로 감싸기
|
162 |
+
- 큰따옴표는 백슬래시로 이스케이프 처리
|
163 |
+
- 각 행은 새로운 줄로 구분
|
164 |
+
- 모든 필드는 쉼표로 구분
|
165 |
|
166 |
입력 텍스트:
|
167 |
+
"""
|
168 |
|
169 |
+
full_prompt = f"{system_prompt}\n\n{input_text}\n\n출력:"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
170 |
|
|
|
171 |
try:
|
172 |
response = ""
|
173 |
stream = hf_client.text_generation(
|
174 |
+
prompt=full_prompt,
|
175 |
+
max_new_tokens=4000, # 토큰 수 증가
|
176 |
+
temperature=0.3, # 더 결정적인 출력을 위해 낮춤
|
177 |
top_p=0.9,
|
178 |
stream=True,
|
179 |
)
|
180 |
+
|
181 |
for msg in stream:
|
182 |
if msg:
|
183 |
response += msg
|
184 |
+
|
185 |
+
# 응답 정제
|
186 |
processed_text = response.strip()
|
187 |
+
|
188 |
+
# CSV 형식 검증
|
189 |
+
try:
|
190 |
+
# StringIO를 사용하여 CSV 형식 검증
|
191 |
+
from io import StringIO
|
192 |
+
import csv
|
193 |
+
csv.reader(StringIO(processed_text))
|
194 |
+
return processed_text
|
195 |
+
except csv.Error:
|
196 |
+
return "LLM이 올바른 CSV 형식을 생성하지 못했습니다. 다시 시도해주세요."
|
197 |
+
|
198 |
except Exception as e:
|
199 |
error_message = f"전처리 중 오류가 발생했습니다: {str(e)}\n{traceback.format_exc()}"
|
200 |
print(error_message)
|
|
|
228 |
}
|
229 |
"""
|
230 |
|
|
|
|
|
231 |
# Gradio Blocks 인터페이스 설정
|
232 |
with gr.Blocks(css=css) as demo:
|
233 |
gr.Markdown("# My RAG: LLM이 나만의 데이터로 학습한 콘텐츠 생성/답변", elem_id="initial-description")
|
|
|
237 |
elem_id="initial-description"
|
238 |
)
|
239 |
|
240 |
+
|
241 |
+
|
242 |
# 첫 번째 탭: 챗봇 데이터 업로드 (탭 이름 변경: "My 데이터셋+LLM")
|
243 |
with gr.Tab("My 데이터셋+LLM"):
|
244 |
gr.Markdown("### LLM과 대화하기")
|
|
|
393 |
outputs=[convert_status, parquet_preview_convert, download_parquet_convert]
|
394 |
)
|
395 |
|
396 |
+
# 네 번째 탭: 텍스트를 데이터셋 형식으로 전처리 (개선된 버전)
|
397 |
with gr.Tab("Text Preprocessing with LLM"):
|
398 |
gr.Markdown("### 텍스트를 입력하면 LLM이 데이터셋 형식에 맞게 전처리하여 출력합니다.")
|
399 |
with gr.Row():
|
|
|
403 |
lines=15,
|
404 |
placeholder="여기에 전처리할 텍스트를 입력하세요..."
|
405 |
)
|
406 |
+
|
407 |
+
with gr.Row():
|
408 |
+
preprocess_button = gr.Button("전처리 실행", variant="primary")
|
409 |
+
clear_button = gr.Button("초기화")
|
410 |
+
|
411 |
+
preprocess_status = gr.Textbox(
|
412 |
+
label="전처리 상태",
|
413 |
+
interactive=False,
|
414 |
+
value="대기 중..."
|
415 |
+
)
|
416 |
+
|
417 |
processed_text_output = gr.Textbox(
|
418 |
label="전처리된 데이터셋 출력",
|
419 |
lines=15,
|
420 |
interactive=False
|
421 |
)
|
422 |
+
|
423 |
+
# Parquet 변환 및 다운로드 섹션
|
424 |
+
with gr.Row():
|
425 |
+
convert_to_parquet_button = gr.Button("Parquet으로 변환", visible=True)
|
426 |
+
download_parquet = gr.File(
|
427 |
+
label="변환된 Parquet 파일 다운로드",
|
428 |
+
visible=False
|
429 |
+
)
|
430 |
|
431 |
def handle_text_preprocessing(input_text: str):
|
432 |
+
if not input_text.strip():
|
433 |
+
return "입력 텍스트가 없습니다.", ""
|
434 |
+
|
435 |
+
try:
|
436 |
+
preprocess_status_msg = "전처리를 시작합니다..."
|
437 |
+
yield preprocess_status_msg, ""
|
438 |
+
|
439 |
+
processed_text = preprocess_text_with_llm(input_text)
|
440 |
+
|
441 |
+
if processed_text:
|
442 |
+
preprocess_status_msg = "전처리가 완료되었습니다."
|
443 |
+
yield preprocess_status_msg, processed_text
|
444 |
+
else:
|
445 |
+
preprocess_status_msg = "전처리 결과가 없습니다."
|
446 |
+
yield preprocess_status_msg, ""
|
447 |
+
|
448 |
+
except Exception as e:
|
449 |
+
error_msg = f"처리 중 오류가 발생했습니다: {str(e)}"
|
450 |
+
yield error_msg, ""
|
451 |
+
|
452 |
+
def clear_inputs():
|
453 |
+
return "", "대기 중...", ""
|
454 |
+
|
455 |
+
def convert_to_parquet_file(processed_text: str):
|
456 |
+
if not processed_text.strip():
|
457 |
+
return "변환할 텍스트가 없습니다.", None
|
458 |
+
|
459 |
+
try:
|
460 |
+
message, parquet_content, parquet_filename = text_to_parquet(processed_text)
|
461 |
+
if parquet_filename:
|
462 |
+
return message, parquet_filename
|
463 |
+
return message, None
|
464 |
+
except Exception as e:
|
465 |
+
return f"Parquet 변환 중 오류 발생: {str(e)}", None
|
466 |
+
|
467 |
+
# 이벤트 핸들러 연결
|
468 |
preprocess_button.click(
|
469 |
handle_text_preprocessing,
|
470 |
inputs=[raw_text_input],
|
471 |
+
outputs=[preprocess_status, processed_text_output],
|
472 |
+
queue=True
|
473 |
)
|
474 |
|
475 |
+
clear_button.click(
|
476 |
+
clear_inputs,
|
477 |
+
outputs=[raw_text_input, preprocess_status, processed_text_output]
|
478 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
479 |
|
480 |
+
convert_to_parquet_button.click(
|
481 |
+
convert_to_parquet_file,
|
482 |
+
inputs=[processed_text_output],
|
483 |
+
outputs=[preprocess_status, download_parquet]
|
484 |
+
)
|
485 |
|
486 |
+
# 예제 텍스트 추가
|
487 |
+
with gr.Accordion("예제 텍스트", open=False):
|
488 |
+
gr.Examples(
|
489 |
+
examples=[
|
490 |
+
["이순신은 조선 중기의 무신이다. 그는 임진왜란 당시 해군을 이끌었다. 거북선을 만들어 왜군과 싸웠다."],
|
491 |
+
["인공지능은 컴퓨터 과학의 한 분야이다. 기계학습은 인공지능의 하위 분야이다. 딥러닝은 기계학습의 한 방법이다."]
|
492 |
+
],
|
493 |
+
inputs=raw_text_input,
|
494 |
+
label="예제 선택"
|
495 |
+
)
|
496 |
|
497 |
+
gr.Markdown("### [email protected]", elem_id="initial-description")
|
498 |
|
499 |
+
if __name__ == "__main__":
|
500 |
+
demo.launch(share=True)
|