Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,5 @@
|
|
1 |
import streamlit as st
|
|
|
2 |
from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
|
3 |
from llama_index.llms.huggingface import HuggingFaceInferenceAPI
|
4 |
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
@@ -8,7 +9,6 @@ import shutil
|
|
8 |
import os
|
9 |
import time
|
10 |
|
11 |
-
|
12 |
icons = {"assistant": "robot.png", "user": "man-kddi.png"}
|
13 |
|
14 |
# Configure the Llama index settings
|
@@ -17,7 +17,6 @@ Settings.llm = HuggingFaceInferenceAPI(
|
|
17 |
tokenizer_name="meta-llama/Meta-Llama-3-8B-Instruct",
|
18 |
context_window=3900,
|
19 |
token=os.getenv("HF_TOKEN"),
|
20 |
-
# max_new_tokens=1000,
|
21 |
generate_kwargs={"temperature": 0.1},
|
22 |
)
|
23 |
Settings.embed_model = HuggingFaceEmbedding(
|
@@ -33,33 +32,39 @@ os.makedirs(DATA_DIR, exist_ok=True)
|
|
33 |
os.makedirs(PERSIST_DIR, exist_ok=True)
|
34 |
|
35 |
def data_ingestion():
|
36 |
-
documents =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
storage_context = StorageContext.from_defaults()
|
38 |
index = VectorStoreIndex.from_documents(documents)
|
39 |
index.storage_context.persist(persist_dir=PERSIST_DIR)
|
40 |
|
41 |
def remove_old_files():
|
42 |
-
# Specify the directory path you want to clear
|
43 |
directory_path = "data"
|
44 |
-
|
45 |
-
# Remove all files and subdirectories in the specified directory
|
46 |
shutil.rmtree(directory_path)
|
47 |
-
|
48 |
-
# Recreate an empty directory if needed
|
49 |
os.makedirs(directory_path)
|
50 |
|
51 |
def extract_transcript_details(youtube_video_url):
|
52 |
try:
|
53 |
-
video_id=youtube_video_url.split("=")[1]
|
54 |
-
|
55 |
-
transcript_text=YouTubeTranscriptApi.get_transcript(video_id)
|
56 |
|
57 |
transcript = ""
|
58 |
for i in transcript_text:
|
59 |
transcript += " " + i["text"]
|
60 |
|
61 |
return transcript
|
62 |
-
|
63 |
except Exception as e:
|
64 |
st.error(e)
|
65 |
|
@@ -67,21 +72,20 @@ def handle_query(query):
|
|
67 |
storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
|
68 |
index = load_index_from_storage(storage_context)
|
69 |
chat_text_qa_msgs = [
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
]
|
80 |
text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
|
81 |
query_engine = index.as_query_engine(text_qa_template=text_qa_template)
|
82 |
answer = query_engine.query(query)
|
83 |
|
84 |
-
|
85 |
if hasattr(answer, 'response'):
|
86 |
return answer.response
|
87 |
elif isinstance(answer, dict) and 'response' in answer:
|
@@ -94,7 +98,6 @@ def streamer(text):
|
|
94 |
yield i
|
95 |
time.sleep(0.001)
|
96 |
|
97 |
-
|
98 |
# Streamlit app initialization
|
99 |
st.title("Chat with your PDF📄")
|
100 |
st.markdown("**Built by [Pachaiappan❤️](https://mr-vicky-01.github.io/Portfolio/)**")
|
@@ -108,15 +111,15 @@ for message in st.session_state.messages:
|
|
108 |
|
109 |
with st.sidebar:
|
110 |
st.title("Menu:")
|
111 |
-
uploaded_file = st.file_uploader("Upload your PDF Files and Click on the Submit & Process Button")
|
112 |
video_url = st.text_input("Enter Youtube Video Link: ")
|
113 |
if st.button("Submit & Process"):
|
114 |
with st.spinner("Processing..."):
|
115 |
-
if len(os.listdir("data")) !=0:
|
116 |
remove_old_files()
|
117 |
|
118 |
if uploaded_file:
|
119 |
-
filepath =
|
120 |
with open(filepath, "wb") as f:
|
121 |
f.write(uploaded_file.getbuffer())
|
122 |
|
@@ -125,10 +128,10 @@ with st.sidebar:
|
|
125 |
with open("data/saved_text.txt", "w") as file:
|
126 |
file.write(extracted_text)
|
127 |
|
128 |
-
data_ingestion() # Process
|
129 |
st.success("Done")
|
130 |
|
131 |
-
user_prompt = st.chat_input("Ask me anything about the content of the PDF:")
|
132 |
|
133 |
if user_prompt and (uploaded_file or video_url):
|
134 |
st.session_state.messages.append({'role': 'user', "content": user_prompt})
|
@@ -140,4 +143,3 @@ if user_prompt and (uploaded_file or video_url):
|
|
140 |
response = handle_query(user_prompt)
|
141 |
with st.chat_message("user", avatar="robot.png"):
|
142 |
st.write_stream(streamer(response))
|
143 |
-
st.session_state.messages.append({'role': 'assistant', "content": response})
|
|
|
1 |
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
from llama_index.core import StorageContext, load_index_from_storage, VectorStoreIndex, SimpleDirectoryReader, ChatPromptTemplate
|
4 |
from llama_index.llms.huggingface import HuggingFaceInferenceAPI
|
5 |
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
|
|
9 |
import os
|
10 |
import time
|
11 |
|
|
|
12 |
icons = {"assistant": "robot.png", "user": "man-kddi.png"}
|
13 |
|
14 |
# Configure the Llama index settings
|
|
|
17 |
tokenizer_name="meta-llama/Meta-Llama-3-8B-Instruct",
|
18 |
context_window=3900,
|
19 |
token=os.getenv("HF_TOKEN"),
|
|
|
20 |
generate_kwargs={"temperature": 0.1},
|
21 |
)
|
22 |
Settings.embed_model = HuggingFaceEmbedding(
|
|
|
32 |
os.makedirs(PERSIST_DIR, exist_ok=True)
|
33 |
|
34 |
def data_ingestion():
|
35 |
+
documents = []
|
36 |
+
|
37 |
+
# Load documents from the data directory
|
38 |
+
documents += SimpleDirectoryReader(DATA_DIR).load_data()
|
39 |
+
|
40 |
+
# Process and load CSV files
|
41 |
+
for file in os.listdir(DATA_DIR):
|
42 |
+
if file.endswith(".csv"):
|
43 |
+
csv_path = os.path.join(DATA_DIR, file)
|
44 |
+
df = pd.read_csv(csv_path)
|
45 |
+
# Convert DataFrame to a list of text strings (or any other format suitable for your embeddings)
|
46 |
+
csv_texts = df.apply(lambda row: " ".join(row.astype(str)), axis=1).tolist()
|
47 |
+
documents += csv_texts
|
48 |
+
|
49 |
storage_context = StorageContext.from_defaults()
|
50 |
index = VectorStoreIndex.from_documents(documents)
|
51 |
index.storage_context.persist(persist_dir=PERSIST_DIR)
|
52 |
|
53 |
def remove_old_files():
|
|
|
54 |
directory_path = "data"
|
|
|
|
|
55 |
shutil.rmtree(directory_path)
|
|
|
|
|
56 |
os.makedirs(directory_path)
|
57 |
|
58 |
def extract_transcript_details(youtube_video_url):
|
59 |
try:
|
60 |
+
video_id = youtube_video_url.split("=")[1]
|
61 |
+
transcript_text = YouTubeTranscriptApi.get_transcript(video_id)
|
|
|
62 |
|
63 |
transcript = ""
|
64 |
for i in transcript_text:
|
65 |
transcript += " " + i["text"]
|
66 |
|
67 |
return transcript
|
|
|
68 |
except Exception as e:
|
69 |
st.error(e)
|
70 |
|
|
|
72 |
storage_context = StorageContext.from_defaults(persist_dir=PERSIST_DIR)
|
73 |
index = load_index_from_storage(storage_context)
|
74 |
chat_text_qa_msgs = [
|
75 |
+
(
|
76 |
+
"user",
|
77 |
+
"""You are Q&A assistant named CHATTO, created by Pachaiappan [linkdin](https://www.linkedin.com/in/pachaiappan) an AI Specialist. 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, you only say the user to 'Please ask a questions within the context of the document'.
|
78 |
+
Context:
|
79 |
+
{context_str}
|
80 |
+
Question:
|
81 |
+
{query_str}
|
82 |
+
"""
|
83 |
+
)
|
84 |
]
|
85 |
text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)
|
86 |
query_engine = index.as_query_engine(text_qa_template=text_qa_template)
|
87 |
answer = query_engine.query(query)
|
88 |
|
|
|
89 |
if hasattr(answer, 'response'):
|
90 |
return answer.response
|
91 |
elif isinstance(answer, dict) and 'response' in answer:
|
|
|
98 |
yield i
|
99 |
time.sleep(0.001)
|
100 |
|
|
|
101 |
# Streamlit app initialization
|
102 |
st.title("Chat with your PDF📄")
|
103 |
st.markdown("**Built by [Pachaiappan❤️](https://mr-vicky-01.github.io/Portfolio/)**")
|
|
|
111 |
|
112 |
with st.sidebar:
|
113 |
st.title("Menu:")
|
114 |
+
uploaded_file = st.file_uploader("Upload your PDF/CSV Files and Click on the Submit & Process Button")
|
115 |
video_url = st.text_input("Enter Youtube Video Link: ")
|
116 |
if st.button("Submit & Process"):
|
117 |
with st.spinner("Processing..."):
|
118 |
+
if len(os.listdir("data")) != 0:
|
119 |
remove_old_files()
|
120 |
|
121 |
if uploaded_file:
|
122 |
+
filepath = os.path.join(DATA_DIR, uploaded_file.name)
|
123 |
with open(filepath, "wb") as f:
|
124 |
f.write(uploaded_file.getbuffer())
|
125 |
|
|
|
128 |
with open("data/saved_text.txt", "w") as file:
|
129 |
file.write(extracted_text)
|
130 |
|
131 |
+
data_ingestion() # Process every time new file is uploaded
|
132 |
st.success("Done")
|
133 |
|
134 |
+
user_prompt = st.chat_input("Ask me anything about the content of the PDF/CSV:")
|
135 |
|
136 |
if user_prompt and (uploaded_file or video_url):
|
137 |
st.session_state.messages.append({'role': 'user', "content": user_prompt})
|
|
|
143 |
response = handle_query(user_prompt)
|
144 |
with st.chat_message("user", avatar="robot.png"):
|
145 |
st.write_stream(streamer(response))
|
|