Update app.py
Browse files
app.py
CHANGED
@@ -1,51 +1,17 @@
|
|
|
|
1 |
import os
|
2 |
-
import concurrent.futures
|
3 |
-
import docx
|
4 |
import torch
|
5 |
import numpy as np
|
6 |
-
import streamlit as st
|
7 |
from hazm import *
|
|
|
8 |
from transformers import AutoTokenizer, AutoModel
|
|
|
9 |
|
10 |
-
# بارگذاری
|
11 |
-
|
12 |
-
|
13 |
-
tokenizer = AutoTokenizer.from_pretrained("HooshvareLab/bert-fa-base-uncased")
|
14 |
-
model = AutoModel.from_pretrained("HooshvareLab/bert-fa-base-uncased")
|
15 |
-
return tokenizer, model
|
16 |
-
|
17 |
-
tokenizer, model = load_model()
|
18 |
-
|
19 |
-
# پردازش فایلهای Word و تبدیل به جملات
|
20 |
-
@st.cache_data
|
21 |
-
def load_text_chunks(folder_path):
|
22 |
-
normalizer = Normalizer()
|
23 |
-
sentence_tokenizer = SentenceTokenizer()
|
24 |
-
texts = []
|
25 |
|
26 |
-
|
27 |
-
if filename.endswith(".docx"):
|
28 |
-
full_path = os.path.join(folder_path, filename)
|
29 |
-
doc = docx.Document(full_path)
|
30 |
-
file_text = "\n".join([para.text for para in doc.paragraphs])
|
31 |
-
if file_text.strip():
|
32 |
-
texts.append(file_text)
|
33 |
-
|
34 |
-
all_sentences = []
|
35 |
-
for text in texts:
|
36 |
-
normalized = normalizer.normalize(text)
|
37 |
-
sentences = sentence_tokenizer.tokenize(normalized)
|
38 |
-
all_sentences.extend(sentences)
|
39 |
-
|
40 |
-
# تقسیم به بخشهای ۵ جملهای
|
41 |
-
chunks = []
|
42 |
-
for i in range(0, len(all_sentences), 5):
|
43 |
-
chunk = " ".join(all_sentences[i:i+5])
|
44 |
-
if chunk:
|
45 |
-
chunks.append(chunk)
|
46 |
-
return chunks
|
47 |
-
|
48 |
-
# محاسبه embedding با BERT
|
49 |
def get_embedding(text):
|
50 |
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
51 |
with torch.no_grad():
|
@@ -53,35 +19,56 @@ def get_embedding(text):
|
|
53 |
embeddings = outputs.last_hidden_state.mean(dim=1)
|
54 |
return embeddings.squeeze().numpy()
|
55 |
|
56 |
-
# شباهت
|
57 |
def cosine_similarity(vec1, vec2):
|
58 |
return np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))
|
59 |
|
60 |
-
#
|
61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
63 |
-
#
|
64 |
folder_path = '46'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
|
66 |
-
|
67 |
-
|
68 |
-
|
|
|
|
|
|
|
|
|
69 |
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
return similarities
|
76 |
-
if st.button("🔍 جستجو"):
|
77 |
-
if not user_input.strip():
|
78 |
-
st.warning("لطفاً یک جمله وارد کنید.")
|
79 |
-
else:
|
80 |
-
with st.spinner("در حال محاسبه شباهتها..."):
|
81 |
-
user_embedding = get_embedding(user_input)
|
82 |
-
similarities = calculate_similarities_parallel(user_embedding, chunks)
|
83 |
-
most_similar_index = np.argmax(similarities)
|
84 |
-
result = chunks[most_similar_index]
|
85 |
|
86 |
-
|
87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
import os
|
|
|
|
|
3 |
import torch
|
4 |
import numpy as np
|
|
|
5 |
from hazm import *
|
6 |
+
import docx
|
7 |
from transformers import AutoTokenizer, AutoModel
|
8 |
+
from langchain.llms import OpenAI
|
9 |
|
10 |
+
# بارگذاری مدلها و توکنایزر
|
11 |
+
tokenizer = AutoTokenizer.from_pretrained("HooshvareLab/bert-fa-base-uncased")
|
12 |
+
model = AutoModel.from_pretrained("HooshvareLab/bert-fa-base-uncased")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
+
@st.cache
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
def get_embedding(text):
|
16 |
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
17 |
with torch.no_grad():
|
|
|
19 |
embeddings = outputs.last_hidden_state.mean(dim=1)
|
20 |
return embeddings.squeeze().numpy()
|
21 |
|
22 |
+
# تابع برای محاسبه شباهت
|
23 |
def cosine_similarity(vec1, vec2):
|
24 |
return np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))
|
25 |
|
26 |
+
# تعریف مدل LLM برای بازنویسی پاسخ
|
27 |
+
llm = OpenAI(api_key="your_openai_api_key")
|
28 |
+
|
29 |
+
def rewrite_answer_with_llm(answer, user_input):
|
30 |
+
prompt = f"پاسخی که باید بازنویسی شود: {answer}\n\nلطفاً این پاسخ را با لحن مشابه به سوال پرسیده شده بازنویسی کن:\n\nسوال: {user_input}"
|
31 |
+
response = llm(prompt)
|
32 |
+
return response['choices'][0]['text'].strip()
|
33 |
+
|
34 |
+
# وارد کردن متن از کاربر
|
35 |
+
user_input = st.text_input("✅ لطفاً جمله خود را وارد کنید: ")
|
36 |
|
37 |
+
# بارگذاری متنها و تقسیم به بخشها
|
38 |
folder_path = '46'
|
39 |
+
texts = []
|
40 |
+
for filename in os.listdir(folder_path):
|
41 |
+
if filename.endswith(".docx"):
|
42 |
+
full_path = os.path.join(folder_path, filename)
|
43 |
+
doc = docx.Document(full_path)
|
44 |
+
file_text = "\n".join([para.text for para in doc.paragraphs])
|
45 |
+
if file_text.strip():
|
46 |
+
texts.append(file_text)
|
47 |
|
48 |
+
normalizer = Normalizer()
|
49 |
+
sentence_tokenizer = SentenceTokenizer()
|
50 |
+
all_sentences = []
|
51 |
+
for text in texts:
|
52 |
+
normalized = normalizer.normalize(text)
|
53 |
+
sentences = sentence_tokenizer.tokenize(normalized)
|
54 |
+
all_sentences.extend(sentences)
|
55 |
|
56 |
+
chunks = []
|
57 |
+
for i in range(0, len(all_sentences), 5):
|
58 |
+
chunk = " ".join(all_sentences[i:i+5])
|
59 |
+
if chunk:
|
60 |
+
chunks.append(chunk)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
+
# محاسبه شباهتها
|
63 |
+
if user_input:
|
64 |
+
with st.spinner("در حال محاسبه شباهتها..."):
|
65 |
+
user_embedding = get_embedding(user_input)
|
66 |
+
similarities = [cosine_similarity(user_embedding, get_embedding(chunk)) for chunk in chunks]
|
67 |
+
most_similar_index = np.argmax(similarities)
|
68 |
+
most_similar_chunk = chunks[most_similar_index]
|
69 |
+
|
70 |
+
# بازنویسی پاسخ با مدل LLM
|
71 |
+
rewritten_answer = rewrite_answer_with_llm(most_similar_chunk, user_input)
|
72 |
+
|
73 |
+
st.subheader("📌 پاسخ بازنویسیشده:")
|
74 |
+
st.write(rewritten_answer)
|