Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import bs4
|
| 4 |
+
from langchain_openai import ChatOpenAI
|
| 5 |
+
from langchain_community.document_loaders import PyPDFLoader, WebBaseLoader
|
| 6 |
+
from langchain_chroma import Chroma
|
| 7 |
+
from langchain_openai import OpenAIEmbeddings
|
| 8 |
+
from langchain_core.output_parsers import StrOutputParser
|
| 9 |
+
from langchain_core.runnables import RunnablePassthrough
|
| 10 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 11 |
+
from langchain import hub
|
| 12 |
+
from bs4 import BeautifulSoup
|
| 13 |
+
import requests
|
| 14 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
os.environ["OPENAI_API_KEY"] = "sk-None-I5QCG8e21NqWVwxcHz2QT3BlbkFJUMfGESJ2JMWLZUwA4zPg"
|
| 18 |
+
llm = ChatOpenAI(model="gpt-4")
|
| 19 |
+
system_prompt = ChatPromptTemplate.from_messages([
|
| 20 |
+
("system", """You are an assistant for question-answering tasks. Use the following pieces of retrieved context to answer the question.
|
| 21 |
+
If you don't know the answer, just say that you don't know. Use three sentences maximum and keep the answer concise.
|
| 22 |
+
If the question is in Chinese, explain in Chisese. 如果问题以中文提问,那么就用流畅自然的中文来回答。
|
| 23 |
+
Question: {question}
|
| 24 |
+
Context: {context}
|
| 25 |
+
Answer:"""),
|
| 26 |
+
("user", "{question}, {context}")
|
| 27 |
+
])
|
| 28 |
+
|
| 29 |
+
vector_store = Chroma(
|
| 30 |
+
collection_name = "example_collection",
|
| 31 |
+
embedding_function = OpenAIEmbeddings(),
|
| 32 |
+
persist_directory = "./chroma_langchain_db", # Where to save data locally, remove if not neccesary
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def read_url(url):
|
| 36 |
+
response = requests.get(url)
|
| 37 |
+
html_content = response.text
|
| 38 |
+
paragraphs = BeautifulSoup(html_content, 'html.parser').find_all('p')
|
| 39 |
+
|
| 40 |
+
full_content = ""
|
| 41 |
+
for p in paragraphs:
|
| 42 |
+
full_content += p.get_text()
|
| 43 |
+
|
| 44 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200, add_start_index=True)
|
| 45 |
+
splits = text_splitter.create_documents([full_content])
|
| 46 |
+
return splits
|
| 47 |
+
|
| 48 |
+
def read_file(file):
|
| 49 |
+
if file.name.endswith('.pdf'):
|
| 50 |
+
loader = PyPDFLoader(file.name)
|
| 51 |
+
pages = loader.load_and_split()
|
| 52 |
+
|
| 53 |
+
elif file.name.endswith('.txt') or file.name.endswith('.md'):
|
| 54 |
+
loader = TextLoader(file.name)
|
| 55 |
+
pages = loader.load_and_split()
|
| 56 |
+
else:
|
| 57 |
+
return None
|
| 58 |
+
|
| 59 |
+
return pages
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def output_format_docs(docs):
|
| 64 |
+
formatted_docs = [
|
| 65 |
+
f"\n ========== 第{i+1}个知识片段 ========== \n{doc.page_content}"
|
| 66 |
+
for i, doc in enumerate(docs)
|
| 67 |
+
]
|
| 68 |
+
return "\n".join(formatted_docs)
|
| 69 |
+
|
| 70 |
+
def format_docs(docs):
|
| 71 |
+
return "\n\n".join(doc.page_content for doc in docs)
|
| 72 |
+
|
| 73 |
+
# ==================== GRADIO START ====================
|
| 74 |
+
def greet(prompt, file, url):
|
| 75 |
+
if file is not None:
|
| 76 |
+
file_splits = read_file(file)
|
| 77 |
+
if url is not None:
|
| 78 |
+
url_splits = read_url(url)
|
| 79 |
+
|
| 80 |
+
all_splits = file_splits + url_splits
|
| 81 |
+
vectorstore.add_documents(documents = all_splits)
|
| 82 |
+
|
| 83 |
+
retriever = vectorstore.as_retriever()
|
| 84 |
+
retrieved_docs = retriever.invoke(prompt)
|
| 85 |
+
formatted_doc = format_docs(retrieved_docs)
|
| 86 |
+
|
| 87 |
+
chain = system_prompt | llm | StrOutputParser()
|
| 88 |
+
complete_sentence = chain.invoke({"question": prompt, "context": formatted_doc})
|
| 89 |
+
|
| 90 |
+
output_0 = "========== 以下是系统搜索到的知识片段 ==========\n\n" + output_format_docs(retrieved_docs)
|
| 91 |
+
output_1 = "========== 以下是模型结合知识片段的回答 ==========\n\n" + complete_sentence
|
| 92 |
+
|
| 93 |
+
return output_0, output_1
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
demo = gr.Interface(fn=greet,
|
| 97 |
+
inputs=[gr.Textbox(placeholder = '在此处提问!', info = '这是info!', lines = 3),
|
| 98 |
+
gr.File(file_types = ['.pdf', '.txt', '.md'],
|
| 99 |
+
label = '支持PDF、TXT、MD格式(请勿上传公司内部文件!)',
|
| 100 |
+
# value = '/content/drive/MyDrive/Final Project Report.pdf',
|
| 101 |
+
file_count = 'multiple'),
|
| 102 |
+
gr.Textbox(placeholder = '在此处提问!')],
|
| 103 |
+
outputs = [gr.Textbox(label = '知识片段'), gr.Textbox(label = 'GPT参考知识片段的输出')]
|
| 104 |
+
)
|
| 105 |
+
demo.launch(debug=True)
|