aelsaeed commited on
Commit
ed48cdc
·
verified ·
1 Parent(s): be62a9f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -23
app.py CHANGED
@@ -33,7 +33,6 @@ download_from_drive(DRIVE_THESES_ID, THESES_FILE)
33
  books_df = pd.read_excel(BOOKS_FILE).fillna("")
34
  theses_df = pd.read_excel(THESES_FILE).fillna("")
35
 
36
- # إضافة نوع المصدر
37
  books_df["المصدر"] = "كتاب"
38
  theses_df["المصدر"] = "رسالة"
39
 
@@ -44,56 +43,89 @@ def emb_path(name):
44
  # ================== بناء أو تحميل الـ embeddings ==================
45
  def build_or_load_embeddings(df, name):
46
  path = emb_path(name)
 
47
  if os.path.exists(path):
48
  try:
49
- with open(path,"rb") as f:
50
  emb = pickle.load(f)
51
  if len(emb) == len(df):
52
  return emb
53
  except Exception:
54
  pass
55
- # تأكد من وجود عمود Title
56
  if "Title" not in df.columns:
57
  df["Title"] = df["العنوان"]
 
58
  texts = df["Title"].astype(str).tolist()
59
  emb = model.encode(texts, convert_to_numpy=True, show_progress_bar=True)
60
- with open(path,"wb") as f:
61
- pickle.dump(emb,f)
 
 
62
  return emb
63
 
64
- books_embeddings = build_or_load_embeddings(books_df,"books")
65
- theses_embeddings = build_or_load_embeddings(theses_df,"theses")
66
 
67
  # ================== دمج المكتبة ==================
68
  library_df = pd.concat([books_df, theses_df], ignore_index=True)
69
- library_embeddings = np.concatenate([books_embeddings, theses_embeddings], axis=0)
 
 
 
 
 
70
 
71
  # ================== CSS ==================
72
  CUSTOM_CSS = """
73
  <style>
74
- .styled-table{border-collapse:collapse;margin:15px 0;font-size:14px;width:100%;text-align:right;direction:rtl;}
75
- .styled-table th,.styled-table td{border:1px solid #ddd;padding:8px;}
76
- .styled-table tr:nth-child(even){background-color:#f9f9f9;}
77
- .styled-table tr:nth-child(odd){background-color:#fff;}
78
- .styled-table th{background-color:#4da6ff;color:white;}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  </style>
80
  """
81
 
82
- # ================== عرض النتائج HTML لكل نتيجة ==================
83
  def results_to_html(df):
84
  if df.empty:
85
  return "<p>❌ لم يتم العثور على نتائج</p>"
86
 
87
- # التأكد من الأعمدة المطلوبة
88
  for col in ["المؤلف","العنوان","سنة النشر","الموقع على الرف","المصدر"]:
89
  if col not in df.columns:
90
  df[col] = "-"
91
 
92
- html_results = ""
93
  for _, row in df.iterrows():
94
- row_df = pd.DataFrame([row[["المؤلف","العنوان","سنة النشر","الموقع على الرف","المصدر"]]])
95
- html_results += row_df.to_html(index=False, escape=False, classes="styled-table", border=0)
96
- return CUSTOM_CSS + html_results
 
 
 
 
 
 
 
 
97
 
98
  # ================== البحث ==================
99
  def local_search_df(query, mode, source_filter):
@@ -108,11 +140,18 @@ def local_search_df(query, mode, source_filter):
108
 
109
  # بحث نصي
110
  if mode == "نصي":
111
- df = df_search[df_search["العنوان"].str.contains(query, case=False, na=False)]
112
- # بحث دلالي
 
 
 
113
  else:
114
  q_emb = model.encode([query], convert_to_numpy=True)
115
- scores = util.cos_sim(q_emb, library_embeddings)[0].cpu().numpy()
 
 
 
 
116
  df_search["score"] = scores
117
  df = df_search.sort_values("score", ascending=False)
118
 
@@ -166,4 +205,4 @@ with gr.Blocks(title="البحث الدلالي بالمكتبة") as app:
166
  outputs=file_out
167
  )
168
 
169
- app.launch()
 
33
  books_df = pd.read_excel(BOOKS_FILE).fillna("")
34
  theses_df = pd.read_excel(THESES_FILE).fillna("")
35
 
 
36
  books_df["المصدر"] = "كتاب"
37
  theses_df["المصدر"] = "رسالة"
38
 
 
43
  # ================== بناء أو تحميل الـ embeddings ==================
44
  def build_or_load_embeddings(df, name):
45
  path = emb_path(name)
46
+
47
  if os.path.exists(path):
48
  try:
49
+ with open(path, "rb") as f:
50
  emb = pickle.load(f)
51
  if len(emb) == len(df):
52
  return emb
53
  except Exception:
54
  pass
55
+
56
  if "Title" not in df.columns:
57
  df["Title"] = df["العنوان"]
58
+
59
  texts = df["Title"].astype(str).tolist()
60
  emb = model.encode(texts, convert_to_numpy=True, show_progress_bar=True)
61
+
62
+ with open(path, "wb") as f:
63
+ pickle.dump(emb, f)
64
+
65
  return emb
66
 
67
+ books_embeddings = build_or_load_embeddings(books_df, "books")
68
+ theses_embeddings = build_or_load_embeddings(theses_df, "theses")
69
 
70
  # ================== دمج المكتبة ==================
71
  library_df = pd.concat([books_df, theses_df], ignore_index=True)
72
+ library_embeddings = np.concatenate(
73
+ [books_embeddings, theses_embeddings], axis=0
74
+ )
75
+
76
+ # 🔴 التعديل المهم
77
+ library_df["embedding"] = list(library_embeddings)
78
 
79
  # ================== CSS ==================
80
  CUSTOM_CSS = """
81
  <style>
82
+ .styled-table{
83
+ border-collapse:collapse;
84
+ margin:15px 0;
85
+ font-size:14px;
86
+ width:100%;
87
+ text-align:right;
88
+ direction:rtl;
89
+ }
90
+ .styled-table th,.styled-table td{
91
+ border:1px solid #ddd;
92
+ padding:8px;
93
+ }
94
+ .styled-table tr:nth-child(even){
95
+ background-color:#f9f9f9;
96
+ }
97
+ .styled-table tr:nth-child(odd){
98
+ background-color:#fff;
99
+ }
100
+ .styled-table th{
101
+ background-color:#4da6ff;
102
+ color:white;
103
+ }
104
  </style>
105
  """
106
 
107
+ # ================== عرض النتائج ==================
108
  def results_to_html(df):
109
  if df.empty:
110
  return "<p>❌ لم يتم العثور على نتائج</p>"
111
 
 
112
  for col in ["المؤلف","العنوان","سنة النشر","الموقع على الرف","المصدر"]:
113
  if col not in df.columns:
114
  df[col] = "-"
115
 
116
+ html = ""
117
  for _, row in df.iterrows():
118
+ row_df = pd.DataFrame([row[[
119
+ "المؤلف","العنوان","سنة النشر","الموقع على الرف","المصدر"
120
+ ]]])
121
+ html += row_df.to_html(
122
+ index=False,
123
+ escape=False,
124
+ classes="styled-table",
125
+ border=0
126
+ )
127
+
128
+ return CUSTOM_CSS + html
129
 
130
  # ================== البحث ==================
131
  def local_search_df(query, mode, source_filter):
 
140
 
141
  # بحث نصي
142
  if mode == "نصي":
143
+ df = df_search[
144
+ df_search["العنوان"].str.contains(query, case=False, na=False)
145
+ ]
146
+
147
+ # بحث دلالي (✔️ بعد الإصلاح)
148
  else:
149
  q_emb = model.encode([query], convert_to_numpy=True)
150
+
151
+ emb_matrix = np.vstack(df_search["embedding"].values)
152
+ scores = util.cos_sim(q_emb, emb_matrix)[0].cpu().numpy()
153
+
154
+ df_search = df_search.copy()
155
  df_search["score"] = scores
156
  df = df_search.sort_values("score", ascending=False)
157
 
 
205
  outputs=file_out
206
  )
207
 
208
+ app.launch()