sudip2003 commited on
Commit
180ada1
1 Parent(s): 53cfec3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -0
app.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import PyPDF2
3
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
4
+ from langchain_community.embeddings import HuggingFaceBgeEmbeddings
5
+ from langchain.vectorstores import Chroma
6
+ from langchain.memory import ChatMessageHistory, ConversationBufferMemory
7
+ from langchain_groq import ChatGroq
8
+ from langchain.chains import ConversationalRetrievalChain
9
+ from langchain_community.document_loaders import WebBaseLoader
10
+ import os
11
+
12
+ # Function to process text and create ConversationalRetrievalChain
13
+ def process_text_and_create_chain(text):
14
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
15
+ texts = text_splitter.split_text(text)
16
+ metadatas = [{"source": f"{i}-pl"} for i in range(len(texts))]
17
+
18
+ model_name = "BAAI/bge-small-en"
19
+ model_kwargs = {"device": "cpu"}
20
+ encode_kwargs = {"normalize_embeddings": True}
21
+ hf = HuggingFaceBgeEmbeddings(
22
+ model_name=model_name, model_kwargs=model_kwargs, encode_kwargs=encode_kwargs
23
+ )
24
+
25
+ db = Chroma.from_texts(texts, hf, metadatas=metadatas)
26
+
27
+ message_history = ChatMessageHistory()
28
+ memory = ConversationBufferMemory(
29
+ memory_key="chat_history",
30
+ output_key="answer",
31
+ chat_memory=message_history,
32
+ return_messages=True,
33
+ )
34
+
35
+ llm_groq = ChatGroq(
36
+ groq_api_key="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",
37
+ model_name='mixtral-8x7b-32768'
38
+ )
39
+
40
+ chain = ConversationalRetrievalChain.from_llm(
41
+ llm=llm_groq,
42
+ chain_type="stuff",
43
+ retriever=db.as_retriever(),
44
+ memory=memory,
45
+ return_source_documents=True,
46
+ )
47
+
48
+ return chain
49
+
50
+ # Initialize global variables
51
+ global_chain = None
52
+
53
+ # Function to handle PDF upload
54
+ def handle_pdf_upload(file):
55
+ if file is None:
56
+ return "No file uploaded. Please upload a PDF file.", gr.update(visible=False), gr.update(visible=True)
57
+
58
+ if not file.name.lower().endswith('.pdf'):
59
+ return "Error: Please upload a PDF file.", gr.update(visible=False), gr.update(visible=True)
60
+
61
+ try:
62
+ print(f"Processing file: {file.name}")
63
+ pdf_reader = PyPDF2.PdfReader(file.name)
64
+ pdf_text = ""
65
+ for page in pdf_reader.pages:
66
+ pdf_text += page.extract_text()
67
+
68
+ global global_chain
69
+ global_chain = process_text_and_create_chain(pdf_text)
70
+ return "PDF processed successfully.", gr.update(visible=True), gr.update(visible=False)
71
+ except Exception as e:
72
+ print(f"Error processing PDF: {str(e)}")
73
+ return f"Error processing PDF: {str(e)}", gr.update(visible=False), gr.update(visible=True)
74
+
75
+ # Function to handle link input
76
+ def handle_link_input(link):
77
+ try:
78
+ loader = WebBaseLoader(link)
79
+ data = loader.load()
80
+ doc = "\n".join([doc.page_content for doc in data])
81
+
82
+ global global_chain
83
+ global_chain = process_text_and_create_chain(doc)
84
+ return "Link processed successfully.", gr.update(visible=True), gr.update(visible=False)
85
+ except Exception as e:
86
+ print(f"Error processing link: {str(e)}")
87
+ return f"Error processing link: {str(e)}", gr.update(visible=False), gr.update(visible=True)
88
+
89
+ # Function to handle user query
90
+ def handle_query(query, chatbot):
91
+ if global_chain is None:
92
+ return chatbot + [("Bot", "Please provide input first.")]
93
+ try:
94
+ result = global_chain({"question": query})
95
+ return chatbot + [("You", query), ("System", result['answer'])]
96
+ except Exception as e:
97
+ print(f"Error processing query: {str(e)}")
98
+ return chatbot + [("Bot", f"Error: {str(e)}")]
99
+
100
+ # Function to toggle input method
101
+ def toggle_input_method(input_method):
102
+ if input_method == "Upload PDF":
103
+ return gr.update(visible=True), gr.update(visible=False)
104
+ elif input_method == "Paste Link":
105
+ return gr.update(visible=False), gr.update(visible=True)
106
+ else:
107
+ return gr.update(visible=False), gr.update(visible=False)
108
+
109
+ # Gradio interface
110
+ with gr.Blocks() as demo:
111
+ gr.Markdown("# Chat-With-Context")
112
+
113
+ with gr.Row():
114
+ input_method = gr.Radio(["Upload PDF", "Paste Link"], label="Choose Input Method", interactive=True)
115
+
116
+ with gr.Row(visible=False) as upload_section:
117
+ pdf_input = gr.File(label="Upload PDF")
118
+ upload_button = gr.Button("Process PDF")
119
+
120
+ with gr.Row(visible=False) as text_input_section:
121
+ text_input = gr.Textbox(label="Paste Link")
122
+ submit_text_button = gr.Button("Process Link")
123
+
124
+ input_status = gr.Textbox(label="Status", interactive=False)
125
+
126
+ with gr.Row(visible=False) as chat_section:
127
+ chatbot = gr.Chatbot(label="Chat")
128
+ query_input = gr.Textbox(label="Write Your Question", placeholder="Message Chat-With-Context")
129
+ send_button = gr.Button("Send")
130
+
131
+ input_method.change(toggle_input_method, inputs=input_method, outputs=[upload_section, text_input_section])
132
+ upload_button.click(fn=handle_pdf_upload, inputs=pdf_input, outputs=[input_status, chat_section, upload_section])
133
+ submit_text_button.click(fn=handle_link_input, inputs=text_input, outputs=[input_status, chat_section, text_input_section])
134
+ send_button.click(fn=handle_query, inputs=[query_input, chatbot], outputs=chatbot)
135
+
136
+
137
+
138
+ demo.launch(share=True)