Spaces:
Sleeping
Sleeping
bunch of changes
Browse files- app.py +198 -2
- chunks_output.txt +0 -0
- converted_docs/1.docx +0 -0
- converted_docs/10.docx +0 -0
- converted_docs/11.docx +0 -0
- converted_docs/12.docx +0 -0
- converted_docs/13.docx +0 -0
- converted_docs/14.docx +0 -0
- converted_docs/15.docx +0 -0
- converted_docs/16.docx +0 -0
- converted_docs/17.docx +0 -0
- converted_docs/19.docx +0 -0
- converted_docs/2.docx +0 -0
- converted_docs/20.docx +0 -0
- converted_docs/3.docx +0 -0
- converted_docs/4.docx +0 -0
- converted_docs/5.docx +0 -0
- converted_docs/6.docx +0 -0
- converted_docs/7.docx +0 -0
- converted_docs/8.docx +0 -0
- converted_docs/9.docx +0 -0
- requirements.txt +6 -0
app.py
CHANGED
@@ -1,4 +1,200 @@
|
|
1 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
-
|
4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
2 |
+
from docx import Document
|
3 |
+
import os
|
4 |
+
from langchain_core.prompts import PromptTemplate
|
5 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
6 |
+
import torch
|
7 |
+
import time
|
8 |
+
from sentence_transformers import SentenceTransformer
|
9 |
+
from langchain.vectorstores import Chroma
|
10 |
+
from langchain.docstore.document import Document
|
11 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
12 |
|
13 |
+
|
14 |
+
docs_folder = "./converted_docs"
|
15 |
+
|
16 |
+
|
17 |
+
# Function to load .docx files from Google Drive folder
|
18 |
+
def load_docx_files_from_drive(drive_folder):
|
19 |
+
docx_files = [f for f in os.listdir(drive_folder) if f.endswith(".docx")]
|
20 |
+
documents = []
|
21 |
+
|
22 |
+
for file_name in docx_files:
|
23 |
+
file_path = os.path.join(drive_folder, file_name)
|
24 |
+
doc = Document(file_path)
|
25 |
+
content = "\n".join([p.text for p in doc.paragraphs if p.text.strip()])
|
26 |
+
documents.append(content)
|
27 |
+
|
28 |
+
return documents
|
29 |
+
|
30 |
+
|
31 |
+
# Load .docx files from Google Drive folder
|
32 |
+
documents = load_docx_files_from_drive(docs_folder)
|
33 |
+
|
34 |
+
|
35 |
+
def split_extracted_text_into_chunks(documents):
|
36 |
+
# List to hold all chunks
|
37 |
+
chunks = []
|
38 |
+
|
39 |
+
for doc_text in documents:
|
40 |
+
# Split the document text into lines
|
41 |
+
lines = doc_text.splitlines()
|
42 |
+
|
43 |
+
# Initialize variables for splitting
|
44 |
+
current_chunk = []
|
45 |
+
for line in lines:
|
46 |
+
# Check if the line starts with "File Name:"
|
47 |
+
if line.startswith("File Name:"):
|
48 |
+
# If there's a current chunk, save it before starting a new one
|
49 |
+
if current_chunk:
|
50 |
+
chunks.append("\n".join(current_chunk))
|
51 |
+
current_chunk = [] # Reset the current chunk
|
52 |
+
|
53 |
+
# Add the line to the current chunk
|
54 |
+
current_chunk.append(line)
|
55 |
+
|
56 |
+
# Add the last chunk for the current document
|
57 |
+
if current_chunk:
|
58 |
+
chunks.append("\n".join(current_chunk))
|
59 |
+
|
60 |
+
return chunks
|
61 |
+
|
62 |
+
|
63 |
+
# Split the extracted documents into chunks
|
64 |
+
chunks = split_extracted_text_into_chunks(documents)
|
65 |
+
|
66 |
+
|
67 |
+
def save_chunks_to_file(chunks, output_file_path):
|
68 |
+
# Open the file in write mode
|
69 |
+
with open(output_file_path, "w", encoding="utf-8") as file:
|
70 |
+
for i, chunk in enumerate(chunks, start=1):
|
71 |
+
# Write each chunk with a header for easy identification
|
72 |
+
file.write(f"Chunk {i}:\n")
|
73 |
+
file.write(chunk)
|
74 |
+
file.write("\n" + "=" * 50 + "\n")
|
75 |
+
|
76 |
+
|
77 |
+
# Path to save the chunks file
|
78 |
+
output_file_path = "./chunks_output.txt"
|
79 |
+
|
80 |
+
# Split the extracted documents into chunks
|
81 |
+
chunks = split_extracted_text_into_chunks(documents)
|
82 |
+
|
83 |
+
# Save the chunks to the file
|
84 |
+
save_chunks_to_file(chunks, output_file_path)
|
85 |
+
|
86 |
+
|
87 |
+
# Step 1: Load the model through LangChain's wrapper
|
88 |
+
embedding_model = HuggingFaceEmbeddings(
|
89 |
+
model_name="Omartificial-Intelligence-Space/Arabic-Triplet-Matryoshka-V2"
|
90 |
+
)
|
91 |
+
|
92 |
+
|
93 |
+
# Step 2: Embed the chunks (now simplified)
|
94 |
+
def embed_chunks(chunks):
|
95 |
+
return [
|
96 |
+
{"chunk": chunk, "embedding": embedding_model.embed_query(chunk)}
|
97 |
+
for chunk in chunks
|
98 |
+
]
|
99 |
+
|
100 |
+
|
101 |
+
embeddings = embed_chunks(chunks)
|
102 |
+
|
103 |
+
|
104 |
+
# Step 3: Prepare documents (unchanged)
|
105 |
+
def prepare_documents_for_chroma(embeddings):
|
106 |
+
return [
|
107 |
+
Document(page_content=entry["chunk"], metadata={"chunk_index": i})
|
108 |
+
for i, entry in enumerate(embeddings, start=1)
|
109 |
+
]
|
110 |
+
|
111 |
+
|
112 |
+
documents = prepare_documents_for_chroma(embeddings)
|
113 |
+
|
114 |
+
# Step 4: Create Chroma store (fixed)
|
115 |
+
vectorstore = Chroma.from_documents(
|
116 |
+
documents=documents,
|
117 |
+
embedding=embedding_model, # Proper embedding object
|
118 |
+
persist_directory="./chroma_db", # Optional persistence
|
119 |
+
)
|
120 |
+
|
121 |
+
|
122 |
+
class RAGPipeline:
|
123 |
+
def __init__(self, vectorstore, model_name="CohereForAI/aya-expanse-8b", k=6):
|
124 |
+
self.vectorstore = vectorstore
|
125 |
+
self.model_name = model_name
|
126 |
+
self.k = k
|
127 |
+
self.retriever = self.vectorstore.as_retriever(
|
128 |
+
search_type="mmr", search_kwargs={"k": self.k}
|
129 |
+
)
|
130 |
+
self.prompt_template = PromptTemplate.from_template(self._get_template())
|
131 |
+
|
132 |
+
# Load model and tokenizer
|
133 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
134 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
135 |
+
self.model_name, torch_dtype=torch.bfloat16, device_map="auto"
|
136 |
+
)
|
137 |
+
|
138 |
+
def _get_template(self):
|
139 |
+
return """\
|
140 |
+
<s>[INST] <<SYS>>
|
141 |
+
أنت مساعد مفيد يقدم إجابات باللغة العربية بناءً على السياق المقدم.
|
142 |
+
- أجب فقط باللغة العربية
|
143 |
+
- إذا لم تجد إجابة في السياق، قل أنك لا تعرف
|
144 |
+
- كن دقيقاً وواضحاً في إجاباتك
|
145 |
+
<</SYS>>
|
146 |
+
|
147 |
+
السياق: {context}
|
148 |
+
|
149 |
+
السؤال: {question}
|
150 |
+
الإجابة: [/INST]\
|
151 |
+
"""
|
152 |
+
|
153 |
+
def generate_response(self, question):
|
154 |
+
retrieved_docs = self._retrieve_documents(question)
|
155 |
+
prompt = self._create_prompt(retrieved_docs, question)
|
156 |
+
response = self._generate_response(prompt)
|
157 |
+
return response
|
158 |
+
|
159 |
+
def _retrieve_documents(self, question):
|
160 |
+
start = time.time()
|
161 |
+
retrieved_docs = self.retriever.invoke(question)
|
162 |
+
result = {f"doc_{i}": doc.page_content for i, doc in enumerate(retrieved_docs)}
|
163 |
+
end = time.time()
|
164 |
+
time_lapsed = end - start
|
165 |
+
print(f"Time lapsed in Retreival: {time_lapsed}")
|
166 |
+
return result
|
167 |
+
|
168 |
+
def _create_prompt(self, docs, question):
|
169 |
+
return self.prompt_template.format(context=docs, question=question)
|
170 |
+
|
171 |
+
def _generate_response(self, prompt):
|
172 |
+
inputs = self.tokenizer(prompt, return_tensors="pt").to(self.model.device)
|
173 |
+
|
174 |
+
start = time.time()
|
175 |
+
outputs = self.model.generate(
|
176 |
+
inputs.input_ids,
|
177 |
+
max_new_tokens=1024,
|
178 |
+
temperature=0.7,
|
179 |
+
top_p=0.9,
|
180 |
+
do_sample=True,
|
181 |
+
pad_token_id=self.tokenizer.eos_token_id,
|
182 |
+
)
|
183 |
+
end = time.time()
|
184 |
+
time_lapsed = end - start
|
185 |
+
print(f"Time lapsed in Generation: {time_lapsed}")
|
186 |
+
|
187 |
+
response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
188 |
+
# Extract only the assistant's response after [/INST]
|
189 |
+
return response.split("[/INST]")[-1].strip()
|
190 |
+
|
191 |
+
|
192 |
+
rag_pipeline = RAGPipeline(vectorstore)
|
193 |
+
|
194 |
+
|
195 |
+
question = st.text_area("أدخل سؤالك هنا")
|
196 |
+
if st.button("Generate Answer"):
|
197 |
+
response = rag_pipeline.generate_response(question)
|
198 |
+
st.write(response)
|
199 |
+
print("Question: ", question)
|
200 |
+
print("Response: ", response)
|
chunks_output.txt
ADDED
File without changes
|
converted_docs/1.docx
ADDED
Binary file (72 kB). View file
|
|
converted_docs/10.docx
ADDED
Binary file (35 kB). View file
|
|
converted_docs/11.docx
ADDED
Binary file (59.6 kB). View file
|
|
converted_docs/12.docx
ADDED
Binary file (46.6 kB). View file
|
|
converted_docs/13.docx
ADDED
Binary file (52.3 kB). View file
|
|
converted_docs/14.docx
ADDED
Binary file (45.1 kB). View file
|
|
converted_docs/15.docx
ADDED
Binary file (47.7 kB). View file
|
|
converted_docs/16.docx
ADDED
Binary file (63.1 kB). View file
|
|
converted_docs/17.docx
ADDED
Binary file (55.5 kB). View file
|
|
converted_docs/19.docx
ADDED
Binary file (70 kB). View file
|
|
converted_docs/2.docx
ADDED
Binary file (115 kB). View file
|
|
converted_docs/20.docx
ADDED
Binary file (57.4 kB). View file
|
|
converted_docs/3.docx
ADDED
Binary file (44 kB). View file
|
|
converted_docs/4.docx
ADDED
Binary file (84.5 kB). View file
|
|
converted_docs/5.docx
ADDED
Binary file (60.7 kB). View file
|
|
converted_docs/6.docx
ADDED
Binary file (55.1 kB). View file
|
|
converted_docs/7.docx
ADDED
Binary file (59.2 kB). View file
|
|
converted_docs/8.docx
ADDED
Binary file (45.2 kB). View file
|
|
converted_docs/9.docx
ADDED
Binary file (45.1 kB). View file
|
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch
|
2 |
+
python-docx
|
3 |
+
langchain
|
4 |
+
langchain_community==0.0.36
|
5 |
+
langchain_chroma
|
6 |
+
sentence-transformers
|