# ================== imports ================== import gradio as gr import pandas as pd import numpy as np import os, tempfile, re import gdown from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity # ================== إعدادات ================== BOOKS_FILE = "book.xlsx" THESES_FILE = "theses.xlsx" DRIVE_BOOKS_ID = "1IVu5M_zHWg3wo-cbQm3FWhmDIafUSCVP" DRIVE_THESES_ID = "1hvZIGFG6h0kQY32bIuEWGRdXTZp84vhk" TOP_K = 20 TFIDF_TOP_N = 120 # ================== تحميل الملفات ================== def download_from_drive(file_id, output): if not os.path.exists(output): url = f"https://drive.google.com/uc?id={file_id}" print(f"Downloading {output}...") gdown.download(url, output, quiet=False) download_from_drive(DRIVE_BOOKS_ID, BOOKS_FILE) download_from_drive(DRIVE_THESES_ID, THESES_FILE) # ================== تحميل البيانات ================== def safe_read_excel(path): if not os.path.exists(path): raise FileNotFoundError(f"الملف غير موجود: {path}") return pd.read_excel(path).fillna("") books_df = safe_read_excel(BOOKS_FILE) theses_df = safe_read_excel(THESES_FILE) books_df["المصدر"] = "كتاب" theses_df["المصدر"] = "رسالة" # ================== توحيد الأعمدة المهمة ================== def ensure_column(df, col_name): if col_name not in df.columns: df[col_name] = "" return df important_cols = ["العنوان", "المؤلف", "سنة النشر", "الموقع على الرف"] for df in [books_df, theses_df]: for col in important_cols: ensure_column(df, col) df["الموقع على الرف"] = ( df["الموقع على الرف"] .astype(str) .str.strip() .replace(["nan", "NaN", "None", ""], "-") ) library_df = pd.concat([books_df, theses_df], ignore_index=True) # ================== اكتشاف الأعمدة الدلالية ================== def detect_semantic_columns(df): exclude = ["م", "سنة", "تاريخ", "رقم", "كود", "الموقع", "الرف"] include = ["عنوان", "العنوان", "مؤلف", "المؤلف", "موضوع", "ملخص", "وصف", "كلمات"] cols = [] for c in df.columns: s = str(c) if any(x in s for x in exclude): continue if any(x in s for x in include): cols.append(c) if not cols: cols = df.select_dtypes(include="object").columns.tolist() return list(dict.fromkeys(cols)) semantic_cols = detect_semantic_columns(library_df) # ================== Normalize ================== def normalize_text(text): text = str(text).lower() text = text.replace("أ", "ا").replace("إ", "ا").replace("آ", "ا") text = text.replace("ى", "ي").replace("ة", "ه") text = text.replace("ؤ", "و").replace("ئ", "ي") text = re.sub(r"[^\w\s]", " ", text) text = re.sub(r"\d+", " ", text) return re.sub(r"\s+", " ", text).strip() def row_to_text(row): return normalize_text( " ".join(str(row[c]) for c in semantic_cols if c in row and str(row[c]).strip()) ) # ================== نص موحد للبحث ================== print("Preparing searchable text...") library_df["search_text"] = library_df.apply(row_to_text, axis=1) # ================== بناء TF-IDF مرة واحدة فقط ================== print("Building TF-IDF index...") tfidf_vectorizer = TfidfVectorizer(ngram_range=(1, 2), max_features=20000) tfidf_matrix = tfidf_vectorizer.fit_transform(library_df["search_text"].tolist()) print("TF-IDF ready.") # ================== تحميل الـ Semantic Model عند الحاجة فقط ================== semantic_model = None embeddings_cache = None def load_semantic_resources(): global semantic_model, embeddings_cache if semantic_model is None: print("Loading semantic model lazily...") from sentence_transformers import SentenceTransformer semantic_model = SentenceTransformer("sentence-transformers/paraphrase-MiniLM-L3-v2") print("Semantic model loaded.") if embeddings_cache is None: print("Generating embeddings lazily...") embeddings_cache = semantic_model.encode( library_df["search_text"].tolist(), convert_to_numpy=True, normalize_embeddings=True, show_progress_bar=True ) print("Embeddings ready.") # ================== CSS ================== CUSTOM_CSS = """ """ def safe(v): return "-" if pd.isna(v) or str(v).strip() == "" else str(v) def results_to_html(df, query="", mode="", source_filter="", extra_note=""): if df.empty: return CUSTOM_CSS + """
| #{i} العنوان | {safe(r.get("العنوان"))} |
| المؤلف | {safe(r.get("المؤلف"))} |
| سنة النشر | {safe(r.get("سنة النشر"))} |
| الموقع على الرف | {safe(r.get("الموقع على الرف"))} |
| المصدر | {safe(r.get("المصدر"))} |