Daoneeee commited on
Commit
2712123
·
1 Parent(s): acd4925

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -33
app.py CHANGED
@@ -11,48 +11,39 @@ from langchain.chains import ConversationalRetrievalChain
11
  from htmlTemplates import css, bot_template, user_template
12
  from langchain.llms import HuggingFaceHub, LlamaCpp, CTransformers # For loading transformer models.
13
  from langchain.document_loaders import PyPDFLoader, TextLoader, JSONLoader, CSVLoader
14
- import tempfile # 임시 파일을 생성하기 위한 라이브러리입니다.
15
  import os
16
 
17
 
18
  # PDF 문서로부터 텍스트를 추출하는 함수입니다.
19
  def get_pdf_text(pdf_docs):
20
- temp_dir = tempfile.TemporaryDirectory() # 임시 디렉토리를 생성합니다.
21
- temp_filepath = os.path.join(temp_dir.name, pdf_docs.name) # 임시 파일 경로를 생성합니다.
22
  with open(temp_filepath, "wb") as f: # 임시 파일을 바이너리 쓰기 모드로 엽니다.
23
- f.write(pdf_docs.getvalue()) # PDF 문서의 내용을 임시 파일에 씁니다.
24
- pdf_loader = PyPDFLoader(temp_filepath) # PyPDFLoader를 사용해 PDF를 로드합니다.
25
- pdf_doc = pdf_loader.load() # 텍스트를 추출합니다.
26
- return pdf_doc # 추출한 텍스트를 반환합니다.
 
27
 
28
  # 과제
29
  # 아래 텍스트 추출 함수를 작성
30
 
31
  def get_text_file(docs):
32
- # 텍스트 파일의 경우, 내용을 바로 읽어옵니다.
33
- text_content = docs.getvalue().decode("utf-8") # UTF-8 인코딩을 기준으로 디코딩합니다.
34
  return [text_content]
35
 
36
  def get_csv_file(docs):
37
- # CSV 파일의 경우, 각 행 또는 열에서 텍스트를 추출합니다.
38
- import pandas as pd
39
- csv_content = docs.getvalue().decode("utf-8") # 바이트를 문자열로 디코딩합니다.
40
- csv_data = pd.read_csv(pd.compat.StringIO(csv_content)) # Pandas를 사용하여 CSV를 읽어옵니다.
41
  text_list = []
42
-
43
- # 필요한 대로 각 열 또는 행에서 텍스트를 추출합니다.
44
  for column in csv_data.columns:
45
  text_list.extend(csv_data[column].astype(str).tolist())
46
-
47
  return text_list
48
 
49
  def get_json_file(docs):
50
- # JSON 파일의 경우, 특정 키 또는 값에서 텍스트를 추출합니다.
51
- import json
52
- json_content = docs.getvalue().decode("utf-8") # 바이트를 문자열로 디코딩합니다.
53
  json_data = json.loads(json_content)
54
-
55
- # 필요한 대로 JSON 키 또는 값에서 텍스트를 추출합니다.
56
  text_list = []
57
  for key, value in json_data.items():
58
  if isinstance(value, str):
@@ -61,20 +52,19 @@ def get_json_file(docs):
61
  text_list.extend(value)
62
  elif isinstance(value, dict):
63
  text_list.extend(value.values())
64
-
65
  return text_list
66
 
67
-
68
  # 문서들을 처리하여 텍스트 청크로 나누는 함수입니다.
69
  def get_text_chunks(documents):
70
  text_splitter = RecursiveCharacterTextSplitter(
71
- chunk_size=1000, # 청크의 크기를 지정합니다.
72
- chunk_overlap=200, # 청크 사이의 중복을 지정합니다.
73
- length_function=len # 텍스트의 길이를 측정하는 함수를 지정합니다.
74
  )
75
 
76
- documents = text_splitter.split_documents(documents) # 문서들을 청크로 나눕니다
77
- return documents # 나눈 청크를 반환합니다.
78
 
79
 
80
  # 텍스트 청크들로부터 벡터 스토어를 생성하는 함수입니다.
@@ -82,15 +72,15 @@ def get_vectorstore(text_chunks):
82
  # OpenAI 임베딩 모델을 로드합니다. (Embedding models - Ada v2)
83
 
84
  embeddings = OpenAIEmbeddings()
85
- vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS 벡터 스토어를 생성합니다.
86
 
87
- return vectorstore # 생성된 벡터 스토어를 반환합니다.
88
 
89
 
90
  def get_conversation_chain(vectorstore):
91
  gpt_model_name = 'gpt-3.5-turbo'
92
- llm = ChatOpenAI(model_name = gpt_model_name) #gpt-3.5 모델 로드
93
-
94
  # 대화 기록을 저장하기 위한 메모리를 생성합니다.
95
  memory = ConversationBufferMemory(
96
  memory_key='chat_history', return_messages=True)
@@ -102,6 +92,7 @@ def get_conversation_chain(vectorstore):
102
  )
103
  return conversation_chain
104
 
 
105
  # 사용자 입력을 처리하는 함수입니다.
106
  def handle_userinput(user_question):
107
  # 대화 체인을 사용하여 사용자 질문에 대한 응답을 생성합니다.
@@ -176,4 +167,3 @@ def main():
176
  if __name__ == '__main__':
177
  main()
178
 
179
-
 
11
  from htmlTemplates import css, bot_template, user_template
12
  from langchain.llms import HuggingFaceHub, LlamaCpp, CTransformers # For loading transformer models.
13
  from langchain.document_loaders import PyPDFLoader, TextLoader, JSONLoader, CSVLoader
14
+ import tempfile # 임시 파일을 생성하기 위한 라이브러리입니다.
15
  import os
16
 
17
 
18
  # PDF 문서로부터 텍스트를 추출하는 함수입니다.
19
  def get_pdf_text(pdf_docs):
20
+ temp_dir = tempfile.TemporaryDirectory() # 임시 디렉토리를 생성합니다.
21
+ temp_filepath = os.path.join(temp_dir.name, pdf_docs.name) # 임시 파일 경로를 생성합니다.
22
  with open(temp_filepath, "wb") as f: # 임시 파일을 바이너리 쓰기 모드로 엽니다.
23
+ f.write(pdf_docs.getvalue()) # PDF 문서의 내용을 임시 파일에 씁니다.
24
+ pdf_loader = PyPDFLoader(temp_filepath) # PyPDFLoader를 사용해 PDF를 로드합니다.
25
+ pdf_doc = pdf_loader.load() # 텍스트를 추출합니다.
26
+ return pdf_doc # 추출한 텍스트를 반환합니다.
27
+
28
 
29
  # 과제
30
  # 아래 텍스트 추출 함수를 작성
31
 
32
  def get_text_file(docs):
33
+ text_content = docs.getvalue().decode("utf-8")
 
34
  return [text_content]
35
 
36
  def get_csv_file(docs):
37
+ csv_content = docs.getvalue().decode("utf-8")
38
+ csv_data = pd.read_csv(pd.compat.StringIO(csv_content))
 
 
39
  text_list = []
 
 
40
  for column in csv_data.columns:
41
  text_list.extend(csv_data[column].astype(str).tolist())
 
42
  return text_list
43
 
44
  def get_json_file(docs):
45
+ json_content = docs.getvalue().decode("utf-8")
 
 
46
  json_data = json.loads(json_content)
 
 
47
  text_list = []
48
  for key, value in json_data.items():
49
  if isinstance(value, str):
 
52
  text_list.extend(value)
53
  elif isinstance(value, dict):
54
  text_list.extend(value.values())
 
55
  return text_list
56
 
57
+
58
  # 문서들을 처리하여 텍스트 청크로 나누는 함수입니다.
59
  def get_text_chunks(documents):
60
  text_splitter = RecursiveCharacterTextSplitter(
61
+ chunk_size=1000, # 청크의 크기를 지정합니다.
62
+ chunk_overlap=200, # 청크 사이의 중복을 지정합니다.
63
+ length_function=len # 텍스트의 길이를 측정하는 함수를 지정합니다.
64
  )
65
 
66
+ documents = text_splitter.split_documents(documents) # 문서들을 청크로 나눕니다
67
+ return documents # 나눈 청크를 반환합니다.
68
 
69
 
70
  # 텍스트 청크들로부터 벡터 스토어를 생성하는 함수입니다.
 
72
  # OpenAI 임베딩 모델을 로드합니다. (Embedding models - Ada v2)
73
 
74
  embeddings = OpenAIEmbeddings()
75
+ vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS 벡터 스토어를 생성합니다.
76
 
77
+ return vectorstore # 생성된 벡터 스토어를 반환합니다.
78
 
79
 
80
  def get_conversation_chain(vectorstore):
81
  gpt_model_name = 'gpt-3.5-turbo'
82
+ llm = ChatOpenAI(model_name=gpt_model_name) # gpt-3.5 모델 로드
83
+
84
  # 대화 기록을 저장하기 위한 메모리를 생성합니다.
85
  memory = ConversationBufferMemory(
86
  memory_key='chat_history', return_messages=True)
 
92
  )
93
  return conversation_chain
94
 
95
+
96
  # 사용자 입력을 처리하는 함수입니다.
97
  def handle_userinput(user_question):
98
  # 대화 체인을 사용하여 사용자 질문에 대한 응답을 생성합니다.
 
167
  if __name__ == '__main__':
168
  main()
169