File size: 1,668 Bytes
cd8aa60
 
 
 
 
 
 
 
 
 
 
 
10a7877
cd8aa60
 
9290216
cd8aa60
 
 
 
 
9290216
 
cd8aa60
 
9290216
 
cd8aa60
 
 
 
 
 
 
 
9290216
cd8aa60
 
 
 
 
 
 
 
 
9290216
cd8aa60
 
 
9290216
cd8aa60
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import os
from PyPDF2 import PdfReader
import docx
from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import FAISS
from langchain.chains.question_answering import load_qa_chain
from langchain_openai import OpenAI
from langchain.callbacks import get_openai_callback
import gradio as gr
from aiohttp import web

# Set your OpenAI API key
os.environ["OPENAI_API_KEY"] = "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"

# Function to read text from a file
def read_txt(file_path):
    with open(file_path, "r") as file:
        text = file.read()
    return text

# Load text from the specified file
text_file_path = '/home/user/app/content/lawsofpower.txt'
user_query = read_txt(text_file_path)

# Set up text processing components
char_text_splitter = CharacterTextSplitter(separator="\n", chunk_size=1000, chunk_overlap=200, length_function=len)
text_chunks = char_text_splitter.split_text(user_query)

embeddings = OpenAIEmbeddings()
docsearch = FAISS.from_texts(text_chunks, embeddings)

llm = OpenAI()
chain = load_qa_chain(llm, chain_type="stuff")

# Define the chatbot interface
async def chatbot_interface(request):
    data = await request.post()
    input_text = data.get("input_text", "")
    
    docs = docsearch.similarity_search(input_text)
    response = chain.run(input_documents=docs, question=input_text)
    
    return web.Response(text=response)

# Set up the web application
app = web.Application()
app.router.add_post('/chatbot', chatbot_interface)

# Run the web server
if __name__ == "__main__":
    web.run_app(app, port=os.getenv("PORT", 8080))