aelsaeed commited on
Commit
8306da7
·
verified ·
1 Parent(s): 19429c9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -59
app.py CHANGED
@@ -7,11 +7,8 @@ from sentence_transformers import SentenceTransformer, util
7
  import gdown
8
 
9
  # ================== إعدادات ==================
10
- BOOKS_FILE = "book.xlsx"
11
- THESES_FILE = "theses.xlsx"
12
-
13
- DRIVE_BOOKS_ID = "1FElHiASfiVLeuHWYaqd2Q5foxWRlJT-O"
14
- DRIVE_THESES_ID = "1K2Mtze6ZdvfKUsFMCOWlRBjDq-ZnJNrv"
15
 
16
  EMB_DIR = "embeddings"
17
  os.makedirs(EMB_DIR, exist_ok=True)
@@ -28,38 +25,34 @@ def download_from_drive(file_id, output):
28
  except Exception:
29
  pass
30
 
31
- download_from_drive(DRIVE_BOOKS_ID, BOOKS_FILE)
32
- download_from_drive(DRIVE_THESES_ID, THESES_FILE)
33
 
34
- # ================== تحميل ودمج الملفات ==================
35
- def load_and_merge():
36
- if not os.path.exists(BOOKS_FILE) or not os.path.exists(THESES_FILE):
37
- raise FileNotFoundError("❌ تأكدي من وجود book.xlsx و theses.xlsx")
38
 
39
- books = pd.read_excel(BOOKS_FILE).fillna("")
40
- theses = pd.read_excel(THESES_FILE).fillna("")
41
 
42
  # توحيد عمود العنوان
43
- def normalize_title(df):
44
- if "Title" not in df.columns:
45
- if "العنوان" in df.columns:
46
- df["Title"] = df["العنوان"].astype(str)
47
- else:
48
- df["Title"] = df.iloc[:, 0].astype(str)
49
- return df
50
 
51
- books = normalize_title(books)
52
- theses = normalize_title(theses)
 
 
53
 
54
- # إضافة نوع المصدر
55
- books["المصدر"] = "كتاب"
56
- theses["المصدر"] = "رسالة"
57
 
58
- # دمج
59
- merged = pd.concat([books, theses], ignore_index=True)
60
- return merged
61
 
62
- library_df = load_and_merge()
63
 
64
  # ================== Embeddings ==================
65
  def emb_path(name):
@@ -81,41 +74,55 @@ def build_or_load_embeddings(df, name):
81
 
82
  library_embeddings = build_or_load_embeddings(library_df, "library")
83
 
84
- # ================== عرض النتائج HTML ==================
85
- def results_to_html(df):
86
- return df.to_html(index=False, escape=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  # ================== البحث ==================
89
- def local_search_df(query, mode, source_filter):
90
  if not query or not query.strip():
91
  return "<p>⚠️ اكتب كلمة أو جملة للبحث</p>", pd.DataFrame()
92
 
93
- df_search = library_df.copy()
94
-
95
- # فلترة حسب المصدر
96
- if source_filter != "الكل":
97
- df_search = df_search[df_search["المصدر"] == source_filter]
98
-
99
  # ---- بحث نصي ----
100
  if mode == "نصي":
101
- col = "العنوان" if "العنوان" in df_search.columns else "Title"
102
- df = df_search[df_search[col].astype(str).str.contains(query, case=False, na=False)]
103
 
104
  # ---- بحث دلالي ----
105
  else:
106
  q_emb = model.encode([query], convert_to_numpy=True)
107
  scores = util.cos_sim(q_emb, library_embeddings)[0].cpu().numpy()
108
- df_search = df_search.copy()
109
- df_search["score"] = scores
110
- df = df_search.sort_values("score", ascending=False)
111
 
112
  if df.empty:
113
- df = pd.DataFrame([{"نتيجة": "❌ لم يتم العثور على نتائج"}])
114
 
115
- if "Title" in df.columns:
116
- df = df.drop(columns=["Title"])
117
-
118
- return results_to_html(df), df
119
 
120
  # ================== حفظ النتائج Excel ==================
121
  def save_to_excel(df):
@@ -127,9 +134,8 @@ def save_to_excel(df):
127
  return tmp.name
128
 
129
  # ================== الواجهة ==================
130
- with gr.Blocks(title="البحث الدلالي بالمكتبة") as app:
131
- gr.Markdown("## 🔍 البحث بالمكتبة (ملف موحد)")
132
-
133
  query = gr.Textbox(label="اكتب كلمة أو موضوع البحث")
134
 
135
  mode = gr.Radio(
@@ -138,12 +144,6 @@ with gr.Blocks(title="البحث الدلالي بالمكتبة") as app:
138
  label="نوع البحث"
139
  )
140
 
141
- source_filter = gr.Radio(
142
- ["الكل", "كتاب", "رسالة"],
143
- value="الكل",
144
- label="فلترة حسب المصدر"
145
- )
146
-
147
  btn_search = gr.Button("🔎 بحث")
148
 
149
  df_state = gr.State()
@@ -152,7 +152,7 @@ with gr.Blocks(title="البحث الدلالي بالمكتبة") as app:
152
 
153
  btn_search.click(
154
  local_search_df,
155
- inputs=[query, mode, source_filter],
156
  outputs=[output_html, df_state]
157
  )
158
 
 
7
  import gdown
8
 
9
  # ================== إعدادات ==================
10
+ LIB_FILE = "library.xlsx" # ملف المكتبة
11
+ DRIVE_FILE_ID = "PUT_DRIVE_FILE_ID_HERE" # ID الملف على Google Drive
 
 
 
12
 
13
  EMB_DIR = "embeddings"
14
  os.makedirs(EMB_DIR, exist_ok=True)
 
25
  except Exception:
26
  pass
27
 
28
+ download_from_drive(DRIVE_FILE_ID, LIB_FILE)
 
29
 
30
+ # ================== تحميل البيانات ==================
31
+ def load_library():
32
+ if not os.path.exists(LIB_FILE):
33
+ raise FileNotFoundError("❌ ملف library.xlsx غير موجود")
34
 
35
+ df = pd.read_excel(LIB_FILE).fillna("غير متوافر")
 
36
 
37
  # توحيد عمود العنوان
38
+ if "Title" not in df.columns:
39
+ if "العنوان" in df.columns:
40
+ df["Title"] = df["العنوان"].astype(str)
41
+ else:
42
+ df["Title"] = df.iloc[:, 0].astype(str)
 
 
43
 
44
+ # تأكد من وجود عمود المؤلف، سنة النشر، الموقع على الرف
45
+ for col in ["المؤلف", "سنة النشر", "الموقع على الرف"]:
46
+ if col not in df.columns:
47
+ df[col] = "غير متوافر"
48
 
49
+ # إذا لم يوجد عمود المصدر (كتاب/رسالة) أضيفيه
50
+ if "المصدر" not in df.columns:
51
+ df["المصدر"] = "كتاب"
52
 
53
+ return df
 
 
54
 
55
+ library_df = load_library()
56
 
57
  # ================== Embeddings ==================
58
  def emb_path(name):
 
74
 
75
  library_embeddings = build_or_load_embeddings(library_df, "library")
76
 
77
+ # ================== عرض النتائج HTML كـ Cards ==================
78
+ def results_to_html_cards(df):
79
+ if df.empty:
80
+ return "<p>❌ لم يتم العثور على نتائج</p>"
81
+
82
+ html = '<div style="display:flex; flex-wrap:wrap; gap:15px;">'
83
+ for _, row in df.iterrows():
84
+ card = f"""
85
+ <div style="
86
+ border:1px solid #ccc;
87
+ border-radius:10px;
88
+ padding:15px;
89
+ width:250px;
90
+ box-shadow: 2px 2px 8px rgba(0,0,0,0.1);
91
+ background: #f9f9f9;">
92
+ <div style="font-size:40px; text-align:center;">📖</div>
93
+ <h3 style="margin-top:5px; font-size:16px;">{row['Title']}</h3>
94
+ <p><b>المؤلف:</b> {row['المؤلف']}</p>
95
+ <p><b>سنة النشر:</b> {row['سنة النشر']}</p>
96
+ <p><b>الموقع على الرف:</b> {row['الموقع على الرف']}</p>
97
+ <p><b>المصدر:</b> {row['المصدر']}</p>
98
+ </div>
99
+ """
100
+ html += card
101
+ html += "</div>"
102
+ return html
103
 
104
  # ================== البحث ==================
105
+ def local_search_df(query, mode):
106
  if not query or not query.strip():
107
  return "<p>⚠️ اكتب كلمة أو جملة للبحث</p>", pd.DataFrame()
108
 
 
 
 
 
 
 
109
  # ---- بحث نصي ----
110
  if mode == "نصي":
111
+ col = "العنوان" if "العنوان" in library_df.columns else "Title"
112
+ df = library_df[library_df[col].astype(str).str.contains(query, case=False, na=False)]
113
 
114
  # ---- بحث دلالي ----
115
  else:
116
  q_emb = model.encode([query], convert_to_numpy=True)
117
  scores = util.cos_sim(q_emb, library_embeddings)[0].cpu().numpy()
118
+ df = library_df.copy()
119
+ df["score"] = scores
120
+ df = df.sort_values("score", ascending=False)
121
 
122
  if df.empty:
123
+ df = pd.DataFrame([{"Title":"❌ لم يتم العثور على نتائج"}])
124
 
125
+ return results_to_html_cards(df), df
 
 
 
126
 
127
  # ================== حفظ النتائج Excel ==================
128
  def save_to_excel(df):
 
134
  return tmp.name
135
 
136
  # ================== الواجهة ==================
137
+ with gr.Blocks(title="AI Library Explorer") as app:
138
+ gr.Markdown("## 📚 البحث في مقتنيات المكتبة")
 
139
  query = gr.Textbox(label="اكتب كلمة أو موضوع البحث")
140
 
141
  mode = gr.Radio(
 
144
  label="نوع البحث"
145
  )
146
 
 
 
 
 
 
 
147
  btn_search = gr.Button("🔎 بحث")
148
 
149
  df_state = gr.State()
 
152
 
153
  btn_search.click(
154
  local_search_df,
155
+ inputs=[query, mode],
156
  outputs=[output_html, df_state]
157
  )
158