Spaces:
Sleeping

File size: 16,903 Bytes
f2a7e88
 
 
 
 
 
8400fc6
2b4caa9
 
18813ab
f2a7e88
b20a1ac
 
f2a7e88
b20a1ac
 
f2a7e88
b20a1ac
 
 
 
 
 
 
 
 
 
 
f2a7e88
8400fc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2a7e88
b20a1ac
 
 
 
f2a7e88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8400fc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18813ab
8400fc6
 
 
 
 
 
 
 
 
 
 
 
 
 
18813ab
8400fc6
18813ab
 
 
8400fc6
18813ab
 
 
 
 
 
 
 
8400fc6
18813ab
8400fc6
 
 
 
 
 
 
 
18813ab
 
 
 
8400fc6
18813ab
8400fc6
 
 
18813ab
8400fc6
18813ab
8400fc6
18813ab
 
 
8400fc6
 
 
 
 
 
 
 
18813ab
8400fc6
18813ab
8400fc6
 
 
18813ab
8400fc6
18813ab
8400fc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18813ab
 
8400fc6
 
 
 
 
 
 
18813ab
8400fc6
 
 
18813ab
 
 
b20a1ac
 
 
f2a7e88
b20a1ac
2b4caa9
f2a7e88
8400fc6
f2a7e88
8400fc6
2b4caa9
8400fc6
f2a7e88
b20a1ac
f2a7e88
 
8400fc6
f2a7e88
8400fc6
f2a7e88
b20a1ac
 
 
 
8400fc6
f2a7e88
8400fc6
2b4caa9
b20a1ac
f2a7e88
2b4caa9
 
b20a1ac
 
2b4caa9
 
 
 
 
 
 
 
 
 
 
b20a1ac
 
2b4caa9
 
 
 
 
 
b20a1ac
 
2b4caa9
b20a1ac
35d1d9a
2b4caa9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b20a1ac
 
2b4caa9
 
b20a1ac
 
2b4caa9
 
 
 
f2a7e88
 
 
 
 
b20a1ac
f2a7e88
b20a1ac
f2a7e88
b20a1ac
f2a7e88
b20a1ac
2b4caa9
f2a7e88
2b4caa9
 
 
 
b20a1ac
 
2b4caa9
 
 
 
 
 
fb42ecc
 
cc09641
fb42ecc
 
2b4caa9
 
 
b20a1ac
 
2b4caa9
 
b20a1ac
 
2b4caa9
 
 
 
 
 
 
b20a1ac
 
2b4caa9
 
 
b20a1ac
 
2b4caa9
 
 
 
 
 
 
 
 
 
8400fc6
2f25a33
8400fc6
2b4caa9
cc09641
7e2455e
b20a1ac
fb42ecc
18813ab
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
import streamlit as st
import requests
from bs4 import BeautifulSoup
import csv
import io
import time
import json
import openpyxl
from openpyxl import Workbook
import streamlit.components.v1 as components

# page config
st.set_page_config(page_title="Book Scraper", layout="wide")

# sidebar
st.sidebar.title("Settings / الاعدادات")

lang = st.sidebar.selectbox("Language / اللغة", ["العربية", "English"])

AR = lang == "العربية"

theme = st.sidebar.selectbox(
    "القالب / Theme",
    ["داكن / Dark", "فاتح / Light", "أزرق / Blue", "أخضر / Green"]
)
font = st.sidebar.selectbox("الخط / Font", ["Cairo", "Tajawal", "Arial", "Courier New"])
font_size = st.sidebar.slider("حجم الخط / Font Size", 12, 24, 16)
text_color = st.sidebar.color_picker("لون النص / Text Color", "#ffffff")

# ============== اعدادات الشخصية المساعدة ==============
st.sidebar.markdown("---")
st.sidebar.subheader("الشخصية المساعدة / Assistant Character")

CHAR_OPTIONS = {
    'Clippy': 'كليبي 📎',
    'Merlin': 'مارلن 🧙',
    'Rover':  'روفر 🐶',
    'Links':  'لينكس 🐱',
    'Genius': 'الفيلسوف 🧑‍🔬',
    'Peedy':  'بيدي 🦜',
    'Bonzi':  'بونزي 🐵',
    'Rocky':  'روكي 🐧',
    'F1':     'روبوت 🤖',
}
char_pick_label = "اختر شكل الشخصية" if AR else "Choose Character Look"
character_key = st.sidebar.selectbox(char_pick_label, list(CHAR_OPTIONS.keys()), format_func=lambda k: CHAR_OPTIONS[k])

char_name_label = "شنو تريد تسميها؟" if AR else "Name the Character"
character_name = st.sidebar.text_input(char_name_label, "كليبي" if AR else "Clippy")

user_name_label = "شسمك؟ (راح تصيحك بيه)" if AR else "Your Name (it'll call you this)"
user_name = st.sidebar.text_input(user_name_label, "صديقي" if AR else "Friend")

themes = {
    "داكن / Dark":  {"bg": "#1e1e2e", "card": "#2a2a3e", "accent": "#7c6af7"},
    "فاتح / Light": {"bg": "#f0f2f6", "card": "#ffffff",  "accent": "#4a90d9"},
    "أزرق / Blue":  {"bg": "#0d1b2a", "card": "#1b2a3b",  "accent": "#00b4d8"},
    "أخضر / Green": {"bg": "#0d2b1e", "card": "#1a3a2a",  "accent": "#2ecc71"},
}
t = themes[theme]

st.markdown(f"""
<style>
@import url('https://fonts.googleapis.com/css2?family=Cairo&family=Tajawal&display=swap');
html, body, [class*="css"] {{
    font-family: '{font}', sans-serif;
    font-size: {font_size}px;
    background-color: {t['bg']};
    color: {text_color};
}}
.main {{ background-color: {t['bg']}; }}
.book-card {{
    background-color: {t['card']};
    border-left: 4px solid {t['accent']};
    border-radius: 10px;
    padding: 12px 16px;
    margin-bottom: 10px;
    font-size: {font_size}px;
    color: {text_color};
}}
.title-bar {{
    font-size: {font_size + 6}px;
    font-weight: bold;
    color: {t['accent']};
    margin-bottom: 20px;
}}
.count-badge {{
    background-color: {t['accent']};
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: {font_size - 2}px;
}}
</style>
""", unsafe_allow_html=True)

# ============== نصوص الحقول والازرار (نعرفها هنا عشان نستخدمها بالتلميحات وبالواجهة) ==============
LBL_URL     = "رابط الموقع" if AR else "Website URL"
LBL_REFRESH = "تحديث تلقائي (ثانية، 0=إيقاف)" if AR else "Auto Refresh (sec, 0=off)"
LBL_PAGES   = "عدد الصفحات" if AR else "Number of Pages"
LBL_SEARCH  = "بحث باسم الكتاب" if AR else "Search by Title"
LBL_PRICE   = "الحد الاقصى للسعر" if AR else "Max Price"
LBL_SORT    = "ترتيب حسب" if AR else "Sort By"
BTN_START   = "ابدأ السحب" if AR else "Start Scraping"
BTN_CSV     = "تنزيل CSV" if AR else "Download CSV"
BTN_EXCEL   = "تنزيل Excel" if AR else "Download Excel"

# ============== تلميحات الحقول ==============
FIELD_HINTS = {
    LBL_URL: (f"اكتب رابط الموقع هنا يا {user_name} 🌐" if AR else f"Type the website URL here, {user_name} 🌐"),
    LBL_SEARCH: (f"دور عن اسم الكتاب اللي تريده يا {user_name} 🔍" if AR else f"Search for a book title, {user_name} 🔍"),
    LBL_PRICE: ("حدد اعلى سعر تقبل بيه 💰" if AR else "Set your max price 💰"),
    LBL_SORT: ("شلون تريد ترتب الكتب؟ 📊" if AR else "How do you want to sort? 📊"),
    LBL_REFRESH: ("تريد تحديث تلقائي؟ حدد الثواني ⏱️" if AR else "Want auto refresh? Set seconds ⏱️"),
    LBL_PAGES: ("كم صفحة تريد نسحب؟ 📄" if AR else "How many pages to scrape? 📄"),
}

# ============== ردود فعل الازرار ==============
BUTTON_REACTIONS = {
    BTN_START: [
        f"هذا خوش رابط والله يا {user_name}، عمي محد يلحگك انت! 😂",
        f"خلي نشوف شنو عندهم من كتب زينة يا {user_name}...",
        "استنى شوية، جاري السحب! 🚀",
    ] if AR else [
        f"Nice link, {user_name}! Nobody can catch you 😂",
        "Let's see what books they've got...",
        "Hang tight, scraping now! 🚀",
    ],
    BTN_CSV: [
        f"زين يا {user_name}، احتفظ بالملف منيح 📥",
        "تم تجهيز ملف الـ CSV!",
    ] if AR else [
        f"Nice one, {user_name}! Keep that file safe 📥",
        "CSV is ready!",
    ],
    BTN_EXCEL: [
        f"اكسل احلى وياك يا {user_name} 😎",
        "تم تجهيز ملف الاكسل!",
    ] if AR else [
        f"Excel looks better with you, {user_name} 😎",
        "Excel file is ready!",
    ],
}

GENERIC_REACTIONS = [
    f"شنو رايك بالتصميم يا {user_name}؟ 😊",
    f"تحتاج مساعدة ثانية يا {user_name}؟",
    "زين، استمر! 👍",
] if AR else [
    f"What do you think of the design, {user_name}? 😊",
    f"Need any more help, {user_name}?",
    "Nice, keep going! 👍",
]

GREETING = (f"هلا {user_name}! انا {character_name} 👋" if AR else f"Hi {user_name}! I'm {character_name} 👋")

# ============== الشخصية المساعدة المتحركة ==============
components.html(f"""
<script type="module">
  import {{ initAgent }} from 'https://cdn.jsdelivr.net/npm/clippyjs/dist/index.mjs';
  import * as clippyAgents from 'https://cdn.jsdelivr.net/npm/clippyjs/dist/agents/index.mjs';

  const frame = window.frameElement;
  if(frame){{
    frame.style.position = 'fixed';
    frame.style.top = '0';
    frame.style.left = '0';
    frame.style.width = '100vw';
    frame.style.height = '100vh';
    frame.style.zIndex = '999999';
    frame.style.border = 'none';
    frame.style.pointerEvents = 'none';
  }}
  document.body.style.pointerEvents = 'none';

  const CHARACTER_KEY   = {json.dumps(character_key)};
  const CHARACTER_NAME  = {json.dumps(character_name)};
  const USER_NAME       = {json.dumps(user_name)};
  const GREETING        = {json.dumps(GREETING)};
  const FIELD_HINTS     = {json.dumps(FIELD_HINTS, ensure_ascii=False)};
  const BUTTON_REACTIONS= {json.dumps(BUTTON_REACTIONS, ensure_ascii=False)};
  const GENERIC_REACTIONS = {json.dumps(GENERIC_REACTIONS, ensure_ascii=False)};

  let currentAgent = null;
  let roamTimer = null;
  let lastReactionTime = 0;
  let lastHintTime = 0;

  function randomPoint(){{
    return {{ x: 40 + Math.random() * (window.innerWidth - 150), y: 80 + Math.random() * (window.innerHeight - 200) }};
  }}

  function startRoaming(agent){{
    clearInterval(roamTimer);
    roamTimer = setInterval(() => {{
      if(!agent) return;
      const p = randomPoint();
      agent.moveTo(p.x, p.y);
      agent.animate();
    }}, 12000);
  }}

  // رد فعل عند الضغط على أي زر
  function handleClick(e){{
    const btn = e.target.closest('button, a, [role="button"]');
    if(!btn || !currentAgent) return;
    const now = Date.now();
    if(now - lastReactionTime < 1200) return;
    lastReactionTime = now;

    const txt = btn.textContent.trim();
    const rect = btn.getBoundingClientRect();
    currentAgent.stopCurrent();
    currentAgent.gestureAt(rect.left + rect.width/2, rect.top);
    currentAgent.animate();

    const specific = BUTTON_REACTIONS[txt];
    const pool = specific && specific.length ? specific : GENERIC_REACTIONS;
    const line = pool[Math.floor(Math.random() * pool.length)];
    currentAgent.speak(line);
  }}

  // تلميح عند التركيز على حقل ادخال
  function handleFocus(e){{
    const input = e.target;
    if(!currentAgent) return;
    if(!(input.tagName === 'INPUT' || input.tagName === 'TEXTAREA' || input.getAttribute('role') === 'combobox')) return;

    const now = Date.now();
    if(now - lastHintTime < 800) return;

    let container = input.closest('[data-testid]') || input.parentElement?.parentElement;
    const label = container ? container.querySelector('label') : null;
    const txt = label ? label.textContent.trim() : '';
    if(!FIELD_HINTS[txt]) return;
    lastHintTime = now;

    const rect = input.getBoundingClientRect();
    currentAgent.stopCurrent();
    currentAgent.moveTo(Math.max(10, rect.left - 20), Math.max(10, rect.top - 90));
    currentAgent.gestureAt(rect.left, rect.top);
    currentAgent.speak(FIELD_HINTS[txt]);
  }}

  try{{
    window.parent.document.addEventListener('click', handleClick);
    window.parent.document.addEventListener('focusin', handleFocus);
  }}catch(err){{ console.warn('تعذر الوصول لصفحة Streamlit الأساسية', err); }}

  async function init(){{
    if(!clippyAgents[CHARACTER_KEY]) return;
    if(currentAgent){{ try{{ currentAgent.hide(); currentAgent.dispose(); }}catch(e){{}} currentAgent = null; }}
    const agent = await initAgent(clippyAgents[CHARACTER_KEY]);
    currentAgent = agent;
    agent.show();

    const comboKey = CHARACTER_KEY + '|' + CHARACTER_NAME + '|' + USER_NAME;
    const lastCombo = localStorage.getItem('assistantCombo');
    if(lastCombo !== comboKey){{
      agent.speak(GREETING);
      localStorage.setItem('assistantCombo', comboKey);
    }}
    startRoaming(agent);
  }}

  init();
</script>
""", height=0)

# title
title_text = "أداة استخراج بيانات الكتب" if AR else "Book Data Scraper"
st.markdown(f'<div class="title-bar">{title_text}</div>', unsafe_allow_html=True)

# main inputs
col1, col2, col3_main = st.columns([2, 1, 1])
with col1:
    url = st.text_input(LBL_URL, "https://books.toscrape.com")
with col2:
    auto_refresh = st.number_input(LBL_REFRESH, min_value=0, value=0, step=10)
with col3_main:
    max_pages = st.number_input(LBL_PAGES, min_value=1, max_value=50, value=1)

# search and filter
col3, col4, col5 = st.columns(3)
with col3:
    search_query = st.text_input(LBL_SEARCH)
with col4:
    max_price = st.slider(LBL_PRICE, 0, 100, 100)
with col5:
    if AR:
        sort_options = ["بدون ترتيب", "السعر تصاعدي", "السعر تنازلي", "الاسم", "التقييم"]
    else:
        sort_options = ["No Sort", "Price Low to High", "Price High to Low", "Title", "Rating"]
    sort_by = st.selectbox(LBL_SORT, sort_options)

button = st.button(BTN_START)

rating_map = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}

def scrape_books(base_url, max_pages):
    data = []
    progress_text = "جاري السحب..." if AR else "Scraping..."
    progress = st.progress(0, text=progress_text)

    for page in range(1, max_pages + 1):
        try:
            if page == 1:
                page_url = base_url
            else:
                page_url = base_url.rstrip("/") + f"/catalogue/page-{page}.html"

            response = requests.get(page_url, timeout=10)

            if response.status_code != 200:
                msg = f"الصفحة {page} غير موجودة، تم الايقاف." if AR else f"Page {page} not found, stopped."
                st.warning(msg)
                break

            soup = BeautifulSoup(response.text, "html.parser")
            books = soup.find_all("article", class_="product_pod")

            if not books:
                msg = f"لا توجد كتب بالصفحة {page}." if AR else f"No books found on page {page}."
                st.warning(msg)
                break

            for book in books:
                title = book.h3.a["title"]
                price_text = book.find("p", class_="price_color").text
                price_num = float(price_text.replace("£", "").replace("Â", "").strip())
                rating_word = book.p["class"][1]
                rating_num = rating_map.get(rating_word, 0)
                rating_stars = "★" * rating_num + "☆" * (5 - rating_num)
                img_tag = book.find("img")
                img_url = ""
                if img_tag:
                    img_src = img_tag["src"].replace("../../", "")
                    img_url = "https://books.toscrape.com/" + img_src

                data.append({
                    "title": title,
                    "price": price_num,
                    "price_text": price_text,
                    "rating": rating_num,
                    "rating_stars": rating_stars,
                    "img_url": img_url
                })

            prog_text = f"صفحة {page} من {max_pages}" if AR else f"Page {page} of {max_pages}"
            progress.progress(page / max_pages, text=prog_text)

        except Exception as e:
            msg = f"خطأ بالصفحة {page}: {e}" if AR else f"Error on page {page}: {e}"
            st.error(msg)
            break

    progress.empty()
    return data

def filter_sort(data, search, max_p, sort):
    if search:
        data = [b for b in data if search.lower() in b["title"].lower()]
    data = [b for b in data if b["price"] <= max_p]
    if sort in ["السعر تصاعدي", "Price Low to High"]:
        data = sorted(data, key=lambda x: x["price"])
    elif sort in ["السعر تنازلي", "Price High to Low"]:
        data = sorted(data, key=lambda x: x["price"], reverse=True)
    elif sort in ["الاسم", "Title"]:
        data = sorted(data, key=lambda x: x["title"])
    elif sort in ["التقييم", "Rating"]:
        data = sorted(data, key=lambda x: x["rating"], reverse=True)
    return data

def export_excel(data):
    wb = Workbook()
    ws = wb.active
    ws.title = "Books"
    ws.append(["Title", "Price", "Rating"])
    for b in data:
        ws.append([b["title"], b["price_text"], b["rating_stars"]])
    output = io.BytesIO()
    wb.save(output)
    return output.getvalue()

if button or auto_refresh > 0:
    placeholder = st.empty()

    while True:
        with placeholder.container():
            data = scrape_books(url, max_pages)

            if not data:
                msg = "لم يتم ايجاد بيانات. تحقق من الرابط." if AR else "No data found. Check the URL."
                st.error(msg)
            else:
                filtered = filter_sort(data, search_query, max_price, sort_by)
                count_msg = f"تم ايجاد {len(filtered)} كتاب" if AR else f"Found {len(filtered)} books"
                st.markdown(f'<span class="count-badge">{count_msg}</span>', unsafe_allow_html=True)
                st.write("")

                cols = st.columns(4)
                for i, book in enumerate(filtered):
                    with cols[i % 4]:
                        if book["img_url"]:
                            st.image(book["img_url"], use_column_width=True)
                        price_label = "السعر" if AR else "Price"
                        rating_label = "التقييم" if AR else "Rating"
                        st.markdown(f"""
                        <div class="book-card">
                            <b>{book['title']}</b><br>
                            {price_label}: {book['price_text']}<br>
                            {rating_label}: {book['rating_stars']}
                        </div>
                        """, unsafe_allow_html=True)

                csv_output = io.StringIO()
                writer = csv.writer(csv_output)
                writer.writerow(["Title", "Price", "Rating"])
                writer.writerows([[b["title"], b["price_text"], b["rating_stars"]] for b in filtered])

                col_csv, col_excel = st.columns(2)
                with col_csv:
                    st.download_button(BTN_CSV, csv_output.getvalue(), "books.csv", "text/csv")
                with col_excel:
                    st.download_button(BTN_EXCEL, export_excel(filtered), "books.xlsx",
                                       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

        if auto_refresh == 0:
            break
        time.sleep(auto_refresh)
        st.rerun()