File size: 3,153 Bytes
3bbfff2
 
 
 
 
085c7bf
3bbfff2
 
 
 
f1a7e30
3bbfff2
 
 
 
 
 
 
 
 
3372024
 
 
 
 
 
 
 
 
3bbfff2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
085c7bf
3bbfff2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3372024
 
 
 
 
79ff5ca
 
 
 
 
 
 
 
b9ca76a
 
3372024
 
3bbfff2
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import os
import streamlit as st
import pandas as pd
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain_openai import ChatOpenAI  # Updated import statement
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationalRetrievalChain
from langchain.text_splitter import CharacterTextSplitter

OPENAI_API_KEY = "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"
os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY

# Initialize variables
vectorstore = None
conversation_chain = None
chat_history = []

# Function to process uploaded CSV file
def process_csv(csv_file):
    try:
        df = pd.read_csv(csv_file)
        text = df.to_string(index=False)
        text_chunks = get_text_chunks(text)
        vectorstore = get_vectorstore(text_chunks)
        conversation_chain = get_conversation_chain(vectorstore)
        return conversation_chain
    except Exception as e:
        st.error(f"Error processing CSV file: {e}")

# Function to split text into chunks
def get_text_chunks(text):
    text_splitter = CharacterTextSplitter(
        separator="\n",
        chunk_size=1000,
        chunk_overlap=200,
        length_function=len
    )
    chunks = text_splitter.split_text(text)
    return chunks

# Function to create vectorstore from text chunks
def get_vectorstore(text_chunks):
    embeddings = OpenAIEmbeddings()
    vectorstore = FAISS.from_texts(texts=text_chunks, embedding=embeddings)
    return vectorstore

# Function to create conversation chain
def get_conversation_chain(vectorstore):
    llm = ChatOpenAI()  # Use the correct class from langchain-openai
    memory = ConversationBufferMemory(
        memory_key='chat_history', return_messages=True)
    conversation_chain = ConversationalRetrievalChain.from_llm(
        llm=llm,
        retriever=vectorstore.as_retriever(),
        memory=memory
    )
    return conversation_chain

# Streamlit app
def main():
    global vectorstore, conversation_chain, chat_history

    st.title('CSV Chatbot')

    # Page to upload CSV file
    st.subheader('Upload CSV File')
    csv_file = st.file_uploader('Upload CSV', type=['csv'])

    if csv_file:
        conversation_chain = process_csv(csv_file)

        if conversation_chain:
            # Chat interface
            st.subheader('Chat Interface')
            user_question = st.text_input('Ask a question:')
            if st.button('Ask'):
                st.spinner("Generating Response.....")
                response = conversation_chain.invoke({'question': user_question})
                chat_history = response['chat_history']
                for message in chat_history:
                    if message['role'] == 'user':
                        st.write(f"You: {message['content']}")
                    elif message['role'] == 'assistant':
                        st.write(f"Assistant: {message['content']}")
            else:
                st.error("Failed to process CSV file. Please try again.")
        else:
            st.error("Failed to process CSV file. Please try again.")

if __name__ == '__main__':
    main()