Rajut commited on
Commit
9ff796c
·
verified ·
1 Parent(s): 2a06ee9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -0
app.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from PyPDF2 import PdfReader
3
+ import docx
4
+ from langchain.text_splitter import CharacterTextSplitter
5
+ from langchain.embeddings.openai import OpenAIEmbeddings
6
+ from langchain.vectorstores import FAISS
7
+ from langchain.chains.question_answering import load_qa_chain
8
+ from langchain_openai import OpenAI
9
+ from langchain.callbacks import get_openai_callback
10
+ import gradio as gr
11
+ from aiohttp import web
12
+
13
+ # Set your OpenAI API key
14
+ os.environ["OPENAI_API_KEY"] = "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"
15
+
16
+ # Function to read text from a file
17
+ def read_txt(file_path):
18
+ with open(file_path, "r") as file:
19
+ text = file.read()
20
+ return text
21
+
22
+ # Load text from the specified file
23
+ text_file_path = '/home/user/app/content/lawsofpower.txt'
24
+ user_query = read_txt(text_file_path)
25
+
26
+ # Set up text processing components
27
+ char_text_splitter = CharacterTextSplitter(separator="\n", chunk_size=1000, chunk_overlap=200, length_function=len)
28
+ text_chunks = char_text_splitter.split_text(user_query)
29
+
30
+ embeddings = OpenAIEmbeddings()
31
+ docsearch = FAISS.from_texts(text_chunks, embeddings)
32
+
33
+ llm = OpenAI()
34
+ chain = load_qa_chain(llm, chain_type="stuff")
35
+
36
+ # Define the chatbot interface
37
+ async def chatbot_interface(request):
38
+ data = await request.post()
39
+ input_text = data.get("input_text", "")
40
+
41
+ docs = docsearch.similarity_search(input_text)
42
+ response = chain.run(input_documents=docs, question=input_text)
43
+
44
+ return web.Response(text=response)
45
+
46
+ # Set up the web application
47
+ app = web.Application()
48
+ app.router.add_post('/chatbot', chatbot_interface)
49
+
50
+ # Run the web server
51
+ if __name__ == "__main__":
52
+ web.run_app(app, port=os.getenv("PORT", 8080))