M17idd commited on
Commit
bc23008
·
verified ·
1 Parent(s): d8bfdcf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -65
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
- @st.cache_resource
12
- def load_model():
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
- for filename in os.listdir(folder_path):
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
- st.title("🔎 یافتن نزدیک‌ترین بخش ۵ جمله‌ای به ورودی شما")
 
 
 
 
 
 
 
 
62
 
63
- # مسیر پوشه فایل‌های docx
64
  folder_path = '46'
 
 
 
 
 
 
 
 
65
 
66
- # بارگذاری و نمایش تعداد بخش‌ها
67
- chunks = load_text_chunks(folder_path)
68
- st.success(f"{len(chunks)} بخش ۵ جمله‌ای بارگذاری شد.")
 
 
 
 
69
 
70
- # ورودی کاربر
71
- user_input = st.text_area("لطفاً جمله یا متن خود را وارد کنید:")
72
- def calculate_similarities_parallel(user_embedding, chunks):
73
- with concurrent.futures.ThreadPoolExecutor() as executor:
74
- similarities = list(executor.map(lambda chunk: cosine_similarity(user_embedding, get_embedding(chunk)), chunks))
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
- st.subheader("📌 شبیه‌ترین بخش ۵ جمله‌ای:")
87
- st.write(result)
 
 
 
 
 
 
 
 
 
 
 
 
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)