shahed125238 commited on
Commit
830ad8f
·
verified ·
1 Parent(s): cadc5ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -37
app.py CHANGED
@@ -1,49 +1,114 @@
1
  import gradio as gr
2
- from llama_index import load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
 
 
 
 
 
 
 
3
  import os
 
4
 
5
- # Define directories
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  PERSIST_DIR = "./db"
7
  DATA_DIR = "data"
8
 
9
- # Ensure directories exist
10
  os.makedirs(DATA_DIR, exist_ok=True)
11
  os.makedirs(PERSIST_DIR, exist_ok=True)
12
 
 
 
 
 
 
 
 
 
13
  def data_ingestion():
14
- try:
15
- documents = SimpleDirectoryReader(DATA_DIR).load_data()
16
- index = VectorStoreIndex.from_documents(documents)
17
- index.storage_context.persist(persist_dir=PERSIST_DIR) # Adjust this if storage is handled differently
18
- except Exception as e:
19
- print(f"Error during data ingestion: {str(e)}")
20
 
 
21
  def handle_query(query):
22
- try:
23
- index = load_index_from_storage(persist_dir=PERSIST_DIR) # Adjust loading method if needed
24
-
25
- chat_text_qa_msgs = [
26
- (
27
- "user",
28
- """You are a Q&A assistant named AskAI, created by Vatsa. 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.
29
- Context:
30
- {context_str}
31
- Question:
32
- {query_str}
33
- """
34
- )
35
- ]
36
- text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
37
-
38
- query_engine = index.as_query_engine(text_qa_template=text_qa_template)
39
- answer = query_engine.query(query)
40
-
41
- if hasattr(answer, 'response'):
42
- return answer.response
43
- elif isinstance(answer, dict) and 'response' in answer:
44
- return answer['response']
45
- else:
46
- return "Sorry, I couldn't find an answer."
47
- except Exception as e:
48
- print(f"Error during query handling: {str(e)}")
49
- return "An error occurred while processing your query."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import pandas as pd
3
+ import pickle
4
+ import streamlit as st
5
+ from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
6
+ from llama_index.llms.huggingface import HuggingFaceInferenceAPI
7
+ from dotenv import load_dotenv
8
+ from llama_index.embeddings.huggingface import HuggingFaceEmbedding
9
+ from llama_index.core import Settings
10
  import os
11
+ import base64
12
 
13
+ # Load environment variables for HuggingFace API
14
+ load_dotenv()
15
+
16
+ # Configure the Llama index settings
17
+ Settings.llm = HuggingFaceInferenceAPI(
18
+ model_name="google/gemma-1.1-7b-it",
19
+ tokenizer_name="google/gemma-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
+ Settings.embed_model = HuggingFaceEmbedding(
26
+ model_name="BAAI/bge-small-en-v1.5"
27
+ )
28
+
29
+ # Define directories for persistent storage and data
30
  PERSIST_DIR = "./db"
31
  DATA_DIR = "data"
32
 
33
+ # Ensure data directory exists
34
  os.makedirs(DATA_DIR, exist_ok=True)
35
  os.makedirs(PERSIST_DIR, exist_ok=True)
36
 
37
+ # Function to display PDF in Streamlit
38
+ def displayPDF(file):
39
+ with open(file, "rb") as f:
40
+ base64_pdf = base64.b64encode(f.read()).decode('utf-8')
41
+ pdf_display = f'<iframe src="data:application/pdf;base64,{base64_pdf}" width="100%" height="600" type="application/pdf"></iframe>'
42
+ st.markdown(pdf_display, unsafe_allow_html=True)
43
+
44
+ # Function to handle PDF ingestion
45
  def data_ingestion():
46
+ documents = SimpleDirectoryReader(DATA_DIR).load_data()
47
+ storage_context = StorageContext.from_defaults()
48
+ index = VectorStoreIndex.from_documents(documents)
49
+ index.storage_context.persist(persist_dir=PERSIST_DIR)
 
 
50
 
51
+ # Function to handle user queries
52
  def handle_query(query):
53
+ storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
54
+ index = load_index_from_storage(storage_context)
55
+ chat_text_qa_msgs = [
56
+ (
57
+ "user",
58
+ """You are a Q&A assistant named AskAI, created by Vatsa. You have a specific response programmed for when users ask about your creator, Suriya. The response is: "I was created by Suriya, an enthusiast in Artificial Intelligence."
59
+ Context:
60
+ {context_str}
61
+ Question:
62
+ {query_str}
63
+ """
64
+ )
65
+ ]
66
+ text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
67
+
68
+ query_engine = index.as_query_engine(text_qa_template=text_qa_template)
69
+ answer = query_engine.query(query)
70
+
71
+ if hasattr(answer, 'response'):
72
+ return answer.response
73
+ elif isinstance(answer, dict) and 'response' in answer:
74
+ return answer['response']
75
+ else:
76
+ return "Sorry, I couldn't find an answer."
77
+
78
+ # Streamlit interface
79
+ st.title("Integrated App: Gradio & Streamlit")
80
+ st.markdown("### PDF Q&A + Machine Health Prediction")
81
+
82
+ # Gradio App via iframe
83
+ st.markdown("#### Machine Health Prediction App (Gradio)")
84
+ gradio_app_url = "http://localhost:7860" # URL where Gradio app is running
85
+ st.markdown(f'<iframe src="{gradio_app_url}" width="100%" height="800"></iframe>', unsafe_allow_html=True)
86
+
87
+ # Streamlit section for PDF upload and chat
88
+ st.markdown("#### PDF Chatbot App (Streamlit)")
89
+
90
+ if 'messages' not in st.session_state:
91
+ st.session_state.messages = [{'role': 'assistant', "content": 'Hello! Upload a PDF and ask me anything about its content.'}]
92
+
93
+ with st.sidebar:
94
+ st.title("Menu:")
95
+ uploaded_file = st.file_uploader("Upload your PDF Files and Click on the Submit & Process Button")
96
+ if st.button("Submit & Process"):
97
+ with st.spinner("Processing..."):
98
+ filepath = "data/saved_pdf.pdf"
99
+ with open(filepath, "wb") as f:
100
+ f.write(uploaded_file.getbuffer())
101
+ # displayPDF(filepath) # Display the uploaded PDF
102
+ data_ingestion() # Process PDF every time new file is uploaded
103
+ st.success("Done")
104
+
105
+ user_prompt = st.chat_input("Ask me anything about the content of the PDF:")
106
+ if user_prompt:
107
+ st.session_state.messages.append({'role': 'user', "content": user_prompt})
108
+ response = handle_query(user_prompt)
109
+ st.session_state.messages.append({'role': 'assistant', "content": response})
110
+
111
+ for message in st.session_state.messages:
112
+ with st.chat_message(message['role']):
113
+ st.write(message['content'])
114
+