rishabh5752 commited on
Commit
17829f2
β€’
1 Parent(s): 6f1887b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pickle
3
+ import time
4
+ import gradio as gr
5
+ from langchain import OpenAI
6
+ from langchain.chains import RetrievalQAWithSourcesChain
7
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
8
+ from langchain.document_loaders import UnstructuredURLLoader
9
+ from langchain.embeddings import OpenAIEmbeddings
10
+ from langchain.vectorstores import FAISS
11
+ from dotenv import load_dotenv
12
+
13
+ load_dotenv() # take environment variables from .env (especially openai api key)
14
+
15
+ # Define the main function to process URLs and handle queries
16
+ def process_and_query(url1, url2, url3, query):
17
+ urls = [url1, url2, url3]
18
+ file_path = "faiss_store_openai.pkl"
19
+ llm = OpenAI(temperature=0.9, max_tokens=500)
20
+
21
+ # Load data
22
+ loader = UnstructuredURLLoader(urls=urls)
23
+ data = loader.load()
24
+
25
+ # Split data
26
+ text_splitter = RecursiveCharacterTextSplitter(
27
+ separators=['\n\n', '\n', '.', ','],
28
+ chunk_size=1000
29
+ )
30
+ docs = text_splitter.split_documents(data)
31
+
32
+ # Create embeddings and save it to FAISS index
33
+ embeddings = OpenAIEmbeddings()
34
+ vectorstore_openai = FAISS.from_documents(docs, embeddings)
35
+
36
+ # Save the FAISS index to a pickle file
37
+ with open(file_path, "wb") as f:
38
+ pickle.dump(vectorstore_openai, f)
39
+
40
+ # Process the query
41
+ if os.path.exists(file_path):
42
+ with open(file_path, "rb") as f:
43
+ vectorstore = pickle.load(f)
44
+ chain = RetrievalQAWithSourcesChain.from_llm(llm=llm, retriever=vectorstore.as_retriever())
45
+ result = chain({"question": query}, return_only_outputs=True)
46
+ answer = result["answer"]
47
+
48
+ # Extract and format sources
49
+ sources = result.get("sources", "")
50
+ sources_list = sources.split("\n") if sources else []
51
+ return answer, sources_list
52
+
53
+ # Define the Gradio interface
54
+ url1_input = gr.inputs.Textbox(label="URL 1")
55
+ url2_input = gr.inputs.Textbox(label="URL 2")
56
+ url3_input = gr.inputs.Textbox(label="URL 3")
57
+ query_input = gr.inputs.Textbox(label="Question")
58
+
59
+ output_text = gr.outputs.Textbox(label="Answer")
60
+ output_sources = gr.outputs.Textbox(label="Sources")
61
+
62
+ interface = gr.Interface(
63
+ fn=process_and_query,
64
+ inputs=[url1_input, url2_input, url3_input, query_input],
65
+ outputs=[output_text, output_sources],
66
+ title="RockyBot: News Research Tool πŸ“ˆ",
67
+ description="Enter up to three news article URLs and ask a question. The bot will process the articles and provide an answer along with the sources."
68
+ )
69
+
70
+ if __name__ == "__main__":
71
+ interface.launch()