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