Gaurav-2273 commited on
Commit
bfaa73f
1 Parent(s): a7320b9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -60
app.py CHANGED
@@ -1,63 +1,75 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
-
61
-
62
- if __name__ == "__main__":
63
- demo.launch()
 
 
 
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
+ import fitz # PyMuPDF
4
+ import re
5
+ from langchain_openai.embeddings import OpenAIEmbeddings
6
+ from langchain_chroma import Chroma
7
+ from langchain.retrievers.multi_query import MultiQueryRetriever
8
+ from langchain.chains import ConversationalRetrievalChain
9
+ from langchain.memory import ConversationBufferMemory
10
+ from langchain_openai import ChatOpenAI
11
+ from langchain_experimental.text_splitter import SemanticChunker
12
 
13
+ # Place your OpenAI API key in a safe place, such as an environment variable or a secure vault
14
+ openai_api_key = "YOUR_OPENAI_API_KEY_HERE"
15
+
16
+ vectorstore = None
17
+ llm = None
18
+ qa_instance = None
19
+ chat_history = []
20
+
21
+ def extract_text_from_pdf(pdf_bytes):
22
+ document = fitz.open("pdf", pdf_bytes)
23
+ text = ""
24
+ for page_num in range(len(document)):
25
+ page = document.load_page(page_num)
26
+ text += page.get_text()
27
+ document.close()
28
+ return text
29
+
30
+ def clean_text(text):
31
+ cleaned_text = re.sub(r'\s+', ' ', text)
32
+ cleaned_text = re.sub(r'(.)\1{2,}', r'\1', cleaned_text)
33
+ cleaned_text = re.sub(r'\b(\w+)\b(?:\s+\1\b)+', r'\1', cleaned_text)
34
+ return cleaned_text.strip()
35
+
36
+ def initialize_chatbot(cleaned_text):
37
+ global vectorstore, llm, qa_instance
38
+ if vectorstore is None:
39
+ embeddings = OpenAIEmbeddings(api_key=openai_api_key)
40
+ text_splitter = SemanticChunker(embeddings)
41
+ docs = text_splitter.create_documents([cleaned_text])
42
+ vectorstore = Chroma.from_documents(documents=docs, embedding=embeddings)
43
+ if llm is None:
44
+ llm = ChatOpenAI(api_key=openai_api_key, temperature=0.5, model="gpt-4o", verbose=True)
45
+ retriever = MultiQueryRetriever.from_llm(retriever=vectorstore.as_retriever(), llm=llm)
46
+ memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
47
+ qa_instance = ConversationalRetrievalChain.from_llm(llm, retriever=retriever, memory=memory)
48
+
49
+ def setup_qa_system(pdf_file):
50
+ if pdf_file is None:
51
+ return [("Please upload a PDF file.", "")]
52
+ extracted_text = extract_text_from_pdf(pdf_file)
53
+ cleaned_text = clean_text(extracted_text)
54
+ initialize_chatbot(cleaned_text)
55
+ chat_history = [("Chatbot initialized. Please ask a question.", "")]
56
+ return chat_history
57
+
58
+ def answer_query(question):
59
+ if qa_instance is None:
60
+ return [("Please upload a PDF and initialize the system first.", "")]
61
+ if not question.strip():
62
+ return [("Please enter a question.", "")]
63
+ result = qa_instance({"question": question})
64
+ chat_history.append((question, result['answer']))
65
+ return chat_history
66
+
67
+ with gr.Blocks() as demo:
68
+ upload = gr.File(label="Upload PDF", type="binary", file_types=["pdf"])
69
+ chatbot = gr.Chatbot(label="Chatbot")
70
+ question = gr.Textbox(label="Ask a question", placeholder="Type your question after uploading PDF...")
71
+
72
+ upload.change(setup_qa_system, inputs=[upload], outputs=[chatbot])
73
+ question.submit(answer_query, inputs=[question], outputs=[chatbot])
74
+
75
+ demo.launch()