Pavan178 commited on
Commit
4fdf319
·
verified ·
1 Parent(s): f723fc5

Update gradio_app.py

Browse files
Files changed (1) hide show
  1. gradio_app.py +75 -120
gradio_app.py CHANGED
@@ -1,124 +1,79 @@
1
  import gradio as gr
2
- from llama_index import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader
3
- from llama_index.llms import HuggingFaceInferenceAPI
4
- from llama_index.prompts import ChatPromptTemplate
5
- from llama_index.embeddings import HuggingFaceEmbedding
6
- from llama_index import ServiceContext
7
- from dotenv import load_dotenv
8
- import os
9
- import base64
10
- import tempfile
11
- from pathlib import Path
12
-
13
- # Load environment variables
14
- load_dotenv()
15
-
16
- # Configure the Llama index settings
17
- llm = HuggingFaceInferenceAPI(
18
- model_name="google/gemini-1.1-7b-it",
19
- tokenizer_name="google/gemini-1.1-7b-it",
20
- context_window=3000,
21
- token=os.getenv("HF_TOKEN"),
22
- max_new_tokens=512,
23
- generate_kwargs={"temperature": 0.1},
24
- )
25
- embed_model = HuggingFaceEmbedding(
26
- model_name="BAAI/bge-small-en-v1.5"
27
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- # Create a service context
30
- service_context = ServiceContext.from_defaults(
31
- llm=llm,
32
- embed_model=embed_model
 
 
 
 
 
 
33
  )
34
 
35
- # Define the directory for persistent storage and data
36
- PERSIST_DIR = "./db"
37
- DATA_DIR = "data"
38
-
39
- # Ensure data directory exists
40
- os.makedirs(DATA_DIR, exist_ok=True)
41
- os.makedirs(PERSIST_DIR, exist_ok=True)
42
-
43
- def displayPDF(file):
44
- base64_pdf = base64.b64encode(file.read()).decode('utf-8')
45
- return f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
46
-
47
- def data_ingestion():
48
- documents = SimpleDirectoryReader(DATA_DIR).load_data()
49
- storage_context = StorageContext.from_defaults()
50
- index = VectorStoreIndex.from_documents(documents, service_context=service_context)
51
- index.storage_context.persist(persist_dir=PERSIST_DIR)
52
-
53
- def handle_query(query):
54
- storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
55
- index = load_index_from_storage(storage_context, service_context=service_context)
56
- chat_text_qa_msgs = [
57
- (
58
- "user",
59
- """You are a Q&A assistant named CHATTO, created by Suriya. You have a specific response programmed for when users specifically ask about your creator, Suriya. The response is: "I was created by Suriya, an enthusiast in Artificial Intelligence. He is dedicated to solving complex problems and delivering innovative solutions. With a strong focus on machine learning, deep learning, Python, generative AI, NLP, and computer vision, Suriya is passionate about pushing the boundaries of AI to explore new possibilities." For all other inquiries, your main goal is to provide answers as accurately as possible, based on the instructions and context you have been given. If a question does not match the provided context or is outside the scope of the document, kindly advise the user to ask questions within the context of the document.
60
- Context:
61
- {context_str}
62
- Question:
63
- {query_str}
64
- """
65
- )
66
- ]
67
- text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
68
-
69
- query_engine = index.as_query_engine(text_qa_template=text_qa_template)
70
- answer = query_engine.query(query)
71
-
72
- if hasattr(answer, 'response'):
73
- return answer.response
74
- elif isinstance(answer, dict) and 'response' in answer:
75
- return answer['response']
76
- else:
77
- return "Sorry, I couldn't find an answer."
78
-
79
- def process_file(file):
80
- if file is None:
81
- return "Please upload a PDF file."
82
-
83
- try:
84
- with tempfile.NamedTemporaryFile(delete=False) as temp_file:
85
- temp_file.write(file.read())
86
- temp_path = Path(temp_file.name)
87
-
88
- # Copy the file to the DATA_DIR
89
- dest_path = Path(DATA_DIR) / file.name
90
- dest_path.parent.mkdir(parents=True, exist_ok=True)
91
- temp_path.replace(dest_path)
92
-
93
- # Process the uploaded PDF
94
- data_ingestion()
95
- return f"PDF '{file.name}' processed successfully. You can now ask questions about its content.", displayPDF(file)
96
- except Exception as e:
97
- return f"An error occurred while processing the file: {str(e)}", None
98
-
99
- def chat_function(message, history):
100
- response = handle_query(message)
101
- history.append((message, response))
102
- return history, history
103
-
104
- with gr.Blocks() as demo:
105
- gr.Markdown("# (PDF) Information and Inference🗞️")
106
- gr.Markdown("Retrieval-Augmented Generation")
107
-
108
- with gr.Row():
109
- with gr.Column(scale=1):
110
- file_output = gr.Textbox(label="Upload Status")
111
- file_display = gr.HTML()
112
- upload_button = gr.UploadButton("Upload PDF", file_types=[".pdf"])
113
-
114
- with gr.Column(scale=2):
115
- chatbot = gr.Chatbot()
116
- msg = gr.Textbox(label="Ask me anything about the content of the PDF:")
117
- clear = gr.Button("Clear")
118
-
119
- upload_button.upload(process_file, upload_button, [file_output, file_display])
120
- msg.submit(chat_function, [msg, chatbot], [chatbot, chatbot])
121
- clear.click(lambda: None, None, chatbot, queue=False)
122
-
123
- if __name__ == "__main__":
124
- demo.launch()
 
1
  import gradio as gr
2
+ import langchain.llms as llms
3
+ import langchain.llms.prompts as prompts
4
+ import langchain.pipelines as pipelines
5
+ from langchain.llms.responses import ResponseItem
6
+
7
+ def process_pdf(pdf_file):
8
+ """Processes the uploaded PDF using a pre-trained information extraction pipeline.
9
+
10
+ Args:
11
+ pdf_file (bytes): The uploaded PDF file content.
12
+
13
+ Returns:
14
+ dict: A dictionary containing the extracted information from the PDF.
15
+ """
16
+
17
+ # Replace with your preferred information extraction pipeline
18
+ # (e.g., Camelot, PyMuPDF, PDFMiner.Six)
19
+ extracted_data = extract_information_from_pdf(pdf_file)
20
+ return extracted_data
21
+
22
+ def answer_question(question, context, llm):
23
+ """Answers the user's question using the provided context and LLaMA3 model.
24
+
25
+ Args:
26
+ question (str): The user's question.
27
+ context (dict): The extracted information from the PDF.
28
+ llm (llms.BaseLLM): The LLaMA3 language model instance.
29
+
30
+ Returns:
31
+ ResponseItem: A ResponseItem object containing the answer, score, and retrieval.
32
+ """
33
+
34
+ # Replace with your preferred RAG prompt template
35
+ # (e.g., "The document says [RETRIEVAL]. Can you answer this question based on it: {question}?")
36
+ prompt = prompts.get_rag_answering_prompt(question, context, retrieval_template="")
37
+
38
+ response = llm.run(prompt, wait_for_sequences=True)
39
+ return response[0]
40
+
41
+ def chatbot(pdf_file, message, chat_history):
42
+ """Handles user interaction, processes PDF, answers questions, and maintains chat history.
43
+
44
+ Args:
45
+ pdf_file (bytes, optional): The uploaded PDF file content (if applicable).
46
+ message (str): The user's message (question).
47
+ chat_history (list): A list of previous messages.
48
+
49
+ Returns:
50
+ list: An updated chat history with the chatbot's response.
51
+ """
52
+
53
+ if pdf_file is not None:
54
+ context = process_pdf(pdf_file)
55
+ chat_history.append(f"**You uploaded a PDF.**")
56
+
57
+ if message:
58
+ # Access the LLaMA3 model (replace with your setup)
59
+ llm = llms.get_llm("facebook/bart-base") # Example LLaMA3 model (replace with your access)
60
+
61
+ response = answer_question(message, context, llm)
62
+ chat_history.append(f"**User:** {message}")
63
+ chat_history.append(f"**Chatbot:** {response.generated_text}")
64
+
65
+ return chat_history
66
 
67
+ # Gradio interface setup
68
+ interface = gr.Interface(
69
+ fn=chatbot,
70
+ inputs=[
71
+ gr.File(type="pdf", label="Upload PDF (optional)"),
72
+ gr.Textbox(label="Ask a question"),
73
+ ],
74
+ outputs=gr.Textbox(multiline=True),
75
+ title="PDF Q&A Chatbot with LLaMA3",
76
+ description="Ask questions about the uploaded PDF or provide an empty file to use example content.",
77
  )
78
 
79
+ interface.launch()