import time import streamlit as st from langchain.document_loaders import PyPDFLoader from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.embeddings.base import Embeddings from langchain.vectorstores import FAISS from langchain.indexes import VectorstoreIndexCreator from langchain.chains import RetrievalQA from langchain.chat_models import ChatOpenAI from typing import List from together import Together import pandas as pd import streamlit as st from langchain.docstore.document import Document import docx import os from hazm import * st.markdown(""" """, unsafe_allow_html=True) # ----------------- احراز هویت ساده ----------------- if "authenticated" not in st.session_state: st.session_state.authenticated = False if not st.session_state.authenticated: st.markdown("

ورود به رزم‌یار ارتش

", unsafe_allow_html=True) username = st.text_input("نام کاربری:", placeholder="شناسه نظامی خود را وارد کنید") password = st.text_input("رمز عبور:", type="password", placeholder="رمز عبور نظامی") if st.button("ورود"): if username == "admin" and password == "123": st.session_state.authenticated = True st.rerun() else: st.error("نام کاربری یا رمز عبور اشتباه است.") st.stop() # ----------------- سایدبار ----------------- with st.sidebar: st.image("log.png", use_container_width=True) # اصلاح use_column_width menu_items = [ ("گزارش عملیاتی", "https://cdn-icons-png.flaticon.com/512/3596/3596165.png"), ("تاریخچه ماموریت‌ها", "https://cdn-icons-png.flaticon.com/512/709/709496.png"), ("تحلیل داده‌های نظامی", "https://cdn-icons-png.flaticon.com/512/1828/1828932.png"), ("مدیریت منابع", "https://cdn-icons-png.flaticon.com/512/681/681494.png"), ("دستیار فرماندهی", "https://cdn-icons-png.flaticon.com/512/3601/3601646.png"), ("تنظیمات امنیتی", "https://cdn-icons-png.flaticon.com/512/2099/2099058.png"), ("پشتیبانی فنی", "https://cdn-icons-png.flaticon.com/512/597/597177.png"), ] for idx, (text, icon) in enumerate(menu_items): st.markdown(f""" """, unsafe_allow_html=True) if idx in [1, 3, 5]: st.markdown("
", unsafe_allow_html=True) # ----------------- محتوای اصلی ----------------- st.markdown("""

رزم‌یار ارتش

دستیار هوشمندارتش
""", unsafe_allow_html=True) # پیام خوش‌آمدگویی st.markdown(f"""
🪖 به رزم‌ یار ارتش خوش آمدید.
""", unsafe_allow_html=True) # ----------------- لود csv و ساخت ایندکس ----------------- normalizer = Normalizer() # توکنایزر هضم tokenizer = word_tokenize # بارگذاری مدل WordEmbedding word_embedding = WordEmbedding(model_type='fasttext') WordEmbedding = wordEmbedding.load_model('word2vec.bin') # مدل از اینترنت دانلود می‌شود class CustomEmbeddings(Embeddings): def __init__(self, word_embedding: WordEmbedding): self.word_embedding = word_embedding def embed_documents(self, texts: List[str]) -> List[List[float]]: embeddings = [] for text in texts: # ایجاد امبدینگ برای هر کلمه در متن embeddings.append([self.word_embedding.embed(word) for word in tokenizer(text)]) return embeddings def embed_query(self, text: str) -> List[float]: return self.embed_documents([text])[0] @st.cache_resource def get_docx_index(folder_path): with st.spinner('📄 در حال پردازش فایل‌های Word...'): texts = [] # خواندن تمام فایل‌های .docx در پوشه 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) # نرمال‌سازی و توکنایز کردن متن‌ها normalized_texts = [normalizer.normalize(text) for text in texts] tokenized_texts = [tokenizer(text) for text in normalized_texts] # تقسیم متن‌ها text_splitter = RecursiveCharacterTextSplitter( chunk_size=300, chunk_overlap=50, length_function=len, separators=["\n\n", "\n", " ", ""] ) split_texts = [] for text in normalized_texts: split_texts.extend(text_splitter.split_text(text)) # ایجاد embedding با استفاده از WordEmbedding embeddings = CustomEmbeddings(word_embedding=word_embedding) # ساخت ایندکس index_creator = VectorstoreIndexCreator( embedding=embeddings, text_splitter=text_splitter ) documents = [Document(page_content=text) for text in split_texts] return index_creator.from_documents(documents) # مسیر فایل CSV folder_path = '46/' try: docx_index = get_docx_index(folder_path) except Exception as e: st.error(f"❌ خطا در ساخت ایندکس: {e}") #------------------------------------------ llm = ChatOpenAI( base_url="https://api.together.xyz/v1", api_key='0291f33aee03412a47fa5d8e562e515182dcc5d9aac5a7fb5eefdd1759005979', model="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free" ) chain = RetrievalQA.from_chain_type( llm=llm, chain_type='stuff', retriever=docx_index.vectorstore.as_retriever(), input_key='question' ) if 'messages' not in st.session_state: st.session_state.messages = [] if 'pending_prompt' not in st.session_state: st.session_state.pending_prompt = None for msg in st.session_state.messages: with st.chat_message(msg['role']): st.markdown(f"🗨️ {msg['content']}", unsafe_allow_html=True) prompt = st.chat_input("چطور می‌تونم کمک کنم؟") if prompt: st.session_state.messages.append({'role': 'user', 'content': prompt}) st.session_state.pending_prompt = prompt st.rerun() if st.session_state.pending_prompt: with st.chat_message('ai'): thinking = st.empty() thinking.markdown("🤖 در حال فکر کردن...") response = chain.run(f'پاسخ را فقط به زبان فارسی جواب بده به هیچ عنوان از زبان چینی در پاسخ استفاده نکن. سوال: {st.session_state.pending_prompt}') answer = response.split("Helpful Answer:")[-1].strip() if "Helpful Answer:" in response else response.strip() if not answer: answer = "متأسفم، اطلاعات دقیقی در این مورد ندارم." thinking.empty() full_response = "" placeholder = st.empty() for word in answer.split(): full_response += word + " " placeholder.markdown(full_response + "▌") time.sleep(0.03) placeholder.markdown(full_response) st.session_state.messages.append({'role': 'ai', 'content': full_response}) st.session_state.pending_prompt = None