Update app.py
Browse files
app.py
CHANGED
@@ -7,6 +7,9 @@ import json
|
|
7 |
import io
|
8 |
import traceback
|
9 |
import csv
|
|
|
|
|
|
|
10 |
|
11 |
# 추론 API 클라이언트 설정
|
12 |
hf_client = InferenceClient(
|
@@ -31,8 +34,13 @@ def load_parquet(filename: str) -> str:
|
|
31 |
except Exception as e:
|
32 |
return f"파일을 읽는 중 오류가 발생했습니다: {str(e)}"
|
33 |
|
|
|
|
|
|
|
|
|
|
|
34 |
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:
|
35 |
-
# 시스템 프롬프트
|
36 |
system_prefix = """반드시 한글로 답변할 것. 너는 업로드된 데이터를 기반으로 질문에 답변하는 역할을 한다.
|
37 |
|
38 |
주요 지침:
|
@@ -50,35 +58,36 @@ def respond(message: str, history: List[Dict[str, str]], system_message: str = "
|
|
50 |
system_prefix += f"\n\n데이터 요약:\n{data_summary}"
|
51 |
except Exception as e:
|
52 |
print(f"데이터 로드 오류: {str(e)}")
|
|
|
|
|
|
|
53 |
|
54 |
# 최근 대화 컨텍스트만 유지
|
55 |
recent_history = history[-3:] if history else []
|
56 |
-
|
57 |
-
prompt = system_prefix + "\n\n"
|
58 |
for chat in recent_history:
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
prompt += f"AI: {chat['content']}\n"
|
63 |
-
prompt += f"사용자: {message}\nAI:"
|
64 |
|
65 |
try:
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
temperature=temperature,
|
72 |
top_p=top_p,
|
73 |
-
|
74 |
)
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
|
|
79 |
# 응답 정제
|
80 |
-
cleaned_response = clean_response(
|
81 |
yield cleaned_response
|
|
|
82 |
except Exception as e:
|
83 |
error_message = f"추론 오류: {str(e)}"
|
84 |
print(error_message)
|
@@ -216,6 +225,7 @@ def text_to_parquet(text: str) -> Tuple[str, str, str]:
|
|
216 |
print(f"{error_message}\n{traceback.format_exc()}")
|
217 |
return error_message, "", ""
|
218 |
|
|
|
219 |
def preprocess_text_with_llm(input_text: str) -> str:
|
220 |
if not input_text.strip():
|
221 |
return "입력 텍스트가 비어있습니다."
|
@@ -232,56 +242,78 @@ def preprocess_text_with_llm(input_text: str) -> str:
|
|
232 |
- Technology (기술)
|
233 |
- Politics (정치)
|
234 |
- Culture (문화)
|
235 |
-
5. metadata: 날짜, 출처 등 추가 정보
|
236 |
|
237 |
-
|
238 |
-
|
239 |
-
-
|
240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
241 |
|
242 |
-
|
243 |
-
|
|
|
|
|
244 |
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
250 |
|
251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
252 |
|
253 |
try:
|
254 |
-
response =
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
|
|
|
|
261 |
)
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
else:
|
271 |
-
processed_text = response.strip()
|
272 |
-
|
273 |
-
# 중복 출력 제거
|
274 |
-
lines = processed_text.split('\n')
|
275 |
-
unique_lines = []
|
276 |
-
seen_texts = set()
|
277 |
-
|
278 |
-
for line in lines:
|
279 |
-
line = line.strip()
|
280 |
-
if line and '출력:' not in line and line not in seen_texts:
|
281 |
-
unique_lines.append(line)
|
282 |
-
seen_texts.add(line)
|
283 |
-
|
284 |
-
processed_text = '\n'.join(unique_lines)
|
285 |
|
286 |
# CSV 형식 검증
|
287 |
try:
|
@@ -599,3 +631,5 @@ with gr.Blocks(css=css) as demo:
|
|
599 |
if __name__ == "__main__":
|
600 |
demo.launch(share=True)
|
601 |
|
|
|
|
|
|
7 |
import io
|
8 |
import traceback
|
9 |
import csv
|
10 |
+
# HuggingFace 클라이언트 대신 OpenAI 클라이언트 사용
|
11 |
+
from openai import OpenAI
|
12 |
+
import os
|
13 |
|
14 |
# 추론 API 클라이언트 설정
|
15 |
hf_client = InferenceClient(
|
|
|
34 |
except Exception as e:
|
35 |
return f"파일을 읽는 중 오류가 발생했습니다: {str(e)}"
|
36 |
|
37 |
+
|
38 |
+
# OpenAI 클라이언트 설정
|
39 |
+
client = OpenAI(api_key=os.getenv("OPEN_AI"))
|
40 |
+
|
41 |
+
# respond 함수 수정
|
42 |
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:
|
43 |
+
# 시스템 프롬프트 설정
|
44 |
system_prefix = """반드시 한글로 답변할 것. 너는 업로드된 데이터를 기반으로 질문에 답변하는 역할을 한다.
|
45 |
|
46 |
주요 지침:
|
|
|
58 |
system_prefix += f"\n\n데이터 요약:\n{data_summary}"
|
59 |
except Exception as e:
|
60 |
print(f"데이터 로드 오류: {str(e)}")
|
61 |
+
|
62 |
+
# 대화 히스토리 구성
|
63 |
+
messages = [{"role": "system", "content": system_prefix}]
|
64 |
|
65 |
# 최근 대화 컨텍스트만 유지
|
66 |
recent_history = history[-3:] if history else []
|
|
|
|
|
67 |
for chat in recent_history:
|
68 |
+
messages.append({"role": chat["role"], "content": chat["content"]})
|
69 |
+
|
70 |
+
messages.append({"role": "user", "content": message})
|
|
|
|
|
71 |
|
72 |
try:
|
73 |
+
# OpenAI API 호출
|
74 |
+
response = client.chat.completions.create(
|
75 |
+
model="gpt-4-0125-preview", # GPT-4-mini 모델 사용
|
76 |
+
messages=messages,
|
77 |
+
max_tokens=max_tokens,
|
78 |
temperature=temperature,
|
79 |
top_p=top_p,
|
80 |
+
stream=True
|
81 |
)
|
82 |
+
|
83 |
+
full_response = ""
|
84 |
+
for chunk in response:
|
85 |
+
if chunk.choices[0].delta.content:
|
86 |
+
full_response += chunk.choices[0].delta.content
|
87 |
# 응답 정제
|
88 |
+
cleaned_response = clean_response(full_response)
|
89 |
yield cleaned_response
|
90 |
+
|
91 |
except Exception as e:
|
92 |
error_message = f"추론 오류: {str(e)}"
|
93 |
print(error_message)
|
|
|
225 |
print(f"{error_message}\n{traceback.format_exc()}")
|
226 |
return error_message, "", ""
|
227 |
|
228 |
+
# preprocess_text_with_llm 함수도 수정
|
229 |
def preprocess_text_with_llm(input_text: str) -> str:
|
230 |
if not input_text.strip():
|
231 |
return "입력 텍스트가 비어있습니다."
|
|
|
242 |
- Technology (기술)
|
243 |
- Politics (정치)
|
244 |
- Culture (문화)
|
245 |
+
5. metadata: 날짜, 출처 등 추가 정보"""
|
246 |
|
247 |
+
try:
|
248 |
+
response = client.chat.completions.create(
|
249 |
+
model="gpt-4-0125-preview",
|
250 |
+
messages=[
|
251 |
+
{"role": "system", "content": system_prompt},
|
252 |
+
{"role": "user", "content": input_text}
|
253 |
+
],
|
254 |
+
max_tokens=4000,
|
255 |
+
temperature=0.1,
|
256 |
+
stream=True
|
257 |
+
)
|
258 |
|
259 |
+
full_response = ""
|
260 |
+
for chunk in response:
|
261 |
+
if chunk.choices[0].delta.content:
|
262 |
+
full_response += chunk.choices[0].delta.content
|
263 |
|
264 |
+
# 응답 정제
|
265 |
+
processed_text = clean_response(full_response)
|
266 |
+
|
267 |
+
# CSV 형식 검증
|
268 |
+
try:
|
269 |
+
from io import StringIO
|
270 |
+
import csv
|
271 |
+
csv.reader(StringIO(processed_text))
|
272 |
+
return processed_text
|
273 |
+
except csv.Error:
|
274 |
+
return "LLM이 올바른 CSV 형식을 생성하지 못했습니다. 다시 시도해주세요."
|
275 |
+
|
276 |
+
except Exception as e:
|
277 |
+
error_message = f"전처리 중 오류가 발생했습니다: {str(e)}"
|
278 |
+
print(error_message)
|
279 |
+
return error_message# preprocess_text_with_llm 함수도 수정
|
280 |
+
def preprocess_text_with_llm(input_text: str) -> str:
|
281 |
+
if not input_text.strip():
|
282 |
+
return "입력 텍스트가 비어있습니다."
|
283 |
+
|
284 |
+
system_prompt = """반드시 한글(한국어)로 답변하시오. 당신은 데이터 전처리 전문가입니다. 입력된 텍스트를 CSV 데이터셋 형식으로 변환하세요.
|
285 |
|
286 |
+
규칙:
|
287 |
+
1. 출력 형식: id,text,label,metadata
|
288 |
+
2. id: 1부터 시작하는 순차적 번호
|
289 |
+
3. text: 의미 있는 단위로 분리된 텍스트
|
290 |
+
4. label: 텍스트의 주제나 카테고리를 아래 기준으로 정확하게 한 개만 선택
|
291 |
+
- Historical_Figure (역사적 인물)
|
292 |
+
- Military_History (군사 역사)
|
293 |
+
- Technology (기술)
|
294 |
+
- Politics (정치)
|
295 |
+
- Culture (문화)
|
296 |
+
5. metadata: 날짜, 출처 등 추가 정보"""
|
297 |
|
298 |
try:
|
299 |
+
response = client.chat.completions.create(
|
300 |
+
model="gpt-4o-mini",
|
301 |
+
messages=[
|
302 |
+
{"role": "system", "content": system_prompt},
|
303 |
+
{"role": "user", "content": input_text}
|
304 |
+
],
|
305 |
+
max_tokens=4000,
|
306 |
+
temperature=0.1,
|
307 |
+
stream=True
|
308 |
)
|
309 |
+
|
310 |
+
full_response = ""
|
311 |
+
for chunk in response:
|
312 |
+
if chunk.choices[0].delta.content:
|
313 |
+
full_response += chunk.choices[0].delta.content
|
314 |
+
|
315 |
+
# 응답 정제
|
316 |
+
processed_text = clean_response(full_response)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
317 |
|
318 |
# CSV 형식 검증
|
319 |
try:
|
|
|
631 |
if __name__ == "__main__":
|
632 |
demo.launch(share=True)
|
633 |
|
634 |
+
|
635 |
+
llm 모델 변경하라. openai api를 이용하고 모델은 gpt-4o-mini로 설정하라. api키는 os.getenv("OPEN_AI")를 이용하라
|