sujeongim0402@gmail.com commited on
Commit
8d79d7e
β€’
1 Parent(s): 631d102

edit codes

Browse files
Files changed (4) hide show
  1. README.md +7 -6
  2. app.py +167 -0
  3. htmlTemplates.py +44 -0
  4. requirements.txt +14 -0
README.md CHANGED
@@ -1,12 +1,13 @@
1
  ---
2
- title: Langchain
3
- emoji: ⚑
4
- colorFrom: green
5
- colorTo: gray
6
- sdk: gradio
7
- sdk_version: 4.7.1
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Basic DAG AI Chatbot With ChatGPT
3
+ emoji: πŸ“š
4
+ colorFrom: purple
5
+ colorTo: purple
6
+ sdk: streamlit
7
+ sdk_version: 1.27.2
8
  app_file: app.py
9
  pinned: false
10
+ license: apache-2.0
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import json
3
+ import streamlit as st
4
+ from dotenv import load_dotenv
5
+ from PyPDF2 import PdfReader
6
+ from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter
7
+ from langchain.embeddings import OpenAIEmbeddings, HuggingFaceInstructEmbeddings
8
+ from langchain.vectorstores import FAISS, Chroma
9
+ from langchain.embeddings import HuggingFaceEmbeddings # General embeddings from HuggingFace models.
10
+ from langchain.chat_models import ChatOpenAI
11
+ from langchain.memory import ConversationBufferMemory
12
+ from langchain.chains import ConversationalRetrievalChain
13
+ from htmlTemplates import css, bot_template, user_template
14
+ from langchain.llms import HuggingFaceHub, LlamaCpp, CTransformers # For loading transformer models.
15
+ from langchain.document_loaders import PyPDFLoader, TextLoader, JSONLoader, CSVLoader
16
+ import tempfile # μž„μ‹œ νŒŒμΌμ„ μƒμ„±ν•˜κΈ° μœ„ν•œ λΌμ΄λΈŒλŸ¬λ¦¬μž…λ‹ˆλ‹€.
17
+ import os
18
+
19
+
20
+ # PDF λ¬Έμ„œλ‘œλΆ€ν„° ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
21
+ def get_pdf_text(pdf_docs):
22
+ temp_dir = tempfile.TemporaryDirectory() # μž„μ‹œ 디렉토리λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
23
+ temp_filepath = os.path.join(temp_dir.name, pdf_docs.name) # μž„μ‹œ 파일 경둜λ₯Ό μƒμ„±ν•©λ‹ˆλ‹€.
24
+ with open(temp_filepath, "wb") as f: # μž„μ‹œ νŒŒμΌμ„ λ°”μ΄λ„ˆλ¦¬ μ“°κΈ° λͺ¨λ“œλ‘œ μ—½λ‹ˆλ‹€.
25
+ f.write(pdf_docs.getvalue()) # PDF λ¬Έμ„œμ˜ λ‚΄μš©μ„ μž„μ‹œ νŒŒμΌμ— μ”λ‹ˆλ‹€.
26
+ pdf_loader = PyPDFLoader(temp_filepath) # PyPDFLoaderλ₯Ό μ‚¬μš©ν•΄ PDFλ₯Ό λ‘œλ“œν•©λ‹ˆλ‹€.
27
+ pdf_doc = pdf_loader.load() # ν…μŠ€νŠΈλ₯Ό μΆ”μΆœν•©λ‹ˆλ‹€.
28
+ return pdf_doc # μΆ”μΆœν•œ ν…μŠ€νŠΈλ₯Ό λ°˜ν™˜ν•©λ‹ˆλ‹€.
29
+
30
+ # 과제
31
+ # μ•„λž˜ ν…μŠ€νŠΈ μΆ”μΆœ ν•¨μˆ˜λ₯Ό μž‘μ„±
32
+
33
+ # Text file extraction
34
+ def get_text_file(docs):
35
+ return docs.read() # Assuming the input is already a text file
36
+
37
+
38
+ # CSV file extraction
39
+ def get_csv_file(docs):
40
+ temp_dir = tempfile.TemporaryDirectory()
41
+ temp_filepath = os.path.join(temp_dir.name, "temp.csv")
42
+ with open(temp_filepath, "wb") as f:
43
+ f.write(docs.getvalue())
44
+
45
+ with open(temp_filepath, "r") as csv_file:
46
+ csv_reader = csv.reader(csv_file)
47
+ csv_data = [row for row in csv_reader]
48
+
49
+ return csv_data
50
+
51
+
52
+ # JSON file extraction
53
+ def get_json_file(docs):
54
+ json_data = json.loads(docs.read())
55
+ return json_data
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
+ # ν…μŠ€νŠΈ μ²­ν¬λ“€λ‘œλΆ€ν„° 벑터 μŠ€ν† μ–΄λ₯Ό μƒμ„±ν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
71
+ def get_vectorstore(text_chunks):
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)
87
+ # λŒ€ν™” 검색 체인을 μƒμ„±ν•©λ‹ˆλ‹€.
88
+ conversation_chain = ConversationalRetrievalChain.from_llm(
89
+ llm=llm,
90
+ retriever=vectorstore.as_retriever(),
91
+ memory=memory
92
+ )
93
+ return conversation_chain
94
+
95
+ # μ‚¬μš©μž μž…λ ₯을 μ²˜λ¦¬ν•˜λŠ” ν•¨μˆ˜μž…λ‹ˆλ‹€.
96
+ def handle_userinput(user_question):
97
+ # λŒ€ν™” 체인을 μ‚¬μš©ν•˜μ—¬ μ‚¬μš©μž μ§ˆλ¬Έμ— λŒ€ν•œ 응닡을 μƒμ„±ν•©λ‹ˆλ‹€.
98
+ response = st.session_state.conversation({'question': user_question})
99
+ # λŒ€ν™” 기둝을 μ €μž₯ν•©λ‹ˆλ‹€.
100
+ st.session_state.chat_history = response['chat_history']
101
+
102
+ for i, message in enumerate(st.session_state.chat_history):
103
+ if i % 2 == 0:
104
+ st.write(user_template.replace(
105
+ "{{MSG}}", message.content), unsafe_allow_html=True)
106
+ else:
107
+ st.write(bot_template.replace(
108
+ "{{MSG}}", message.content), unsafe_allow_html=True)
109
+
110
+
111
+ def main():
112
+ load_dotenv()
113
+ st.set_page_config(page_title="Chat with multiple Files",
114
+ page_icon=":books:")
115
+ st.write(css, unsafe_allow_html=True)
116
+
117
+ if "conversation" not in st.session_state:
118
+ st.session_state.conversation = None
119
+ if "chat_history" not in st.session_state:
120
+ st.session_state.chat_history = None
121
+
122
+ st.header("Chat with multiple Files :")
123
+ user_question = st.text_input("Ask a question about your documents:")
124
+ if user_question:
125
+ handle_userinput(user_question)
126
+
127
+ with st.sidebar:
128
+ openai_key = st.text_input("Paste your OpenAI API key (sk-...)")
129
+ if openai_key:
130
+ os.environ["OPENAI_API_KEY"] = openai_key
131
+
132
+ st.subheader("Your documents")
133
+ docs = st.file_uploader(
134
+ "Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
135
+ if st.button("Process"):
136
+ with st.spinner("Processing"):
137
+ # get pdf text
138
+ doc_list = []
139
+
140
+ for file in docs:
141
+ print('file - type : ', file.type)
142
+ if file.type == 'text/plain':
143
+ # file is .txt
144
+ doc_list.extend(get_text_file(file))
145
+ elif file.type in ['application/octet-stream', 'application/pdf']:
146
+ # file is .pdf
147
+ doc_list.extend(get_pdf_text(file))
148
+ elif file.type == 'text/csv':
149
+ # file is .csv
150
+ doc_list.extend(get_csv_file(file))
151
+ elif file.type == 'application/json':
152
+ # file is .json
153
+ doc_list.extend(get_json_file(file))
154
+
155
+ # get the text chunks
156
+ text_chunks = get_text_chunks(doc_list)
157
+
158
+ # create vector store
159
+ vectorstore = get_vectorstore(text_chunks)
160
+
161
+ # create conversation chain
162
+ st.session_state.conversation = get_conversation_chain(
163
+ vectorstore)
164
+
165
+
166
+ if __name__ == '__main__':
167
+ main()
htmlTemplates.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ css = '''
2
+ <style>
3
+ .chat-message {
4
+ padding: 1.5rem; border-radius: 0.5rem; margin-bottom: 1rem; display: flex
5
+ }
6
+ .chat-message.user {
7
+ background-color: #2b313e
8
+ }
9
+ .chat-message.bot {
10
+ background-color: #475063
11
+ }
12
+ .chat-message .avatar {
13
+ width: 20%;
14
+ }
15
+ .chat-message .avatar img {
16
+ max-width: 78px;
17
+ max-height: 78px;
18
+ border-radius: 50%;
19
+ object-fit: cover;
20
+ }
21
+ .chat-message .message {
22
+ width: 80%;
23
+ padding: 0 1.5rem;
24
+ color: #fff;
25
+ }
26
+ '''
27
+
28
+ bot_template = '''
29
+ <div class="chat-message bot">
30
+ <div class="avatar">
31
+ <img src="https://i.ibb.co/cN0nmSj/Screenshot-2023-05-28-at-02-37-21.png" style="max-height: 78px; max-width: 78px; border-radius: 50%; object-fit: cover;">
32
+ </div>
33
+ <div class="message">{{MSG}}</div>
34
+ </div>
35
+ '''
36
+
37
+ user_template = '''
38
+ <div class="chat-message user">
39
+ <div class="avatar">
40
+ <img src="https://i.ibb.co/rdZC7LZ/Photo-logo-1.png">
41
+ </div>
42
+ <div class="message">{{MSG}}</div>
43
+ </div>
44
+ '''
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ langchain
2
+ llama-cpp-python
3
+ PyPDF2==3.0.1
4
+ faiss-cpu==1.7.4
5
+ ctransformers
6
+ pypdf
7
+ chromadb
8
+ tiktoken
9
+ pysqlite3-binary
10
+ streamlit-extras
11
+ InstructorEmbedding
12
+ sentence-transformers
13
+ jq
14
+ openai