Pavan178 commited on
Commit
7ac2dc6
·
verified ·
1 Parent(s): 3934742

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -112
app.py CHANGED
@@ -1,115 +1,4 @@
1
- import gradio as gr
2
- from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
3
- from llama_index.llms.huggingface import HuggingFaceInferenceAPI
4
- from dotenv import load_dotenv
5
- from llama_index.embeddings.huggingface import HuggingFaceEmbedding
6
- from llama_index.core import Settings
7
- import os
8
- import tempfile
9
-
10
- # Load environment variables
11
- load_dotenv()
12
-
13
- # Configure the Llama index settings
14
- Settings.llm = HuggingFaceInferenceAPI(
15
- model_name="google/gemma-1.1-7b-it",
16
- tokenizer_name="google/gemma-1.1-7b-it",
17
- context_window=3000,
18
- token=os.getenv("HF_TOKEN"),
19
- max_new_tokens=512,
20
- generate_kwargs={"temperature": 0.1},
21
- )
22
- Settings.embed_model = HuggingFaceEmbedding(
23
- model_name="BAAI/bge-small-en-v1.5"
24
- )
25
-
26
- # Define the directory for persistent storage and data
27
- PERSIST_DIR = "./db"
28
- DATA_DIR = "data"
29
-
30
- # Ensure data directory exists
31
- os.makedirs(DATA_DIR, exist_ok=True)
32
- os.makedirs(PERSIST_DIR, exist_ok=True)
33
-
34
- def data_ingestion():
35
- documents = SimpleDirectoryReader(DATA_DIR).load_data()
36
- storage_context = StorageContext.from_defaults()
37
- index = VectorStoreIndex.from_documents(documents)
38
- index.storage_context.persist(persist_dir=PERSIST_DIR)
39
-
40
- def handle_query(query):
41
- storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
42
- index = load_index_from_storage(storage_context)
43
- chat_text_qa_msgs = [
44
- (
45
- "user",
46
- """You are a Q&A assistant named EazyPeazy, 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.
47
- Context:
48
- {context_str}
49
- Question:
50
- {query_str}
51
- """
52
- )
53
- ]
54
- text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
55
-
56
- query_engine = index.as_query_engine(text_qa_template=text_qa_template)
57
- answer = query_engine.query(query)
58
-
59
- if hasattr(answer, 'response'):
60
- return answer.response
61
- elif isinstance(answer, dict) and 'response' in answer:
62
- return answer['response']
63
- else:
64
- return "Sorry, I couldn't find an answer."
65
-
66
- def process_file(file):
67
- if file is None:
68
- return "Please upload a PDF file."
69
-
70
- temp_dir = tempfile.mkdtemp()
71
- temp_path = os.path.join(temp_dir, "uploaded.pdf")
72
-
73
- with open(temp_path, "wb") as f:
74
- f.write(file.read())
75
-
76
- # Copy the file to the DATA_DIR
77
- os.makedirs(DATA_DIR, exist_ok=True)
78
- dest_path = os.path.join(DATA_DIR, "saved_pdf.pdf")
79
- os.replace(temp_path, dest_path)
80
-
81
- # Process the uploaded PDF
82
- data_ingestion()
83
-
84
- return "PDF processed successfully. You can now ask questions about its content."
85
-
86
- def chatbot(message, history):
87
- response = handle_query(message)
88
- history.append((message, response))
89
- return history, ""
90
-
91
- # Gradio interface
92
- with gr.Blocks() as demo:
93
- gr.Markdown("# (PDF) Information and Inference🗞️")
94
- gr.Markdown("Retrieval-Augmented Generation")
95
-
96
- with gr.Row():
97
- with gr.Column(scale=1):
98
- file_output = gr.Textbox(label="Upload Status")
99
- upload_button = gr.UploadButton("Upload PDF", file_types=[".pdf"])
100
- upload_button.upload(process_file, upload_button, file_output)
101
-
102
- with gr.Column(scale=2):
103
- chatbot = gr.Chatbot(
104
- [],
105
- elem_id="chatbot",
106
- bubble_full_width=False,
107
- )
108
- msg = gr.Textbox(label="Ask me anything about the content of the PDF:")
109
- clear = gr.Button("Clear")
110
-
111
- msg.submit(chatbot, [msg, chatbot], [chatbot, msg])
112
- clear.click(lambda: None, None, chatbot, queue=False)
113
 
114
  if __name__ == "__main__":
115
  demo.launch()
 
1
+ from gradio_app import demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  if __name__ == "__main__":
4
  demo.launch()