Update app.py
Browse files
app.py
CHANGED
|
@@ -81,7 +81,7 @@ def get_conversation_chain(vectorstore, tokenH):
|
|
| 81 |
def generate_response(messages):
|
| 82 |
try:
|
| 83 |
completion = client.chat.completions.create(
|
| 84 |
-
model="
|
| 85 |
messages=messages,
|
| 86 |
max_tokens=500
|
| 87 |
)
|
|
@@ -148,516 +148,3 @@ def main():
|
|
| 148 |
if __name__ == '__main__':
|
| 149 |
main()
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
# import streamlit as st
|
| 154 |
-
# from dotenv import load_dotenv
|
| 155 |
-
# from PyPDF2 import PdfReader
|
| 156 |
-
# from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter
|
| 157 |
-
# from langchain_community.embeddings import OpenAIEmbeddings, HuggingFaceInstructEmbeddings
|
| 158 |
-
# from langchain_community.vectorstores import FAISS, Chroma
|
| 159 |
-
# from langchain_community.embeddings import HuggingFaceEmbeddings # General embeddings from HuggingFace models.
|
| 160 |
-
# from langchain.chat_models import ChatOpenAI
|
| 161 |
-
# from langchain.memory import ConversationBufferMemory
|
| 162 |
-
# from langchain.chains import ConversationalRetrievalChain
|
| 163 |
-
# from htmlTemplates import css, bot_template, user_template
|
| 164 |
-
# from langchain.llms import HuggingFaceHub, LlamaCpp, CTransformers # For loading transformer models.
|
| 165 |
-
# from langchain_community.document_loaders import PyPDFLoader, TextLoader, JSONLoader, CSVLoader
|
| 166 |
-
# import tempfile # 임시 파일을 생성하기 위한 라이브러리입니다.
|
| 167 |
-
# import os
|
| 168 |
-
|
| 169 |
-
# def get_pdf_text(pdf_docs):
|
| 170 |
-
# temp_dir = tempfile.TemporaryDirectory() # 임시 디렉토리를 생성합니다.
|
| 171 |
-
# temp_filepath = os.path.join(temp_dir.name, pdf_docs.name) # 임시 파일 경로를 생성합니다.
|
| 172 |
-
# with open(temp_filepath, "wb") as f: # 임시 파일을 바이너리 쓰기 모드로 엽니다.
|
| 173 |
-
# f.write(pdf_docs.getvalue()) # PDF 문서의 내용을 임시 파일에 씁니다.
|
| 174 |
-
# pdf_loader = PyPDFLoader(temp_filepath) # PyPDFLoader를 사용해 PDF를 로드합니다.
|
| 175 |
-
# pdf_doc = pdf_loader.load() # 텍스트를 추출합니다.
|
| 176 |
-
# return pdf_doc # 추출한 텍스트를 반환합니다.
|
| 177 |
-
|
| 178 |
-
# def get_text_file(text_docs):
|
| 179 |
-
# temp_dir = tempfile.TemporaryDirectory()
|
| 180 |
-
# temp_filepath = os.path.join(temp_dir.name, text_docs.name)
|
| 181 |
-
# with open(temp_filepath, "wb") as f:
|
| 182 |
-
# f.write(text_docs.getvalue())
|
| 183 |
-
# text_loader = TextLoader(temp_filepath)
|
| 184 |
-
# text_doc = text_loader.load()
|
| 185 |
-
# return text_doc
|
| 186 |
-
|
| 187 |
-
# def get_csv_file(csv_docs):
|
| 188 |
-
# temp_dir = tempfile.TemporaryDirectory()
|
| 189 |
-
# temp_filepath = os.path.join(temp_dir.name, csv_docs.name)
|
| 190 |
-
# with open(temp_filepath, "wb") as f:
|
| 191 |
-
# f.write(csv_docs.getvalue())
|
| 192 |
-
# csv_loader = CSVLoader(temp_filepath)
|
| 193 |
-
# csv_doc = csv_loader.load()
|
| 194 |
-
# return csv_doc
|
| 195 |
-
|
| 196 |
-
# def get_json_file(json_docs):
|
| 197 |
-
# temp_dir = tempfile.TemporaryDirectory()
|
| 198 |
-
# temp_filepath = os.path.join(temp_dir.name, json_docs.name)
|
| 199 |
-
# with open(temp_filepath, "wb") as f:
|
| 200 |
-
# f.write(json_docs.getvalue())
|
| 201 |
-
# json_loader = JSONLoader(temp_filepath)
|
| 202 |
-
# json_doc = json_loader.load()
|
| 203 |
-
# return json_doc
|
| 204 |
-
|
| 205 |
-
# def get_text_chunks(documents):
|
| 206 |
-
# text_splitter = RecursiveCharacterTextSplitter(
|
| 207 |
-
# chunk_size=300, # 청크의 크기를 지정합니다.
|
| 208 |
-
# chunk_overlap=100, # 청크 사이의 중복을 지정합니다.
|
| 209 |
-
# length_function=len # 텍스트의 길이를 측정하는 함수를 지정합니다.
|
| 210 |
-
# )
|
| 211 |
-
|
| 212 |
-
# documents = text_splitter.split_documents(documents) # 문서들을 청크로 나눕니다
|
| 213 |
-
# return documents # 나눈 청크를 반환합니다.
|
| 214 |
-
|
| 215 |
-
# # 텍스트 청크들로부터 벡터 스토어를 생성하는 함수입니다.
|
| 216 |
-
# def get_vectorstore(text_chunks):
|
| 217 |
-
# # embeddings = OpenAIEmbeddings()
|
| 218 |
-
# # embeddings = HuggingFaceEmbeddings(model_name="WhereIsAI/UAE-Large-V1")
|
| 219 |
-
# embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 220 |
-
# vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS 벡터 스토어를 생성합니다.
|
| 221 |
-
# return vectorstore # 생성된 벡터 스토어를 반환합니다.
|
| 222 |
-
|
| 223 |
-
# # def get_conversation_chain(vectorstore, tokenH):
|
| 224 |
-
# # if not tokenH:
|
| 225 |
-
# # raise ValueError("API token is required to initialize the HuggingFaceHub model")
|
| 226 |
-
|
| 227 |
-
# # # Initialize the HuggingFaceHub model with the correct token
|
| 228 |
-
# # try:
|
| 229 |
-
# # llm = HuggingFaceHub(
|
| 230 |
-
# # repo_id="Qwen/Qwen2.5-7B-Instruct",
|
| 231 |
-
# # token=tokenH)
|
| 232 |
-
# # except Exception as e:
|
| 233 |
-
# # raise ValueError(f"Error initializing HuggingFaceHub model: {str(e)}")
|
| 234 |
-
|
| 235 |
-
# # # Create conversational retrieval chain without memory
|
| 236 |
-
# # conversation_chain = ConversationalRetrievalChain.from_llm(
|
| 237 |
-
# # llm=llm,
|
| 238 |
-
# # retriever=vectorstore.as_retriever()
|
| 239 |
-
# # )
|
| 240 |
-
|
| 241 |
-
# # return conversation_chain
|
| 242 |
-
# from huggingface_hub import InferenceClient
|
| 243 |
-
|
| 244 |
-
# def get_conversation_chain(vectorstore, tokenH):
|
| 245 |
-
# if not tokenH:
|
| 246 |
-
# raise ValueError("API token is required to initialize the HuggingFaceHub model")
|
| 247 |
-
|
| 248 |
-
# # Initialize the InferenceClient with the API key
|
| 249 |
-
# try:
|
| 250 |
-
# client = InferenceClient(api_key=tokenH)
|
| 251 |
-
# except Exception as e:
|
| 252 |
-
# raise ValueError(f"Error initializing HuggingFace InferenceClient: {str(e)}")
|
| 253 |
-
|
| 254 |
-
# # Initialize chat history
|
| 255 |
-
# chat_history = []
|
| 256 |
-
|
| 257 |
-
# # Function to generate responses from the InferenceClient
|
| 258 |
-
# def generate_response(messages):
|
| 259 |
-
# nonlocal chat_history
|
| 260 |
-
# try:
|
| 261 |
-
# completion = client.chat.completions.create(
|
| 262 |
-
# model="microsoft/Phi-3.5-mini-instruct",
|
| 263 |
-
# messages=messages,
|
| 264 |
-
# max_tokens=500
|
| 265 |
-
# )
|
| 266 |
-
# # Add the new message and response to chat history
|
| 267 |
-
# chat_history.append({"role": "user", "content": messages[-1]["content"]})
|
| 268 |
-
# chat_history.append({"role": "assistant", "content": completion.choices[0].message['content']})
|
| 269 |
-
|
| 270 |
-
# # Return the current assistant's response
|
| 271 |
-
# return completion.choices[0].message['content']
|
| 272 |
-
# except Exception as e:
|
| 273 |
-
# raise ValueError(f"Error generating response: {str(e)}")
|
| 274 |
-
|
| 275 |
-
# # Create conversational retrieval chain without memory
|
| 276 |
-
# def conversation_chain(user_input):
|
| 277 |
-
# # Ensure user input is a string
|
| 278 |
-
# if isinstance(user_input, dict):
|
| 279 |
-
# user_input = user_input.get('question', '')
|
| 280 |
-
|
| 281 |
-
# # Get the relevant documents from the vector store using retriever's query method
|
| 282 |
-
# retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 5}) # Adjust the search arguments
|
| 283 |
-
# documents = retriever.get_relevant_documents(user_input)
|
| 284 |
-
|
| 285 |
-
# # Extract text from the documents (ensure they are strings)
|
| 286 |
-
# documents_text = "\n".join(doc.page_content for doc in documents) # Use doc.page_content instead of doc['text']
|
| 287 |
-
|
| 288 |
-
# # Prepare the messages for the InferenceClient
|
| 289 |
-
# messages = [{"role": "user", "content": user_input}, {"role": "system", "content": documents_text}]
|
| 290 |
-
# response = generate_response(messages)
|
| 291 |
-
|
| 292 |
-
# # Return the response
|
| 293 |
-
# return response
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
# def handle_userinput(user_question):
|
| 297 |
-
# # 대화 체인을 사용하여 사용자 질문에 대한 응답을 생성합니다.
|
| 298 |
-
# response = st.session_state.conversation({'question': user_question})
|
| 299 |
-
|
| 300 |
-
# # Ensure response contains both chat_history and the assistant's response
|
| 301 |
-
# st.session_state.chat_history = response['chat_history']
|
| 302 |
-
|
| 303 |
-
# # Display chat history
|
| 304 |
-
# for i, message in enumerate(st.session_state.chat_history):
|
| 305 |
-
# if i % 2 == 0:
|
| 306 |
-
# st.write(user_template.replace("{{MSG}}", message['content']), unsafe_allow_html=True)
|
| 307 |
-
# else:
|
| 308 |
-
# st.write(bot_template.replace("{{MSG}}", message['content']), unsafe_allow_html=True)
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
# def main():
|
| 312 |
-
# st.set_page_config(page_title="Chat with multiple Files", page_icon=":books:")
|
| 313 |
-
# st.write(css, unsafe_allow_html=True)
|
| 314 |
-
|
| 315 |
-
# if "conversation" not in st.session_state:
|
| 316 |
-
# st.session_state.conversation = None
|
| 317 |
-
# if "chat_history" not in st.session_state:
|
| 318 |
-
# st.session_state.chat_history = None
|
| 319 |
-
|
| 320 |
-
# st.header("Chat with multiple Files :")
|
| 321 |
-
# st.header("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21")
|
| 322 |
-
# tokenH = st.text_input("Paste your TOKEN key (sk-...)", key="token_input_1")
|
| 323 |
-
|
| 324 |
-
# # Validate if the token is empty
|
| 325 |
-
# if not tokenH:
|
| 326 |
-
# st.warning("Please enter a valid HuggingFace API token.")
|
| 327 |
-
# return
|
| 328 |
-
|
| 329 |
-
# user_question = st.text_input("Ask a question about your documents:")
|
| 330 |
-
# if user_question:
|
| 331 |
-
# handle_userinput(user_question)
|
| 332 |
-
|
| 333 |
-
# with st.sidebar:
|
| 334 |
-
# tokenH_sidebar = st.text_input("Paste your TOKEN key (sk-...)", key="token_input_2")
|
| 335 |
-
# tokenH = tokenH_sidebar or tokenH # fallback to main input if sidebar is empty
|
| 336 |
-
|
| 337 |
-
# st.subheader("Your documents")
|
| 338 |
-
# docs = st.file_uploader(
|
| 339 |
-
# "Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
|
| 340 |
-
# if st.button("Process"):
|
| 341 |
-
# with st.spinner("Processing"):
|
| 342 |
-
# # get pdf text
|
| 343 |
-
# doc_list = []
|
| 344 |
-
|
| 345 |
-
# for file in docs:
|
| 346 |
-
# print('file - type : ', file.type)
|
| 347 |
-
# if file.type == 'text/plain':
|
| 348 |
-
# # file is .txt
|
| 349 |
-
# doc_list.extend(get_text_file(file))
|
| 350 |
-
# elif file.type in ['application/octet-stream', 'application/pdf']:
|
| 351 |
-
# # file is .pdf
|
| 352 |
-
# doc_list.extend(get_pdf_text(file))
|
| 353 |
-
# elif file.type == 'text/csv':
|
| 354 |
-
# # file is .csv
|
| 355 |
-
# doc_list.extend(get_csv_file(file))
|
| 356 |
-
# elif file.type == 'application/json':
|
| 357 |
-
# # file is .json
|
| 358 |
-
# doc_list.extend(get_json_file(file))
|
| 359 |
-
|
| 360 |
-
# # get the text chunks
|
| 361 |
-
# text_chunks = get_text_chunks(doc_list)
|
| 362 |
-
|
| 363 |
-
# # create vector store
|
| 364 |
-
# vectorstore = get_vectorstore(text_chunks)
|
| 365 |
-
|
| 366 |
-
# # create conversation chain
|
| 367 |
-
# st.session_state.conversation = get_conversation_chain(vectorstore, tokenH)
|
| 368 |
-
|
| 369 |
-
# if __name__ == '__main__':
|
| 370 |
-
# main()
|
| 371 |
-
|
| 372 |
-
# import streamlit as st
|
| 373 |
-
# from dotenv import load_dotenv
|
| 374 |
-
# from PyPDF2 import PdfReader
|
| 375 |
-
# from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter
|
| 376 |
-
# from langchain_community.embeddings import OpenAIEmbeddings, HuggingFaceInstructEmbeddings
|
| 377 |
-
# from langchain_community.vectorstores import FAISS, Chroma
|
| 378 |
-
# from langchain_community.embeddings import HuggingFaceEmbeddings # General embeddings from HuggingFace models.
|
| 379 |
-
# from langchain.chat_models import ChatOpenAI
|
| 380 |
-
# from langchain.memory import ConversationBufferMemory
|
| 381 |
-
# from langchain.chains import ConversationalRetrievalChain
|
| 382 |
-
# from htmlTemplates import css, bot_template, user_template
|
| 383 |
-
# from langchain.llms import HuggingFaceHub, LlamaCpp, CTransformers # For loading transformer models.
|
| 384 |
-
# from langchain_community.document_loaders import PyPDFLoader, TextLoader, JSONLoader, CSVLoader
|
| 385 |
-
# import tempfile # 임시 파일을 생성하기 위한 라이브러리입니다.
|
| 386 |
-
# import os
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
# def get_pdf_text(pdf_docs):
|
| 390 |
-
# temp_dir = tempfile.TemporaryDirectory() # 임시 디렉토리를 생성합니다.
|
| 391 |
-
# temp_filepath = os.path.join(temp_dir.name, pdf_docs.name) # 임시 파일 경로를 생성합니다.
|
| 392 |
-
# with open(temp_filepath, "wb") as f: # 임시 파일을 바이너리 쓰기 모드로 엽니다.
|
| 393 |
-
# f.write(pdf_docs.getvalue()) # PDF 문서의 내용을 임시 파일에 씁니다.
|
| 394 |
-
# pdf_loader = PyPDFLoader(temp_filepath) # PyPDFLoader를 사용해 PDF를 로드합니다.
|
| 395 |
-
# pdf_doc = pdf_loader.load() # 텍스트를 추출합니다.
|
| 396 |
-
# return pdf_doc # 추출한 텍스트를 반환합니다.
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
# def get_text_file(text_docs):
|
| 400 |
-
# temp_dir = tempfile.TemporaryDirectory()
|
| 401 |
-
# temp_filepath = os.path.join(temp_dir.name, text_docs.name)
|
| 402 |
-
# with open(temp_filepath, "wb") as f:
|
| 403 |
-
# f.write(text_docs.getvalue())
|
| 404 |
-
# text_loader = TextLoader(temp_filepath)
|
| 405 |
-
# text_doc = text_loader.load()
|
| 406 |
-
# return text_doc
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
# def get_csv_file(csv_docs):
|
| 410 |
-
# temp_dir = tempfile.TemporaryDirectory()
|
| 411 |
-
# temp_filepath = os.path.join(temp_dir.name, csv_docs.name)
|
| 412 |
-
# with open(temp_filepath, "wb") as f:
|
| 413 |
-
# f.write(csv_docs.getvalue())
|
| 414 |
-
# csv_loader = CSVLoader(temp_filepath)
|
| 415 |
-
# csv_doc = csv_loader.load()
|
| 416 |
-
# return csv_doc
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
# def get_json_file(json_docs):
|
| 420 |
-
# temp_dir = tempfile.TemporaryDirectory()
|
| 421 |
-
# temp_filepath = os.path.join(temp_dir.name, json_docs.name)
|
| 422 |
-
# with open(temp_filepath, "wb") as f:
|
| 423 |
-
# f.write(json_docs.getvalue())
|
| 424 |
-
# json_loader = JSONLoader(temp_filepath)
|
| 425 |
-
# json_doc = json_loader.load()
|
| 426 |
-
# return json_doc
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
# def get_text_chunks(documents):
|
| 430 |
-
# text_splitter = RecursiveCharacterTextSplitter(
|
| 431 |
-
# chunk_size=1000, # 청크의 크기를 지정합니다.
|
| 432 |
-
# chunk_overlap=200, # 청크 사이의 중복을 지정합니다.
|
| 433 |
-
# length_function=len # 텍스트의 길이를 측정하는 함수를 지정합니다.
|
| 434 |
-
# )
|
| 435 |
-
|
| 436 |
-
# documents = text_splitter.split_documents(documents) # 문서들을 청크로 나눕니다
|
| 437 |
-
# return documents # 나눈 청크를 반환합니다.
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
# from langchain_huggingface import HuggingFaceEmbeddings
|
| 441 |
-
# # 텍스트 청크들로부터 벡터 스토어를 생성하는 함수입니다.
|
| 442 |
-
# def get_vectorstore(text_chunks):
|
| 443 |
-
# # OpenAI 임베딩 모델을 로드합니다. (Embedding models - Ada v2)
|
| 444 |
-
|
| 445 |
-
# # embeddings = OpenAIEmbeddings()
|
| 446 |
-
# embeddings = HuggingFaceEmbeddings(model_name="WhereIsAI/UAE-Large-V1")
|
| 447 |
-
# vectorstore = FAISS.from_documents(text_chunks, embeddings) # FAISS 벡터 스토어를 생성합니다.
|
| 448 |
-
|
| 449 |
-
# return vectorstore # 생성된 벡터 스토어를 반환합니다.
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
# api="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21"
|
| 453 |
-
# repo_id = "HuggingFaceH4/zephyr-7b-alpha"
|
| 454 |
-
# # from huggingface_hub import InferenceClient
|
| 455 |
-
|
| 456 |
-
# # from langchain.llms import HuggingFaceHub
|
| 457 |
-
# # from langchain.llms import HuggingFaceInferenceAPI
|
| 458 |
-
# # def get_conversation_chain(vectorstore):
|
| 459 |
-
# # # gpt_model_name = 'gpt-3.5-turbo'
|
| 460 |
-
# # # llm = ChatOpenAI(model_name = gpt_model_name) #gpt-3.5 모델 로드
|
| 461 |
-
# # # llm = HuggingFaceInferenceAPI(model_name="HuggingFaceH4/zephyr-7b-alpha", token=api[:-2])
|
| 462 |
-
# # # llm = InferenceClient(
|
| 463 |
-
# # # model=repo_id,
|
| 464 |
-
# # # token=api[:-2], # Pass the token here
|
| 465 |
-
# # # timeout=120)
|
| 466 |
-
# # # llm = HuggingFaceHub(
|
| 467 |
-
# # # repo_id="HuggingFaceH4/zephyr-7b-alpha",
|
| 468 |
-
# # # token=api[:-2],
|
| 469 |
-
# # # huggingfacehub_api_token=api[:-2]
|
| 470 |
-
# # # )
|
| 471 |
-
# # # 대화 기록을 저장하기 위한 메모리를 생성합니다.
|
| 472 |
-
# # if "HUGGINGFACEHUB_API_TOKEN" not in os.environ:
|
| 473 |
-
# # st.write(ValueError("HUGGINGFACEHUB_API_TOKEN is not set in the environment variables."))
|
| 474 |
-
|
| 475 |
-
# # llm = HuggingFaceHub(
|
| 476 |
-
# # repo_id="HuggingFaceH4/zephyr-7b-alpha",
|
| 477 |
-
# # token=os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
| 478 |
-
# # )
|
| 479 |
-
# # memory = ConversationBufferMemory(
|
| 480 |
-
# # memory_key='chat_history', return_messages=True)
|
| 481 |
-
# # # 대화 검색 체인을 생성합니다.
|
| 482 |
-
# # conversation_chain = ConversationalRetrievalChain.from_llm(
|
| 483 |
-
# # llm=llm,
|
| 484 |
-
# # retriever=vectorstore.as_retriever(),
|
| 485 |
-
# # memory=memory
|
| 486 |
-
# # )
|
| 487 |
-
# # return conversation_chain
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
# import os
|
| 492 |
-
# from langchain.llms import HuggingFaceHub
|
| 493 |
-
# from langchain.memory import ConversationBufferMemory
|
| 494 |
-
# from langchain.chains import ConversationalRetrievalChain
|
| 495 |
-
|
| 496 |
-
# # def get_conversation_chain(vectorstore,tokenH):
|
| 497 |
-
# # # api_token = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
| 498 |
-
|
| 499 |
-
# # # if api_token is None:
|
| 500 |
-
# # # st.header("HUGGINGFACEHUB_API_TOKEN is not set in the environment variables :")
|
| 501 |
-
# # # raise ValueError("HUGGINGFACEHUB_API_TOKEN is not set in the environment variables.")
|
| 502 |
-
|
| 503 |
-
# # # Initialize the HuggingFaceHub model with the correct token
|
| 504 |
-
# # # llm = HuggingFaceHub(
|
| 505 |
-
# # # repo_id="HuggingFaceH4/zephyr-7b-alpha",
|
| 506 |
-
# # # token=tokenH
|
| 507 |
-
# # # )
|
| 508 |
-
# # tokenH = st.text_input("Paste your TOKENH key (sk-...)")
|
| 509 |
-
|
| 510 |
-
# # if tokenH:
|
| 511 |
-
# # llm = HuggingFaceHub(
|
| 512 |
-
# # repo_id="HuggingFaceH4/zephyr-7b-alpha",
|
| 513 |
-
# # token=tokenH # Token passed here directly
|
| 514 |
-
# # )
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
# # # Set up memory for conversation history
|
| 518 |
-
# # memory = ConversationBufferMemory(
|
| 519 |
-
# # memory_key='chat_history', return_messages=True
|
| 520 |
-
# # )
|
| 521 |
-
|
| 522 |
-
# # # Create conversational retrieval chain
|
| 523 |
-
# # conversation_chain = ConversationalRetrievalChain.from_llm(
|
| 524 |
-
# # llm=llm,
|
| 525 |
-
# # retriever=vectorstore.as_retriever(),
|
| 526 |
-
# # memory=memory
|
| 527 |
-
# # )
|
| 528 |
-
|
| 529 |
-
# # return conversation_chain
|
| 530 |
-
|
| 531 |
-
# # def get_conversation_chain(vectorstore, tokenH):
|
| 532 |
-
# # if not tokenH:
|
| 533 |
-
# # raise ValueError("API token is required to initialize the HuggingFaceHub model")
|
| 534 |
-
|
| 535 |
-
# # # Initialize the HuggingFaceHub model with the correct token
|
| 536 |
-
# # try:
|
| 537 |
-
# # llm = HuggingFaceHub(
|
| 538 |
-
# # repo_id="Qwen/Qwen2.5-7B-Instruct",
|
| 539 |
-
# # token=tokenH,
|
| 540 |
-
# # use_auth_token=True
|
| 541 |
-
# # )
|
| 542 |
-
# # except Exception as e:
|
| 543 |
-
# # raise ValueError(f"Error initializing HuggingFaceHub model: {str(e)}")
|
| 544 |
-
|
| 545 |
-
# # # Set up memory for conversation history
|
| 546 |
-
# # memory = ConversationBufferMemory(
|
| 547 |
-
# # memory_key='chat_history', return_messages=True
|
| 548 |
-
# # )
|
| 549 |
-
|
| 550 |
-
# # # Create conversational retrieval chain
|
| 551 |
-
# # conversation_chain = ConversationalRetrievalChain.from_llm(
|
| 552 |
-
# # llm=llm,
|
| 553 |
-
# # retriever=vectorstore.as_retriever(),
|
| 554 |
-
# # memory=memory
|
| 555 |
-
# # )
|
| 556 |
-
|
| 557 |
-
# # return conversation_chain
|
| 558 |
-
|
| 559 |
-
# def get_conversation_chain(vectorstore, tokenH):
|
| 560 |
-
# if not tokenH:
|
| 561 |
-
# raise ValueError("API token is required to initialize the HuggingFaceHub model")
|
| 562 |
-
|
| 563 |
-
# # Initialize the HuggingFaceHub model with the correct token
|
| 564 |
-
# try:
|
| 565 |
-
# llm = HuggingFaceHub(
|
| 566 |
-
# repo_id="Qwen/Qwen2.5-7B-Instruct",
|
| 567 |
-
# token=tokenH)
|
| 568 |
-
# except Exception as e:
|
| 569 |
-
# raise ValueError(f"Error initializing HuggingFaceHub model: {str(e)}")
|
| 570 |
-
|
| 571 |
-
# # Set up memory for conversation history
|
| 572 |
-
# memory = ConversationBufferMemory(
|
| 573 |
-
# memory_key='chat_history', return_messages=True
|
| 574 |
-
# )
|
| 575 |
-
|
| 576 |
-
# # Create conversational retrieval chain
|
| 577 |
-
# conversation_chain = ConversationalRetrievalChain.from_llm(
|
| 578 |
-
# llm=llm,
|
| 579 |
-
# retriever=vectorstore.as_retriever(),
|
| 580 |
-
# memory=memory
|
| 581 |
-
# )
|
| 582 |
-
|
| 583 |
-
# return conversation_chain
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
# def handle_userinput(user_question):
|
| 587 |
-
# # 대화 체인을 사용하여 사용자 질문에 대한 응답을 생성합니다.
|
| 588 |
-
# response = st.session_state.conversation({'question': user_question})
|
| 589 |
-
# # 대화 기록을 저장합니다.
|
| 590 |
-
# st.session_state.chat_history = response['chat_history']
|
| 591 |
-
|
| 592 |
-
# for i, message in enumerate(st.session_state.chat_history):
|
| 593 |
-
# if i % 2 == 0:
|
| 594 |
-
# st.write(user_template.replace(
|
| 595 |
-
# "{{MSG}}", message.content), unsafe_allow_html=True)
|
| 596 |
-
# else:
|
| 597 |
-
# st.write(bot_template.replace(
|
| 598 |
-
# "{{MSG}}", message.content), unsafe_allow_html=True)
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
# def main():
|
| 603 |
-
# # load_dotenv()
|
| 604 |
-
# st.set_page_config(page_title="Chat with multiple Files",
|
| 605 |
-
# page_icon=":books:")
|
| 606 |
-
# st.write(css, unsafe_allow_html=True)
|
| 607 |
-
|
| 608 |
-
# if "conversation" not in st.session_state:
|
| 609 |
-
# st.session_state.conversation = None
|
| 610 |
-
# if "chat_history" not in st.session_state:
|
| 611 |
-
# st.session_state.chat_history = None
|
| 612 |
-
|
| 613 |
-
# st.header("Chat with multiple Files :",)
|
| 614 |
-
# st.header("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21")
|
| 615 |
-
# tokenH = st.text_input("Paste your TOKEN key (sk-...)", key="token_input_1")
|
| 616 |
-
|
| 617 |
-
# # Validate if the token is empty
|
| 618 |
-
# if not tokenH:
|
| 619 |
-
# st.warning("Please enter a valid HuggingFace API token.")
|
| 620 |
-
# return
|
| 621 |
-
|
| 622 |
-
# user_question = st.text_input("Ask a question about your documents:")
|
| 623 |
-
# if user_question:
|
| 624 |
-
# handle_userinput(user_question)
|
| 625 |
-
|
| 626 |
-
# with st.sidebar:
|
| 627 |
-
# tokenH_sidebar = st.text_input("Paste your TOKEN key (sk-...)", key="token_input_2")
|
| 628 |
-
# tokenH = tokenH_sidebar or tokenH # fallback to main input if sidebar is empty
|
| 629 |
-
|
| 630 |
-
# st.subheader("Your documents")
|
| 631 |
-
# docs = st.file_uploader(
|
| 632 |
-
# "Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
|
| 633 |
-
# if st.button("Process"):
|
| 634 |
-
# with st.spinner("Processing"):
|
| 635 |
-
# # get pdf text
|
| 636 |
-
# doc_list = []
|
| 637 |
-
|
| 638 |
-
# for file in docs:
|
| 639 |
-
# print('file - type : ', file.type)
|
| 640 |
-
# if file.type == 'text/plain':
|
| 641 |
-
# # file is .txt
|
| 642 |
-
# doc_list.extend(get_text_file(file))
|
| 643 |
-
# elif file.type in ['application/octet-stream', 'application/pdf']:
|
| 644 |
-
# # file is .pdf
|
| 645 |
-
# doc_list.extend(get_pdf_text(file))
|
| 646 |
-
# elif file.type == 'text/csv':
|
| 647 |
-
# # file is .csv
|
| 648 |
-
# doc_list.extend(get_csv_file(file))
|
| 649 |
-
# elif file.type == 'application/json':
|
| 650 |
-
# # file is .json
|
| 651 |
-
# doc_list.extend(get_json_file(file))
|
| 652 |
-
|
| 653 |
-
# # get the text chunks
|
| 654 |
-
# text_chunks = get_text_chunks(doc_list)
|
| 655 |
-
|
| 656 |
-
# # create vector store
|
| 657 |
-
# vectorstore = get_vectorstore(text_chunks)
|
| 658 |
-
|
| 659 |
-
# # create conversation chain
|
| 660 |
-
# st.session_state.conversation = get_conversation_chain(vectorstore, tokenH)
|
| 661 |
-
|
| 662 |
-
# if __name__ == '__main__':
|
| 663 |
-
# main()
|
|
|
|
| 81 |
def generate_response(messages):
|
| 82 |
try:
|
| 83 |
completion = client.chat.completions.create(
|
| 84 |
+
model="Qwen/Qwen2.5-72B-Instruct",
|
| 85 |
messages=messages,
|
| 86 |
max_tokens=500
|
| 87 |
)
|
|
|
|
| 148 |
if __name__ == '__main__':
|
| 149 |
main()
|
| 150 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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