Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- app.py +23 -0
- prepare_vector_dp.py +53 -0
- qabot.py +66 -0
app.py
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# backend.py
|
2 |
+
from fastapi import FastAPI, Request
|
3 |
+
from pydantic import BaseModel
|
4 |
+
from qabot import llm_chain
|
5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
6 |
+
|
7 |
+
app = FastAPI()
|
8 |
+
|
9 |
+
# Allow CORS for local frontend testing
|
10 |
+
app.add_middleware(
|
11 |
+
CORSMiddleware,
|
12 |
+
allow_origins=["*"],
|
13 |
+
allow_methods=["*"],
|
14 |
+
allow_headers=["*"],
|
15 |
+
)
|
16 |
+
|
17 |
+
class Query(BaseModel):
|
18 |
+
query: str
|
19 |
+
|
20 |
+
@app.post("/ask")
|
21 |
+
async def ask_question(query: Query):
|
22 |
+
answer = llm_chain.invoke({"query": query.query})
|
23 |
+
return {"answer": answer["result"]}
|
prepare_vector_dp.py
ADDED
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter, CharacterTextSplitter
|
2 |
+
from langchain_community.document_loaders import PyPDFLoader, DirectoryLoader
|
3 |
+
from langchain_community.vectorstores import FAISS
|
4 |
+
from langchain_community.embeddings import GPT4AllEmbeddings
|
5 |
+
|
6 |
+
from huggingface_hub import hf_hub_download
|
7 |
+
|
8 |
+
# Khai bao bien
|
9 |
+
pdf_data_path = "data"
|
10 |
+
vector_dp_path = "vectorstores/db_faiss"
|
11 |
+
|
12 |
+
model_file = hf_hub_download(
|
13 |
+
repo_id="Pudding48/TinyLlamaTest", # Replace with your model repo
|
14 |
+
filename="tinyllama-1.1b-chat-v1.0.Q8_0.gguf",
|
15 |
+
cache_dir="model" # Will be created in the Space's environment
|
16 |
+
)
|
17 |
+
|
18 |
+
# Ham 1. Tao ra vector DB tu 1 doan text
|
19 |
+
def create_db_from_text():
|
20 |
+
raw_text = "Trường Đại học Khoa học – Đại học Huế là một trong những cơ sở đào tạo và nghiên cứu hàng đầu tại khu vực miền Trung và Tây Nguyên. Được thành lập từ năm 1957, trường có bề dày truyền thống trong giảng dạy các ngành khoa học tự nhiên, xã hội và nhân văn. Với đội ngũ giảng viên giàu kinh nghiệm, cơ sở vật chất hiện đại và môi trường học tập năng động, Trường Đại học Khoa học luôn là lựa chọn uy tín của sinh viên trong và ngoài nước. Trường hiện tọa lạc tại số 77 Nguyễn Huệ, thành phố Huế – trung tâm văn hóa, giáo dục lớn của cả nước."
|
21 |
+
|
22 |
+
text_splitter = CharacterTextSplitter(
|
23 |
+
separator="\n",
|
24 |
+
chunk_size=512,
|
25 |
+
chunk_overlap=50,
|
26 |
+
length_function=len
|
27 |
+
)
|
28 |
+
|
29 |
+
chunks = text_splitter.split_text(raw_text)
|
30 |
+
|
31 |
+
# Embeding
|
32 |
+
embedding_model = GPT4AllEmbeddings(model_file= model_file)
|
33 |
+
|
34 |
+
# Dua vao Faiss Vector DB
|
35 |
+
db = FAISS.from_texts(texts=chunks, embedding=embedding_model)
|
36 |
+
db.save_local(vector_dp_path)
|
37 |
+
return db
|
38 |
+
|
39 |
+
def create_dp_from_files():
|
40 |
+
# Khai bao loader de quet toan bo thu muc data
|
41 |
+
loader = DirectoryLoader(pdf_data_path, glob="*.pdf",loader_cls=PyPDFLoader)
|
42 |
+
documents = loader.load()
|
43 |
+
|
44 |
+
text_splitter = CharacterTextSplitter(chunk_size = 512, chunk_overlap = 50)
|
45 |
+
chunks = text_splitter.split_documents(documents)
|
46 |
+
|
47 |
+
embedding_model = GPT4AllEmbeddings(model_file = model_file)
|
48 |
+
dp = FAISS.from_documents(chunks, embedding_model)
|
49 |
+
dp.save_local(vector_dp_path)
|
50 |
+
return dp
|
51 |
+
|
52 |
+
# create_db_from_text()
|
53 |
+
create_dp_from_files()
|
qabot.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain_community.llms import CTransformers
|
2 |
+
from langchain.prompts import PromptTemplate
|
3 |
+
from langchain_core.runnables import RunnableSequence
|
4 |
+
from langchain.chains import RetrievalQA
|
5 |
+
from langchain_community.embeddings import GPT4AllEmbeddings
|
6 |
+
from langchain_community.vectorstores import FAISS
|
7 |
+
|
8 |
+
from huggingface_hub import hf_hub_download
|
9 |
+
|
10 |
+
model_file = hf_hub_download(
|
11 |
+
repo_id="Pudding48/TinyLlamaTest", # Replace with your model repo
|
12 |
+
filename="tinyllama-1.1b-chat-v1.0.Q8_0.gguf",
|
13 |
+
cache_dir="model" # Will be created in the Space's environment
|
14 |
+
)
|
15 |
+
|
16 |
+
# Cấu hình
|
17 |
+
#model_file = "model/tinyllama-1.1b-chat-v1.0.Q8_0.gguf"
|
18 |
+
vector_dp_path = "vectorstores/db_faiss"
|
19 |
+
|
20 |
+
# Load LLM
|
21 |
+
def load_llm(model_file):
|
22 |
+
llm = CTransformers(
|
23 |
+
model=model_file,
|
24 |
+
model_type="llama",
|
25 |
+
temperature=0.01,
|
26 |
+
config={'gpu_layers': 0},
|
27 |
+
max_new_tokens=128,
|
28 |
+
context_length=512
|
29 |
+
)
|
30 |
+
return llm
|
31 |
+
|
32 |
+
# Tạo prompt template
|
33 |
+
def creat_prompt(template):
|
34 |
+
prompt = PromptTemplate(template=template, input_variables=["context","question"])
|
35 |
+
return prompt
|
36 |
+
|
37 |
+
# Tạo pipeline chain (thay cho LLMChain)
|
38 |
+
def create_qa_chain(prompt, llm, db):
|
39 |
+
llm_chain = RetrievalQA.from_chain_type(
|
40 |
+
llm = llm,
|
41 |
+
chain_type = "stuff",
|
42 |
+
retriever =db.as_retriever(search_kwargs = {"k":1}),
|
43 |
+
return_source_documents = False,
|
44 |
+
chain_type_kwargs={'prompt':prompt}
|
45 |
+
)
|
46 |
+
return llm_chain
|
47 |
+
|
48 |
+
def read_vector_db():
|
49 |
+
embedding_model = GPT4AllEmbeddings(model_file = "model/all-minilm-l6-v2-q4_0.gguf")
|
50 |
+
db = FAISS.load_local(vector_dp_path, embedding_model,allow_dangerous_deserialization=True)
|
51 |
+
return db
|
52 |
+
|
53 |
+
db = read_vector_db()
|
54 |
+
llm = load_llm(model_file)
|
55 |
+
# Mẫu prompt
|
56 |
+
template = """<|im_start|>system\nSử dụng thông tin sau đây để trả lời câu hỏi. Nếu bạn không biết câu trả lời, hãy nói không biết, đừng cố tạo ra câu trả lời\n
|
57 |
+
{context}<|im_end|>\n<|im_start|>user\n{question}<|im_end|>\n<|im_start|>assistant"""
|
58 |
+
|
59 |
+
# Khởi tạo các thành phần
|
60 |
+
prompt = creat_prompt(template)
|
61 |
+
llm_chain =create_qa_chain(prompt, llm, db)
|
62 |
+
|
63 |
+
# Chạy thử chain
|
64 |
+
question = "Khoa công nghệ thông tin thành lập năm nào ?"
|
65 |
+
response = llm_chain.invoke({"query": question})
|
66 |
+
print(response)
|