Spaces:
Sleeping
Sleeping
Download src/streamlit_app.py from fuerr18/scraper-tool: direct link, hf CLI and curl.
- Browser
- Download file 16.9 kB
-
https://huggingface.co/spaces/fuerr18/scraper-tool/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/fuerr18/scraper-tool/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/fuerr18/scraper-tool/resolve/main/src/streamlit_app.py
16.9 kB
| 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() |