aelsaeed commited on
Commit
0223d15
·
verified ·
1 Parent(s): 2443249

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -172
app.py CHANGED
@@ -1,192 +1,94 @@
1
- # ================== imports ==================
2
- import gradio as gr
3
  import pandas as pd
4
  import numpy as np
5
- import os, tempfile, re
6
- from sentence_transformers import SentenceTransformer, util
7
- from sklearn.feature_extraction.text import TfidfVectorizer
8
  from sklearn.metrics.pairwise import cosine_similarity
9
- import gdown
10
-
11
- # ================== إعدادات ==================
12
- BOOKS_FILE = "book.xlsx"
13
- THESES_FILE = "theses.xlsx"
14
-
15
- DRIVE_BOOKS_ID = "1IVu5M_zHWg3wo-cbQm3FWhmDIafUSCVP"
16
- DRIVE_THESES_ID = "1zpC9b28VvT3NRLEywDcEqEdYcTOtEdQDwFoYWtFOMKA"
17
-
18
- TOP_K = 20
19
- TFIDF_TOP_N = 150
20
- TFIDF_FALLBACK_MIN = 40
21
 
22
- # ================== نموذج طبي ==================
23
- model = SentenceTransformer(
24
- "pritamdeka/BioBERT-mnli-snli-scinli-scitail-mednli-stsb"
25
- )
26
 
27
- # ================== تحميل الملفات ==================
28
- def download_from_drive(file_id, output):
29
- if not os.path.exists(output):
30
- url = f"https://drive.google.com/uc?id={file_id}"
31
- gdown.download(url, output, quiet=True)
32
 
33
- download_from_drive(DRIVE_BOOKS_ID, BOOKS_FILE)
34
- download_from_drive(DRIVE_THESES_ID, THESES_FILE)
35
 
36
- # ================== تحميل البيانات ==================
37
- books_df = pd.read_excel(BOOKS_FILE).fillna("")
38
- theses_df = pd.read_excel(THESES_FILE).fillna("")
 
 
 
 
 
 
 
 
 
39
 
40
- books_df["المصدر"] = "كتاب"
41
- theses_df["المصدر"] = "رسالة"
 
42
 
43
- library_df = pd.concat([books_df, theses_df], ignore_index=True)
 
 
 
44
 
45
- # ================== Normalize ==================
46
- def normalize_text(text):
47
- text = str(text).lower()
48
- text = re.sub(r"[^a-zA-Z0-9\u0600-\u06FF\s]", " ", text)
49
- text = text.replace("أ", "ا").replace("إ", "ا").replace("آ", "ا")
50
- text = text.replace("ى", "ي").replace("ة", "ه")
51
- return re.sub(r"\s+", " ", text).strip()
52
-
53
- # ================== استخراج نصوص الصفوف ==================
54
- semantic_cols = [c for c in library_df.columns if library_df[c].dtype == object]
55
-
56
- def row_to_text(row):
57
- text = " ".join(str(row[c]) for c in semantic_cols if row[c])
58
- text = normalize_text(text)
59
- return text
60
-
61
- # ================== Embeddings ==================
62
- texts = library_df.apply(row_to_text, axis=1).tolist()
63
- embeddings = model.encode(texts, convert_to_numpy=True, normalize_embeddings=True, show_progress_bar=True)
64
- library_df["embedding"] = list(embeddings)
65
-
66
- # ================== TF-IDF ==================
67
- def tfidf_prefilter(df, query):
68
- texts = df.apply(row_to_text, axis=1).tolist()
69
- vec = TfidfVectorizer(ngram_range=(1,3), max_features=30000, stop_words="english")
70
- mat = vec.fit_transform(texts)
71
- q_vec = vec.transform([normalize_text(query)])
72
- scores = cosine_similarity(q_vec, mat)[0]
73
- df = df.copy()
74
- df["tfidf_score"] = scores
75
- return df.sort_values("tfidf_score", ascending=False).head(TFIDF_TOP_N)
76
-
77
- # ================== CSS ==================
78
- CUSTOM_CSS = """
79
- <style>
80
- .card{border:1px solid #ddd;border-radius:8px;padding:10px;margin:12px 0;background:#fafafa;}
81
- .card table{width:100%;border-collapse:collapse;direction:rtl;}
82
- .card td{border:1px solid #ccc;padding:8px;text-align:center;vertical-align:middle;font-size:15px;}
83
- .card td.label{width:30%;font-weight:bold;}
84
- .row-title td{background:#e3f2fd;color:#0d47a1;font-weight:bold;}
85
- .row-author td{background:#fce4ec;color:#880e4f;}
86
- .row-year td{background:#e8f5e9;color:#1b5e20;}
87
- .row-degree td{background:#f3e5f5;color:#6a1b9a;font-weight:bold;}
88
- .row-shelf td{background:#fff8e1;color:#e65100;font-weight:bold;font-size:16px;}
89
- </style>
90
- """
91
-
92
- def safe(v):
93
- return "-" if pd.isna(v) or str(v).strip() == "" else str(v)
94
-
95
- def results_to_html(df):
96
- if df.empty:
97
- return "<p>❌ لا توجد نتائج</p>"
98
- html = ""
99
- for _, r in df.iterrows():
100
- html += f"""
101
- <div class="card">
102
- <table>
103
- <tr class="row-title">
104
- <td class="label">العنوان</td>
105
- <td>{safe(r.get("العنوان"))}</td>
106
- </tr>
107
- <tr class="row-author">
108
- <td class="label">المؤلف</td>
109
- <td>{safe(r.get("المؤلف"))}</td>
110
- </tr>
111
- <tr class="row-degree">
112
- <td class="label">الفئة / القسم</td>
113
- <td>{safe(r.get("الفئة"))}</td>
114
- </tr>
115
- <tr class="row-year">
116
- <td class="label">سنة النشر</td>
117
- <td>{safe(r.get("سنة النشر"))}</td>
118
- </tr>
119
- <tr class="row-shelf">
120
- <td class="label">الموقع على الرف</td>
121
- <td>{safe(r.get("الموقع على الرف"))}</td>
122
- </tr>
123
- </table>
124
- </div>
125
- """
126
- return CUSTOM_CSS + html
127
-
128
- # ================== البحث ==================
129
- def local_search_df(query, mode, category, year_from, year_to):
130
- if not query.strip():
131
- return "<p>⚠️ اكتب كلمة للبحث</p>", pd.DataFrame()
132
-
133
- df = library_df.copy()
134
-
135
- # فلترة الفئة
136
  if category != "الكل":
137
- df = df[df["الفئة"] == category]
138
-
139
- # فلترة سنة النشر
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  if year_from:
141
- df = df[df["سنة النشر"].astype(str).str.isnumeric()]
142
- df = df[df["سنة النشر"].astype(int) >= int(year_from)]
143
  if year_to:
144
- df = df[df["سنة النشر"].astype(str).str.isnumeric()]
145
- df = df[df["سنة النشر"].astype(int) <= int(year_to)]
 
146
 
147
- if mode == "نصي":
148
- q = normalize_text(query)
149
- mask = df.apply(lambda r: q in row_to_text(r), axis=1)
150
- df = df[mask].head(TOP_K)
151
- else:
152
- df_pref = tfidf_prefilter(df, query)
153
- if len(df_pref) < TFIDF_FALLBACK_MIN:
154
- df_pref = df
155
- q_emb = model.encode([normalize_text(query)], normalize_embeddings=True)
156
- mat = np.vstack(df_pref["embedding"].values)
157
- scores = util.cos_sim(q_emb, mat)[0].cpu().numpy()
158
- df_pref["score"] = scores
159
- df = df_pref.sort_values("score", ascending=False).head(TOP_K)
160
-
161
- return results_to_html(df), df
162
-
163
- # ================== حفظ النتائج ==================
164
- def save_to_excel(df):
165
- tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".xlsx")
166
- df.drop(columns=["embedding", "score", "tfidf_score"], errors="ignore").to_excel(tmp.name, index=False)
167
- return tmp.name
168
-
169
- # ================== واجهة Gradio ==================
170
  categories = ["الكل"] + sorted(library_df["الفئة"].dropna().unique().tolist())
171
 
172
- with gr.Blocks(title="نظام البحث الذكي بالمكتبة") as app:
173
- gr.Markdown("## 🔍 البحث الذكي في مقتنيات المكتبة")
174
-
175
- query = gr.Textbox(label="كلمة أو موضوع البحث")
176
- mode = gr.Radio(["نصي", "دلالي (Semantic)"], value="دلالي", label="نوع البحث")
177
- category = gr.Dropdown(categories, value="الكل", label="اختر الفئة")
178
- year_from = gr.Textbox(label="من سنة (اختياري)")
179
- year_to = gr.Textbox(label="إلى سنة (اختياري)")
180
-
181
- btn = gr.Button("🔎 بحث")
182
- out_html = gr.HTML()
183
- df_state = gr.State()
184
- file_out = gr.File(label="⬇️ تحميل النتائج")
185
-
186
- btn.click(local_search_df, [query, mode, category, year_from, year_to], [out_html, df_state])
187
- gr.Button("📥 حفظ النتائج").click(save_to_excel, df_state, file_out)
 
 
 
 
 
 
188
 
189
- app.launch()
190
 
191
 
192
 
 
 
 
1
  import pandas as pd
2
  import numpy as np
3
+ from sentence_transformers import SentenceTransformer
4
+ from fuzzywuzzy import fuzz
 
5
  from sklearn.metrics.pairwise import cosine_similarity
6
+ import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ # ================== تحميل البيانات ==================
9
+ books_file = "books.xlsx"
10
+ theses_file = "theses.xlsx"
 
11
 
12
+ books_df = pd.read_excel(books_file)
13
+ theses_df = pd.read_excel(theses_file)
 
 
 
14
 
15
+ library_df = pd.concat([books_df, theses_df], ignore_index=True)
 
16
 
17
+ # ================== توليد عمود الفئة ==================
18
+ library_df["الفئة"] = ""
19
+ current_category = ""
20
+ rows_to_drop = []
21
+ for i, row in library_df.iterrows():
22
+ title = str(row.get("العنوان", "")).strip()
23
+ # لو الصف ده بيحتوي على اسم قسم بدل رسالة
24
+ if any(keyword in title for keyword in ["جامعة", "كليه", "قسم", "مكتبة"]):
25
+ current_category = title
26
+ rows_to_drop.append(i) # نخزن صفوف الأقسام لنحذفها بعد كده
27
+ else:
28
+ library_df.at[i, "الفئة"] = current_category
29
 
30
+ # حذف الصفوف اللي مجرد أسماء أقسام
31
+ library_df.drop(rows_to_drop, inplace=True)
32
+ library_df.reset_index(drop=True, inplace=True)
33
 
34
+ # ================== إعداد Embeddings للبحث الدلالي ==================
35
+ MODEL_NAME = "all-MiniLM-L6-v2"
36
+ model = SentenceTransformer(MODEL_NAME)
37
+ embeddings = model.encode(library_df["العنوان"].tolist(), show_progress_bar=True)
38
 
39
+ # ================== دوال البحث ==================
40
+ def text_search(query, category="الكل", year_from=None, year_to=None):
41
+ results = library_df.copy()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  if category != "الكل":
43
+ results = results[results["الفئة"] == category]
44
+ if year_from:
45
+ results = results[results["سنة النشر"].astype(str).str[:4].astype(int) >= int(year_from)]
46
+ if year_to:
47
+ results = results[results["سنة النشر"].astype(str).str[:4].astype(int) <= int(year_to)]
48
+ results["score"] = results["العنوان"].apply(lambda x: fuzz.partial_ratio(str(x), query))
49
+ results = results.sort_values(by="score", ascending=False)
50
+ return results.head(20)[["العنوان", "المؤلف", "سنة النشر", "الفئة", "الموقع على الرف"]]
51
+
52
+ def semantic_search(query, category="الكل", year_from=None, year_to=None):
53
+ query_emb = model.encode([query])
54
+ scores = cosine_similarity(query_emb, embeddings)[0]
55
+ results = library_df.copy()
56
+ results["score"] = scores
57
+ if category != "الكل":
58
+ results = results[results["الفئة"] == category]
59
  if year_from:
60
+ results = results[results["سنة النشر"].astype(str).str[:4].astype(int) >= int(year_from)]
 
61
  if year_to:
62
+ results = results[results["سنة النشر"].astype(str).str[:4].astype(int) <= int(year_to)]
63
+ results = results.sort_values(by="score", ascending=False)
64
+ return results.head(20)[["العنوان", "المؤلف", "سنة النشر", "الفئة", "الموقع على الرف"]]
65
 
66
+ # ================== إعداد واجهة Gradio ==================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  categories = ["الكل"] + sorted(library_df["الفئة"].dropna().unique().tolist())
68
 
69
+ with gr.Blocks() as demo:
70
+ gr.Markdown("## البحث في مكتبة الرسائل والكتب")
71
+ with gr.Row():
72
+ search_input = gr.Textbox(label="اكتب كلمة البحث")
73
+ category_input = gr.Dropdown(choices=categories, label="اختر الفئة", value="الكل")
74
+ with gr.Row():
75
+ year_from_input = gr.Textbox(label="من سنة (اختياري)")
76
+ year_to_input = gr.Textbox(label="إلى سنة (اختياري)")
77
+ with gr.Row():
78
+ search_type = gr.Radio(choices=["بحث نصي", "بحث دلالي"], label="نوع البحث", value="بحث نصي")
79
+ output_table = gr.Dataframe(headers=["العنوان", "المؤلف", "سنة النشر", "الفئة", "الموقع على الرف"])
80
+
81
+ def search_action(query, category, year_from, year_to, search_type_val):
82
+ if search_type_val == "بحث نصي":
83
+ return text_search(query, category, year_from, year_to)
84
+ else:
85
+ return semantic_search(query, category, year_from, year_to)
86
+
87
+ search_btn = gr.Button("بحث")
88
+ search_btn.click(search_action, [search_input, category_input, year_from_input, year_to_input, search_type], output_table)
89
+
90
+ demo.launch()
91
 
 
92
 
93
 
94